@everfur/sdk 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +648 -1
- package/README.md +58 -23
- package/consent/package.json +8 -0
- package/dist/Chat-DPUD6dnc.d.cts +128 -0
- package/dist/Chat-DwAC2vhB.d.ts +128 -0
- package/dist/DepthViews-DNEM96Se.d.ts +16 -0
- package/dist/DepthViews-DP0R-DhB.d.cts +19 -0
- package/dist/DepthViews-D_3hl4xk.d.ts +19 -0
- package/dist/DepthViews-DbFhR4Du.d.cts +16 -0
- package/dist/ErrorPolicyPort-CNf4uQZP.d.cts +22 -0
- package/dist/ErrorPolicyPort-CwbfmxzJ.d.ts +22 -0
- package/dist/{EverfurResult-D92-uL82.d.cts → EverfurResult-DN9pL2Ab.d.cts} +11 -10
- package/dist/{EverfurResult-D92-uL82.d.ts → EverfurResult-DN9pL2Ab.d.ts} +11 -10
- package/dist/{PhotoController-BItt5M7u.d.cts → PhotoController-3l7MT9jA.d.cts} +1 -1
- package/dist/{PhotoController-D8zMTdcW.d.ts → PhotoController-vzY5bfY_.d.ts} +1 -1
- package/dist/animations/index.cjs +1 -1997
- package/dist/animations/index.d.cts +35 -35
- package/dist/animations/index.d.ts +35 -35
- package/dist/animations/index.js +1 -1972
- package/dist/attachments-5NeobOCd.d.ts +256 -0
- package/dist/attachments-Bw3iMQgu.d.ts +146 -0
- package/dist/attachments-CQgFrEQ7.d.cts +146 -0
- package/dist/attachments-D8T5re7e.d.cts +256 -0
- package/dist/casesRepository-ClLv6qMl.d.ts +188 -0
- package/dist/casesRepository-DHwtGRYY.d.cts +188 -0
- package/dist/chat/index.cjs +1 -1170
- package/dist/chat/index.d.cts +31 -53
- package/dist/chat/index.d.ts +31 -53
- package/dist/chat/index.js +1 -1167
- package/dist/client/index.cjs +9 -2315
- package/dist/client/index.d.cts +77 -15
- package/dist/client/index.d.ts +77 -15
- package/dist/client/index.js +9 -2215
- package/dist/{config-CiJ0PVBB.d.ts → config-CzTZGlfF.d.cts} +63 -25
- package/dist/{config-BSjBdxrZ.d.cts → config-DW60uRb9.d.ts} +63 -25
- package/dist/consent/index.cjs +1 -0
- package/dist/consent/index.d.cts +33 -0
- package/dist/consent/index.d.ts +33 -0
- package/dist/consent/index.js +1 -0
- package/dist/context-DXhqHlPU.d.ts +159 -0
- package/dist/context-XvTzq1tE.d.cts +159 -0
- package/dist/copy-Mjoo91aS.d.ts +198 -0
- package/dist/copy-bKDNigLb.d.cts +198 -0
- package/dist/core/index.cjs +13 -3175
- package/dist/core/index.d.cts +58 -12
- package/dist/core/index.d.ts +58 -12
- package/dist/core/index.js +13 -3163
- package/dist/depth-CErXCU8J.d.cts +502 -0
- package/dist/depth-DjDcJ6kH.d.ts +502 -0
- package/dist/entitlementRepository-DKdXFgTo.d.cts +698 -0
- package/dist/entitlementRepository-DSbzuyAW.d.ts +698 -0
- package/dist/{identity-DK9zORrG.d.ts → identity-BMx2SUOM.d.ts} +19 -6
- package/dist/{identity-Brl-lDd6.d.cts → identity-DI4eVx9S.d.cts} +19 -6
- package/dist/{ids-CJ1S6adf.d.cts → ids-B2GAAifq.d.cts} +1 -1
- package/dist/{ids-CJ1S6adf.d.ts → ids-B2GAAifq.d.ts} +1 -1
- package/dist/index.cjs +12 -4488
- package/dist/index.d.cts +29 -121
- package/dist/index.d.ts +29 -121
- package/dist/index.js +12 -4464
- package/dist/models-B-Uh2LTf.d.ts +214 -0
- package/dist/models-D2EUxPZY.d.cts +214 -0
- package/dist/notifications/index.cjs +2 -0
- package/dist/notifications/index.d.cts +17 -0
- package/dist/notifications/index.d.ts +17 -0
- package/dist/notifications/index.js +2 -0
- package/dist/pets-CtQdRpWo.d.ts +92 -0
- package/dist/pets-aB8q0JyX.d.cts +92 -0
- package/dist/photo/index.cjs +1 -2189
- package/dist/photo/index.d.cts +6 -6
- package/dist/photo/index.d.ts +6 -6
- package/dist/photo/index.js +1 -2186
- package/dist/ports-BN6RHF9W.d.cts +48 -0
- package/dist/ports-BN6RHF9W.d.ts +48 -0
- package/dist/ports-DEBzEhbp.d.cts +386 -0
- package/dist/ports-DMolTRzU.d.ts +386 -0
- package/dist/profile-CSs1wlXT.d.cts +93 -0
- package/dist/profile-CSs1wlXT.d.ts +93 -0
- package/dist/records/depth/index.cjs +2 -0
- package/dist/records/depth/index.d.cts +13 -0
- package/dist/records/depth/index.d.ts +13 -0
- package/dist/records/depth/index.js +2 -0
- package/dist/records/index.cjs +3 -2839
- package/dist/records/index.d.cts +137 -203
- package/dist/records/index.d.ts +137 -203
- package/dist/records/index.js +3 -2833
- package/dist/requestFunnel-CjW7uDuA.d.ts +87 -0
- package/dist/requestFunnel-L-BQfi0z.d.cts +87 -0
- package/dist/{resolve-Dq_4_agU.d.ts → resolve-D4Ywz5OS.d.cts} +10 -4
- package/dist/{resolve-Dq_4_agU.d.cts → resolve-D4Ywz5OS.d.ts} +10 -4
- package/dist/{runtime-BgQnA594.d.cts → runtime-B8s-_hv8.d.cts} +134 -59
- package/dist/{runtime-CBA-LvdM.d.ts → runtime-BR9ysG0J.d.ts} +134 -59
- package/dist/server/events/index.cjs +2 -0
- package/dist/server/events/index.d.cts +550 -0
- package/dist/server/events/index.d.ts +550 -0
- package/dist/server/events/index.js +2 -0
- package/dist/server/index.cjs +2 -533
- package/dist/server/index.d.cts +73 -18
- package/dist/server/index.d.ts +73 -18
- package/dist/server/index.js +2 -530
- package/dist/species-BXAIMh7I.d.cts +9 -0
- package/dist/species-BXAIMh7I.d.ts +9 -0
- package/dist/televet/index.cjs +1 -0
- package/dist/televet/index.d.cts +60 -0
- package/dist/televet/index.d.ts +60 -0
- package/dist/televet/index.js +1 -0
- package/dist/testing/index.cjs +5 -823
- package/dist/testing/index.d.cts +17 -3
- package/dist/testing/index.d.ts +17 -3
- package/dist/testing/index.js +5 -820
- package/dist/testing/rn/index.cjs +1 -449
- package/dist/testing/rn/index.d.cts +17 -29
- package/dist/testing/rn/index.d.ts +17 -29
- package/dist/testing/rn/index.js +1 -444
- package/dist/testing/web/index.cjs +1 -0
- package/dist/testing/web/index.d.cts +131 -0
- package/dist/testing/web/index.d.ts +131 -0
- package/dist/testing/web/index.js +1 -0
- package/dist/timelineRows-CaohZzXS.d.cts +19 -0
- package/dist/timelineRows-DZed6dAM.d.ts +19 -0
- package/dist/typeStyle-0TydiZ1w.d.cts +19 -0
- package/dist/typeStyle-CWMsoe6b.d.ts +19 -0
- package/dist/uploadTransport-D0M0T4hN.d.ts +38 -0
- package/dist/uploadTransport-DKJHs3Yj.d.cts +38 -0
- package/dist/useRecordsDepth-BHBzJ76R.d.cts +237 -0
- package/dist/useRecordsDepth-BU-OhzH6.d.ts +237 -0
- package/dist/useVetVisit-Bc84hWUU.d.cts +187 -0
- package/dist/useVetVisit-CjmMa896.d.ts +187 -0
- package/dist/video/index.cjs +1 -1941
- package/dist/video/index.d.cts +4 -4
- package/dist/video/index.d.ts +4 -4
- package/dist/video/index.js +1 -1938
- package/dist/view-C3qPIXGX.d.cts +310 -0
- package/dist/view-DtSPYpKa.d.ts +310 -0
- package/dist/visitIntent-D7_yVp1I.d.cts +8 -0
- package/dist/visitIntent-D7_yVp1I.d.ts +8 -0
- package/dist/web/consent/index.cjs +1 -0
- package/dist/web/consent/index.d.cts +34 -0
- package/dist/web/consent/index.d.ts +34 -0
- package/dist/web/consent/index.js +1 -0
- package/dist/web/index.cjs +14 -0
- package/dist/web/index.d.cts +217 -0
- package/dist/web/index.d.ts +217 -0
- package/dist/web/index.js +14 -0
- package/dist/web/notifications/index.cjs +2 -0
- package/dist/web/notifications/index.d.cts +213 -0
- package/dist/web/notifications/index.d.ts +213 -0
- package/dist/web/notifications/index.js +2 -0
- package/dist/web/records/depth/index.cjs +2 -0
- package/dist/web/records/depth/index.d.cts +12 -0
- package/dist/web/records/depth/index.d.ts +12 -0
- package/dist/web/records/depth/index.js +2 -0
- package/dist/web/records/index.cjs +4 -0
- package/dist/web/records/index.d.cts +194 -0
- package/dist/web/records/index.d.ts +194 -0
- package/dist/web/records/index.js +4 -0
- package/dist/web/televet/index.cjs +1 -0
- package/dist/web/televet/index.d.cts +50 -0
- package/dist/web/televet/index.d.ts +50 -0
- package/dist/web/televet/index.js +1 -0
- package/notifications/package.json +8 -0
- package/package.json +197 -9
- package/records/depth/package.json +8 -0
- package/server/events/device-blocked.cjs +15 -0
- package/server/events/package.json +9 -0
- package/televet/package.json +8 -0
- package/testing/web/native-blocked.cjs +12 -0
- package/testing/web/package.json +8 -0
- package/web/consent/native-blocked.cjs +12 -0
- package/web/consent/package.json +8 -0
- package/web/native-blocked.cjs +12 -0
- package/web/notifications/native-blocked.cjs +12 -0
- package/web/notifications/package.json +8 -0
- package/web/package.json +8 -0
- package/web/records/depth/native-blocked.cjs +12 -0
- package/web/records/depth/package.json +8 -0
- package/web/records/native-blocked.cjs +12 -0
- package/web/records/package.json +8 -0
- package/web/televet/native-blocked.cjs +12 -0
- package/web/televet/package.json +8 -0
- package/dist/ChatController-CKdBvPj2.d.ts +0 -146
- package/dist/ChatController-CpUMvvZf.d.cts +0 -146
- package/dist/FilePort-BabWrv7I.d.cts +0 -22
- package/dist/FilePort-BabWrv7I.d.ts +0 -22
- package/dist/petsRepository-BEGb97M9.d.cts +0 -326
- package/dist/petsRepository-Bu18r2kK.d.ts +0 -326
- package/dist/requestFunnel-DuUH-kAe.d.cts +0 -28
- package/dist/requestFunnel-dio5OmR9.d.ts +0 -28
package/dist/records/index.js
CHANGED
|
@@ -1,2834 +1,4 @@
|
|
|
1
|
-
import { createContext, useState, useRef, useEffect, useCallback, useMemo, useReducer, useContext, useSyncExternalStore } from 'react';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import 'react-native-safe-area-context';
|
|
4
|
-
import { View, ActivityIndicator, Pressable, Text, AccessibilityInfo, ScrollView, StyleSheet } from 'react-native';
|
|
5
|
-
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
|
|
1
|
+
import {createContext,forwardRef,useRef,useMemo,useState,useCallback,useEffect,useReducer,createElement,useContext,useSyncExternalStore,Component}from'react';import {z}from'zod';import {TextInput,View,Pressable,ScrollView,ActivityIndicator,StyleSheet,PanResponder,KeyboardAvoidingView,Image,Linking,BackHandler,Text,Modal,AccessibilityInfo}from'react-native';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var qd=Object.defineProperty;var i=(e,t)=>qd(e,"name",{value:t,configurable:true});var Lo=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(Lo.map(e=>e.wireCode));var Fd=Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),Fa=Object.freeze(Lo.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:Fd[e.wireCode]}))),zd=new Map(Fa.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Nd=Object.freeze(["http_envelope",...[...new Set(Fa.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Ln(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let o of [t??"http_envelope",...Nd]){let n=zd.get(o+r);if(n)return n}}i(Ln,"contractErrorFor");function Md(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Md,"contractDocUrl");function za(e){return null}i(za,"publishedDocUrl");var Bd=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function Na(e){return Bd[e]}i(Na,"categoryFor");function Ma(e){let t=Ln(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),o=r.replace(/[^A-Z0-9]/g,"");if(o==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(o){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Ma,"fromWire");var Hd=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Vo(e){return Hd.has(e)}i(Vo,"isAutoRetryable");var Ud=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Ba(e){return Vo(e)||Ud.has(e)}i(Ba,"isRetryableCode");var jd=500,qo=8e3,Ha=4;function Ua(e,t=Math.random){let r=Math.max(0,e),o=Math.min(jd*2**r,qo);return Math.floor(t()*o)}i(Ua,"backoffDelayMs");var $d=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function Fo(e){return $d[e]}i(Fo,"userFacingError");function ja(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(ja,"defineHidden");var Wd=/^[a-z][a-z0-9_]{0,63}$/;function q(e,t){let r=Ln(t?.wireCode,t?.wireEnvelope),o={code:e,category:Na(e),retryable:t?.retryable??Ba(e),displayMessage:Fo(e)};if(t?.httpStatus!==void 0&&(o.httpStatus=t.httpStatus),t?.requestId&&(o.requestId=t.requestId),typeof t?.reasonCode=="string"&&Wd.test(t.reasonCode)&&(o.reasonCode=t.reasonCode),r);return t?.wireMessage&&ja(o,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ja(o,"raw",t.raw),Object.freeze(o)}i(q,"makeEverfurError");function _e(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(_e,"ok");function B(e){return Object.freeze({ok:false,error:e})}i(B,"err");var Vn=class Vn extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Vn.prototype);}};i(Vn,"EverfurConfigError");var en=Vn;var Ka=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),$a=Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function Gd(e){let t=Object.prototype.hasOwnProperty.call($a,e)?$a[e]:void 0;if(t!==void 0)return t;let r=e;return Ka.has(r)?r:"parsing"}i(Gd,"normalizeStatus");function Qa(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Qa,"normalizeOrigin");var Yd=z.object({request_id:z.string().min(1),pet_ref:z.string().min(1),status:z.string(),simple_status:z.string().nullish(),simple_status_detail:z.string().nullish(),status_label:z.string().optional(),dispatch_status:z.string().nullish(),can_retry_send:z.boolean().optional(),can_revoke:z.boolean().optional(),can_convert_to_upload:z.boolean().optional(),can_update_clinic_email:z.boolean().optional(),reminder_count:z.number().int().nonnegative().optional(),last_reminder_at:z.string().nullish(),waiting_expectation:z.string().nullish(),document_count:z.number().optional(),held_item_count:z.number().optional(),received_at:z.string().nullish(),parsing_started_at:z.string().nullish(),review_started_at:z.string().nullish(),created_at:z.string().optional(),updated_at:z.string().optional(),source:z.string().nullish().catch(null),action_needed_label:z.string().nullish().catch(null),failure_reason:z.string().nullish().catch(null),failure_code:z.string().nullish().catch(null),recovery_stage:z.string().nullish().catch(null),show_clinic_phone:z.boolean().optional().catch(void 0),clinic_name:z.string().nullish().catch(null),clinic_email:z.string().nullish().catch(null),clinic_phone:z.string().nullish().catch(null),converted_to_upload_at:z.string().nullish().catch(null),request_group_id:z.string().nullish().catch(null)}).passthrough();function cr(e){let t=Yd.safeParse(e);if(!t.success)return null;let r=t.data,o=Qd(r.simple_status),n=o==="requested"&&(r.status==="awaiting_upload"||r.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":o==="parsing"&&(r.simple_status_detail==="in_review"||r.simple_status_detail==="review_email_failed")?"in_review":o??Gd(r.status);return Object.freeze({id:r.request_id,petRef:r.pet_ref,status:n,simpleStatus:o,simpleStatusDetail:r.simple_status_detail??null,statusLabel:r.status_label??"",dispatchStatus:r.dispatch_status??null,canRetrySend:r.can_retry_send===true,canRevoke:r.can_revoke===true,canConvertToUpload:r.can_convert_to_upload===true,canUpdateClinicEmail:r.can_update_clinic_email===true,reminderCount:r.reminder_count??0,lastReminderAt:r.last_reminder_at??null,waitingExpectation:r.waiting_expectation??null,documentCount:Ga(r.document_count,0),heldItemCount:Ga(r.held_item_count,0),receivedAt:r.received_at??null,parsingStartedAt:r.parsing_started_at??null,reviewStartedAt:r.review_started_at??null,createdAt:r.created_at??"",updatedAt:r.updated_at??"",wireStatus:r.status,source:r.source??null,actionNeededLabel:r.action_needed_label??null,failureReason:r.failure_reason??null,failureCode:r.failure_code??null,recoveryStage:r.recovery_stage??null,showClinicPhone:r.show_clinic_phone===true,clinicName:r.clinic_name??null,clinicEmail:r.clinic_email??null,clinicPhone:r.clinic_phone??null,convertedToUploadAt:r.converted_to_upload_at??null,requestGroupId:r.request_group_id??null})}i(cr,"mapRequestView");var Kd=z.object({request_group_id:z.string().min(1),pet_ref:z.string().min(1),total:z.number().int().nonnegative(),responded:z.number().int().nonnegative(),pending:z.number().int().nonnegative(),members:z.array(z.unknown())});function Xa(e){let t=Kd.safeParse(e);if(!t.success)return null;let r=t.data,o=zo(r.members);return o.some(n=>n.petRef!==r.pet_ref)?null:Object.freeze({requestGroupId:r.request_group_id,petRef:r.pet_ref,total:r.total,responded:r.responded,pending:r.pending,members:o})}i(Xa,"mapRequestGroup");function Qd(e){return !e||e==="awaiting_upload"||e==="in_review"?null:Ka.has(e)?e:null}i(Qd,"normalizeSimpleStatus");function zo(e){let t=Array.isArray(e)?e:[],r=[];for(let o of t){let n=cr(o);n!==null&&r.push(n);}return Object.freeze(r)}i(zo,"mapRequestList");var Xd=z.object({source_doc_id:z.string().min(1),request_id:z.string().min(1)});function Ja(e){let t=Xd.safeParse(e);return t.success?Object.freeze({documentId:t.data.source_doc_id,requestId:t.data.request_id,status:"received"}):null}i(Ja,"mapUploadedDocument");var Jd=z.object({label:z.string(),value:z.string()}),No=z.object({key:z.string(),category:z.string().optional(),label:z.string().optional(),value:z.string().nullish(),unit:z.string().nullish(),observed_at:z.string().nullish(),status:z.string().nullish(),origin:z.string().nullish(),canonical_key:z.string().nullish()}),Zd=z.object({at:z.string(),value:z.number().nullish(),display:z.string().nullish(),origin:z.string().nullish()}),eu=z.object({key:z.string(),label:z.string().optional(),points:z.array(Zd).optional()}),tu=z.object({title:z.string(),detail:z.string().nullish(),due_at:z.string().nullish()}),Mo=z.object({doc_id:z.string(),title:z.string().nullish(),page_count:z.number().nullish(),received_at:z.string().nullish()});function Bo(e){return Object.freeze({key:e.key,category:e.category??"",label:e.label??e.key,value:e.value??null,unit:e.unit??null,observedAt:e.observed_at??null,status:e.status??null,origin:Qa(e.origin),canonicalKey:e.canonical_key??null})}i(Bo,"mapEntityRow");function Ho(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(Ho,"mapDocumentRow");var ru=z.object({identity:z.array(Jd).optional(),entities:z.array(No).optional(),entity_series:z.array(eu).optional(),forward_looking:z.array(tu).optional(),documents:z.array(Mo).optional()});function Za(e,t){let r=ou(t)?t:{},o=Ya(r.schema_version,"epdf/1.0"),n=Ya(r.disclaimer,""),l=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Wa(l,o,n);let s=ru.safeParse(r);if(!s.success)return Wa(l,o,n);let c=s.data,a=(c.identity??[]).map(R=>Object.freeze({label:R.label,value:R.value})),d=(c.entities??[]).map(Bo),u=(c.entity_series??[]).map(R=>Object.freeze({key:R.key,label:R.label??R.key,points:Object.freeze((R.points??[]).map(v=>Object.freeze({at:v.at,value:v.value??null,display:v.display??null,origin:Qa(v.origin)})))})),p=(c.forward_looking??[]).map(R=>Object.freeze({title:R.title,detail:R.detail??null,dueAt:R.due_at??null})),f={};for(let R of c.documents??[])f[R.doc_id]=Ho(R);let h=r.is_empty===true||a.length===0&&d.length===0&&u.length===0&&p.length===0&&Object.keys(f).length===0;return Object.freeze({petRef:l,schemaVersion:o,isEmpty:h,withheld:false,generatedAt:iu(r.generated_at),identity:Object.freeze(a),entities:Object.freeze(d),entitySeries:Object.freeze(u),forwardLooking:Object.freeze(p),documents:Object.freeze(f),disclaimer:n})}i(Za,"mapRecordView");function Wa(e,t,r){return Object.freeze({petRef:e,schemaVersion:t,isEmpty:false,withheld:true,generatedAt:null,identity:Object.freeze([]),entities:Object.freeze([]),entitySeries:Object.freeze([]),forwardLooking:Object.freeze([]),documents:Object.freeze({}),disclaimer:r})}i(Wa,"withheldView");var nu=z.object({pet_ref:z.string().optional(),granted:z.boolean().optional(),version:z.string().nullish(),granted_at:z.string().nullish()});function qn(e,t){let r=nu.safeParse(t),o=r.success?r.data:{};return Object.freeze({petRef:typeof o.pet_ref=="string"&&o.pet_ref.length>0?o.pet_ref:e,granted:o.granted===true,version:o.version??null,grantedAt:o.granted_at??null})}i(qn,"mapConsent");function ou(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ou,"isObject");function Ga(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(Ga,"numberOr");function Ya(e,t){return typeof e=="string"&&e.length>0?e:t}i(Ya,"strOr");function iu(e){return typeof e=="string"&&e.length>0?e:null}i(iu,"strOrNull");var es=Object.freeze(["published","failed","revoked"]);function zr(e){return es.includes(e)}i(zr,"isTerminalStatus");function dr(e){if(e===null)return null;let t=e.recordsReason;return t==="consent_required"||t==="session_required"||t==="entitlement"||t==="pet_not_found"?t:null}i(dr,"recordsDenialReasonOf");var au="records_consent_required";function su(e){let t=e.raw;if(t===null||typeof t!="object")return null;let r=t,o=typeof r.error=="object"&&r.error!==null?r.error.code:r.code;return typeof o=="string"&&o.length>0?o:null}i(su,"recordsWireCodeOf");function tr(e){return e===null||e.httpStatus!==409?false:su(e)===au}i(tr,"isRecordsConsentRequired");var lu=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Fn(e){return e!==lu}i(Fn,"isUploadTransportAvailable");var ts=Object.freeze({record(){}}),ur=25*1024*1024,rs=64,tn=128,mt=128,rn="application/pdf",ns=9e4;function is(e){return new Uo(e)}i(is,"createRecordsController");var jo=class jo{constructor(t){this.recordCache=new Map;this.consentEpoch=new Map;this.reportedGaps=new Set;this.repository=t.repository,this.uploads=t.uploads,this.telemetry=t.telemetry??ts,this.newIdempotencyKey=t.newIdempotencyKey??mu(),this.timers=t.timers??uu,this.uploadDeadlineMs=t.uploadDeadlineMs??ns;}async createUploadRequest(t){let r=await this.repository.createRequest({pet_ref:t.petRef,idempotency_key:t.idempotencyKey});if(!r.ok)return this.onRequestError(r.error);let o=cr(r.value);return o===null?B(zn()):(this.observeRequest(o),_e(o))}async getRequest(t){let r=await this.repository.getRequest(t);if(!r.ok)return this.onRequestError(r.error);let o=cr(r.value);return o===null?B(zn()):(this.observeRequest(o),_e(o))}async listRequests(){let t=await this.repository.listRequests();if(!t.ok)return this.onRequestError(t.error);let r=zo(t.value);for(let o of r)this.observeRequest(o);return _e(r)}async uploadDocument(t){let{requestId:r,file:o}=t,n=cu(o);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),B(os(`upload rejected: ${n}`));let l=await this.repository.initiateUpload(r,{content_type:rn,file_size:o.sizeBytes});if(!l.ok)return this.onRequestError(l.error);let s=await this.postToS3(l.value,o,t);if(!s.ok)return this.telemetry.record("records.upload.failed",{reason:s.reason}),B(os(s.reason));let c=await this.repository.completeUpload(r,{upload_id:l.value.upload_id});if(!c.ok)return c.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:du(c.error)??"corrupt"}),this.onRequestError(c.error);let a=Ja(c.value);return a===null?B(zn()):_e(a)}async postToS3(t,r,o){let n=new AbortController,l=pu(n.signal,o.signal),s=this.timers.setTimeout(()=>n.abort(),this.uploadDeadlineMs);try{let c={signal:l};return o.onProgress&&(c.onProgress=o.onProgress),await this.uploads.postMultipart(t,r,c),{ok:!0}}catch{return {ok:false,reason:n.signal.aborted&&o.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(s);}}async getRecord(t){let r=this.consentEpoch.get(t)??0,o=await this.repository.getRecord(t);if(r!==(this.consentEpoch.get(t)??0))return B(Object.freeze({...q("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let l=dr(o.error);return l==="consent_required"?(this.recordCache.delete(t),this.telemetry.record("records.consent.denied",{pet_ref:t})):l==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t}),B(o.error)}let n=Za(t,o.value);return n.petRef!==t?B(zn()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:t}),this.recordCache.delete(t),_e(n)):(this.recordCache.set(t,n),_e(n))}peekCachedRecord(t){return this.recordCache.get(t)??null}async getConsent(t){let r=await this.repository.getConsent(t);return r.ok?_e(qn(t,r.value)):B(r.error)}async grantConsent(t){let r=await this.repository.putConsent(t.petRef,{consent_version:t.consentVersion,idempotency_key:t.idempotencyKey});return r.ok?_e(qn(t.petRef,r.value)):(dr(r.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t.petRef}),B(r.error))}async revokeConsent(t){let r=await this.repository.deleteConsent(t);return r.ok?(this.consentEpoch.set(t,(this.consentEpoch.get(t)??0)+1),this.recordCache.delete(t),_e(qn(t,r.value))):B(r.error)}reportCapabilityDenied(t){this.telemetry.record("records.capability.denied",t?{pet_ref:t}:{});}observeRequest(t){t.reviewStartedAt!==null&&!this.reportedGaps.has(t.id)&&(this.reportedGaps.add(t.id),this.telemetry.record("records.parse.gap",{request_id:t.id}));}onRequestError(t){return dr(t)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),B(t)}};i(jo,"RecordsControllerImpl");var Uo=jo;function cu(e){if(e.mimeType!==rn)return "unsupported_format";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>ur?"oversize":null}i(cu,"validateFile");function du(e){let t=e.wireMessage;return t==="unsupported_format"||t==="oversize"||t==="corrupt"?t:null}i(du,"reasonFromWire");function os(e){return q("mediaUploadFailed",{retryable:false,wireMessage:e})}i(os,"uploadFailed");function zn(){return q("internalError",{retryable:true})}i(zn,"internal");var uu={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function pu(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let o=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),r.signal}i(pu,"mergeSignals");function mu(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(mu,"defaultIdempotencyFactory");function pr(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(pr,"assertNever");function as(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(as,"errorFrame");function gu(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(gu,"authHeaders");function nn(e,t){return {...e,headers:{...bu(e.headers),...gu(t)}}}i(nn,"withAuthHeaders");function bu(e){if(!e)return {};let t={};for(let[r,o]of Object.entries(e)){let n=r.toLowerCase();n==="authorization"||n==="x-everfur-partner-key"||(t[r]=o);}return t}i(bu,"stripAuthHeaders");async function ss(e,t){if(t.mode==="anonymous")return t.transport.request(nn(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return B($o())}let o=await t.transport.request(nn(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(o.ok||o.error.httpStatus!==401)return o;let n;try{n=await t.identity.currentToken({forceRefresh:!0});}catch{return B($o())}let l=await t.transport.request(nn(e,{mode:"personalized",token:n,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !l.ok&&l.error.httpStatus===401?B($o(l.error.httpStatus)):l}i(ss,"authedSend");function $o(e){return q("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i($o,"authRejectedError");function ls(e){return q("internalError",{retryable:true,wireMessage:hu(e)})}i(ls,"networkError");function hu(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(hu,"describeCause");var Ru=3e4,vu=qo*2,xu="idempotency-key",wu=new Set(["POST","PUT","PATCH","DELETE"]),Cu=Object.freeze({onEvent(){}}),Eu=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function mr(e){let t=e.observer??Cu,r=e.timers??Eu,o=e.rng??Math.random,n=e.sleep??((f,h)=>qu(f,r,h)),l=e.maxAttempts??Ha,s=e.unaryTimeoutMs??Ru,c=e.newIdempotencyKey??rr(),a=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,h,R){let v=R?.maxAttempts,y=Math.max(1,v??l),b=R?.idempotent??wu.has(h.method)?c():null,w=Su(h,b),x=0;for(;;){let E=i($=>Object.freeze({call:f,method:h.method,path:h.path,attempt:x,...b?{idempotencyKey:b}:{},...$}),"stamp");a(E({phase:"attempt"}));let D=Lu(s,r),k=Vu(D.signal,h.signal),S;try{S=await ss({...w,signal:k.signal},e.auth);}catch($){S=B(ls($));}finally{k.dispose(),D.cancel();}if(S.ok)return a(E({phase:"settled",ok:true,reason:"ok"})),S;let I=S.error,Y=Tu(I,x,{maxAttempts:y,rng:o,now:r.now(),aborted:h.signal?.aborted===true,...v!==void 0?{perCallMaxAttempts:v}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),z={ok:false,code:I.code,reason:Y.reason,...I.httpStatus!==void 0?{httpStatus:I.httpStatus}:{},...I.requestId!==void 0?{requestId:I.requestId}:{}};if(!Y.retry)return a(E({phase:"settled",...z})),B(I);if(a(E({phase:"retry",...z,delayMs:Y.delayMs})),await n(Y.delayMs,h.signal),h.signal?.aborted===true)return a(E({phase:"settled",...z,reason:"aborted"})),B(I);x+=1;}}i(d,"send");async function u(f){return nn(f,await Ou(e.auth))}i(u,"authorize");async function*p(f,h,R){a(Object.freeze({call:f,phase:"stream.open",method:h.method,path:h.path,attempt:0}));try{yield*e.auth.transport.stream(h,R);}catch{yield as({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:u,stream:p})}i(mr,"createRequestFunnel");function Su(e,t){let r={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==xu&&(r[o]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(Su,"assembleHeaders");function rr(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(rr,"defaultIdempotencyKeyFactory");var ku=10;function Tu(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let o=_u(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!Vo(e.code))return {retry:false,reason:"terminal-code"};let n=o==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let s=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(ku,Math.floor(d)))},"policyCeiling"),c=r.perCallMaxAttempts??s()??r.maxAttempts;if(t+1>=c)return {retry:false,reason:"attempts-exhausted"};let a=Pu(e,r.now);return a!==null?a>vu?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:a}:{retry:true,reason:n,delayMs:Ua(t,r.rng)}}i(Tu,"decideRetry");function _u(e){let t=e.code==="unknown"?Ma(Au(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(_u,"throttleKind");function Pu(e,t){let r=Iu(e.raw);if(r===null)return null;let o=r-t;return o>0?o:0}i(Pu,"retryOverrideMs");function Iu(e){for(let t of ds(e)){let r=t.resets_at,o=Du(r);if(o!==null)return o}return null}i(Iu,"findResetsAt");function ds(e){if(!cs(e))return [];let t=[e];for(let r of ["error","detail"]){let o=e[r];cs(o)&&t.push(o);}return t}i(ds,"candidateScopes");function Du(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(Du,"parseInstantMs");function Au(e){for(let t of ds(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Au,"rawWireCode");function cs(e){return typeof e=="object"&&e!==null}i(cs,"isRecord");async function Ou(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(Ou,"resolveDeviceAuth");function Lu(e,t){let r=new AbortController,o=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(o),"cancel")}}i(Lu,"boundedSignal");function Vu(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let o=new AbortController;if(e.aborted||t.aborted)return o.abort(),{signal:o.signal,dispose:r};let n=i(()=>o.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),{signal:o.signal,dispose:i(()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",n);},"dispose")}}i(Vu,"mergeSignals");function qu(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(o=>{let n=t.setTimeout(()=>{r?.removeEventListener("abort",l),o();},e),l=i(()=>{t.clearTimeout(n),o();},"onAbort");r?.addEventListener("abort",l,{once:true});})}i(qu,"delayAbortable");function yr(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let o=e.charCodeAt(t+1);if(!(o>=56320&&o<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(yr,"hasLoneSurrogate");var nr="/widget/v1/records";function ps(e){let{auth:t}=e,r=t.mode,o=e.funnel??mr({auth:t,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(a,d,u)=>{let p=await o.send(a,d);return p.ok?p:B(Nu(p.error,r,u))},"send"),l=i((a,d)=>typeof d!="string"||d.length===0?q("validationFailed",{retryable:false,wireMessage:`${a} is required and must be a non-empty string`}):yr(d)?q("validationFailed",{retryable:false,wireMessage:`${a} contains an unpaired surrogate and cannot be encoded`}):null,"segmentError"),s=i((a,d,u)=>{let p=l(a,d);if(p!==null)return p;let h=[...d].length;return h>u?q("validationFailed",{retryable:false,wireMessage:`${a} is ${h} characters; the server accepts at most ${u}`}):null},"boundsError"),c=i((...a)=>a.find(d=>d!==null)??null,"firstError");return {createRequest:i(a=>{let d=c(s("idempotency_key",a.idempotency_key,tn),s("pet_ref",a.pet_ref,mt));return d?Promise.resolve(B(d)):n("records.createRequest",Wo(`${nr}/requests`,a),"request")},"createRequest"),initiateUpload:i((a,d)=>{let u=l("request_id",a);return u?Promise.resolve(B(u)):n("records.initiateUpload",Wo(`${nr}/requests/${encodeURIComponent(a)}/uploads/initiate`,d),"request")},"initiateUpload"),completeUpload:i((a,d)=>{let u=l("request_id",a);return u?Promise.resolve(B(u)):n("records.completeUpload",Wo(`${nr}/requests/${encodeURIComponent(a)}/uploads/complete`,d),"request")},"completeUpload"),getRequest:i(a=>{let d=l("request_id",a);return d?Promise.resolve(B(d)):n("records.getRequest",Nn(`${nr}/requests/${encodeURIComponent(a)}`),"request")},"getRequest"),listRequests:i(async()=>{let a=await n("records.listRequests",Nn(`${nr}/requests`),"request");if(!a.ok)return a;let d=a.value;return {ok:true,value:Array.isArray(d)?d:d.items??[]}},"listRequests"),getRecord:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.getRecord",Nn(`${nr}/pets/${encodeURIComponent(a)}/record`),"content")},"getRecord"),getConsent:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.getConsent",Nn(`${nr}/pets/${encodeURIComponent(a)}/consent`),"consent")},"getConsent"),putConsent:i((a,d)=>{let u=c(s("consent_version",d.consent_version,rs),s("idempotency_key",d.idempotency_key,tn),s("pet_ref",a,mt));return u?Promise.resolve(B(u)):n("records.putConsent",Mu(`${nr}/pets/${encodeURIComponent(a)}/consent`,d),"consent")},"putConsent"),deleteConsent:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.deleteConsent",Bu(`${nr}/pets/${encodeURIComponent(a)}/consent`),"consent")},"deleteConsent")}}i(ps,"createHttpRecordsRepository");function us(e,t){let r={...e,recordsReason:t};for(let o of ["wireMessage","raw"]){let n=Object.getOwnPropertyDescriptor(e,o);n!==void 0&&Object.defineProperty(r,o,n);}return Object.freeze(r)}i(us,"withReason");var Fu="pet_not_registered";function zu(e){return e.httpStatus!==404?null:e.reasonCode===Fu?"pet_not_found":"entitlement"}i(zu,"recordsErrorReasonFor");function Nu(e,t,r){let o=zu(e);return o!==null?us(e,o):e.code!=="accessDenied"?e:us(e,t==="anonymous"?"session_required":r==="content"?"consent_required":"entitlement")}i(Nu,"tagReason");function Nn(e){return {method:"GET",path:e}}i(Nn,"get");function Wo(e,t){return {method:"POST",path:e,body:t}}i(Wo,"post");function Mu(e,t){return {method:"PUT",path:e,body:t}}i(Mu,"put");function Bu(e){return {method:"DELETE",path:e}}i(Bu,"del");var ms=Symbol.for("@everfur/sdk#EverfurContext@v1"),ys=globalThis,fs=ys[ms]??(ys[ms]=createContext(null));fs.displayName??="EverfurContext";function ke(){let e=useContext(fs);if(e===null)throw new en("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(ke,"useEverfurContext");var Go=new Map,Yo=new Set;function gs(e){Go.set(e,(Go.get(e)??0)+1);for(let t of [...Yo])t();}i(gs,"notifyRecordsConsentWithdrawn");function Wu(e){return Go.get(e)??0}i(Wu,"recordsConsentEpochOf");function Gu(e){return Yo.add(e),()=>{Yo.delete(e);}}i(Gu,"subscribe");function Mn(e){let t=useCallback(()=>Wu(e),[e]);return useSyncExternalStore(Gu,t,t)}i(Mn,"useRecordsConsentEpoch");var Qo={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[]},hs=4e3,Ku=30;function yt(e){let{petRef:t}=e,r=useRef(e.uploadTransport);r.current=e.uploadTransport;let o=e.uploadTransport!==void 0,{runtime:n,userRef:l,scopeEpoch:s}=ke(),c=useMemo(()=>({}),[n,l,t,s,e.controller]),a=useRef(c),[d,u]=useState({scope:c,controller:e.controller??null}),p=e.controller??(d.scope===c?d.controller:null),[f,h]=useState({scope:c,value:Qo}),R=f.scope===c?f.value:Qo,v=useCallback(C=>{h(T=>T.scope===c?{scope:c,value:C(T.value)}:T);},[c]),y=useRef(0);useEffect(()=>(a.current=c,h({scope:c,value:Qo}),()=>{a.current=null,y.current+=1;}),[c]),useEffect(()=>{if(e.controller)return;let{services:C}=n.registry,T={record:i((M,K)=>C.telemetry.track(M,K),"record")},A=n.registry.acquire("records",`${l??""}|${t}${o?"|own-upload":""}`,()=>is({repository:ps({auth:C.authFor(l),...C.errorPolicy?{errorPolicy:C.errorPolicy}:{}}),uploads:o?{postMultipart:i((M,K,ye)=>(r.current??C.uploadTransport).postMultipart(M,K,ye),"postMultipart")}:C.uploadTransport,telemetry:T}),()=>{});return u({scope:c,controller:A}),()=>{n.registry.release(A);}},[n,l,t,e.controller,s,c,o]);let g=useCallback(C=>{v(T=>({...T,...C}));},[v]),b=useCallback(async()=>{if(!p||a.current!==c)return;let C=y.current+=1;D.current=0,I(),g({loading:true,error:null,denialReason:null,withheld:false});let[T,A]=await Promise.all([p.getConsent(t),p.listRequests()]);if(C!==y.current)return;let M=T.ok?T.value:null,K=A.ok?A.value.filter(Ve=>Ve.petRef===t):[],ye=A.ok?null:A.error;if(M&&M.granted){let Ve=await p.getRecord(t);if(C!==y.current)return;if(Ve.ok){g({consent:M,requests:K,record:Ve.value,withheld:Ve.value.withheld,error:Ve.value.withheld?ep():ye,denialReason:null,loading:false});return}g({consent:M,requests:K,record:null,error:Ve.error,denialReason:dr(Ve.error),withheld:false,loading:false});return}g({consent:M,requests:K,record:null,error:T.ok?ye:T.error,denialReason:M?"consent_required":Zu(T),withheld:false,loading:false});},[p,t,g,c]);useEffect(()=>(b(),()=>{y.current+=1;}),[b]);let w=useMemo(()=>Ju(R.requests),[R.requests]),x=w?.id??null,E=w?.status??null,D=useRef(0),k=useRef(null),[S,I]=useReducer(C=>C+1,0);useEffect(()=>{if(!p||x===null||E===null||zr(E)||E==="in_review")return;k.current!==String(x)&&(k.current=String(x),D.current=0);let C=false,T=i(async()=>{if(C||D.current>=Ku)return;D.current+=1;let M=await p.getRequest(x);if(!C){if(M.ok&&M.value.petRef===t){if(v(K=>({...K,requests:Hn(K.requests,M.value)})),zr(M.value.status)){M.value.status==="published"&&b();return}if(M.value.status==="in_review")return}A=setTimeout(()=>{T();},hs);}},"tick"),A=setTimeout(()=>{T();},hs);return ()=>{C=true,clearTimeout(A);}},[p,x,E,b,S,t,v]);let Y=useCallback(async C=>{if(!p||a.current!==c)return Un();let T=await p.createUploadRequest({petRef:t,idempotencyKey:C});return a.current===c&&T.ok&&T.value.petRef===t&&v(A=>({...A,requests:Hn(A.requests,T.value)})),T},[p,t,c,v]),z=useCallback((C,T)=>{v(A=>({...A,uploadQueue:A.uploadQueue.map(M=>M.key===C?T(M):M)}));},[v]),$=useCallback(async(C,T)=>{let A=Date.now().toString(36),M=T.map((ye,Ve)=>{let ie=Qu(ye);return {key:`${A}-${Ve}`,name:ye.name??null,status:ie===null?"queued":"skipped",progress:0,skipReason:ie,error:null}}),K=[...M];if(!p||a.current!==c)return Object.freeze(K);v(ye=>({...ye,uploadQueue:M,isUploading:true,uploadProgress:0}));for(let[ye,Ve]of T.entries()){let ie=M[ye];if(ie.status==="skipped")continue;if(a.current!==c)break;z(ie.key,Xe=>({...Xe,status:"uploading",progress:0})),g({uploadProgress:0});let we=await p.uploadDocument({requestId:C,file:Ve,onProgress:i(Xe=>{if(a.current!==c)return;let Vt=Math.min(1,Math.max(0,Xe));z(ie.key,qt=>({...qt,progress:Math.max(qt.progress,Vt)})),g({uploadProgress:Vt});},"onProgress")});if(a.current!==c)break;let vt=we.ok?{...ie,status:"done",progress:1}:{...ie,status:"failed",error:we.error};if(K[ye]=vt,z(ie.key,()=>vt),we.ok){let Xe=await p.getRequest(C);a.current===c&&Xe.ok&&Xe.value.petRef===t&&v(Vt=>({...Vt,requests:Hn(Vt.requests,Xe.value)}));}}return a.current===c&&g({isUploading:false,uploadProgress:null}),Object.freeze(K)},[p,g,z,t,c,v]),G=useCallback(async(C,T)=>{if(!p||a.current!==c)return Un();let A=`${Date.now().toString(36)}-0`;v(K=>({...K,isUploading:true,uploadProgress:0,uploadQueue:[{key:A,name:T.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let M=await p.uploadDocument({requestId:C,file:T,onProgress:i(K=>{a.current===c&&(g({uploadProgress:K}),z(A,ye=>({...ye,progress:Math.max(ye.progress,Math.min(1,K))})));},"onProgress")});if(a.current!==c)return M;if(g({isUploading:false,uploadProgress:null}),z(A,K=>M.ok?{...K,status:"done",progress:1}:{...K,status:"failed",error:M.error}),M.ok){let K=await p.getRequest(C);a.current===c&&K.ok&&K.value.petRef===t&&v(ye=>({...ye,requests:Hn(ye.requests,K.value)}));}return M},[p,g,z,t,c,v]),Z=useCallback(async(C,T)=>{if(!p||a.current!==c)return Un();let A=await p.grantConsent({petRef:t,consentVersion:C,idempotencyKey:T});return A.ok&&a.current===c&&b(),A},[p,t,b,c]),oe=useCallback(async()=>{if(!p||a.current!==c)return Un();let C=await p.revokeConsent(t);return C.ok&&gs(t),C.ok&&a.current===c&&(y.current+=1,g({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:C.value})),C},[p,t,g,c]),Ee=useCallback(()=>{b();},[b]),H=Xu(R,p!==null);return useMemo(()=>({status:H,record:R.record,requests:R.requests,activeRequest:w,consent:R.consent,error:R.error,denialReason:R.denialReason,withheld:R.withheld,isUploading:R.isUploading,uploadProgress:R.uploadProgress,uploadQueue:R.uploadQueue,createRequest:Y,uploadDocument:G,uploadDocuments:$,grantConsent:Z,revokeConsent:oe,refresh:Ee}),[H,R,w,Y,G,$,Z,oe,Ee])}i(yt,"useEverfurRecords");function Qu(e){if(e.mimeType!==rn)return "unsupported";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>ur?"too_large":null}i(Qu,"skipReasonFor");function Xu(e,t){return e.loading||!t?"loading":e.withheld||e.denialReason!==null||e.error!==null?"error":e.record!==null&&!e.record.isEmpty||e.requests.length>0?"populated":"empty"}i(Xu,"selectStatus");function Ju(e){if(e.length===0)return null;let t=e[0];for(let r of e)r.updatedAt>t.updatedAt&&(t=r);return t}i(Ju,"newestRequest");function Hn(e,t){let r=e.filter(o=>o.id!==t.id);return [t,...r]}i(Hn,"replaceRequest");function Zu(e){return e.ok?"consent_required":dr(e.error)??"consent_required"}i(Zu,"consentDenial");function ep(){return q("internalError",{retryable:false})}i(ep,"withheldSentinel");function Un(){return {ok:false,error:q("internalError",{retryable:true})}}i(Un,"notReady");function Xo(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(Xo,"reportHostFailure");function tp(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(tp,"isThenable");function jn(e,...t){if(typeof e=="function")try{let r=e(...t);return tp(r)&&Promise.resolve(r).then(void 0,Xo),r}catch(r){Xo(r);return}}i(jn,"callHost");var Rs=new WeakMap;function an(e){if(typeof e!="function")return;let t=Rs.get(e);if(t!==void 0)return t;let r=i((...o)=>{jn(e,...o);},"guarded");return Rs.set(e,r),r}i(an,"guardHost");function Fe(e,t){let r=null;for(let o of t){let n=e[o];typeof n=="function"&&(r??={...e},r[o]=an(n));}return r??e}i(Fe,"guardHostProps");function kr(e,...t){let r;try{r=e(...t);}catch(o){return Xo(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(r).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(kr,"callHostAsync");var vs=Object.freeze({name:"dashboard"});function $n(e=vs){return Object.freeze({stack:Object.freeze([e])})}i($n,"initialRecordsNav");function Wn(e){return e.stack[e.stack.length-1]??vs}i(Wn,"currentRecordsScreen");function Jo(e,t){return Object.freeze({stack:Object.freeze([...e.stack,t])})}i(Jo,"pushRecordsNav");function Zo(e,t){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),t])})}i(Zo,"replaceRecordsNav");function ei(e){return $n(e)}i(ei,"resetRecordsNav");function Gn(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(Gn,"popRecordsNav");function xs(e,t){return t.name==="dashboard"?ei(t):Wn(e).name==="upload"&&t.name==="request"?Zo(e,t):Jo(e,t)}i(xs,"transitionRecordsNav");function ti(e,t){switch(t.type){case "push":return Jo(e,t.screen);case "pop":return Gn(e).state;case "replace":return Zo(e,t.screen);case "reset":return ei(t.screen);case "navigate":return xs(e,t.screen);default:return e}}i(ti,"recordsNavReducer");function oi(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))oi(e[t]);}return e}i(oi,"deepFreeze");var rp=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Cs={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Es={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},ws={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},np={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},op={regular:"400",medium:"500",bold:"700"},ip={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},ap=0,Yn="System",Kn="monospace",sp=["content","heading","control","compact","badge"];function lp(e){let t={};for(let r of sp)t[r]=e;return t}i(lp,"authoredTierSizes");function Ss(){return {family:Yn,mono:Kn,fontUrl:null,families:{regular:Yn,medium:Yn,bold:Yn,mono:Kn,monoMedium:Kn,monoBold:Kn},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:ws,tierSizes:lp(ws),lineHeight:np,weight:op,letterSpacing:ip,scale:1,maxScale:ap,scaleCaps:rp}}i(Ss,"baseType");var ks={},ri=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function ni(e){return `cubic-bezier(${e.join(", ")})`}i(ni,"cssCubicBezier");var Ts={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:ni(ri.standard),emphasized:ni(ri.emphasized),exit:ni(ri.exit)},reducedMotion:false},cp={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#B91C1C",errorRed:"#FF1B00",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},_s=oi({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:cp,space:Cs,radius:Es,type:Ss(),motion:Ts,slots:ks}),dp={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A938C",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"};oi({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:dp,space:Cs,radius:Es,type:Ss(),motion:Ts,slots:ks});var Ps=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Is=globalThis,ii=Is[Ps]??(Is[Ps]=createContext(_s));ii.displayName??="EverfurThemeContext";function L(){return useContext(ii)}i(L,"useEverfurTheme");function gp(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(gp,"tierMultiplier");function m({tier:e="content",...t}){let{type:r}=L(),o=gp(r,e);return createElement(Text,o===void 0?t:{maxFontSizeMultiplier:o,...t})}i(m,"Text");var qe=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var bp=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function _(e,t){let r=e.type,o=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:o}:{fontFamily:o,fontWeight:r.weight[bp[t]]}}i(_,"face");var U=Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you\u2019re authorizing",send:"Send request",sending:"Sending\u2026",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can\u2019t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used"});var xe=Object.freeze({title:U.title,placeholder:U.placeholder,searchA11y:U.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload\u2026",uploadOwnA11y:"Upload records you already have",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:U.recentlyUsed,noMatch:i(e=>`No clinics match \u201C${e}\u201D. You can still request records using the option above.`,"noMatch"),loadingMore:"Loading more\u2026",loadMoreFailed:"Couldn\u2019t load more. Tap to retry.",loadMoreRetryA11y:"Retry loading more clinics",selectA11y:i(e=>`Request records from ${e}`,"selectA11y"),fallback:Object.freeze({title:"Can\u2019t find your clinic?",subtitle:"Add it by email and we\u2019ll request your records.",expandA11y:"Can't find your clinic? Add it by email to request records.",collapseA11y:"Hide the request-by-email form",nameLabel:"Clinic name",namePlaceholder:"Your clinic\u2019s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue",submitA11y:"Request records by email"})});function As(e){switch(e){case "verified":return {label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case "unverified":return {label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return {label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}i(As,"clinicEmailStatusBadge");function Os(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} km`}i(Os,"formatClinicDistanceLabel");function Ls(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} ${e===1?"kilometer":"kilometers"} away`}i(Ls,"formatClinicDistanceForA11y");var Vs=300,ai=2;var ce=Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"});function qs(e){return !zr(e.status)}i(qs,"isRecordsInProgress");function Qn(e,t){if(t===null)return null;let r=e.filter(l=>l.petRef===t);if(r.length===0)return null;let o=r.find(l=>l.status==="published");return o!==void 0?o:r.filter(qs).sort((l,s)=>s.updatedAt.localeCompare(l.updatedAt))[0]??null}i(Qn,"pickPetRecordsRequest");function si(e){if(e.hasMarkers)return "published";let t=Qn(e.requests,e.petRef);return t===null?"none":t.status==="published"||qs(t)?"in_progress":"none"}i(si,"deriveRecordsDashboardState");function hp(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i(hp,"selectDashboardLoading");function li(e){return hp(e)?"loading":e.hasFullRecord?"record":e.markersError||e.recordError&&!e.hasMarkers?"error":e.dashboardState==="in_progress"&&e.drivingRequest!==null?"in_progress":e.dashboardState==="none"?"none":"labs_only"}i(li,"selectDashboardView");function wt(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(wt,"recordsEmptyVariantForError");var ge=Object.freeze({loading:"Loading record request",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there\u2019s no reply by day 14.",waitingBanner:i(e=>`It\u2019s been ${e} ${e===1?"day":"days"}. Some clinics take a little longer; we\u2019ve been following up automatically and are still on it. If there\u2019s no reply by day 14, we\u2019ll let you know.`,"waitingBanner"),viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",tryAnotherClinicA11y:"Request records from a different clinic",convert:"Upload my own records instead",converting:"Switching\u2026",convertHint:"We\u2019ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we\u2019ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting\u2026",cancel:"Cancel request",cancelling:"Cancelling\u2026",cancelA11y:"Cancel this records request",cancellingA11y:"Cancelling, please wait",resend:"Resend email",resending:"Resending\u2026",resendA11y:"Resend the authorization email to the clinic",resendingA11y:"Resending the email, please wait",errors:Object.freeze({cancel:"We couldn\u2019t cancel this request. Please try again.",retry:"We couldn\u2019t retry this request. Please try again.",email:"We couldn\u2019t update the clinic email. Please try again.",convert:"We couldn\u2019t switch this to an upload. Please try again.",start:"We couldn\u2019t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function Rp(e){if(e.wireStatus==="clinic_declined")return "The clinic declined to release the records.";if(e.wireStatus==="clinic_responded_no_records")return "The clinic replied but didn\u2019t include your records.";switch(e.failureCode){case "no_response":return "The clinic didn\u2019t reply after several reminders over 14 days.";case "parse_timeout":case "parse_error":return "We received the records but couldn\u2019t read them. Uploading a clean copy usually fixes this.";case "hard_bounce":case "dispatch_failed":return "We couldn\u2019t deliver the email to the clinic.";default:return "This request didn\u2019t go through."}}i(Rp,"fallbackFailureTitle");function Fs(e){let t=e.failureReason?.trim()??"";return t.length>0?t:Rp(e)}i(Fs,"failureTitle");var vp=1440*60*1e3;function ci(e,t){if(!e.createdAt)return 0;let r=Date.parse(e.createdAt);if(Number.isNaN(r))return 0;let o=t-r;return o<=0?0:Math.floor(o/vp)}i(ci,"requestElapsedDays");var xp=7;function zs(e,t){return e.wireStatus!=="awaiting_response"?false:ci(e,t)>=xp}i(zs,"requestWaitingTooLong");function di(e){return e.status==="failed"}i(di,"isTerminalFailure");function Ns(e){return di(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i(Ns,"shouldOfferRecovery");function Hs(e,t){let[r,o]=useState(""),[n,l]=useState(""),[s,c]=useState([]),[a,d]=useState(null),[u,p]=useState([]),[f,h]=useState(true),[R,v]=useState(false),[y,g]=useState(false),[b,w]=useState(null),[x,E]=useState(null),[D,k]=useState(0),S=useRef(0),I=useRef(true),Y=t?.latitude,z=t?.longitude,$=useMemo(()=>Y!==void 0&&z!==void 0?{latitude:Y,longitude:z}:void 0,[Y,z]);useEffect(()=>(I.current=true,()=>{I.current=false,S.current+=1;}),[e]),useEffect(()=>{let H=true;return h(true),e.recentClinics({limit:5}).then(C=>{H&&(C.ok&&p(C.value.clinics),h(false));}).catch(()=>{H&&h(false);}),()=>{H=false;}},[e]),useEffect(()=>{let H=r.trim();if(H.length<ai){l("");return}let C=setTimeout(()=>l(H),Vs);return ()=>clearTimeout(C)},[r]);let G=n.length>=ai;useEffect(()=>{let H=S.current+=1;if(c([]),d(null),w(null),E(null),!G){v(false);return}v(true),e.searchClinics({query:n,limit:25,...$?{location:$}:{}}).then(C=>{!I.current||H!==S.current||(C.ok?(c(C.value.clinics),d(C.value.nextCursor)):w(C.error),v(false));}).catch(()=>{I.current&&H===S.current&&v(false);});},[e,n,G,$,D]);let Z=useCallback(()=>{if(!G||a===null||y)return;let H=S.current;g(true),E(null),e.searchClinics({query:n,limit:25,cursor:a,...$?{location:$}:{}}).then(C=>{!I.current||H!==S.current||(C.ok?(c(T=>[...T,...C.value.clinics]),d(C.value.nextCursor)):E(C.error),g(false));}).catch(()=>{I.current&&H===S.current&&g(false);});},[e,a,n,G,y,$]),oe=useCallback(H=>o(H),[]),Ee=useCallback(()=>k(H=>H+1),[]);return useMemo(()=>({query:r,debouncedQuery:n,isSearchActive:G,clinics:s,recent:u,recentLoading:f,initialLoading:R,loadingMore:y,hasNextPage:a!==null,error:b,pageError:x,setQuery:oe,loadMore:Z,retry:Ee}),[r,n,G,s,u,f,R,y,a,b,x,oe,Z,Ee])}i(Hs,"useClinicPicker");function pi(e,t,r,o){return Object.freeze({key:e?.id??`free:${t??""}`,clinic:e,freeText:t,email:r,idempotencyKey:o})}i(pi,"clinicDraftFor");var Nr=10,Jn=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),sn=i((e,t=1)=>z.string().refine(r=>!yr(r)&&[...r].length>=t&&[...r].length<=e),"text"),js=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),wp=z.object({clinicId:Jn.optional(),clinicFreeText:sn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:sn(320,3).refine(e=>!js(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Jn.optional(),signaturePngBase64:z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0)),Cp=z.object({petRef:sn(128),ownerName:sn(200).refine(e=>e.trim().length>0&&!js(e)),authorizationVersion:sn(64),clinics:z.array(wp).min(1).max(Nr)}).strict(),Ep=z.object({request_group_id:Jn,pet_ref:z.string(),created_count:z.number().int().nonnegative(),failed_count:z.number().int().nonnegative(),results:z.array(z.object({idempotency_key:z.string(),clinic_id:Jn.nullable().optional(),clinic_free_text:z.string().nullable().optional(),created:z.boolean(),request:z.unknown().optional(),failure_code:z.string().nullable().optional(),failure_reason:z.string().nullable().optional()}))});function $s(e){let t=e.funnel??mr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!Cp.safeParse(r).success)return B(q("validationFailed",{retryable:false}));let o=await t.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:r.petRef,owner_name:r.ownerName,authorization_version:r.authorizationVersion,clinics:r.clinics.map(s=>({...s.clinicId!==void 0?{clinic_id:s.clinicId}:{clinic_free_text:s.clinicFreeText},...s.clinicEmail!==void 0?{clinic_email:s.clinicEmail}:{},...s.signatureId!==void 0?{signature_id:s.signatureId}:{signature_png_base64:s.signaturePngBase64},idempotency_key:s.idempotencyKey}))}});if(!o.ok)return o;let n=Ep.safeParse(o.value);if(!n.success||n.data.pet_ref!==r.petRef)return Us();let l=[];for(let s of n.data.results){let c=s.request===void 0||s.request===null?null:cr(s.request);if(s.created!==(c!==null))return Us();l.push(Object.freeze({idempotencyKey:s.idempotency_key,clinicId:s.clinic_id??null,clinicFreeText:s.clinic_free_text??null,created:s.created,request:c,failureCode:s.failure_code??null,failureReason:s.failure_reason??null}));}return _e(Object.freeze({requestGroupId:n.data.request_group_id,petRef:n.data.pet_ref,results:Object.freeze(l),createdCount:n.data.created_count,failedCount:n.data.failed_count}))}}}i($s,"createRecordsClinicBatchClient");function Us(){return B(q("internalError",{retryable:false}))}i(Us,"malformed");var Ws=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Sp=z.object({clinics:z.array(z.object({clinic_id:Ws,name:z.string().min(1),address:z.string().nullable(),phone:z.string().nullable(),email_status:z.string(),distance_km:z.number().finite().nonnegative().nullable()})),next_cursor:z.string().nullable().optional()}),kp=z.object({authorization_version:z.string().min(1),scope_template:z.string().min(1),authorization_template:z.string().min(1)}),Tp=z.object({upload_id:z.string().min(1),upload_url:z.string().url().refine(e=>e.startsWith("https://")),upload_fields:z.record(z.string())});function Gs(e){let{repository:t}=e,r=i(async n=>{let l=await n;if(!l.ok)return l;let s=cr(l.value);return s===null?Tr():_e(s)},"request"),o=i(async n=>{let l=await n;if(!l.ok)return l;let s=Sp.safeParse(l.value);return s.success?_e(Object.freeze({clinics:Object.freeze(s.data.clinics.map(c=>Object.freeze({id:c.clinic_id,name:c.name,address:c.address,phone:c.phone,emailStatus:c.email_status,distanceKm:c.distance_km}))),nextCursor:s.data.next_cursor??null})):Tr()},"page");return {searchClinics:i((n={})=>o(t.searchClinics(n)),"searchClinics"),recentClinics:i((n={})=>o(t.recentClinics(n)),"recentClinics"),async getRequestGroup(n){let l=await t.getRequestGroup(n);if(!l.ok)return l;let s=Xa(l.value);return s===null?Tr():_e(s)},async getAuthorizationCopy(){let n=await t.getAuthorizationCopy();if(!n.ok)return n;let l=kp.safeParse(n.value);return l.success?_e(Object.freeze({authorizationVersion:l.data.authorization_version,scopeTemplate:l.data.scope_template,authorizationTemplate:l.data.authorization_template})):Tr()},async createClinicRequest(n){let l=await r(t.createClinicRequest(n));return l.ok&&l.value.petRef!==n.petRef?Tr():l},retryRequest:i(n=>r(t.retryRequest(n)),"retryRequest"),revokeRequest:i(n=>r(t.revokeRequest(n)),"revokeRequest"),updateClinicEmail:i((n,l)=>r(t.updateClinicEmail(n,l)),"updateClinicEmail"),convertToUpload:i(n=>r(t.convertToUpload(n)),"convertToUpload"),async initiateSignatureUpload(n){let l=await t.initiateSignatureUpload(n);if(!l.ok)return l;let s=Tp.safeParse(l.value);return s.success?_e(Object.freeze({uploadId:s.data.upload_id,uploadUrl:s.data.upload_url,uploadFields:Object.freeze(s.data.upload_fields)})):Tr()},async completeSignatureUpload(n){let l=await t.completeSignatureUpload(n);if(!l.ok)return l;let s=z.object({signature_id:Ws}).safeParse(l.value);return s.success?_e(s.data.signature_id):Tr()}}}i(Gs,"createRecordsClinicController");function Tr(){return B(q("internalError",{retryable:false}))}i(Tr,"malformed");var fr="/widget/v1/records",Ys=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),br=i((e,t=1)=>z.string().refine(r=>!yr(r)&&[...r].length>=t&&[...r].length<=e),"text"),Qs=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),Xs=br(320,3).refine(e=>!Qs(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),Ks=br(64),_p=z.object({limit:z.number().int().min(1).max(25).optional()}).strict(),Pp=z.object({query:br(200,0).optional(),location:z.object({latitude:z.number().finite().min(-90).max(90),longitude:z.number().finite().min(-180).max(180)}).strict().optional(),limit:z.number().int().min(1).max(100).optional(),cursor:br(512,0).optional()}).strict(),Ip=z.object({petRef:br(128),ownerName:br(200).refine(e=>e.trim().length>0&&!Qs(e)),authorizationVersion:br(64),clinicId:Ys.optional(),clinicFreeText:br(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Xs.optional(),signatureId:Ys.optional(),signaturePngBase64:z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0));function Js(e){let t=e.funnel??mr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((n,l,s=false)=>t.send(`records.clinic.${n}`,l,l.method==="GET"||s?void 0:{idempotent:false,maxAttempts:1}),"send"),o=i((n,l,s)=>Ks.safeParse(n).success?r(l,{method:"POST",path:`${fr}/requests/${encodeURIComponent(n)}/${l}`,...s?{body:s}:{}}):gr(),"recover");return {searchClinics(n){return Pp.safeParse(n).success?r("search",{method:"GET",path:`${fr}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):gr()},recentClinics(n){return _p.safeParse(n).success?r("recent",{method:"GET",path:`${fr}/clinics/recent`,query:{limit:n.limit}}):gr()},getRequestGroup(n){return Ks.safeParse(n).success?r("requestGroup",{method:"GET",path:`${fr}/request-groups/${encodeURIComponent(n)}`}):gr()},getAuthorizationCopy:i(()=>r("authorizationCopy",{method:"GET",path:`${fr}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return Ip.safeParse(n).success?r("create",{method:"POST",path:`${fr}/clinic-requests`,body:{pet_ref:n.petRef,owner_name:n.ownerName,authorization_version:n.authorizationVersion,idempotency_key:n.idempotencyKey,...n.clinicId!==void 0?{clinic_id:n.clinicId}:{clinic_free_text:n.clinicFreeText},...n.clinicEmail!==void 0?{clinic_email:n.clinicEmail}:{},...n.signatureId!==void 0?{signature_id:n.signatureId}:{signature_png_base64:n.signaturePngBase64}}},true):gr()},retryRequest:i(n=>o(n,"retry"),"retryRequest"),revokeRequest:i(n=>o(n,"revoke"),"revokeRequest"),convertToUpload:i(n=>o(n,"convert-to-upload"),"convertToUpload"),updateClinicEmail(n,l){return Xs.safeParse(l).success?o(n,"clinic-email",{clinic_email:l}):gr()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?gr():r("signatureInitiate",{method:"POST",path:`${fr}/signatures/initiate`,body:{content_type:"image/png",file_size:n}})},completeSignatureUpload(n){return /^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n)?r("signatureComplete",{method:"POST",path:`${fr}/signatures/complete`,body:{upload_id:n}}):gr()}}}i(Js,"createHttpRecordsClinicRepository");function gr(){return Promise.resolve(B(q("validationFailed",{retryable:false})))}i(gr,"invalid");function Nt(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=useMemo(()=>{let{services:l}=e.registry;return Gs({repository:Js({auth:l.authFor(t),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})})},[e,t,r]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>{let l=i(async s=>{if(t===null||n.current!==o)return B(q("accessDenied"));let c=await s();return n.current===o?c:B(q("accessDenied"))},"run");return {searchClinics:i(s=>l(()=>o.searchClinics(s)),"searchClinics"),recentClinics:i(s=>l(()=>o.recentClinics(s)),"recentClinics"),getRequestGroup:i(s=>l(()=>o.getRequestGroup(s)),"getRequestGroup"),getAuthorizationCopy:i(()=>l(()=>o.getAuthorizationCopy()),"getAuthorizationCopy"),createClinicRequest:i(s=>l(()=>o.createClinicRequest(s)),"createClinicRequest"),retryRequest:i(s=>l(()=>o.retryRequest(s)),"retryRequest"),revokeRequest:i(s=>l(()=>o.revokeRequest(s)),"revokeRequest"),updateClinicEmail:i((s,c)=>l(()=>o.updateClinicEmail(s,c)),"updateClinicEmail"),convertToUpload:i(s=>l(()=>o.convertToUpload(s)),"convertToUpload"),initiateSignatureUpload:i(s=>l(()=>o.initiateSignatureUpload(s)),"initiateSignatureUpload"),completeSignatureUpload:i(s=>l(()=>o.completeSignatureUpload(s)),"completeSignatureUpload")}},[o,t])}i(Nt,"useEverfurRecordsClinic");function mi(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=useMemo(()=>{let{services:l}=e.registry;return $s({auth:l.authFor(t),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})},[e,t,r]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>({async createClinicRequestBatch(l){if(t===null||n.current!==o)return B(q("accessDenied"));let s=await o.createClinicRequestBatch(l);return n.current===o?s:B(q("accessDenied"))}}),[o,t])}i(mi,"useEverfurRecordsClinicBatch");var gi=class gi extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,o){return Object.is(r.resetKey,o.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(gi,"HostRenderBoundary");var yi=gi;function Ap({render:e}){return e()}i(Ap,"RenderHost");function fi({render:e,fallback:t,resetKey:r}){return createElement(yi,{fallback:t,resetKey:r,children:createElement(Ap,{render:e})})}i(fi,"HostRender");var Op=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function Lp(e){return Op[e]}i(Lp,"requires");function rl(e,t,r){let o=Lp(e),n=new Map;for(let c of t)n.set(c.resource,c);if(r?.isPending===true&&o.some(c=>!n.has(c)))return bi({name:e,enabled:false,isPending:true,limits:{}});let l=Vp(o,n);return o.filter(c=>n.get(c)?.granted!==true).length===0?bi({name:e,enabled:true,isPending:false,limits:l}):bi({name:e,enabled:false,isPending:false,limits:l,disabled:qp(o,n)})}i(rl,"decideCapability");function Vp(e,t){let r={};for(let o of e){let n=t.get(o)?.limits;if(n)for(let[l,s]of Object.entries(n)){let c=r[l];r[l]=c===void 0?s:Math.min(c,s);}}return r}i(Vp,"mergeLimits");function qp(e,t){for(let r of e){let o=t.get(r)?.disabled;if(o)return Object.freeze({reason:o.reason,level:o.level,recoverable:o.recoverable})}return Object.freeze({reason:Fo("accessDenied"),level:"user_entitlement",recoverable:false})}i(qp,"disabledFor");function bi(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(bi,"freezeDecision");function hi(e){let{runtime:t}=ke(),r=t.entitlements,o=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>rl(e,o.decisions,{isPending:o.isPending}),[e,o])}i(hi,"useCapability");var Np=48;function Mp(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Mp,"selectView");function Ne(e){let{capability:t,children:r,renderDisabled:o,renderPending:n,style:l}=e,s=hi(t),c=useMemo(()=>Mp(s),[s]);switch(c){case "enabled":return r;case "pending":return n?jsx(fi,{render:n,fallback:jsx(ol,{capability:t,style:l})}):jsx(ol,{capability:t,style:l});case "disabled":return o?jsx(fi,{render:()=>o(s),fallback:jsx(il,{decision:s,style:l}),resetKey:s}):jsx(il,{decision:s,style:l});default:return pr(c)}}i(Ne,"CapabilityGate");function ol({capability:e,style:t}){let r=L(),o=useMemo(()=>al(r),[r]);return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:o.skeletonBar})})}i(ol,"PendingSkeleton");function il({decision:e,style:t}){let r=L(),o=useMemo(()=>al(r),[r]),n=e.disabled?.reason??"";return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:n,children:n.length>0?jsx(m,{style:o.offstateText,children:n}):null})}i(il,"OffState");function al(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({offstate:{minHeight:Np,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:o.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{..._(e,"regular"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:o.xs,backgroundColor:t.brandSofter}})}i(al,"makeStyles");var ln=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function Me(e){let t=L(),r=useMemo(()=>Up(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${ln.title}. ${ln.body}`,children:[jsx(m,{style:r.title,children:ln.title}),jsx(m,{style:r.body,children:ln.body})]})}i(Me,"ClinicalDisclaimer");function Up(e){let{color:t,space:r,type:o}=e;return StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{..._(e,"bold"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.secondary,letterSpacing:o.letterSpacing.eyebrow},body:{..._(e,"regular"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.muted}})}i(Up,"makeStyles");function Je(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(Je,"slotBox");function ot(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(ot,"slotText");var cl=Object.freeze({idle:Object.freeze({title:"Find your pet\u2019s clinic",body:"Search for the clinic that holds your pet\u2019s records. We\u2019ll request them on your behalf once you sign the authorization.",action:null}),no_requests:Object.freeze({title:"No record requests yet",body:"When you request records from a clinic, you\u2019ll be able to track every step here.",action:null}),no_records:Object.freeze({title:"Nothing to show just yet",body:"Once your pet\u2019s records arrive and our team reviews them, lab trends and visits will appear here.",action:null}),rate_limited:Object.freeze({title:"Slow down a moment",body:"You\u2019ve made a lot of requests just now. You can try again shortly.",action:"Try again"}),service_unavailable:Object.freeze({title:"Records search is temporarily down",body:"We\u2019re working on it. Please try again in a few minutes.",action:"Try again"}),error:Object.freeze({title:"Couldn\u2019t reach Everfur",body:"Check your connection and try again.",action:"Try again"})}),xi=60;function dl(e){return `Try again in ${e}s`}i(dl,"coolingActionLabel");var ul="Try again, available shortly";function Qe({variant:e,onAction:t,message:r,testID:o}){let n=Yp(),l=cl[e],[s,c]=useState(e==="rate_limited"?xi:0);useEffect(()=>{e==="rate_limited"&&c(xi);},[e]),useEffect(()=>{if(s<=0)return;let u=setTimeout(()=>c(p=>Math.max(0,p-1)),1e3);return ()=>clearTimeout(u)},[s]);let a=e==="rate_limited"&&s>0,d=a?dl(s):l.action;return jsxs(View,{style:n.container,accessibilityRole:"summary",testID:o,children:[jsx(View,{style:n.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:n.title,children:l.title}),jsx(m,{style:n.body,children:r??l.body}),d!==null&&t?jsx(Pressable,{onPress:t,disabled:a,accessibilityRole:"button",accessibilityLabel:a?ul:d,accessibilityState:{disabled:a},style:[n.action,a?n.actionDisabled:null],testID:o?`${o}-action`:`records-empty-${e}-action`,children:jsx(m,{style:n.actionLabel,children:d})}):null]})}i(Qe,"RecordsEmptyState");function Yp(){let e=L();return useMemo(()=>Kp(e),[e])}i(Yp,"useStyles");function Kp(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=r.lg+r.xs+r.xs/2;return StyleSheet.create({container:{paddingVertical:r.xxl,paddingHorizontal:r.xl,alignItems:"center",gap:r.sm+r.xs/2},glyph:{width:s,height:s,borderRadius:s/2,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug)-1,color:t.brandInk,textAlign:"center"},body:{..._(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.normal),color:t.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:r.sm,minHeight:r.xxl+r.sm,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,backgroundColor:t.brand,alignItems:"center",justifyContent:"center",...Je(l.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug)-1,...ot(l.primaryButton)}})}i(Kp,"makeStyles");var Ze="Back";function et({title:e,onBack:t,right:r,testID:o,variant:n="brand"}){let l=dn();return jsxs(View,{style:l.row,testID:o,children:[t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Ze,hitSlop:12,style:l.back,testID:o?`${o}-back`:void 0,children:jsx(View,{style:l.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):jsx(View,{style:l.back}),jsx(m,{style:n==="document"?l.documentTitle:l.title,accessibilityRole:"header",numberOfLines:1,children:e}),jsx(View,{style:l.right,children:r??jsx(View,{style:l.back})})]})}i(et,"ScreenHeader");function fl(){let e=dn();return jsxs(View,{style:e.listGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.listBar}),jsx(View,{style:e.listBar}),jsx(View,{style:e.listBar})]})}i(fl,"ListGlyph");function gl(){let e=dn();return jsxs(View,{style:e.shareGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:[e.shareDot,e.shareDotTop]}),jsx(View,{style:[e.shareDot,e.shareDotLeft]}),jsx(View,{style:[e.shareDot,e.shareDotBottom]}),jsx(View,{style:[e.shareStroke,e.shareStrokeUp]}),jsx(View,{style:[e.shareStroke,e.shareStrokeDown]})]})}i(gl,"ShareGlyph");function bl(){let e=dn();return jsxs(View,{style:e.sendGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.sendBody}),jsx(View,{style:e.sendFold})]})}i(bl,"SendGlyph");function hl(){let e=dn();return jsxs(View,{style:e.downloadGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.downloadStem}),jsx(View,{style:e.downloadHead}),jsx(View,{style:e.downloadTray})]})}i(hl,"DownloadGlyph");function dn(){let e=L();return useMemo(()=>em(e),[e])}i(dn,"useStyles");function em(e){let{color:t,space:r,type:o}=e,n=r.xxl+r.md,l=r.md,s=r.xs/2,c=r.lg+r.xs+r.xs/2;return StyleSheet.create({row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md,gap:r.sm},back:{width:n,height:n,alignItems:"center",justifyContent:"center"},chevron:{width:l,height:l,borderLeftWidth:s,borderBottomWidth:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginLeft:r.xs},title:{flex:1,..._(e,"bold"),fontSize:o.size.heading,lineHeight:Math.round(o.size.heading*o.lineHeight.tight)+1,color:t.brandInk},documentTitle:{flex:1,textAlign:"center",..._(e,"bold"),fontSize:o.size.subtitle,lineHeight:Math.round(o.size.subtitle*o.lineHeight.snug),color:t.text.primary},right:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2},listGlyph:{width:c,height:c,justifyContent:"space-evenly"},listBar:{height:s,borderRadius:s,backgroundColor:t.brandInk},shareGlyph:{width:c-r.xs,height:c-r.xs},shareDot:{position:"absolute",width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs,borderWidth:s,borderColor:t.brandInk},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:r.xs+r.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:r.xs,top:r.sm,width:r.sm+r.xs/2,height:s,backgroundColor:t.brandInk},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:c-r.xs,height:c-r.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],borderRadius:s},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:s,backgroundColor:t.brandInk},downloadGlyph:{width:c-r.xs,height:c-r.xs,alignItems:"center"},downloadStem:{width:s,height:r.sm+r.xs/2,backgroundColor:t.brandInk},downloadHead:{width:r.sm,height:r.sm,borderRightWidth:s,borderBottomWidth:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginTop:-r.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:r.xs+r.xs/2,borderLeftWidth:s,borderRightWidth:s,borderBottomWidth:s,borderColor:t.brandInk}})}i(em,"makeStyles");var nm=120,om=44;function im({reason:e,onExit:t,exitLabel:r,style:o}){let{color:n,space:l,radius:s,type:c}=L();return jsxs(View,{testID:"records-gate-off",style:[{minHeight:nm,justifyContent:"center",gap:l.md,padding:l.lg,borderRadius:s.md,borderWidth:1,borderColor:n.brandBorder,backgroundColor:n.surfaceCream},o],children:[e.length>0?jsx(m,{style:{fontSize:c.size.bodyTight,color:n.text.muted},children:e}):null,jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:r,testID:"records-gate-off-exit",style:{minHeight:om,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:l.lg,borderRadius:s.pill,borderWidth:1.5,borderColor:n.brand},children:jsx(m,{style:{fontSize:c.size.body,color:n.brand},children:r})})]})}i(im,"RecordsGateOffState");function Be(e,t){return e===void 0?{}:{renderDisabled:i(r=>jsx(im,{reason:r.disabled?.reason??"",onExit:e,exitLabel:t}),"renderDisabled")}}i(Be,"recordsGateExit");var sm="your pet";function He(e){let t=e?.trim()??"";return t.length>0?t:sm}i(He,"petNameOr");var dt=Object.freeze({title:"Health records",openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${He(e)}\u2019s lab trends`,"lead"),retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:i(e=>`Important: ${e}`,"important")}),Mt=Object.freeze({title:"Marker Summary",marker:"Marker",markers:"Markers",outOfRange:"OUT OF RANGE",inRange:"IN RANGE",noRange:"NO RANGE",subtitle:"Summary of your pet\u2019s biomarkers",ask:"Ask about these markers",askA11y:"Ask Everfur about these markers",a11y:i((e,t,r,o)=>`Marker summary: ${e} ${e===1?"marker":"markers"}, ${t} in range, ${r} out of range${o>0?`, ${o} without a range`:""}.`,"a11y")}),wi=Object.freeze({counter:i((e,t)=>`${e+1} of ${t}`,"counter"),a11y:i((e,t,r)=>e!==null?`${e}, marker ${t+1} of ${r}. Swipe left or right to see more markers.`:`Marker ${t+1} of ${r}`,"a11y")}),or=Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we\u2019ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askA11y:i(e=>`Ask Everfur about ${e}`,"askA11y"),status:i(e=>`Status: ${e}`,"status"),latestA11y:i((e,t,r)=>`Latest reading ${e}, ${t}, collected ${r}`,"latestA11y"),readingsA11y:i(e=>`${e} readings, oldest to newest`,"readingsA11y")}),Ct=Object.freeze({title:"Where this reading came from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn\u2019t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading",askA11y:"Ask Everfur about this reading"}),Mr=Object.freeze({title:i(e=>`${He(e)}\u2019s records request`,"title"),body:i(e=>`We\u2019re requesting ${He(e)}\u2019s records from your vet. This usually takes a few days; we\u2019ll show lab trends here as soon as they arrive.`,"body"),a11y:i(e=>`Records request in progress for ${He(e)}.`,"a11y"),openA11y:i((e,t)=>`Open ${He(e)}\u2019s records request. ${t}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),_r=Object.freeze({title:i(e=>`Add ${He(e)}\u2019s records`,"title"),body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicA11y:i(e=>`Request ${He(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${He(e)}\u2019s records`,"uploadDocumentA11y")});var to="rgba(0,0,0,0.4)";function be(){let e=L();return useMemo(()=>um(e),[e])}i(be,"useScreenStyles");function hr({disclaimer:e,style:t}){let r=be();return e.trim().length===0?null:jsxs(View,{style:[r.band,t],accessible:true,accessibilityRole:"text",accessibilityLabel:dt.important(e),testID:"records-disclaimer-band",children:[jsx(View,{style:r.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{style:r.infoGlyphText,children:"i"})}),jsx(m,{style:r.bandText,children:e})]})}i(hr,"DisclaimerBand");function re({label:e,onPress:t,kind:r="primary",disabled:o=false,busy:n=false,accessibilityLabel:l,testID:s,style:c}){let a=be(),d=L(),u=r==="primary"?a.pillPrimary:r==="outline"?a.pillOutline:r==="danger"?a.pillDanger:r==="ask"?a.pillAsk:a.pillLink,p=r==="primary"?a.pillPrimaryLabel:r==="danger"?a.pillDangerLabel:r==="ask"?a.pillAskLabel:r==="link"?a.pillLinkLabel:a.pillOutlineLabel;return jsxs(Pressable,{onPress:t,disabled:o||n,accessibilityRole:"button",accessibilityLabel:l??e,accessibilityState:{disabled:o||n,busy:n},style:[a.pill,u,o?a.pillDisabled:null,c],testID:s,children:[n?jsx(ActivityIndicator,{size:"small",color:r==="primary"?d.color.onPrimary:d.color.brandInk}):null,jsx(m,{style:p,children:e})]})}i(re,"Pill");function Kt({label:e,tone:t="neutral",testID:r}){let o=be(),{bg:n,fg:l}=o.chipTones[t];return jsx(View,{style:[o.chip,n],testID:r,children:jsx(m,{style:[o.chipText,l],children:e})})}i(Kt,"Chip");function Bt({title:e,count:t}){let r=be();return jsxs(View,{style:r.sectionHeader,children:[jsx(m,{style:r.sectionTitle,accessibilityRole:"header",children:e}),t!==void 0?jsx(m,{style:r.sectionCount,children:t}):null]})}i(Bt,"SectionHeader");function Pr({direction:e="right"}){let t=be(),r=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsx(View,{style:[t.chevron,{transform:[{rotate:r}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(Pr,"Chevron");function um(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c}=n,a=i((v,y)=>Math.round(v*y),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl+r.md,p=i((v,y,g,b="regular")=>({..._(e,b),fontSize:v,lineHeight:a(v,y),color:g}),"text"),f=ot(l.recordCard),h=e.brightness==="dark"?t.errorRed:t.danger,R=i((v,y)=>({bg:{backgroundColor:v},fg:{color:y}}),"tone");return {chipTones:{neutral:R(t.badgeBgNeutral,t.text.secondary),info:R(t.brandSoft,t.brandInk),warning:R(t.badgeBgCaution,t.warningStrong),critical:R(t.badgeBgCritical,t.danger),positive:R(t.badgeBgPositive,t.success)},...StyleSheet.create({root:{flex:1,backgroundColor:t.background},body:{flex:1},content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg},contentTight:{paddingHorizontal:r.sm,paddingBottom:r.xxl,gap:r.lg},inset:{paddingHorizontal:r.sm},section:{gap:r.sm+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.xs},sectionTitle:{...p(s.body+1,c.snug,t.text.primary,"bold")},sectionCount:{...p(s.bodyTight,c.snug,t.text.muted,"medium")},card:{borderRadius:o.lg-r.xs,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.xs,...Je(l.recordCard,d)},creamCard:{borderRadius:o.lg-r.xs/2,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md,...Je(l.recordCard,d)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,paddingVertical:r.md},rowDivider:{borderTopWidth:d,borderTopColor:t.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:r.xs+r.xs/2},rowTitle:{...p(s.body,c.snug,t.text.primary,"medium"),...f},rowDetail:{...p(s.caption,c.normal,t.text.secondary),marginTop:r.xs/2,...f},rowValue:{...p(s.body+1,c.snug,t.text.primary,"bold"),marginTop:r.xs/2,...f},rowMuted:{...p(s.caption,c.normal,t.text.muted),...f},chip:{borderRadius:o.pill,paddingHorizontal:r.sm,paddingVertical:r.xs-1,alignSelf:"flex-start"},chipText:{...p(s.tiny,c.snug,t.text.primary,"medium")},pill:{minHeight:u,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm},pillPrimary:{backgroundColor:t.brand,...Je(l.primaryButton)},pillPrimaryLabel:{...p(s.body,c.snug,t.onPrimary,"bold"),...ot(l.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:t.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...p(s.body,c.snug,t.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:t.danger,backgroundColor:t.surface},pillDangerLabel:{...p(s.bodyTight,c.snug,t.danger,"bold")},pillAsk:{borderWidth:d,borderColor:t.borderRingCream,backgroundColor:t.surface},pillAskLabel:{...p(s.body,c.snug,t.text.primary,"bold")},pillLink:{backgroundColor:"transparent",paddingHorizontal:r.sm},pillLinkLabel:{...p(s.body,c.snug,t.linkInk,"bold")},pillDisabled:{opacity:.5},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},infoNoteText:{flex:1,...p(s.bodyTight,c.normal,t.text.primary)},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCaution,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},cautionNoteText:{flex:1,...p(s.bodyTight,c.normal,t.warningStrong)},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2},statusText:p(s.bodyTight,c.relaxed,t.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCritical,padding:r.md},errorText:{flex:1,...p(s.bodyTight,c.normal,h)},band:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft},bandText:{flex:1,...p(s.caption,c.normal,t.text.secondary)},infoGlyph:{width:r.md+r.xs/2,height:r.md+r.xs/2,borderRadius:o.pill,borderWidth:1,borderColor:t.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...p(s.small,c.tight,t.text.secondary,"bold")},chevron:{width:r.sm,height:r.sm,borderTopWidth:r.xs/2,borderRightWidth:r.xs/2,borderColor:t.text.muted},lead:{paddingHorizontal:r.sm,...p(s.body+1,c.snug,t.text.primary,"bold")},field:{minHeight:u,paddingHorizontal:r.md,paddingVertical:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,..._(e,"regular"),fontSize:s.body},fieldLabel:{...p(s.bodyTight,c.normal,t.text.secondary,"medium")},muted:p(s.caption,c.normal,t.text.muted),bodyText:p(s.body,c.normal,t.text.primary)})}}i(um,"makeScreenStyles");function Br(e,t){return e===null?"":t?`${e} ${t}`:e}i(Br,"formatEntityValue");var vl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Q(e){if(!e)return "-";let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(t!==null){let n=vl[Number(t[2])-1];return n===void 0?"-":`${n} ${Number(t[3])}, ${t[1]}`}let r=Date.parse(e);if(Number.isNaN(r))return "-";let o=new Date(r);return `${vl[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(Q,"formatRecordsDate");var fe=Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:i(e=>`Measured ${e}`,"measured"),uploadedDocument:"Uploaded document",kind:Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:i(e=>`Dr. ${e}`,"doctor"),lot:i(e=>`Lot ${e}`,"lot"),expires:i(e=>`Expires ${e}`,"expires")});function Qt(e){switch(e){case "above":return {label:"Above range",outOfRange:true};case "below":return {label:"Below range",outOfRange:true};case "in_range":return {label:"In range",outOfRange:false};default:return {label:"No range on file",outOfRange:false}}}i(Qt,"markerStatusLabel");function Hr(e,t){return t<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${t} visits`}i(Hr,"trajectoryLabel");function ir(e){let t=e.replace(/_/g," ").trim();return t.length===0?e:t.charAt(0).toUpperCase()+t.slice(1)}i(ir,"humanize");var xl=Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function Ir(e){return Object.prototype.hasOwnProperty.call(xl,e)?xl[e]:ir(e)}i(Ir,"bodySystemLabel");var wl=Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function Ur(e){return Object.prototype.hasOwnProperty.call(wl,e)?wl[e]:ir(e)}i(Ur,"soapSectionLabel");function Cl(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(Cl,"formatWeightKg");function Et(e,t,r){if((e===null||!Number.isFinite(e))&&r)return r;if(e===null||!Number.isFinite(e))return "-";let o=e.toFixed(3).replace(/\.?0+$/,"");return t?`${o} ${t}`:o}i(Et,"formatMarkerReading");function Ei(e,t,r){let o=Hr(t,r);return e?`${fe.measured(Q(e))}${o?` \xB7 ${o}`:""}`:o}i(Ei,"labDetailLine");var de=Object.freeze({openA11y:"Share medical record",title:"Share medical record",helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",createLink:"Create link and share",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn\u2019t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",copyLinkA11y:i(e=>`Copy share link, ${e}`,"copyLinkA11y"),turnOff:"Turn off",turnOffA11y:i(e=>`Turn off share link, ${e}`,"turnOffA11y"),turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",copied:"Link copied.",copyFailed:"Could not copy the link.",turnedOff:"Link turned off."})});function pm(e,t){if(!e)return false;let r=Date.parse(e);return Number.isNaN(r)?false:r<=t}i(pm,"isShareExpired");function mm(e,t){let r=Q(e);return r==="-"?t?"Expired":"No expiry date":t?`Expired ${r}`:`Expires ${r}`}i(mm,"formatShareExpiry");function El(e,t,r){let o=e.map(n=>{let l=pm(n.expiresAt,r),s=mm(n.expiresAt,l),c=Q(n.createdAt),a=l?"Expired":"Active",d=s.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return {shareId:n.shareId,shareUrl:t[n.shareId]??null,active:!l,statusLabel:a,expiryLabel:s,createdLabel:c==="-"?null:`Created ${c}`,a11yLabel:`Share link. ${a}. ${s}.`,actionContext:d}});return Object.freeze([...o.filter(n=>n.active),...o.filter(n=>!n.active)])}i(El,"buildShareRows");function ro(e,t){let r=e?.httpStatus;if(tr(e)){if(t==="create")return "Records access for this pet is off, so a new link cannot be created.";if(t==="download")return "Records access for this pet is off, so the PDF cannot be downloaded."}if(r===429)return "You are creating links a little too fast. Wait a moment, then try again.";if(t==="revoke"&&(r===404||r===409||r===410))return "That link was already turned off.";if(r===401||r===403)return "You need to be signed in as this pet's owner to do that.";switch(t){case "create":return "Could not create a share link. Please try again.";case "revoke":return "Could not turn off that link. Please try again.";default:return "Could not download the record PDF. Please try again."}}i(ro,"shareErrorMessage");function ve({width:e,height:t,radius:r,style:o}){let{color:n,radius:l}=L();return jsx(View,{style:[{width:e,height:t,borderRadius:r??l.xs,backgroundColor:n.skeleton},o],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(ve,"SkeletonBlock");var Si=180,kl=70,no=22,fm=300,Tl=44,oo=24,ki=34,gm=6,bm=5;function io({testID:e}){let t=mn(),r=i(o=>jsxs(View,{style:t.actionRow,children:[jsxs(View,{style:t.actionLeft,children:[jsx(ve,{width:18,height:18,radius:9}),jsx(ve,{width:"55%",height:14,radius:7})]}),jsx(ve,{width:18,height:18,radius:9})]},o),"action");return jsxs(View,{style:t.dashboard,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:dt.loading,testID:e,children:[jsx(View,{style:t.inset,children:jsxs(View,{style:t.summaryCard,children:[jsx(ve,{width:Si,height:Si,radius:Si/2}),jsxs(View,{style:t.badges,children:[jsx(ve,{width:kl,height:no,radius:no/2}),jsx(ve,{width:kl,height:no,radius:no/2})]})]})}),jsx(ve,{width:150,height:16,radius:8,style:t.inset}),jsx(View,{style:t.carouselCard,children:jsx(ve,{width:"100%",height:fm,radius:14})}),jsxs(View,{style:t.dots,children:[jsx(ve,{width:6,height:6,radius:3}),jsx(ve,{width:18,height:6,radius:3}),jsx(ve,{width:6,height:6,radius:3})]}),jsx(ve,{width:46,height:12,radius:6,style:t.centered}),jsx(View,{style:t.inset,children:jsx(ve,{width:"100%",height:Tl,radius:12})}),jsxs(View,{style:[t.inset,t.actions],children:[r("a"),r("b")]})]})}i(io,"DashboardSkeleton");function _l({testID:e}){let t=mn();return jsxs(View,{style:t.request,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:ge.loading,testID:e,children:[jsx(View,{children:[0,1,2,3].map(r=>jsxs(View,{style:t.railRow,children:[jsxs(View,{style:t.railColumn,children:[jsx(ve,{width:oo,height:oo,radius:oo/2}),r<3?jsx(ve,{width:2,height:20,radius:1,style:t.connector}):null]}),jsxs(View,{style:t.railBody,children:[jsx(ve,{width:"55%",height:14,radius:7}),jsx(ve,{width:"75%",height:11,radius:6})]})]},r))}),jsxs(View,{style:t.statusCard,children:[jsx(ve,{width:"90%",height:13,radius:6}),jsx(ve,{width:"60%",height:13,radius:6})]}),jsx(ve,{width:"100%",height:50,radius:25})]})}i(_l,"RequestSkeleton");function Pl({testID:e}){let t=mn();return jsxs(View,{style:t.timeline,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:fe.loadingTimeline,testID:e,children:[jsx(View,{style:t.timelineDisclaimer,children:jsx(ve,{width:"100%",height:Tl,radius:12})}),Array.from({length:gm},(r,o)=>jsxs(View,{children:[o>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,children:[jsx(ve,{width:ki,height:ki,radius:ki/2}),jsxs(View,{style:t.timelineBody,children:[jsxs(View,{style:t.timelineTop,children:[jsx(ve,{width:44,height:10,radius:5}),jsx(ve,{width:56,height:12,radius:6})]}),jsx(ve,{width:"70%",height:14,radius:7}),o%2===0?jsx(ve,{width:"45%",height:12,radius:6}):null]})]})]},o))]})}i(Pl,"TimelineSkeleton");function Il({testID:e}){let t=mn();return jsx(View,{style:t.clinics,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:xe.loading,testID:e,children:Array.from({length:bm},(r,o)=>jsxs(View,{style:t.clinicRow,children:[jsx(ve,{width:"65%",height:14,radius:7}),jsx(ve,{width:"40%",height:11,radius:6})]},o))})}i(Il,"ClinicsSkeleton");function Dl({testID:e}){let t=mn();return jsx(View,{style:t.shares,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:de.loadingLinks,testID:e,children:[0,1].map(r=>jsxs(View,{style:t.shareRow,children:[jsx(ve,{width:"55%",height:13}),jsx(ve,{width:"40%",height:11})]},r))})}i(Dl,"SharesSkeleton");var Ti=62;function mn(){let e=L();return useMemo(()=>hm(e),[e])}i(mn,"useStyles");function hm(e){let{color:t,space:r,radius:o}=e,n=StyleSheet.hairlineWidth;return StyleSheet.create({dashboard:{flex:1,paddingHorizontal:r.sm,paddingTop:r.xs,gap:r.lg,backgroundColor:t.background},inset:{paddingHorizontal:r.sm},summaryCard:{alignItems:"center",borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg+r.xs,gap:r.md+r.xs/2},badges:{flexDirection:"row",gap:r.md},carouselCard:{borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg},dots:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.xs+r.xs/2},centered:{alignSelf:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},request:{paddingHorizontal:r.lg,paddingTop:r.xs,gap:r.lg+r.xs/2,backgroundColor:t.background},railRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md},railColumn:{alignItems:"center",width:oo},connector:{marginVertical:r.xs/2},railBody:{flex:1,paddingBottom:r.lg+r.xs/2,gap:r.xs+r.xs/2},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2,gap:r.sm},timeline:{flex:1,backgroundColor:t.background},timelineDisclaimer:{paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBody:{flex:1,gap:r.xs-1},timelineTop:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},timelineSeparator:{height:n,backgroundColor:t.brandBorder,marginLeft:Ti},clinics:{gap:r.md},clinicRow:{borderRadius:o.lg-r.xs/2,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2,gap:r.sm},shares:{gap:r.md,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:n,borderColor:t.brandBorder},shareRow:{gap:r.xs+r.xs/2}})}i(hm,"makeStyles");var Em=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function _i(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",style:e.style,...Be(e.onBack,Ze),children:t===null?jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsx(Sm,{...Fe(e,["onNavigate","onBack"])},JSON.stringify([t,r,e.petRef]))})}i(_i,"EverfurClinicPicker");function Sm({petRef:e,controller:t,recordsController:r,location:o,onNavigate:n,onBack:l,style:s}){let c=be(),a=Tm(),d=L(),u=Nt(),p=Hs(t??u,o),f=yt(r?{petRef:e,controller:r}:{petRef:e}),h=useRef(rr()),[R,v]=useState(false),[y,g]=useState(null),[b,w]=useState(false),[x,E]=useState(""),[D,k]=useState(false),[S,I]=useState(""),[Y,z]=useState(false),$=useCallback(A=>{n?.({name:"consent",clinic:pi(A,null,"",h.current())});},[n]),G=i(()=>{R||(v(true),g(null),f.createRequest(`records-upload-${Date.now().toString(36)}`).then(A=>{if(v(false),!A.ok){g(ge.errors.start);return}n?.({name:"request",requestId:A.value.id});}));},"startUpload"),Z=D?x:p.query,oe=Em.test(S.trim()),Ee=Z.trim().length>0&&oe,H=i(A=>{let{layoutMeasurement:M,contentOffset:K,contentSize:ye}=A.nativeEvent;M.height+K.y>=ye.height-M.height*.6&&p.loadMore();},"onEndReached"),C=p.isSearchActive?p.clinics:p.recent,T=p.isSearchActive?p.error?wt(p.error):!p.initialLoading&&p.clinics.length===0?"idle":null:p.recent.length>0||p.recentLoading?null:"idle";return jsxs(View,{style:[c.root,s],children:[jsx(et,{title:xe.title,onBack:l,testID:"records-clinic-header"}),jsxs(View,{style:a.searchBar,children:[jsx(View,{style:a.searchGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(qe,{value:p.query,onChangeText:p.setQuery,placeholder:xe.placeholder,placeholderTextColor:d.color.text.muted,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",maxLength:200,accessibilityLabel:xe.searchA11y,style:a.searchInput,testID:"records-clinic-search-input"}),p.query.length>0?jsx(Pressable,{onPress:()=>p.setQuery(""),accessibilityRole:"button",accessibilityLabel:xe.clearSearch,hitSlop:8,testID:"records-clinic-search-clear",children:jsx(m,{style:a.clearGlyph,children:"\xD7"})}):null]}),n?jsxs(View,{style:a.uploadWrap,children:[y?jsx(View,{style:c.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:c.errorText,children:y})}):null,jsx(re,{label:R?xe.uploadOwnStarting:xe.uploadOwn,kind:"outline",accessibilityLabel:xe.uploadOwnA11y,busy:R,onPress:G,testID:"records-clinic-upload-own"})]}):null,jsxs(ScrollView,{contentContainerStyle:a.list,keyboardShouldPersistTaps:"handled",onScroll:p.isSearchActive?H:void 0,scrollEventThrottle:200,testID:"records-clinic-results",children:[p.isSearchActive?jsxs(View,{style:a.fallbackCard,testID:"records-clinic-fallback-card",children:[jsxs(Pressable,{onPress:()=>w(A=>!A),accessibilityRole:"button",accessibilityLabel:b?xe.fallback.collapseA11y:xe.fallback.expandA11y,style:a.fallbackHeader,testID:"records-clinic-fallback",children:[jsxs(View,{style:a.fallbackCopy,children:[jsx(m,{style:a.fallbackTitle,numberOfLines:1,children:xe.fallback.title}),jsx(m,{style:a.fallbackSubtitle,numberOfLines:2,children:xe.fallback.subtitle})]}),jsx(Pr,{direction:b?"up":"down"})]}),b?jsxs(View,{style:a.fallbackForm,children:[jsx(m,{style:c.fieldLabel,children:xe.fallback.nameLabel}),jsx(qe,{accessibilityLabel:xe.fallback.nameLabel,style:c.field,value:Z,onChangeText:A=>{E(A),k(true);},placeholder:xe.fallback.namePlaceholder,placeholderTextColor:d.color.text.placeholder,autoCapitalize:"words",autoCorrect:false,maxLength:200,testID:"records-clinic-fallback-name"}),jsx(m,{style:c.fieldLabel,children:xe.fallback.emailLabel}),jsx(qe,{accessibilityLabel:xe.fallback.emailLabel,style:c.field,value:S,onChangeText:A=>{I(A),z(false);},onBlur:()=>z(true),placeholder:xe.fallback.emailPlaceholder,placeholderTextColor:d.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,testID:"records-clinic-fallback-email"}),Y&&S.trim().length>0&&!oe?jsx(m,{style:c.errorText,accessibilityRole:"alert",children:ge.errors.invalidEmail}):null,jsx(m,{style:c.muted,children:xe.fallback.reviewNote}),jsx(re,{label:xe.fallback.submit,accessibilityLabel:xe.fallback.submitA11y,disabled:!Ee||!n,onPress:()=>n?.({name:"consent",clinic:pi(null,Z.trim(),S.trim().toLowerCase(),h.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):p.recent.length>0?jsx(m,{style:a.sectionLabel,accessibilityRole:"header",testID:"records-clinic-recent-label",children:xe.recentlyUsed}):null,p.isSearchActive&&p.initialLoading?jsx(Il,{testID:"records-clinic-page-loading"}):null,C.map(A=>jsx(km,{clinic:A,onSelect:$,styles:a},A.id)),T&&!p.initialLoading?jsx(Qe,{variant:T,message:p.isSearchActive&&T==="idle"?xe.noMatch(p.debouncedQuery):p.error?.displayMessage,onAction:p.error?.retryable===true?p.retry:void 0,testID:"records-clinic-empty"}):null,jsxs(View,{style:a.footer,children:[p.loadingMore?jsxs(View,{style:a.footerLoading,testID:"records-clinic-loading-more",children:[jsx(ActivityIndicator,{color:d.color.brandInk,size:"small"}),jsx(m,{style:c.muted,children:xe.loadingMore})]}):null,p.pageError?jsx(Pressable,{onPress:p.loadMore,accessibilityRole:"button",accessibilityLabel:xe.loadMoreRetryA11y,style:a.footerRetry,testID:"records-clinic-page-error-retry",children:jsx(m,{style:a.footerRetryLabel,children:xe.loadMoreFailed})}):null]})]}),jsx(Me,{})]})}i(Sm,"PickerBody");function km({clinic:e,onSelect:t,styles:r}){let o=As(e.emailStatus),n=Os(e.distanceKm),l=[e.name,e.address,e.phone?`phone ${e.phone}`:null,n?Ls(e.distanceKm):null,o.a11y].filter(Boolean).join(", ");return jsxs(Pressable,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:xe.selectA11y(l),hitSlop:8,style:r.item,testID:`records-clinic-${e.id}`,children:[jsxs(View,{style:r.itemHeader,children:[jsx(m,{style:r.itemName,numberOfLines:1,children:e.name}),n?jsx(m,{style:r.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:n}):null]}),e.address?jsx(m,{style:r.itemAddress,numberOfLines:2,children:e.address}):null,e.phone?jsx(m,{style:r.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:e.phone}):null,jsx(View,{style:[r.badge,o.tone==="positive"?r.badgePositive:o.tone==="caution"?r.badgeCaution:r.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{style:[r.badgeLabel,o.tone==="positive"?r.badgePositiveText:o.tone==="caution"?r.badgeCautionText:r.badgeNeutralText],children:o.label})})]})}i(km,"ClinicRow");function Tm(){let e=L();return useMemo(()=>_m(e),[e])}i(Tm,"useLocalStyles");function _m(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=i((c,a,d,u="regular")=>({..._(e,u),fontSize:c,lineHeight:Math.round(c*a),color:d}),"text");return StyleSheet.create({searchBar:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.md+r.xs/2,height:r.xxl+r.md,marginHorizontal:r.lg,marginBottom:r.sm,borderRadius:o.lg+r.xs/2,backgroundColor:t.surfaceSubtle,borderWidth:l,borderColor:t.borderHairlineGreen},searchGlyph:{width:r.md,height:r.md,borderRadius:o.pill,borderWidth:2,borderColor:t.text.muted},searchInput:{flex:1,...s(n.size.body,n.lineHeight.snug,t.text.primary),paddingVertical:0},clearGlyph:s(n.size.heading,n.lineHeight.tight,t.text.muted),uploadWrap:{paddingHorizontal:r.lg,paddingBottom:r.md,gap:r.sm},list:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.md},sectionLabel:{...s(n.size.caption,n.lineHeight.normal,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:o.lg-r.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.md},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:r.md,minHeight:r.xxl+r.md},fallbackCopy:{flex:1,gap:r.xs/2},fallbackTitle:{...s(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},fallbackSubtitle:s(n.size.caption,n.lineHeight.normal,t.text.muted),fallbackForm:{gap:r.sm},item:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},itemName:{flex:1,...s(n.size.body,n.lineHeight.snug,t.brandInk,"bold")},itemDistance:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},itemAddress:s(n.size.caption,n.lineHeight.normal,t.text.primary),itemPhone:s(n.size.caption,n.lineHeight.normal,t.text.muted),badge:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+1,paddingVertical:r.xs},badgePositive:{backgroundColor:t.badgeBgPositive},badgeCaution:{backgroundColor:t.badgeBgCaution},badgeNeutral:{backgroundColor:t.badgeBgNeutral},badgeLabel:{...s(n.size.micro,n.lineHeight.snug,t.text.muted,"bold")},badgePositiveText:{color:t.success},badgeCautionText:{color:t.cautionAccent},badgeNeutralText:{color:t.text.muted},footer:{gap:r.sm,paddingTop:r.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.md},footerRetry:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...s(n.size.bodyTight,n.lineHeight.snug,t.brandInk,"bold")}})}i(_m,"makeLocalStyles");var Oe=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${Nr} clinics`,sendA11y:i(e=>e===1?"Send 1 records request":`Send ${e} records requests`,"sendA11y"),send:i(e=>`Send ${e} ${e===1?"request":"requests"}`,"send"),sending:"Sending\u2026",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:i(e=>`Remove ${e}`,"remove"),emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn\u2019t send any of these requests. See the details below and try again.",partial:i((e,t,r)=>`${e} of ${t} requests sent. ${r} couldn\u2019t be sent.`,"partial"),allSent:i(e=>`${e} ${e===1?"request":"requests"} sent.`,"allSent"),responded:i((e,t)=>`${e} of ${t} ${t===1?"clinic":"clinics"} responded`,"responded")});function yn(e,t,r,o){let n={owner_name:t,pet_name:r,clinic_name:o},l=false,s=e.scopeTemplate.replace(/\{([^{}]+)\}/g,(c,a)=>Object.prototype.hasOwnProperty.call(n,a)?n[a]??"":(l=true,""));return l||/[{}]/.test(s)?null:s}i(yn,"renderClinicScope");function fn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(fn,"clinicNeedsEmail");function Ol(e,t,r){let[o,n]=useState(e.ownerName),[l,s]=useState(""),[c,a]=useState(null),[d,u]=useState(""),[p,f]=useState([]),[h,R]=useState([]),[v,y]=useState(null),[g,b]=useState(null),[w,x]=useState(false),[E,D]=useState(false),[k,S]=useState(null),[I,Y]=useState(0),z=useRef(false),$=useRef(false),G=useRef(0),Z=useRef(rr()),oe=useRef(null),Ee=useRef(null),H=useRef(0);useEffect(()=>(z.current=true,$.current=false,x(false),()=>{z.current=false,H.current+=1,G.current+=1,oe.current=null,Ee.current?.abort();}),[t]),useEffect(()=>{let ie=true;return y(null),oe.current=null,t.getAuthorizationCopy().then(we=>{ie&&(we.ok?(y(we.value),b(null)):b(we.error));}).catch(()=>{ie&&b(q("internalError"));}),()=>{ie=false;}},[t,I]),useEffect(()=>{let ie=true;return R([]),t.recentClinics({limit:5}).then(we=>{ie&&we.ok&&R(we.value.clinics);}).catch(()=>{}),()=>{ie=false;}},[t]);let C=i(()=>{oe.current=null,b(null);},"invalidate"),T=c?.name??l.trim(),A=v?yn(v,o.trim(),e.petName,T):null,M=fn(c),K=!!(v&&A&&o.trim()&&e.petName.trim()&&T&&(!M||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.trim()))&&r),ye=i(async()=>{if($.current)return;let ie=++G.current;D(true);try{let we=await t.searchClinics({query:l.trim(),limit:100});if(!z.current||ie!==G.current)return;we.ok?(f(we.value.clinics),b(null)):b(we.error);}catch{z.current&&ie===G.current&&b(q("internalError"));}finally{z.current&&ie===G.current&&D(false);}},"search"),Ve=i(async()=>{if($.current||k||!K||!v||!A||!r)return;$.current=true;let ie=H.current,we=i(()=>z.current&&H.current===ie,"current");x(true),b(null);try{if(!oe.current){Ee.current=new AbortController;let Xe=await r({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:T,authorizationVersion:v.authorizationVersion,scopeText:A,signal:Ee.current.signal});if(!we()||Xe===null)return;let Vt=c&&(!M||c.emailStatus==="none")?{clinicId:c.id}:{clinicFreeText:T};oe.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:v.authorizationVersion,...Vt,...M?{clinicEmail:d.trim().toLowerCase()}:{},...Xe.signatureId!==void 0?{signatureId:Xe.signatureId}:{signaturePngBase64:Xe.signaturePngBase64},idempotencyKey:Z.current()};}if(!we())return;let vt=await t.createClinicRequest(oe.current);if(!we())return;if(!vt.ok){b(vt.error);return}if(vt.value.petRef!==e.petRef){b(q("internalError"));return}S(vt.value),oe.current=null,e.onCreated?.(vt.value);}catch{we()&&b(q("internalError"));}finally{$.current=false,we()&&x(false);}},"submit");return {ownerName:o,query:l,clinic:c,email:d,clinics:p,copy:v,scope:A,error:g,busy:w,searching:E,created:k,ready:K,needsEmail:M,recent:p.length===0&&c===null?h:[],setOwnerName(ie){$.current||(C(),n(ie));},setQuery(ie){$.current||(C(),G.current+=1,D(false),f([]),a(null),u(""),s(ie));},setEmail(ie){$.current||(C(),u(ie));},selectClinic(ie){$.current||(C(),G.current+=1,D(false),f([]),a(ie),s(ie.name),u(""));},invalidate:C,search:ye,submit:Ve,retryCopy(){b(null),Y(ie=>ie+1);}}}i(Ol,"useClinicRequestForm");var Pm=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function bn(e){return e.clinic?.name??e.freeText??""}i(bn,"draftName");function gn(e){return fn(e.clinic)}i(gn,"draftNeedsEmail");function Ll(e,t,r,o,n){let[l,s]=useState(e.ownerName),[c,a]=useState(""),[d,u]=useState([]),[p,f]=useState([]),[h,R]=useState([]),[v,y]=useState(null),[g,b]=useState(null),[w,x]=useState(false),[E,D]=useState(false),[k,S]=useState(null),[I,Y]=useState(null),[z,$]=useState(0),G=useRef(false),Z=useRef(false),oe=useRef(0),Ee=useRef(0),H=useRef(rr()),C=useRef(null),T=useRef(null);useEffect(()=>(G.current=true,Z.current=false,x(false),()=>{G.current=false,Ee.current+=1,oe.current+=1,C.current=null,T.current?.abort();}),[t,r]),useEffect(()=>{let F=true;return y(null),C.current=null,t.getAuthorizationCopy().then(Re=>{F&&(Re.ok?(y(Re.value),b(null)):b(Re.error));}).catch(()=>{F&&b(q("internalError"));}),()=>{F=false;}},[t,z]),useEffect(()=>{let F=true;return f([]),t.recentClinics({limit:5}).then(Re=>{F&&Re.ok&&f(Re.value.clinics);}).catch(()=>{}),()=>{F=false;}},[t]);let A=i(()=>{C.current=null,b(null);},"invalidate"),M=h.map(bn),K=v?M.map(F=>yn(v,l.trim(),e.petName,F)):[],ye=K.every(F=>F!==null)?K.join(`
|
|
6
2
|
|
|
7
|
-
// src/rn/records/useRecords.ts
|
|
8
|
-
|
|
9
|
-
Object.freeze({ wireCode: "AccessDeniedException", envelope: "http_envelope", httpStatus: 403, retryable: false }),
|
|
10
|
-
Object.freeze({ wireCode: "AuthorizationException", envelope: "http_envelope", httpStatus: 401, retryable: false }),
|
|
11
|
-
Object.freeze({ wireCode: "ConflictException", envelope: "http_envelope", httpStatus: 409, retryable: true }),
|
|
12
|
-
Object.freeze({ wireCode: "DAILY_QUOTA_EXCEEDED", envelope: "http_envelope", httpStatus: 429, retryable: true }),
|
|
13
|
-
Object.freeze({ wireCode: "IDEMPOTENCY_KEY_IN_FLIGHT", envelope: "http_envelope", httpStatus: 409, retryable: true }),
|
|
14
|
-
Object.freeze({ wireCode: "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST", envelope: "http_envelope", httpStatus: 409, retryable: false }),
|
|
15
|
-
Object.freeze({ wireCode: "InternalFailureException", envelope: "http_envelope", httpStatus: 500, retryable: true }),
|
|
16
|
-
Object.freeze({ wireCode: "NotImplementedException", envelope: "http_envelope", httpStatus: 501, retryable: false }),
|
|
17
|
-
Object.freeze({ wireCode: "PaymentRequiredException", envelope: "http_envelope", httpStatus: 402, retryable: false }),
|
|
18
|
-
Object.freeze({ wireCode: "ResourceNotFoundException", envelope: "http_envelope", httpStatus: 404, retryable: false }),
|
|
19
|
-
Object.freeze({ wireCode: "ServiceUnavailableException", envelope: "http_envelope", httpStatus: 503, retryable: true }),
|
|
20
|
-
Object.freeze({ wireCode: "TIER_UPGRADE_REQUIRED", envelope: "http_envelope", httpStatus: 402, retryable: false }),
|
|
21
|
-
Object.freeze({ wireCode: "ThrottlingException", envelope: "http_envelope", httpStatus: 429, retryable: true }),
|
|
22
|
-
Object.freeze({ wireCode: "ValidationException", envelope: "http_envelope", httpStatus: 400, retryable: false }),
|
|
23
|
-
Object.freeze({ wireCode: "accessDenied", envelope: "http_envelope", httpStatus: 403, retryable: false }),
|
|
24
|
-
Object.freeze({ wireCode: "authExpired", envelope: "http_envelope", httpStatus: 401, retryable: true }),
|
|
25
|
-
Object.freeze({ wireCode: "internal_error", envelope: "sse_frame", httpStatus: 200, retryable: false }),
|
|
26
|
-
Object.freeze({ wireCode: "invalidRequest", envelope: "http_envelope", httpStatus: 400, retryable: false }),
|
|
27
|
-
Object.freeze({ wireCode: "not_found", envelope: "sse_frame", httpStatus: 200, retryable: false }),
|
|
28
|
-
Object.freeze({ wireCode: "session_required", envelope: "http_envelope", httpStatus: 403, retryable: false }),
|
|
29
|
-
Object.freeze({ wireCode: "timeout", envelope: "sse_frame", httpStatus: 200, retryable: true }),
|
|
30
|
-
Object.freeze({ wireCode: "unavailable", envelope: "http_envelope", httpStatus: 503, retryable: true })
|
|
31
|
-
]);
|
|
32
|
-
Object.freeze(
|
|
33
|
-
CONTRACT_RETRYABILITY.map((row) => row.wireCode)
|
|
34
|
-
);
|
|
35
|
-
|
|
36
|
-
// src/client/errors/contract.ts
|
|
37
|
-
var NORMALIZED_FOLD = Object.freeze({
|
|
38
|
-
// the default status-mapped envelope
|
|
39
|
-
ValidationException: "validationFailed",
|
|
40
|
-
AuthorizationException: "authRejected",
|
|
41
|
-
PaymentRequiredException: "paymentRequired",
|
|
42
|
-
AccessDeniedException: "accessDenied",
|
|
43
|
-
ResourceNotFoundException: "resourceNotFound",
|
|
44
|
-
ConflictException: "conflict",
|
|
45
|
-
ThrottlingException: "rateLimited",
|
|
46
|
-
InternalFailureException: "internalError",
|
|
47
|
-
NotImplementedException: "notImplemented",
|
|
48
|
-
ServiceUnavailableException: "serviceUnavailable",
|
|
49
|
-
// dict-detail codes on the widget surface
|
|
50
|
-
authExpired: "authExpired",
|
|
51
|
-
unavailable: "serviceUnavailable",
|
|
52
|
-
session_required: "sessionRequired",
|
|
53
|
-
accessDenied: "accessDenied",
|
|
54
|
-
invalidRequest: "sdkUpdateRequired",
|
|
55
|
-
// typed codes
|
|
56
|
-
IDEMPOTENCY_KEY_IN_FLIGHT: "idempotencyInFlight",
|
|
57
|
-
IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST: "idempotencyConflict",
|
|
58
|
-
DAILY_QUOTA_EXCEEDED: "quotaExceeded",
|
|
59
|
-
TIER_UPGRADE_REQUIRED: "paymentRequired",
|
|
60
|
-
// SSE error frames
|
|
61
|
-
not_found: "conversationNotFound",
|
|
62
|
-
timeout: "streamTimeout",
|
|
63
|
-
internal_error: "internalError"
|
|
64
|
-
});
|
|
65
|
-
var CONTRACT_ERROR_ROWS = Object.freeze(
|
|
66
|
-
CONTRACT_RETRYABILITY.map(
|
|
67
|
-
(generated) => Object.freeze({
|
|
68
|
-
wireCode: generated.wireCode,
|
|
69
|
-
envelope: generated.envelope,
|
|
70
|
-
retryable: generated.retryable,
|
|
71
|
-
normalized: NORMALIZED_FOLD[generated.wireCode]
|
|
72
|
-
})
|
|
73
|
-
)
|
|
74
|
-
);
|
|
75
|
-
var BY_UPPER = new Map(
|
|
76
|
-
CONTRACT_ERROR_ROWS.map((r) => [r.wireCode.toUpperCase(), r])
|
|
77
|
-
);
|
|
78
|
-
function contractErrorFor(wireCode) {
|
|
79
|
-
if (typeof wireCode !== "string") return void 0;
|
|
80
|
-
const key = wireCode.trim().toUpperCase();
|
|
81
|
-
return key.length > 0 ? BY_UPPER.get(key) : void 0;
|
|
82
|
-
}
|
|
83
|
-
var CATEGORY_OF = Object.freeze({
|
|
84
|
-
// the caller's sign-in state is wrong and a credential change is the remedy
|
|
85
|
-
authExpired: "authentication",
|
|
86
|
-
authRejected: "authentication",
|
|
87
|
-
sessionRequired: "authentication",
|
|
88
|
-
// signed in, correctly identified, and still not allowed
|
|
89
|
-
accessDenied: "authorization",
|
|
90
|
-
// a plan gate, not a permission failure: the remedy is commercial
|
|
91
|
-
paymentRequired: "entitlement",
|
|
92
|
-
// slow down / come back later
|
|
93
|
-
quotaExceeded: "rateLimit",
|
|
94
|
-
rateLimited: "rateLimit",
|
|
95
|
-
// the request itself was wrong; retrying it unchanged can never succeed
|
|
96
|
-
validationFailed: "invalidRequest",
|
|
97
|
-
sdkUpdateRequired: "invalidRequest",
|
|
98
|
-
// the target is gone, hidden, or was never visible to this caller
|
|
99
|
-
conversationNotFound: "notFound",
|
|
100
|
-
petNotFound: "notFound",
|
|
101
|
-
resourceNotFound: "notFound",
|
|
102
|
-
// something else already holds the thing
|
|
103
|
-
conflict: "conflict",
|
|
104
|
-
idempotencyConflict: "conflict",
|
|
105
|
-
idempotencyInFlight: "conflict",
|
|
106
|
-
// the pipe, not the request: timeouts, drops, a briefly unreachable dependency
|
|
107
|
-
streamTimeout: "connection",
|
|
108
|
-
streamIncomplete: "connection",
|
|
109
|
-
upstreamLlmTimeout: "connection",
|
|
110
|
-
serviceUnavailable: "connection",
|
|
111
|
-
// the server admits fault
|
|
112
|
-
internalError: "server",
|
|
113
|
-
notImplemented: "server",
|
|
114
|
-
mediaUploadFailed: "media",
|
|
115
|
-
moderationBlocked: "policy",
|
|
116
|
-
unknown: "unknown"
|
|
117
|
-
});
|
|
118
|
-
function categoryFor(code) {
|
|
119
|
-
return CATEGORY_OF[code];
|
|
120
|
-
}
|
|
121
|
-
function fromWire(wire) {
|
|
122
|
-
const contractRow = contractErrorFor(wire);
|
|
123
|
-
if (contractRow) return contractRow.normalized;
|
|
124
|
-
const upper = (wire ?? "").trim().toUpperCase();
|
|
125
|
-
const canonical = upper.replace(/[^A-Z0-9]/g, "");
|
|
126
|
-
if (canonical === "AUTHREJECTED") return "authRejected";
|
|
127
|
-
if (upper.startsWith("AUTH")) return "authExpired";
|
|
128
|
-
switch (canonical) {
|
|
129
|
-
case "DAILYQUOTAEXCEEDED":
|
|
130
|
-
case "QUOTAEXCEEDED":
|
|
131
|
-
return "quotaExceeded";
|
|
132
|
-
case "RATELIMITED":
|
|
133
|
-
case "TOOMANYREQUESTS":
|
|
134
|
-
return "rateLimited";
|
|
135
|
-
case "IDEMPOTENCYKEYCONFLICT":
|
|
136
|
-
case "IDEMPOTENCYCONFLICT":
|
|
137
|
-
return "idempotencyConflict";
|
|
138
|
-
case "ACCESSDENIED":
|
|
139
|
-
case "FORBIDDEN":
|
|
140
|
-
return "accessDenied";
|
|
141
|
-
case "NOTFOUND":
|
|
142
|
-
case "CONVERSATIONNOTFOUND":
|
|
143
|
-
return "conversationNotFound";
|
|
144
|
-
case "PETNOTFOUND":
|
|
145
|
-
return "petNotFound";
|
|
146
|
-
case "TIMEOUT":
|
|
147
|
-
case "STREAMTIMEOUT":
|
|
148
|
-
return "streamTimeout";
|
|
149
|
-
// Analysis-domain deterministic 400s (NON-retryable). Additive per SPEC-00 §3.1 / SPEC-11b §2.6:
|
|
150
|
-
// fold to a NON-retried target so the SDK never retries a permanently-failing bad-input request.
|
|
151
|
-
// (Comment above the group so the empty fall-through cases stay lint-clean under no-fallthrough.)
|
|
152
|
-
case "MEDIAUPLOADFAILED":
|
|
153
|
-
case "UNRECOGNIZEDVIDEOFORMAT":
|
|
154
|
-
case "FILETOOSMALL":
|
|
155
|
-
return "mediaUploadFailed";
|
|
156
|
-
case "MODERATIONBLOCKED":
|
|
157
|
-
return "moderationBlocked";
|
|
158
|
-
case "UPSTREAMLLMTIMEOUT":
|
|
159
|
-
return "upstreamLlmTimeout";
|
|
160
|
-
case "INTERNALERROR":
|
|
161
|
-
case "INTERNALSERVERERROR":
|
|
162
|
-
return "internalError";
|
|
163
|
-
case "STREAMINCOMPLETE":
|
|
164
|
-
case "CHATSTREAMINCOMPLETE":
|
|
165
|
-
return "streamIncomplete";
|
|
166
|
-
// Deterministic 400s that can only come from an SDK bug -> unknown (NON-retryable). NEVER internalError
|
|
167
|
-
// (which IS auto-retried): mapping a bad-input 400 to a retryable code retries a request that never succeeds.
|
|
168
|
-
case "INVALIDANALYSISTYPE":
|
|
169
|
-
case "INVALIDUPLOADPURPOSE":
|
|
170
|
-
return "unknown";
|
|
171
|
-
default:
|
|
172
|
-
return "unknown";
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
var AUTO_RETRYABLE_CODES = /* @__PURE__ */ new Set([
|
|
176
|
-
"streamTimeout",
|
|
177
|
-
"rateLimited",
|
|
178
|
-
"internalError",
|
|
179
|
-
"upstreamLlmTimeout",
|
|
180
|
-
"streamIncomplete"
|
|
181
|
-
]);
|
|
182
|
-
function isAutoRetryable(code) {
|
|
183
|
-
return AUTO_RETRYABLE_CODES.has(code);
|
|
184
|
-
}
|
|
185
|
-
var RETRYABLE_CONTRACT_CODES = /* @__PURE__ */ new Set([
|
|
186
|
-
"serviceUnavailable",
|
|
187
|
-
"conflict",
|
|
188
|
-
"idempotencyInFlight"
|
|
189
|
-
]);
|
|
190
|
-
function isRetryableCode(code) {
|
|
191
|
-
return isAutoRetryable(code) || RETRYABLE_CONTRACT_CODES.has(code);
|
|
192
|
-
}
|
|
193
|
-
var BACKOFF_BASE_MS = 500;
|
|
194
|
-
var BACKOFF_CAP_MS = 8e3;
|
|
195
|
-
var MAX_RETRY_ATTEMPTS = 4;
|
|
196
|
-
function backoffDelayMs(attempt, rng = Math.random) {
|
|
197
|
-
const bounded = Math.max(0, attempt);
|
|
198
|
-
const ceiling = Math.min(BACKOFF_BASE_MS * 2 ** bounded, BACKOFF_CAP_MS);
|
|
199
|
-
return Math.floor(rng() * ceiling);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// src/client/errors/EverfurError.ts
|
|
203
|
-
var USER_FACING_COPY = Object.freeze({
|
|
204
|
-
authExpired: "Please sign in again to continue.",
|
|
205
|
-
authRejected: "Please sign in again to continue.",
|
|
206
|
-
sessionRequired: "This app needs to be updated to keep using Everfur.",
|
|
207
|
-
accessDenied: "This feature isn't available on your account right now.",
|
|
208
|
-
paymentRequired: "This is part of a paid plan.",
|
|
209
|
-
quotaExceeded: "You have used today's messages. This resets tomorrow.",
|
|
210
|
-
rateLimited: "You are sending messages quickly. Try again in a few seconds.",
|
|
211
|
-
validationFailed: "Something in that request was not right. Check the details and try again.",
|
|
212
|
-
sdkUpdateRequired: "This app needs to be updated to keep using Everfur.",
|
|
213
|
-
conflict: "That is already running. Wait for it to finish, then try again.",
|
|
214
|
-
idempotencyConflict: "That message was already delivered.",
|
|
215
|
-
idempotencyInFlight: "That is still processing. Give it a moment.",
|
|
216
|
-
conversationNotFound: "This conversation is no longer available.",
|
|
217
|
-
petNotFound: "We could not find that pet. Please pick a pet and try again.",
|
|
218
|
-
resourceNotFound: "We could not find that.",
|
|
219
|
-
streamTimeout: "The response timed out. Tap retry to try again.",
|
|
220
|
-
mediaUploadFailed: "We could not upload that photo. Please attach it again.",
|
|
221
|
-
moderationBlocked: "This request cannot be answered here.",
|
|
222
|
-
upstreamLlmTimeout: "The response timed out. Tap retry to try again.",
|
|
223
|
-
internalError: "We hit a snag on our end. Please try again.",
|
|
224
|
-
notImplemented: "That is not available yet.",
|
|
225
|
-
serviceUnavailable: "That service is briefly unavailable. Try again shortly.",
|
|
226
|
-
streamIncomplete: "The connection dropped mid-answer. Tap retry to continue.",
|
|
227
|
-
unknown: "Something went wrong. Please try again."
|
|
228
|
-
});
|
|
229
|
-
function userFacingError(code) {
|
|
230
|
-
return USER_FACING_COPY[code];
|
|
231
|
-
}
|
|
232
|
-
function defineHidden(target, key, value) {
|
|
233
|
-
Object.defineProperty(target, key, {
|
|
234
|
-
value,
|
|
235
|
-
enumerable: false,
|
|
236
|
-
writable: false,
|
|
237
|
-
configurable: false
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
function makeEverfurError(code, opts) {
|
|
241
|
-
contractErrorFor(opts?.wireCode);
|
|
242
|
-
const error = {
|
|
243
|
-
code,
|
|
244
|
-
category: categoryFor(code),
|
|
245
|
-
retryable: opts?.retryable ?? isRetryableCode(code),
|
|
246
|
-
displayMessage: userFacingError(code)
|
|
247
|
-
};
|
|
248
|
-
if (opts?.httpStatus !== void 0) error.httpStatus = opts.httpStatus;
|
|
249
|
-
if (opts?.requestId) error.requestId = opts.requestId;
|
|
250
|
-
if (opts?.wireMessage) defineHidden(error, "wireMessage", opts.wireMessage);
|
|
251
|
-
if (opts?.raw !== void 0 && opts.raw !== null) defineHidden(error, "raw", opts.raw);
|
|
252
|
-
return Object.freeze(error);
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
// src/client/errors/EverfurResult.ts
|
|
256
|
-
function ok(value, warning) {
|
|
257
|
-
return Object.freeze(
|
|
258
|
-
{ ok: true, value }
|
|
259
|
-
);
|
|
260
|
-
}
|
|
261
|
-
function err(error) {
|
|
262
|
-
return Object.freeze({ ok: false, error });
|
|
263
|
-
}
|
|
264
|
-
var EverfurConfigError = class _EverfurConfigError extends Error {
|
|
265
|
-
constructor(kind, message) {
|
|
266
|
-
super(message);
|
|
267
|
-
this.name = "EverfurConfigError";
|
|
268
|
-
this.kind = kind;
|
|
269
|
-
Object.setPrototypeOf(this, _EverfurConfigError.prototype);
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
function brandPetRef(raw) {
|
|
273
|
-
return raw;
|
|
274
|
-
}
|
|
275
|
-
function brandRequestId(raw) {
|
|
276
|
-
return raw;
|
|
277
|
-
}
|
|
278
|
-
function brandDocumentId(raw) {
|
|
279
|
-
return raw;
|
|
280
|
-
}
|
|
281
|
-
var KNOWN_STATUSES = /* @__PURE__ */ new Set([
|
|
282
|
-
"awaiting_upload",
|
|
283
|
-
"received",
|
|
284
|
-
"parsing",
|
|
285
|
-
"in_review",
|
|
286
|
-
"published",
|
|
287
|
-
"failed",
|
|
288
|
-
"revoked"
|
|
289
|
-
]);
|
|
290
|
-
var STATUS_ALIASES = Object.freeze({
|
|
291
|
-
records_received: "received",
|
|
292
|
-
// the server's spelling; `received` is never sent verbatim
|
|
293
|
-
parsing_failed: "failed",
|
|
294
|
-
// TERMINAL. Folding to `parsing` polled forever on a dead request.
|
|
295
|
-
clinic_declined: "failed"
|
|
296
|
-
// TERMINAL. The clinic refused; nothing further will arrive.
|
|
297
|
-
});
|
|
298
|
-
function normalizeStatus(raw) {
|
|
299
|
-
const aliased = Object.prototype.hasOwnProperty.call(STATUS_ALIASES, raw) ? STATUS_ALIASES[raw] : void 0;
|
|
300
|
-
if (aliased !== void 0) return aliased;
|
|
301
|
-
const value = raw;
|
|
302
|
-
return KNOWN_STATUSES.has(value) ? value : "parsing";
|
|
303
|
-
}
|
|
304
|
-
function normalizeOrigin(raw) {
|
|
305
|
-
return raw === "owner_reported" || raw === "clinic_document" ? raw : null;
|
|
306
|
-
}
|
|
307
|
-
var requestSchema = z.object({
|
|
308
|
-
request_id: z.string().min(1),
|
|
309
|
-
pet_ref: z.string().min(1),
|
|
310
|
-
status: z.string(),
|
|
311
|
-
status_label: z.string().optional(),
|
|
312
|
-
document_count: z.number().optional(),
|
|
313
|
-
held_item_count: z.number().optional(),
|
|
314
|
-
received_at: z.string().nullish(),
|
|
315
|
-
parsing_started_at: z.string().nullish(),
|
|
316
|
-
review_started_at: z.string().nullish(),
|
|
317
|
-
created_at: z.string().optional(),
|
|
318
|
-
updated_at: z.string().optional()
|
|
319
|
-
}).passthrough();
|
|
320
|
-
function mapRequestView(wire) {
|
|
321
|
-
const parsed = requestSchema.safeParse(wire);
|
|
322
|
-
if (!parsed.success) return null;
|
|
323
|
-
const w = parsed.data;
|
|
324
|
-
return Object.freeze({
|
|
325
|
-
id: brandRequestId(w.request_id),
|
|
326
|
-
petRef: brandPetRef(w.pet_ref),
|
|
327
|
-
status: normalizeStatus(w.status),
|
|
328
|
-
statusLabel: w.status_label ?? "",
|
|
329
|
-
documentCount: numberOr(w.document_count, 0),
|
|
330
|
-
heldItemCount: numberOr(w.held_item_count, 0),
|
|
331
|
-
receivedAt: w.received_at ?? null,
|
|
332
|
-
parsingStartedAt: w.parsing_started_at ?? null,
|
|
333
|
-
reviewStartedAt: w.review_started_at ?? null,
|
|
334
|
-
createdAt: w.created_at ?? "",
|
|
335
|
-
updatedAt: w.updated_at ?? ""
|
|
336
|
-
});
|
|
337
|
-
}
|
|
338
|
-
function mapRequestList(wire) {
|
|
339
|
-
const list = Array.isArray(wire) ? wire : [];
|
|
340
|
-
const out = [];
|
|
341
|
-
for (const entry of list) {
|
|
342
|
-
const view = mapRequestView(entry);
|
|
343
|
-
if (view !== null) out.push(view);
|
|
344
|
-
}
|
|
345
|
-
return Object.freeze(out);
|
|
346
|
-
}
|
|
347
|
-
var acceptedSchema = z.object({
|
|
348
|
-
source_doc_id: z.string().min(1),
|
|
349
|
-
request_id: z.string().min(1)
|
|
350
|
-
});
|
|
351
|
-
function mapUploadedDocument(wire) {
|
|
352
|
-
const parsed = acceptedSchema.safeParse(wire);
|
|
353
|
-
if (!parsed.success) return null;
|
|
354
|
-
return Object.freeze({
|
|
355
|
-
documentId: brandDocumentId(parsed.data.source_doc_id),
|
|
356
|
-
requestId: brandRequestId(parsed.data.request_id),
|
|
357
|
-
status: "received"
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
var identitySchema = z.object({ label: z.string(), value: z.string() });
|
|
361
|
-
var entitySchema = z.object({
|
|
362
|
-
key: z.string(),
|
|
363
|
-
category: z.string().optional(),
|
|
364
|
-
label: z.string().optional(),
|
|
365
|
-
value: z.string().nullish(),
|
|
366
|
-
unit: z.string().nullish(),
|
|
367
|
-
observed_at: z.string().nullish(),
|
|
368
|
-
status: z.string().nullish(),
|
|
369
|
-
origin: z.string().nullish()
|
|
370
|
-
});
|
|
371
|
-
var seriesPointSchema = z.object({
|
|
372
|
-
at: z.string(),
|
|
373
|
-
value: z.number().nullish(),
|
|
374
|
-
display: z.string().nullish(),
|
|
375
|
-
origin: z.string().nullish()
|
|
376
|
-
});
|
|
377
|
-
var seriesSchema = z.object({
|
|
378
|
-
key: z.string(),
|
|
379
|
-
label: z.string().optional(),
|
|
380
|
-
points: z.array(seriesPointSchema).optional()
|
|
381
|
-
});
|
|
382
|
-
var forwardSchema = z.object({
|
|
383
|
-
title: z.string(),
|
|
384
|
-
detail: z.string().nullish(),
|
|
385
|
-
due_at: z.string().nullish()
|
|
386
|
-
});
|
|
387
|
-
var documentSchema = z.object({
|
|
388
|
-
doc_id: z.string(),
|
|
389
|
-
title: z.string().nullish(),
|
|
390
|
-
page_count: z.number().nullish(),
|
|
391
|
-
received_at: z.string().nullish()
|
|
392
|
-
});
|
|
393
|
-
var contentSchema = z.object({
|
|
394
|
-
identity: z.array(identitySchema).optional(),
|
|
395
|
-
entities: z.array(entitySchema).optional(),
|
|
396
|
-
entity_series: z.array(seriesSchema).optional(),
|
|
397
|
-
forward_looking: z.array(forwardSchema).optional(),
|
|
398
|
-
documents: z.array(documentSchema).optional()
|
|
399
|
-
});
|
|
400
|
-
function mapRecordView(petRef, wire) {
|
|
401
|
-
const w = isObject(wire) ? wire : {};
|
|
402
|
-
const schemaVersion = strOr(w["schema_version"], "epdf/1.0");
|
|
403
|
-
const disclaimer = strOr(w["disclaimer"], "");
|
|
404
|
-
const pet = brandPetRef(typeof w["pet_ref"] === "string" && w["pet_ref"].length > 0 ? w["pet_ref"] : petRef);
|
|
405
|
-
if (w["withheld"] === true) {
|
|
406
|
-
return withheldView(pet, schemaVersion, disclaimer);
|
|
407
|
-
}
|
|
408
|
-
const content = contentSchema.safeParse(w);
|
|
409
|
-
if (!content.success) {
|
|
410
|
-
return withheldView(pet, schemaVersion, disclaimer);
|
|
411
|
-
}
|
|
412
|
-
const c = content.data;
|
|
413
|
-
const identity = (c.identity ?? []).map(
|
|
414
|
-
(i) => Object.freeze({ label: i.label, value: i.value })
|
|
415
|
-
);
|
|
416
|
-
const entities = (c.entities ?? []).map(
|
|
417
|
-
(e) => Object.freeze({
|
|
418
|
-
key: e.key,
|
|
419
|
-
category: e.category ?? "",
|
|
420
|
-
label: e.label ?? e.key,
|
|
421
|
-
value: e.value ?? null,
|
|
422
|
-
unit: e.unit ?? null,
|
|
423
|
-
observedAt: e.observed_at ?? null,
|
|
424
|
-
status: e.status ?? null,
|
|
425
|
-
origin: normalizeOrigin(e.origin)
|
|
426
|
-
})
|
|
427
|
-
);
|
|
428
|
-
const entitySeries = (c.entity_series ?? []).map(
|
|
429
|
-
(s) => Object.freeze({
|
|
430
|
-
key: s.key,
|
|
431
|
-
label: s.label ?? s.key,
|
|
432
|
-
points: Object.freeze(
|
|
433
|
-
(s.points ?? []).map(
|
|
434
|
-
(p) => Object.freeze({
|
|
435
|
-
at: p.at,
|
|
436
|
-
value: p.value ?? null,
|
|
437
|
-
display: p.display ?? null,
|
|
438
|
-
origin: normalizeOrigin(p.origin)
|
|
439
|
-
})
|
|
440
|
-
)
|
|
441
|
-
)
|
|
442
|
-
})
|
|
443
|
-
);
|
|
444
|
-
const forwardLooking = (c.forward_looking ?? []).map(
|
|
445
|
-
(f) => Object.freeze({ title: f.title, detail: f.detail ?? null, dueAt: f.due_at ?? null })
|
|
446
|
-
);
|
|
447
|
-
const documents = {};
|
|
448
|
-
for (const d of c.documents ?? []) {
|
|
449
|
-
documents[d.doc_id] = Object.freeze({
|
|
450
|
-
docId: d.doc_id,
|
|
451
|
-
title: d.title ?? null,
|
|
452
|
-
pageCount: d.page_count ?? null,
|
|
453
|
-
receivedAt: d.received_at ?? null
|
|
454
|
-
});
|
|
455
|
-
}
|
|
456
|
-
const isEmpty = w["is_empty"] === true || identity.length === 0 && entities.length === 0 && entitySeries.length === 0 && forwardLooking.length === 0 && Object.keys(documents).length === 0;
|
|
457
|
-
return Object.freeze({
|
|
458
|
-
petRef: pet,
|
|
459
|
-
schemaVersion,
|
|
460
|
-
isEmpty,
|
|
461
|
-
withheld: false,
|
|
462
|
-
generatedAt: strOrNull(w["generated_at"]),
|
|
463
|
-
identity: Object.freeze(identity),
|
|
464
|
-
entities: Object.freeze(entities),
|
|
465
|
-
entitySeries: Object.freeze(entitySeries),
|
|
466
|
-
forwardLooking: Object.freeze(forwardLooking),
|
|
467
|
-
documents: Object.freeze(documents),
|
|
468
|
-
disclaimer
|
|
469
|
-
});
|
|
470
|
-
}
|
|
471
|
-
function withheldView(petRef, schemaVersion, disclaimer) {
|
|
472
|
-
return Object.freeze({
|
|
473
|
-
petRef,
|
|
474
|
-
schemaVersion,
|
|
475
|
-
isEmpty: false,
|
|
476
|
-
withheld: true,
|
|
477
|
-
generatedAt: null,
|
|
478
|
-
identity: Object.freeze([]),
|
|
479
|
-
entities: Object.freeze([]),
|
|
480
|
-
entitySeries: Object.freeze([]),
|
|
481
|
-
forwardLooking: Object.freeze([]),
|
|
482
|
-
documents: Object.freeze({}),
|
|
483
|
-
disclaimer
|
|
484
|
-
});
|
|
485
|
-
}
|
|
486
|
-
var consentSchema = z.object({
|
|
487
|
-
pet_ref: z.string().optional(),
|
|
488
|
-
granted: z.boolean().optional(),
|
|
489
|
-
version: z.string().nullish(),
|
|
490
|
-
granted_at: z.string().nullish()
|
|
491
|
-
});
|
|
492
|
-
function mapConsent(petRef, wire) {
|
|
493
|
-
const parsed = consentSchema.safeParse(wire);
|
|
494
|
-
const data = parsed.success ? parsed.data : {};
|
|
495
|
-
return Object.freeze({
|
|
496
|
-
petRef: brandPetRef(typeof data.pet_ref === "string" && data.pet_ref.length > 0 ? data.pet_ref : petRef),
|
|
497
|
-
granted: data.granted === true,
|
|
498
|
-
version: data.version ?? null,
|
|
499
|
-
grantedAt: data.granted_at ?? null
|
|
500
|
-
});
|
|
501
|
-
}
|
|
502
|
-
function isObject(v) {
|
|
503
|
-
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
504
|
-
}
|
|
505
|
-
function numberOr(v, fallback) {
|
|
506
|
-
return typeof v === "number" && Number.isFinite(v) ? v : fallback;
|
|
507
|
-
}
|
|
508
|
-
function strOr(v, fallback) {
|
|
509
|
-
return typeof v === "string" && v.length > 0 ? v : fallback;
|
|
510
|
-
}
|
|
511
|
-
function strOrNull(v) {
|
|
512
|
-
return typeof v === "string" && v.length > 0 ? v : null;
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
// src/core/records/models.ts
|
|
516
|
-
var RECORDS_TERMINAL = Object.freeze([
|
|
517
|
-
"published",
|
|
518
|
-
"failed",
|
|
519
|
-
"revoked"
|
|
520
|
-
]);
|
|
521
|
-
function isTerminalStatus(status) {
|
|
522
|
-
return RECORDS_TERMINAL.includes(status);
|
|
523
|
-
}
|
|
524
|
-
function recordsDenialReasonOf(error) {
|
|
525
|
-
if (error === null) return null;
|
|
526
|
-
const reason = error.recordsReason;
|
|
527
|
-
return reason === "consent_required" || reason === "session_required" || reason === "entitlement" ? reason : null;
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
// src/core/records/ports.ts
|
|
531
|
-
var noopRecordsTelemetry = Object.freeze({
|
|
532
|
-
record() {
|
|
533
|
-
}
|
|
534
|
-
});
|
|
535
|
-
var MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
|
|
536
|
-
var CONSENT_VERSION_MAX = 64;
|
|
537
|
-
var IDEMPOTENCY_KEY_MAX = 128;
|
|
538
|
-
var PET_REF_MAX = 128;
|
|
539
|
-
var RECORDS_UPLOAD_CONTENT_TYPE = "application/pdf";
|
|
540
|
-
var UPLOAD_DEADLINE_MS = 9e4;
|
|
541
|
-
|
|
542
|
-
// src/core/records/RecordsController.ts
|
|
543
|
-
function createRecordsController(deps) {
|
|
544
|
-
return new RecordsControllerImpl(deps);
|
|
545
|
-
}
|
|
546
|
-
var RecordsControllerImpl = class {
|
|
547
|
-
constructor(deps) {
|
|
548
|
-
/** In-memory record cache (per pet). NEVER persisted to disk. Cleared on revoke. */
|
|
549
|
-
this.recordCache = /* @__PURE__ */ new Map();
|
|
550
|
-
/** Parse-gap dedup: a request's gap metric fires at most once per id. */
|
|
551
|
-
this.reportedGaps = /* @__PURE__ */ new Set();
|
|
552
|
-
this.repository = deps.repository;
|
|
553
|
-
this.uploads = deps.uploads;
|
|
554
|
-
this.telemetry = deps.telemetry ?? noopRecordsTelemetry;
|
|
555
|
-
this.newIdempotencyKey = deps.newIdempotencyKey ?? defaultIdempotencyFactory();
|
|
556
|
-
this.timers = deps.timers ?? defaultTimers;
|
|
557
|
-
this.uploadDeadlineMs = deps.uploadDeadlineMs ?? UPLOAD_DEADLINE_MS;
|
|
558
|
-
}
|
|
559
|
-
// ---- request lifecycle ------------------------------------------------
|
|
560
|
-
async createUploadRequest(input) {
|
|
561
|
-
const res = await this.repository.createRequest({
|
|
562
|
-
pet_ref: input.petRef,
|
|
563
|
-
idempotency_key: input.idempotencyKey
|
|
564
|
-
});
|
|
565
|
-
if (!res.ok) return this.onRequestError(res.error);
|
|
566
|
-
const view = mapRequestView(res.value);
|
|
567
|
-
if (view === null) return err(internal());
|
|
568
|
-
this.observeRequest(view);
|
|
569
|
-
return ok(view);
|
|
570
|
-
}
|
|
571
|
-
async getRequest(id) {
|
|
572
|
-
const res = await this.repository.getRequest(id);
|
|
573
|
-
if (!res.ok) return this.onRequestError(res.error);
|
|
574
|
-
const view = mapRequestView(res.value);
|
|
575
|
-
if (view === null) return err(internal());
|
|
576
|
-
this.observeRequest(view);
|
|
577
|
-
return ok(view);
|
|
578
|
-
}
|
|
579
|
-
async listRequests() {
|
|
580
|
-
const res = await this.repository.listRequests();
|
|
581
|
-
if (!res.ok) return this.onRequestError(res.error);
|
|
582
|
-
const views = mapRequestList(res.value);
|
|
583
|
-
for (const view of views) this.observeRequest(view);
|
|
584
|
-
return ok(views);
|
|
585
|
-
}
|
|
586
|
-
// ---- two-phase upload (§3.2) ------------------------------------------
|
|
587
|
-
async uploadDocument(input) {
|
|
588
|
-
const { requestId, file } = input;
|
|
589
|
-
const rejection = validateFile(file);
|
|
590
|
-
if (rejection !== null) {
|
|
591
|
-
this.telemetry.record("records.upload.rejected", { reason: rejection });
|
|
592
|
-
return err(uploadFailed(`upload rejected: ${rejection}`));
|
|
593
|
-
}
|
|
594
|
-
const initiated = await this.repository.initiateUpload(requestId, {
|
|
595
|
-
content_type: RECORDS_UPLOAD_CONTENT_TYPE,
|
|
596
|
-
file_size: file.sizeBytes
|
|
597
|
-
});
|
|
598
|
-
if (!initiated.ok) {
|
|
599
|
-
return this.onRequestError(initiated.error);
|
|
600
|
-
}
|
|
601
|
-
const s3 = await this.postToS3(initiated.value, file, input);
|
|
602
|
-
if (!s3.ok) {
|
|
603
|
-
this.telemetry.record("records.upload.failed", { reason: s3.reason });
|
|
604
|
-
return err(uploadFailed(s3.reason));
|
|
605
|
-
}
|
|
606
|
-
const completed = await this.repository.completeUpload(requestId, {
|
|
607
|
-
upload_id: initiated.value.upload_id
|
|
608
|
-
});
|
|
609
|
-
if (!completed.ok) {
|
|
610
|
-
if (completed.error.code === "mediaUploadFailed") {
|
|
611
|
-
this.telemetry.record("records.upload.rejected", {
|
|
612
|
-
reason: reasonFromWire(completed.error) ?? "corrupt"
|
|
613
|
-
});
|
|
614
|
-
}
|
|
615
|
-
return this.onRequestError(completed.error);
|
|
616
|
-
}
|
|
617
|
-
const doc = mapUploadedDocument(completed.value);
|
|
618
|
-
if (doc === null) return err(internal());
|
|
619
|
-
return ok(doc);
|
|
620
|
-
}
|
|
621
|
-
async postToS3(policy, file, input) {
|
|
622
|
-
const deadline = new AbortController();
|
|
623
|
-
const signal = mergeSignals(deadline.signal, input.signal);
|
|
624
|
-
const handle = this.timers.setTimeout(() => deadline.abort(), this.uploadDeadlineMs);
|
|
625
|
-
try {
|
|
626
|
-
const opts = { signal };
|
|
627
|
-
if (input.onProgress) opts.onProgress = input.onProgress;
|
|
628
|
-
await this.uploads.postMultipart(policy, file, opts);
|
|
629
|
-
return { ok: true };
|
|
630
|
-
} catch {
|
|
631
|
-
const reason = deadline.signal.aborted && input.signal?.aborted !== true ? "timeout" : "upload_error";
|
|
632
|
-
return { ok: false, reason };
|
|
633
|
-
} finally {
|
|
634
|
-
this.timers.clearTimeout(handle);
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
// ---- record read (consent-gated, redaction-fail-closed) ---------------
|
|
638
|
-
async getRecord(pet) {
|
|
639
|
-
const res = await this.repository.getRecord(pet);
|
|
640
|
-
if (!res.ok) {
|
|
641
|
-
const reason = recordsDenialReasonOf(res.error);
|
|
642
|
-
if (reason === "consent_required") {
|
|
643
|
-
this.telemetry.record("records.consent.denied", { pet_ref: pet });
|
|
644
|
-
} else if (reason === "entitlement") {
|
|
645
|
-
this.telemetry.record("records.capability.denied", { pet_ref: pet });
|
|
646
|
-
}
|
|
647
|
-
return err(res.error);
|
|
648
|
-
}
|
|
649
|
-
const view = mapRecordView(pet, res.value);
|
|
650
|
-
if (view.withheld) {
|
|
651
|
-
this.telemetry.record("records.redaction.withheld", { pet_ref: pet });
|
|
652
|
-
this.recordCache.delete(pet);
|
|
653
|
-
return ok(view);
|
|
654
|
-
}
|
|
655
|
-
this.recordCache.set(pet, view);
|
|
656
|
-
return ok(view);
|
|
657
|
-
}
|
|
658
|
-
peekCachedRecord(pet) {
|
|
659
|
-
return this.recordCache.get(pet) ?? null;
|
|
660
|
-
}
|
|
661
|
-
// ---- consent ----------------------------------------------------------
|
|
662
|
-
async getConsent(pet) {
|
|
663
|
-
const res = await this.repository.getConsent(pet);
|
|
664
|
-
if (!res.ok) {
|
|
665
|
-
return err(res.error);
|
|
666
|
-
}
|
|
667
|
-
return ok(mapConsent(pet, res.value));
|
|
668
|
-
}
|
|
669
|
-
async grantConsent(input) {
|
|
670
|
-
const res = await this.repository.putConsent(
|
|
671
|
-
input.petRef,
|
|
672
|
-
{ consent_version: input.consentVersion, idempotency_key: input.idempotencyKey }
|
|
673
|
-
);
|
|
674
|
-
if (!res.ok) {
|
|
675
|
-
const reason = recordsDenialReasonOf(res.error);
|
|
676
|
-
if (reason === "entitlement") this.telemetry.record("records.capability.denied", { pet_ref: input.petRef });
|
|
677
|
-
return err(res.error);
|
|
678
|
-
}
|
|
679
|
-
return ok(mapConsent(input.petRef, res.value));
|
|
680
|
-
}
|
|
681
|
-
async revokeConsent(pet) {
|
|
682
|
-
const res = await this.repository.deleteConsent(pet);
|
|
683
|
-
if (!res.ok) return err(res.error);
|
|
684
|
-
this.recordCache.delete(pet);
|
|
685
|
-
return ok(mapConsent(pet, res.value));
|
|
686
|
-
}
|
|
687
|
-
// ---- telemetry ---------------------------------------------------------
|
|
688
|
-
reportCapabilityDenied(pet) {
|
|
689
|
-
this.telemetry.record("records.capability.denied", pet ? { pet_ref: pet } : {});
|
|
690
|
-
}
|
|
691
|
-
// ---- internals ---------------------------------------------------------
|
|
692
|
-
/** Emit `records.parse.gap` at most once when a request first shows a manual-review gap (R6). */
|
|
693
|
-
observeRequest(view) {
|
|
694
|
-
if (view.reviewStartedAt !== null && !this.reportedGaps.has(view.id)) {
|
|
695
|
-
this.reportedGaps.add(view.id);
|
|
696
|
-
this.telemetry.record("records.parse.gap", { request_id: view.id });
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
/** Shared error path for the request lane: emit capability-denied on an entitlement 403, then surface. */
|
|
700
|
-
onRequestError(error) {
|
|
701
|
-
const reason = recordsDenialReasonOf(error);
|
|
702
|
-
if (reason === "entitlement") this.telemetry.record("records.capability.denied", {});
|
|
703
|
-
return err(error);
|
|
704
|
-
}
|
|
705
|
-
};
|
|
706
|
-
function validateFile(file) {
|
|
707
|
-
if (file.mimeType !== RECORDS_UPLOAD_CONTENT_TYPE) return "unsupported_format";
|
|
708
|
-
const size = file.sizeBytes;
|
|
709
|
-
if (typeof size !== "number" || !Number.isFinite(size) || size <= 0 || size > MAX_UPLOAD_BYTES) {
|
|
710
|
-
return "oversize";
|
|
711
|
-
}
|
|
712
|
-
return null;
|
|
713
|
-
}
|
|
714
|
-
function reasonFromWire(error) {
|
|
715
|
-
const raw = error.wireMessage;
|
|
716
|
-
if (raw === "unsupported_format" || raw === "oversize" || raw === "corrupt") return raw;
|
|
717
|
-
return null;
|
|
718
|
-
}
|
|
719
|
-
function uploadFailed(wireMessage) {
|
|
720
|
-
return makeEverfurError("mediaUploadFailed", { retryable: false, wireMessage });
|
|
721
|
-
}
|
|
722
|
-
function internal() {
|
|
723
|
-
return makeEverfurError("internalError", { retryable: true });
|
|
724
|
-
}
|
|
725
|
-
var defaultTimers = {
|
|
726
|
-
setTimeout: (handler, ms) => setTimeout(handler, ms),
|
|
727
|
-
clearTimeout: (handle) => clearTimeout(handle)
|
|
728
|
-
};
|
|
729
|
-
function mergeSignals(a, b) {
|
|
730
|
-
if (!b) return a;
|
|
731
|
-
const ctrl = new AbortController();
|
|
732
|
-
if (a.aborted || b.aborted) {
|
|
733
|
-
ctrl.abort();
|
|
734
|
-
return ctrl.signal;
|
|
735
|
-
}
|
|
736
|
-
const onAbort = () => ctrl.abort();
|
|
737
|
-
a.addEventListener("abort", onAbort, { once: true });
|
|
738
|
-
b.addEventListener("abort", onAbort, { once: true });
|
|
739
|
-
return ctrl.signal;
|
|
740
|
-
}
|
|
741
|
-
function defaultIdempotencyFactory() {
|
|
742
|
-
let counter = 0;
|
|
743
|
-
return () => `records-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
// src/client/protocol/frames.ts
|
|
747
|
-
function assertNever(x) {
|
|
748
|
-
throw new Error(
|
|
749
|
-
`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`
|
|
750
|
-
);
|
|
751
|
-
}
|
|
752
|
-
function errorFrame(fields) {
|
|
753
|
-
return Object.freeze({
|
|
754
|
-
kind: "error",
|
|
755
|
-
terminal: true,
|
|
756
|
-
code: fields.code,
|
|
757
|
-
retryable: fields.retryable,
|
|
758
|
-
wireMessage: fields.wireMessage,
|
|
759
|
-
synthesized: fields.synthesized,
|
|
760
|
-
lastEventId: fields.lastEventId,
|
|
761
|
-
serverRequestId: null
|
|
762
|
-
});
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
// src/client/identity.ts
|
|
766
|
-
function authHeaders(auth) {
|
|
767
|
-
const headers = {};
|
|
768
|
-
if (auth.mode === "personalized") {
|
|
769
|
-
headers.authorization = `Bearer ${auth.token}`;
|
|
770
|
-
} else {
|
|
771
|
-
headers["x-everfur-partner-key"] = auth.publishableKey;
|
|
772
|
-
}
|
|
773
|
-
if (auth.userRef) headers["x-everfur-user-ref"] = auth.userRef;
|
|
774
|
-
if (auth.sessionId) headers["x-everfur-session-id"] = auth.sessionId;
|
|
775
|
-
return headers;
|
|
776
|
-
}
|
|
777
|
-
function withAuthHeaders(req, auth) {
|
|
778
|
-
return { ...req, headers: { ...stripAuthHeaders(req.headers), ...authHeaders(auth) } };
|
|
779
|
-
}
|
|
780
|
-
function stripAuthHeaders(headers) {
|
|
781
|
-
if (!headers) return {};
|
|
782
|
-
const out = {};
|
|
783
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
784
|
-
const lower = key.toLowerCase();
|
|
785
|
-
if (lower === "authorization" || lower === "x-everfur-partner-key") continue;
|
|
786
|
-
out[key] = value;
|
|
787
|
-
}
|
|
788
|
-
return out;
|
|
789
|
-
}
|
|
790
|
-
async function authedSend(req, ctx) {
|
|
791
|
-
if (ctx.mode === "anonymous") {
|
|
792
|
-
return ctx.transport.request(
|
|
793
|
-
withAuthHeaders(req, {
|
|
794
|
-
mode: "anonymous",
|
|
795
|
-
publishableKey: ctx.publishableKey,
|
|
796
|
-
userRef: ctx.userRef,
|
|
797
|
-
...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
|
|
798
|
-
})
|
|
799
|
-
);
|
|
800
|
-
}
|
|
801
|
-
let token;
|
|
802
|
-
try {
|
|
803
|
-
token = await ctx.identity.currentToken();
|
|
804
|
-
} catch {
|
|
805
|
-
return err(authRejectedError());
|
|
806
|
-
}
|
|
807
|
-
const first = await ctx.transport.request(
|
|
808
|
-
withAuthHeaders(req, {
|
|
809
|
-
mode: "personalized",
|
|
810
|
-
token,
|
|
811
|
-
userRef: ctx.userRef,
|
|
812
|
-
...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
|
|
813
|
-
})
|
|
814
|
-
);
|
|
815
|
-
if (first.ok || first.error.httpStatus !== 401) return first;
|
|
816
|
-
let refreshed;
|
|
817
|
-
try {
|
|
818
|
-
refreshed = await ctx.identity.currentToken({ forceRefresh: true });
|
|
819
|
-
} catch {
|
|
820
|
-
return err(authRejectedError());
|
|
821
|
-
}
|
|
822
|
-
const retry = await ctx.transport.request(
|
|
823
|
-
withAuthHeaders(req, {
|
|
824
|
-
mode: "personalized",
|
|
825
|
-
token: refreshed,
|
|
826
|
-
userRef: ctx.userRef,
|
|
827
|
-
...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
|
|
828
|
-
})
|
|
829
|
-
);
|
|
830
|
-
if (!retry.ok && retry.error.httpStatus === 401) {
|
|
831
|
-
return err(authRejectedError(retry.error.httpStatus));
|
|
832
|
-
}
|
|
833
|
-
return retry;
|
|
834
|
-
}
|
|
835
|
-
function authRejectedError(httpStatus) {
|
|
836
|
-
return makeEverfurError("authRejected", {
|
|
837
|
-
retryable: false,
|
|
838
|
-
...httpStatus !== void 0 ? { httpStatus } : {}
|
|
839
|
-
});
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
// src/client/transport.ts
|
|
843
|
-
function networkError(cause) {
|
|
844
|
-
return makeEverfurError("internalError", { retryable: true, wireMessage: describeCause(cause) });
|
|
845
|
-
}
|
|
846
|
-
function describeCause(cause) {
|
|
847
|
-
if (cause instanceof Error) return cause.message;
|
|
848
|
-
return typeof cause === "string" ? cause : "network request failed";
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
// src/client/funnel/requestFunnel.ts
|
|
852
|
-
var FUNNEL_UNARY_TIMEOUT_MS = 3e4;
|
|
853
|
-
var RETRY_OVERRIDE_MAX_MS = BACKOFF_CAP_MS * 2;
|
|
854
|
-
var IDEMPOTENCY_HEADER = "idempotency-key";
|
|
855
|
-
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
856
|
-
var NOOP_OBSERVER = Object.freeze({
|
|
857
|
-
onEvent() {
|
|
858
|
-
}
|
|
859
|
-
});
|
|
860
|
-
var defaultFunnelTimers = Object.freeze({
|
|
861
|
-
setTimeout: (handler, ms) => setTimeout(handler, ms),
|
|
862
|
-
clearTimeout: (handle) => clearTimeout(handle),
|
|
863
|
-
now: () => Date.now()
|
|
864
|
-
});
|
|
865
|
-
function createRequestFunnel(deps) {
|
|
866
|
-
const observer = deps.observer ?? NOOP_OBSERVER;
|
|
867
|
-
const timers = deps.timers ?? defaultFunnelTimers;
|
|
868
|
-
const rng = deps.rng ?? Math.random;
|
|
869
|
-
const sleep = deps.sleep ?? ((ms, signal) => delayAbortable(ms, timers, signal));
|
|
870
|
-
const ceiling = deps.maxAttempts ?? MAX_RETRY_ATTEMPTS;
|
|
871
|
-
const timeoutMs = deps.unaryTimeoutMs ?? FUNNEL_UNARY_TIMEOUT_MS;
|
|
872
|
-
const mintKey = deps.newIdempotencyKey ?? defaultIdempotencyKeyFactory();
|
|
873
|
-
const emit = (event) => {
|
|
874
|
-
try {
|
|
875
|
-
observer.onEvent(event);
|
|
876
|
-
} catch {
|
|
877
|
-
}
|
|
878
|
-
};
|
|
879
|
-
async function send(call, req, opts) {
|
|
880
|
-
const perCallMaxAttempts = opts?.maxAttempts;
|
|
881
|
-
const maxAttempts = Math.max(1, perCallMaxAttempts ?? ceiling);
|
|
882
|
-
const idempotent = opts?.idempotent ?? MUTATING_METHODS.has(req.method);
|
|
883
|
-
const idempotencyKey = idempotent ? mintKey() : null;
|
|
884
|
-
const base = assembleHeaders(req, idempotencyKey);
|
|
885
|
-
let attempt = 0;
|
|
886
|
-
for (; ; ) {
|
|
887
|
-
const stamp = (extra) => Object.freeze({
|
|
888
|
-
call,
|
|
889
|
-
method: req.method,
|
|
890
|
-
path: req.path,
|
|
891
|
-
attempt,
|
|
892
|
-
...idempotencyKey ? { idempotencyKey } : {},
|
|
893
|
-
...extra
|
|
894
|
-
});
|
|
895
|
-
emit(stamp({ phase: "attempt" }));
|
|
896
|
-
const deadline = boundedSignal(timeoutMs, timers);
|
|
897
|
-
const merged = mergeSignals2(deadline.signal, req.signal);
|
|
898
|
-
let settled;
|
|
899
|
-
try {
|
|
900
|
-
settled = await authedSend({ ...base, signal: merged.signal }, deps.auth);
|
|
901
|
-
} catch (cause) {
|
|
902
|
-
settled = err(networkError(cause));
|
|
903
|
-
} finally {
|
|
904
|
-
merged.dispose();
|
|
905
|
-
deadline.cancel();
|
|
906
|
-
}
|
|
907
|
-
if (settled.ok) {
|
|
908
|
-
emit(stamp({ phase: "settled", ok: true, reason: "ok" }));
|
|
909
|
-
return settled;
|
|
910
|
-
}
|
|
911
|
-
const error = settled.error;
|
|
912
|
-
const decision = decideRetry(error, attempt, {
|
|
913
|
-
maxAttempts,
|
|
914
|
-
rng,
|
|
915
|
-
now: timers.now(),
|
|
916
|
-
aborted: req.signal?.aborted === true,
|
|
917
|
-
...perCallMaxAttempts !== void 0 ? { perCallMaxAttempts } : {},
|
|
918
|
-
...deps.errorPolicy !== void 0 ? { policy: deps.errorPolicy } : {}
|
|
919
|
-
});
|
|
920
|
-
const settledEvent = {
|
|
921
|
-
ok: false,
|
|
922
|
-
code: error.code,
|
|
923
|
-
reason: decision.reason,
|
|
924
|
-
...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {},
|
|
925
|
-
...error.requestId !== void 0 ? { requestId: error.requestId } : {}
|
|
926
|
-
};
|
|
927
|
-
if (!decision.retry) {
|
|
928
|
-
emit(stamp({ phase: "settled", ...settledEvent }));
|
|
929
|
-
return err(error);
|
|
930
|
-
}
|
|
931
|
-
emit(stamp({ phase: "retry", ...settledEvent, delayMs: decision.delayMs }));
|
|
932
|
-
await sleep(decision.delayMs, req.signal);
|
|
933
|
-
if (req.signal?.aborted === true) {
|
|
934
|
-
emit(stamp({ phase: "settled", ...settledEvent, reason: "aborted" }));
|
|
935
|
-
return err(error);
|
|
936
|
-
}
|
|
937
|
-
attempt += 1;
|
|
938
|
-
}
|
|
939
|
-
}
|
|
940
|
-
async function authorize(req) {
|
|
941
|
-
return withAuthHeaders(req, await resolveDeviceAuth(deps.auth));
|
|
942
|
-
}
|
|
943
|
-
async function* stream(call, req, signal) {
|
|
944
|
-
emit(
|
|
945
|
-
Object.freeze({
|
|
946
|
-
call,
|
|
947
|
-
phase: "stream.open",
|
|
948
|
-
method: req.method,
|
|
949
|
-
path: req.path,
|
|
950
|
-
attempt: 0
|
|
951
|
-
})
|
|
952
|
-
);
|
|
953
|
-
try {
|
|
954
|
-
yield* deps.auth.transport.stream(req, signal);
|
|
955
|
-
} catch {
|
|
956
|
-
yield errorFrame({
|
|
957
|
-
// The same wire spelling sse.ts synthesizes, so `fromWire` folds it to the retryable `internalError`
|
|
958
|
-
// like any other transport failure. wireMessage stays null: it is the SERVER's text, and a thrown
|
|
959
|
-
// host exception's `.message` is not that.
|
|
960
|
-
code: "internal_error",
|
|
961
|
-
retryable: true,
|
|
962
|
-
wireMessage: null,
|
|
963
|
-
synthesized: true,
|
|
964
|
-
lastEventId: null});
|
|
965
|
-
}
|
|
966
|
-
}
|
|
967
|
-
return Object.freeze({ send, authorize, stream });
|
|
968
|
-
}
|
|
969
|
-
function assembleHeaders(req, idempotencyKey) {
|
|
970
|
-
const headers = {};
|
|
971
|
-
for (const [key, value] of Object.entries(req.headers ?? {})) {
|
|
972
|
-
if (key.toLowerCase() === IDEMPOTENCY_HEADER) continue;
|
|
973
|
-
headers[key] = value;
|
|
974
|
-
}
|
|
975
|
-
if (idempotencyKey !== null) headers["Idempotency-Key"] = idempotencyKey;
|
|
976
|
-
return { ...req, headers };
|
|
977
|
-
}
|
|
978
|
-
function defaultIdempotencyKeyFactory() {
|
|
979
|
-
let counter = 0;
|
|
980
|
-
return () => `efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
|
|
981
|
-
}
|
|
982
|
-
var POLICY_MAX_ATTEMPTS_CAP = 10;
|
|
983
|
-
function decideRetry(error, attempt, ctx) {
|
|
984
|
-
if (ctx.aborted) return { retry: false, reason: "aborted" };
|
|
985
|
-
const throttle = throttleKind(error);
|
|
986
|
-
if (throttle === "quota") {
|
|
987
|
-
return { retry: false, reason: "daily-quota-exhausted" };
|
|
988
|
-
}
|
|
989
|
-
if (throttle !== "burst" && !isAutoRetryable(error.code)) {
|
|
990
|
-
return { retry: false, reason: "terminal-code" };
|
|
991
|
-
}
|
|
992
|
-
const reason = throttle === "burst" ? "burst-throttle" : "retryable-code";
|
|
993
|
-
const policyVetoedRetry = () => {
|
|
994
|
-
if (ctx.policy === void 0) return false;
|
|
995
|
-
try {
|
|
996
|
-
return !ctx.policy.shouldRetry(error.code, attempt);
|
|
997
|
-
} catch {
|
|
998
|
-
return false;
|
|
999
|
-
}
|
|
1000
|
-
};
|
|
1001
|
-
if (policyVetoedRetry()) return { retry: false, reason: "terminal-code" };
|
|
1002
|
-
const policyCeiling = () => {
|
|
1003
|
-
if (ctx.policy === void 0) return null;
|
|
1004
|
-
let raw;
|
|
1005
|
-
try {
|
|
1006
|
-
raw = ctx.policy.maxAttempts(error.code);
|
|
1007
|
-
} catch {
|
|
1008
|
-
return null;
|
|
1009
|
-
}
|
|
1010
|
-
if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
|
|
1011
|
-
return Math.max(1, Math.min(POLICY_MAX_ATTEMPTS_CAP, Math.floor(raw)));
|
|
1012
|
-
};
|
|
1013
|
-
const ceiling = ctx.perCallMaxAttempts ?? policyCeiling() ?? ctx.maxAttempts;
|
|
1014
|
-
if (attempt + 1 >= ceiling) return { retry: false, reason: "attempts-exhausted" };
|
|
1015
|
-
const override = retryOverrideMs(error, ctx.now);
|
|
1016
|
-
if (override !== null) {
|
|
1017
|
-
if (override > RETRY_OVERRIDE_MAX_MS) {
|
|
1018
|
-
return { retry: false, reason: "server-reset-beyond-budget" };
|
|
1019
|
-
}
|
|
1020
|
-
return { retry: true, reason, delayMs: override };
|
|
1021
|
-
}
|
|
1022
|
-
return { retry: true, reason, delayMs: backoffDelayMs(attempt, ctx.rng) };
|
|
1023
|
-
}
|
|
1024
|
-
function throttleKind(error) {
|
|
1025
|
-
const code = error.code === "unknown" ? fromWire(rawWireCode(error.raw)) : error.code;
|
|
1026
|
-
if (code === "quotaExceeded") return "quota";
|
|
1027
|
-
if (code === "rateLimited") return "burst";
|
|
1028
|
-
if (error.httpStatus === 429) {
|
|
1029
|
-
return "burst";
|
|
1030
|
-
}
|
|
1031
|
-
return null;
|
|
1032
|
-
}
|
|
1033
|
-
function retryOverrideMs(error, now) {
|
|
1034
|
-
const at = findResetsAt(error.raw);
|
|
1035
|
-
if (at === null) return null;
|
|
1036
|
-
const delta = at - now;
|
|
1037
|
-
return delta > 0 ? delta : 0;
|
|
1038
|
-
}
|
|
1039
|
-
function findResetsAt(raw) {
|
|
1040
|
-
for (const scope of candidateScopes(raw)) {
|
|
1041
|
-
const value = scope["resets_at"];
|
|
1042
|
-
const parsed = parseInstantMs(value);
|
|
1043
|
-
if (parsed !== null) return parsed;
|
|
1044
|
-
}
|
|
1045
|
-
return null;
|
|
1046
|
-
}
|
|
1047
|
-
function candidateScopes(raw) {
|
|
1048
|
-
if (!isRecord(raw)) return [];
|
|
1049
|
-
const out = [raw];
|
|
1050
|
-
for (const nested of ["error", "detail"]) {
|
|
1051
|
-
const value = raw[nested];
|
|
1052
|
-
if (isRecord(value)) out.push(value);
|
|
1053
|
-
}
|
|
1054
|
-
return out;
|
|
1055
|
-
}
|
|
1056
|
-
function parseInstantMs(value) {
|
|
1057
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
1058
|
-
return value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
|
|
1059
|
-
}
|
|
1060
|
-
if (typeof value === "string" && value.trim().length > 0) {
|
|
1061
|
-
const parsed = Date.parse(value);
|
|
1062
|
-
return Number.isFinite(parsed) ? parsed : null;
|
|
1063
|
-
}
|
|
1064
|
-
return null;
|
|
1065
|
-
}
|
|
1066
|
-
function rawWireCode(raw) {
|
|
1067
|
-
for (const scope of candidateScopes(raw)) {
|
|
1068
|
-
const code = scope["code"];
|
|
1069
|
-
if (typeof code === "string" && code.length > 0) return code;
|
|
1070
|
-
}
|
|
1071
|
-
return null;
|
|
1072
|
-
}
|
|
1073
|
-
function isRecord(value) {
|
|
1074
|
-
return typeof value === "object" && value !== null;
|
|
1075
|
-
}
|
|
1076
|
-
async function resolveDeviceAuth(auth) {
|
|
1077
|
-
if (auth.mode === "anonymous") {
|
|
1078
|
-
return {
|
|
1079
|
-
mode: "anonymous",
|
|
1080
|
-
publishableKey: auth.publishableKey,
|
|
1081
|
-
userRef: auth.userRef,
|
|
1082
|
-
...auth.sessionId ? { sessionId: auth.sessionId } : {}
|
|
1083
|
-
};
|
|
1084
|
-
}
|
|
1085
|
-
return {
|
|
1086
|
-
mode: "personalized",
|
|
1087
|
-
token: await auth.identity.currentToken(),
|
|
1088
|
-
userRef: auth.userRef,
|
|
1089
|
-
...auth.sessionId ? { sessionId: auth.sessionId } : {}
|
|
1090
|
-
};
|
|
1091
|
-
}
|
|
1092
|
-
function boundedSignal(ms, timers) {
|
|
1093
|
-
const ctrl = new AbortController();
|
|
1094
|
-
const handle = timers.setTimeout(() => ctrl.abort(), ms);
|
|
1095
|
-
return { signal: ctrl.signal, cancel: () => timers.clearTimeout(handle) };
|
|
1096
|
-
}
|
|
1097
|
-
function mergeSignals2(deadline, caller) {
|
|
1098
|
-
const noop = () => void 0;
|
|
1099
|
-
if (!caller) return { signal: deadline, dispose: noop };
|
|
1100
|
-
const ctrl = new AbortController();
|
|
1101
|
-
if (deadline.aborted || caller.aborted) {
|
|
1102
|
-
ctrl.abort();
|
|
1103
|
-
return { signal: ctrl.signal, dispose: noop };
|
|
1104
|
-
}
|
|
1105
|
-
const onAbort = () => ctrl.abort();
|
|
1106
|
-
deadline.addEventListener("abort", onAbort, { once: true });
|
|
1107
|
-
caller.addEventListener("abort", onAbort, { once: true });
|
|
1108
|
-
return {
|
|
1109
|
-
signal: ctrl.signal,
|
|
1110
|
-
dispose: () => {
|
|
1111
|
-
deadline.removeEventListener("abort", onAbort);
|
|
1112
|
-
caller.removeEventListener("abort", onAbort);
|
|
1113
|
-
}
|
|
1114
|
-
};
|
|
1115
|
-
}
|
|
1116
|
-
function delayAbortable(ms, timers, signal) {
|
|
1117
|
-
if (ms <= 0 || signal?.aborted === true) return Promise.resolve();
|
|
1118
|
-
return new Promise((resolve) => {
|
|
1119
|
-
const handle = timers.setTimeout(() => {
|
|
1120
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1121
|
-
resolve();
|
|
1122
|
-
}, ms);
|
|
1123
|
-
const onAbort = () => {
|
|
1124
|
-
timers.clearTimeout(handle);
|
|
1125
|
-
resolve();
|
|
1126
|
-
};
|
|
1127
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1128
|
-
});
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
// src/client/text.ts
|
|
1132
|
-
function hasLoneSurrogate(value) {
|
|
1133
|
-
for (let i = 0; i < value.length; i += 1) {
|
|
1134
|
-
const code = value.charCodeAt(i);
|
|
1135
|
-
if (code >= 55296 && code <= 56319) {
|
|
1136
|
-
const low = value.charCodeAt(i + 1);
|
|
1137
|
-
if (!(low >= 56320 && low <= 57343)) return true;
|
|
1138
|
-
i += 1;
|
|
1139
|
-
} else if (code >= 56320 && code <= 57343) {
|
|
1140
|
-
return true;
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
return false;
|
|
1144
|
-
}
|
|
1145
|
-
|
|
1146
|
-
// src/core/records/repository.ts
|
|
1147
|
-
var BASE = "/widget/v1/records";
|
|
1148
|
-
function createHttpRecordsRepository(deps) {
|
|
1149
|
-
const { auth } = deps;
|
|
1150
|
-
const mode = auth.mode;
|
|
1151
|
-
const funnel = deps.funnel ?? createRequestFunnel({ auth, ...deps.errorPolicy ? { errorPolicy: deps.errorPolicy } : {} });
|
|
1152
|
-
const send = async (call, req, kind) => {
|
|
1153
|
-
const res = await funnel.send(call, req);
|
|
1154
|
-
if (res.ok) return res;
|
|
1155
|
-
return err(tagReason(res.error, mode, kind));
|
|
1156
|
-
};
|
|
1157
|
-
const segmentError = (field, value) => {
|
|
1158
|
-
if (typeof value !== "string" || value.length === 0) {
|
|
1159
|
-
return makeEverfurError("validationFailed", {
|
|
1160
|
-
retryable: false,
|
|
1161
|
-
wireMessage: `${field} is required and must be a non-empty string`
|
|
1162
|
-
});
|
|
1163
|
-
}
|
|
1164
|
-
if (hasLoneSurrogate(value)) {
|
|
1165
|
-
return makeEverfurError("validationFailed", {
|
|
1166
|
-
retryable: false,
|
|
1167
|
-
wireMessage: `${field} contains an unpaired surrogate and cannot be encoded`
|
|
1168
|
-
});
|
|
1169
|
-
}
|
|
1170
|
-
return null;
|
|
1171
|
-
};
|
|
1172
|
-
const boundsError = (field, value, max) => {
|
|
1173
|
-
const unusable = segmentError(field, value);
|
|
1174
|
-
if (unusable !== null) return unusable;
|
|
1175
|
-
const value_ = value;
|
|
1176
|
-
const length = [...value_].length;
|
|
1177
|
-
if (length > max) {
|
|
1178
|
-
return makeEverfurError("validationFailed", {
|
|
1179
|
-
retryable: false,
|
|
1180
|
-
wireMessage: `${field} is ${length} characters; the server accepts at most ${max}`
|
|
1181
|
-
});
|
|
1182
|
-
}
|
|
1183
|
-
return null;
|
|
1184
|
-
};
|
|
1185
|
-
const firstError = (...checks) => checks.find((c) => c !== null) ?? null;
|
|
1186
|
-
return {
|
|
1187
|
-
createRequest: (body) => {
|
|
1188
|
-
const invalid = firstError(
|
|
1189
|
-
boundsError("idempotency_key", body.idempotency_key, IDEMPOTENCY_KEY_MAX),
|
|
1190
|
-
boundsError("pet_ref", body.pet_ref, PET_REF_MAX)
|
|
1191
|
-
);
|
|
1192
|
-
if (invalid) return Promise.resolve(err(invalid));
|
|
1193
|
-
return send("records.createRequest", post(`${BASE}/requests`, body), "request");
|
|
1194
|
-
},
|
|
1195
|
-
initiateUpload: (requestId, body) => {
|
|
1196
|
-
const invalid = segmentError("request_id", requestId);
|
|
1197
|
-
if (invalid) return Promise.resolve(err(invalid));
|
|
1198
|
-
return send(
|
|
1199
|
-
"records.initiateUpload",
|
|
1200
|
-
post(`${BASE}/requests/${encodeURIComponent(requestId)}/uploads/initiate`, body),
|
|
1201
|
-
"request"
|
|
1202
|
-
);
|
|
1203
|
-
},
|
|
1204
|
-
completeUpload: (requestId, body) => {
|
|
1205
|
-
const invalid = segmentError("request_id", requestId);
|
|
1206
|
-
if (invalid) return Promise.resolve(err(invalid));
|
|
1207
|
-
return send(
|
|
1208
|
-
"records.completeUpload",
|
|
1209
|
-
post(`${BASE}/requests/${encodeURIComponent(requestId)}/uploads/complete`, body),
|
|
1210
|
-
"request"
|
|
1211
|
-
);
|
|
1212
|
-
},
|
|
1213
|
-
getRequest: (requestId) => {
|
|
1214
|
-
const invalid = segmentError("request_id", requestId);
|
|
1215
|
-
if (invalid) return Promise.resolve(err(invalid));
|
|
1216
|
-
return send(
|
|
1217
|
-
"records.getRequest",
|
|
1218
|
-
get(`${BASE}/requests/${encodeURIComponent(requestId)}`),
|
|
1219
|
-
"request"
|
|
1220
|
-
);
|
|
1221
|
-
},
|
|
1222
|
-
listRequests: async () => {
|
|
1223
|
-
const res = await send(
|
|
1224
|
-
"records.listRequests",
|
|
1225
|
-
get(`${BASE}/requests`),
|
|
1226
|
-
"request"
|
|
1227
|
-
);
|
|
1228
|
-
if (!res.ok) return res;
|
|
1229
|
-
const value = res.value;
|
|
1230
|
-
const items = Array.isArray(value) ? value : value.items ?? [];
|
|
1231
|
-
return { ok: true, value: items };
|
|
1232
|
-
},
|
|
1233
|
-
getRecord: (petRef) => {
|
|
1234
|
-
const invalid = boundsError("pet_ref", petRef, PET_REF_MAX);
|
|
1235
|
-
if (invalid) return Promise.resolve(err(invalid));
|
|
1236
|
-
return send(
|
|
1237
|
-
"records.getRecord",
|
|
1238
|
-
get(`${BASE}/pets/${encodeURIComponent(petRef)}/record`),
|
|
1239
|
-
"content"
|
|
1240
|
-
);
|
|
1241
|
-
},
|
|
1242
|
-
getConsent: (petRef) => {
|
|
1243
|
-
const invalid = boundsError("pet_ref", petRef, PET_REF_MAX);
|
|
1244
|
-
if (invalid) return Promise.resolve(err(invalid));
|
|
1245
|
-
return send(
|
|
1246
|
-
"records.getConsent",
|
|
1247
|
-
get(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),
|
|
1248
|
-
"consent"
|
|
1249
|
-
);
|
|
1250
|
-
},
|
|
1251
|
-
putConsent: (petRef, body) => {
|
|
1252
|
-
const invalid = firstError(
|
|
1253
|
-
boundsError("consent_version", body.consent_version, CONSENT_VERSION_MAX),
|
|
1254
|
-
boundsError("idempotency_key", body.idempotency_key, IDEMPOTENCY_KEY_MAX),
|
|
1255
|
-
boundsError("pet_ref", petRef, PET_REF_MAX)
|
|
1256
|
-
);
|
|
1257
|
-
if (invalid) return Promise.resolve(err(invalid));
|
|
1258
|
-
return send(
|
|
1259
|
-
"records.putConsent",
|
|
1260
|
-
put(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`, body),
|
|
1261
|
-
"consent"
|
|
1262
|
-
);
|
|
1263
|
-
},
|
|
1264
|
-
deleteConsent: (petRef) => {
|
|
1265
|
-
const invalid = boundsError("pet_ref", petRef, PET_REF_MAX);
|
|
1266
|
-
if (invalid) return Promise.resolve(err(invalid));
|
|
1267
|
-
return send(
|
|
1268
|
-
"records.deleteConsent",
|
|
1269
|
-
del(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),
|
|
1270
|
-
"consent"
|
|
1271
|
-
);
|
|
1272
|
-
}
|
|
1273
|
-
};
|
|
1274
|
-
}
|
|
1275
|
-
function withReason(error, reason) {
|
|
1276
|
-
const tagged = { ...error, recordsReason: reason };
|
|
1277
|
-
for (const key of ["wireMessage", "raw"]) {
|
|
1278
|
-
const descriptor = Object.getOwnPropertyDescriptor(error, key);
|
|
1279
|
-
if (descriptor !== void 0) Object.defineProperty(tagged, key, descriptor);
|
|
1280
|
-
}
|
|
1281
|
-
return Object.freeze(tagged);
|
|
1282
|
-
}
|
|
1283
|
-
function tagReason(error, mode, kind) {
|
|
1284
|
-
if (error.httpStatus === 404) return withReason(error, "entitlement");
|
|
1285
|
-
if (error.code !== "accessDenied") return error;
|
|
1286
|
-
const reason = mode === "anonymous" ? "session_required" : kind === "content" ? "consent_required" : "entitlement";
|
|
1287
|
-
return withReason(error, reason);
|
|
1288
|
-
}
|
|
1289
|
-
function get(path) {
|
|
1290
|
-
return { method: "GET", path };
|
|
1291
|
-
}
|
|
1292
|
-
function post(path, body) {
|
|
1293
|
-
return { method: "POST", path, body };
|
|
1294
|
-
}
|
|
1295
|
-
function put(path, body) {
|
|
1296
|
-
return { method: "PUT", path, body };
|
|
1297
|
-
}
|
|
1298
|
-
function del(path) {
|
|
1299
|
-
return { method: "DELETE", path };
|
|
1300
|
-
}
|
|
1301
|
-
|
|
1302
|
-
// src/client/entitlements/resolve.ts
|
|
1303
|
-
var REQUIRES = Object.freeze({
|
|
1304
|
-
chat: Object.freeze(["chat.message.create"]),
|
|
1305
|
-
records: Object.freeze(["records.upload.create", "records.record.read"]),
|
|
1306
|
-
video: Object.freeze(["video.gait.execute"]),
|
|
1307
|
-
photo: Object.freeze(["photo.checkup.execute"]),
|
|
1308
|
-
animations: Object.freeze(["animations.state.read"])
|
|
1309
|
-
});
|
|
1310
|
-
function requires(name) {
|
|
1311
|
-
return REQUIRES[name];
|
|
1312
|
-
}
|
|
1313
|
-
function decideCapability(name, decisions, opts) {
|
|
1314
|
-
if (opts?.isPending === true) {
|
|
1315
|
-
return freezeDecision({ name, enabled: false, isPending: true, limits: {} });
|
|
1316
|
-
}
|
|
1317
|
-
const keys = requires(name);
|
|
1318
|
-
const byResource = /* @__PURE__ */ new Map();
|
|
1319
|
-
for (const decision of decisions) byResource.set(decision.resource, decision);
|
|
1320
|
-
const limits = mergeLimits(keys, byResource);
|
|
1321
|
-
const missing = keys.filter((key) => byResource.get(key)?.granted !== true);
|
|
1322
|
-
if (missing.length === 0) {
|
|
1323
|
-
return freezeDecision({ name, enabled: true, isPending: false, limits });
|
|
1324
|
-
}
|
|
1325
|
-
return freezeDecision({
|
|
1326
|
-
name,
|
|
1327
|
-
enabled: false,
|
|
1328
|
-
isPending: false,
|
|
1329
|
-
limits,
|
|
1330
|
-
disabled: disabledFor(keys, byResource)
|
|
1331
|
-
});
|
|
1332
|
-
}
|
|
1333
|
-
function mergeLimits(keys, byResource) {
|
|
1334
|
-
const out = {};
|
|
1335
|
-
for (const key of keys) {
|
|
1336
|
-
const decisionLimits = byResource.get(key)?.limits;
|
|
1337
|
-
if (!decisionLimits) continue;
|
|
1338
|
-
for (const [limitKey, limitValue] of Object.entries(decisionLimits)) {
|
|
1339
|
-
const existing = out[limitKey];
|
|
1340
|
-
out[limitKey] = existing === void 0 ? limitValue : Math.min(existing, limitValue);
|
|
1341
|
-
}
|
|
1342
|
-
}
|
|
1343
|
-
return out;
|
|
1344
|
-
}
|
|
1345
|
-
function disabledFor(keys, byResource) {
|
|
1346
|
-
for (const key of keys) {
|
|
1347
|
-
const explicit = byResource.get(key)?.disabled;
|
|
1348
|
-
if (explicit) {
|
|
1349
|
-
return Object.freeze({
|
|
1350
|
-
reason: explicit.reason,
|
|
1351
|
-
level: explicit.level,
|
|
1352
|
-
recoverable: explicit.recoverable
|
|
1353
|
-
});
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
return Object.freeze({
|
|
1357
|
-
reason: userFacingError("accessDenied"),
|
|
1358
|
-
level: "user_entitlement",
|
|
1359
|
-
recoverable: false
|
|
1360
|
-
});
|
|
1361
|
-
}
|
|
1362
|
-
function freezeDecision(d) {
|
|
1363
|
-
const base = {
|
|
1364
|
-
name: d.name,
|
|
1365
|
-
enabled: d.enabled,
|
|
1366
|
-
isPending: d.isPending,
|
|
1367
|
-
limits: Object.freeze({ ...d.limits })
|
|
1368
|
-
};
|
|
1369
|
-
if (d.disabled !== void 0) base.disabled = d.disabled;
|
|
1370
|
-
return Object.freeze(base);
|
|
1371
|
-
}
|
|
1372
|
-
|
|
1373
|
-
// src/client/theme/tokens.ts
|
|
1374
|
-
function deepFreeze(value) {
|
|
1375
|
-
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
1376
|
-
Object.freeze(value);
|
|
1377
|
-
for (const key of Object.keys(value)) {
|
|
1378
|
-
deepFreeze(value[key]);
|
|
1379
|
-
}
|
|
1380
|
-
}
|
|
1381
|
-
return value;
|
|
1382
|
-
}
|
|
1383
|
-
var SPACE = { xs: 4, sm: 8, md: 12, lg: 16, xl: 24, xxl: 32 };
|
|
1384
|
-
var RADIUS = { tile: 5, xs: 6, sm: 10, md: 14, lg: 20, xl: 28, pill: 500 };
|
|
1385
|
-
var TYPE_SIZE = {
|
|
1386
|
-
nano: 8,
|
|
1387
|
-
small: 9,
|
|
1388
|
-
micro: 10,
|
|
1389
|
-
tiny: 11,
|
|
1390
|
-
caption: 12,
|
|
1391
|
-
bodyTight: 13,
|
|
1392
|
-
body: 14,
|
|
1393
|
-
subtitle: 16,
|
|
1394
|
-
heading: 18,
|
|
1395
|
-
verdict: 24
|
|
1396
|
-
};
|
|
1397
|
-
var LINE_HEIGHT = { tight: 1.15, snug: 1.3, normal: 1.4, relaxed: 1.55 };
|
|
1398
|
-
var WEIGHT = { regular: "400", medium: "500", bold: "700" };
|
|
1399
|
-
var LETTER_SPACING = {
|
|
1400
|
-
eyebrow: 1,
|
|
1401
|
-
monoWide: 0.9,
|
|
1402
|
-
headerBrand: -0.42,
|
|
1403
|
-
tight: -0.35
|
|
1404
|
-
};
|
|
1405
|
-
function baseType() {
|
|
1406
|
-
return {
|
|
1407
|
-
family: "System",
|
|
1408
|
-
mono: "monospace",
|
|
1409
|
-
fontUrl: null,
|
|
1410
|
-
size: TYPE_SIZE,
|
|
1411
|
-
lineHeight: LINE_HEIGHT,
|
|
1412
|
-
weight: WEIGHT,
|
|
1413
|
-
letterSpacing: LETTER_SPACING
|
|
1414
|
-
};
|
|
1415
|
-
}
|
|
1416
|
-
var MOTION = {
|
|
1417
|
-
duration: { instant: 80, fast: 140, normal: 220, slow: 320 },
|
|
1418
|
-
spring: { gentle: { damping: 18, stiffness: 200 } },
|
|
1419
|
-
easing: { standard: "cubic-bezier(0.4, 0, 0.2, 1)" },
|
|
1420
|
-
reducedMotion: false
|
|
1421
|
-
};
|
|
1422
|
-
var LIGHT_COLOR = {
|
|
1423
|
-
brand: "#10462E",
|
|
1424
|
-
brandSoft: "rgba(16,70,46,0.10)",
|
|
1425
|
-
brandSofter: "rgba(16,70,46,0.15)",
|
|
1426
|
-
brandBorder: "rgba(16,70,46,0.18)",
|
|
1427
|
-
borderHairlineGreen: "rgba(16,70,46,0.25)",
|
|
1428
|
-
surface: "#FFFFFF",
|
|
1429
|
-
surfaceCream: "#FDFBF8",
|
|
1430
|
-
surfaceSubtle: "#EFE9E3",
|
|
1431
|
-
background: "#FFFFFF",
|
|
1432
|
-
borderRingCream: "#D8D2C8",
|
|
1433
|
-
text: {
|
|
1434
|
-
primary: "#111111",
|
|
1435
|
-
secondary: "#0E462E",
|
|
1436
|
-
muted: "#6E6660",
|
|
1437
|
-
placeholder: "rgba(0,0,0,0.30)",
|
|
1438
|
-
onBrand: "#FFFFFF",
|
|
1439
|
-
metaCool: "#3D3D3D"
|
|
1440
|
-
},
|
|
1441
|
-
primary: "#10462E",
|
|
1442
|
-
onPrimary: "#FFFFFF",
|
|
1443
|
-
accent: "#10462E",
|
|
1444
|
-
onAccent: "#FFFFFF",
|
|
1445
|
-
accentEdge: "#07C168",
|
|
1446
|
-
success: "#07C168",
|
|
1447
|
-
danger: "#B91C1C",
|
|
1448
|
-
errorRed: "#FF1B00",
|
|
1449
|
-
warningStrong: "#A45610",
|
|
1450
|
-
cautionAccent: "#D9821D",
|
|
1451
|
-
riskConcern: "#EFA700",
|
|
1452
|
-
badgeBgPositive: "rgba(7,193,104,0.12)",
|
|
1453
|
-
badgeBgCaution: "rgba(217,130,29,0.14)",
|
|
1454
|
-
badgeBgCritical: "rgba(185,28,28,0.12)",
|
|
1455
|
-
badgeBgNeutral: "rgba(110,102,96,0.12)",
|
|
1456
|
-
bubbleUser: "#10462E",
|
|
1457
|
-
bubbleAssistant: "#FFFFFF",
|
|
1458
|
-
skeleton: "#EFE9E3",
|
|
1459
|
-
scanButtonPink: "#FFC3BC",
|
|
1460
|
-
checkupCardLowRiskBg: "rgba(7,193,104,0.10)",
|
|
1461
|
-
checkupCardConcernBg: "rgba(239,167,0,0.10)"
|
|
1462
|
-
};
|
|
1463
|
-
var EVERFUR_LIGHT = deepFreeze({
|
|
1464
|
-
brightness: "light",
|
|
1465
|
-
meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
|
|
1466
|
-
color: LIGHT_COLOR,
|
|
1467
|
-
space: SPACE,
|
|
1468
|
-
radius: RADIUS,
|
|
1469
|
-
type: baseType(),
|
|
1470
|
-
motion: MOTION
|
|
1471
|
-
});
|
|
1472
|
-
var DARK_COLOR = {
|
|
1473
|
-
brand: "#6BD39A",
|
|
1474
|
-
brandSoft: "rgba(107,211,154,0.12)",
|
|
1475
|
-
brandSofter: "rgba(107,211,154,0.18)",
|
|
1476
|
-
brandBorder: "rgba(107,211,154,0.22)",
|
|
1477
|
-
borderHairlineGreen: "rgba(107,211,154,0.28)",
|
|
1478
|
-
surface: "#1C1F23",
|
|
1479
|
-
surfaceCream: "#23272C",
|
|
1480
|
-
surfaceSubtle: "#23272C",
|
|
1481
|
-
background: "#15171A",
|
|
1482
|
-
borderRingCream: "#3A3F45",
|
|
1483
|
-
text: {
|
|
1484
|
-
primary: "#F5F3F0",
|
|
1485
|
-
secondary: "#A9E4C4",
|
|
1486
|
-
muted: "#9A938C",
|
|
1487
|
-
placeholder: "rgba(255,255,255,0.35)",
|
|
1488
|
-
onBrand: "#0E1F17",
|
|
1489
|
-
metaCool: "#C9C9C9"
|
|
1490
|
-
},
|
|
1491
|
-
primary: "#6BD39A",
|
|
1492
|
-
onPrimary: "#0E1F17",
|
|
1493
|
-
accent: "#6BD39A",
|
|
1494
|
-
onAccent: "#0E1F17",
|
|
1495
|
-
accentEdge: "#34D888",
|
|
1496
|
-
success: "#07C168",
|
|
1497
|
-
danger: "#B91C1C",
|
|
1498
|
-
errorRed: "#FF1B00",
|
|
1499
|
-
warningStrong: "#A45610",
|
|
1500
|
-
cautionAccent: "#D9821D",
|
|
1501
|
-
riskConcern: "#EFA700",
|
|
1502
|
-
badgeBgPositive: "rgba(7,193,104,0.18)",
|
|
1503
|
-
badgeBgCaution: "rgba(217,130,29,0.20)",
|
|
1504
|
-
badgeBgCritical: "rgba(185,28,28,0.22)",
|
|
1505
|
-
badgeBgNeutral: "rgba(255,255,255,0.10)",
|
|
1506
|
-
bubbleUser: "#6BD39A",
|
|
1507
|
-
bubbleAssistant: "#1C1F23",
|
|
1508
|
-
skeleton: "#23272C",
|
|
1509
|
-
scanButtonPink: "#FFC3BC",
|
|
1510
|
-
checkupCardLowRiskBg: "rgba(7,193,104,0.16)",
|
|
1511
|
-
checkupCardConcernBg: "rgba(239,167,0,0.16)"
|
|
1512
|
-
};
|
|
1513
|
-
deepFreeze({
|
|
1514
|
-
brightness: "dark",
|
|
1515
|
-
meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
|
|
1516
|
-
color: DARK_COLOR,
|
|
1517
|
-
space: SPACE,
|
|
1518
|
-
radius: RADIUS,
|
|
1519
|
-
type: baseType(),
|
|
1520
|
-
motion: MOTION
|
|
1521
|
-
});
|
|
1522
|
-
var EVERFUR_THEME_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurThemeContext@v1");
|
|
1523
|
-
var globalThemeHost = globalThis;
|
|
1524
|
-
var EverfurThemeContext = globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] ?? (globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] = createContext(EVERFUR_LIGHT));
|
|
1525
|
-
EverfurThemeContext.displayName ??= "EverfurThemeContext";
|
|
1526
|
-
function useEverfurTheme() {
|
|
1527
|
-
return useContext(EverfurThemeContext);
|
|
1528
|
-
}
|
|
1529
|
-
|
|
1530
|
-
// src/rn/facade.ts
|
|
1531
|
-
var EVERFUR_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurContext@v1");
|
|
1532
|
-
var globalContextHost = globalThis;
|
|
1533
|
-
var EverfurContext = globalContextHost[EVERFUR_CONTEXT_SYMBOL] ?? (globalContextHost[EVERFUR_CONTEXT_SYMBOL] = createContext(null));
|
|
1534
|
-
EverfurContext.displayName ??= "EverfurContext";
|
|
1535
|
-
function useEverfurContext() {
|
|
1536
|
-
const ctx = useContext(EverfurContext);
|
|
1537
|
-
if (ctx === null) {
|
|
1538
|
-
throw new EverfurConfigError(
|
|
1539
|
-
"not-initialized",
|
|
1540
|
-
"Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high."
|
|
1541
|
-
);
|
|
1542
|
-
}
|
|
1543
|
-
return ctx;
|
|
1544
|
-
}
|
|
1545
|
-
|
|
1546
|
-
// src/rn/records/useRecords.ts
|
|
1547
|
-
var INITIAL = {
|
|
1548
|
-
record: null,
|
|
1549
|
-
requests: [],
|
|
1550
|
-
consent: null,
|
|
1551
|
-
error: null,
|
|
1552
|
-
denialReason: null,
|
|
1553
|
-
withheld: false,
|
|
1554
|
-
loading: true,
|
|
1555
|
-
isUploading: false,
|
|
1556
|
-
uploadProgress: null
|
|
1557
|
-
};
|
|
1558
|
-
var POLL_INTERVAL_MS = 4e3;
|
|
1559
|
-
var MAX_POLLS = 30;
|
|
1560
|
-
function useEverfurRecords(opts) {
|
|
1561
|
-
const { petRef } = opts;
|
|
1562
|
-
const { runtime, userRef } = useEverfurContext();
|
|
1563
|
-
const [controller, setController] = useState(opts.controller ?? null);
|
|
1564
|
-
const [snap, setSnap] = useState(INITIAL);
|
|
1565
|
-
const generation = useRef(0);
|
|
1566
|
-
useEffect(() => {
|
|
1567
|
-
if (opts.controller) {
|
|
1568
|
-
setController(opts.controller);
|
|
1569
|
-
return;
|
|
1570
|
-
}
|
|
1571
|
-
const { services } = runtime.registry;
|
|
1572
|
-
const telemetry = {
|
|
1573
|
-
record: (event, props) => services.telemetry.track(event, props)
|
|
1574
|
-
};
|
|
1575
|
-
const acquired = runtime.registry.acquire(
|
|
1576
|
-
"records",
|
|
1577
|
-
`${userRef ?? ""}|${petRef}`,
|
|
1578
|
-
() => createRecordsController({
|
|
1579
|
-
repository: createHttpRecordsRepository({
|
|
1580
|
-
auth: services.authFor(userRef),
|
|
1581
|
-
...services.errorPolicy ? { errorPolicy: services.errorPolicy } : {}
|
|
1582
|
-
}),
|
|
1583
|
-
uploads: services.uploadTransport,
|
|
1584
|
-
telemetry
|
|
1585
|
-
}),
|
|
1586
|
-
// The records controller holds only an in-memory cache and has no dispose; dropping the ref clears it.
|
|
1587
|
-
() => {
|
|
1588
|
-
}
|
|
1589
|
-
);
|
|
1590
|
-
setController(acquired);
|
|
1591
|
-
return () => {
|
|
1592
|
-
runtime.registry.release(acquired);
|
|
1593
|
-
setController((current) => current === acquired ? null : current);
|
|
1594
|
-
};
|
|
1595
|
-
}, [runtime, userRef, petRef, opts.controller]);
|
|
1596
|
-
const patch = useCallback((partial) => {
|
|
1597
|
-
setSnap((current) => ({ ...current, ...partial }));
|
|
1598
|
-
}, []);
|
|
1599
|
-
const load = useCallback(async () => {
|
|
1600
|
-
if (!controller) return;
|
|
1601
|
-
const gen = generation.current += 1;
|
|
1602
|
-
pollsRef.current = 0;
|
|
1603
|
-
rearmPolls();
|
|
1604
|
-
patch({ loading: true, error: null, denialReason: null, withheld: false });
|
|
1605
|
-
const [consentRes, listRes] = await Promise.all([
|
|
1606
|
-
controller.getConsent(petRef),
|
|
1607
|
-
controller.listRequests()
|
|
1608
|
-
]);
|
|
1609
|
-
if (gen !== generation.current) return;
|
|
1610
|
-
const consent = consentRes.ok ? consentRes.value : null;
|
|
1611
|
-
const requests = listRes.ok ? listRes.value : [];
|
|
1612
|
-
const listError = listRes.ok ? null : listRes.error;
|
|
1613
|
-
if (consent && consent.granted) {
|
|
1614
|
-
const recordRes = await controller.getRecord(petRef);
|
|
1615
|
-
if (gen !== generation.current) return;
|
|
1616
|
-
if (recordRes.ok) {
|
|
1617
|
-
patch({
|
|
1618
|
-
consent,
|
|
1619
|
-
requests,
|
|
1620
|
-
record: recordRes.value,
|
|
1621
|
-
withheld: recordRes.value.withheld,
|
|
1622
|
-
error: recordRes.value.withheld ? withheldSentinel() : listError,
|
|
1623
|
-
denialReason: null,
|
|
1624
|
-
loading: false
|
|
1625
|
-
});
|
|
1626
|
-
return;
|
|
1627
|
-
}
|
|
1628
|
-
patch({
|
|
1629
|
-
consent,
|
|
1630
|
-
requests,
|
|
1631
|
-
record: null,
|
|
1632
|
-
error: recordRes.error,
|
|
1633
|
-
denialReason: recordsDenialReasonOf(recordRes.error),
|
|
1634
|
-
withheld: false,
|
|
1635
|
-
loading: false
|
|
1636
|
-
});
|
|
1637
|
-
return;
|
|
1638
|
-
}
|
|
1639
|
-
patch({
|
|
1640
|
-
consent,
|
|
1641
|
-
requests,
|
|
1642
|
-
record: null,
|
|
1643
|
-
// When the CONSENT read itself failed, its error is the one that explains the state; `listError` is
|
|
1644
|
-
// incidental. This branch is now reachable with a real error because a 404 no longer folds into a
|
|
1645
|
-
// fake `granted:false`.
|
|
1646
|
-
error: consentRes.ok ? listError : consentRes.error,
|
|
1647
|
-
denialReason: consent ? "consent_required" : consentDenial(consentRes),
|
|
1648
|
-
withheld: false,
|
|
1649
|
-
loading: false
|
|
1650
|
-
});
|
|
1651
|
-
}, [controller, petRef, patch]);
|
|
1652
|
-
useEffect(() => {
|
|
1653
|
-
void load();
|
|
1654
|
-
}, [load]);
|
|
1655
|
-
const activeRequest = useMemo(() => newestRequest(snap.requests), [snap.requests]);
|
|
1656
|
-
const activeId = activeRequest?.id ?? null;
|
|
1657
|
-
const activeStatus = activeRequest?.status ?? null;
|
|
1658
|
-
const pollsRef = useRef(0);
|
|
1659
|
-
const polledIdRef = useRef(null);
|
|
1660
|
-
const [pollEpoch, rearmPolls] = useReducer((n) => n + 1, 0);
|
|
1661
|
-
useEffect(() => {
|
|
1662
|
-
if (!controller || activeId === null || activeStatus === null) return;
|
|
1663
|
-
if (isTerminalStatus(activeStatus) || activeStatus === "in_review") return;
|
|
1664
|
-
if (polledIdRef.current !== String(activeId)) {
|
|
1665
|
-
polledIdRef.current = String(activeId);
|
|
1666
|
-
pollsRef.current = 0;
|
|
1667
|
-
}
|
|
1668
|
-
let cancelled = false;
|
|
1669
|
-
const tick = async () => {
|
|
1670
|
-
if (cancelled || pollsRef.current >= MAX_POLLS) return;
|
|
1671
|
-
pollsRef.current += 1;
|
|
1672
|
-
const res = await controller.getRequest(activeId);
|
|
1673
|
-
if (cancelled) return;
|
|
1674
|
-
if (res.ok) {
|
|
1675
|
-
setSnap((current) => ({ ...current, requests: replaceRequest(current.requests, res.value) }));
|
|
1676
|
-
if (isTerminalStatus(res.value.status)) {
|
|
1677
|
-
if (res.value.status === "published") void load();
|
|
1678
|
-
return;
|
|
1679
|
-
}
|
|
1680
|
-
if (res.value.status === "in_review") return;
|
|
1681
|
-
}
|
|
1682
|
-
handle = setTimeout(() => void tick(), POLL_INTERVAL_MS);
|
|
1683
|
-
};
|
|
1684
|
-
let handle = setTimeout(() => void tick(), POLL_INTERVAL_MS);
|
|
1685
|
-
return () => {
|
|
1686
|
-
cancelled = true;
|
|
1687
|
-
clearTimeout(handle);
|
|
1688
|
-
};
|
|
1689
|
-
}, [controller, activeId, activeStatus, load, pollEpoch]);
|
|
1690
|
-
const createRequest = useCallback(
|
|
1691
|
-
async (idempotencyKey) => {
|
|
1692
|
-
if (!controller) return notReady();
|
|
1693
|
-
const res = await controller.createUploadRequest({ petRef, idempotencyKey });
|
|
1694
|
-
if (res.ok) setSnap((c) => ({ ...c, requests: replaceRequest(c.requests, res.value) }));
|
|
1695
|
-
return res;
|
|
1696
|
-
},
|
|
1697
|
-
[controller, petRef]
|
|
1698
|
-
);
|
|
1699
|
-
const uploadDocument = useCallback(
|
|
1700
|
-
async (requestId, file) => {
|
|
1701
|
-
if (!controller) return notReady();
|
|
1702
|
-
patch({ isUploading: true, uploadProgress: 0 });
|
|
1703
|
-
const res = await controller.uploadDocument({
|
|
1704
|
-
requestId,
|
|
1705
|
-
file,
|
|
1706
|
-
onProgress: (fraction) => patch({ uploadProgress: fraction })
|
|
1707
|
-
});
|
|
1708
|
-
patch({ isUploading: false, uploadProgress: null });
|
|
1709
|
-
if (res.ok) {
|
|
1710
|
-
const refreshed = await controller.getRequest(requestId);
|
|
1711
|
-
if (refreshed.ok) setSnap((c) => ({ ...c, requests: replaceRequest(c.requests, refreshed.value) }));
|
|
1712
|
-
}
|
|
1713
|
-
return res;
|
|
1714
|
-
},
|
|
1715
|
-
[controller, patch]
|
|
1716
|
-
);
|
|
1717
|
-
const grantConsent = useCallback(
|
|
1718
|
-
async (consentVersion, idempotencyKey) => {
|
|
1719
|
-
if (!controller) return notReady();
|
|
1720
|
-
const res = await controller.grantConsent({ petRef, consentVersion, idempotencyKey });
|
|
1721
|
-
if (res.ok) void load();
|
|
1722
|
-
return res;
|
|
1723
|
-
},
|
|
1724
|
-
[controller, petRef, load]
|
|
1725
|
-
);
|
|
1726
|
-
const revokeConsent = useCallback(async () => {
|
|
1727
|
-
if (!controller) return notReady();
|
|
1728
|
-
const res = await controller.revokeConsent(petRef);
|
|
1729
|
-
if (res.ok) {
|
|
1730
|
-
patch({ record: null, withheld: false, denialReason: "consent_required", consent: res.value });
|
|
1731
|
-
}
|
|
1732
|
-
return res;
|
|
1733
|
-
}, [controller, petRef, patch]);
|
|
1734
|
-
const refresh = useCallback(() => {
|
|
1735
|
-
void load();
|
|
1736
|
-
}, [load]);
|
|
1737
|
-
const status = selectStatus(snap, controller !== null);
|
|
1738
|
-
return useMemo(
|
|
1739
|
-
() => ({
|
|
1740
|
-
status,
|
|
1741
|
-
record: snap.record,
|
|
1742
|
-
requests: snap.requests,
|
|
1743
|
-
activeRequest,
|
|
1744
|
-
consent: snap.consent,
|
|
1745
|
-
error: snap.error,
|
|
1746
|
-
denialReason: snap.denialReason,
|
|
1747
|
-
withheld: snap.withheld,
|
|
1748
|
-
isUploading: snap.isUploading,
|
|
1749
|
-
uploadProgress: snap.uploadProgress,
|
|
1750
|
-
createRequest,
|
|
1751
|
-
uploadDocument,
|
|
1752
|
-
grantConsent,
|
|
1753
|
-
revokeConsent,
|
|
1754
|
-
refresh
|
|
1755
|
-
}),
|
|
1756
|
-
[status, snap, activeRequest, createRequest, uploadDocument, grantConsent, revokeConsent, refresh]
|
|
1757
|
-
);
|
|
1758
|
-
}
|
|
1759
|
-
function selectStatus(snap, hasController) {
|
|
1760
|
-
if (snap.loading || !hasController) return "loading";
|
|
1761
|
-
if (snap.withheld || snap.denialReason !== null || snap.error !== null) return "error";
|
|
1762
|
-
if (snap.record !== null && !snap.record.isEmpty) return "populated";
|
|
1763
|
-
if (snap.requests.length > 0) return "populated";
|
|
1764
|
-
return "empty";
|
|
1765
|
-
}
|
|
1766
|
-
function newestRequest(requests) {
|
|
1767
|
-
if (requests.length === 0) return null;
|
|
1768
|
-
let newest = requests[0];
|
|
1769
|
-
for (const r of requests) if (r.updatedAt > newest.updatedAt) newest = r;
|
|
1770
|
-
return newest;
|
|
1771
|
-
}
|
|
1772
|
-
function replaceRequest(requests, next) {
|
|
1773
|
-
const filtered = requests.filter((r) => r.id !== next.id);
|
|
1774
|
-
return [next, ...filtered];
|
|
1775
|
-
}
|
|
1776
|
-
function consentDenial(res) {
|
|
1777
|
-
return res.ok ? "consent_required" : recordsDenialReasonOf(res.error) ?? "consent_required";
|
|
1778
|
-
}
|
|
1779
|
-
function withheldSentinel() {
|
|
1780
|
-
return makeEverfurError("internalError", { retryable: false });
|
|
1781
|
-
}
|
|
1782
|
-
function notReady() {
|
|
1783
|
-
return { ok: false, error: makeEverfurError("internalError", { retryable: true }) };
|
|
1784
|
-
}
|
|
1785
|
-
function useCapability(name) {
|
|
1786
|
-
const { runtime } = useEverfurContext();
|
|
1787
|
-
const store = runtime.entitlements;
|
|
1788
|
-
const snapshot = useSyncExternalStore(
|
|
1789
|
-
store.subscribe,
|
|
1790
|
-
store.getSnapshot,
|
|
1791
|
-
store.getSnapshot
|
|
1792
|
-
);
|
|
1793
|
-
return useMemo(
|
|
1794
|
-
() => decideCapability(name, snapshot.decisions, { isPending: snapshot.isPending }),
|
|
1795
|
-
[name, snapshot]
|
|
1796
|
-
);
|
|
1797
|
-
}
|
|
1798
|
-
var MIN_OFFSTATE_HEIGHT = 48;
|
|
1799
|
-
function selectView(decision) {
|
|
1800
|
-
if (decision.isPending) return "pending";
|
|
1801
|
-
return decision.enabled ? "enabled" : "disabled";
|
|
1802
|
-
}
|
|
1803
|
-
function CapabilityGate(props) {
|
|
1804
|
-
const { capability, children, renderDisabled, renderPending, style } = props;
|
|
1805
|
-
const decision = useCapability(capability);
|
|
1806
|
-
const view = useMemo(() => selectView(decision), [decision]);
|
|
1807
|
-
switch (view) {
|
|
1808
|
-
case "enabled":
|
|
1809
|
-
return children;
|
|
1810
|
-
case "pending":
|
|
1811
|
-
return renderPending ? renderPending() : /* @__PURE__ */ jsx(PendingSkeleton, { capability, style });
|
|
1812
|
-
case "disabled":
|
|
1813
|
-
return renderDisabled ? renderDisabled(decision) : /* @__PURE__ */ jsx(OffState, { decision, style });
|
|
1814
|
-
default:
|
|
1815
|
-
return assertNever(view);
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1818
|
-
function PendingSkeleton({
|
|
1819
|
-
capability,
|
|
1820
|
-
style
|
|
1821
|
-
}) {
|
|
1822
|
-
const theme = useEverfurTheme();
|
|
1823
|
-
const styles = useMemo(() => makeStyles(theme), [theme]);
|
|
1824
|
-
return /* @__PURE__ */ jsx(
|
|
1825
|
-
View,
|
|
1826
|
-
{
|
|
1827
|
-
style: [styles.offstate, style],
|
|
1828
|
-
accessible: true,
|
|
1829
|
-
accessibilityState: { busy: true },
|
|
1830
|
-
accessibilityLabel: `Loading ${capability}`,
|
|
1831
|
-
children: /* @__PURE__ */ jsx(View, { style: styles.skeletonBar })
|
|
1832
|
-
}
|
|
1833
|
-
);
|
|
1834
|
-
}
|
|
1835
|
-
function OffState({
|
|
1836
|
-
decision,
|
|
1837
|
-
style
|
|
1838
|
-
}) {
|
|
1839
|
-
const theme = useEverfurTheme();
|
|
1840
|
-
const styles = useMemo(() => makeStyles(theme), [theme]);
|
|
1841
|
-
const message = decision.disabled?.reason ?? "";
|
|
1842
|
-
return /* @__PURE__ */ jsx(
|
|
1843
|
-
View,
|
|
1844
|
-
{
|
|
1845
|
-
style: [styles.offstate, style],
|
|
1846
|
-
accessible: true,
|
|
1847
|
-
accessibilityRole: "text",
|
|
1848
|
-
accessibilityLabel: message,
|
|
1849
|
-
children: message.length > 0 ? /* @__PURE__ */ jsx(Text, { style: styles.offstateText, children: message }) : null
|
|
1850
|
-
}
|
|
1851
|
-
);
|
|
1852
|
-
}
|
|
1853
|
-
function makeStyles(theme) {
|
|
1854
|
-
const { color, space, radius, type } = theme;
|
|
1855
|
-
return StyleSheet.create({
|
|
1856
|
-
// A deliberate cream card with a soft brand hairline, never a bare grey slab.
|
|
1857
|
-
offstate: {
|
|
1858
|
-
minHeight: MIN_OFFSTATE_HEIGHT,
|
|
1859
|
-
justifyContent: "center",
|
|
1860
|
-
paddingHorizontal: space.lg,
|
|
1861
|
-
paddingVertical: space.md,
|
|
1862
|
-
backgroundColor: color.surfaceCream,
|
|
1863
|
-
borderRadius: radius.md,
|
|
1864
|
-
borderWidth: StyleSheet.hairlineWidth,
|
|
1865
|
-
borderColor: color.brandBorder
|
|
1866
|
-
},
|
|
1867
|
-
offstateText: {
|
|
1868
|
-
fontFamily: type.family,
|
|
1869
|
-
fontSize: type.size.body,
|
|
1870
|
-
lineHeight: Math.round(type.size.body * type.lineHeight.normal),
|
|
1871
|
-
color: color.text.muted
|
|
1872
|
-
},
|
|
1873
|
-
// A soft green shimmer bar (brand wash) that stays legible on the cream card in both light and dark,
|
|
1874
|
-
// where the neutral `skeleton` token would collide with the dark cream surface.
|
|
1875
|
-
skeletonBar: {
|
|
1876
|
-
height: space.md,
|
|
1877
|
-
borderRadius: radius.xs,
|
|
1878
|
-
backgroundColor: color.brandSofter
|
|
1879
|
-
}
|
|
1880
|
-
});
|
|
1881
|
-
}
|
|
1882
|
-
var CLINICAL_DISCLAIMER = Object.freeze({
|
|
1883
|
-
title: "For educational use only",
|
|
1884
|
-
body: "Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."
|
|
1885
|
-
});
|
|
1886
|
-
function ClinicalDisclaimer(props) {
|
|
1887
|
-
const theme = useEverfurTheme();
|
|
1888
|
-
const styles = useMemo(() => makeStyles2(theme), [theme]);
|
|
1889
|
-
return /* @__PURE__ */ jsxs(
|
|
1890
|
-
View,
|
|
1891
|
-
{
|
|
1892
|
-
style: [styles.container, props.style],
|
|
1893
|
-
accessible: true,
|
|
1894
|
-
accessibilityRole: "text",
|
|
1895
|
-
accessibilityLabel: `${CLINICAL_DISCLAIMER.title}. ${CLINICAL_DISCLAIMER.body}`,
|
|
1896
|
-
children: [
|
|
1897
|
-
/* @__PURE__ */ jsx(Text, { style: styles.title, children: CLINICAL_DISCLAIMER.title }),
|
|
1898
|
-
/* @__PURE__ */ jsx(Text, { style: styles.body, children: CLINICAL_DISCLAIMER.body })
|
|
1899
|
-
]
|
|
1900
|
-
}
|
|
1901
|
-
);
|
|
1902
|
-
}
|
|
1903
|
-
function makeStyles2(theme) {
|
|
1904
|
-
const { color, space, type } = theme;
|
|
1905
|
-
return StyleSheet.create({
|
|
1906
|
-
container: {
|
|
1907
|
-
paddingHorizontal: space.lg,
|
|
1908
|
-
paddingVertical: space.md,
|
|
1909
|
-
borderTopWidth: StyleSheet.hairlineWidth,
|
|
1910
|
-
borderTopColor: color.borderHairlineGreen,
|
|
1911
|
-
backgroundColor: color.surfaceCream,
|
|
1912
|
-
gap: space.xs
|
|
1913
|
-
},
|
|
1914
|
-
title: {
|
|
1915
|
-
fontFamily: type.family,
|
|
1916
|
-
fontSize: type.size.caption,
|
|
1917
|
-
lineHeight: Math.round(type.size.caption * type.lineHeight.snug),
|
|
1918
|
-
color: color.text.secondary,
|
|
1919
|
-
fontWeight: type.weight.bold,
|
|
1920
|
-
letterSpacing: type.letterSpacing.eyebrow
|
|
1921
|
-
},
|
|
1922
|
-
body: {
|
|
1923
|
-
fontFamily: type.family,
|
|
1924
|
-
fontSize: type.size.caption,
|
|
1925
|
-
lineHeight: Math.round(type.size.caption * type.lineHeight.snug),
|
|
1926
|
-
color: color.text.muted,
|
|
1927
|
-
fontWeight: type.weight.regular
|
|
1928
|
-
}
|
|
1929
|
-
});
|
|
1930
|
-
}
|
|
1931
|
-
|
|
1932
|
-
// src/rn/records/format.ts
|
|
1933
|
-
function formatEntityValue(value, unit) {
|
|
1934
|
-
if (value === null) return "";
|
|
1935
|
-
return unit ? `${value} ${unit}` : value;
|
|
1936
|
-
}
|
|
1937
|
-
function formatShortDate(at) {
|
|
1938
|
-
if (at === null || at.length === 0) return "";
|
|
1939
|
-
const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(at);
|
|
1940
|
-
if (iso !== null) {
|
|
1941
|
-
const year = iso[1] ?? "";
|
|
1942
|
-
const month = iso[2] ?? "";
|
|
1943
|
-
const day = iso[3] ?? "";
|
|
1944
|
-
return `${Number(month)}/${Number(day)}/${year.slice(2)}`;
|
|
1945
|
-
}
|
|
1946
|
-
const ms = Date.parse(at);
|
|
1947
|
-
if (Number.isNaN(ms)) return at;
|
|
1948
|
-
const date = new Date(ms);
|
|
1949
|
-
return `${date.getUTCMonth() + 1}/${date.getUTCDate()}/${String(date.getUTCFullYear()).slice(2)}`;
|
|
1950
|
-
}
|
|
1951
|
-
var TINT_KEYS = ["brandSoft", "badgeBgPositive", "badgeBgCaution", "badgeBgNeutral"];
|
|
1952
|
-
function buildRows(entities, forwardLooking, documents) {
|
|
1953
|
-
const rows = [];
|
|
1954
|
-
const order = [];
|
|
1955
|
-
const byCategory = /* @__PURE__ */ new Map();
|
|
1956
|
-
for (const entity of entities) {
|
|
1957
|
-
const category = entity.category.trim();
|
|
1958
|
-
if (category.length === 0) continue;
|
|
1959
|
-
const bucket = byCategory.get(category);
|
|
1960
|
-
if (bucket === void 0) {
|
|
1961
|
-
order.push(category);
|
|
1962
|
-
byCategory.set(category, [entity]);
|
|
1963
|
-
} else {
|
|
1964
|
-
bucket.push(entity);
|
|
1965
|
-
}
|
|
1966
|
-
}
|
|
1967
|
-
for (const category of order) {
|
|
1968
|
-
const group = byCategory.get(category) ?? [];
|
|
1969
|
-
rows.push({
|
|
1970
|
-
id: `cat:${category}`,
|
|
1971
|
-
title: category,
|
|
1972
|
-
count: group.length,
|
|
1973
|
-
dateLabel: null,
|
|
1974
|
-
entities: group,
|
|
1975
|
-
detail: null
|
|
1976
|
-
});
|
|
1977
|
-
}
|
|
1978
|
-
forwardLooking.forEach((item, index) => {
|
|
1979
|
-
const title = item.title.trim();
|
|
1980
|
-
if (title.length === 0) return;
|
|
1981
|
-
const detail = item.detail !== null && item.detail.length > 0 ? item.detail : null;
|
|
1982
|
-
rows.push({
|
|
1983
|
-
id: `fwd:${index}`,
|
|
1984
|
-
title,
|
|
1985
|
-
count: null,
|
|
1986
|
-
dateLabel: formatShortDate(item.dueAt),
|
|
1987
|
-
entities: null,
|
|
1988
|
-
detail
|
|
1989
|
-
});
|
|
1990
|
-
});
|
|
1991
|
-
for (const doc of Object.values(documents)) {
|
|
1992
|
-
const title = doc.title !== null ? doc.title.trim() : "";
|
|
1993
|
-
if (title.length === 0) continue;
|
|
1994
|
-
rows.push({
|
|
1995
|
-
id: `doc:${doc.docId}`,
|
|
1996
|
-
title,
|
|
1997
|
-
count: null,
|
|
1998
|
-
dateLabel: formatShortDate(doc.receivedAt),
|
|
1999
|
-
entities: null,
|
|
2000
|
-
detail: null
|
|
2001
|
-
});
|
|
2002
|
-
}
|
|
2003
|
-
return rows;
|
|
2004
|
-
}
|
|
2005
|
-
function RecordNavCards({
|
|
2006
|
-
entities,
|
|
2007
|
-
forwardLooking,
|
|
2008
|
-
documents,
|
|
2009
|
-
testID
|
|
2010
|
-
}) {
|
|
2011
|
-
const styles = useStyles();
|
|
2012
|
-
const rows = useMemo(
|
|
2013
|
-
() => buildRows(entities, forwardLooking, documents),
|
|
2014
|
-
[entities, forwardLooking, documents]
|
|
2015
|
-
);
|
|
2016
|
-
const [expanded, setExpanded] = useState(() => /* @__PURE__ */ new Set());
|
|
2017
|
-
if (rows.length === 0) return null;
|
|
2018
|
-
const toggle = (id) => {
|
|
2019
|
-
setExpanded((current) => {
|
|
2020
|
-
const next = new Set(current);
|
|
2021
|
-
if (next.has(id)) next.delete(id);
|
|
2022
|
-
else next.add(id);
|
|
2023
|
-
return next;
|
|
2024
|
-
});
|
|
2025
|
-
};
|
|
2026
|
-
return /* @__PURE__ */ jsx(View, { style: styles.stack, testID, children: rows.map((row, index) => {
|
|
2027
|
-
const tintKey = TINT_KEYS[index % TINT_KEYS.length] ?? "brandSoft";
|
|
2028
|
-
const tint = styles.tints[tintKey];
|
|
2029
|
-
const body = row.entities ?? (row.detail !== null ? row.detail : null);
|
|
2030
|
-
const expandable = row.entities !== null || row.detail !== null;
|
|
2031
|
-
const isOpen = expanded.has(row.id);
|
|
2032
|
-
const trailing = row.count !== null ? `${row.count}` : row.dateLabel !== null ? row.dateLabel : null;
|
|
2033
|
-
const a11y = [row.title, trailing].filter((s) => s !== null && s.length > 0).join(", ");
|
|
2034
|
-
return /* @__PURE__ */ jsxs(View, { testID: testID ? `${testID}-row-${index}` : void 0, children: [
|
|
2035
|
-
/* @__PURE__ */ jsx(
|
|
2036
|
-
NavCard,
|
|
2037
|
-
{
|
|
2038
|
-
styles,
|
|
2039
|
-
tint,
|
|
2040
|
-
title: row.title,
|
|
2041
|
-
trailing,
|
|
2042
|
-
expandable,
|
|
2043
|
-
isOpen,
|
|
2044
|
-
a11y,
|
|
2045
|
-
onPress: expandable ? () => toggle(row.id) : void 0
|
|
2046
|
-
}
|
|
2047
|
-
),
|
|
2048
|
-
expandable && isOpen ? /* @__PURE__ */ jsx(NavCardBody, { styles, body }) : null
|
|
2049
|
-
] }, row.id);
|
|
2050
|
-
}) });
|
|
2051
|
-
}
|
|
2052
|
-
function NavCard({
|
|
2053
|
-
styles,
|
|
2054
|
-
tint,
|
|
2055
|
-
title,
|
|
2056
|
-
trailing,
|
|
2057
|
-
expandable,
|
|
2058
|
-
isOpen,
|
|
2059
|
-
a11y,
|
|
2060
|
-
onPress
|
|
2061
|
-
}) {
|
|
2062
|
-
return /* @__PURE__ */ jsxs(
|
|
2063
|
-
Pressable,
|
|
2064
|
-
{
|
|
2065
|
-
onPress,
|
|
2066
|
-
disabled: onPress === void 0,
|
|
2067
|
-
accessibilityRole: "button",
|
|
2068
|
-
accessibilityLabel: a11y,
|
|
2069
|
-
accessibilityState: { expanded: expandable ? isOpen : void 0, disabled: onPress === void 0 },
|
|
2070
|
-
style: [styles.card, tint],
|
|
2071
|
-
children: [
|
|
2072
|
-
/* @__PURE__ */ jsx(View, { style: styles.iconChip }),
|
|
2073
|
-
/* @__PURE__ */ jsx(Text, { style: styles.title, numberOfLines: 2, children: title }),
|
|
2074
|
-
/* @__PURE__ */ jsxs(View, { style: styles.trailing, children: [
|
|
2075
|
-
trailing !== null ? /* @__PURE__ */ jsx(View, { style: styles.pill, children: /* @__PURE__ */ jsx(Text, { style: styles.pillLabel, numberOfLines: 1, children: trailing }) }) : null,
|
|
2076
|
-
expandable ? /* @__PURE__ */ jsx(View, { style: isOpen ? styles.chevronOpen : styles.chevron }) : null
|
|
2077
|
-
] })
|
|
2078
|
-
]
|
|
2079
|
-
}
|
|
2080
|
-
);
|
|
2081
|
-
}
|
|
2082
|
-
function NavCardBody({
|
|
2083
|
-
styles,
|
|
2084
|
-
body
|
|
2085
|
-
}) {
|
|
2086
|
-
if (body === null) return null;
|
|
2087
|
-
if (typeof body === "string") {
|
|
2088
|
-
return /* @__PURE__ */ jsx(View, { style: styles.body, children: /* @__PURE__ */ jsx(Text, { style: styles.detailText, children: body }) });
|
|
2089
|
-
}
|
|
2090
|
-
return /* @__PURE__ */ jsx(View, { style: styles.body, children: body.map((entity) => /* @__PURE__ */ jsxs(View, { style: styles.factRow, children: [
|
|
2091
|
-
/* @__PURE__ */ jsx(Text, { style: styles.factLabel, numberOfLines: 2, children: entity.label }),
|
|
2092
|
-
/* @__PURE__ */ jsx(Text, { style: styles.factValue, numberOfLines: 2, children: formatEntityValue(entity.value, entity.unit) })
|
|
2093
|
-
] }, entity.key)) });
|
|
2094
|
-
}
|
|
2095
|
-
function useStyles() {
|
|
2096
|
-
const theme = useEverfurTheme();
|
|
2097
|
-
return useMemo(() => makeStyles3(theme), [theme]);
|
|
2098
|
-
}
|
|
2099
|
-
function makeStyles3(theme) {
|
|
2100
|
-
const { color, space, radius, type } = theme;
|
|
2101
|
-
const { size, lineHeight, weight, letterSpacing, family } = type;
|
|
2102
|
-
const lh = (fontSize, multiplier) => Math.round(fontSize * multiplier);
|
|
2103
|
-
const hairline = StyleSheet.hairlineWidth;
|
|
2104
|
-
const boldWeight = weight.bold;
|
|
2105
|
-
const mediumWeight = weight.medium;
|
|
2106
|
-
const rowMinHeight = space.xxl + space.xl;
|
|
2107
|
-
const chipSize = space.xl;
|
|
2108
|
-
const chevronSize = space.sm;
|
|
2109
|
-
const chevronStroke = space.xs / 2;
|
|
2110
|
-
const softShadow = {
|
|
2111
|
-
shadowColor: color.brand,
|
|
2112
|
-
shadowOffset: { width: 0, height: space.xs },
|
|
2113
|
-
shadowRadius: space.sm,
|
|
2114
|
-
shadowOpacity: 0.06,
|
|
2115
|
-
elevation: space.xs
|
|
2116
|
-
};
|
|
2117
|
-
const chevronBase = {
|
|
2118
|
-
width: chevronSize,
|
|
2119
|
-
height: chevronSize,
|
|
2120
|
-
borderTopWidth: chevronStroke,
|
|
2121
|
-
borderRightWidth: chevronStroke,
|
|
2122
|
-
borderColor: color.brand
|
|
2123
|
-
};
|
|
2124
|
-
return {
|
|
2125
|
-
tints: {
|
|
2126
|
-
brandSoft: { backgroundColor: color.brandSoft },
|
|
2127
|
-
badgeBgPositive: { backgroundColor: color.badgeBgPositive },
|
|
2128
|
-
badgeBgCaution: { backgroundColor: color.badgeBgCaution },
|
|
2129
|
-
badgeBgNeutral: { backgroundColor: color.badgeBgNeutral }
|
|
2130
|
-
},
|
|
2131
|
-
...StyleSheet.create({
|
|
2132
|
-
stack: { gap: space.sm },
|
|
2133
|
-
card: {
|
|
2134
|
-
flexDirection: "row",
|
|
2135
|
-
alignItems: "center",
|
|
2136
|
-
gap: space.md,
|
|
2137
|
-
minHeight: rowMinHeight,
|
|
2138
|
-
paddingHorizontal: space.lg,
|
|
2139
|
-
paddingVertical: space.md,
|
|
2140
|
-
borderRadius: radius.md,
|
|
2141
|
-
borderWidth: hairline,
|
|
2142
|
-
borderColor: color.brandBorder,
|
|
2143
|
-
...softShadow
|
|
2144
|
-
},
|
|
2145
|
-
iconChip: {
|
|
2146
|
-
width: chipSize,
|
|
2147
|
-
height: chipSize,
|
|
2148
|
-
borderRadius: radius.sm,
|
|
2149
|
-
backgroundColor: color.brand
|
|
2150
|
-
},
|
|
2151
|
-
title: {
|
|
2152
|
-
flex: 1,
|
|
2153
|
-
fontFamily: family,
|
|
2154
|
-
fontSize: size.subtitle,
|
|
2155
|
-
lineHeight: lh(size.subtitle, lineHeight.snug),
|
|
2156
|
-
color: color.text.secondary,
|
|
2157
|
-
fontWeight: boldWeight,
|
|
2158
|
-
letterSpacing: letterSpacing.tight
|
|
2159
|
-
},
|
|
2160
|
-
trailing: {
|
|
2161
|
-
flexDirection: "row",
|
|
2162
|
-
alignItems: "center",
|
|
2163
|
-
gap: space.sm
|
|
2164
|
-
},
|
|
2165
|
-
pill: {
|
|
2166
|
-
minWidth: space.xl,
|
|
2167
|
-
alignItems: "center",
|
|
2168
|
-
justifyContent: "center",
|
|
2169
|
-
paddingHorizontal: space.sm,
|
|
2170
|
-
paddingVertical: space.xs,
|
|
2171
|
-
borderRadius: radius.pill,
|
|
2172
|
-
backgroundColor: color.surfaceCream,
|
|
2173
|
-
borderWidth: hairline,
|
|
2174
|
-
borderColor: color.brandBorder
|
|
2175
|
-
},
|
|
2176
|
-
pillLabel: {
|
|
2177
|
-
fontFamily: family,
|
|
2178
|
-
fontSize: size.caption,
|
|
2179
|
-
lineHeight: lh(size.caption, lineHeight.tight),
|
|
2180
|
-
color: color.text.secondary,
|
|
2181
|
-
fontWeight: boldWeight
|
|
2182
|
-
},
|
|
2183
|
-
chevron: { ...chevronBase, transform: [{ rotate: "45deg" }] },
|
|
2184
|
-
chevronOpen: { ...chevronBase, transform: [{ rotate: "135deg" }] },
|
|
2185
|
-
body: {
|
|
2186
|
-
gap: space.xs,
|
|
2187
|
-
marginTop: space.xs,
|
|
2188
|
-
paddingHorizontal: space.lg,
|
|
2189
|
-
paddingVertical: space.md,
|
|
2190
|
-
borderRadius: radius.sm,
|
|
2191
|
-
backgroundColor: color.surfaceCream,
|
|
2192
|
-
borderWidth: hairline,
|
|
2193
|
-
borderColor: color.brandBorder
|
|
2194
|
-
},
|
|
2195
|
-
factRow: {
|
|
2196
|
-
flexDirection: "row",
|
|
2197
|
-
justifyContent: "space-between",
|
|
2198
|
-
gap: space.md,
|
|
2199
|
-
paddingVertical: space.xs,
|
|
2200
|
-
borderBottomWidth: hairline,
|
|
2201
|
-
borderBottomColor: color.borderHairlineGreen
|
|
2202
|
-
},
|
|
2203
|
-
factLabel: {
|
|
2204
|
-
fontFamily: family,
|
|
2205
|
-
fontSize: size.body,
|
|
2206
|
-
lineHeight: lh(size.body, lineHeight.normal),
|
|
2207
|
-
color: color.text.muted,
|
|
2208
|
-
flexShrink: 1
|
|
2209
|
-
},
|
|
2210
|
-
factValue: {
|
|
2211
|
-
fontFamily: family,
|
|
2212
|
-
fontSize: size.body,
|
|
2213
|
-
lineHeight: lh(size.body, lineHeight.normal),
|
|
2214
|
-
color: color.text.primary,
|
|
2215
|
-
fontWeight: mediumWeight,
|
|
2216
|
-
textAlign: "right",
|
|
2217
|
-
flexShrink: 1
|
|
2218
|
-
},
|
|
2219
|
-
detailText: {
|
|
2220
|
-
fontFamily: family,
|
|
2221
|
-
fontSize: size.body,
|
|
2222
|
-
lineHeight: lh(size.body, lineHeight.normal),
|
|
2223
|
-
color: color.text.secondary
|
|
2224
|
-
}
|
|
2225
|
-
})
|
|
2226
|
-
};
|
|
2227
|
-
}
|
|
2228
|
-
function pct(value) {
|
|
2229
|
-
return `${value}%`;
|
|
2230
|
-
}
|
|
2231
|
-
function isFinitePoint(point) {
|
|
2232
|
-
return point.value !== null && Number.isFinite(point.value);
|
|
2233
|
-
}
|
|
2234
|
-
function pointDisplay(point) {
|
|
2235
|
-
if (point.display !== null && point.display.length > 0) return point.display;
|
|
2236
|
-
return point.value !== null ? String(point.value) : "";
|
|
2237
|
-
}
|
|
2238
|
-
function buildTrendModel(series) {
|
|
2239
|
-
const primary = series.find((s) => s.points.some(isFinitePoint));
|
|
2240
|
-
if (primary === void 0) return null;
|
|
2241
|
-
const numeric = primary.points.filter(isFinitePoint);
|
|
2242
|
-
const first = numeric[0];
|
|
2243
|
-
if (first === void 0) return null;
|
|
2244
|
-
const values = numeric.map((p) => p.value);
|
|
2245
|
-
let lo = Math.min(...values);
|
|
2246
|
-
let hi = Math.max(...values);
|
|
2247
|
-
if (lo === hi) {
|
|
2248
|
-
lo -= 1;
|
|
2249
|
-
hi += 1;
|
|
2250
|
-
}
|
|
2251
|
-
const pad = (hi - lo) * 0.18;
|
|
2252
|
-
const yMin = lo - pad;
|
|
2253
|
-
const yMax = hi + pad;
|
|
2254
|
-
const span = yMax - yMin;
|
|
2255
|
-
const xInset = 6;
|
|
2256
|
-
const count = numeric.length;
|
|
2257
|
-
const points = numeric.map((p, index) => ({
|
|
2258
|
-
xPct: count <= 1 ? 50 : xInset + index / (count - 1) * (100 - 2 * xInset),
|
|
2259
|
-
// y in percent DOWN from the top: the max of the domain sits at 0%, the min at 100%.
|
|
2260
|
-
yPct: (yMax - p.value) / span * 100
|
|
2261
|
-
}));
|
|
2262
|
-
const bandTopPct = (yMax - hi) / span * 100;
|
|
2263
|
-
const bandBottomPct = (yMax - lo) / span * 100;
|
|
2264
|
-
const minPoint = numeric.reduce((acc, p) => p.value < acc.value ? p : acc, first);
|
|
2265
|
-
const maxPoint = numeric.reduce((acc, p) => p.value > acc.value ? p : acc, first);
|
|
2266
|
-
const lastNumeric = numeric[numeric.length - 1] ?? first;
|
|
2267
|
-
const latest = primary.points[primary.points.length - 1] ?? lastNumeric;
|
|
2268
|
-
const latestDisplay = pointDisplay(latest);
|
|
2269
|
-
const heroDisplay = latestDisplay.length > 0 ? latestDisplay : pointDisplay(lastNumeric);
|
|
2270
|
-
return {
|
|
2271
|
-
label: primary.label,
|
|
2272
|
-
heroDisplay,
|
|
2273
|
-
minDisplay: pointDisplay(minPoint),
|
|
2274
|
-
maxDisplay: pointDisplay(maxPoint),
|
|
2275
|
-
firstDate: formatShortDate(primary.points[0]?.at ?? null),
|
|
2276
|
-
lastDate: formatShortDate(latest.at),
|
|
2277
|
-
points,
|
|
2278
|
-
bandTopPct,
|
|
2279
|
-
bandBottomPct
|
|
2280
|
-
};
|
|
2281
|
-
}
|
|
2282
|
-
function TrendRangeCard({ series, testID }) {
|
|
2283
|
-
const styles = useStyles2();
|
|
2284
|
-
const model = useMemo(() => buildTrendModel(series), [series]);
|
|
2285
|
-
if (model === null) return null;
|
|
2286
|
-
const summary = model.heroDisplay.length > 0 ? `${model.label}, ${model.heroDisplay}` : model.label;
|
|
2287
|
-
const bandHeightPct = Math.max(0, model.bandBottomPct - model.bandTopPct);
|
|
2288
|
-
return /* @__PURE__ */ jsxs(View, { style: styles.card, testID, children: [
|
|
2289
|
-
/* @__PURE__ */ jsxs(View, { accessible: true, accessibilityRole: "text", accessibilityLabel: summary, children: [
|
|
2290
|
-
/* @__PURE__ */ jsx(Text, { style: styles.eyebrow, numberOfLines: 1, children: model.label }),
|
|
2291
|
-
model.heroDisplay.length > 0 ? /* @__PURE__ */ jsx(Text, { style: styles.hero, numberOfLines: 1, children: model.heroDisplay }) : null
|
|
2292
|
-
] }),
|
|
2293
|
-
/* @__PURE__ */ jsxs(
|
|
2294
|
-
View,
|
|
2295
|
-
{
|
|
2296
|
-
style: styles.plot,
|
|
2297
|
-
accessibilityElementsHidden: true,
|
|
2298
|
-
importantForAccessibility: "no-hide-descendants",
|
|
2299
|
-
children: [
|
|
2300
|
-
model.points.map((p, index) => /* @__PURE__ */ jsx(View, { style: [styles.guide, { left: pct(p.xPct) }] }, `g-${index}`)),
|
|
2301
|
-
/* @__PURE__ */ jsx(View, { style: [styles.band, { top: pct(model.bandTopPct), height: pct(bandHeightPct) }] }),
|
|
2302
|
-
model.points.map((p, index) => {
|
|
2303
|
-
const latest = index === model.points.length - 1;
|
|
2304
|
-
return /* @__PURE__ */ jsx(
|
|
2305
|
-
View,
|
|
2306
|
-
{
|
|
2307
|
-
style: [styles.point, latest ? styles.pointLatest : null, { left: pct(p.xPct), top: pct(p.yPct) }]
|
|
2308
|
-
},
|
|
2309
|
-
`pt-${index}`
|
|
2310
|
-
);
|
|
2311
|
-
}),
|
|
2312
|
-
model.maxDisplay.length > 0 ? /* @__PURE__ */ jsx(Text, { style: [styles.edgeLabel, { top: pct(model.bandTopPct) }], numberOfLines: 1, children: model.maxDisplay }) : null,
|
|
2313
|
-
model.minDisplay.length > 0 ? /* @__PURE__ */ jsx(Text, { style: [styles.edgeLabel, { top: pct(model.bandBottomPct) }], numberOfLines: 1, children: model.minDisplay }) : null
|
|
2314
|
-
]
|
|
2315
|
-
}
|
|
2316
|
-
),
|
|
2317
|
-
model.firstDate.length > 0 || model.lastDate.length > 0 ? /* @__PURE__ */ jsxs(View, { style: styles.dates, children: [
|
|
2318
|
-
/* @__PURE__ */ jsx(Text, { style: styles.dateLabel, children: model.firstDate }),
|
|
2319
|
-
/* @__PURE__ */ jsx(Text, { style: styles.dateLabel, children: model.lastDate })
|
|
2320
|
-
] }) : null
|
|
2321
|
-
] });
|
|
2322
|
-
}
|
|
2323
|
-
function useStyles2() {
|
|
2324
|
-
const theme = useEverfurTheme();
|
|
2325
|
-
return useMemo(() => makeStyles4(theme), [theme]);
|
|
2326
|
-
}
|
|
2327
|
-
function makeStyles4(theme) {
|
|
2328
|
-
const { color, space, radius, type } = theme;
|
|
2329
|
-
const { size, lineHeight, weight, letterSpacing, family } = type;
|
|
2330
|
-
const lh = (fontSize, multiplier) => Math.round(fontSize * multiplier);
|
|
2331
|
-
const hairline = StyleSheet.hairlineWidth;
|
|
2332
|
-
const boldWeight = weight.bold;
|
|
2333
|
-
const mediumWeight = weight.medium;
|
|
2334
|
-
const plotHeight = space.xxl * 3;
|
|
2335
|
-
const dotSize = space.sm;
|
|
2336
|
-
const dotOffset = -(dotSize / 2);
|
|
2337
|
-
const bandInset = space.xs;
|
|
2338
|
-
const softShadow = {
|
|
2339
|
-
shadowColor: color.brand,
|
|
2340
|
-
shadowOffset: { width: 0, height: space.xs },
|
|
2341
|
-
shadowRadius: space.sm,
|
|
2342
|
-
shadowOpacity: 0.08,
|
|
2343
|
-
elevation: space.xs
|
|
2344
|
-
};
|
|
2345
|
-
return StyleSheet.create({
|
|
2346
|
-
card: {
|
|
2347
|
-
gap: space.sm,
|
|
2348
|
-
padding: space.lg,
|
|
2349
|
-
borderRadius: radius.md,
|
|
2350
|
-
backgroundColor: color.surfaceCream,
|
|
2351
|
-
borderWidth: hairline,
|
|
2352
|
-
borderColor: color.brandBorder,
|
|
2353
|
-
...softShadow
|
|
2354
|
-
},
|
|
2355
|
-
eyebrow: {
|
|
2356
|
-
fontFamily: family,
|
|
2357
|
-
fontSize: size.caption,
|
|
2358
|
-
lineHeight: lh(size.caption, lineHeight.normal),
|
|
2359
|
-
color: color.text.muted,
|
|
2360
|
-
letterSpacing: letterSpacing.eyebrow,
|
|
2361
|
-
textTransform: "uppercase"
|
|
2362
|
-
},
|
|
2363
|
-
hero: {
|
|
2364
|
-
fontFamily: family,
|
|
2365
|
-
fontSize: size.verdict,
|
|
2366
|
-
lineHeight: lh(size.verdict, lineHeight.tight),
|
|
2367
|
-
color: color.text.primary,
|
|
2368
|
-
fontWeight: boldWeight,
|
|
2369
|
-
letterSpacing: letterSpacing.tight
|
|
2370
|
-
},
|
|
2371
|
-
plot: {
|
|
2372
|
-
position: "relative",
|
|
2373
|
-
height: plotHeight,
|
|
2374
|
-
marginTop: space.xs
|
|
2375
|
-
},
|
|
2376
|
-
guide: {
|
|
2377
|
-
position: "absolute",
|
|
2378
|
-
top: 0,
|
|
2379
|
-
bottom: 0,
|
|
2380
|
-
width: hairline,
|
|
2381
|
-
backgroundColor: color.borderHairlineGreen
|
|
2382
|
-
},
|
|
2383
|
-
band: {
|
|
2384
|
-
position: "absolute",
|
|
2385
|
-
left: bandInset,
|
|
2386
|
-
right: space.xs,
|
|
2387
|
-
borderRadius: radius.sm,
|
|
2388
|
-
backgroundColor: color.brandSoft
|
|
2389
|
-
},
|
|
2390
|
-
point: {
|
|
2391
|
-
position: "absolute",
|
|
2392
|
-
width: dotSize,
|
|
2393
|
-
height: dotSize,
|
|
2394
|
-
marginLeft: dotOffset,
|
|
2395
|
-
marginTop: dotOffset,
|
|
2396
|
-
borderRadius: radius.pill,
|
|
2397
|
-
backgroundColor: color.brand,
|
|
2398
|
-
borderWidth: hairline,
|
|
2399
|
-
borderColor: color.surfaceCream
|
|
2400
|
-
},
|
|
2401
|
-
pointLatest: {
|
|
2402
|
-
backgroundColor: color.accent,
|
|
2403
|
-
borderColor: color.onAccent
|
|
2404
|
-
},
|
|
2405
|
-
edgeLabel: {
|
|
2406
|
-
position: "absolute",
|
|
2407
|
-
right: 0,
|
|
2408
|
-
marginTop: -space.sm,
|
|
2409
|
-
fontFamily: family,
|
|
2410
|
-
fontSize: size.tiny,
|
|
2411
|
-
lineHeight: lh(size.tiny, lineHeight.tight),
|
|
2412
|
-
color: color.text.muted,
|
|
2413
|
-
fontWeight: mediumWeight
|
|
2414
|
-
},
|
|
2415
|
-
dates: {
|
|
2416
|
-
flexDirection: "row",
|
|
2417
|
-
justifyContent: "space-between"
|
|
2418
|
-
},
|
|
2419
|
-
dateLabel: {
|
|
2420
|
-
fontFamily: family,
|
|
2421
|
-
fontSize: size.tiny,
|
|
2422
|
-
lineHeight: lh(size.tiny, lineHeight.normal),
|
|
2423
|
-
color: color.text.muted
|
|
2424
|
-
}
|
|
2425
|
-
});
|
|
2426
|
-
}
|
|
2427
|
-
var SPINNER_DELAY_MS = 300;
|
|
2428
|
-
function EverfurRecords(props) {
|
|
2429
|
-
const { petRef, controller, onPickDocument, consentVersion, style } = props;
|
|
2430
|
-
return /* @__PURE__ */ jsx(CapabilityGate, { capability: "records", style, children: /* @__PURE__ */ jsx(
|
|
2431
|
-
RecordsBody,
|
|
2432
|
-
{
|
|
2433
|
-
petRef,
|
|
2434
|
-
controller,
|
|
2435
|
-
onPickDocument,
|
|
2436
|
-
consentVersion,
|
|
2437
|
-
style
|
|
2438
|
-
}
|
|
2439
|
-
) });
|
|
2440
|
-
}
|
|
2441
|
-
function RecordsBody({
|
|
2442
|
-
petRef,
|
|
2443
|
-
controller,
|
|
2444
|
-
onPickDocument,
|
|
2445
|
-
consentVersion,
|
|
2446
|
-
style
|
|
2447
|
-
}) {
|
|
2448
|
-
const styles = useStyles3();
|
|
2449
|
-
const recordsOpts = useMemo(
|
|
2450
|
-
() => controller ? { petRef, controller } : { petRef },
|
|
2451
|
-
[petRef, controller]
|
|
2452
|
-
);
|
|
2453
|
-
const records = useEverfurRecords(recordsOpts);
|
|
2454
|
-
const view = records.status;
|
|
2455
|
-
const canUpload = onPickDocument !== void 0;
|
|
2456
|
-
const onUpload = useMemo(
|
|
2457
|
-
() => makeUploadHandler(records, onPickDocument),
|
|
2458
|
-
[records, onPickDocument]
|
|
2459
|
-
);
|
|
2460
|
-
const onGrant = useMemo(
|
|
2461
|
-
() => makeGrantHandler(records, consentVersion),
|
|
2462
|
-
[records, consentVersion]
|
|
2463
|
-
);
|
|
2464
|
-
const canGrant = useMemo(
|
|
2465
|
-
() => (consentVersion ?? records.consent?.version ?? "").length > 0,
|
|
2466
|
-
[consentVersion, records.consent]
|
|
2467
|
-
);
|
|
2468
|
-
return /* @__PURE__ */ jsxs(View, { style: [styles.container, style], children: [
|
|
2469
|
-
/* @__PURE__ */ jsx(View, { style: styles.body, children: renderView(view, records, onUpload, onGrant, canUpload, canGrant) }),
|
|
2470
|
-
/* @__PURE__ */ jsx(ClinicalDisclaimer, {})
|
|
2471
|
-
] });
|
|
2472
|
-
}
|
|
2473
|
-
function renderView(view, records, onUpload, onGrant, canUpload, canGrant) {
|
|
2474
|
-
switch (view) {
|
|
2475
|
-
case "loading":
|
|
2476
|
-
return /* @__PURE__ */ jsx(LoadingState, {});
|
|
2477
|
-
case "empty":
|
|
2478
|
-
return /* @__PURE__ */ jsx(EmptyState, { onUpload, canUpload });
|
|
2479
|
-
case "error":
|
|
2480
|
-
return renderErrorFamily(records, onGrant, canGrant);
|
|
2481
|
-
case "populated":
|
|
2482
|
-
return /* @__PURE__ */ jsx(PopulatedState, { record: records.record, activeRequest: records.activeRequest });
|
|
2483
|
-
default:
|
|
2484
|
-
return assertNever(view);
|
|
2485
|
-
}
|
|
2486
|
-
}
|
|
2487
|
-
function renderErrorFamily(records, onGrant, canGrant) {
|
|
2488
|
-
if (records.denialReason === "consent_required") {
|
|
2489
|
-
return canGrant ? /* @__PURE__ */ jsx(ConsentRequiredState, { onGrant }) : /* @__PURE__ */ jsx(ConsentUnavailableState, {});
|
|
2490
|
-
}
|
|
2491
|
-
if (records.denialReason === "entitlement") {
|
|
2492
|
-
return /* @__PURE__ */ jsx(ErrorState, { error: makeEverfurError("accessDenied"), onRetry: records.refresh });
|
|
2493
|
-
}
|
|
2494
|
-
if (records.denialReason === "session_required") {
|
|
2495
|
-
return /* @__PURE__ */ jsx(SessionRequiredState, {});
|
|
2496
|
-
}
|
|
2497
|
-
if (records.withheld) {
|
|
2498
|
-
return /* @__PURE__ */ jsx(WithheldState, {});
|
|
2499
|
-
}
|
|
2500
|
-
const error = records.error;
|
|
2501
|
-
if (error === null) return /* @__PURE__ */ jsx(WithheldState, {});
|
|
2502
|
-
return /* @__PURE__ */ jsx(ErrorState, { error, onRetry: records.refresh });
|
|
2503
|
-
}
|
|
2504
|
-
function makeUploadHandler(records, onPickDocument) {
|
|
2505
|
-
return () => {
|
|
2506
|
-
if (!onPickDocument) return;
|
|
2507
|
-
void (async () => {
|
|
2508
|
-
const file = await onPickDocument();
|
|
2509
|
-
if (!file) return;
|
|
2510
|
-
const key = `records-upload-${Date.now().toString(36)}`;
|
|
2511
|
-
const created = await records.createRequest(key);
|
|
2512
|
-
if (!created.ok) return;
|
|
2513
|
-
await records.uploadDocument(created.value.id, file);
|
|
2514
|
-
})();
|
|
2515
|
-
};
|
|
2516
|
-
}
|
|
2517
|
-
function makeGrantHandler(records, consentVersion) {
|
|
2518
|
-
return () => {
|
|
2519
|
-
const version = consentVersion ?? records.consent?.version ?? "";
|
|
2520
|
-
if (version.length === 0) return;
|
|
2521
|
-
const key = `records-consent-${Date.now().toString(36)}`;
|
|
2522
|
-
void records.grantConsent(version, key);
|
|
2523
|
-
};
|
|
2524
|
-
}
|
|
2525
|
-
function LoadingState() {
|
|
2526
|
-
const styles = useStyles3();
|
|
2527
|
-
const [visible, setVisible] = useState(false);
|
|
2528
|
-
useEffect(() => {
|
|
2529
|
-
const id = setTimeout(() => setVisible(true), SPINNER_DELAY_MS);
|
|
2530
|
-
return () => clearTimeout(id);
|
|
2531
|
-
}, []);
|
|
2532
|
-
return /* @__PURE__ */ jsx(View, { style: styles.centered, accessible: true, accessibilityState: { busy: true }, accessibilityLabel: "Loading", children: visible ? /* @__PURE__ */ jsx(ActivityIndicator, {}) : null });
|
|
2533
|
-
}
|
|
2534
|
-
function EmptyState({ onUpload, canUpload }) {
|
|
2535
|
-
const styles = useStyles3();
|
|
2536
|
-
return /* @__PURE__ */ jsxs(View, { style: styles.centered, accessible: true, accessibilityRole: "summary", accessibilityLabel: "No records yet", children: [
|
|
2537
|
-
/* @__PURE__ */ jsx(View, { style: styles.emptyGlyph }),
|
|
2538
|
-
/* @__PURE__ */ jsx(
|
|
2539
|
-
Pressable,
|
|
2540
|
-
{
|
|
2541
|
-
onPress: canUpload ? onUpload : void 0,
|
|
2542
|
-
disabled: !canUpload,
|
|
2543
|
-
accessibilityRole: "button",
|
|
2544
|
-
accessibilityLabel: "Upload records",
|
|
2545
|
-
accessibilityState: { disabled: !canUpload },
|
|
2546
|
-
style: canUpload ? styles.primaryButton : styles.disabledButton,
|
|
2547
|
-
children: /* @__PURE__ */ jsx(Text, { style: canUpload ? styles.primaryLabel : styles.disabledLabel, children: "Upload records" })
|
|
2548
|
-
}
|
|
2549
|
-
)
|
|
2550
|
-
] });
|
|
2551
|
-
}
|
|
2552
|
-
function ConsentRequiredState({ onGrant }) {
|
|
2553
|
-
const styles = useStyles3();
|
|
2554
|
-
return /* @__PURE__ */ jsx(View, { style: styles.centered, accessible: true, accessibilityRole: "alert", accessibilityLabel: "Consent required", children: /* @__PURE__ */ jsx(
|
|
2555
|
-
Pressable,
|
|
2556
|
-
{
|
|
2557
|
-
onPress: onGrant,
|
|
2558
|
-
accessibilityRole: "button",
|
|
2559
|
-
accessibilityLabel: "Allow",
|
|
2560
|
-
style: styles.primaryButton,
|
|
2561
|
-
children: /* @__PURE__ */ jsx(Text, { style: styles.primaryLabel, children: "Allow" })
|
|
2562
|
-
}
|
|
2563
|
-
) });
|
|
2564
|
-
}
|
|
2565
|
-
function AlertState({ label, glyph }) {
|
|
2566
|
-
const styles = useStyles3();
|
|
2567
|
-
useEffect(() => {
|
|
2568
|
-
AccessibilityInfo.announceForAccessibility?.(label);
|
|
2569
|
-
}, [label]);
|
|
2570
|
-
return /* @__PURE__ */ jsxs(
|
|
2571
|
-
View,
|
|
2572
|
-
{
|
|
2573
|
-
style: styles.centered,
|
|
2574
|
-
accessible: true,
|
|
2575
|
-
accessibilityRole: "alert",
|
|
2576
|
-
accessibilityLiveRegion: "assertive",
|
|
2577
|
-
accessibilityLabel: label,
|
|
2578
|
-
children: [
|
|
2579
|
-
/* @__PURE__ */ jsx(View, { style: glyph === "withheld" ? styles.withheldGlyph : styles.emptyGlyph }),
|
|
2580
|
-
/* @__PURE__ */ jsx(Text, { style: styles.errorText, children: label })
|
|
2581
|
-
]
|
|
2582
|
-
}
|
|
2583
|
-
);
|
|
2584
|
-
}
|
|
2585
|
-
function ConsentUnavailableState() {
|
|
2586
|
-
return /* @__PURE__ */ jsx(AlertState, { label: "Consent required", glyph: "empty" });
|
|
2587
|
-
}
|
|
2588
|
-
function SessionRequiredState() {
|
|
2589
|
-
return /* @__PURE__ */ jsx(AlertState, { label: "Sign in required", glyph: "empty" });
|
|
2590
|
-
}
|
|
2591
|
-
function WithheldState() {
|
|
2592
|
-
return /* @__PURE__ */ jsx(AlertState, { label: "Record unavailable", glyph: "withheld" });
|
|
2593
|
-
}
|
|
2594
|
-
function ErrorState({ error, onRetry }) {
|
|
2595
|
-
const styles = useStyles3();
|
|
2596
|
-
useEffect(() => {
|
|
2597
|
-
AccessibilityInfo.announceForAccessibility?.(error.displayMessage);
|
|
2598
|
-
}, [error.displayMessage]);
|
|
2599
|
-
return /* @__PURE__ */ jsxs(View, { style: styles.centered, accessible: true, accessibilityRole: "alert", accessibilityLiveRegion: "assertive", children: [
|
|
2600
|
-
/* @__PURE__ */ jsx(Text, { style: styles.errorText, children: error.displayMessage }),
|
|
2601
|
-
error.retryable ? /* @__PURE__ */ jsx(Pressable, { onPress: onRetry, accessibilityRole: "button", accessibilityLabel: "Try again", style: styles.primaryButton, children: /* @__PURE__ */ jsx(Text, { style: styles.primaryLabel, children: "Try again" }) }) : null
|
|
2602
|
-
] });
|
|
2603
|
-
}
|
|
2604
|
-
function PopulatedState({
|
|
2605
|
-
record,
|
|
2606
|
-
activeRequest
|
|
2607
|
-
}) {
|
|
2608
|
-
const styles = useStyles3();
|
|
2609
|
-
const hasTimeline = activeRequest !== null && (activeRequest.statusLabel.length > 0 || activeRequest.heldItemCount > 0);
|
|
2610
|
-
const hasRecord = record !== null && !record.isEmpty;
|
|
2611
|
-
if (!hasTimeline && !hasRecord) return /* @__PURE__ */ jsx(LoadingState, {});
|
|
2612
|
-
return /* @__PURE__ */ jsxs(ScrollView, { style: styles.list, contentContainerStyle: styles.listContent, accessibilityLabel: "Records", children: [
|
|
2613
|
-
hasTimeline && activeRequest ? /* @__PURE__ */ jsx(RequestTimeline, { request: activeRequest }) : null,
|
|
2614
|
-
record && !record.isEmpty ? /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
2615
|
-
/* @__PURE__ */ jsx(TrendRangeCard, { series: record.entitySeries, testID: "records-trend-card" }),
|
|
2616
|
-
/* @__PURE__ */ jsx(
|
|
2617
|
-
RecordNavCards,
|
|
2618
|
-
{
|
|
2619
|
-
entities: record.entities,
|
|
2620
|
-
forwardLooking: record.forwardLooking,
|
|
2621
|
-
documents: record.documents,
|
|
2622
|
-
testID: "records-nav-cards"
|
|
2623
|
-
}
|
|
2624
|
-
),
|
|
2625
|
-
/* @__PURE__ */ jsx(RecordDetails, { record })
|
|
2626
|
-
] }) : null
|
|
2627
|
-
] });
|
|
2628
|
-
}
|
|
2629
|
-
function RequestTimeline({ request }) {
|
|
2630
|
-
const styles = useStyles3();
|
|
2631
|
-
const hasLabel = request.statusLabel.length > 0;
|
|
2632
|
-
const hasHeld = request.heldItemCount > 0;
|
|
2633
|
-
if (!hasLabel && !hasHeld) return null;
|
|
2634
|
-
return /* @__PURE__ */ jsxs(
|
|
2635
|
-
View,
|
|
2636
|
-
{
|
|
2637
|
-
style: styles.timeline,
|
|
2638
|
-
accessible: true,
|
|
2639
|
-
accessibilityRole: "text",
|
|
2640
|
-
...hasLabel ? { accessibilityLabel: request.statusLabel } : {},
|
|
2641
|
-
children: [
|
|
2642
|
-
hasLabel ? /* @__PURE__ */ jsx(Text, { style: styles.timelineLabel, children: request.statusLabel }) : null,
|
|
2643
|
-
hasHeld ? /* @__PURE__ */ jsx(Text, { style: styles.timelineMeta, children: `${request.heldItemCount} being reviewed` }) : null
|
|
2644
|
-
]
|
|
2645
|
-
}
|
|
2646
|
-
);
|
|
2647
|
-
}
|
|
2648
|
-
function RecordDetails({ record }) {
|
|
2649
|
-
const styles = useStyles3();
|
|
2650
|
-
const uncategorized = record.entities.filter((entity) => entity.category.trim().length === 0);
|
|
2651
|
-
const hasDetails = record.identity.length > 0 || uncategorized.length > 0;
|
|
2652
|
-
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
2653
|
-
hasDetails ? /* @__PURE__ */ jsxs(View, { style: styles.recordBlock, children: [
|
|
2654
|
-
record.identity.map((field) => /* @__PURE__ */ jsxs(View, { style: styles.row, children: [
|
|
2655
|
-
/* @__PURE__ */ jsx(Text, { style: styles.rowLabel, children: field.label }),
|
|
2656
|
-
/* @__PURE__ */ jsx(Text, { style: styles.rowValue, children: field.value })
|
|
2657
|
-
] }, field.label)),
|
|
2658
|
-
uncategorized.map((entity) => /* @__PURE__ */ jsxs(View, { style: styles.row, children: [
|
|
2659
|
-
/* @__PURE__ */ jsx(Text, { style: styles.rowLabel, children: entity.label }),
|
|
2660
|
-
/* @__PURE__ */ jsx(Text, { style: styles.rowValue, children: formatEntityValue(entity.value, entity.unit) })
|
|
2661
|
-
] }, entity.key))
|
|
2662
|
-
] }) : null,
|
|
2663
|
-
record.disclaimer.length > 0 ? /* @__PURE__ */ jsx(Text, { style: styles.disclaimer, children: record.disclaimer }) : null
|
|
2664
|
-
] });
|
|
2665
|
-
}
|
|
2666
|
-
function useStyles3() {
|
|
2667
|
-
const theme = useEverfurTheme();
|
|
2668
|
-
return useMemo(() => makeStyles5(theme), [theme]);
|
|
2669
|
-
}
|
|
2670
|
-
function makeStyles5(theme) {
|
|
2671
|
-
const { color, space, radius, type } = theme;
|
|
2672
|
-
const { size, lineHeight, weight, letterSpacing, family } = type;
|
|
2673
|
-
const lh = (fontSize, multiplier) => Math.round(fontSize * multiplier);
|
|
2674
|
-
const hairline = StyleSheet.hairlineWidth;
|
|
2675
|
-
const boldWeight = weight.bold;
|
|
2676
|
-
const mediumWeight = weight.medium;
|
|
2677
|
-
const minSurface = space.xxl * 3 + space.xl;
|
|
2678
|
-
const touchTarget = space.xxl + space.md;
|
|
2679
|
-
const glyphSize = space.xxl + space.sm;
|
|
2680
|
-
const errorColor = theme.brightness === "dark" ? color.errorRed : color.danger;
|
|
2681
|
-
const softShadow = {
|
|
2682
|
-
shadowColor: color.brand,
|
|
2683
|
-
shadowOffset: { width: 0, height: space.xs },
|
|
2684
|
-
shadowRadius: space.sm,
|
|
2685
|
-
shadowOpacity: 0.08,
|
|
2686
|
-
elevation: space.xs
|
|
2687
|
-
};
|
|
2688
|
-
return StyleSheet.create({
|
|
2689
|
-
container: { flex: 1, minHeight: minSurface, backgroundColor: color.background },
|
|
2690
|
-
body: { flex: 1 },
|
|
2691
|
-
centered: {
|
|
2692
|
-
minHeight: minSurface,
|
|
2693
|
-
flexGrow: 1,
|
|
2694
|
-
alignItems: "center",
|
|
2695
|
-
justifyContent: "center",
|
|
2696
|
-
padding: space.xl,
|
|
2697
|
-
gap: space.lg
|
|
2698
|
-
},
|
|
2699
|
-
// Branded empty placeholder: a soft-brand disc ringed in the hairline brand border.
|
|
2700
|
-
emptyGlyph: {
|
|
2701
|
-
width: glyphSize,
|
|
2702
|
-
height: glyphSize,
|
|
2703
|
-
borderRadius: radius.lg,
|
|
2704
|
-
backgroundColor: color.brandSoft,
|
|
2705
|
-
borderWidth: hairline,
|
|
2706
|
-
borderColor: color.brandBorder
|
|
2707
|
-
},
|
|
2708
|
-
// Withheld / fail-closed glyph: a caution wash ringed in the caution accent.
|
|
2709
|
-
withheldGlyph: {
|
|
2710
|
-
width: glyphSize,
|
|
2711
|
-
height: glyphSize,
|
|
2712
|
-
borderRadius: radius.sm,
|
|
2713
|
-
backgroundColor: color.badgeBgCaution,
|
|
2714
|
-
borderWidth: hairline,
|
|
2715
|
-
borderColor: color.cautionAccent
|
|
2716
|
-
},
|
|
2717
|
-
errorText: {
|
|
2718
|
-
fontFamily: family,
|
|
2719
|
-
fontSize: size.subtitle,
|
|
2720
|
-
lineHeight: lh(size.subtitle, lineHeight.snug),
|
|
2721
|
-
color: errorColor,
|
|
2722
|
-
textAlign: "center",
|
|
2723
|
-
marginBottom: space.md
|
|
2724
|
-
},
|
|
2725
|
-
// Primary CTA: brand fill, WCAG onPrimary foreground, pill radius, soft brand shadow.
|
|
2726
|
-
primaryButton: {
|
|
2727
|
-
minHeight: touchTarget,
|
|
2728
|
-
minWidth: touchTarget,
|
|
2729
|
-
alignItems: "center",
|
|
2730
|
-
justifyContent: "center",
|
|
2731
|
-
paddingHorizontal: space.xl,
|
|
2732
|
-
paddingVertical: space.md,
|
|
2733
|
-
borderRadius: radius.pill,
|
|
2734
|
-
backgroundColor: color.primary,
|
|
2735
|
-
...softShadow
|
|
2736
|
-
},
|
|
2737
|
-
primaryLabel: {
|
|
2738
|
-
fontFamily: family,
|
|
2739
|
-
color: color.onPrimary,
|
|
2740
|
-
fontSize: size.body,
|
|
2741
|
-
fontWeight: boldWeight,
|
|
2742
|
-
letterSpacing: letterSpacing.tight
|
|
2743
|
-
},
|
|
2744
|
-
disabledButton: {
|
|
2745
|
-
minHeight: touchTarget,
|
|
2746
|
-
minWidth: touchTarget,
|
|
2747
|
-
alignItems: "center",
|
|
2748
|
-
justifyContent: "center",
|
|
2749
|
-
paddingHorizontal: space.xl,
|
|
2750
|
-
paddingVertical: space.md,
|
|
2751
|
-
borderRadius: radius.pill,
|
|
2752
|
-
backgroundColor: color.surfaceSubtle,
|
|
2753
|
-
borderWidth: hairline,
|
|
2754
|
-
borderColor: color.brandBorder
|
|
2755
|
-
},
|
|
2756
|
-
disabledLabel: {
|
|
2757
|
-
fontFamily: family,
|
|
2758
|
-
color: color.text.muted,
|
|
2759
|
-
fontSize: size.body,
|
|
2760
|
-
fontWeight: boldWeight,
|
|
2761
|
-
letterSpacing: letterSpacing.tight
|
|
2762
|
-
},
|
|
2763
|
-
list: { flex: 1 },
|
|
2764
|
-
listContent: { padding: space.lg, gap: space.md },
|
|
2765
|
-
// Request timeline: a cream card with the brand hairline border + soft depth.
|
|
2766
|
-
timeline: {
|
|
2767
|
-
paddingVertical: space.md,
|
|
2768
|
-
paddingHorizontal: space.lg,
|
|
2769
|
-
borderRadius: radius.md,
|
|
2770
|
-
backgroundColor: color.surfaceCream,
|
|
2771
|
-
borderWidth: hairline,
|
|
2772
|
-
borderColor: color.brandBorder,
|
|
2773
|
-
gap: space.xs,
|
|
2774
|
-
...softShadow
|
|
2775
|
-
},
|
|
2776
|
-
timelineLabel: {
|
|
2777
|
-
fontFamily: family,
|
|
2778
|
-
fontSize: size.subtitle,
|
|
2779
|
-
lineHeight: lh(size.subtitle, lineHeight.snug),
|
|
2780
|
-
color: color.text.secondary,
|
|
2781
|
-
fontWeight: boldWeight,
|
|
2782
|
-
letterSpacing: letterSpacing.tight
|
|
2783
|
-
},
|
|
2784
|
-
timelineMeta: {
|
|
2785
|
-
fontFamily: family,
|
|
2786
|
-
fontSize: size.bodyTight,
|
|
2787
|
-
lineHeight: lh(size.bodyTight, lineHeight.normal),
|
|
2788
|
-
color: color.text.muted
|
|
2789
|
-
},
|
|
2790
|
-
// Parsed record: a cream card of hairline-divided label/value rows.
|
|
2791
|
-
recordBlock: {
|
|
2792
|
-
gap: space.sm,
|
|
2793
|
-
padding: space.md,
|
|
2794
|
-
borderRadius: radius.md,
|
|
2795
|
-
backgroundColor: color.surfaceCream,
|
|
2796
|
-
borderWidth: hairline,
|
|
2797
|
-
borderColor: color.brandBorder,
|
|
2798
|
-
...softShadow
|
|
2799
|
-
},
|
|
2800
|
-
row: {
|
|
2801
|
-
flexDirection: "row",
|
|
2802
|
-
justifyContent: "space-between",
|
|
2803
|
-
gap: space.md,
|
|
2804
|
-
paddingVertical: space.xs,
|
|
2805
|
-
borderBottomWidth: hairline,
|
|
2806
|
-
borderBottomColor: color.borderHairlineGreen
|
|
2807
|
-
},
|
|
2808
|
-
rowLabel: {
|
|
2809
|
-
fontFamily: family,
|
|
2810
|
-
fontSize: size.body,
|
|
2811
|
-
lineHeight: lh(size.body, lineHeight.normal),
|
|
2812
|
-
color: color.text.muted,
|
|
2813
|
-
flexShrink: 1
|
|
2814
|
-
},
|
|
2815
|
-
rowValue: {
|
|
2816
|
-
fontFamily: family,
|
|
2817
|
-
fontSize: size.body,
|
|
2818
|
-
lineHeight: lh(size.body, lineHeight.normal),
|
|
2819
|
-
color: color.text.primary,
|
|
2820
|
-
fontWeight: mediumWeight,
|
|
2821
|
-
textAlign: "right",
|
|
2822
|
-
flexShrink: 1
|
|
2823
|
-
},
|
|
2824
|
-
disclaimer: {
|
|
2825
|
-
fontFamily: family,
|
|
2826
|
-
fontSize: size.caption,
|
|
2827
|
-
lineHeight: lh(size.caption, lineHeight.normal),
|
|
2828
|
-
color: color.text.muted,
|
|
2829
|
-
marginTop: space.md
|
|
2830
|
-
}
|
|
2831
|
-
});
|
|
2832
|
-
}
|
|
2833
|
-
|
|
2834
|
-
export { EverfurRecords, RECORDS_TERMINAL, isTerminalStatus, recordsDenialReasonOf, useEverfurRecords };
|
|
3
|
+
`):null,Ve=h.length>0&&h.every(F=>!gn(F)||Pm.test(F.email.trim())),ie=h.length>=Nr,we=!!(v&&ye&&l.trim()&&e.petName.trim()&&Ve&&o)&&k===null,vt=i(async()=>{if(Z.current)return;let F=++oe.current;D(true);try{let Re=await t.searchClinics({query:c.trim(),limit:100});if(!G.current||F!==oe.current)return;Re.ok?(u(Re.value.clinics),b(null)):b(Re.error);}catch{G.current&&F===oe.current&&b(q("internalError"));}finally{G.current&&F===oe.current&&D(false);}},"search"),Xe=i(F=>{Z.current||ie||k!==null||F.clinic!==null&&h.some(Re=>Re.clinic?.id===F.clinic?.id)||(A(),R(Re=>[...Re,{...F,key:H.current(),idempotencyKey:H.current()}]),u([]),a(""));},"add"),Vt=i(async()=>{if(Z.current||k!==null||!we||!v||!ye||!o)return;Z.current=true;let F=Ee.current,Re=i(()=>G.current&&Ee.current===F,"current");x(true),b(null);try{if(C.current===null){T.current=new AbortController;let xt=await o({petRef:e.petRef,petName:e.petName,ownerName:l.trim(),clinicName:M.join(", "),authorizationVersion:v.authorizationVersion,scopeText:ye,signal:T.current.signal});if(!Re()||xt===null)return;if(C.current=xt,xt.signaturePngBase64!==void 0&&n!==void 0){let Vd=await n(xt.signaturePngBase64,T.current.signal);if(!Re())return;C.current={signatureId:Vd.signatureId};}}let Ft=C.current,Jr=h.map(xt=>({...xt.clinic!==null&&(!gn(xt)||xt.clinic.emailStatus==="none")?{clinicId:xt.clinic.id}:{clinicFreeText:bn(xt)},...gn(xt)?{clinicEmail:xt.email.trim().toLowerCase()}:{},...Ft.signatureId!==void 0?{signatureId:Ft.signatureId}:{signaturePngBase64:Ft.signaturePngBase64},idempotencyKey:xt.idempotencyKey})),Zr=await r.createClinicRequestBatch({petRef:e.petRef,ownerName:l.trim(),authorizationVersion:v.authorizationVersion,clinics:Jr});if(!Re())return;if(!Zr.ok){b(Zr.error);return}S(Zr.value),e.onCreated?.(Zr.value),qt(Zr.value.requestGroupId,F);}catch{Re()&&b(q("internalError"));}finally{Z.current=false,Re()&&x(false);}},"submit"),qt=i(async(F,Re)=>{try{let Ft=await t.getRequestGroup(F);if(!G.current||Ee.current!==Re)return;Ft.ok&&Ft.value.petRef===e.petRef&&Y(Ft.value);}catch{}},"loadGroup"),Se=i(async()=>{k===null||Z.current||await qt(k.requestGroupId,Ee.current);},"refreshGroup");return {ownerName:l,query:c,clinics:d,copy:v,scopeText:ye,error:g,busy:w,searching:E,drafts:h,outcome:k,group:I,ready:we,atCap:ie,recent:d.length===0?p.filter(F=>!h.some(Re=>Re.clinic?.id===F.id)):[],setOwnerName(F){Z.current||(A(),s(F));},setQuery(F){Z.current||(oe.current+=1,D(false),u([]),a(F));},search:vt,addClinic(F){Xe({clinic:F,freeText:null,email:""});},addFreeText(){let F=c.trim();F.length!==0&&Xe({clinic:null,freeText:F,email:""});},setDraftEmail(F,Re){Z.current||(A(),R(Ft=>Ft.map(Jr=>Jr.key===F?{...Jr,email:Re}:Jr)));},removeDraft(F){Z.current||k!==null||(A(),R(Re=>Re.filter(Ft=>Ft.key!==F)));},submit:Vt,refreshGroup:Se,retryCopy(){b(null),$(F=>F+1);}}}i(Ll,"useClinicBatchForm");function Vl(e){try{let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.port&&t.port!=="443")return !1;let r=t.hostname.toLowerCase();return r==="s3.amazonaws.com"||r.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(r)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(r)||r==="s3-accelerate.amazonaws.com"||r.endsWith(".s3-accelerate.amazonaws.com")||r==="s3-accelerate.dualstack.amazonaws.com"||r.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}i(Vl,"trustedSignatureUploadUrl");var Im="Signature upload failed",Dm=3e4;function Am(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-t}i(Am,"base64ByteLength");async function Di(e,t,r,o){let n=i(()=>new Error(Im),"fail"),l=Am(e);if(l<=0||r.aborted)throw n();let s=await t.initiateSignatureUpload(l);if(!s.ok||r.aborted||!Vl(s.value.uploadUrl))throw n();let c=new FormData;for(let[f,h]of Object.entries(s.value.uploadFields))c.append(f,h);c.append("file",{uri:`data:image/png;base64,${e}`,name:"signature.png",type:"image/png"});let a=new AbortController,d=i(()=>a.abort(),"onAbort");r.addEventListener("abort",d,{once:true});let u=setTimeout(d,Dm);try{if(!(await(o??fetch)(s.value.uploadUrl,{method:"POST",body:c,credentials:"omit",signal:a.signal})).ok||r.aborted)throw n()}catch{throw n()}finally{clearTimeout(u),r.removeEventListener("abort",d);}let p=await t.completeSignatureUpload(s.value.uploadId);if(!p.ok||r.aborted)throw n();return {signatureId:p.value}}i(Di,"registerRnSignature");var jr=Object.freeze({width:360,height:120});function Nl(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(Nl,"blank");function Ml(e,t,r,o){for(let n=-o;n<=o;n+=1)for(let l=-o;l<=o;l+=1){if(l*l+n*n>o*o+o)continue;let s=t+l,c=r+n;s<0||c<0||s>=e.width||c>=e.height||(e.pixels[c*e.width+s]=1);}}i(Ml,"stamp");var Om=16384;function Lm(e,t){let[r,o]=e;if(!Number.isFinite(r)||!Number.isFinite(o))return null;let n=Math.min(2*t.width,Math.max(-t.width,Math.round(r))),l=Math.min(2*t.height,Math.max(-t.height,Math.round(o)));return [n,l]}i(Lm,"padPoint");function Vm(e,t,r,o,n){let[l,s]=t,[c,a]=r,d=Math.abs(c-l),u=-Math.abs(a-s),p=l<c?1:-1,f=s<a?1:-1,h=d+u,R=0;for(;R<n&&(Ml(e,l,s,o),R+=1,!(l===c&&s===a));){let v=2*h;v>=u&&(h+=u,l+=p),v<=d&&(h+=d,s+=f);}return R}i(Vm,"line");function Bl(e,t=1){let r=Nl(jr.width,jr.height);for(let o of e){let n=[];for(let s of o){let c=Lm(s,r);c!==null&&n.push(c);}if(n.length===0)continue;if(n.length===1){let[s,c]=n[0];Ml(r,s,c,t);continue}let l=Om;for(let s=1;s<n.length&&l>0;s+=1)l-=Vm(r,n[s-1],n[s],t,l);}return r}i(Bl,"rasterizeStrokes");var qm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",Fm="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",zm="0123456789abcdefghijklmnopqrstuv",Fi=5,zi=7,Ai=Fi+1;function Nm(e,t){let r=qm.indexOf(e);return r<0?0:zm.indexOf(Fm.charAt(r*zi+t))}i(Nm,"glyphRow");function Hl(e){let t=Nl(jr.width,jr.height),r=e.trim();if(r.length===0)return t;let o=[...r],n=4;for(;n>1&&(o.length*Ai-1)*n>t.width-8;)n-=1;let l=(o.length*Ai-1)*n,s=Math.max(0,Math.floor((t.width-l)/2)),c=Math.floor((t.height-zi*n)/2);return o.forEach((a,d)=>{let u=s+d*Ai*n;for(let p=0;p<zi;p+=1){let f=Nm(a,p);for(let h=0;h<Fi;h+=1)if((f>>Fi-1-h&1)!==0)for(let R=0;R<n;R+=1)for(let v=0;v<n;v+=1){let y=u+h*n+v,g=c+p*n+R;y<t.width&&g<t.height&&(t.pixels[g*t.width+y]=1);}}}),t}i(Hl,"rasterizeTypedName");var Hi=class Hi{constructor(){this.bytes=[];this.acc=0;this.count=0;}writeBits(t,r){for(this.acc|=t<<this.count,this.count+=r;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8;}writeCode(t,r){let o=0;for(let n=0;n<r;n+=1)o=o<<1|t>>n&1;this.writeBits(o,r);}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};i(Hi,"BitWriter");var Ni=Hi;function Mi(e,t){t<144?e.writeCode(48+t,8):t<256?e.writeCode(400+(t-144),9):t<280?e.writeCode(t-256,7):e.writeCode(192+(t-280),8);}i(Mi,"writeLiteral");var Oi=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],ql=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Li=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Fl=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function Mm(e,t,r){let o=Oi.length-1;for(;Oi[o]>t;)o-=1;Mi(e,257+o),ql[o]>0&&e.writeBits(t-Oi[o],ql[o]);let n=Li.length-1;for(;Li[n]>r;)n-=1;e.writeCode(n,5),Fl[n]>0&&e.writeBits(r-Li[n],Fl[n]);}i(Mm,"writeMatch");var Bm=32768,Vi=3,Hm=258,zl=15,Um=64;function jm(e){let t=new Ni;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<zl).fill(-1),o=new Int32Array(e.length).fill(-1),n=i(c=>(e[c]<<10^e[c+1]<<5^e[c+2])&(1<<zl)-1,"hashAt"),l=i(c=>{if(c+Vi>e.length)return;let a=n(c);o[c]=r[a],r[a]=c;},"insert"),s=0;for(;s<e.length;){let c=0,a=0;if(s+Vi<=e.length){let d=r[n(s)],u=0,p=Math.min(Hm,e.length-s);for(;d>=0&&u<Um&&s-d<=Bm;){let f=0;for(;f<p&&e[d+f]===e[s+f];)f+=1;if(f>c&&(c=f,a=s-d,f===p))break;d=o[d],u+=1;}}if(c>=Vi){Mm(t,c,a);for(let d=0;d<c;d+=1)l(s+d);s+=c;}else Mi(t,e[s]),l(s),s+=1;}return Mi(t,256),t.finish()}i(jm,"deflate");function $m(e){let t=1,r=0;for(let o of e)t=(t+o)%65521,r=(r+t)%65521;return (r<<16|t)>>>0}i($m,"adler32");var so=null;function Wm(e){if(so===null){so=new Uint32Array(256);for(let r=0;r<256;r+=1){let o=r;for(let n=0;n<8;n+=1)o=o&1?3988292384^o>>>1:o>>>1;so[r]=o>>>0;}}let t=4294967295;for(let r of e)t=so[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(Wm,"crc32");function hn(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(hn,"u32");function qi(e,t){let r=Uint8Array.from([...e].map(n=>n.charCodeAt(0))),o=new Uint8Array(r.length+t.length);return o.set(r,0),o.set(t,r.length),[...hn(t.length),...o,...hn(Wm(o))]}i(qi,"chunk");var lo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Gm(e){let t="";for(let r=0;r<e.length;r+=3){let o=e[r],n=r+1<e.length?e[r+1]:0,l=r+2<e.length?e[r+2]:0,s=o<<16|n<<8|l;t+=lo.charAt(s>>18&63)+lo.charAt(s>>12&63),t+=r+1<e.length?lo.charAt(s>>6&63):"=",t+=r+2<e.length?lo.charAt(s&63):"=";}return t}i(Gm,"toBase64");function Bi(e){let{width:t,height:r,pixels:o}=e,n=Math.ceil(t/8)+1,l=new Uint8Array(n*r);for(let u=0;u<r;u+=1){let p=u*n;l[p]=0,l.fill(255,p+1,p+n);for(let f=0;f<t;f+=1)if(o[u*t+f]===1){let h=p+1+(f>>3);l[h]=l[h]&~(128>>(f&7));}}let s=jm(l),c=new Uint8Array(2+s.length+4);c[0]=120,c[1]=1,c.set(s,2),c.set(hn($m(l)),2+s.length);let a=Uint8Array.from([...hn(t),...hn(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...qi("IHDR",a),...qi("IDAT",c),...qi("IEND",new Uint8Array(0))]);return Gm(d)}i(Bi,"encodeSignaturePng");var Xm=8,$l=2,Rn=3;function Lr({onChange:e,disabled:t=false}){let r=Jm(),[o,n]=useState("draw"),[l,s]=useState(""),[c,a]=useState([]),[d,u]=useState(0),p=useRef([]),f=useRef(null),h=d>0?jr.width/d:1,R=useRef(h);R.current=h;let v=useRef(t);v.current=t,useEffect(()=>{if(o==="type"){jn(e,l.trim().length>0?Bi(Hl(l)):null);return}let E=c.reduce((D,k)=>D+k.length,0);jn(e,E>=Xm?Bi(Bl(c)):null);},[o,l,c,e]);let y=i(E=>{let{locationX:D,locationY:k}=E.nativeEvent;return [D*R.current,k*R.current]},"point"),g=useMemo(()=>PanResponder.create({onStartShouldSetPanResponder:i(()=>!v.current,"onStartShouldSetPanResponder"),onMoveShouldSetPanResponder:i(()=>!v.current,"onMoveShouldSetPanResponder"),onPanResponderTerminationRequest:i(()=>false,"onPanResponderTerminationRequest"),onPanResponderGrant:i(E=>{p.current=[y(E)];},"onPanResponderGrant"),onPanResponderMove:i(E=>{let D=y(E),k=p.current[p.current.length-1];k!==void 0&&Math.abs(k[0]-D[0])<$l&&Math.abs(k[1]-D[1])<$l||(p.current=[...p.current,D],a(S=>[...S.filter(I=>I!==f.current),f.current=p.current]));},"onPanResponderMove"),onPanResponderRelease:i(()=>{let E=p.current;p.current=[],a(D=>[...D.filter(k=>k!==f.current),E]),f.current=null;},"onPanResponderRelease"),onPanResponderTerminate:i(()=>{let E=p.current;p.current=[],a(D=>[...D.filter(k=>k!==f.current),E]),f.current=null;},"onPanResponderTerminate")}),[]),b=useCallback(()=>{v.current||(p.current=[],f.current=null,a([]),s(""));},[]),w=useCallback(()=>{b(),n(E=>E==="draw"?"type":"draw");},[b]),x=i(E=>u(E.nativeEvent.layout.width),"onLayout");return jsxs(View,{style:r.container,testID:"records-signature-pad",children:[jsx(m,{style:r.label,children:o==="draw"?U.draw:U.type}),o==="type"?jsx(qe,{accessibilityLabel:U.type,style:r.input,value:l,maxLength:100,editable:!t,autoComplete:"off",autoCorrect:false,onChangeText:E=>{v.current||s(E);}}):null,jsx(View,{onLayout:x,style:[r.canvas,{height:d>0?d/3:120}],accessible:true,accessibilityLabel:U.sign,accessibilityRole:"image",testID:"records-signature-canvas",...o==="draw"?g.panHandlers:{},children:o==="type"?jsx(m,{style:r.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:l.trim()}):c.map((E,D)=>E.map(([k,S],I)=>jsx(View,{pointerEvents:"none",style:[r.dot,{left:k/h-Rn/2,top:S/h-Rn/2}]},`${D}-${I}`)))}),jsxs(View,{style:r.actions,children:[jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:U.clear,accessibilityState:{disabled:t},disabled:t,onPress:b,style:r.button,children:jsx(m,{style:r.buttonLabel,children:U.clear})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:o==="draw"?U.toType:U.toDraw,accessibilityState:{disabled:t},disabled:t,onPress:w,style:r.button,children:jsx(m,{style:r.buttonLabel,children:o==="draw"?U.toType:U.toDraw})})]})]})}i(Lr,"SignaturePad");function Jm(){let e=L();return useMemo(()=>Zm(e),[e])}i(Jm,"useStyles");function Zm(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({container:{gap:r.sm},label:{..._(e,"regular"),fontSize:n.size.body,color:t.text.primary},input:{minHeight:44,padding:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,..._(e,"regular"),fontSize:n.size.body},canvas:{width:"100%",backgroundColor:"#ffffff",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,overflow:"hidden",justifyContent:"center"},dot:{position:"absolute",width:Rn,height:Rn,borderRadius:Rn/2,backgroundColor:"#111111"},typedPreview:{textAlign:"center",fontSize:32,fontStyle:"italic",fontWeight:"700",color:"#111111",paddingHorizontal:r.md},actions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},button:{minHeight:44,paddingHorizontal:r.md,justifyContent:"center",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,backgroundColor:t.surface},buttonLabel:{..._(e,"regular"),fontSize:n.size.body,color:t.text.primary}})}i(Zm,"makeStyles");function ji(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",...Be(e.onClose,U.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsx(ry,{...Fe(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(ji,"EverfurClinicRequestBatch");function ry(e){let t=Nt(),r=mi(),o=e.controller??t,[n,l]=useState(null),s=useCallback(async()=>n===null?null:{signaturePngBase64:n},[n]),c=useCallback((y,g)=>Di(y,o,g),[o]),a=Ll(e,o,e.batchClient??r,e.onCaptureSignature??s,e.onCaptureSignature?void 0:c),d=e.onCaptureSignature!==void 0||n!==null,u=L(),p={minHeight:44,padding:u.space.sm,borderWidth:1,borderColor:u.color.borderHairlineGreen,borderRadius:u.radius.sm,color:u.color.text.primary,backgroundColor:u.color.surface},f={color:u.color.text.primary,fontSize:u.type.size.body},h={color:u.color.text.muted,fontSize:u.type.size.bodyTight},R=i((y,g,b=false,w=y)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:w,accessibilityState:{disabled:b},disabled:b,onPress:g,style:[p,{justifyContent:"center",opacity:b?.5:1}],children:jsx(m,{style:f,children:y})}),"button"),v=a.busy?Oe.sending:a.drafts.length===0?Oe.addToContinue:a.error?Oe.tryAgain:Oe.send(a.drafts.length);return jsxs(View,{accessibilityLabel:a.outcome?Oe.resultTitle:Oe.title,style:[{backgroundColor:u.color.surface,padding:u.space.lg,gap:u.space.md,borderRadius:u.radius.lg,minHeight:120},e.style],children:[jsx(m,{accessibilityRole:"header",style:[f,{..._(u,"bold"),fontSize:u.type.size.heading}],children:a.outcome?Oe.resultTitle:Oe.title}),jsx(m,{style:f,children:e.petName}),a.outcome?jsxs(View,{style:{gap:u.space.sm},testID:"records-batch-result",children:[jsx(m,{accessibilityRole:"summary",accessibilityLiveRegion:"polite",style:f,children:a.outcome.createdCount===0?Oe.allFailed:a.outcome.failedCount>0?Oe.partial(a.outcome.createdCount,a.outcome.results.length,a.outcome.failedCount):Oe.allSent(a.outcome.createdCount)}),jsx(m,{accessibilityRole:"header",style:f,children:Oe.perClinic}),a.outcome.results.map((y,g)=>{let b=y.request?.clinicName??a.drafts[g]?.clinic?.name??y.clinicFreeText??"",w=y.created?Oe.sent:Oe.notSent;return jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:[`${b}. ${w}.`,y.created?y.request?.statusLabel:y.failureReason].filter(Boolean).join(" "),testID:`records-batch-row-${y.created?"created":"failed"}`,children:[jsx(m,{style:f,children:b}),jsx(m,{style:h,children:w}),y.created&&y.request?.statusLabel?jsx(m,{style:h,children:y.request.statusLabel}):null,!y.created&&y.failureReason?jsx(m,{style:h,children:y.failureReason}):null]},y.idempotencyKey)}),a.group?jsx(m,{accessibilityLiveRegion:"polite",style:f,children:Oe.responded(a.group.responded,a.group.total)}):null,a.group?.members.map(y=>y.statusLabel?jsx(m,{style:h,children:[y.clinicName,y.statusLabel].filter(Boolean).join(": ")},y.id):null)]}):jsxs(Fragment,{children:[jsx(m,{style:f,children:U.ownerName}),jsx(qe,{accessibilityLabel:U.ownerName,style:p,value:a.ownerName,maxLength:200,editable:!a.busy,autoComplete:"name",onChangeText:a.setOwnerName}),a.drafts.map(y=>jsxs(View,{style:{gap:u.space.xs},testID:`records-batch-draft-${y.key}`,children:[jsx(m,{style:f,children:bn(y)}),gn(y)?jsxs(Fragment,{children:[jsx(m,{style:h,children:y.email.trim()?y.email:Oe.emailToAdd}),jsx(qe,{accessibilityLabel:U.email,style:p,value:y.email,placeholder:U.emailPlaceholder,placeholderTextColor:u.color.text.placeholder,maxLength:320,editable:!a.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:g=>a.setDraftEmail(y.key,g)})]}):null,R(Oe.remove(bn(y)),()=>a.removeDraft(y.key),a.busy)]},y.key)),jsx(m,{style:f,children:a.atCap?Oe.atCap:Oe.addClinic}),!a.atCap&&jsxs(Fragment,{children:[jsx(qe,{accessibilityLabel:U.clinic,style:p,value:a.query,placeholder:U.placeholder,placeholderTextColor:u.color.text.placeholder,maxLength:200,editable:!a.busy,onChangeText:a.setQuery}),R(U.search,()=>{a.search();},a.busy||a.searching||a.query.trim().length<2),a.query.trim().length>0&&a.clinics.length===0&&!a.searching&&R(Oe.addClinic,a.addFreeText,a.busy),a.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:f,children:ce.loading}),a.recent.length>0&&jsx(m,{accessibilityRole:"header",style:f,children:U.recentlyUsed}),a.recent.map(y=>jsx(View,{children:R([y.name,y.address,y.phone].filter(Boolean).join(", "),()=>a.addClinic(y),a.busy)},`recent-${y.id}`)),a.clinics.map(y=>jsx(View,{children:R([y.name,y.address,y.phone].filter(Boolean).join(", "),()=>a.addClinic(y),a.busy)},y.id))]}),jsx(m,{accessibilityRole:"header",style:f,children:U.scopeHeading}),a.copy?jsx(m,{style:f,children:a.drafts.length>0&&a.ownerName.trim()?a.scopeText??q("internalError").displayMessage:ce.consentRequired}):!a.error&&jsx(m,{accessibilityLiveRegion:"polite",style:f,children:ce.loading}),!e.onCaptureSignature&&jsx(Lr,{onChange:l,disabled:a.busy}),!d&&jsx(m,{accessibilityRole:"alert",style:f,children:U.missingSignature}),a.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:f,children:a.error.displayMessage}),!a.copy&&a.error&&R(ce.retry,a.retryCopy),R(v,()=>{a.submit();},a.busy||!a.ready||!d,Oe.sendA11y(a.drafts.length))]}),e.onClose&&R(U.cancel,e.onClose,a.busy),jsx(Me,{})]})}i(ry,"BatchBody");var se=Object.freeze({scopeHeading:"What you\u2019re authorizing",scopeBody:"You\u2019re asking your pet\u2019s clinic to release their medical records to Everfur, on your behalf, so we can organize them for you.",whatWeDo:Object.freeze(["We email the clinic a signed copy of this authorization.","When records arrive, our team reviews them before they appear in your app.","You can revoke this request at any time."]),retentionNote:"We keep the records you receive so you always have them. See our Privacy Policy for how records are stored and used.",authorizeLabel:i((e,t)=>`I authorize ${t} to release ${He(e)}\u2019s records to Everfur.`,"authorizeLabel"),missingSignatureError:"Please add your signature before submitting.",missingDraftError:"Something went wrong with your selection. Please go back and pick the clinic again.",newClinicDirectSendNote:"We\u2019ll email this clinic directly to request your pet\u2019s medical records. Clinics usually reply within a week.",titleFreeText:"Confirm your request",titleDirectory:"Authorize records release",noEmailNote:i((e,t)=>`We don\u2019t have an email on file for ${t}. Add it so we can request ${He(e)}\u2019s records.`,"noEmailNote"),emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",emailRequired:"Enter the clinic email before sending the request.",reuseSignature:"Reuse a previous signature",reuseHint:"\u2026or sign again below",reuseTileA11y:"Use this earlier signature",reuseTileSelectedA11y:"Earlier signature, selected",signType:"Type your name to sign",signDraw:"Sign with your finger",clear:"Clear",clearA11y:"Clear signature",fullName:"Your full name",fullNamePlaceholder:"Jane Doe",toType:"Can\u2019t draw? Type your name instead",toTypeA11y:"Can\u2019t draw? Type your name to sign instead",toDraw:"Draw your signature instead",signatureHint:i(e=>`Your signature is added to the authorization sent to ${e}.`,"signatureHint"),submit:"Authorize & send request",submitting:"Submitting\u2026",submitA11y:"Submit authorization"});var ny="value_text",Kl=64,Ql=512;function Xl(e){return e!==null&&e.httpStatus===409&&!tr(e)}i(Xl,"isFactReviewerLocked");var vn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:ny}),Jl=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,Zl=/^\d{4}-\d{2}-\d{2}$/;function ec(e){if(e==null)return "text";let t=e.trim();return Jl.test(t)?"num":Zl.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(ec,"inferFactValueKind");function $i(e,t){let r=t.trim(),o=ec(e);if(o==="num"&&Jl.test(r)){let n=Number(r);if(Number.isFinite(n))return Object.freeze({[vn.num]:n})}return o==="date"&&Zl.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[vn.date]:r}):Object.freeze(o==="bool"&&(r==="true"||r==="false")?{[vn.bool]:r==="true"}:{[vn.text]:r})}i($i,"factCorrectionFor");var Ie=z.string().nullish(),mo=z.number().nullish(),oy=z.object({collected_at:Ie,at:Ie,value:mo,unit:Ie,qualitative_result:Ie,ref_low:mo,ref_high:mo,status:Ie,source_clinic:Ie,source_doc_id:Ie,doc_id:Ie,reviewed:z.boolean().nullish()}),iy=z.object({collected_at:Ie,at:Ie,value:mo,unit:Ie,qualitative_result:Ie,status:Ie}),ay=z.object({marker_id:z.string().min(1),canonical_name:Ie,name:Ie,loinc_code:Ie,canonical_unit:Ie,unit:Ie,panel_name:Ie,panel:Ie,meaning_text:Ie,meaning:Ie,latest:iy.nullish(),trajectory:Ie,points:z.array(oy).optional()}),sy=z.object({total_markers:z.number().int().nonnegative(),in_range_count:z.number().int().nonnegative(),out_of_range_count:z.number().int().nonnegative(),unknown_count:z.number().int().nonnegative()}),ly=z.object({markers:z.array(ay).optional(),summary:sy.nullish(),disclaimer:z.string().optional(),featured_marker_id:Ie});function cy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(cy,"isObject");function tc(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(tc,"withheldMarkers");function rc(e,t){let r=cy(t)?t:{},o=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return tc(o);let n=ly.safeParse(r);if(!n.success)return tc(o);let l=n.data,s=i(a=>Object.freeze({at:a.collected_at??a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,sourceClinic:a.source_clinic??null,docId:a.source_doc_id??a.doc_id??null,reviewed:a.reviewed===true}),"point"),c=(l.markers??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.canonical_name??a.name??a.marker_id,loincCode:a.loinc_code??null,unit:a.canonical_unit??a.unit??null,panel:a.panel_name??a.panel??null,meaning:a.meaning_text??a.meaning??null,latest:a.latest?Object.freeze({at:a.latest.collected_at??a.latest.at??null,value:a.latest.value??null,unit:a.latest.unit??null,qualitativeResult:a.latest.qualitative_result??null,status:a.latest.status??null}):null,trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(s))}));return Object.freeze({petRef:o,withheld:false,markers:Object.freeze(c),summary:l.summary?Object.freeze({totalMarkers:l.summary.total_markers,inRangeCount:l.summary.in_range_count,outOfRangeCount:l.summary.out_of_range_count,unknownCount:l.summary.unknown_count}):null,disclaimer:l.disclaimer??"",featuredMarkerId:l.featured_marker_id??null})}i(rc,"mapRecordMarkers");var dy=z.string().min(1).refine(e=>e.startsWith("https://")),xn=z.string().nullish(),uy=z.object({share_id:z.string().min(1),share_url:z.string().min(1),expires_at:xn}),py=z.object({shares:z.array(z.object({share_id:z.string().min(1),expires_at:xn,created_at:xn,view_count:z.number().int().nonnegative().nullish(),last_viewed_at:xn})).optional()}),my=z.object({download_url:dy,expires_at:xn});function yy(e,t){let r=e.trim();if(r.length===0)return null;try{let o=/^[a-z][a-z0-9+.-]*:/i.test(r)?new URL(r):t!==void 0?new URL(r,t):null;return o===null||o.protocol!=="https:"?null:o.toString()}catch{return null}}i(yy,"resolveShareUrl");function nc(e,t){let r=uy.safeParse(e);if(!r.success)return null;let o=yy(r.data.share_url,t);return o===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:o,expiresAt:r.data.expires_at??null})}i(nc,"mapRecordShareLink");function oc(e){let t=py.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null}))):null}i(oc,"mapRecordShareList");function ic(e){let t=my.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(ic,"mapRecordPdfLink");var fy=z.object({signatures:z.array(z.object({signature_id:z.string().min(1),preview_url:z.string().min(1).refine(e=>e.startsWith("https://")),created_at:z.string().nullish()})).optional()});function ac(e){let t=fy.safeParse(e);return t.success?Object.freeze((t.data.signatures??[]).map(r=>Object.freeze({signatureId:r.signature_id,previewUrl:r.preview_url,createdAt:r.created_at??null}))):null}i(ac,"mapSignatureSuggestions");var N=z.string().nullish(),wn=z.number().nullish(),gy=z.object({at:N,value:wn,unit:N,qualitative_result:N,ref_low:wn,ref_high:wn,status:N,doc_id:N}),by=z.object({marker_id:z.string(),name:z.string(),loinc_code:N,unit:N,panel:N,meaning:N,latest:z.object({at:N,value:wn,unit:N,qualitative_result:N,status:N}).nullish(),trajectory:N,points:z.array(gy).optional()}),hy=z.object({encounter_id:z.string(),date:N,type:N,clinic_name:N,veterinarian:N,doc_id:N}),Ry=z.object({note_id:z.string(),encounter_id:N,observed_on:N,sections:z.array(z.object({section:z.string(),text:z.string()})).optional()}),vy=z.object({exam_id:z.string(),encounter_id:N,observed_on:N,doc_id:N,systems:z.record(z.object({finding_status:N,finding:N})).optional()}),xy=z.object({has_lab_history:z.boolean().optional(),has_vaccination_history:z.boolean().optional(),has_weight_history:z.boolean().optional(),has_vitals_history:z.boolean().optional(),has_physical_exam_history:z.boolean().optional(),has_procedure_history:z.boolean().optional(),has_genetic_history:z.boolean().optional(),has_reproductive_history:z.boolean().optional(),has_parasite_prevention_history:z.boolean().optional(),earliest_record_at:N,latest_record_at:N,documents_ingested:z.number().int().nonnegative().optional(),documents_in_review:z.number().int().nonnegative().optional(),entities_pending_review:z.record(z.number().int().nonnegative()).optional(),held_total:z.number().int().nonnegative().optional()}),wy=z.object({conflict_id:z.string(),entity_type:z.string(),field:N,severity:N,candidates:z.array(z.object({value:z.string(),source_doc_id:N,doc_id:N,collected_at:N})).optional()}),Cy=z.object({lab_results:z.array(by).optional(),encounters:z.array(hy).optional(),clinician_notes:z.array(Ry).optional(),physical_exams:z.array(vy).optional(),completeness:xy.nullish(),conflicts:z.array(wy).optional()}),Ey=z.object({visits:z.array(z.object({visit_id:z.string(),visit_date:N,veterinarian:N,summary:N,doc_id:N})),vaccines:z.array(z.object({vaccine_id:z.string(),product:N,lot:N,administered_on:N,expires_on:N,doc_id:N})),weights:z.array(z.object({weight_id:z.string(),observed_on:N,weight_kg:wn,doc_id:N})),medications:z.array(z.object({medication_id:z.string(),drug_name:N,dose:N,route:N,frequency:N,sig:N,rx_number:N,started_on:N,stopped_on:N,doc_id:N})),disclaimer:z.string().optional()}),Sy=z.object({document:Mo,contributions:z.array(No),contribution_count:z.number().int().nonnegative().optional()});function Gi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Gi,"isObject");function Yi(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(Yi,"petOf");function Wi(e,t){return Object.freeze({petRef:e,available:false,withheld:t,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(Wi,"emptyDepth");function ky(e,t){let r=Gi(t)?t:{},o=Yi(r,e);if(r.withheld===true)return Wi(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return Wi(o,false);let l=Cy.safeParse(r);if(!l.success)return Wi(o,true);let s=l.data,c=i(a=>Object.freeze({at:a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,docId:a.doc_id??null}),"point");return Object.freeze({petRef:o,available:true,withheld:false,labResults:Object.freeze((s.lab_results??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.name,loincCode:a.loinc_code??null,unit:a.unit??null,panel:a.panel??null,meaning:a.meaning??null,latest:Object.freeze({at:a.latest?.at??null,value:a.latest?.value??null,unit:a.latest?.unit??null,qualitativeResult:a.latest?.qualitative_result??null,status:a.latest?.status??null}),trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(c))}))),encounters:Object.freeze((s.encounters??[]).map(a=>Object.freeze({encounterId:a.encounter_id,date:a.date??null,type:a.type??null,clinicName:a.clinic_name??null,veterinarian:a.veterinarian??null,docId:a.doc_id??null}))),clinicianNotes:Object.freeze((s.clinician_notes??[]).map(a=>Object.freeze({noteId:a.note_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,sections:Object.freeze((a.sections??[]).map(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((s.physical_exams??[]).map(a=>Object.freeze({examId:a.exam_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,docId:a.doc_id??null,systems:Object.freeze(Object.entries(a.systems??{}).map(([d,u])=>Object.freeze({system:d,findingStatus:u.finding_status??null,finding:u.finding??null})))}))),completeness:s.completeness?Object.freeze({hasLabHistory:s.completeness.has_lab_history===true,hasVaccinationHistory:s.completeness.has_vaccination_history===true,hasWeightHistory:s.completeness.has_weight_history===true,hasVitalsHistory:s.completeness.has_vitals_history===true,hasPhysicalExamHistory:s.completeness.has_physical_exam_history===true,hasProcedureHistory:s.completeness.has_procedure_history===true,hasGeneticHistory:s.completeness.has_genetic_history===true,hasReproductiveHistory:s.completeness.has_reproductive_history===true,hasParasitePreventionHistory:s.completeness.has_parasite_prevention_history===true,earliestRecordAt:s.completeness.earliest_record_at??null,latestRecordAt:s.completeness.latest_record_at??null,documentsIngested:s.completeness.documents_ingested??0,documentsInReview:s.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...s.completeness.entities_pending_review??{}}),heldTotal:s.completeness.held_total??0}):null,conflicts:Object.freeze((s.conflicts??[]).map(a=>Object.freeze({conflictId:a.conflict_id,entityType:a.entity_type,field:a.field??null,severity:a.severity??"needs_review",candidates:Object.freeze((a.candidates??[]).map(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(ky,"mapRecordDepth");function sc(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(sc,"withheldTimeline");function Ty(e,t){let r=Gi(t)?t:{},o=Yi(r,e);if(r.withheld===true)return sc(o);let n=Ey.safeParse(r);if(!n.success)return sc(o);let l=n.data,s=l.visits.map(u=>Object.freeze({visitId:u.visit_id,visitDate:u.visit_date??null,veterinarian:u.veterinarian??null,summary:u.summary??null,docId:u.doc_id??null})),c=l.vaccines.map(u=>Object.freeze({vaccineId:u.vaccine_id,product:u.product??null,lot:u.lot??null,administeredOn:u.administered_on??null,expiresOn:u.expires_on??null,docId:u.doc_id??null})),a=l.weights.map(u=>Object.freeze({weightId:u.weight_id,observedOn:u.observed_on??null,weightKg:u.weight_kg??null,docId:u.doc_id??null})),d=l.medications.map(u=>Object.freeze({medicationId:u.medication_id,drugName:u.drug_name??null,dose:u.dose??null,route:u.route??null,frequency:u.frequency??null,sig:u.sig??null,rxNumber:u.rx_number??null,startedOn:u.started_on??null,stoppedOn:u.stopped_on??null,docId:u.doc_id??null}));return Object.freeze({petRef:o,withheld:false,isEmpty:s.length===0&&c.length===0&&a.length===0&&d.length===0,visits:Object.freeze(s),vaccines:Object.freeze(c),weights:Object.freeze(a),medications:Object.freeze(d),disclaimer:l.disclaimer??""})}i(Ty,"mapRecordsTimeline");function _y(e,t){let r=Gi(t)?t:{},o=Yi(r,e),n=i(()=>Object.freeze({petRef:o,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(r.withheld===true)return n();let l=Sy.safeParse(r);if(!l.success)return n();let s=Object.freeze(l.data.contributions.map(Bo));return Object.freeze({petRef:o,withheld:false,document:Ho(l.data.document),contributions:s,contributionCount:l.data.contribution_count??s.length})}i(_y,"mapDocumentContributions");var Py="/widget/v1/records/pets";function lc(e){let t=e.funnel??mr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!yr(a)&&[...a].length<=d,"segment"),o=i(async(a,d,u,p)=>{if(!r(d,mt))return Rr();let f=await t.send(a,{method:"GET",path:u});if(!f.ok)return f;let h=p(f.value);return h.petRef===d?_e(h):B(q("internalError",{retryable:false}))},"read"),n=i(a=>`${Py}/${encodeURIComponent(a)}`,"pet"),l=i(a=>`${n(a)}/everfur_record`,"record"),s=i(async(a,d,u)=>{let p=await t.send(a,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!p.ok)return p;let f=u(p.value);return f===null?B(q("internalError",{retryable:false})):_e(f)},"parsed"),c=i((a,d)=>!r(a.entityType,Kl)||!r(a.canonicalKey,Ql)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,tn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:a.entityType,canonical_key:a.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...a.idempotencyKey!==void 0?{idempotency_key:a.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(a=>o("records.depth.record",a,`${n(a)}/record`,d=>ky(a,d)),"getRecordDepth"),getTimeline:i(a=>o("records.depth.timeline",a,`${n(a)}/timeline`,d=>Ty(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?o("records.depth.contributions",a,`${n(a)}/documents/${encodeURIComponent(d)}/contributions`,u=>_y(a,u)):Rr()},getMarkers:i(a=>o("records.depth.markers",a,`${n(a)}/markers`,d=>rc(a,d)),"getMarkers"),createShare(a){return r(a,mt)?s("records.share.create",{method:"POST",path:`${l(a)}/share`},d=>nc(d,e.apiBaseUrl)):Rr()},listShares(a){return r(a,mt)?s("records.share.list",{method:"GET",path:`${l(a)}/shares`},oc):Rr()},async revokeShare(a,d){if(!r(a,mt)||!r(d,64))return Rr();let u=await t.send("records.share.revoke",{method:"DELETE",path:`${l(a)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return u.ok?_e(void 0):u},getPdfLink(a){return r(a,mt)?s("records.pdf.link",{method:"GET",path:`${l(a)}/pdf-link`},ic):Rr()},async editFact(a,d){let u=r(a,mt)?c(d,d.correctedFields):null;if(u===null)return Rr();let p=await t.send("records.fact.edit",{method:"POST",path:`${l(a)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return p.ok?_e(void 0):p},async removeFact(a,d){let u=r(a,mt)?c(d):null;if(u===null)return Rr();let p=await t.send("records.fact.remove",{method:"POST",path:`${l(a)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return p.ok?_e(void 0):p},listAuthorizationSignatures:i(()=>s("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},ac),"listAuthorizationSignatures")}}i(lc,"createRecordsDepthClient");function Rr(){return Promise.resolve(B(q("validationFailed",{retryable:false})))}i(Rr,"invalid");function sr(){let{runtime:e,userRef:t,scopeEpoch:r}=ke();return useMemo(()=>{let{services:o}=e.registry;return lc({auth:o.authFor(t),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,t,r])}i(sr,"useEverfurRecordsDepthClient");function Ut(e,t,r,o=""){let n=sr(),{userRef:l}=ke(),s=Mn(e),c=useMemo(()=>({}),[n,e,o,s]),[a,d]=useState({scope:c,value:null,error:null,loading:true}),u=useRef(0),p=useCallback(async()=>{let g=u.current+=1;if(d({scope:c,value:null,error:null,loading:true}),l===null){d({scope:c,value:null,error:null,loading:false});return}let b=await t(n,e);g===u.current&&(b.ok?d({scope:c,value:b.value,error:null,loading:false}):d({scope:c,value:null,error:b.error,loading:false}));},[n,e,t,c,l]);useEffect(()=>(p(),()=>{u.current+=1;}),[p]);let f=a.scope===c?a:{value:null,error:null,loading:true},h=useCallback(()=>{p();},[p]),R=f.error===null||f.error.httpStatus!==404,v=R?f.error:null,y=f.loading?"loading":v!==null?"error":f.value===null?"empty":f.value.withheld?"populated":r(f.value)?"empty":"populated";return useMemo(()=>({status:y,value:f.value,error:v,available:R,refresh:h}),[y,f.value,v,R,h])}i(Ut,"useRecordsDepthRead");function vr(e){return e!==null&&e.httpStatus===404}i(vr,"isDarkRouteError");var Ly=i((e,t)=>e.getMarkers(t),"readMarkers"),Vy=i(e=>e.markers.length===0,"markersEmpty");function Qi(e){let t=Ut(e,Ly,Vy);return useMemo(()=>{let r=t.available&&t.value!==null&&!t.value.withheld?t.value:null;return {status:t.status,markers:r,available:t.available,error:t.error,refresh:t.refresh}},[t])}i(Qi,"useRecordsMarkers");var qy=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function uc(e){let{clinic:t,controller:r,depthClient:o,capture:n,onCreated:l}=e,s=t.clinic?.name??t.freeText??"",c=t.clinic===null,[a,d]=useState(false),[u,p]=useState(e.ownerName),[f,h]=useState(t.email),[R,v]=useState(false),[y,g]=useState(null),[b,w]=useState(null),[x,E]=useState(0),[D,k]=useState(null),[S,I]=useState(false),[Y,z]=useState(null),[$,G]=useState([]),[Z,oe]=useState(null),[Ee,H]=useState(false),C=useRef(false),T=useRef(true),A=useRef(rr()),M=useRef(null);useEffect(()=>(T.current=true,()=>{T.current=false,M.current=null;}),[r]),useEffect(()=>{let Se=true;return g(null),M.current=null,r.getAuthorizationCopy().then(F=>{Se&&(F.ok?(g(F.value),w(null)):w(F.error));}).catch(()=>{Se&&w(q("internalError"));}),()=>{Se=false;}},[r,x]),useEffect(()=>{if(o===void 0)return;let Se=true;return o.listAuthorizationSignatures().then(F=>{Se&&(F.ok?G(F.value):vr(F.error)||G([]));}).catch(()=>{}),()=>{Se=false;}},[o]);let K=fn(t.clinic),ye=f.trim().toLowerCase(),Ve=qy.test(ye),ie=K&&(R||ye.length>0)&&!Ve?se.emailRequired:null,we=y?yn(y,u.trim(),He(e.petName),s):null,vt=e.hostCapture===true||Ee||Z!==null,Xe=!!(a&&y&&we&&u.trim()&&s&&vt&&(!K||Ve)),Vt=useCallback(async()=>{if(!(C.current||Y!==null||!y||!we)){if(!s){k(se.missingDraftError);return}if(K&&!Ve){v(true),k(se.emailRequired);return}if(!(!a||!u.trim())){C.current=true,I(true),k(null);try{if(M.current===null){let F=Z!==null?{signatureId:Z}:await n();if(!T.current)return;if(F===null){k(se.missingSignatureError);return}let Re=t.clinic&&(!K||t.clinic.emailStatus==="none")?{clinicId:t.clinic.id}:{clinicFreeText:s};M.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:y.authorizationVersion,...Re,...K?{clinicEmail:ye}:{},...F.signatureId!==void 0?{signatureId:F.signatureId}:{signaturePngBase64:F.signaturePngBase64},idempotencyKey:A.current()};}let Se=await r.createClinicRequest(M.current);if(!T.current)return;if(!Se.ok){k(Se.error.displayMessage);return}if(Se.value.petRef!==e.petRef){k(q("internalError").displayMessage);return}z(Se.value),M.current=null,l?.(Se.value);}catch{T.current&&k(q("internalError").displayMessage);}finally{C.current=false,T.current&&I(false);}}}},[a,n,t.clinic,s,r,y,Y,e.petRef,K,ye,l,u,Z,we,Ve]),qt=useCallback(()=>{M.current=null,k(null);},[]);return {title:c?se.titleFreeText:se.titleDirectory,clinicName:s,isFreeText:c,authorized:a,ownerName:u,email:f,emailError:ie,needsEmail:K,directoryClinicNoEmail:K&&t.clinic!==null,copy:y,copyError:b,scope:we,error:D,busy:S,created:Y,ready:Xe,signatures:$,reuseSignatureId:Z,hasSignature:vt,setAuthorized(Se){C.current||(qt(),d(Se));},setOwnerName(Se){C.current||(qt(),p(Se));},setEmail(Se){C.current||(qt(),v(false),h(Se));},setSigned(Se){C.current||(qt(),H(Se),Se&&oe(null));},pickReuseSignature(Se){C.current||(qt(),oe(Se));},retryCopy(){w(null),E(Se=>Se+1);},submit:Vt}}i(uc,"useRecordsConsentForm");function Zi(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",style:e.style,...Be(e.onBack,Ze),children:t===null?jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsx(By,{...Fe(e,["onCreated","onNavigate","onBack"])},JSON.stringify([t,r,e.petRef,e.clinic.key]))})}i(Zi,"EverfurRecordsConsent");function By({petRef:e,petName:t,clinic:r,ownerName:o,onCaptureSignature:n,onCreated:l,controller:s,onNavigate:c,onBack:a,style:d}){let u=be(),p=Hy(),f=L(),h=Nt(),R=sr(),[v,y]=useState(null),[g,b]=useState("draw"),w=useCallback(async()=>v===null?null:{signaturePngBase64:v},[v]),x=uc({petRef:e,petName:t,ownerName:o??"",clinic:r,controller:s??h,depthClient:R,capture:n?()=>n({petRef:e,petName:He(t),ownerName:x.ownerName,clinicName:x.clinicName,authorizationVersion:x.copy?.authorizationVersion??"",scopeText:x.scope??"",signal:new AbortController().signal}):w,hostCapture:n!==void 0,onCreated:i(S=>{l?.(S),c?.({name:"dashboard"});},"onCreated")}),E=useRef(x);E.current=x;let D=useCallback(S=>{y(S),E.current.setSigned(S!==null);},[]),k=x.busy;return jsxs(View,{style:[u.root,d],children:[jsx(et,{title:x.title,onBack:a,testID:"records-consent-header"}),jsxs(KeyboardAvoidingView,{behavior:"padding",style:u.body,children:[jsxs(ScrollView,{contentContainerStyle:p.content,keyboardShouldPersistTaps:"handled",testID:"records-consent",children:[jsxs(View,{style:p.scopeCard,accessibilityRole:"summary",children:[jsx(m,{style:p.scopeHeading,accessibilityRole:"header",children:se.scopeHeading}),jsx(m,{style:p.scopeBody,children:se.scopeBody}),jsx(View,{style:p.bullets,children:se.whatWeDo.map(S=>jsxs(View,{style:p.bulletRow,children:[jsx(m,{style:p.check,children:"\u2713"}),jsx(m,{style:p.bulletText,children:S})]},S))}),jsx(View,{style:p.retentionRow,children:jsx(m,{style:p.retentionText,children:se.retentionNote})}),x.copy&&x.scope?jsx(m,{style:p.serverScope,testID:"records-consent-scope",children:x.scope}):x.copyError?jsxs(Fragment,{children:[jsx(m,{style:u.errorText,accessibilityRole:"alert",children:x.copyError.displayMessage}),jsx(re,{label:ce.retry,kind:"outline",onPress:x.retryCopy,testID:"records-consent-copy-retry"})]}):jsx(m,{style:u.muted,accessibilityLiveRegion:"polite",children:ce.loading})]}),jsxs(Pressable,{onPress:()=>x.setAuthorized(!x.authorized),accessibilityRole:"checkbox",accessibilityState:{checked:x.authorized},accessibilityLabel:se.authorizeLabel(t,x.clinicName),hitSlop:6,style:[p.toggle,x.authorized?p.toggleChecked:null],testID:"records-authorize-toggle",children:[jsx(View,{style:[p.box,x.authorized?p.boxChecked:null],accessibilityElementsHidden:true,importantForAccessibility:"no",children:x.authorized?jsx(m,{style:p.boxCheck,children:"\u2713"}):null}),jsx(m,{style:p.toggleLabel,children:se.authorizeLabel(t,x.clinicName)})]}),jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:se.fullName}),jsx(qe,{accessibilityLabel:se.fullName,style:u.field,value:x.ownerName,placeholder:se.fullNamePlaceholder,placeholderTextColor:f.color.text.placeholder,maxLength:200,editable:!k,autoComplete:"name",autoCapitalize:"words",onChangeText:x.setOwnerName,testID:"records-consent-owner-name"})]}),x.needsEmail?jsxs(View,{style:p.block,testID:"records-consent-email-block",children:[x.directoryClinicNoEmail?jsx(View,{style:u.cautionNote,testID:"records-consent-no-email-note",children:jsx(m,{style:u.cautionNoteText,children:se.noEmailNote(t,x.clinicName)})}):null,jsx(m,{style:u.fieldLabel,children:se.emailLabel}),jsx(qe,{accessibilityLabel:se.emailLabel,style:u.field,value:x.email,placeholder:se.emailPlaceholder,placeholderTextColor:f.color.text.placeholder,maxLength:320,editable:!k,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:x.setEmail,testID:"records-consent-clinic-email"}),x.emailError?jsx(m,{style:u.errorText,accessibilityRole:"alert",children:x.emailError}):null,jsx(m,{style:u.muted,testID:"records-consent-review-note",children:se.newClinicDirectSendNote})]}):null,n?null:jsxs(View,{style:p.signatureBlock,children:[x.signatures.length>0?jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:se.reuseSignature}),jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:p.gallery,children:x.signatures.map(S=>{let I=x.reuseSignatureId===S.signatureId;return jsx(Pressable,{onPress:()=>x.pickReuseSignature(I?null:S.signatureId),accessibilityRole:"button",accessibilityLabel:I?se.reuseTileSelectedA11y:se.reuseTileA11y,style:[p.tile,I?p.tileSelected:null],testID:`records-consent-reuse-${S.signatureId}`,children:jsx(Image,{source:{uri:S.previewUrl},style:p.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},S.signatureId)})}),jsx(m,{style:u.muted,children:se.reuseHint})]}):null,jsx(View,{style:p.signatureHeader,children:jsx(m,{style:u.fieldLabel,children:g==="type"?se.signType:se.signDraw})}),jsx(Lr,{onChange:D,disabled:k}),jsx(Pressable,{onPress:()=>b(S=>S==="draw"?"type":"draw"),accessibilityRole:"button",accessibilityLabel:g==="draw"?se.toTypeA11y:se.toDraw,style:p.modeToggle,testID:"records-consent-sign-mode-toggle",children:jsx(m,{style:p.modeToggleText,children:g==="draw"?se.toType:se.toDraw})}),jsx(m,{style:u.muted,children:se.signatureHint(x.clinicName)})]}),x.error?jsx(View,{style:u.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:jsx(m,{style:u.errorText,children:x.error})}):null,x.created?jsx(m,{accessibilityLiveRegion:"polite",style:u.bodyText,children:x.created.statusLabel||ce.records}):null]}),jsx(View,{style:p.footer,children:jsx(re,{label:k?se.submitting:se.submit,accessibilityLabel:se.submitA11y,disabled:!x.ready,busy:k,onPress:()=>{x.submit();},style:p.submit,testID:"records-consent-submit"})})]}),jsx(Me,{})]})}i(By,"ConsentBody");function Hy(){let e=L();return useMemo(()=>Uy(e),[e])}i(Hy,"useLocalStyles");function Uy(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=i((c,a,d,u="regular")=>({..._(e,u),fontSize:c,lineHeight:Math.round(c*a),color:d}),"text");return StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xl+r.xs,gap:r.lg+r.xs/2},scopeCard:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md},scopeHeading:{...s(n.size.body+1,n.lineHeight.snug,t.brandInk,"bold")},scopeBody:s(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),bullets:{gap:r.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:r.sm},check:{...s(n.size.body,n.lineHeight.normal,t.brandInk,"bold")},bulletText:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,t.text.primary)},retentionRow:{paddingTop:r.xs,borderTopWidth:1,borderTopColor:t.borderHairlineGreen},retentionText:s(n.size.tiny,n.lineHeight.normal,t.text.muted),serverScope:{...s(n.size.bodyTight,n.lineHeight.relaxed,t.text.secondary),paddingTop:r.xs},toggle:{flexDirection:"row",alignItems:"flex-start",gap:r.md,borderRadius:o.lg-r.xs,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2},toggleChecked:{borderColor:t.brandInk,backgroundColor:t.brandSoft},box:{width:r.xl,height:r.xl,borderRadius:o.xs+1,borderWidth:1.6,borderColor:t.brandInk,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},boxChecked:{backgroundColor:t.brandInk},boxCheck:{...s(n.size.body,n.lineHeight.tight,t.surface,"bold")},toggleLabel:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"bold")},block:{gap:r.sm},signatureBlock:{gap:r.sm},gallery:{gap:r.sm,paddingVertical:r.xs},tile:{width:r.xxl*3+r.lg,height:r.xxl+r.lg+r.sm,borderRadius:o.sm,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,overflow:"hidden"},tileSelected:{borderColor:t.brandInk,borderWidth:2},tileImage:{width:"100%",height:"100%"},signatureHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},modeToggle:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},modeToggleText:{...s(n.size.bodyTight,n.lineHeight.snug,t.linkInk,"bold"),textDecorationLine:"underline"},footer:{paddingHorizontal:r.lg,paddingTop:r.md,paddingBottom:r.xxl,borderTopWidth:l,borderTopColor:t.borderHairlineGreen,backgroundColor:t.background},submit:{minHeight:r.xxl+r.lg+r.xs+r.xs/2}})}i(Uy,"makeLocalStyles");function fo(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(fo,"markerStatusTone");function $y(e){switch(e){case "above":return "above the reference range";case "below":return "below the reference range";case "in_range":return "within range";default:return "no reference range on file"}}i($y,"markerStatusSpoken");function Wy(e){return e.refLow!==null&&e.refHigh!==null?`, reference range ${e.refLow} to ${e.refHigh}`:e.refLow!==null?`, reference range at least ${e.refLow}`:e.refHigh!==null?`, reference range up to ${e.refHigh}`:""}i(Wy,"rangePhrase");function go(e,t){let r=t?` ${t}`:"";return e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}${r}`:e.refLow!==null?`\u2265 ${e.refLow}${r}`:e.refHigh!==null?`\u2264 ${e.refHigh}${r}`:"-"}i(go,"formatReferenceRange");function gc(e,t){let r=t.reviewed?", reviewed by our team":"",o=t.sourceClinic?`, from ${t.sourceClinic}`:"";return `${Q(t.at)}: ${Et(t.value,e.unit,t.qualitativeResult)}, ${$y(t.status)}${Wy(t)}${o}${r}`}i(gc,"markerPointSpoken");function Ge(e){return e?.trim()||"my pet"}i(Ge,"lead");function bc(e){let t=e.trim();return /[.!?]$/.test(t)?t:`${t}.`}i(bc,"clause");function hc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${Ge(e)}'s ${r}`],n=[t.latestValueText?.trim(),t.statusText?.trim(),t.trajectoryText?.trim()].filter(Boolean).join(", ");return o[0]+=n?`: ${n}.`:".",t.meaningText?.trim()&&o.push(bc(t.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${Ge(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:t.markerId,payload:{marker:r,...t.statusText?.trim()?{status:t.statusText.trim()}:{}}}}}i(hc,"buildMarkerAskPrompt");function Rc(e,t,r){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:l,unknownCount:s}=t;if(o===0)return {prompt:`I'm looking at ${Ge(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${Ge(e)}?`,entityRef:{type:"marker_summary",id:r,payload:{total:0}}};let c=s>0?`, ${s} without a reference range`:"";return {prompt:`I'm looking at ${Ge(e)}'s lab markers: ${o} total, ${n} in range, ${l} out of range${c}. What should I focus on?`,entityRef:{type:"marker_summary",id:r,payload:{total:o,inRange:n,outOfRange:l,unknown:s}}}}i(Rc,"buildMarkerSummaryAskPrompt");function vc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`${r}: ${t.valueText.trim()}`];t.collectedAt?.trim()&&o.push(`collected ${t.collectedAt.trim()}`),t.sourceClinic?.trim()&&o.push(`from ${t.sourceClinic.trim()}`),t.referenceText?.trim()&&o.push(`reference range ${t.referenceText.trim()}`),t.flagged&&o.push(`flagged ${t.flagged}`);let n={marker:r};return t.flagged&&(n.status=t.flagged),t.reviewed!==void 0&&(n.reviewed=t.reviewed),{prompt:`I'm looking at ${Ge(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:t.entityId,payload:n}}}i(vc,"buildMarkerReadingAskPrompt");function xc(e,t,r){let o=t.clinicName?.trim(),n=t.heldItemCount??0,l=n>0?`, ${n} fact${n===1?"":"s"} being verified`:"";return {prompt:`I'm looking at ${Ge(e)}'s records request${o?` to ${o}`:""}, status: ${t.statusLabel.trim()}${l}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:r,payload:{status:t.status,held:n,...o?{clinic:o}:{}}}}}i(xc,"buildRecordsRequestAskPrompt");var Gy=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function wc(e,t,r,o){let n=t.entityTypeLabel.trim()||"record",l=t.title.trim()||n,s=t.detail?.trim();return {prompt:`I'm looking at ${Ge(e)}'s ${n.toLowerCase()}: ${l}${s?`, ${s}`:""}. What does this mean, and what should I keep on top of for ${Ge(e)}?`,entityRef:{type:Gy[r]??r,id:o,payload:{kind:n,title:l,...s?{detail:s}:{}}}}}i(wc,"buildEntityRowAskPrompt");function Cc(e,t,r){let o=t.filter(s=>s.label.trim()),n={type:"upcoming_care",id:r};if(o.length===0)return {prompt:`I'm looking at ${Ge(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${Ge(e)} be on?`,entityRef:n};let l=[...o].sort((s,c)=>(s.tone==="overdue"?0:1)-(c.tone==="overdue"?0:1)).slice(0,4).map(s=>s.relativeText.trim()?`${s.label.trim()} (${s.relativeText.trim().toLowerCase()})`:s.label.trim());return {prompt:`I'm looking at ${Ge(e)}'s upcoming care: ${l.join(", ")}. What should I prioritize for ${Ge(e)}, and how do I stay on top of these?`,entityRef:n}}i(Cc,"buildUpcomingCareAskPrompt");function Ec(e,t,r){let o=[`I'm looking at ${Ge(e)}'s physical exam${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`],n=t.abnormal.filter(l=>l.system.trim());return n.length>0?(o.push(`Abnormal: ${n.slice(0,6).map(l=>`${l.system.trim()}: ${l.finding.trim()}`).join("; ")}.`),o.push(`What do these findings mean, and what should I follow up on for ${Ge(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${Ge(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:r}}}i(Ec,"buildPhysicalExamAskPrompt");function Sc(e,t,r){let o=[`I'm looking at ${Ge(e)}'s visit notes${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`];for(let n of t.sections.filter(l=>l.text.trim()).slice(0,3))o.push(`${n.label.trim()||"Note"}: ${bc(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${Ge(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:r}}}i(Sc,"buildVisitNoteAskPrompt");function kc(e,t,r){let o=t.scopeLabel.trim()||"a detail",n=t.candidates.filter(s=>s.value.trim()),l=n.slice(0,3).map(s=>`"${s.value.trim()}"${s.clinicName?.trim()?` (${s.clinicName.trim()})`:""}`).join(" vs ");return {prompt:`Two of ${Ge(e)}'s documents disagree on ${o}: ${l}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:r,payload:{field:o,severity:t.severity,values:n.map(s=>s.value.trim()).join(" | ")}}}}i(kc,"buildConflictAskPrompt");function Cn(e){return e!==void 0}i(Cn,"canUploadRecords");function ea(e,t){return e??t?.version??""}i(ea,"resolveConsentVersion");function qr(e,t){return ea(e,t).length>0}i(qr,"canGrantConsent");function xr(e,t){return e.denialReason==="consent_required"?t?{kind:"consent_required"}:{kind:"consent_unavailable"}:e.denialReason==="pet_not_found"?{kind:"pet_not_found",error:q("petNotFound",{retryable:false})}:e.denialReason==="entitlement"?{kind:"error",error:q("accessDenied")}:e.denialReason==="session_required"?{kind:"session_required"}:e.withheld?{kind:"withheld"}:e.error===null?{kind:"withheld"}:{kind:"error",error:e.error}}i(xr,"selectErrorView");function bo(e){let t=e.clinicName?.trim()??"";return t.length>0?t:e.source==="owner_provided"?Tc.ownerUpload:Tc.clinicRequest}i(bo,"selectRequestTitle");var Tc=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function Yy(e){let t=[...e].sort((r,o)=>r.updatedAt!==o.updatedAt?r.updatedAt>o.updatedAt?-1:1:r.createdAt!==o.createdAt?r.createdAt>o.createdAt?-1:1:0);return Object.freeze(t)}i(Yy,"selectRequestList");function En(e){let t=e.actionNeededLabel?.trim()??"";return t.length>0?t:e.statusLabel}i(En,"selectPrimaryLabel");function ho(e){if(e.showClinicPhone!==true)return null;let t=e.clinicPhone?.trim()??"";return t.length===0?null:{phone:t,dial:`tel:${t.replace(/[^+\d]/g,"")}`,clinicName:e.clinicName?.trim()||null}}i(ho,"selectClinicCall");var gt=200,Pc=16;function Qy(e,t){let r=e.inRangeCount+e.outOfRangeCount+e.unknownCount;if(!Number.isFinite(r)||r<=0)return [];let o=[{key:"in_range",color:t.inRange,count:e.inRangeCount},{key:"out_of_range",color:t.outOfRange,count:e.outOfRangeCount},{key:"unknown",color:t.unknown,count:e.unknownCount}],n=0,l=[];for(let s of o){if(!(s.count>0))continue;let c=s.count/r*360;if(!Number.isFinite(c))return null;l.push({key:s.key,color:s.color,startDeg:n,sweepDeg:c}),n+=c;}return l}i(Qy,"buildRingSegments");function Dc({summary:e,onAsk:t,testID:r}){let o=Jy(),n=L(),{totalMarkers:l,inRangeCount:s,outOfRangeCount:c,unknownCount:a}=e,d=useMemo(()=>Qy(e,{inRange:n.color.success,outOfRange:n.color.danger,unknown:n.color.text.muted}),[e,n]),u=d!==null&&d.length>0;return jsxs(View,{style:o.card,accessibilityRole:"summary",testID:r,children:[jsx(m,{style:o.title,children:Mt.title}),jsx(View,{style:o.ringRow,accessible:true,accessibilityRole:"image",accessibilityLabel:Mt.a11y(l,s,c,a),children:jsxs(View,{style:o.ringWrap,children:[jsx(View,{style:o.track}),d===null?null:d.map(p=>jsx(Xy,{segment:p,styles:o},p.key)),jsxs(View,{style:o.center,pointerEvents:"none",children:[jsx(m,{style:o.centerCount,children:l}),jsx(m,{style:o.centerLabel,children:l===1?Mt.marker:Mt.markers})]})]})}),u||d===null?jsxs(View,{style:o.badges,children:[jsx(ta,{count:c,label:Mt.outOfRange,color:n.color.danger,styles:o}),jsx(ta,{count:s,label:Mt.inRange,color:n.color.success,styles:o}),a>0?jsx(ta,{count:a,label:Mt.noRange,color:n.color.text.muted,styles:o}):null]}):null,jsx(m,{style:o.subtitle,children:Mt.subtitle}),t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Mt.askA11y,style:o.ask,testID:"marker-summary-ask",children:jsx(m,{style:o.askLabel,children:Mt.ask})}):null]})}i(Dc,"MarkerSummaryCard");function Xy({segment:e,styles:t}){return (e.sweepDeg<=180?[{start:e.startDeg,sweep:e.sweepDeg}]:[{start:e.startDeg,sweep:180},{start:e.startDeg+180,sweep:e.sweepDeg-180}]).map((o,n)=>jsx(View,{style:[t.piece,{transform:[{rotate:`${o.start}deg`}]}],pointerEvents:"none",testID:`marker-ring-${e.key}`,children:jsx(View,{style:t.window,children:jsx(View,{style:[t.halfRing,{borderTopColor:e.color,borderRightColor:e.color,transform:[{rotate:`${o.sweep-135}deg`}]}]})})},n))}i(Xy,"Arc");function ta({count:e,label:t,color:r,styles:o}){return jsx(View,{style:[o.badge,{borderColor:r}],children:jsx(m,{style:[o.badgeText,{color:r}],children:`${e} ${t}`})})}i(ta,"Badge");function Jy(){let e=L();return useMemo(()=>Zy(e),[e])}i(Jy,"useStyles");function Zy(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=StyleSheet.hairlineWidth,c=ot(l.recordCard);return StyleSheet.create({card:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.brandBorder,padding:r.lg-1,gap:r.sm+r.xs/2,...Je(l.recordCard,s)},title:{..._(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.letterSpacing.headerBrand,...c},ringRow:{alignItems:"center"},ringWrap:{width:gt,height:gt,alignItems:"center",justifyContent:"center"},track:{position:"absolute",width:gt,height:gt,borderRadius:gt/2,borderWidth:Pc,borderColor:t.surfaceSubtle},piece:{position:"absolute",width:gt,height:gt},window:{position:"absolute",left:gt/2,top:0,width:gt/2,height:gt,overflow:"hidden"},halfRing:{position:"absolute",left:-gt/2,top:0,width:gt,height:gt,borderRadius:gt/2,borderWidth:Pc,borderBottomColor:"transparent",borderLeftColor:"transparent"},center:{position:"absolute",alignItems:"center",justifyContent:"center"},centerCount:{..._(e,"medium"),fontSize:n.size.verdict*2,lineHeight:n.size.verdict*2+r.xs,color:t.text.primary,textAlign:"center",...c},centerLabel:{..._(e,"medium"),fontSize:n.size.heading-1,lineHeight:n.size.heading+r.xs/2,color:t.text.primary,textAlign:"center",...c},badges:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center",gap:r.sm},badge:{borderWidth:1,borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs},badgeText:{..._(e,"mono"),fontSize:n.size.nano,lineHeight:n.size.tiny,letterSpacing:n.letterSpacing.headerBrand/2,textTransform:"uppercase"},subtitle:{..._(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.relaxed),color:t.text.primary,...c},ask:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.sm,marginTop:r.xs/2,paddingHorizontal:r.lg,borderRadius:o.pill,borderWidth:s,borderColor:t.borderRingCream,backgroundColor:t.surface},askLabel:{..._(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.primary,letterSpacing:n.letterSpacing.tight}})}i(Zy,"makeStyles");function ef(e){return e.value!==null&&Number.isFinite(e.value)}i(ef,"numeric");function Ac(e){let t=e.points.filter(ef);if(t.length===0)return null;let r=e.points[e.points.length-1]??null,o=r?.refLow??null,n=r?.refHigh??null,l=t.map(g=>g.value),s=Math.min(...l,...o!==null?[o]:[],...n!==null?[n]:[]),c=Math.max(...l,...o!==null?[o]:[],...n!==null?[n]:[]);s===c&&(s-=1,c+=1);let a=(c-s)*.18,d=s-a,u=c+a,p=u-d,f=i(g=>(u-g)/p*100,"y"),h=6,R=t.length,v=t.map((g,b)=>({index:b,xPct:R<=1?50:h+b/(R-1)*(100-2*h),yPct:f(g.value),status:g.status,point:g})),y=o!==null||n!==null?{topPct:n!==null?f(n):0,bottomPct:o!==null?f(o):100}:null;return {points:v,band:y,firstDate:t[0]?.at??null,lastDate:t[t.length-1]?.at??null}}i(Ac,"buildMarkerChart");var nf=416,of=140;function vo(e){return `${e}%`}i(vo,"pct");function af({marker:e,width:t,onPointPress:r,onAsk:o}){let n=ra(),l=be(),s=Qt(e.latest?.status??null),c=fo(e.latest?.status??null),a=Hr(e.trajectory,e.points.length),d=useMemo(()=>Ac(e),[e]),u=e.latest?Et(e.latest.value,e.unit,e.latest.qualitativeResult):null;return jsx(View,{style:[n.page,t!==void 0?{width:t}:null],testID:`marker-card-${e.markerId}`,children:jsxs(View,{style:n.card,children:[jsxs(View,{style:n.headerRow,children:[jsxs(View,{style:n.nameColumn,children:[jsx(m,{style:n.markerName,numberOfLines:2,children:e.name}),e.unit?jsx(m,{style:n.unit,children:e.unit}):null]}),jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:or.status(s.label),children:jsx(Kt,{label:s.label,tone:c})})]}),e.latest&&u!==null?jsxs(View,{style:n.latestRow,children:[jsx(m,{style:[n.latestValue,s.outOfRange?n.latestValueDanger:null],accessibilityLabel:or.latestA11y(u,s.label,Q(e.latest.at)),children:u}),jsx(m,{style:n.latestDate,children:Q(e.latest.at)})]}):null,a?jsx(m,{style:n.trajectory,accessibilityRole:"text",children:a}):null,d!==null?jsxs(View,{style:n.chartWrap,children:[jsxs(View,{style:n.plot,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[d.band?jsx(View,{style:[n.band,{top:vo(d.band.topPct),height:vo(Math.max(0,d.band.bottomPct-d.band.topPct))}]}):null,d.points.map(p=>jsx(Pressable,{onPress:()=>r(e,p.point),hitSlop:12,style:[n.point,p.status==="above"||p.status==="below"?n.pointDanger:null,{left:vo(p.xPct),top:vo(p.yPct)}],testID:`marker-point-${e.markerId}-${p.index}`},p.index))]}),jsx(View,{style:n.a11yTable,accessibilityRole:"summary",accessibilityLabel:or.readingsA11y(e.name),children:e.points.map((p,f)=>jsx(View,{accessibilityRole:"text",accessibilityLabel:gc(e,p)},f))}),jsx(m,{style:e.points.length===1?n.singleHint:n.tapHint,children:e.points.length===1?or.singleHint:or.tapHint})]}):jsx(View,{style:n.emptyBody,accessibilityRole:"text",children:jsx(m,{style:n.emptyText,children:or.empty})}),o?jsx(Pressable,{onPress:()=>o(e),accessibilityRole:"button",accessibilityLabel:or.askA11y(e.name),style:[l.pill,l.pillAsk],testID:`marker-ask-${e.markerId}`,children:jsx(m,{style:l.pillAskLabel,children:or.ask})}):null]})})}i(af,"MarkerTrendCard");function qc({markers:e,onPointPress:t,onAsk:r}){let o=ra(),[n,l]=useState(0),[s,c]=useState(0),a=i(p=>l(p.nativeEvent.layout.width),"onLayout"),d=i(p=>{if(n<=0)return;let f=Math.round(p.nativeEvent.contentOffset.x/n);c(Math.max(0,Math.min(f,e.length-1)));},"onMomentumEnd"),u=e[s]??null;return jsxs(View,{style:o.carousel,onLayout:a,testID:"marker-carousel",children:[jsx(ScrollView,{horizontal:true,pagingEnabled:true,showsHorizontalScrollIndicator:false,onMomentumScrollEnd:d,snapToAlignment:"start",children:e.map(p=>jsx(af,{marker:p,width:n>0?n:void 0,onPointPress:t,onAsk:r},p.markerId))}),jsxs(View,{style:o.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:wi.a11y(u?.name??null,s,e.length),children:[jsx(View,{style:o.dots,children:e.map((p,f)=>jsx(View,{style:[o.dot,f===s?o.dotActive:null]},p.markerId))}),jsx(m,{style:o.counter,children:wi.counter(s,e.length)})]})]})}i(qc,"MarkerTrendCarousel");function Fc({marker:e,point:t,onClose:r,onAsk:o}){let n=ra(),l=be();if(e===null||t===null)return null;let s=i((c,a)=>jsxs(View,{style:n.detailRow,accessible:true,accessibilityRole:"text",accessibilityLabel:`${c}: ${a}`,children:[jsx(m,{style:n.detailLabel,children:c}),jsx(m,{style:n.detailValue,children:a})]},c),"row");return jsxs(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:r,children:[jsx(Pressable,{style:n.backdrop,onPress:r,accessibilityRole:"button",accessibilityLabel:Ct.close}),jsxs(View,{style:n.sheet,accessibilityViewIsModal:true,testID:"marker-provenance-sheet",children:[jsx(View,{style:n.handle}),jsxs(View,{style:n.sheetHeader,children:[jsx(m,{style:n.sheetTitle,accessibilityRole:"header",children:Ct.title}),jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Ct.close,hitSlop:10,style:n.closeButton,testID:"marker-provenance-close",children:jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsxs(View,{style:n.sheetBody,children:[jsxs(View,{style:n.valueRow,children:[jsx(m,{style:n.sheetName,children:e.name}),jsx(m,{style:n.sheetValue,children:Et(t.value,e.unit,t.qualitativeResult)})]}),t.reviewed?jsx(View,{style:n.reviewed,accessibilityRole:"text",children:jsx(m,{style:n.reviewedText,children:Ct.reviewed})}):null,s(Ct.collected,Q(t.at)),t.sourceClinic?s(Ct.clinic,t.sourceClinic):null,s(Ct.referenceRange,t.refLow!==null||t.refHigh!==null?go(t,e.unit):Ct.noRange),t.docId?s(Ct.sourceDocument,t.docId):null,t.reviewed?null:jsx(m,{style:n.unverified,accessibilityRole:"text",children:Ct.unverified}),o?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Ct.askA11y,style:[l.pill,l.pillAsk],testID:"marker-provenance-ask",children:jsx(m,{style:l.pillAskLabel,children:Ct.ask})}):null]})]})]})}i(Fc,"MarkerProvenanceSheet");function ra(){let e=L();return useMemo(()=>sf(e),[e])}i(ra,"useStyles");function sf(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=StyleSheet.hairlineWidth,c=r.md,a=i((f,h,R,v="regular")=>({..._(e,v),fontSize:f,lineHeight:Math.round(f*h),color:R}),"text"),d=ot(l.recordCard),u=a(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold"),p=a(n.size.verdict+r.xs,n.lineHeight.tight,t.text.primary,"bold");return StyleSheet.create({page:{paddingHorizontal:r.sm},card:{borderRadius:o.lg-r.xs/2,borderWidth:s,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg,gap:r.md,...Je(l.recordCard,s)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm+r.xs/2},nameColumn:{flex:1,gap:r.xs/2},markerName:{...u,...d},sheetName:u,unit:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted,...d},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},latestValue:{...p,...d},sheetValue:p,latestValueDanger:{color:t.danger},latestDate:{...a(n.size.caption,n.lineHeight.normal,t.text.muted),...d},trajectory:{...a(n.size.bodyTight,n.lineHeight.normal,t.text.muted),...d},chartWrap:{gap:r.sm},plot:{height:of,borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:t.badgeBgPositive},point:{position:"absolute",width:c,height:c,borderRadius:c/2,marginLeft:-c/2,marginTop:-c/2,backgroundColor:t.brand,borderWidth:2,borderColor:t.surface},pointDanger:{backgroundColor:t.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...a(n.size.tiny,n.lineHeight.normal,t.text.placeholder),textAlign:"center",...d},singleHint:{...a(n.size.caption,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},emptyBody:{alignItems:"center",justifyContent:"center",gap:r.sm,paddingVertical:r.xxl+r.xs},emptyText:{...a(n.size.bodyTight,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},carousel:{height:nf},footer:{alignItems:"center",gap:r.sm,paddingTop:r.md},dots:{flexDirection:"row",gap:r.xs+r.xs/2},dot:{width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs-1,backgroundColor:t.borderHairlineGreen},dotActive:{width:r.lg+r.xs/2,backgroundColor:t.brand},counter:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,letterSpacing:n.letterSpacing.eyebrow/3,color:t.text.muted},backdrop:{flex:1,backgroundColor:to},sheet:{backgroundColor:t.surfaceCream,borderTopLeftRadius:o.xl-r.xs,borderTopRightRadius:o.xl-r.xs,paddingHorizontal:r.lg+r.xs,paddingTop:r.sm,paddingBottom:r.xxl+r.xs,maxHeight:"80%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},sheetTitle:{flex:1,...a(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},closeButton:{width:r.xxl+r.md,height:r.xxl+r.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...a(n.size.verdict,n.lineHeight.tight,t.text.primary)},sheetBody:{gap:r.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},reviewed:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs,backgroundColor:t.badgeBgPositive},reviewedText:{...a(n.size.tiny,n.lineHeight.normal,t.success,"medium")},detailRow:{gap:r.xs/2},detailLabel:{...a(n.size.caption,n.lineHeight.normal,t.text.muted,"medium")},detailValue:a(n.size.body,n.lineHeight.normal,t.text.primary),unverified:a(n.size.caption,n.lineHeight.normal,t.text.muted)})}i(sf,"makeStyles");var W=Object.freeze({title:"Full medical record",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:i(e=>`${e} ${e===1?"document":"documents"} from your vet ${e===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,"inReview"),needsAttention:"Needs your attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:i(e=>`${e} ${e===1?"document":"documents"} on file`,"documentsOnFile"),inReviewChip:i(e=>`${e} in review`,"inReviewChip"),beingVerified:i(e=>`${e} being verified`,"beingVerified"),beingVerifiedA11y:i(e=>`${e} ${e===1?"fact is":"facts are"} being verified`,"beingVerifiedA11y"),pendingReview:"Pending review: ",dateRange:i((e,t)=>`${Q(e)} to ${Q(t)}`,"dateRange"),documents:"Documents",uploadedDocument:fe.uploadedDocument,documentRowA11y:i(e=>`View what ${e} contributed to this record`,"documentRowA11y"),identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",lastDone:i(e=>`Last done ${e}`,"lastDone"),overdue:"Overdue",due:i(e=>`Due ${e}`,"due"),askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:fe.labResults,visits:fe.visits,physicalExams:fe.physicalExams,visitNotes:fe.visitNotes,document:Object.freeze({title:"Health Record",download:"Download record PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:i(e=>`Generated ${Q(e)}`,"generated"),identity:"Identity",labs:"Blood & Lab Work",ref:i(e=>`Ref ${e}`,"ref"),noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),zc=Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function kn(e){return Object.prototype.hasOwnProperty.call(zc,e)?zc[e]:ir(e)}i(kn,"entityTypeLabel");var Nc=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function Mc(e){let t=Nc.filter(o=>e.includes(o)),r=e.filter(o=>!Nc.includes(o));return [...t,...r]}i(Mc,"orderEntityTypes");function xo(e){switch(e){case "identity_risk":return {label:"Identity mismatch",rank:0,tone:"critical"};case "benign":return {label:"Minor difference",rank:2,tone:"neutral"};default:return {label:"Needs review",rank:1,tone:"warning"}}}i(xo,"conflictSeverityMeta");function Tn(e,t){if(!e)return null;let r=Date.parse(e);if(Number.isNaN(r))return null;let o=r<t-1440*60*1e3;return {label:o?W.overdue:W.due(Q(e)),overdue:o}}i(Tn,"dueBadge");function Bc(e){return e===null?null:e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}`:e.refLow!==null?`\u2265 ${e.refLow}`:e.refHigh!==null?`\u2264 ${e.refHigh}`:null}i(Bc,"formatReferenceBand");var at=Object.freeze({editA11y:i(e=>`Edit ${e}. Correct or remove this record detail.`,"editA11y"),title:i(e=>`Edit ${e}`,"title"),helper:"Corrects your record. Your vet can still review it.",close:"Close",closeEditorA11y:"Close editor",save:"Save changes",saving:"Saving...",remove:"Remove this detail",removeA11y:i(e=>`Remove ${e}`,"removeA11y"),confirmRemove:"Remove this detail from your record? This can't be undone.",removeConfirm:"Remove",removing:"Removing...",keep:"Keep",noChange:"Change a value before saving.",saved:"Saved.",removed:"Removed.",detail:"record detail"});function Hc(e,t){return tr(e)?t==="remove"?"Records access for this pet is off, so this detail cannot be removed.":"Records access for this pet is off, so this detail cannot be changed.":Xl(e)?t==="remove"?"A clinician already reviewed this detail, so it can't be removed here.":"A clinician already reviewed this detail, so it can't be changed here.":t==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}i(Hc,"factEditErrorMessage");var lf=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function na(e,t){if(Object.keys(t.edits).length===0&&t.removed.length===0)return e;let r=[];for(let o of e){let n=o.canonicalKey??null;if(n!==null&&t.removed.includes(n))continue;let l=n!==null?t.edits[n]:void 0;r.push(l===void 0?o:Object.freeze({...o,value:l}));}return Object.freeze(r)}i(na,"applyFactOverlay");function oa(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(oa,"isFactEditable");function cf(){return `records-fact-${Date.now().toString(36)}`}i(cf,"defaultFactKey");function ia(e,t={}){let r=sr(),{userRef:o}=ke(),[n,l]=useState(lf),[s,c]=useState(false),[a,d]=useState(null),u=useMemo(()=>({}),[r,e,o]),[p,f]=useState(null),h=useCallback(()=>f(u),[u]),R=o!==null&&p!==u,v=useRef(false),y=useRef(t.newIdempotencyKey);y.current=t.newIdempotencyKey;let g=useCallback(()=>(y.current??cf)(),[]),b=useCallback((D,k,S)=>{if(c(false),!D.ok){if(k(),vr(D.error)){h();return}d(Hc(D.error,S));}},[h]),w=useCallback(async(D,k)=>{let S=D.canonicalKey??"",I=k.trim();if(v.current||S.length===0||I.length===0)return B(q("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let Y=n;l($=>({...$,edits:{...$.edits,[S]:I}}));let z=await r.editFact(e,{entityType:D.category,canonicalKey:S,correctedFields:$i(D.value,I),idempotencyKey:g()});return v.current=false,b(z,()=>l(Y),"edit"),z},[r,e,n,b,g]),x=useCallback(async D=>{let k=D.canonicalKey??"";if(v.current||k.length===0)return B(q("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let S=n;l(Y=>({...Y,removed:[...Y.removed,k]}));let I=await r.removeFact(e,{entityType:D.category,canonicalKey:k,idempotencyKey:g()});return v.current=false,b(I,()=>l(S),"remove"),I},[r,e,n,b,g]),E=useCallback(()=>d(null),[]);return useMemo(()=>({overlay:n,busy:s,error:a,available:R,edit:w,remove:x,clearError:E}),[n,s,a,R,w,x,E])}i(ia,"useRecordFactEdit");function Wc({entity:e,factEdit:t,children:r}){let o=Gc(),[n,l]=useState(false),s=e.label.trim()||at.detail;return jsxs(View,{style:o.row,children:[jsx(View,{style:o.main,children:r}),jsx(Pressable,{onPress:()=>l(true),accessibilityRole:"button",accessibilityLabel:at.editA11y(s),hitSlop:6,style:o.editButton,testID:`fact-edit-open-${e.canonicalKey??e.key}`,children:jsx(View,{style:o.pencil,accessibilityElementsHidden:true,importantForAccessibility:"no"})}),n?jsx(yf,{entity:e,title:s,factEdit:t,onClose:()=>l(false)}):null]})}i(Wc,"FactEditAffordance");function yf({entity:e,title:t,factEdit:r,onClose:o}){let n=Gc(),l=be(),s=L(),[c,a]=useState(e.value??""),[d,u]=useState(null),[p,f]=useState(false);useEffect(()=>{r.clearError();},[r]);let h=c.trim().length>0&&c.trim()!==(e.value??"").trim(),R=d??r.error,v=r.busy,y=i(()=>{if(!h){u(at.noChange);return}u(null),r.edit(e,c).then(b=>{b.ok&&o();});},"submitEdit"),g=i(()=>{u(null),r.remove(e).then(b=>{b.ok?o():f(false);});},"submitRemove");return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:o,children:jsxs(KeyboardAvoidingView,{behavior:"padding",style:n.backdrop,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:at.closeEditorA11y,onPress:o}),jsxs(View,{style:n.sheet,accessibilityViewIsModal:true,testID:"fact-edit-sheet",children:[jsx(View,{style:n.handle}),jsxs(View,{style:n.header,children:[jsxs(View,{style:n.headerText,children:[jsx(m,{style:n.title,accessibilityRole:"header",children:at.title(t)}),jsx(m,{style:[n.helper,R?n.helperError:null],accessibilityLiveRegion:"polite",children:R??at.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:at.close,onPress:o,hitSlop:12,style:n.closeButton,testID:"fact-edit-close",children:jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsx(m,{style:l.fieldLabel,children:e.label}),jsx(qe,{accessibilityLabel:e.label,style:l.field,value:c,onChangeText:b=>{a(b),u(null);},editable:!v,maxLength:512,placeholderTextColor:s.color.text.placeholder,testID:"fact-edit-field"}),p?jsxs(View,{style:n.confirmBlock,testID:"fact-edit-confirm-remove",children:[jsx(m,{style:n.confirmText,children:at.confirmRemove}),jsxs(View,{style:n.confirmRow,children:[jsx(re,{label:v?at.removing:at.removeConfirm,kind:"danger",busy:v,onPress:g,style:n.confirmButton,testID:"fact-edit-remove-confirm"}),jsx(re,{label:at.keep,kind:"outline",disabled:v,onPress:()=>f(false),style:n.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):jsxs(View,{style:n.actions,children:[jsx(re,{label:v?at.saving:at.save,busy:v,disabled:!h,onPress:y,testID:"fact-edit-save"}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:at.removeA11y(t),disabled:v,onPress:()=>{u(null),f(true);},style:[n.removeButton,v?n.removeDisabled:null],testID:"fact-edit-remove",children:jsx(m,{style:n.removeText,children:at.remove})})]})]})]})})}i(yf,"FactEditSheet");function Gc(){let e=L();return useMemo(()=>ff(e),[e])}i(Gc,"useStyles");function ff(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,s=e.brightness==="dark"?t.errorRed:t.danger,c=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*d),color:u}),"text");return StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:r.sm},main:{flex:1},editButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},pencil:{width:r.md+r.xs/2,height:r.xs/2,backgroundColor:t.brandInk,borderRadius:o.pill,transform:[{rotate:"-45deg"}]},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:to},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),helperError:{color:s},closeButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),actions:{gap:r.sm},removeButton:{minHeight:l,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...c(n.size.bodyTight,n.lineHeight.snug,t.danger,"bold")},confirmBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.badgeBgCritical},confirmText:c(n.size.bodyTight,n.lineHeight.normal,t.text.primary),confirmRow:{flexDirection:"row",gap:r.sm},confirmButton:{flex:1}})}i(ff,"makeStyles");function So({record:e,depth:t,petName:r,showLabs:o=true,onNavigate:n,onAsk:l,factEdit:s,nowMs:c}){let a=be(),d=gf(),u=c??Date.now(),p=useMemo(()=>s?na(e.entities,s.overlay):e.entities,[e.entities,s]),f=useMemo(()=>{let y=[],g=new Map;for(let b of p){let w=b.category.trim();if(w.length===0)continue;let x=g.get(w);x===void 0?(y.push(w),g.set(w,[b])):x.push(b);}return {order:Mc(y),groups:g}},[p]),h=Object.values(e.documents),R=i((y,g,b)=>l?jsx(Pressable,{onPress:()=>{let w=y();l(w.prompt,w.entityRef);},accessibilityRole:"button",accessibilityLabel:g,style:[a.pill,a.pillAsk,d.ask],testID:b,children:jsx(m,{style:a.pillAskLabel,children:g})}):null,"ask"),v=s!==void 0&&s.available;return jsxs(Fragment,{children:[jsxs(View,{style:d.sections,children:[t&&t.conflicts.length>0?jsxs(View,{style:a.section,testID:"record-section-conflicts",children:[jsx(Bt,{title:W.needsAttention,count:t.conflicts.length}),[...t.conflicts].sort((y,g)=>xo(y.severity).rank-xo(g.severity).rank).map(y=>{let g=xo(y.severity),b=ir(y.field??y.entityType);return jsxs(View,{style:[d.conflictCard,{borderColor:a.chipTones[g.tone].fg.color}],accessibilityRole:"summary",children:[jsxs(View,{style:d.conflictHead,children:[jsx(m,{style:d.conflictTitle,children:g.label}),jsx(Kt,{label:b,tone:g.tone})]}),jsx(m,{style:a.rowDetail,children:W.conflictSub}),y.candidates.map((w,x)=>jsxs(View,{style:d.candidate,children:[jsx(m,{style:a.rowTitle,children:w.value}),jsx(m,{style:a.rowMuted,children:[w.docId?e.documents[w.docId]?.title??W.uploadedDocument:W.uploadedDocument,w.collectedAt?Q(w.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},x)),R(()=>kc(r,{scopeLabel:b,severity:y.severity,candidates:y.candidates.map(w=>({value:w.value,clinicName:w.docId?e.documents[w.docId]?.title??null:null}))},y.conflictId),W.askConflict,`records-ask-conflict-${y.conflictId}`)]},y.conflictId)})]}):null,t?.completeness?jsxs(View,{style:a.section,testID:"record-section-completeness",children:[jsx(Bt,{title:W.whatsOnFile}),jsxs(View,{style:a.card,children:[jsx(View,{style:d.coverageRow,children:[[W.coverage.labs,t.completeness.hasLabHistory],[W.coverage.vaccines,t.completeness.hasVaccinationHistory],[W.coverage.weight,t.completeness.hasWeightHistory],[W.coverage.vitals,t.completeness.hasVitalsHistory],[W.coverage.exams,t.completeness.hasPhysicalExamHistory],[W.coverage.procedures,t.completeness.hasProcedureHistory],[W.coverage.genetics,t.completeness.hasGeneticHistory],[W.coverage.parasite,t.completeness.hasParasitePreventionHistory],[W.coverage.reproductive,t.completeness.hasReproductiveHistory]].map(([y,g])=>jsx(View,{style:[d.coveragePill,g?a.chipTones.positive.bg:a.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${y}: ${g?W.onFile:W.noneOnFile}`,children:jsx(m,{style:[d.coverageText,g?a.chipTones.positive.fg:{color:a.rowMuted.color}],children:y})},y))}),jsxs(View,{style:d.metaRow,children:[jsx(m,{style:d.metaText,children:W.documentsOnFile(t.completeness.documentsIngested)}),t.completeness.documentsInReview>0?jsx(Kt,{label:W.inReviewChip(t.completeness.documentsInReview),tone:"warning"}):null,aa(t.completeness.heldTotal,t.completeness.entitiesPendingReview)>0?jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:W.beingVerifiedA11y(aa(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),children:jsx(Kt,{label:W.beingVerified(aa(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),t.completeness.earliestRecordAt||t.completeness.latestRecordAt?jsx(View,{style:d.metaRow,children:jsx(m,{style:d.metaText,children:W.dateRange(t.completeness.earliestRecordAt,t.completeness.latestRecordAt)})}):null,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).length>0?jsxs(m,{style:d.pendingText,children:[W.pendingReview,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).map(([y,g])=>`${kn(y)} (${g})`).join(", ")]}):null]})]}):null,h.length>0?jsxs(View,{style:a.section,testID:"record-section-documents",children:[jsx(Bt,{title:W.documents,count:h.length}),jsx(View,{style:a.card,children:h.map((y,g)=>{let b=y.title?.trim()||W.uploadedDocument,w=y.receivedAt?Q(y.receivedAt):null,x=jsxs(Fragment,{children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:b}),w?jsx(m,{style:a.rowDetail,children:w}):null]}),n?jsx(Pr,{}):null]});return n?jsx(Pressable,{onPress:()=>n({name:"contributions",docId:y.docId}),accessibilityRole:"button",accessibilityLabel:W.documentRowA11y(b),style:[a.row,g>0?a.rowDivider:null],testID:`records-document-row-${y.docId}`,children:x},y.docId):jsx(View,{style:[a.row,g>0?a.rowDivider:null],children:x},y.docId)})})]}):null,e.identity.length>0?jsxs(View,{style:a.section,testID:"record-section-identity",children:[jsx(Bt,{title:W.identity}),jsx(View,{style:a.card,children:e.identity.map((y,g)=>jsxs(View,{style:[a.row,g>0?a.rowDivider:null],children:[jsx(m,{style:d.identityLabel,children:y.label}),jsx(m,{style:d.identityValue,children:y.value})]},`${g}:${y.label}`))})]}):null,e.forwardLooking.length>0?jsxs(View,{style:a.section,testID:"record-section-upcoming",children:[jsx(Bt,{title:W.upcomingCare,count:e.forwardLooking.length}),jsx(View,{style:a.card,children:e.forwardLooking.map((y,g)=>{let b=Tn(y.dueAt,u);return jsxs(View,{style:[a.row,g>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:y.title}),y.detail?jsx(m,{style:a.rowDetail,children:y.detail}):null]}),b?jsx(Kt,{label:b.label,tone:b.overdue?"critical":"info"}):null]},`${y.title}-${g}`)})}),R(()=>Cc(r,e.forwardLooking.map(y=>{let g=Tn(y.dueAt,u);return {label:y.title,relativeText:g?.label??"",tone:g?.overdue?"overdue":"upcoming"}}),e.petRef),W.askUpcomingCare,"records-ask-upcoming-care")]}):null,f.order.map(y=>{let g=f.groups.get(y)??[];if(g.length===0)return null;let b=kn(y);return jsxs(View,{style:a.section,testID:`record-section-${y}`,children:[jsx(Bt,{title:b,count:g.length}),jsx(View,{style:a.card,children:g.map((w,x)=>{let D=[Br(w.value,w.unit),w.observedAt?Q(w.observedAt):null].filter(S=>S&&S.length>0).join(" \xB7 "),k=jsxs(View,{style:[a.row,x>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:w.label}),D?jsx(m,{style:a.rowDetail,children:D}):null,R(()=>wc(r,{entityTypeLabel:b,title:w.label,detail:D||null},y,w.key),W.askEverfur,`records-ask-entity-${w.key}`)]}),w.status?jsx(Kt,{label:ir(w.status)}):null]});return v&&oa(w)&&s?jsx(Wc,{entity:w,factEdit:s,children:k},w.key):jsx(View,{children:k},w.key)})})]},y)}),t&&t.physicalExams.length>0?jsxs(View,{style:a.section,testID:"record-section-exams",children:[jsx(Bt,{title:W.physicalExams,count:t.physicalExams.length}),t.physicalExams.map(y=>jsxs(View,{style:a.card,children:[jsx(m,{style:[a.rowTitle,d.cardTitle],accessibilityRole:"header",children:y.observedOn?Q(y.observedOn):fe.exam}),y.systems.map((g,b)=>{let w=g.findingStatus==="abnormal",x=w?fe.abnormal:g.findingStatus==="not_examined"?fe.notExamined:fe.normal;return jsxs(View,{style:[a.row,b>0?a.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[Ir(g.system),x,w?g.finding:null].filter(Boolean).join(", "),children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:Ir(g.system)}),w&&g.finding?jsx(m,{style:a.rowDetail,children:g.finding}):null]}),jsx(Kt,{label:x,tone:w?"warning":g.findingStatus==="not_examined"?"neutral":"positive"})]},g.system)}),R(()=>Ec(r,{observedOn:y.observedOn?Q(y.observedOn):null,abnormal:y.systems.filter(g=>g.findingStatus==="abnormal").map(g=>({system:Ir(g.system),finding:g.finding??""}))},y.examId),W.askExam,`records-ask-exam-${y.examId}`)]},y.examId))]}):null,t&&t.clinicianNotes.length>0?jsxs(View,{style:a.section,testID:"record-section-notes",children:[jsx(Bt,{title:W.visitNotes,count:t.clinicianNotes.length}),t.clinicianNotes.map(y=>jsxs(View,{style:a.card,children:[jsx(m,{style:[a.rowTitle,d.cardTitle],accessibilityRole:"header",children:y.observedOn?Q(y.observedOn):fe.visitNote}),y.sections.map((g,b)=>jsxs(View,{style:[d.noteSection,b>0?a.rowDivider:null],children:[jsx(m,{style:d.noteLabel,children:Ur(g.section)}),jsx(m,{style:g.text?d.noteBody:d.noteBodyMuted,children:g.text||fe.notRecorded})]},`${g.section}:${b}`)),R(()=>Sc(r,{observedOn:y.observedOn?Q(y.observedOn):null,sections:y.sections.map(g=>({label:Ur(g.section),text:g.text}))},y.noteId),W.askVisit,`records-ask-note-${y.noteId}`)]},y.noteId))]}):null,o&&t&&t.labResults.length>0?jsxs(View,{style:a.section,testID:"record-section-labs",children:[jsx(Bt,{title:W.labResults,count:t.labResults.length}),jsx(View,{style:a.card,children:t.labResults.map((y,g)=>{let b=Qt(y.latest.status),w=Ei(y.latest.at,y.trajectory,y.points.length);return jsxs(View,{style:[a.row,g>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:y.name}),jsx(m,{style:a.rowValue,children:Et(y.latest.value,y.latest.unit,y.latest.qualitativeResult)}),w?jsx(m,{style:a.rowDetail,children:w}):null]}),jsx(Kt,{label:b.label,tone:fo(y.latest.status)})]},y.markerId)})})]}):null,t&&t.encounters.length>0?jsxs(View,{style:a.section,testID:"record-section-visits",children:[jsx(Bt,{title:W.visits,count:t.encounters.length}),jsx(View,{style:a.card,children:t.encounters.map((y,g)=>{let b=[y.date?Q(y.date):null,y.clinicName,y.veterinarian].filter(w=>w&&w!=="-").join(" \xB7 ");return jsx(View,{style:[a.row,g>0?a.rowDivider:null],children:jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:y.type?ir(y.type):fe.visit}),b?jsx(m,{style:a.rowDetail,children:b}):null]})},y.encounterId)})})]}):null]}),jsx(hr,{disclaimer:e.disclaimer})]})}i(So,"RecordSections");function aa(e,t){return e>0?e:Object.values(t).reduce((r,o)=>r+o,0)}i(aa,"heldCount");function gf(){let e=L();return useMemo(()=>bf(e),[e])}i(gf,"useLocalStyles");function bf(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth;return StyleSheet.create({sections:{gap:r.lg+r.xs},ask:{marginTop:r.lg},conflictCard:{borderRadius:o.md,borderWidth:1,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},conflictHead:{flexDirection:"row",alignItems:"center",gap:r.sm},conflictTitle:{flex:1,..._(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},candidate:{borderTopWidth:l,borderTopColor:t.borderHairlineGreen,paddingTop:r.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,paddingVertical:r.md},coveragePill:{borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs+1},coverageText:{..._(e,"medium"),fontSize:n.size.caption,lineHeight:n.size.caption+r.xs-1},metaRow:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingBottom:r.md},metaText:{flex:1,..._(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},pendingText:{..._(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.normal),color:t.text.muted,paddingBottom:r.md},identityLabel:{..._(e,"medium"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},identityValue:{flexShrink:1,textAlign:"right",..._(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},cardTitle:{paddingTop:r.sm},noteSection:{paddingVertical:r.md,gap:r.xs},noteLabel:{..._(e,"bold"),fontSize:n.size.bodyTight,color:t.text.secondary,textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},noteBody:{..._(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.primary},noteBodyMuted:{..._(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.muted,fontStyle:"italic"}})}i(bf,"makeLocalStyles");var _n=Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:i(e=>`Call the clinic at ${e}`,"callAt")});var hf=Math.round(ur/(1024*1024)),rt=Object.freeze({title:i(e=>`Upload ${He(e)}\u2019s records`,"title"),subtitle:i(e=>`Already have lab results, a vet summary, or test reports? Add them here and we\u2019ll read them and pull out ${He(e)}\u2019s health markers.`,"subtitle"),noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${hf} MB each. You can pick several at once. We\u2019ll read them and add the results to your records.`,chooseFiles:"Choose files",chooseFilesA11y:"Choose records to upload",uploading:i((e,t)=>`Uploading ${e+1} of ${t}\u2026`,"uploading"),cancel:"Cancel",cancelA11y:"Cancel these uploads",received:i(e=>`${e===1?"Record received.":`${e} records received.`} We\u2019ll read and review ${e===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,"received"),retryFailed:i(e=>`Retry ${e} that didn\u2019t upload`,"retryFailed"),retryFailedA11y:i(e=>`Retry ${e} failed upload${e>1?"s":""}`,"retryFailedA11y"),addMore:"Add more files",addMoreA11y:"Add more records",done:"Done",doneA11y:"Done, view records",errors:Object.freeze({start:"We couldn\u2019t start that upload. Check your connection and try again.",startPlain:"We couldn\u2019t start that upload. Please try again.",upload:"We couldn\u2019t upload that record. Check your connection and try again."})});var Xc=Math.round(ur/(1024*1024)),Fr=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,t)=>`Uploading ${e+1} of ${t} records`,"uploading"),uploaded:i((e,t)=>`${e} of ${t} records uploaded`,"uploaded")});function Jc(e){let t=Math.round(e.progress*100);switch(e.status){case "done":return Fr.done;case "failed":return Fr.failed;case "uploading":return e.progress>=1?Fr.verifying:`${t}%`;case "queued":return Fr.queued;default:return null}}i(Jc,"uploadItemStatusLabel");function Zc(e){if(e.length===0)return null;let t=i(l=>{let s=l.map(c=>c.name??"");return s.length<=3?s.join(", "):`${s.slice(0,3).join(", ")} and ${s.length-3} more`},"nameList"),r=e.filter(l=>l.reason==="too_large"),o=e.filter(l=>l.reason==="unsupported"),n=[];return o.length>0&&n.push(`${t(o)} ${o.length>1?"are not PDFs":"is not a PDF"}`),r.length>0&&n.push(`${t(r)} ${r.length>1?"are":"is"} over ${Xc} MB`),`Didn\u2019t upload: ${n.join("; ")}. We can only read PDFs up to ${Xc} MB right now.`}i(Zc,"skippedFilesMessage");function ed(e){let t=[];for(let r of e)r.status==="skipped"&&r.skipReason!==null&&t.push({name:r.name,reason:r.skipReason});return t}i(ed,"skippedOf");var Ot=Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",updateEmailA11y:"Update clinic email and resend request",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep request",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We\u2019ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function td({request:e,onRecovered:t,canUpload:r=false},o){let[n,l]=useState(""),[s,c]=useState(false),[a,d]=useState(null),[u,p]=useState(false),[f,h]=useState(null),R=useRef(false),v=useRef(false),y=useRef(0);useEffect(()=>(v.current=true,()=>{v.current=false,y.current+=1;}),[o]);let g=f!==null&&f.before===e.updatedAt?{...f.value,canRetrySend:e.canRetrySend===true&&f.value.canRetrySend===true,canUpdateClinicEmail:e.canUpdateClinicEmail===true&&f.value.canUpdateClinicEmail===true,canRevoke:e.canRevoke===true&&f.value.canRevoke===true,canConvertToUpload:e.canConvertToUpload===true&&f.value.canConvertToUpload===true}:e,b=n.trim(),w=b.length<=320&&!Array.from(b).some(I=>I.charCodeAt(0)<=32||I.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(b),x=g.canUpdateClinicEmail===true&&b.length>0,E=g.canRetrySend===true&&!s&&!x,D=g.canUpdateClinicEmail===true&&!s&&w,k=g.canConvertToUpload===true&&r,S=i(async I=>{let Y={retry:E,email:D,revoke:g.canRevoke===true&&u,convert:k};if(R.current||!v.current||!Y[I])return;R.current=true,c(true),d(null);let z=y.current,$=i(()=>v.current&&z===y.current,"live");try{let G=I==="retry"?await o.retryRequest(e.id):I==="email"?await o.updateClinicEmail(e.id,b):I==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!$())return;if(!G.ok){d(G.error);return}if(G.value.id!==e.id||G.value.petRef!==e.petRef){d(q("internalError"));return}h({before:e.updatedAt,value:G.value}),l(""),p(!1),t();}catch{$()&&d(q("internalError"));}finally{R.current=false,$()&&c(false);}},"run");return {request:g,email:n,busy:s,error:a,canRetry:E,canUpdateEmail:D,canConvert:k,hasEmailEdit:x,confirmingRevoke:u&&g.canRevoke===true,emailInvalid:b.length>0&&!w,setEmail(I){R.current||(l(I),d(null));},retry:i(()=>S("retry"),"retry"),updateEmail:i(()=>S("email"),"updateEmail"),revoke:i(()=>S("revoke"),"revoke"),convert:i(()=>S("convert"),"convert"),askRevoke(){!R.current&&g.canRevoke===true&&p(true);},keepRequest(){R.current||p(false);}}}i(td,"useRecordsRecovery");var vf=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],xf=["requested","awaiting_upload","records_received","processing","ready"],wf=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],In=Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),kt=Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn\u2019t read this one automatically",manualReview:"Checking these by hand so nothing\u2019s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),Cf=Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),Ef=Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function Sf(e){return e.wireStatus??Ef[e.status]??"sent"}i(Sf,"wireStatusOf");function kf(e,t){return e!=="awaiting_response"||t<=0?null:`${t} ${t===1?"reminder":"reminders"} sent`}i(kf,"reminderProgressLabel");function Tf(e){switch(e){case "submitted":case "sent":return 1;case "awaiting_response":return 2;case "records_received":return 3;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 4;case "published":return 5;default:return -1}}i(Tf,"reachedRailIndex");function _f(e){switch(e.dispatchStatus){case "sent":return kt.delivered;case "preparing":case "queued":case "sending":return kt.emailing;case "failed":return kt.bounced;default:return null}}i(_f,"deliveryDetail");function Pf(e,t){return kf(t,e.reminderCount??0)??kt.waiting}i(Pf,"awaitingDetail");function If(e,t,r){let o=t.source==="owner_provided"||!!t.convertedToUploadAt;switch(e){case "sent_to_clinic":return _f(t);case "awaiting_clinic":return Pf(t,r);case "awaiting_upload":return kt.upload;case "records_received":return o?kt.ownerAdded:kt.clinicSent;case "processing":return kt.preparing;case "ready":return kt.ready;default:return null}}i(If,"railDetail");function Df(e,t){return !!e.reviewStartedAt||t==="parsing_failed"||t==="review_email_failed"}i(Df,"tookReviewBranch");function Af(e,t,r){if(e.key!=="processing"||!Df(t,r))return [e];let o=r==="parsing_failed",n=r==="published",l=n?"done":o?"current":"done",s=n?"done":o?"upcoming":"current";return [{key:"parsing_failed",title:In.parsing_failed,detail:kt.parsingFailed,at:null,state:l},{key:"manual_review",title:In.manual_review,detail:kt.manualReview,at:t.reviewStartedAt??null,state:s}]}i(Af,"expandProcessingPhase");function Of(e){switch(e){case "awaiting_upload":return 3;case "records_received":return 4;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 5;case "published":return 6;default:return 3}}i(Of,"convertedReachedIndex");function rd(e){return {key:"awaiting_clinic",title:kt.switchedTitle,detail:kt.switched,at:e.convertedToUploadAt??null,state:"done"}}i(rd,"convertedClinicSwitchEvent");function Lf(e){switch(e){case "submitted":case "sent":return 0;case "awaiting_upload":return 1;case "records_received":return 2;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 3;case "published":return 4;default:return -1}}i(Lf,"ownerReachedIndex");function Vf(e,t,r){switch(e){case "requested":return t.createdAt||null;case "awaiting_clinic":return t.lastReminderAt??null;case "processing":return t.parsingStartedAt??t.reviewStartedAt??null;case "ready":return r==="published"&&t.updatedAt||null;default:return null}}i(Vf,"railTimestamp");function nd(e,t,r,o){return {key:e,title:In[e],detail:If(e,t,r),at:Vf(e,t,r),state:o}}i(nd,"railEvent");function lr(e,t){return {key:e,title:In[e],detail:Cf[e]??null,at:t.updatedAt||null,state:"failed"}}i(lr,"terminalEvent");function ca(e,t,r,o,n){return e.map((l,s)=>{let c=n?.(l)??null;if(c!==null)return c;let a=o==="published"||s<t?"done":s===t?"current":"upcoming";return nd(l,r,o,a)}).flatMap(l=>Af(l,r,o))}i(ca,"walkRail");function da(e){let t=Sf(e),r=i(n=>nd(n,e,t,"done"),"done");if(t==="revoked")return [r("requested"),lr("revoked",e)];if(e.convertedToUploadAt)return t==="failed"?[r("requested"),r("sent_to_clinic"),rd(e),r("awaiting_upload"),r("records_received"),lr("processing_failed",e)]:ca(wf,Of(t),e,t,n=>n==="awaiting_clinic"?rd(e):null);if(e.source==="owner_provided"){if(t==="failed"||t==="clinic_declined")return [r("requested"),r("awaiting_upload"),r("records_received"),lr("processing_failed",e)];let n=Lf(t);return ca(xf,n<0?1:n,e,t)}if(t==="clinic_declined")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),lr("clinic_declined",e)];if(t==="clinic_responded_no_records")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),lr("clinic_no_records",e)];if(t==="failed"){let n=e.failureCode??null;return n==="no_response"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),lr("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[r("requested"),lr("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),r("records_received"),lr("processing_failed",e)]:[r("requested"),lr("delivery_failed",e)]}let o=Tf(t);return ca(vf,o<0?1:o,e,t)}i(da,"buildRequestTimeline");var zf=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),ko=24,ua=10;function _o({request:e}){let t=Bf(),r=da(e);return jsx(View,{style:t.container,accessibilityRole:"summary",children:r.map((o,n)=>jsx(Nf,{event:o,isLast:n===r.length-1,styles:t},o.key))})}i(_o,"RequestTimeline");function Nf({event:e,isLast:t,styles:r}){let o=e.at?Q(e.at):null,n=[e.title,e.detail,o,zf[e.state]].filter(Boolean);return jsxs(View,{style:r.row,accessible:true,accessibilityRole:"text",accessibilityLabel:n.join(", "),testID:`records-timeline-${e.key}`,children:[jsxs(View,{style:r.railColumn,children:[jsx(Mf,{state:e.state,styles:r}),t?null:jsx(View,{style:[r.connector,e.state==="done"&&r.connectorDone],accessibilityElementsHidden:true,importantForAccessibility:"no"})]}),jsxs(View,{style:r.body,children:[jsxs(View,{style:r.titleRow,children:[jsx(m,{style:[r.title,e.state==="current"&&r.titleCurrent,e.state==="failed"&&r.titleFailed,e.state==="upcoming"&&r.titleUpcoming],children:e.title}),o?jsx(m,{style:r.date,children:o}):null]}),e.detail?jsx(m,{style:[r.detail,e.state==="upcoming"&&r.detailUpcoming],children:e.detail}):null]})]})}i(Nf,"TimelineRow");function Mf({state:e,styles:t}){return e==="done"?jsx(View,{style:[t.dot,t.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{tier:"badge",style:[t.glyph,t.glyphOnBrand],children:"\u2713"})}):e==="failed"?jsx(View,{style:[t.dot,t.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{tier:"badge",style:t.glyph,children:"!"})}):e==="current"?jsx(View,{style:[t.dot,t.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(View,{style:t.dotCurrentCore})}):jsx(View,{style:[t.dot,t.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(Mf,"TimelineDot");function Bf(){let e=L();return useMemo(()=>Hf(e),[e])}i(Bf,"useStyles");function Hf(e){let{color:t,type:r}=e,{size:o}=r;return StyleSheet.create({container:{gap:0},row:{flexDirection:"row",alignItems:"flex-start",gap:12},railColumn:{alignItems:"center",width:ko},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:8},dot:{width:ko,height:ko,borderRadius:ko/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:t.brand},dotFailed:{backgroundColor:t.danger},dotCurrent:{borderWidth:2,borderColor:t.brand,backgroundColor:t.surface},dotCurrentCore:{width:ua,height:ua,borderRadius:ua/2,backgroundColor:t.brand},dotUpcoming:{borderWidth:2,borderColor:t.borderHairlineGreen,backgroundColor:t.surface},glyph:{..._(e,"bold"),fontSize:o.caption,lineHeight:o.caption+2,color:t.surface},glyphOnBrand:{color:t.onPrimary},connector:{width:2,flex:1,minHeight:22,backgroundColor:t.borderHairlineGreen,marginVertical:2},connectorDone:{backgroundColor:t.brand},title:{flex:1,..._(e,"bold"),fontSize:o.body,lineHeight:o.body+4,color:t.text.primary},titleCurrent:{color:t.brandInk},titleFailed:{color:t.danger},titleUpcoming:{color:t.text.muted,..._(e,"regular")},date:{..._(e,"regular"),fontSize:o.caption,lineHeight:o.caption+4,color:t.text.muted},detail:{..._(e,"regular"),fontSize:o.bodyTight,lineHeight:o.bodyTight+4,color:t.text.muted},detailUpcoming:{color:t.text.muted,opacity:.7}})}i(Hf,"makeStyles");function Yr(e,t,r){let o=xr(e,r);switch(o.kind){case "consent_required":return jsx($f,{onGrant:t});case "consent_unavailable":return jsx(Wf,{});case "session_required":return jsx(Gf,{});case "withheld":return jsx(Yf,{});case "pet_not_found":case "error":return jsx(Kf,{error:o.error,onRetry:e.refresh});default:return pr(o)}}i(Yr,"renderErrorFamily");function Kr(e,t){return ()=>{let r=ea(t,e.consent);if(r.length===0)return;let o=`records-consent-${Date.now().toString(36)}`;e.grantConsent(r,o);}}i(Kr,"makeGrantHandler");function ad({records:e}){let t=An(),r=e.uploadQueue;if(r.length===0)return null;let o=r.filter(s=>s.status!=="skipped"),n=o.filter(s=>s.status==="done").length,l=Zc(ed(r));return jsxs(View,{style:t.timeline,testID:"records-upload-queue",children:[l!==null?jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:t.errorText,children:l}):null,o.length>0?jsx(View,{accessibilityLiveRegion:"polite",accessibilityLabel:e.isUploading?Fr.uploading(n,o.length):Fr.uploaded(n,o.length),children:o.map(s=>{let c=Math.round(s.progress*100);return jsxs(View,{style:t.row,testID:`records-upload-file-${s.status}`,children:[jsx(m,{style:t.rowLabel,children:s.name??""}),jsx(m,{style:t.rowValue,children:Jc(s)}),s.status==="uploading"?jsx(View,{style:t.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:c},children:jsx(View,{style:[t.progressFill,{width:`${c}%`}]})}):null,s.status==="failed"&&s.error?jsx(m,{style:t.timelineMeta,children:s.error.displayMessage}):null]},s.key)})}):null]})}i(ad,"UploadQueue");function $f({onGrant:e}){let t=An();return jsx(View,{style:t.centered,accessible:true,accessibilityRole:"alert",accessibilityLabel:ce.consentRequired,children:jsx(Pressable,{onPress:e,accessibilityRole:"button",accessibilityLabel:ce.allow,style:t.primaryButton,children:jsx(m,{style:t.primaryLabel,children:ce.allow})})})}i($f,"ConsentRequiredState");function ya({label:e,glyph:t}){let r=An();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(e);},[e]),jsxs(View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:e,children:[jsx(View,{style:t==="withheld"?r.withheldGlyph:r.emptyGlyph}),jsx(m,{style:r.errorText,children:e})]})}i(ya,"AlertState");function Wf(){return jsx(ya,{label:ce.consentRequired,glyph:"empty"})}i(Wf,"ConsentUnavailableState");function Gf(){return jsx(ya,{label:ce.sessionRequired,glyph:"empty"})}i(Gf,"SessionRequiredState");function Yf(){return jsx(ya,{label:ce.recordUnavailable,glyph:"withheld"})}i(Yf,"WithheldState");function Kf({error:e,onRetry:t}){let r=An();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(e.displayMessage);},[e.displayMessage]),jsxs(View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:[jsx(m,{style:r.errorText,children:e.displayMessage}),e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:ce.retry,style:r.primaryButton,children:jsx(m,{style:r.primaryLabel,children:ce.retry})}):null]})}i(Kf,"ErrorState");function sd({call:e,prompt:t}){let r=An(),o=t.trim().length>0?t:_n.fallbackPrompt;return jsxs(View,{style:r.callCard,accessibilityRole:"summary",children:[jsx(m,{style:r.timelineLabel,children:_n.heading}),jsx(m,{style:r.timelineMeta,children:o}),jsx(Pressable,{onPress:()=>{Linking?.openURL?.(e.dial);},accessibilityRole:"button",accessibilityLabel:_n.callAt(e.phone),style:r.linkButton,testID:"records-call-clinic",children:jsx(m,{style:r.linkLabel,children:_n.call})})]})}i(sd,"ClinicCallCard");function An(){let e=L();return useMemo(()=>Qf(e),[e])}i(An,"useStyles");function Qf(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c,letterSpacing:a}=n,d=Je(l.recordCard,StyleSheet.hairlineWidth),u=ot(l.recordCard),p=i((b,w)=>Math.round(b*w),"lh"),f=StyleSheet.hairlineWidth,h=r.xxl*3+r.xl,R=r.xxl+r.md,v=r.xxl+r.sm,y=e.brightness==="dark"?t.errorRed:t.danger,g={shadowColor:t.brand,shadowOffset:{width:0,height:r.xs},shadowRadius:r.sm,shadowOpacity:.08,elevation:r.xs};return StyleSheet.create({container:{flex:1,minHeight:h,backgroundColor:t.background},body:{flex:1},centered:{minHeight:h,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:v,height:v,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:f,borderColor:t.brandBorder},withheldGlyph:{width:v,height:v,borderRadius:o.sm,backgroundColor:t.badgeBgCaution,borderWidth:f,borderColor:t.cautionAccent},errorText:{..._(e,"regular"),fontSize:s.subtitle,lineHeight:p(s.subtitle,c.snug),color:y,textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...g,...Je(l.primaryButton)},primaryLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,letterSpacing:a.tight,...ot(l.primaryButton)},linkButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...g,...Je(l.primaryButton)},linkLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,letterSpacing:a.tight,...ot(l.primaryButton)},disabledButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.surfaceSubtle,borderWidth:f,borderColor:t.brandBorder},disabledLabel:{..._(e,"bold"),color:t.text.muted,fontSize:s.body,letterSpacing:a.tight},list:{flex:1},listContent:{padding:r.lg,gap:r.md},timeline:{paddingVertical:r.md,paddingHorizontal:r.lg,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,gap:r.xs,...g,...d},timelineTitle:{..._(e,"bold"),fontSize:s.heading,lineHeight:p(s.heading,c.snug),color:t.text.primary,letterSpacing:a.tight,...u},timelineLabel:{..._(e,"bold"),fontSize:s.subtitle,lineHeight:p(s.subtitle,c.snug),color:t.text.secondary,letterSpacing:a.tight,...u},callCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,...d},timelineMeta:{..._(e,"regular"),fontSize:s.bodyTight,lineHeight:p(s.bodyTight,c.normal),color:t.text.muted,...u},recordBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,...g,...d},row:{flexDirection:"row",justifyContent:"space-between",gap:r.md,paddingVertical:r.xs,borderBottomWidth:f,borderBottomColor:t.borderHairlineGreen},rowLabel:{..._(e,"regular"),fontSize:s.body,lineHeight:p(s.body,c.normal),color:t.text.muted,flexShrink:1,...u},rowValue:{..._(e,"medium"),fontSize:s.body,lineHeight:p(s.body,c.normal),color:t.text.primary,textAlign:"right",flexShrink:1,...u},disclaimer:{..._(e,"regular"),fontSize:s.caption,lineHeight:p(s.caption,c.normal),color:t.text.muted,marginTop:r.md},progressTrack:{height:r.xs,borderRadius:o.pill,backgroundColor:t.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:t.brand}})}i(Qf,"makeStyles");var Zf=i((e,t)=>e.getRecordDepth(t),"readDepth"),eg=i(e=>!e.available,"depthEmpty");function ha(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack","onAsk"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(tg,{...o,style:t})})}i(ha,"EverfurRecordsDashboard");function tg({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:s,style:c}){let a=be(),d=Ra(),u=yt(r?{petRef:e,controller:r}:{petRef:e}),p=Qi(e),f=Ut(e,Zf,eg),[h,R]=useState(null),v=useCallback((C,T)=>R({marker:C,point:T}),[]),y=useMemo(()=>qr(o,u.consent),[o,u.consent]),g=useMemo(()=>Kr(u,o),[u,o]),b=p.markers?.markers??[],w=b.length>0,x=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,E=Qn(u.requests,e),D=si({hasMarkers:w,requests:u.requests,petRef:e}),k=li({recordLoading:u.status==="loading",hasFullRecord:x,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:w,requestsLoading:u.status==="loading",dashboardState:D,drivingRequest:E}),S=p.markers?.disclaimer??u.record?.disclaimer??"",I=i(()=>{u.refresh(),p.refresh(),f.refresh();},"retryAll"),Y=f.value!==null&&!f.value.withheld&&f.value.available?f.value:null,z=He(t),$=s&&p.markers?.summary?()=>{let C=Rc(t,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);s(C.prompt,C.entityRef);}:void 0,G=s?C=>{let T=hc(t,{canonicalName:C.name,markerId:C.markerId,latestValueText:C.latest?Et(C.latest.value,C.unit,C.latest.qualitativeResult):null,statusText:C.latest?Qt(C.latest.status).label:null,trajectoryText:Hr(C.trajectory,C.points.length),meaningText:C.meaning});s(T.prompt,T.entityRef);}:void 0,Z=s&&h?()=>{let{marker:C,point:T}=h,A=vc(t,{canonicalName:C.name,valueText:Et(T.value,C.unit,T.qualitativeResult),collectedAt:Q(T.at),sourceClinic:T.sourceClinic,referenceText:T.refLow!==null||T.refHigh!==null?go(T,C.unit):null,flagged:T.status==="above"?"above":T.status==="below"?"below":null,reviewed:T.reviewed,entityId:T.docId??C.markerId});R(null),s(A.prompt,A.entityRef);}:void 0,oe=jsxs(Fragment,{children:[p.markers?.summary?jsx(View,{style:a.inset,children:jsx(Dc,{summary:p.markers.summary,onAsk:$,testID:"dashboard-marker-summary"})}):null,jsx(m,{style:a.lead,children:dt.lead(t)}),jsx(qc,{markers:b,onPointPress:v,onAsk:G})]}),Ee=i(C=>n?jsxs(View,{style:[a.inset,d.actions],children:[C?jsx(fa,{label:dt.viewFullRecord,onPress:()=>n({name:"record"}),testID:"dashboard-full-record-action"}):null,jsx(fa,{label:dt.viewTimeline,onPress:()=>n({name:"timeline"}),testID:"dashboard-timeline-action"})]}):null,"actions"),H;if(u.status==="error"){let C=xr(u,y);H=C.kind==="error"||C.kind==="pet_not_found"?jsx(Qe,{variant:wt(C.error),message:C.error.displayMessage,onAction:C.error.retryable?I:void 0,testID:"dashboard-error"}):Yr(u,g,y);}else switch(k){case "loading":H=jsx(io,{testID:"dashboard-loading"});break;case "record":H=jsxs(ScrollView,{contentContainerStyle:a.contentTight,testID:"dashboard-record",children:[w?oe:p.status==="error"?jsx(View,{style:[a.inset,d.actions],children:jsx(fa,{label:dt.retryMarkers,onPress:I,testID:"dashboard-markers-retry"})}):null,jsx(View,{style:a.inset,children:u.record?jsx(So,{record:u.record,depth:Y,petName:t,showLabs:!w,onNavigate:n,onAsk:s}):null}),Ee(true)]});break;case "error":H=jsx(Qe,{variant:wt(p.error??u.error),message:(p.error??u.error)?.displayMessage,onAction:(p.error??u.error)?.retryable?I:void 0,testID:"dashboard-error"});break;case "in_progress":H=jsxs(ScrollView,{contentContainerStyle:a.content,testID:"dashboard-in-progress",children:[E?jsx(rg,{request:E,petName:z,onOpen:n?()=>n({name:"request",requestId:E.id}):void 0,onAsk:s?()=>{let C=xc(t,{clinicName:E.clinicName??null,statusLabel:En(E),status:E.status,heldItemCount:E.heldItemCount},E.id);s(C.prompt,C.entityRef);}:void 0}):null,jsx(hr,{disclaimer:S})]});break;case "none":H=jsxs(ScrollView,{contentContainerStyle:a.content,testID:"dashboard-request-prompt",children:[jsxs(View,{style:d.promptCard,children:[jsxs(View,{style:d.promptHeader,children:[jsx(View,{style:d.promptGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:d.promptTitle,children:_r.title(t)})]}),jsx(m,{style:d.promptBody,children:_r.body}),n?jsxs(Fragment,{children:[jsx(re,{label:_r.requestFromClinic,accessibilityLabel:_r.requestFromClinicA11y(t),onPress:()=>n({name:"clinicPicker"}),style:d.promptCta,testID:"dashboard-request-prompt-clinic"}),jsx(re,{label:_r.uploadDocument,kind:"outline",accessibilityLabel:_r.uploadDocumentA11y(t),onPress:()=>n({name:"upload"}),style:d.promptCtaSecondary,testID:"dashboard-request-prompt-upload"})]}):null]}),jsx(hr,{disclaimer:S})]});break;case "labs_only":H=jsxs(ScrollView,{contentContainerStyle:a.contentTight,testID:"dashboard-labs-only",children:[oe,jsx(View,{style:a.inset,children:jsx(hr,{disclaimer:S})}),Ee(false)]});break;default:H=pr(k);}return jsxs(View,{style:[a.root,c],children:[jsx(et,{title:dt.title,onBack:l,testID:"dashboard-header",right:n?jsx(Pressable,{onPress:()=>n({name:"timeline"}),accessibilityRole:"button",accessibilityLabel:dt.openTimeline,hitSlop:12,style:d.headerButton,testID:"dashboard-timeline-link",children:jsx(fl,{})}):void 0}),jsx(View,{style:a.body,children:H}),jsx(Fc,{marker:h?.marker??null,point:h?.point??null,onClose:()=>R(null),onAsk:Z}),jsx(Me,{})]})}i(tg,"DashboardBody");function fa({label:e,onPress:t,testID:r}){let o=Ra();return jsxs(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:e,style:o.actionRow,testID:r,children:[jsxs(View,{style:o.actionLeft,children:[jsx(View,{style:o.actionIcon,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:o.actionLabel,children:e})]}),jsx(Pr,{})]})}i(fa,"ActionRow");function rg({request:e,petName:t,onOpen:r,onAsk:o}){let n=be(),l=Ra(),s=e.clinicName?.trim()||Mr.title(t),c=En(e),a=jsxs(View,{style:l.inProgressInner,children:[jsxs(View,{style:l.inProgressHead,children:[jsx(m,{style:l.inProgressTitle,children:s}),r?jsx(Pr,{}):null]}),jsx(_o,{request:e}),c.length>0?jsx(View,{style:n.statusCard,children:jsx(m,{style:n.statusText,children:c})}):null]});return jsxs(View,{style:l.inProgressCard,testID:"dashboard-in-progress-card",accessibilityRole:"summary",accessible:r?false:void 0,accessibilityLabel:r?void 0:Mr.a11y(t),children:[r?jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Mr.openA11y(t,c),testID:"dashboard-in-progress-open",children:a}):a,o?jsx(re,{label:Mr.ask,kind:"ask",accessibilityLabel:Mr.askA11y,onPress:o,testID:"dashboard-in-progress-ask"}):null]})}i(rg,"InProgressCard");function Ra(){let e=L();return useMemo(()=>ng(e),[e])}i(Ra,"useLocalStyles");function ng(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=r.xxl+r.md;return StyleSheet.create({headerButton:{width:s,height:s,alignItems:"center",justifyContent:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},actionIcon:{width:r.lg+r.xs/2,height:r.lg+r.xs/2,borderRadius:o.xs,backgroundColor:t.brandSoft,borderWidth:l,borderColor:t.brandBorder},actionLabel:{flex:1,..._(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},inProgressCard:{borderRadius:o.lg-r.xs/2,backgroundColor:t.surface,borderWidth:l,borderColor:t.brandBorder,padding:r.lg+r.xs/2,gap:r.lg},inProgressInner:{gap:r.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},inProgressTitle:{flex:1,..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),color:t.text.primary},promptCard:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:l,borderColor:t.borderRingCream,paddingHorizontal:r.lg+r.xs,paddingVertical:r.lg+r.xs/2},promptHeader:{flexDirection:"row",alignItems:"center",gap:r.xs+1},promptGlyph:{width:r.xl+1,height:r.xl+1,borderRadius:o.xs,borderWidth:2,borderColor:t.warningStrong},promptTitle:{flex:1,..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),letterSpacing:n.letterSpacing.headerBrand,color:t.brandInk},promptBody:{marginTop:r.sm-1,..._(e,"regular"),fontSize:n.size.bodyTight,lineHeight:r.lg+r.xs,color:t.text.primary},promptCta:{marginTop:r.sm-1,minHeight:r.xxl+r.sm},promptCtaSecondary:{marginTop:r.sm,minHeight:r.xxl+r.sm}})}i(ng,"makeLocalStyles");var Io=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function dd(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(dd,"toMillis");function ud(e){let t=[...e.visits.map((r,o)=>({key:`visit-${o}-${r.visitId}`,kind:"visit",kindLabel:fe.kind.visit,at:r.visitDate,date:Q(r.visitDate),title:r.summary??fe.clinicVisit,detail:r.veterinarian?fe.doctor(r.veterinarian):null,docId:r.docId})),...e.vaccines.map((r,o)=>{let n=[];return r.lot&&n.push(fe.lot(r.lot)),r.expiresOn&&n.push(fe.expires(Q(r.expiresOn))),{key:`vaccine-${o}-${r.vaccineId}`,kind:"vaccine",kindLabel:fe.kind.vaccine,at:r.administeredOn,date:Q(r.administeredOn),title:r.product||fe.kind.vaccine,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}}),...e.weights.map((r,o)=>({key:`weight-${o}-${r.weightId}`,kind:"weight",kindLabel:fe.kind.weight,at:r.observedOn,date:Q(r.observedOn),title:Cl(r.weightKg),detail:null,docId:r.docId})),...e.medications.map((r,o)=>{let n=[r.dose,r.route,r.frequency].filter(l=>!!l);return {key:`medication-${o}-${r.medicationId}`,kind:"medication",kindLabel:fe.kind.medication,at:r.startedOn,date:Q(r.startedOn),title:r.drugName||fe.kind.medication,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}})];return Object.freeze(t.sort((r,o)=>{let n=dd(r.at),l=dd(o.at);return n===null&&l===null?Io[r.kind]-Io[o.kind]:n===null?1:l===null?-1:l!==n?l-n:Io[r.kind]-Io[o.kind]}))}i(ud,"buildTimelineRows");var cg=300,dg=i((e,t)=>e.getTimeline(t),"readTimeline"),ug=i(e=>e.isEmpty,"timelineEmpty");var pg=i(e=>e.contributions.length===0,"contributionsEmpty");function yd({petRef:e,style:t,onBack:r}){let o=Ut(e,dg,ug);return jsx(gd,{state:o,style:t,onBack:r,header:jsx(et,{title:fe.timeline,onBack:an(r),testID:"timeline-header"}),loading:jsx(Pl,{testID:"timeline-loading"}),empty:jsx(Qe,{variant:"no_records",testID:"timeline-empty"}),render:n=>jsx(fg,{timeline:n})})}i(yd,"EverfurRecordsTimeline");function fd({petRef:e,docId:t,style:r,onBack:o}){let n=useCallback((c,a)=>c.getDocumentContributions(a,t),[t]),l=Ut(e,n,pg,t),s=l.value?.document?.title?.trim()||fe.uploadedDocument;return jsx(gd,{state:l,style:r,onBack:o,header:jsx(et,{title:s,onBack:an(o),testID:"contributions-header"}),empty:jsx(Qe,{variant:"no_records",testID:"contributions-empty"}),render:c=>jsx(gg,{view:c})})}i(fd,"EverfurDocumentContributions");function gd({state:e,style:t,header:r,loading:o,empty:n,render:l,onBack:s}){let c=va();return jsx(Ne,{capability:"records",style:t,...Be(an(s),Ze),children:jsxs(View,{style:[c.container,t],children:[r??null,jsx(View,{style:c.body,children:mg(e,l,c,o,n)}),jsx(Me,{})]})})}i(gd,"DepthSurface");function mg(e,t,r,o,n){switch(e.status){case "loading":return o??jsx(yg,{styles:r});case "empty":return n??jsx(View,{style:r.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:ce.empty,children:jsx(View,{style:r.emptyGlyph})});case "error":return e.error?jsx(Qe,{variant:wt(e.error),message:e.error.displayMessage,onAction:e.error.retryable?e.refresh:void 0,testID:"depth-error"}):null;case "populated":return e.value===null||e.value.withheld?null:t(e.value);default:return null}}i(mg,"renderState");function yg({styles:e}){let[t,r]=useState(false);return useEffect(()=>{let o=setTimeout(()=>r(true),cg);return ()=>clearTimeout(o)},[]),jsx(View,{style:e.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:ce.loading,children:t?jsx(ActivityIndicator,{}):null})}i(yg,"LoadingState");function fg({timeline:e}){let t=va(),r=ud(e);return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.timelineContent,accessibilityLabel:fe.timeline,children:[e.disclaimer.length>0?jsx(View,{style:t.timelineBand,accessible:true,accessibilityRole:"text",accessibilityLabel:dt.important(e.disclaimer),children:jsx(m,{style:t.timelineBandText,children:e.disclaimer})}):null,r.map((o,n)=>jsxs(View,{children:[n>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,accessible:true,accessibilityRole:"text",accessibilityLabel:[o.kindLabel,o.date,o.title,o.detail].filter(Boolean).join(", "),testID:`records-timeline-row-${o.kind}`,children:[jsx(View,{style:t.timelineBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxs(View,{style:t.timelineBody,children:[jsxs(View,{style:t.topLine,children:[jsx(m,{style:t.timelineKind,children:o.kindLabel}),jsx(m,{style:t.date,children:o.date})]}),jsx(m,{style:t.timelineTitle,children:o.title}),o.detail?jsx(m,{style:t.rowDetail,children:o.detail}):null]})]})]},o.key))]})}i(fg,"TimelineBody");function gg({view:e}){let t=va();return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.listContent,accessibilityLabel:ce.records,children:[e.document?.receivedAt?jsx(m,{style:t.rowDetail,children:Q(e.document.receivedAt)}):null,jsx(View,{style:t.card,children:e.contributions.map(r=>jsxs(View,{style:t.row,accessible:true,accessibilityRole:"text",children:[jsx(m,{style:t.rowTitle,children:r.label}),jsx(m,{style:t.rowValue,children:Br(r.value,r.unit)}),r.observedAt?jsx(m,{style:t.rowDetail,children:Q(r.observedAt)}):null]},r.key))})]})}i(gg,"ContributionsBody");function va(){let e=L();return useMemo(()=>bg(e),[e])}i(va,"useStyles");function bg(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c}=n,a=i((y,g)=>Math.round(y*g),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl*3+r.xl,p=r.xxl+r.md,f=e.brightness==="dark"?t.errorRed:t.danger,h=ot(l.recordCard),R=i((y,g,b,w="regular")=>({..._(e,w),fontSize:y,lineHeight:a(y,g),color:b}),"text"),v=i((y,g,b,w="regular")=>({...R(y,g,b,w),...h}),"inCard");return StyleSheet.create({container:{flex:1,minHeight:u,backgroundColor:t.background},body:{flex:1},centered:{minHeight:u,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:r.xxl+r.sm,height:r.xxl+r.sm,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},errorText:{...R(s.subtitle,c.snug,f),textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:p,minWidth:p,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...Je(l.primaryButton)},primaryLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,...ot(l.primaryButton)},list:{flex:1},listContent:{padding:r.lg,gap:r.md},section:{gap:r.sm},heading:{...R(s.heading,c.snug,t.text.primary,"bold")},card:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:d,borderColor:t.brandBorder,...Je(l.recordCard,d)},row:{gap:r.xs,paddingVertical:r.xs,borderBottomWidth:d,borderBottomColor:t.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:r.md},kindLabel:{...v(s.caption,c.normal,t.text.muted,"medium")},date:v(s.caption,c.normal,t.text.muted),rowTitle:{...v(s.body,c.normal,t.text.primary,"bold")},rowValue:{...v(s.body,c.normal,t.text.primary,"medium")},rowDetail:v(s.bodyTight,c.normal,t.text.muted),rowMuted:{...v(s.bodyTight,c.normal,t.text.muted),opacity:.7},chip:{...R(s.caption,c.normal,t.text.primary),alignSelf:"flex-start",paddingHorizontal:r.sm,paddingVertical:r.xs,borderRadius:o.pill},chipNeutral:{backgroundColor:t.badgeBgNeutral},chipCaution:{backgroundColor:t.badgeBgCaution},chipCritical:{backgroundColor:t.badgeBgCritical},disclaimer:{...R(s.caption,c.normal,t.text.muted),marginTop:r.md},timelineContent:{paddingBottom:r.xxl},timelineBand:{flexDirection:"row",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft,marginHorizontal:r.lg,marginTop:r.xs,marginBottom:r.md},timelineBandText:{flex:1,...R(s.caption,c.normal,t.text.secondary)},timelineSeparator:{height:d,backgroundColor:t.brandBorder,marginLeft:Ti},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBubble:{width:r.xxl+r.xs/2,height:r.xxl+r.xs/2,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},timelineBody:{flex:1,gap:r.xs-1},timelineKind:{..._(e,"mono"),fontSize:s.micro,lineHeight:s.bodyTight,letterSpacing:n.letterSpacing.eyebrow/3,textTransform:"uppercase",color:t.text.secondary},timelineTitle:{...R(s.body,c.normal,t.text.primary,"medium")}})}i(bg,"makeStyles");function xa(e,t={}){let r=sr(),{userRef:o}=ke(),n=t.now??Date.now,[l,s]=useState(null),[c,a]=useState(true),[d,u]=useState(null),[p,f]=useState(null),h=p===true,[R,v]=useState({}),[y,g]=useState(false),[b,w]=useState(null),[x,E]=useState(false),[D,k]=useState(false),S=Mn(e),I=useRef(0),Y=useRef(true),z=useCallback(async()=>{let T=I.current+=1;if(a(true),u(null),o===null){s(null),a(false);return}let A=await r.listShares(e);T!==I.current||!Y.current||(A.ok?(s(A.value),f(true)):vr(A.error)?(s(null),f(false)):(s(null),u(A.error),bd(A)&&f(true)),a(false));},[r,e,o]);useEffect(()=>(Y.current=true,z(),()=>{Y.current=false,I.current+=1;}),[z]);let $=useRef(S);useEffect(()=>{$.current!==S&&($.current=S,v({}),k(true),z());},[S,z]);let G=useCallback(async()=>{g(true);let T=await r.createShare(e);return Y.current&&(g(false),T.ok?(v(A=>({...A,[T.value.shareId]:T.value.shareUrl})),z()):vr(T.error)?f(false):tr(T.error)&&k(true)),T},[r,e,z]),Z=useCallback(async T=>{w(T);let A=await r.revokeShare(e,T);return Y.current&&(w(null),z()),A},[r,e,z]),oe=useCallback(async()=>{E(true);let T=await r.getPdfLink(e);return Y.current&&(E(false),!T.ok&&tr(T.error)&&k(true)),T},[r,e]),Ee=useCallback(()=>{k(false),z();},[z]),H=useMemo(()=>El(l??[],R,n()),[l,R,n]),C=c?"loading":d!==null?"error":H.length===0?"empty":"populated";return useMemo(()=>({status:C,rows:H,available:h,consentRequired:D,error:d,creating:y,revokingId:b,preparingPdf:x,createLink:G,revoke:Z,pdfLink:oe,refresh:Ee}),[C,H,h,D,d,y,b,x,G,Z,oe,Ee])}i(xa,"useRecordShares");function bd(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(bd,"answeredBehindGate");function hd(e){return e.available||e.status!=="empty"}i(hd,"sharesListShown");function wa(e){let t=sr(),{userRef:r}=ke(),o=useMemo(()=>({}),[t,e,r]),[n,l]=useState({scope:o,lit:null});useEffect(()=>{if(r===null)return;let c=true;return t.listShares(e).then(a=>{c&&(!a.ok&&vr(a.error)?l({scope:o,lit:false}):bd(a)&&l({scope:o,lit:true}));},()=>{}),()=>{c=false;}},[t,e,r,o]);let s=n.scope===o?n.lit:null;return useMemo(()=>({lit:s}),[s])}i(wa,"useRecordsDepthProbe");function Ca(e){let t=sr(),o=wa(e).lit===true,[n,l]=useState(false),[s,c]=useState(null),a=useRef(true);useEffect(()=>(a.current=true,()=>{a.current=false;}),[]);let d=useCallback(async()=>{l(true),c(null);let u=await t.getPdfLink(e);return a.current&&(l(false),u.ok||c(u.error)),u},[t,e]);return useMemo(()=>({preparing:n,available:o,error:s,pdfLink:d}),[n,o,s,d])}i(Ca,"useRecordPdfLink");var Tt=W.document,xd=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),xg=i((e,t)=>e.getRecordDepth(t),"readDepth"),wg=i(e=>!e.available,"depthEmpty");function Ea(e){let{style:t,renderPending:r,...o}=Fe(e,["onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(Eg,{...o,style:t})})}i(Ea,"EverfurRecordDocument");function Cg(e,t){return e.identity.length===0&&e.entities.length===0&&e.forwardLooking.length===0&&(t===null||t.labResults.length===0&&t.physicalExams.length===0&&t.clinicianNotes.length===0)}i(Cg,"documentIsEmpty");function Eg({petRef:e,petName:t,controller:r,consentVersion:o,onBack:n,onOpenUrl:l,style:s}){let c=be(),a=wd(),d=L(),u=yt(r?{petRef:e,controller:r}:{petRef:e}),p=Ut(e,xg,wg),f=Ca(e),h=useMemo(()=>qr(o,u.consent),[o,u.consent]),R=useMemo(()=>Kr(u,o),[u,o]),v=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,y=u.record,g=i(()=>{f.pdfLink().then(x=>{if(!x.ok)return;kr(l??(D=>Linking.openURL(D)),x.value.downloadUrl,"record_pdf");});},"download"),b,w=false;if(u.status==="loading"||p.status==="loading"&&y!==null)b=jsx(View,{style:a.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:dt.loading,testID:"record-document-loading",children:jsx(ActivityIndicator,{color:d.color.brandInk})});else if(u.status==="error"){let x=xr(u,h);b=x.kind==="error"||x.kind==="pet_not_found"?jsx(Qe,{variant:wt(x.error),message:x.error.displayMessage,onAction:x.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):Yr(u,R,h);}else y===null||Cg(y,v)?b=jsx(View,{style:a.centered,testID:"record-document-empty",children:jsx(m,{style:a.emptyText,children:Tt.empty})}):(w=true,b=jsx(Sg,{record:y,depth:v,petName:t,wordmark:d.meta.displayName}));return jsxs(View,{style:[c.root,a.root,s],children:[jsx(et,{title:Tt.title,variant:"document",onBack:n,testID:"record-document-header",right:f.available&&w?jsx(Pressable,{onPress:g,disabled:f.preparing,accessibilityRole:"button",accessibilityLabel:Tt.download,accessibilityState:{disabled:f.preparing,busy:f.preparing},hitSlop:8,style:a.download,testID:"record-document-download",children:f.preparing?jsx(ActivityIndicator,{size:"small",color:d.color.brandInk}):jsx(hl,{})}):void 0}),f.error?jsx(m,{style:[c.errorText,a.inset],accessibilityRole:"alert",children:f.error.displayMessage}):null,jsx(View,{style:c.body,children:b}),jsx(Me,{})]})}i(Eg,"DocumentBody");function Sg({record:e,depth:t,petName:r,wordmark:o}){let n=wd(),l=useMemo(()=>{let a=[],d=new Map;for(let f of e.entities){let h=f.category.trim();if(h.length===0)continue;let R=d.get(h);R===void 0?(a.push(h),d.set(h,[f])):R.push(f);}let u=xd.filter(f=>a.includes(f)),p=a.filter(f=>!xd.includes(f));return [...u,...p].map(f=>({type:f,rows:d.get(f)??[]}))},[e.entities]),s=Date.now(),c=i((a,d,u)=>jsxs(View,{style:n.section,testID:u,children:[jsxs(View,{style:n.sectionHeader,children:[jsx(m,{style:n.sectionTitle,accessibilityRole:"header",children:a}),jsx(View,{style:n.rule})]}),jsx(View,{children:d})]},u),"section");return jsxs(ScrollView,{contentContainerStyle:n.page,showsVerticalScrollIndicator:false,testID:"record-document",children:[jsxs(View,{style:n.letterhead,children:[jsx(m,{style:n.wordmark,children:o}),jsx(m,{style:n.docTitle,children:Tt.docTitle}),jsx(m,{style:n.petName,children:r?.trim()||Tt.namelessPet}),jsx(m,{style:n.generated,children:Tt.generated(e.generatedAt)})]}),e.identity.length>0?c(Tt.identity,e.identity.map((a,d)=>jsxs(View,{style:[n.row,d>0?n.rowDivider:null],children:[jsx(m,{style:n.rowLabel,children:a.label}),jsx(m,{style:n.rowValue,children:a.value})]},`${d}:${a.label}`)),"record-document-identity"):null,t&&t.labResults.length>0?c(Tt.labs,t.labResults.map((a,d)=>{let u=Qt(a.latest.status),p=Bc(a.points[a.points.length-1]??null),f=Et(a.latest.value,a.latest.unit??a.unit,a.latest.qualitativeResult);return jsxs(View,{style:[n.row,u.outOfRange?n.rowFlag:null,d>0?n.rowDivider:null],children:[jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:a.name}),jsxs(m,{style:n.rowMeta,children:[p?Tt.ref(p):Tt.noRange,a.latest.at?` \xB7 ${Q(a.latest.at)}`:""]})]}),jsxs(View,{style:n.rowRight,children:[f!=="-"?jsx(m,{style:[n.rowValue,u.outOfRange?n.rowValueAlert:null],children:f}):null,jsx(m,{style:[n.markerStatus,u.outOfRange?n.rowValueAlert:null],children:u.label})]})]},a.markerId)}),"record-document-labs"):null,l.map(({type:a,rows:d})=>c(kn(a),d.map((u,p)=>{let f=[Br(u.value,u.unit),u.observedAt?Q(u.observedAt):null].filter(h=>h&&h.length>0).join(" \xB7 ");return jsx(View,{style:[n.row,p>0?n.rowDivider:null],children:jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:u.label}),f?jsx(m,{style:n.rowMeta,children:f}):null]})},u.key)}),`record-document-${a}`)),e.forwardLooking.length>0?c(Tt.upcomingCare,e.forwardLooking.map((a,d)=>{let u=Tn(a.dueAt,s);return jsxs(View,{style:[n.row,d>0?n.rowDivider:null],children:[jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:a.title}),a.detail?jsx(m,{style:n.rowMeta,children:a.detail}):null]}),u?jsx(m,{style:[n.rowValue,u.overdue?n.rowValueAlert:null],children:u.label}):null]},`${a.title}-${d}`)}),"record-document-upcoming"):null,t&&t.physicalExams.length>0?c(Tt.physicalExams,t.physicalExams.map((a,d)=>jsxs(View,{style:[n.block,d>0?n.rowDivider:null],children:[a.observedOn?jsx(m,{style:n.blockDate,children:Q(a.observedOn)}):null,a.systems.filter(u=>u.finding).map(u=>jsxs(View,{style:n.fieldRow,children:[jsx(m,{style:n.fieldLabel,children:Ir(u.system)}),jsx(m,{style:n.fieldValue,children:u.finding})]},u.system))]},a.examId)),"record-document-exams"):null,t&&t.clinicianNotes.length>0?c(Tt.clinicianNotes,t.clinicianNotes.map((a,d)=>jsxs(View,{style:[n.block,d>0?n.rowDivider:null],children:[a.observedOn?jsx(m,{style:n.blockDate,children:Q(a.observedOn)}):null,a.sections.filter(u=>u.text).map((u,p)=>jsxs(View,{style:n.noteSection,children:[jsx(m,{style:n.noteLabel,children:Ur(u.section)}),jsx(m,{style:n.noteBody,children:u.text})]},`${u.section}-${p}`))]},a.noteId)),"record-document-notes"):null,e.disclaimer.length>0?jsx(View,{style:n.disclaimer,children:jsx(m,{style:n.disclaimerText,children:e.disclaimer})}):null]})}i(Sg,"RecordDocument");function wd(){let e=L();return useMemo(()=>kg(e),[e])}i(wd,"useLocalStyles");function kg(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*d),color:u}),"text"),c=i((a,d)=>({..._(e,"mono"),fontSize:a,lineHeight:a+r.xs-1,color:d,letterSpacing:n.letterSpacing.eyebrow/2,textTransform:"uppercase"}),"mono");return StyleSheet.create({root:{backgroundColor:t.surface},inset:{paddingHorizontal:r.lg},download:{width:r.xxl+r.xs+r.xs/2,height:r.xxl+r.xs+r.xs/2,borderRadius:o.pill,alignItems:"center",justifyContent:"center"},centered:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xxl,minHeight:r.xxl*3+r.xl},emptyText:{...s(n.size.body,n.lineHeight.normal,t.text.muted,"medium"),textAlign:"center"},page:{paddingHorizontal:r.lg+r.xs,paddingBottom:r.xxl+r.lg},letterhead:{alignItems:"center",paddingTop:r.md,paddingBottom:r.lg+r.xs+r.xs/2,borderBottomWidth:2,borderBottomColor:t.brand,gap:r.xs+r.xs/2,marginBottom:r.sm},wordmark:{...s(n.size.heading,n.lineHeight.snug,t.brandInk,"bold"),letterSpacing:n.letterSpacing.headerBrand},docTitle:{...c(n.size.caption,t.brandInk),marginTop:r.sm+r.xs/2,letterSpacing:n.letterSpacing.eyebrow+.4},petName:s(n.size.verdict+r.xs/2,n.lineHeight.tight,t.text.primary),generated:{...c(n.size.tiny,t.text.muted),textTransform:"none"},section:{marginTop:r.lg+r.xs+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2,marginBottom:r.sm},sectionTitle:c(n.size.tiny,t.brandInk),rule:{flex:1,height:l,backgroundColor:t.borderHairlineGreen},row:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.md+r.xs/2,paddingVertical:r.sm+1},rowDivider:{borderTopWidth:l,borderTopColor:t.borderHairlineGreen},rowFlag:{backgroundColor:t.badgeBgCritical,marginHorizontal:-r.sm,paddingHorizontal:r.sm,borderRadius:o.xs},rowMain:{flexShrink:1},rowRight:{alignItems:"flex-end",gap:r.xs/2},rowLabel:{flexShrink:1,...s(n.size.body,n.lineHeight.normal,t.text.primary,"medium")},rowValue:{...s(n.size.body,n.lineHeight.normal,t.text.primary,"bold"),textAlign:"right"},rowValueAlert:{color:t.danger},rowMeta:{marginTop:r.xs/2,..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},markerStatus:c(n.size.micro,t.text.muted),block:{paddingVertical:r.sm+r.xs/2},blockDate:{...c(n.size.tiny,t.text.muted),marginBottom:r.xs+r.xs/2},fieldRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md+r.xs/2,paddingVertical:r.xs-1},fieldLabel:{width:120,...s(n.size.bodyTight,n.lineHeight.normal,t.text.muted,"medium")},fieldValue:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")},noteSection:{marginTop:r.sm},noteLabel:{...c(n.size.tiny,t.brandInk),marginBottom:r.xs/2},noteBody:s(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),disclaimer:{marginTop:o.xl,paddingTop:r.md+r.xs/2,borderTopWidth:l,borderTopColor:t.borderHairlineGreen},disclaimerText:s(n.size.tiny,n.lineHeight.relaxed,t.text.muted)})}i(kg,"makeLocalStyles");function Sd({petRef:e,onClose:t,onNavigate:r,onOpenUrl:o,onCopy:n}){let l=Dg(),s=be(),c=xa(e),[a,d]=useState(null),[u,p]=useState(null),f=c.available&&!c.consentRequired,h=i((b,w)=>{kr(o??(E=>Linking.openURL(E)),b,w).then(E=>{E.ok||d(de.toasts.shareSheet);});},"open"),R=i(()=>{d(null),c.createLink().then(b=>{b.ok?h(b.value.shareUrl,"share_link"):d(ro(b.error,"create"));});},"onCreateLink"),v=i(()=>{d(null),c.pdfLink().then(b=>{b.ok?h(b.value.downloadUrl,"record_pdf"):d(ro(b.error,"download"));});},"onDownload"),y=i(b=>{!n||b.shareUrl===null||kr(n,b.shareUrl).then(w=>d(w.ok?de.toasts.copied:de.toasts.copyFailed));},"onCopyRow"),g=i(b=>{c.revoke(b).then(w=>{p(null),d(w.ok?de.toasts.turnedOff:ro(w.error,"revoke"));});},"onConfirmRevoke");return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:t,children:jsxs(View,{style:l.backdrop,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:de.closeSheetA11y,onPress:t}),jsxs(View,{style:l.sheet,accessibilityViewIsModal:true,testID:"share-record-sheet",children:[jsx(View,{style:l.handle}),jsxs(View,{style:l.header,children:[jsxs(View,{style:l.headerText,children:[jsx(m,{style:l.title,accessibilityRole:"header",children:de.title}),jsx(m,{style:l.helper,children:de.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:de.close,onPress:t,hitSlop:12,style:l.closeButton,testID:"share-record-close",children:jsx(m,{style:l.closeGlyph,children:"\xD7"})})]}),jsxs(ScrollView,{style:l.scroll,contentContainerStyle:l.body,showsVerticalScrollIndicator:false,children:[jsxs(View,{style:l.actions,children:[r?jsx(re,{label:de.viewDocument,onPress:()=>{t(),r({name:"document"});},testID:"share-view-document"}):null,f?jsx(re,{label:c.creating?de.creatingLink:de.createLink,kind:"outline",busy:c.creating,onPress:R,testID:"share-create-link"}):null,f?jsx(re,{label:c.preparingPdf?de.preparingPdf:de.downloadPdf,kind:"outline",busy:c.preparingPdf,onPress:v,testID:"share-download-pdf"}):null]}),c.consentRequired?jsxs(View,{style:l.stateCard,testID:"share-consent-off",children:[jsx(m,{style:l.stateTitle,accessibilityRole:"header",children:de.consentOffTitle}),jsx(m,{style:l.stateBody,children:de.consentOffBody}),jsx(re,{label:de.retry,kind:"outline",onPress:c.refresh,testID:"share-consent-retry"})]}):null,a?jsx(m,{style:l.notice,accessibilityRole:"alert",accessibilityLiveRegion:"polite",testID:"share-notice",children:a}):null,hd(c)?jsxs(View,{style:l.section,children:[jsx(m,{style:l.sectionLabel,accessibilityRole:"header",children:de.activeLinks}),c.status==="loading"?jsx(Dl,{testID:"share-record-loading"}):c.status==="error"?jsxs(View,{style:l.stateCard,testID:"share-record-error",children:[jsx(m,{style:l.stateTitle,children:de.errorTitle}),jsx(m,{style:l.stateBody,children:de.errorBody}),jsx(re,{label:de.retry,kind:"outline",onPress:c.refresh,testID:"share-record-retry"})]}):c.rows.length===0?jsxs(View,{style:l.stateCard,testID:"share-record-empty",children:[jsx(m,{style:l.stateTitle,children:de.emptyTitle}),jsx(m,{style:l.stateBody,children:de.emptyBody})]}):jsx(View,{style:l.list,children:c.rows.map(b=>jsxs(View,{style:l.row,testID:`share-row-${b.shareId}`,children:[jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:b.a11yLabel,children:[jsxs(View,{style:l.statusLine,children:[jsx(View,{style:[l.statusDot,{backgroundColor:b.active?l.active.color:l.inactive.color}],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:l.status,children:b.statusLabel}),jsx(m,{style:l.expiry,children:b.expiryLabel})]}),b.createdLabel?jsx(m,{style:l.created,children:b.createdLabel}):null]}),b.shareUrl!==null&&!n?jsx(m,{selectable:true,style:l.url,testID:`share-url-${b.shareId}`,children:b.shareUrl}):null,u===b.shareId?jsxs(View,{style:l.confirm,testID:`share-revoke-confirm-${b.shareId}`,children:[jsx(m,{style:l.confirmText,children:de.confirmTurnOff}),jsxs(View,{style:l.rowActions,children:[jsx(re,{label:c.revokingId===b.shareId?de.turningOff:de.turnOff,kind:"danger",busy:c.revokingId===b.shareId,onPress:()=>g(b.shareId),testID:`share-revoke-do-${b.shareId}`}),jsx(re,{label:de.keep,kind:"outline",disabled:c.revokingId===b.shareId,onPress:()=>p(null),testID:`share-revoke-cancel-${b.shareId}`})]})]}):jsxs(View,{style:l.rowActions,children:[n?jsx(re,{label:de.copyLink,kind:"outline",disabled:b.shareUrl===null,accessibilityLabel:de.copyLinkA11y(b.actionContext),onPress:()=>y(b),testID:`share-copy-${b.shareId}`}):null,jsx(re,{label:de.turnOff,kind:"danger",accessibilityLabel:de.turnOffA11y(b.actionContext),onPress:()=>p(b.shareId),testID:`share-ask-revoke-${b.shareId}`})]})]},b.shareId))})]}):null]}),jsx(View,{style:s.inset})]})]})})}i(Sd,"ShareSheet");function Dg(){let e=L();return useMemo(()=>Ag(e),[e])}i(Dg,"useStyles");function Ag(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,s=StyleSheet.hairlineWidth,c=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*d),color:u}),"text");return StyleSheet.create({active:{color:t.success},inactive:{color:t.text.muted},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:"rgba(0,0,0,0.4)"},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),closeButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),scroll:{flexGrow:0},body:{gap:r.lg,paddingBottom:r.sm},actions:{gap:r.sm},notice:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.secondary),padding:r.md,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft},section:{gap:r.sm},sectionLabel:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},stateCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.brandBorder},stateTitle:{...c(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},stateBody:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),list:{gap:r.md},row:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.brandBorder},statusLine:{flexDirection:"row",alignItems:"center",gap:r.sm},statusDot:{width:r.sm,height:r.sm,borderRadius:r.xs},status:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.primary,"bold")},expiry:{...c(n.size.caption,n.lineHeight.normal,t.text.muted)},created:c(n.size.tiny,n.lineHeight.normal,t.text.muted),url:{...c(n.size.caption,n.lineHeight.normal,t.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},confirm:{gap:r.sm},confirmText:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")}})}i(Ag,"makeStyles");var Vg=i((e,t)=>e.getRecordDepth(t),"readDepth"),qg=i(e=>!e.available,"depthEmpty");function _a(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack","onAsk"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(Fg,{...o,style:t})})}i(_a,"EverfurRecordDetail");function Fg({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:s,onOpenUrl:c,onCopy:a,style:d}){let u=be(),p=zg(),f=yt(r?{petRef:e,controller:r}:{petRef:e}),h=Ut(e,Vg,qg),R=ia(e),v=wa(e),[y,g]=useState(false),b=useMemo(()=>qr(o,f.consent),[o,f.consent]),w=useMemo(()=>Kr(f,o),[f,o]),x=h.value!==null&&!h.value.withheld&&h.value.available?h.value:null,E=f.record,D=i(()=>{f.refresh(),h.refresh();},"retry"),k=n!==void 0||v.lit===true,S;if(f.status==="loading"||h.status==="loading"&&E!==null&&!E.isEmpty)S=jsx(io,{testID:"everfur-record-loading"});else if(f.status==="error"){let I=xr(f,b);S=I.kind==="error"||I.kind==="pet_not_found"?jsx(Qe,{variant:wt(I.error),message:I.error.displayMessage,onAction:I.error.retryable?D:void 0,testID:"everfur-record-error"}):Yr(f,w,b);}else if(E===null||E.isEmpty){let I=x?.completeness?.documentsInReview??0;S=jsxs(ScrollView,{contentContainerStyle:u.content,testID:"everfur-record-empty",children:[jsx(Qe,{variant:"no_records",message:I>0?W.inReview(I):void 0}),jsx(hr,{disclaimer:E?.disclaimer??""})]});}else S=jsx(ScrollView,{contentContainerStyle:p.content,testID:"everfur-record",children:jsx(So,{record:E,depth:x,petName:t,onNavigate:n,onAsk:s,factEdit:R})});return jsxs(View,{style:[u.root,d],children:[jsx(et,{title:W.title,onBack:l,testID:"everfur-record-header",right:k||n?jsxs(Fragment,{children:[n?jsx(Pressable,{onPress:()=>n({name:"clinicBatch"}),accessibilityRole:"button",accessibilityLabel:W.requestClinicsA11y,hitSlop:8,style:p.share,testID:"everfur-record-request-clinics",children:jsx(bl,{})}):null,k?jsx(Pressable,{onPress:()=>g(true),accessibilityRole:"button",accessibilityLabel:W.shareA11y,hitSlop:8,style:p.share,testID:"everfur-record-share",children:jsx(gl,{})}):null]}):void 0}),jsx(View,{style:u.body,children:S}),y?jsx(Sd,{petRef:e,onClose:()=>g(false),onNavigate:n,...c?{onOpenUrl:c}:{},...a?{onCopy:a}:{}}):null,jsx(Me,{})]})}i(Fg,"RecordBody");function zg(){let e=L();return useMemo(()=>Ng(e),[e])}i(zg,"useLocalStyles");function Ng(e){let{space:t,radius:r}=e;return StyleSheet.create({content:{paddingHorizontal:t.lg,paddingBottom:t.xxl+t.sm,gap:t.lg+t.xs},share:{width:t.xxl+t.sm,height:t.xxl+t.sm,borderRadius:r.pill,alignItems:"center",justifyContent:"center"}})}i(Ng,"makeLocalStyles");function Ia(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(Ug,{...o,style:t})})}i(Ia,"EverfurRecordsUpload");function Ug({petRef:e,petName:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:s,style:c}){let a=be(),d=Ad(),{runtime:u}=ke(),p=yt(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),f=Cn(o)&&(r!==void 0||n!==void 0||Fn(u.registry.services.uploadTransport));return jsxs(View,{style:[a.root,c],children:[jsx(et,{title:"",onBack:s,testID:"upload-header"}),jsxs(ScrollView,{contentContainerStyle:d.content,testID:"upload-screen",children:[jsxs(View,{style:d.header,children:[jsx(View,{style:d.iconBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:d.title,accessibilityRole:"header",children:rt.title(t)}),jsx(m,{style:d.subtitle,children:rt.subtitle(t)})]}),jsx(Da,{records:p,requestId:null,onPickDocument:o,canUpload:f,onDone:l?h=>l({name:"request",requestId:h}):void 0})]}),jsx(Me,{})]})}i(Ug,"UploadBody");function Da({records:e,requestId:t,onPickDocument:r,canUpload:o,onDone:n}){let l=be(),s=Ad(),[c,a]=useState(null),[d,u]=useState(0),p=useRef(t),f=useRef([]),h=e.uploadQueue.filter(x=>x.status!=="skipped"),R=h.filter(x=>x.status==="done").length,v=h.filter(x=>x.status==="failed").length,y=!e.isUploading&&d>0,g=useCallback(async x=>{if(x.length===0)return;a(null);let E=p.current;if(E===null){let k=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!k.ok){a(rt.errors.start);return}E=k.value.id,p.current=E;}u(k=>k+1);let D=await e.uploadDocuments(E,x);f.current=D.flatMap((k,S)=>k.status==="failed"&&x[S]!==void 0?[x[S]]:[]);},[e]),b=useCallback(()=>{!r||!o||kr(r).then(x=>{if(!x.ok){a(rt.errors.startPlain);return}let E=x.value;E!==null&&g(Array.isArray(E)?E:[E]);});},[r,o,g]),w=useCallback(()=>{g(f.current);},[g]);return jsxs(View,{style:s.card,testID:"records-upload-card",children:[jsx(m,{style:s.cardTitle,accessibilityRole:"header",children:rt.cardTitle}),jsx(m,{style:s.cardSubtitle,children:rt.cardSubtitle}),c?jsx(View,{style:l.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:l.errorText,children:c})}):null,jsx(ad,{records:e}),e.isUploading?jsx(View,{style:s.uploadingRow,children:jsx(m,{style:s.progressText,children:rt.uploading(R,h.length)})}):y?jsxs(View,{style:s.settled,children:[R>0?jsx(m,{style:s.success,accessibilityRole:"alert",children:rt.received(R)}):null,v>0?jsx(re,{label:rt.retryFailed(v),kind:"link",accessibilityLabel:rt.retryFailedA11y(v),onPress:w,testID:"records-upload-retry-failed"}):null,jsxs(View,{style:s.settledActions,children:[jsx(re,{label:rt.addMore,kind:"link",accessibilityLabel:rt.addMoreA11y,disabled:!o,onPress:b,testID:"records-upload-another"}),n&&p.current!==null&&R>0?jsx(re,{label:rt.done,accessibilityLabel:rt.doneA11y,onPress:()=>n(p.current),testID:"records-upload-done"}):null]})]}):jsx(re,{label:rt.chooseFiles,accessibilityLabel:rt.chooseFilesA11y,disabled:!o,onPress:b,testID:"records-upload-choose"})]})}i(Da,"UploadRecordCard");function Ad(){let e=L();return useMemo(()=>jg(e),[e])}i(Ad,"useLocalStyles");function jg(e){let{color:t,space:r,radius:o,type:n}=e,l=i((s,c,a,d="regular")=>({..._(e,d),fontSize:s,lineHeight:Math.round(s*c),color:a}),"text");return StyleSheet.create({content:{padding:r.lg+r.xs,gap:r.lg+r.xs},header:{gap:r.sm,alignItems:"center"},iconBubble:{width:r.xxl+r.lg+r.xs,height:r.xxl+r.lg+r.xs,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{...l(n.size.heading+r.xs/2,n.lineHeight.snug,t.brandInk,"bold"),textAlign:"center"},subtitle:{...l(n.size.body,n.lineHeight.normal,t.text.muted),textAlign:"center",maxWidth:340},card:{borderRadius:o.md,backgroundColor:t.surface,borderWidth:1,borderColor:t.brandSoft,padding:r.lg,gap:r.md},cardTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},cardSubtitle:l(n.size.bodyTight,n.lineHeight.normal,t.text.muted),uploadingRow:{flexDirection:"row",alignItems:"center",gap:r.sm},progressText:{flex:1,...l(n.size.bodyTight,n.lineHeight.normal,t.text.secondary)},settled:{gap:r.sm},success:l(n.size.bodyTight,n.lineHeight.normal,t.text.primary),settledActions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:r.sm}})}i(jg,"makeLocalStyles");function Oa(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(Xg,{...o,style:t})})}i(Oa,"EverfurRecordsRequest");function Xg({petRef:e,requestId:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:s,style:c,nowMs:a}){let d=be(),{runtime:u,userRef:p,scopeEpoch:f}=ke(),h=yt(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),R=h.requests.find(b=>b.id===t)??null,v=Cn(o)&&(r!==void 0||n!==void 0||Fn(u.registry.services.uploadTransport)),y=R?bo(R):"",g;return h.status==="loading"?g=jsx(_l,{testID:"records-request-loading"}):h.status==="error"&&h.error?g=jsx(Qe,{variant:wt(h.error),message:h.error.displayMessage,onAction:h.error.retryable?h.refresh:void 0,testID:"records-request-error"}):R===null?g=jsx(Qe,{variant:"no_requests",testID:"records-request-missing"}):p===null?g=jsx(Qe,{variant:"error",testID:"records-request-error"}):g=jsx(Jg,{request:R,records:h,canUpload:v,onPickDocument:o,onNavigate:l,nowMs:a},JSON.stringify([p,f,R.id])),jsxs(View,{style:[d.root,c],children:[jsx(et,{title:y,onBack:s,testID:"records-request-header"}),jsx(KeyboardAvoidingView,{behavior:"padding",style:d.body,children:g}),jsx(Me,{})]})}i(Xg,"RequestBody");function Jg({request:e,records:t,canUpload:r,onPickDocument:o,onNavigate:n,nowMs:l}){let s=be(),c=Zg(),a=L(),d=td({request:e,onRecovered:t.refresh,canUpload:r},Nt()),[u,p]=useState(null),[f,h]=useState(false),[R,v]=useState(null),y=useRef(true);useEffect(()=>(y.current=true,()=>{y.current=false;}),[]);let g=d.request,b=l??Date.now(),w=g.status==="published",x=g.status==="published"||g.status==="failed"||g.status==="revoked",E=di(g),D=g.wireStatus==="clinic_responded_no_records",k=zs(g,b),S=ci(g,b),I=x?null:g.waitingExpectation?.trim()||null,Y=ho(g),z=Ns(g),$=d.canConvert,G=x&&!w,Z=d.error!==null&&u!==null&&u!=="start"?u==="revoke"?ge.errors.cancel:ge.errors[u]:null,oe=i((H,C)=>{p(H),C();},"run"),Ee=i(()=>{f||(h(true),v(null),t.createRequest(`records-upload-${Date.now().toString(36)}`).then(H=>{if(y.current){if(h(false),!H.ok){v(ge.errors.start);return}n?.({name:"request",requestId:H.value.id});}}));},"startFresh");return jsxs(ScrollView,{contentContainerStyle:c.content,keyboardShouldPersistTaps:"handled",testID:`records-request-${g.id}`,children:[jsx(_o,{request:g}),g.status==="awaiting_upload"?jsx(Da,{records:t,requestId:g.id,onPickDocument:o,canUpload:r}):null,g.statusLabel.length>0?jsx(View,{style:s.statusCard,accessibilityRole:"summary",children:jsx(m,{style:s.statusText,children:g.statusLabel})}):null,I&&!k?jsx(View,{style:s.infoNote,accessibilityRole:"summary",children:jsx(m,{style:s.infoNoteText,children:I})}):g.wireStatus==="awaiting_response"&&!k?jsx(View,{style:s.infoNote,accessibilityRole:"summary",children:jsx(m,{style:s.infoNoteText,children:ge.awaitingNote})}):null,k?jsx(View,{style:s.cautionNote,accessibilityRole:"summary",testID:"records-request-waiting-banner",children:jsx(m,{style:s.cautionNoteText,children:ge.waitingBanner(S)})}):null,w&&n?jsx(re,{label:ge.viewRecords,onPress:()=>n({name:"dashboard"}),style:c.readyCta,testID:"records-request-view-dashboard"}):null,z?jsxs(View,{style:[c.failureCard,E?c.failureCritical:c.failureCaution],accessibilityRole:"summary",testID:"records-failure-card",children:[jsx(m,{style:[c.failureTitle,E?c.failureTitleCritical:c.failureTitleCaution],children:Fs(g)}),g.canUpdateClinicEmail!==true&&g.canRetrySend!==true?jsx(m,{style:s.rowDetail,children:ge.nextStep}):null,g.canUpdateClinicEmail===true?jsxs(View,{style:c.emailBlock,children:[jsx(m,{style:s.fieldLabel,children:Ot.email}),jsx(qe,{style:s.field,accessibilityLabel:Ot.email,placeholder:Ot.emailPlaceholder,placeholderTextColor:a.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,value:d.email,editable:!d.busy,onChangeText:d.setEmail,testID:"records-failure-clinic-email"}),d.emailInvalid?jsx(m,{style:s.errorText,accessibilityRole:"alert",children:ge.errors.invalidEmail}):null,jsx(re,{label:Ot.updateEmail,accessibilityLabel:Ot.updateEmailA11y,disabled:!d.canUpdateEmail,busy:d.busy&&u==="email",onPress:()=>oe("email",d.updateEmail),testID:"records-failure-update-email"})]}):null,g.canRetrySend===true?jsx(re,{label:Ot.retry,kind:"outline",accessibilityLabel:Ot.retryA11y,disabled:!d.canRetry,busy:d.busy&&u==="retry",onPress:()=>oe("retry",d.retry),testID:"records-failure-retry-send"}):null,g.canRetrySend===true&&d.hasEmailEdit?jsx(m,{style:s.rowDetail,children:Ot.retryHint}):null,Z&&(u==="email"||u==="retry")?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:Z})}):null]}):null,(E||D)&&n?jsx(re,{label:ge.tryAnotherClinic,kind:"outline",accessibilityLabel:ge.tryAnotherClinicA11y,onPress:()=>n({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,Y!==null?jsxs(View,{style:c.callBlock,children:[jsx(sd,{call:Y,prompt:g.statusLabel}),g.canRetrySend===true?jsx(re,{label:d.busy&&u==="retry"?ge.resending:ge.resend,kind:"outline",accessibilityLabel:d.busy&&u==="retry"?ge.resendingA11y:ge.resendA11y,disabled:!d.canRetry,onPress:()=>oe("retry",d.retry),testID:"records-resend-authorization"}):null]}):null,$?jsxs(View,{style:c.block,children:[jsx(re,{label:d.busy&&u==="convert"?ge.converting:ge.convert,busy:d.busy&&u==="convert",onPress:()=>oe("convert",d.convert),testID:"records-convert-upload"}),jsx(m,{style:s.muted,children:ge.convertHint}),Z&&u==="convert"?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:Z})}):null]}):null,G?jsxs(View,{style:c.block,children:[jsx(re,{label:f?ge.freshUploadStarting:ge.freshUpload,kind:E||D?"outline":"primary",busy:f,onPress:Ee,testID:"records-upload-own-fresh"}),R?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:R})}):null]}):null,Z&&u==="revoke"?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:Z})}):null,g.canRevoke===true?d.confirmingRevoke?jsxs(View,{style:c.block,testID:"records-revoke-confirm",children:[jsx(m,{style:c.confirmTitle,accessibilityRole:"header",children:Ot.cancelQuestion}),jsx(m,{style:s.bodyText,children:Ot.cancelConsequence}),jsx(re,{label:d.busy&&u==="revoke"?ge.cancelling:ge.cancel,kind:"danger",accessibilityLabel:d.busy&&u==="revoke"?ge.cancellingA11y:ge.cancelA11y,busy:d.busy&&u==="revoke",onPress:()=>oe("revoke",d.revoke),testID:"records-revoke-do"}),jsx(re,{label:Ot.keepRequest,kind:"outline",disabled:d.busy,onPress:d.keepRequest,testID:"records-revoke-keep"})]}):jsx(re,{label:ge.cancel,kind:"danger",accessibilityLabel:ge.cancelA11y,disabled:d.busy,onPress:d.askRevoke,testID:"records-revoke"}):null]})}i(Jg,"RequestDetail");function Zg(){let e=L();return useMemo(()=>eb(e),[e])}i(Zg,"useLocalStyles");function eb(e){let{color:t,space:r,radius:o,type:n}=e,l=i((s,c,a,d="regular")=>({..._(e,d),fontSize:s,lineHeight:Math.round(s*c),color:a}),"text");return StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg+r.xs/2},readyCta:{minHeight:r.xxl+r.lg+r.xs/2},failureCard:{borderRadius:o.lg-r.xs,borderWidth:1,padding:r.md+r.xs/2,gap:r.md},failureCritical:{borderColor:t.badgeBgCritical,backgroundColor:t.badgeBgCritical},failureCaution:{borderColor:t.badgeBgCaution,backgroundColor:t.badgeBgCaution},failureTitle:{...l(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},failureTitleCritical:{color:t.danger},failureTitleCaution:{color:t.warningStrong},emailBlock:{gap:r.sm},callBlock:{gap:r.sm},block:{gap:r.sm},confirmTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")}})}i(eb,"makeLocalStyles");function Od(e){let{petRef:t,petName:r,controller:o,clinicController:n,onPickDocument:l,uploadTransport:s,consentVersion:c,ownerName:a,onCaptureSignature:d,initialScreen:u,onExit:p,style:f,renderPending:h,onOpenUrl:R,onCopy:v,onAsk:y,location:g}=Fe(e,["onExit"]),[b,w]=useReducer(ti,u,$n),x=Wn(b),E=b.stack.length;useEffect(()=>{let $=i(()=>E<=1?false:(w({type:"pop"}),true),"onBackPress"),G=BackHandler.addEventListener("hardwareBackPress",$);return ()=>{G.remove();}},[E]);let D=useCallback($=>w({type:"navigate",screen:$}),[]),k=useMemo(()=>Gn(b).handled?()=>w({type:"pop"}):p,[b,p]),S={onNavigate:D,...k?{onBack:k}:{},...r!==void 0?{petName:r}:{},...R?{onOpenUrl:R}:{},...v?{onCopy:v}:{},...y?{onAsk:y}:{},...g?{location:g}:{}},I={...o?{controller:o}:{},...c!==void 0?{consentVersion:c}:{}},Y={...l?{onPickDocument:l}:{},...s?{uploadTransport:s}:{}},z=h?{renderPending:h}:{};switch(x.name){case "dashboard":return jsx(ha,{petRef:t,...S,...I,...z,style:f});case "request":return jsx(Oa,{petRef:t,requestId:x.requestId,...S,...I,...Y,...z,style:f});case "timeline":return jsx(yd,{petRef:t,...S,style:f});case "record":return jsx(_a,{petRef:t,...S,...I,...z,style:f});case "document":return jsx(Ea,{petRef:t,...S,...I,...z,style:f});case "contributions":return jsx(fd,{petRef:t,docId:x.docId,...S,style:f});case "clinicPicker":return jsx(_i,{petRef:t,...S,...n?{controller:n}:{},...o?{recordsController:o}:{},style:f});case "clinicBatch":return jsx(ji,{petRef:t,petName:r??"",ownerName:a??"",...k?{onClose:k}:{},onCreated:()=>w({type:"navigate",screen:{name:"dashboard"}}),...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:f});case "consent":return jsx(Zi,{petRef:t,clinic:x.clinic,...S,...a!==void 0?{ownerName:a}:{},...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:f});case "upload":return jsx(Ia,{petRef:t,...S,...o?{controller:o}:{},...Y,...z,style:f});default:return pr(x)}}i(Od,"EverfurRecordsFlow");var ab=Od;function db(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",...Be(e.onClose,U.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsx(ub,{...Fe(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(db,"EverfurClinicRequest");function ub(e){let t=Nt(),[r,o]=useState(null),n=useCallback(async()=>r===null?null:{signaturePngBase64:r},[r]),l=Ol(e,e.controller??t,e.onCaptureSignature??n),s=e.onCaptureSignature!==void 0||r!==null,c=L(),a={minHeight:44,padding:c.space.sm,borderWidth:1,borderColor:c.color.borderHairlineGreen,borderRadius:c.radius.sm,color:c.color.text.primary,backgroundColor:c.color.surface},d={color:c.color.text.primary,fontSize:c.type.size.body},u=i((p,f,h=false)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:p,accessibilityState:{disabled:h},disabled:h,onPress:f,style:[a,{justifyContent:"center",opacity:h?.5:1}],children:jsx(m,{style:d,children:p})}),"button");return jsxs(View,{accessibilityLabel:U.title,style:[{backgroundColor:c.color.surface,padding:c.space.lg,gap:c.space.md,borderRadius:c.radius.lg,minHeight:120},e.style],children:[jsx(m,{accessibilityRole:"header",style:[d,{..._(c,"bold"),fontSize:c.type.size.heading}],children:U.title}),jsx(m,{style:d,children:e.petName}),l.created?jsx(m,{accessibilityLiveRegion:"polite",style:d,children:l.created.statusLabel||ce.records}):jsxs(Fragment,{children:[jsx(m,{style:d,children:U.ownerName}),jsx(qe,{accessibilityLabel:U.ownerName,style:a,value:l.ownerName,maxLength:200,editable:!l.busy,autoComplete:"name",onChangeText:l.setOwnerName}),jsx(m,{style:d,children:U.clinic}),jsx(qe,{accessibilityLabel:U.clinic,style:a,value:l.query,placeholder:U.placeholder,placeholderTextColor:c.color.text.placeholder,maxLength:200,editable:!l.busy,onChangeText:l.setQuery}),u(U.search,()=>{l.search();},l.busy||l.searching||l.query.trim().length<2),l.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:ce.loading}),l.recent.length>0&&jsx(m,{accessibilityRole:"header",style:d,testID:"records-clinic-recent-label",children:U.recentlyUsed}),l.recent.map(p=>jsx(View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>l.selectClinic(p),l.busy)},`recent-${p.id}`)),l.clinics.map(p=>jsx(View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>l.selectClinic(p),l.busy)},p.id)),l.needsEmail&&jsxs(Fragment,{children:[jsx(m,{style:d,children:U.email}),jsx(qe,{accessibilityLabel:U.email,style:a,value:l.email,placeholder:U.emailPlaceholder,placeholderTextColor:c.color.text.placeholder,maxLength:320,editable:!l.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:l.setEmail})]}),jsx(m,{accessibilityRole:"header",style:d,children:U.scopeHeading}),l.copy?jsx(m,{style:d,children:l.query.trim()&&l.ownerName.trim()?l.scope??q("internalError").displayMessage:ce.consentRequired}):!l.error&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:ce.loading}),!e.onCaptureSignature&&jsx(Lr,{onChange:o,disabled:l.busy}),!s&&jsx(m,{accessibilityRole:"alert",style:d,children:U.missingSignature}),l.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:d,children:l.error.displayMessage}),!l.copy&&l.error&&u(ce.retry,l.retryCopy),u(l.busy?U.sending:U.send,()=>{l.submit();},l.busy||!l.ready||!s)]}),e.onClose&&u(U.cancel,e.onClose,l.busy),jsx(Me,{})]})}i(ub,"ClinicRequestBody");
|
|
4
|
+
export{_i as EverfurClinicPicker,db as EverfurClinicRequest,ji as EverfurClinicRequestBatch,_a as EverfurRecordDetail,Ea as EverfurRecordDocument,ab as EverfurRecords,Zi as EverfurRecordsConsent,ha as EverfurRecordsDashboard,Od as EverfurRecordsFlow,Oa as EverfurRecordsRequest,Ia as EverfurRecordsUpload,Nr as RECORDS_CLINIC_BATCH_MAX,es as RECORDS_TERMINAL,In as REQUEST_TIMELINE_TITLES,Lr as SignaturePad,na as applyFactOverlay,da as buildRequestTimeline,Wn as currentRecordsScreen,si as deriveRecordsDashboardState,$n as initialRecordsNav,oa as isFactEditable,zr as isTerminalStatus,Qn as pickPetRecordsRequest,Gn as popRecordsNav,Jo as pushRecordsNav,dr as recordsDenialReasonOf,ti as recordsNavReducer,Di as registerRnSignature,Zo as replaceRecordsNav,ei as resetRecordsNav,ho as selectClinicCall,li as selectDashboardView,En as selectPrimaryLabel,Yy as selectRequestList,bo as selectRequestTitle,xs as transitionRecordsNav,yt as useEverfurRecords,Nt as useEverfurRecordsClinic,mi as useEverfurRecordsClinicBatch,ia as useRecordFactEdit,Ca as useRecordPdfLink,xa as useRecordShares,Qi as useRecordsMarkers};
|