@everfur/sdk 0.1.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +703 -4
- package/README.md +63 -23
- package/consent/package.json +8 -0
- package/dist/Chat-BZZ-Py5l.d.ts +128 -0
- package/dist/Chat-Dq4fffIO.d.cts +128 -0
- package/dist/DepthViews-BG3E25MD.d.ts +16 -0
- package/dist/DepthViews-B_hIypI6.d.cts +19 -0
- package/dist/DepthViews-CL75jyRA.d.cts +16 -0
- package/dist/DepthViews-CkYri51q.d.ts +19 -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-BorG422I.d.cts +146 -0
- package/dist/attachments-BrUWQYNK.d.ts +257 -0
- package/dist/attachments-D_SECjr1.d.cts +257 -0
- package/dist/attachments-DpldrvIW.d.ts +146 -0
- package/dist/bookingCopy-CqtDYvCR.d.ts +732 -0
- package/dist/bookingCopy-SREvkG19.d.cts +732 -0
- package/dist/branding-CsRdeNwK.d.cts +566 -0
- package/dist/branding-CsRdeNwK.d.ts +566 -0
- package/dist/callCopy-DoQKG3-L.d.cts +40 -0
- package/dist/callCopy-DoQKG3-L.d.ts +40 -0
- package/dist/casesRepository-DwtZVsbj.d.cts +51 -0
- package/dist/casesRepository-v6QczS9N.d.ts +51 -0
- package/dist/chat/index.cjs +1 -1170
- package/dist/chat/index.d.cts +32 -53
- package/dist/chat/index.d.ts +32 -53
- package/dist/chat/index.js +1 -1167
- package/dist/client/index.cjs +9 -2315
- package/dist/client/index.d.cts +80 -16
- package/dist/client/index.d.ts +80 -16
- package/dist/client/index.js +9 -2215
- package/dist/{config-CiJ0PVBB.d.ts → config--Wu1Umhd.d.cts} +64 -26
- package/dist/{config-BSjBdxrZ.d.cts → config-C7eb_IMD.d.ts} +64 -26
- 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-CL3lyuy1.d.cts +159 -0
- package/dist/context-CahAEha8.d.ts +159 -0
- package/dist/copy-DdVFDL01.d.ts +198 -0
- package/dist/copy-UeUJVk8X.d.cts +198 -0
- package/dist/core/index.cjs +13 -3178
- package/dist/core/index.d.cts +164 -29
- package/dist/core/index.d.ts +164 -29
- package/dist/core/index.js +13 -3166
- package/dist/depth-D5HwcvKC.d.cts +533 -0
- package/dist/depth-DvPwPuT_.d.ts +533 -0
- package/dist/entitlementRepository-B7egEdW6.d.ts +43 -0
- package/dist/entitlementRepository-BpJ7tiwl.d.cts +43 -0
- package/dist/{identity-Brl-lDd6.d.cts → identity-C2-08BZW.d.cts} +20 -7
- package/dist/{identity-DK9zORrG.d.ts → identity-CEi9GRFZ.d.ts} +20 -7
- 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 -4494
- package/dist/index.d.cts +30 -121
- package/dist/index.d.ts +30 -121
- package/dist/index.js +12 -4470
- 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/optionalModule-DbJmsq5f.d.cts +21 -0
- package/dist/optionalModule-DbJmsq5f.d.ts +21 -0
- package/dist/pets-DJv2sj2H.d.ts +92 -0
- package/dist/pets-JVCXgRgR.d.cts +92 -0
- package/dist/petsRepository-B_gKbAzJ.d.cts +142 -0
- package/dist/petsRepository-Bk6GDwLs.d.ts +142 -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-BY2ph0_y.d.cts +376 -0
- package/dist/ports-D7YW8qz9.d.ts +376 -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-BjDpqqvm.d.cts +110 -0
- package/dist/requestFunnel-DFMGcluw.d.ts +110 -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-Bvr8yqXm.d.cts → runtimeTypes-gZEJu-da.d.cts} +104 -132
- package/dist/{runtime-BIYzf9cK.d.ts → runtimeTypes-w5KqBMcs.d.ts} +104 -132
- 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/booking/index.cjs +1 -0
- package/dist/televet/booking/index.d.cts +294 -0
- package/dist/televet/booking/index.d.ts +294 -0
- package/dist/televet/booking/index.js +1 -0
- package/dist/televet/call/index.cjs +1 -0
- package/dist/televet/call/index.d.cts +141 -0
- package/dist/televet/call/index.d.ts +141 -0
- package/dist/televet/call/index.js +1 -0
- package/dist/televet/index.cjs +1 -0
- package/dist/televet/index.d.cts +142 -0
- package/dist/televet/index.d.ts +142 -0
- package/dist/televet/index.js +1 -0
- package/dist/testing/index.cjs +5 -823
- package/dist/testing/index.d.cts +18 -4
- package/dist/testing/index.d.ts +18 -4
- package/dist/testing/index.js +5 -820
- package/dist/testing/rn/index.cjs +1 -449
- package/dist/testing/rn/index.d.cts +18 -29
- package/dist/testing/rn/index.d.ts +18 -29
- package/dist/testing/rn/index.js +1 -444
- package/dist/testing/web/index.cjs +1 -0
- package/dist/testing/web/index.d.cts +132 -0
- package/dist/testing/web/index.d.ts +132 -0
- package/dist/testing/web/index.js +1 -0
- package/dist/timelineRows-C15jxFFH.d.ts +19 -0
- package/dist/timelineRows-odO8g9r2.d.cts +19 -0
- package/dist/typeStyle-CKqVYD6L.d.cts +111 -0
- package/dist/typeStyle-DmoyacDG.d.ts +111 -0
- package/dist/uploadTransport-D0M0T4hN.d.ts +38 -0
- package/dist/uploadTransport-DKJHs3Yj.d.cts +38 -0
- package/dist/useRecordsDepth-C6rjEaLn.d.cts +237 -0
- package/dist/useRecordsDepth-crhBllQK.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-Bxwxp4xD.d.ts +310 -0
- package/dist/view-DyitEO0m.d.cts +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 +218 -0
- package/dist/web/index.d.ts +218 -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 +285 -0
- package/dist/web/records/index.d.ts +285 -0
- package/dist/web/records/index.js +4 -0
- package/dist/web/televet/booking/index.cjs +1 -0
- package/dist/web/televet/booking/index.d.cts +349 -0
- package/dist/web/televet/booking/index.d.ts +349 -0
- package/dist/web/televet/booking/index.js +1 -0
- package/dist/web/televet/call/index.cjs +1 -0
- package/dist/web/televet/call/index.d.cts +142 -0
- package/dist/web/televet/call/index.d.ts +142 -0
- package/dist/web/televet/call/index.js +1 -0
- package/dist/web/televet/index.cjs +1 -0
- package/dist/web/televet/index.d.cts +136 -0
- package/dist/web/televet/index.d.ts +136 -0
- package/dist/web/televet/index.js +1 -0
- package/notifications/package.json +8 -0
- package/package.json +266 -10
- package/records/depth/package.json +8 -0
- package/server/events/device-blocked.cjs +15 -0
- package/server/events/package.json +9 -0
- package/televet/booking/package.json +8 -0
- package/televet/call/package.json +8 -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/booking/native-blocked.cjs +12 -0
- package/web/televet/booking/package.json +8 -0
- package/web/televet/call/native-blocked.cjs +12 -0
- package/web/televet/call/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 Ud=Object.defineProperty;var i=(e,t)=>Ud(e,"name",{value:t,configurable:true});var No=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(No.map(e=>e.wireCode));var jd=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"}),Ua=Object.freeze(No.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:jd[e.wireCode]}))),$d=new Map(Ua.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Wd=Object.freeze(["http_envelope",...[...new Set(Ua.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Vn(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let o of [t??"http_envelope",...Wd]){let n=$d.get(o+r);if(n)return n}}i(Vn,"contractErrorFor");function Gd(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Gd,"contractDocUrl");function ja(e){return null}i(ja,"publishedDocUrl");var Yd=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 $a(e){return Yd[e]}i($a,"categoryFor");function Wa(e){let t=Vn(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(Wa,"fromWire");var Kd=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Mo(e){return Kd.has(e)}i(Mo,"isAutoRetryable");var Qd=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Ga(e){return Mo(e)||Qd.has(e)}i(Ga,"isRetryableCode");var Xd=500,Bo=8e3,Ya=4;function Ka(e,t=Math.random){let r=Math.max(0,e),o=Math.min(Xd*2**r,Bo);return Math.floor(t()*o)}i(Ka,"backoffDelayMs");var Jd=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 Ho(e){return Jd[e]}i(Ho,"userFacingError");function Qa(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(Qa,"defineHidden");var Zd=/^[a-z][a-z0-9_]{0,63}$/;function q(e,t){let r=Vn(t?.wireCode,t?.wireEnvelope),o={code:e,category:$a(e),retryable:t?.retryable??Ga(e),displayMessage:Ho(e)};if(t?.httpStatus!==void 0&&(o.httpStatus=t.httpStatus),t?.requestId&&(o.requestId=t.requestId),typeof t?.reasonCode=="string"&&Zd.test(t.reasonCode)&&(o.reasonCode=t.reasonCode),r);return t?.wireMessage&&Qa(o,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Qa(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 qn=class qn extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,qn.prototype);}};i(qn,"EverfurConfigError");var rn=qn;var ts=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),Xa=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 eu(e){let t=Object.prototype.hasOwnProperty.call(Xa,e)?Xa[e]:void 0;if(t!==void 0)return t;let r=e;return ts.has(r)?r:"parsing"}i(eu,"normalizeStatus");function rs(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(rs,"normalizeOrigin");var tu=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 ur(e){let t=tu.safeParse(e);if(!t.success)return null;let r=t.data,o=nu(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??eu(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:Za(r.document_count,0),heldItemCount:Za(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(ur,"mapRequestView");var ru=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 ns(e){let t=ru.safeParse(e);if(!t.success)return null;let r=t.data,o=Uo(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(ns,"mapRequestGroup");function nu(e){return !e||e==="awaiting_upload"||e==="in_review"?null:ts.has(e)?e:null}i(nu,"normalizeSimpleStatus");function Uo(e){let t=Array.isArray(e)?e:[],r=[];for(let o of t){let n=ur(o);n!==null&&r.push(n);}return Object.freeze(r)}i(Uo,"mapRequestList");var ou=z.object({source_doc_id:z.string().min(1),request_id:z.string().min(1)});function os(e){let t=ou.safeParse(e);return t.success?Object.freeze({documentId:t.data.source_doc_id,requestId:t.data.request_id,status:"received"}):null}i(os,"mapUploadedDocument");var iu=z.object({label:z.string(),value:z.string()}),jo=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()}),au=z.object({at:z.string(),value:z.number().nullish(),display:z.string().nullish(),origin:z.string().nullish()}),su=z.object({key:z.string(),label:z.string().optional(),points:z.array(au).optional()}),lu=z.object({title:z.string(),detail:z.string().nullish(),due_at:z.string().nullish()}),$o=z.object({doc_id:z.string(),title:z.string().nullish(),page_count:z.number().nullish(),received_at:z.string().nullish()});function Wo(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:rs(e.origin),canonicalKey:e.canonical_key??null})}i(Wo,"mapEntityRow");function Go(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(Go,"mapDocumentRow");var cu=z.object({identity:z.array(iu).optional(),entities:z.array(jo).optional(),entity_series:z.array(su).optional(),forward_looking:z.array(lu).optional(),documents:z.array($o).optional()});function is(e,t){let r=uu(t)?t:{},o=es(r.schema_version,"epdf/1.0"),n=es(r.disclaimer,""),l=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Ja(l,o,n);let s=cu.safeParse(r);if(!s.success)return Ja(l,o,n);let c=s.data,a=(c.identity??[]).map(R=>Object.freeze({label:R.label,value:R.value})),d=(c.entities??[]).map(Wo),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:rs(v.origin)})))})),p=(c.forward_looking??[]).map(R=>Object.freeze({title:R.title,detail:R.detail??null,dueAt:R.due_at??null})),g={};for(let R of c.documents??[])g[R.doc_id]=Go(R);let h=r.is_empty===true||a.length===0&&d.length===0&&u.length===0&&p.length===0&&Object.keys(g).length===0;return Object.freeze({petRef:l,schemaVersion:o,isEmpty:h,withheld:false,generatedAt:pu(r.generated_at),identity:Object.freeze(a),entities:Object.freeze(d),entitySeries:Object.freeze(u),forwardLooking:Object.freeze(p),documents:Object.freeze(g),disclaimer:n})}i(is,"mapRecordView");function Ja(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(Ja,"withheldView");var du=z.object({pet_ref:z.string().optional(),granted:z.boolean().optional(),version:z.string().nullish(),granted_at:z.string().nullish()});function zn(e,t){let r=du.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(zn,"mapConsent");function uu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(uu,"isObject");function Za(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(Za,"numberOr");function es(e,t){return typeof e=="string"&&e.length>0?e:t}i(es,"strOr");function pu(e){return typeof e=="string"&&e.length>0?e:null}i(pu,"strOrNull");var as=Object.freeze(["published","failed","revoked"]);function Mr(e){return as.includes(e)}i(Mr,"isTerminalStatus");function pr(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(pr,"recordsDenialReasonOf");var mu="records_consent_required";function yu(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(yu,"recordsWireCodeOf");function rr(e){return e===null||e.httpStatus!==409?false:yu(e)===mu}i(rr,"isRecordsConsentRequired");var fu=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Fn(e){return e!==fu}i(Fn,"isUploadTransportAvailable");var ss=Object.freeze({record(){}}),mr=25*1024*1024,ls=64,nn=128,mt=128,on="application/pdf",cs=9e4;function us(e){return new Yo(e)}i(us,"createRecordsController");var Ko=class Ko{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??ss,this.newIdempotencyKey=t.newIdempotencyKey??vu(),this.timers=t.timers??hu,this.uploadDeadlineMs=t.uploadDeadlineMs??cs;}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=ur(r.value);return o===null?B(Nn()):(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=ur(r.value);return o===null?B(Nn()):(this.observeRequest(o),_e(o))}async listRequests(){let t=await this.repository.listRequests();if(!t.ok)return this.onRequestError(t.error);let r=Uo(t.value);for(let o of r)this.observeRequest(o);return _e(r)}async uploadDocument(t){let{requestId:r,file:o}=t,n=gu(o);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),B(ds(`upload rejected: ${n}`));let l=await this.repository.initiateUpload(r,{content_type:on,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(ds(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:bu(c.error)??"corrupt"}),this.onRequestError(c.error);let a=os(c.value);return a===null?B(Nn()):_e(a)}async postToS3(t,r,o){let n=new AbortController,l=Ru(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=pr(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=is(t,o.value);return n.petRef!==t?B(Nn()):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(zn(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(zn(t.petRef,r.value)):(pr(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(zn(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 pr(t)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),B(t)}};i(Ko,"RecordsControllerImpl");var Yo=Ko;function gu(e){if(e.mimeType!==on)return "unsupported_format";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>mr?"oversize":null}i(gu,"validateFile");function bu(e){let t=e.wireMessage;return t==="unsupported_format"||t==="oversize"||t==="corrupt"?t:null}i(bu,"reasonFromWire");function ds(e){return q("mediaUploadFailed",{retryable:false,wireMessage:e})}i(ds,"uploadFailed");function Nn(){return q("internalError",{retryable:true})}i(Nn,"internal");var hu={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function Ru(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(Ru,"mergeSignals");function vu(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(vu,"defaultIdempotencyFactory");function yr(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(yr,"assertNever");function ps(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(ps,"errorFrame");function Cu(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(Cu,"authHeaders");function an(e,t){return {...e,headers:{...Eu(e.headers),...Cu(t)}}}i(an,"withAuthHeaders");function Eu(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(Eu,"stripAuthHeaders");async function ms(e,t){if(t.mode==="anonymous")return t.transport.request(an(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(Qo())}let o=await t.transport.request(an(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(Qo())}let l=await t.transport.request(an(e,{mode:"personalized",token:n,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !l.ok&&l.error.httpStatus===401?B(Qo(l.error.httpStatus)):l}i(ms,"authedSend");function Qo(e){return q("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(Qo,"authRejectedError");function ys(e){return q("internalError",{retryable:true,wireMessage:Su(e)})}i(ys,"networkError");function Su(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Su,"describeCause");var ku=3e4,Tu=Bo*2,_u="idempotency-key",Pu=new Set(["POST","PUT","PATCH","DELETE"]),Iu=Object.freeze({onEvent(){}}),Du=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Au(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(Au,"seededIdempotencyKey");function fr(e){let t=e.observer??Iu,r=e.timers??Du,o=e.rng??Math.random,n=e.sleep??((g,h)=>ju(g,r,h)),l=e.maxAttempts??Ya,s=e.unaryTimeoutMs??ku,c=e.newIdempotencyKey??nr(),a=i(g=>{try{t.onEvent(g);}catch{}},"emit");async function d(g,h,R){let v=R?.maxAttempts,x=Math.max(1,v??l),y=R?.idempotent??Pu.has(h.method),f=R?.idempotencyKey===void 0?null:Au(R.idempotencyKey),E=y?f??c():null,b=Ou(h,E),C=0;for(;;){let D=i(H=>Object.freeze({call:g,method:h.method,path:h.path,attempt:C,...E?{idempotencyKey:E}:{},...H}),"stamp");a(D({phase:"attempt"}));let S=Hu(s,r),k=Uu(S.signal,h.signal),I;try{I=await ms({...b,signal:k.signal},e.auth);}catch(H){I=B(ys(H));}finally{k.dispose(),S.cancel();}if(I.ok)return a(D({phase:"settled",ok:true,reason:"ok"})),I;let G=I.error,z=Vu(G,C,{maxAttempts:x,rng:o,now:r.now(),aborted:h.signal?.aborted===true,...v!==void 0?{perCallMaxAttempts:v}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),Y={ok:false,code:G.code,reason:z.reason,...G.httpStatus!==void 0?{httpStatus:G.httpStatus}:{},...G.requestId!==void 0?{requestId:G.requestId}:{}};if(!z.retry)return a(D({phase:"settled",...Y})),B(G);if(a(D({phase:"retry",...Y,delayMs:z.delayMs})),await n(z.delayMs,h.signal),h.signal?.aborted===true)return a(D({phase:"settled",...Y,reason:"aborted"})),B(G);C+=1;}}i(d,"send");async function u(g){return an(g,await Bu(e.auth))}i(u,"authorize");async function*p(g,h,R){a(Object.freeze({call:g,phase:"stream.open",method:h.method,path:h.path,attempt:0}));try{yield*e.auth.transport.stream(h,R);}catch{yield ps({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(fr,"createRequestFunnel");function Ou(e,t){let r={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==_u&&(r[o]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(Ou,"assembleHeaders");function nr(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(nr,"defaultIdempotencyKeyFactory");var Lu=10;function Vu(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let o=qu(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!Mo(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(Lu,Math.floor(d)))},"policyCeiling"),c=r.perCallMaxAttempts??s()??r.maxAttempts;if(t+1>=c)return {retry:false,reason:"attempts-exhausted"};let a=zu(e,r.now);return a!==null?a>Tu?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:a}:{retry:true,reason:n,delayMs:Ka(t,r.rng)}}i(Vu,"decideRetry");function qu(e){let t=e.code==="unknown"?Wa(Mu(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(qu,"throttleKind");function zu(e,t){let r=Fu(e.raw);if(r===null)return null;let o=r-t;return o>0?o:0}i(zu,"retryOverrideMs");function Fu(e){for(let t of gs(e)){let r=t.resets_at,o=Nu(r);if(o!==null)return o}return null}i(Fu,"findResetsAt");function gs(e){if(!fs(e))return [];let t=[e];for(let r of ["error","detail"]){let o=e[r];fs(o)&&t.push(o);}return t}i(gs,"candidateScopes");function Nu(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(Nu,"parseInstantMs");function Mu(e){for(let t of gs(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Mu,"rawWireCode");function fs(e){return typeof e=="object"&&e!==null}i(fs,"isRecord");async function Bu(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(Bu,"resolveDeviceAuth");function Hu(e,t){let r=new AbortController,o=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(o),"cancel")}}i(Hu,"boundedSignal");function Uu(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(Uu,"mergeSignals");function ju(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(ju,"delayAbortable");function gr(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(gr,"hasLoneSurrogate");var or="/widget/v1/records";function hs(e){let{auth:t}=e,r=t.mode,o=e.funnel??fr({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(Gu(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`}):gr(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,nn),s("pet_ref",a.pet_ref,mt));return d?Promise.resolve(B(d)):n("records.createRequest",Xo(`${or}/requests`,a),"request")},"createRequest"),initiateUpload:i((a,d)=>{let u=l("request_id",a);return u?Promise.resolve(B(u)):n("records.initiateUpload",Xo(`${or}/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",Xo(`${or}/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",Mn(`${or}/requests/${encodeURIComponent(a)}`),"request")},"getRequest"),listRequests:i(async()=>{let a=await n("records.listRequests",Mn(`${or}/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",Mn(`${or}/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",Mn(`${or}/pets/${encodeURIComponent(a)}/consent`),"consent")},"getConsent"),putConsent:i((a,d)=>{let u=c(s("consent_version",d.consent_version,ls),s("idempotency_key",d.idempotency_key,nn),s("pet_ref",a,mt));return u?Promise.resolve(B(u)):n("records.putConsent",Yu(`${or}/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",Ku(`${or}/pets/${encodeURIComponent(a)}/consent`),"consent")},"deleteConsent")}}i(hs,"createHttpRecordsRepository");function bs(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(bs,"withReason");var $u="pet_not_registered";function Wu(e){return e.httpStatus!==404?null:e.reasonCode===$u?"pet_not_found":"entitlement"}i(Wu,"recordsErrorReasonFor");function Gu(e,t,r){let o=Wu(e);return o!==null?bs(e,o):e.code!=="accessDenied"?e:bs(e,t==="anonymous"?"session_required":r==="content"?"consent_required":"entitlement")}i(Gu,"tagReason");function Mn(e){return {method:"GET",path:e}}i(Mn,"get");function Xo(e,t){return {method:"POST",path:e,body:t}}i(Xo,"post");function Yu(e,t){return {method:"PUT",path:e,body:t}}i(Yu,"put");function Ku(e){return {method:"DELETE",path:e}}i(Ku,"del");var Rs=Symbol.for("@everfur/sdk#EverfurContext@v1"),vs=globalThis,xs=vs[Rs]??(vs[Rs]=createContext(null));xs.displayName??="EverfurContext";function ke(){let e=useContext(xs);if(e===null)throw new rn("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(ke,"useEverfurContext");var Jo=new Map,Zo=new Set;function ws(e){Jo.set(e,(Jo.get(e)??0)+1);for(let t of [...Zo])t();}i(ws,"notifyRecordsConsentWithdrawn");function ep(e){return Jo.get(e)??0}i(ep,"recordsConsentEpochOf");function tp(e){return Zo.add(e),()=>{Zo.delete(e);}}i(tp,"subscribe");function Bn(e){let t=useCallback(()=>ep(e),[e]);return useSyncExternalStore(tp,t,t)}i(Bn,"useRecordsConsentEpoch");var ti={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[]},Es=4e3,np=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),[g,h]=useState({scope:c,value:ti}),R=g.scope===c?g.value:ti,v=useCallback(w=>{h(T=>T.scope===c?{scope:c,value:w(T.value)}:T);},[c]),x=useRef(0);useEffect(()=>(a.current=c,h({scope:c,value:ti}),()=>{a.current=null,x.current+=1;}),[c]),useEffect(()=>{if(e.controller)return;let{services:w}=n.registry,T={record:i((M,X)=>w.telemetry.track(M,X),"record")},O=n.registry.acquire("records",`${l??""}|${t}${o?"|own-upload":""}`,()=>us({repository:hs({auth:w.authFor(l),...w.errorPolicy?{errorPolicy:w.errorPolicy}:{}}),uploads:o?{postMultipart:i((M,X,ye)=>(r.current??w.uploadTransport).postMultipart(M,X,ye),"postMultipart")}:w.uploadTransport,telemetry:T}),()=>{});return u({scope:c,controller:O}),()=>{n.registry.release(O);}},[n,l,t,e.controller,s,c,o]);let y=useCallback(w=>{v(T=>({...T,...w}));},[v]),f=useCallback(async()=>{if(!p||a.current!==c)return;let w=x.current+=1;D.current=0,I(),y({loading:true,error:null,denialReason:null,withheld:false});let[T,O]=await Promise.all([p.getConsent(t),p.listRequests()]);if(w!==x.current)return;let M=T.ok?T.value:null,X=O.ok?O.value.filter(Ve=>Ve.petRef===t):[],ye=O.ok?null:O.error;if(M&&M.granted){let Ve=await p.getRecord(t);if(w!==x.current)return;if(Ve.ok){y({consent:M,requests:X,record:Ve.value,withheld:Ve.value.withheld,error:Ve.value.withheld?lp():ye,denialReason:null,loading:false});return}y({consent:M,requests:X,record:null,error:Ve.error,denialReason:pr(Ve.error),withheld:false,loading:false});return}y({consent:M,requests:X,record:null,error:T.ok?ye:T.error,denialReason:M?"consent_required":sp(T),withheld:false,loading:false});},[p,t,y,c]);useEffect(()=>(f(),()=>{x.current+=1;}),[f]);let E=useMemo(()=>ap(R.requests),[R.requests]),b=E?.id??null,C=E?.status??null,D=useRef(0),S=useRef(null),[k,I]=useReducer(w=>w+1,0);useEffect(()=>{if(!p||b===null||C===null||Mr(C)||C==="in_review")return;S.current!==String(b)&&(S.current=String(b),D.current=0);let w=false,T=i(async()=>{if(w||D.current>=np)return;D.current+=1;let M=await p.getRequest(b);if(!w){if(M.ok&&M.value.petRef===t){if(v(X=>({...X,requests:Un(X.requests,M.value)})),Mr(M.value.status)){M.value.status==="published"&&f();return}if(M.value.status==="in_review")return}O=setTimeout(()=>{T();},Es);}},"tick"),O=setTimeout(()=>{T();},Es);return ()=>{w=true,clearTimeout(O);}},[p,b,C,f,k,t,v]);let G=useCallback(async w=>{if(!p||a.current!==c)return jn();let T=await p.createUploadRequest({petRef:t,idempotencyKey:w});return a.current===c&&T.ok&&T.value.petRef===t&&v(O=>({...O,requests:Un(O.requests,T.value)})),T},[p,t,c,v]),z=useCallback((w,T)=>{v(O=>({...O,uploadQueue:O.uploadQueue.map(M=>M.key===w?T(M):M)}));},[v]),Y=useCallback(async(w,T)=>{let O=Date.now().toString(36),M=T.map((ye,Ve)=>{let ie=op(ye);return {key:`${O}-${Ve}`,name:ye.name??null,status:ie===null?"queued":"skipped",progress:0,skipReason:ie,error:null}}),X=[...M];if(!p||a.current!==c)return Object.freeze(X);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})),y({uploadProgress:0});let we=await p.uploadDocument({requestId:w,file:Ve,onProgress:i(Xe=>{if(a.current!==c)return;let qt=Math.min(1,Math.max(0,Xe));z(ie.key,zt=>({...zt,progress:Math.max(zt.progress,qt)})),y({uploadProgress:qt});},"onProgress")});if(a.current!==c)break;let vt=we.ok?{...ie,status:"done",progress:1}:{...ie,status:"failed",error:we.error};if(X[ye]=vt,z(ie.key,()=>vt),we.ok){let Xe=await p.getRequest(w);a.current===c&&Xe.ok&&Xe.value.petRef===t&&v(qt=>({...qt,requests:Un(qt.requests,Xe.value)}));}}return a.current===c&&y({isUploading:false,uploadProgress:null}),Object.freeze(X)},[p,y,z,t,c,v]),H=useCallback(async(w,T)=>{if(!p||a.current!==c)return jn();let O=`${Date.now().toString(36)}-0`;v(X=>({...X,isUploading:true,uploadProgress:0,uploadQueue:[{key:O,name:T.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let M=await p.uploadDocument({requestId:w,file:T,onProgress:i(X=>{a.current===c&&(y({uploadProgress:X}),z(O,ye=>({...ye,progress:Math.max(ye.progress,Math.min(1,X))})));},"onProgress")});if(a.current!==c)return M;if(y({isUploading:false,uploadProgress:null}),z(O,X=>M.ok?{...X,status:"done",progress:1}:{...X,status:"failed",error:M.error}),M.ok){let X=await p.getRequest(w);a.current===c&&X.ok&&X.value.petRef===t&&v(ye=>({...ye,requests:Un(ye.requests,X.value)}));}return M},[p,y,z,t,c,v]),Z=useCallback(async(w,T)=>{if(!p||a.current!==c)return jn();let O=await p.grantConsent({petRef:t,consentVersion:w,idempotencyKey:T});return O.ok&&a.current===c&&f(),O},[p,t,f,c]),oe=useCallback(async()=>{if(!p||a.current!==c)return jn();let w=await p.revokeConsent(t);return w.ok&&ws(t),w.ok&&a.current===c&&(x.current+=1,y({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:w.value})),w},[p,t,y,c]),Ee=useCallback(()=>{f();},[f]),U=ip(R,p!==null);return useMemo(()=>({status:U,record:R.record,requests:R.requests,activeRequest:E,consent:R.consent,error:R.error,denialReason:R.denialReason,withheld:R.withheld,isUploading:R.isUploading,uploadProgress:R.uploadProgress,uploadQueue:R.uploadQueue,createRequest:G,uploadDocument:H,uploadDocuments:Y,grantConsent:Z,revokeConsent:oe,refresh:Ee}),[U,R,E,G,H,Y,Z,oe,Ee])}i(yt,"useEverfurRecords");function op(e){if(e.mimeType!==on)return "unsupported";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>mr?"too_large":null}i(op,"skipReasonFor");function ip(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(ip,"selectStatus");function ap(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(ap,"newestRequest");function Un(e,t){let r=e.filter(o=>o.id!==t.id);return [t,...r]}i(Un,"replaceRequest");function sp(e){return e.ok?"consent_required":pr(e.error)??"consent_required"}i(sp,"consentDenial");function lp(){return q("internalError",{retryable:false})}i(lp,"withheldSentinel");function jn(){return {ok:false,error:q("internalError",{retryable:true})}}i(jn,"notReady");function ri(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(ri,"reportHostFailure");function cp(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(cp,"isThenable");function $n(e,...t){if(typeof e=="function")try{let r=e(...t);return cp(r)&&Promise.resolve(r).then(void 0,ri),r}catch(r){ri(r);return}}i($n,"callHost");var Ss=new WeakMap;function ln(e){if(typeof e!="function")return;let t=Ss.get(e);if(t!==void 0)return t;let r=i((...o)=>{$n(e,...o);},"guarded");return Ss.set(e,r),r}i(ln,"guardHost");function ze(e,t){let r=null;for(let o of t){let n=e[o];typeof n=="function"&&(r??={...e},r[o]=ln(n));}return r??e}i(ze,"guardHostProps");function Tr(e,...t){let r;try{r=e(...t);}catch(o){return ri(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(r).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(Tr,"callHostAsync");var ks=Object.freeze({name:"dashboard"});function Wn(e=ks){return Object.freeze({stack:Object.freeze([e])})}i(Wn,"initialRecordsNav");function Gn(e){return e.stack[e.stack.length-1]??ks}i(Gn,"currentRecordsScreen");function ni(e,t){return Object.freeze({stack:Object.freeze([...e.stack,t])})}i(ni,"pushRecordsNav");function oi(e,t){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),t])})}i(oi,"replaceRecordsNav");function ii(e){return Wn(e)}i(ii,"resetRecordsNav");function Yn(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(Yn,"popRecordsNav");function Ts(e,t){return t.name==="dashboard"?ii(t):Gn(e).name==="upload"&&t.name==="request"?oi(e,t):ni(e,t)}i(Ts,"transitionRecordsNav");function ai(e,t){switch(t.type){case "push":return ni(e,t.screen);case "pop":return Yn(e).state;case "replace":return oi(e,t.screen);case "reset":return ii(t.screen);case "navigate":return Ts(e,t.screen);default:return e}}i(ai,"recordsNavReducer");function ci(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))ci(e[t]);}return e}i(ci,"deepFreeze");var dp=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Ps={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Is={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},_s={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},up={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},pp={regular:"400",medium:"500",bold:"700"},mp={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},yp=0,Kn="System",Qn="monospace",fp=["content","heading","control","compact","badge"];function gp(e){let t={};for(let r of fp)t[r]=e;return t}i(gp,"authoredTierSizes");function Ds(){return {family:Kn,mono:Qn,fontUrl:null,families:{regular:Kn,medium:Kn,bold:Kn,mono:Qn,monoMedium:Qn,monoBold:Qn},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:_s,tierSizes:gp(_s),lineHeight:up,weight:pp,letterSpacing:mp,scale:1,maxScale:yp,scaleCaps:dp}}i(Ds,"baseType");var As={},si=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function li(e){return `cubic-bezier(${e.join(", ")})`}i(li,"cssCubicBezier");var Os={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:li(si.standard),emphasized:li(si.emphasized),exit:li(si.exit)},reducedMotion:false},bp={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)"},Ls=ci({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:bp,space:Ps,radius:Is,type:Ds(),motion:Os,slots:As}),hp={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)"};ci({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:hp,space:Ps,radius:Is,type:Ds(),motion:Os,slots:As});var Vs=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),qs=globalThis,di=qs[Vs]??(qs[Vs]=createContext(Ls));di.displayName??="EverfurThemeContext";function V(){return useContext(di)}i(V,"useEverfurTheme");function Ep(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Ep,"tierMultiplier");function m({tier:e="content",...t}){let{type:r}=V(),o=Ep(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 Sp=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[Sp[t]]}}i(_,"face");var $=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",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:i(e=>`Typed signature: ${e}`,"typedSignatureA11y"),missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used"});var xe=Object.freeze({title:$.title,placeholder:$.placeholder,searchA11y:$.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:$.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 Fs(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(Fs,"clinicEmailStatusBadge");function Ns(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} km`}i(Ns,"formatClinicDistanceLabel");function Ms(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} ${e===1?"kilometer":"kilometers"} away`}i(Ms,"formatClinicDistanceForA11y");var Bs=300,ui=2;var de=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 Hs(e){return !Mr(e.status)}i(Hs,"isRecordsInProgress");function Xn(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(Hs).sort((l,s)=>s.updatedAt.localeCompare(l.updatedAt))[0]??null}i(Xn,"pickPetRecordsRequest");function pi(e){if(e.hasMarkers)return "published";let t=Xn(e.requests,e.petRef);return t===null?"none":t.status==="published"||Hs(t)?"in_progress":"none"}i(pi,"deriveRecordsDashboardState");function kp(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i(kp,"selectDashboardLoading");function mi(e){return kp(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(mi,"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",timelineA11y:"Request timeline",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 Tp(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(Tp,"fallbackFailureTitle");function Us(e){let t=e.failureReason?.trim()??"";return t.length>0?t:Tp(e)}i(Us,"failureTitle");var _p=1440*60*1e3;function yi(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/_p)}i(yi,"requestElapsedDays");var Pp=7;function js(e,t){return e.wireStatus!=="awaiting_response"?false:yi(e,t)>=Pp}i(js,"requestWaitingTooLong");function fi(e){return e.status==="failed"}i(fi,"isTerminalFailure");function $s(e){return fi(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i($s,"shouldOfferRecovery");function Ys(e,t){let[r,o]=useState(""),[n,l]=useState(""),[s,c]=useState([]),[a,d]=useState(null),[u,p]=useState([]),[g,h]=useState(true),[R,v]=useState(false),[x,y]=useState(false),[f,E]=useState(null),[b,C]=useState(null),[D,S]=useState(0),k=useRef(0),I=useRef(true),G=t?.latitude,z=t?.longitude,Y=useMemo(()=>G!==void 0&&z!==void 0?{latitude:G,longitude:z}:void 0,[G,z]);useEffect(()=>(I.current=true,()=>{I.current=false,k.current+=1;}),[e]),useEffect(()=>{let U=true;return h(true),e.recentClinics({limit:5}).then(w=>{U&&(w.ok&&p(w.value.clinics),h(false));}).catch(()=>{U&&h(false);}),()=>{U=false;}},[e]),useEffect(()=>{let U=r.trim();if(U.length<ui){l("");return}let w=setTimeout(()=>l(U),Bs);return ()=>clearTimeout(w)},[r]);let H=n.length>=ui;useEffect(()=>{let U=k.current+=1;if(c([]),d(null),E(null),C(null),!H){v(false);return}v(true),e.searchClinics({query:n,limit:25,...Y?{location:Y}:{}}).then(w=>{!I.current||U!==k.current||(w.ok?(c(w.value.clinics),d(w.value.nextCursor)):E(w.error),v(false));}).catch(()=>{I.current&&U===k.current&&v(false);});},[e,n,H,Y,D]);let Z=useCallback(()=>{if(!H||a===null||x)return;let U=k.current;y(true),C(null),e.searchClinics({query:n,limit:25,cursor:a,...Y?{location:Y}:{}}).then(w=>{!I.current||U!==k.current||(w.ok?(c(T=>[...T,...w.value.clinics]),d(w.value.nextCursor)):C(w.error),y(false));}).catch(()=>{I.current&&U===k.current&&y(false);});},[e,a,n,H,x,Y]),oe=useCallback(U=>o(U),[]),Ee=useCallback(()=>S(U=>U+1),[]);return useMemo(()=>({query:r,debouncedQuery:n,isSearchActive:H,clinics:s,recent:u,recentLoading:g,initialLoading:R,loadingMore:x,hasNextPage:a!==null,error:f,pageError:b,setQuery:oe,loadMore:Z,retry:Ee}),[r,n,H,s,u,g,R,x,a,f,b,oe,Z,Ee])}i(Ys,"useClinicPicker");function bi(e,t,r,o){return Object.freeze({key:e?.id??`free:${t??""}`,clinic:e,freeText:t,email:r,idempotencyKey:o})}i(bi,"clinicDraftFor");var Br=10,Zn=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),cn=i((e,t=1)=>z.string().refine(r=>!gr(r)&&[...r].length>=t&&[...r].length<=e),"text"),Qs=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),Ip=z.object({clinicId:Zn.optional(),clinicFreeText:cn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:cn(320,3).refine(e=>!Qs(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Zn.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)),Dp=z.object({petRef:cn(128),ownerName:cn(200).refine(e=>e.trim().length>0&&!Qs(e)),authorizationVersion:cn(64),clinics:z.array(Ip).min(1).max(Br)}).strict(),Ap=z.object({request_group_id:Zn,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:Zn.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 Xs(e){let t=e.funnel??fr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!Dp.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=Ap.safeParse(o.value);if(!n.success||n.data.pet_ref!==r.petRef)return Ks();let l=[];for(let s of n.data.results){let c=s.request===void 0||s.request===null?null:ur(s.request);if(s.created!==(c!==null))return Ks();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(Xs,"createRecordsClinicBatchClient");function Ks(){return B(q("internalError",{retryable:false}))}i(Ks,"malformed");var Js=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Op=z.object({clinics:z.array(z.object({clinic_id:Js,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()}),Lp=z.object({authorization_version:z.string().min(1),scope_template:z.string().min(1),authorization_template:z.string().min(1)}),Vp=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 Zs(e){let{repository:t}=e,r=i(async n=>{let l=await n;if(!l.ok)return l;let s=ur(l.value);return s===null?_r():_e(s)},"request"),o=i(async n=>{let l=await n;if(!l.ok)return l;let s=Op.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})):_r()},"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=ns(l.value);return s===null?_r():_e(s)},async getAuthorizationCopy(){let n=await t.getAuthorizationCopy();if(!n.ok)return n;let l=Lp.safeParse(n.value);return l.success?_e(Object.freeze({authorizationVersion:l.data.authorization_version,scopeTemplate:l.data.scope_template,authorizationTemplate:l.data.authorization_template})):_r()},async createClinicRequest(n){let l=await r(t.createClinicRequest(n));return l.ok&&l.value.petRef!==n.petRef?_r():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=Vp.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)})):_r()},async completeSignatureUpload(n){let l=await t.completeSignatureUpload(n);if(!l.ok)return l;let s=z.object({signature_id:Js}).safeParse(l.value);return s.success?_e(s.data.signature_id):_r()}}}i(Zs,"createRecordsClinicController");function _r(){return B(q("internalError",{retryable:false}))}i(_r,"malformed");var br="/widget/v1/records",el=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Rr=i((e,t=1)=>z.string().refine(r=>!gr(r)&&[...r].length>=t&&[...r].length<=e),"text"),rl=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),nl=Rr(320,3).refine(e=>!rl(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),tl=Rr(64),qp=z.object({limit:z.number().int().min(1).max(25).optional()}).strict(),zp=z.object({query:Rr(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:Rr(512,0).optional()}).strict(),Fp=z.object({petRef:Rr(128),ownerName:Rr(200).refine(e=>e.trim().length>0&&!rl(e)),authorizationVersion:Rr(64),clinicId:el.optional(),clinicFreeText:Rr(200).refine(e=>e.trim().length>0).optional(),clinicEmail:nl.optional(),signatureId:el.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 ol(e){let t=e.funnel??fr({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)=>tl.safeParse(n).success?r(l,{method:"POST",path:`${br}/requests/${encodeURIComponent(n)}/${l}`,...s?{body:s}:{}}):hr(),"recover");return {searchClinics(n){return zp.safeParse(n).success?r("search",{method:"GET",path:`${br}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):hr()},recentClinics(n){return qp.safeParse(n).success?r("recent",{method:"GET",path:`${br}/clinics/recent`,query:{limit:n.limit}}):hr()},getRequestGroup(n){return tl.safeParse(n).success?r("requestGroup",{method:"GET",path:`${br}/request-groups/${encodeURIComponent(n)}`}):hr()},getAuthorizationCopy:i(()=>r("authorizationCopy",{method:"GET",path:`${br}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return Fp.safeParse(n).success?r("create",{method:"POST",path:`${br}/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):hr()},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 nl.safeParse(l).success?o(n,"clinic-email",{clinic_email:l}):hr()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?hr():r("signatureInitiate",{method:"POST",path:`${br}/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:`${br}/signatures/complete`,body:{upload_id:n}}):hr()}}}i(ol,"createHttpRecordsClinicRepository");function hr(){return Promise.resolve(B(q("validationFailed",{retryable:false})))}i(hr,"invalid");function Mt(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=useMemo(()=>{let{services:l}=e.registry;return Zs({repository:ol({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(Mt,"useEverfurRecordsClinic");function hi(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=useMemo(()=>{let{services:l}=e.registry;return Xs({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(hi,"useEverfurRecordsClinicBatch");var xi=class xi 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(xi,"HostRenderBoundary");var Ri=xi;function Mp({render:e}){return e()}i(Mp,"RenderHost");function vi({render:e,fallback:t,resetKey:r}){return createElement(Ri,{fallback:t,resetKey:r,children:createElement(Mp,{render:e})})}i(vi,"HostRender");var Bp=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 Hp(e){return Bp[e]}i(Hp,"requires");function ll(e,t,r){let o=Hp(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 wi({name:e,enabled:false,isPending:true,limits:{}});let l=Up(o,n);return o.filter(c=>n.get(c)?.granted!==true).length===0?wi({name:e,enabled:true,isPending:false,limits:l}):wi({name:e,enabled:false,isPending:false,limits:l,disabled:jp(o,n)})}i(ll,"decideCapability");function Up(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(Up,"mergeLimits");function jp(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:Ho("accessDenied"),level:"user_entitlement",recoverable:false})}i(jp,"disabledFor");function wi(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(wi,"freezeDecision");function Ci(e){let{runtime:t}=ke(),r=t.entitlements,o=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>ll(e,o.decisions,{isPending:o.isPending}),[e,o])}i(Ci,"useCapability");var Gp=48;function Yp(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Yp,"selectView");function Ne(e){let{capability:t,children:r,renderDisabled:o,renderPending:n,style:l}=e,s=Ci(t),c=useMemo(()=>Yp(s),[s]);switch(c){case "enabled":return r;case "pending":return n?jsx(vi,{render:n,fallback:jsx(dl,{capability:t,style:l})}):jsx(dl,{capability:t,style:l});case "disabled":return o?jsx(vi,{render:()=>o(s),fallback:jsx(ul,{decision:s,style:l}),resetKey:s}):jsx(ul,{decision:s,style:l});default:return yr(c)}}i(Ne,"CapabilityGate");function dl({capability:e,style:t}){let r=V(),o=useMemo(()=>pl(r),[r]);return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:o.skeletonBar})})}i(dl,"PendingSkeleton");function ul({decision:e,style:t}){let r=V(),o=useMemo(()=>pl(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(ul,"OffState");function pl(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({offstate:{minHeight:Gp,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(pl,"makeStyles");var dn=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=V(),r=useMemo(()=>Xp(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${dn.title}. ${dn.body}`,children:[jsx(m,{style:r.title,children:dn.title}),jsx(m,{style:r.body,children:dn.body})]})}i(Me,"ClinicalDisclaimer");function Xp(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(Xp,"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 fl=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"})}),ki=60;function gl(e){return `Try again in ${e}s`}i(gl,"coolingActionLabel");var bl="Try again, available shortly";function Qe({variant:e,onAction:t,message:r,testID:o}){let n=rm(),l=fl[e],[s,c]=useState(e==="rate_limited"?ki:0);useEffect(()=>{e==="rate_limited"&&c(ki);},[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?gl(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?bl: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 rm(){let e=V();return useMemo(()=>nm(e),[e])}i(rm,"useStyles");function nm(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(nm,"makeStyles");var Ze="Back";function et({title:e,onBack:t,right:r,testID:o,variant:n="brand"}){let l=pn();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 xl(){let e=pn();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(xl,"ListGlyph");function wl(){let e=pn();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(wl,"ShareGlyph");function Cl(){let e=pn();return jsxs(View,{style:e.sendGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.sendBody}),jsx(View,{style:e.sendFold})]})}i(Cl,"SendGlyph");function El(){let e=pn();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(El,"DownloadGlyph");function pn(){let e=V();return useMemo(()=>lm(e),[e])}i(pn,"useStyles");function lm(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(lm,"makeStyles");var um=120,pm=44;function mm({reason:e,onExit:t,exitLabel:r,style:o}){let{color:n,space:l,radius:s,type:c}=V();return jsxs(View,{testID:"records-gate-off",style:[{minHeight:um,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:pm,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(mm,"RecordsGateOffState");function Be(e,t){return e===void 0?{}:{renderDisabled:i(r=>jsx(mm,{reason:r.disabled?.reason??"",onExit:e,exitLabel:t}),"renderDisabled")}}i(Be,"recordsGateExit");var fm="your pet";function He(e){let t=e?.trim()??"";return t.length>0?t:fm}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")}),Bt=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")}),Ti=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")}),ir=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"}),Hr=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"}),Pr=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 ro="rgba(0,0,0,0.4)";function be(){let e=V();return useMemo(()=>Rm(e),[e])}i(be,"useScreenStyles");function vr({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(vr,"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=V(),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 Ht({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(Ht,"Chip");function Pt({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(Pt,"SectionHeader");function Ir({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(Ir,"Chevron");function Rm(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c}=n,a=i((v,x)=>Math.round(v*x),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl+r.md,p=i((v,x,y,f="regular")=>({..._(e,f),fontSize:v,lineHeight:a(v,x),color:y}),"text"),g=ot(l.recordCard),h=e.brightness==="dark"?t.errorRed:t.danger,R=i((v,x)=>({bg:{backgroundColor:v},fg:{color:x}}),"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"),...g},rowDetail:{...p(s.caption,c.normal,t.text.secondary),marginTop:r.xs/2,...g},rowValue:{...p(s.body+1,c.snug,t.text.primary,"bold"),marginTop:r.xs/2,...g},rowMuted:{...p(s.caption,c.normal,t.text.muted),...g},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(Rm,"makeScreenStyles");function Ur(e,t){return e===null?"":t?`${e} ${t}`:e}i(Ur,"formatEntityValue");var kl=["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=kl[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 `${kl[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 Xt(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(Xt,"markerStatusLabel");function jr(e,t){return t<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${t} visits`}i(jr,"trajectoryLabel");function ar(e){let t=e.replace(/_/g," ").trim();return t.length===0?e:t.charAt(0).toUpperCase()+t.slice(1)}i(ar,"humanize");var Tl=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 Dr(e){return Object.prototype.hasOwnProperty.call(Tl,e)?Tl[e]:ar(e)}i(Dr,"bodySystemLabel");var _l=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 $r(e){return Object.prototype.hasOwnProperty.call(_l,e)?_l[e]:ar(e)}i($r,"soapSectionLabel");function Pl(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(Pl,"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 Pi(e,t,r){let o=jr(t,r);return e?`${fe.measured(Q(e))}${o?` \xB7 ${o}`:""}`:o}i(Pi,"labDetailLine");var ue=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 vm(e,t){if(!e)return false;let r=Date.parse(e);return Number.isNaN(r)?false:r<=t}i(vm,"isShareExpired");function xm(e,t){let r=Q(e);return r==="-"?t?"Expired":"No expiry date":t?`Expired ${r}`:`Expires ${r}`}i(xm,"formatShareExpiry");function Il(e,t,r){let o=e.map(n=>{let l=vm(n.expiresAt,r),s=xm(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(Il,"buildShareRows");function no(e,t){let r=e?.httpStatus;if(rr(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(no,"shareErrorMessage");function ve({width:e,height:t,radius:r,style:o}){let{color:n,radius:l}=V();return jsx(View,{style:[{width:e,height:t,borderRadius:r??l.xs,backgroundColor:n.skeleton},o],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(ve,"SkeletonBlock");var Ii=180,Al=70,oo=22,Cm=300,Ol=44,io=24,Di=34,Em=6,Sm=5;function ao({testID:e}){let t=fn(),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:Ii,height:Ii,radius:Ii/2}),jsxs(View,{style:t.badges,children:[jsx(ve,{width:Al,height:oo,radius:oo/2}),jsx(ve,{width:Al,height:oo,radius:oo/2})]})]})}),jsx(ve,{width:150,height:16,radius:8,style:t.inset}),jsx(View,{style:t.carouselCard,children:jsx(ve,{width:"100%",height:Cm,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:Ol,radius:12})}),jsxs(View,{style:[t.inset,t.actions],children:[r("a"),r("b")]})]})}i(ao,"DashboardSkeleton");function Ll({testID:e}){let t=fn();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:io,height:io,radius:io/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(Ll,"RequestSkeleton");function Vl({testID:e}){let t=fn();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:Ol,radius:12})}),Array.from({length:Em},(r,o)=>jsxs(View,{children:[o>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,children:[jsx(ve,{width:Di,height:Di,radius:Di/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(Vl,"TimelineSkeleton");function ql({testID:e}){let t=fn();return jsx(View,{style:t.clinics,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:xe.loading,testID:e,children:Array.from({length:Sm},(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(ql,"ClinicsSkeleton");function zl({testID:e}){let t=fn();return jsx(View,{style:t.shares,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:ue.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(zl,"SharesSkeleton");var Ai=62;function fn(){let e=V();return useMemo(()=>km(e),[e])}i(fn,"useStyles");function km(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:io},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:Ai},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(km,"makeStyles");var Am=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Oi(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:de.sessionRequired}):jsx(Om,{...ze(e,["onNavigate","onBack"])},JSON.stringify([t,r,e.petRef]))})}i(Oi,"EverfurClinicPicker");function Om({petRef:e,controller:t,recordsController:r,location:o,onNavigate:n,onBack:l,style:s}){let c=be(),a=Vm(),d=V(),u=Mt(),p=Ys(t??u,o),g=yt(r?{petRef:e,controller:r}:{petRef:e}),h=useRef(nr()),[R,v]=useState(false),[x,y]=useState(null),[f,E]=useState(false),[b,C]=useState(""),[D,S]=useState(false),[k,I]=useState(""),[G,z]=useState(false),Y=useCallback(O=>{n?.({name:"consent",clinic:bi(O,null,"",h.current())});},[n]),H=i(()=>{R||(v(true),y(null),g.createRequest(`records-upload-${Date.now().toString(36)}`).then(O=>{if(v(false),!O.ok){y(ge.errors.start);return}n?.({name:"request",requestId:O.value.id});}));},"startUpload"),Z=D?b:p.query,oe=Am.test(k.trim()),Ee=Z.trim().length>0&&oe,U=i(O=>{let{layoutMeasurement:M,contentOffset:X,contentSize:ye}=O.nativeEvent;M.height+X.y>=ye.height-M.height*.6&&p.loadMore();},"onEndReached"),w=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:[x?jsx(View,{style:c.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:c.errorText,children:x})}):null,jsx(re,{label:R?xe.uploadOwnStarting:xe.uploadOwn,kind:"outline",accessibilityLabel:xe.uploadOwnA11y,busy:R,onPress:H,testID:"records-clinic-upload-own"})]}):null,jsxs(ScrollView,{contentContainerStyle:a.list,keyboardShouldPersistTaps:"handled",onScroll:p.isSearchActive?U: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:()=>E(O=>!O),accessibilityRole:"button",accessibilityLabel:f?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(Ir,{direction:f?"up":"down"})]}),f?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:O=>{C(O),S(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:k,onChangeText:O=>{I(O),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"}),G&&k.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:bi(null,Z.trim(),k.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(ql,{testID:"records-clinic-page-loading"}):null,w.map(O=>jsx(Lm,{clinic:O,onSelect:Y,styles:a},O.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(Om,"PickerBody");function Lm({clinic:e,onSelect:t,styles:r}){let o=Fs(e.emailStatus),n=Ns(e.distanceKm),l=[e.name,e.address,e.phone?`phone ${e.phone}`:null,n?Ms(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(Lm,"ClinicRow");function Vm(){let e=V();return useMemo(()=>qm(e),[e])}i(Vm,"useLocalStyles");function qm(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(qm,"makeLocalStyles");var Oe=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${Br} 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 gn(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(gn,"renderClinicScope");function bn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(bn,"clinicNeedsEmail");function Nl(e,t,r){let[o,n]=useState(e.ownerName),[l,s]=useState(""),[c,a]=useState(null),[d,u]=useState(""),[p,g]=useState([]),[h,R]=useState([]),[v,x]=useState(null),[y,f]=useState(null),[E,b]=useState(false),[C,D]=useState(false),[S,k]=useState(null),[I,G]=useState(0),z=useRef(false),Y=useRef(false),H=useRef(0),Z=useRef(nr()),oe=useRef(null),Ee=useRef(null),U=useRef(0);useEffect(()=>(z.current=true,Y.current=false,b(false),()=>{z.current=false,U.current+=1,H.current+=1,oe.current=null,Ee.current?.abort();}),[t]),useEffect(()=>{let ie=true;return x(null),oe.current=null,t.getAuthorizationCopy().then(we=>{ie&&(we.ok?(x(we.value),f(null)):f(we.error));}).catch(()=>{ie&&f(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 w=i(()=>{oe.current=null,f(null);},"invalidate"),T=c?.name??l.trim(),O=v?gn(v,o.trim(),e.petName,T):null,M=bn(c),X=!!(v&&O&&o.trim()&&e.petName.trim()&&T&&(!M||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.trim()))&&r),ye=i(async()=>{if(Y.current)return;let ie=++H.current;D(true);try{let we=await t.searchClinics({query:l.trim(),limit:100});if(!z.current||ie!==H.current)return;we.ok?(g(we.value.clinics),f(null)):f(we.error);}catch{z.current&&ie===H.current&&f(q("internalError"));}finally{z.current&&ie===H.current&&D(false);}},"search"),Ve=i(async()=>{if(Y.current||S||!X||!v||!O||!r)return;Y.current=true;let ie=U.current,we=i(()=>z.current&&U.current===ie,"current");b(true),f(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:O,signal:Ee.current.signal});if(!we()||Xe===null)return;let qt=c&&(!M||c.emailStatus==="none")?{clinicId:c.id}:{clinicFreeText:T};oe.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:v.authorizationVersion,...qt,...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){f(vt.error);return}if(vt.value.petRef!==e.petRef){f(q("internalError"));return}k(vt.value),oe.current=null,e.onCreated?.(vt.value);}catch{we()&&f(q("internalError"));}finally{Y.current=false,we()&&b(false);}},"submit");return {ownerName:o,query:l,clinic:c,email:d,clinics:p,copy:v,scope:O,error:y,busy:E,searching:C,created:S,ready:X,needsEmail:M,recent:p.length===0&&c===null?h:[],setOwnerName(ie){Y.current||(w(),n(ie));},setQuery(ie){Y.current||(w(),H.current+=1,D(false),g([]),a(null),u(""),s(ie));},setEmail(ie){Y.current||(w(),u(ie));},selectClinic(ie){Y.current||(w(),H.current+=1,D(false),g([]),a(ie),s(ie.name),u(""));},invalidate:w,search:ye,submit:Ve,retryCopy(){f(null),G(ie=>ie+1);}}}i(Nl,"useClinicRequestForm");var zm=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Rn(e){return e.clinic?.name??e.freeText??""}i(Rn,"draftName");function hn(e){return bn(e.clinic)}i(hn,"draftNeedsEmail");function Ml(e,t,r,o,n){let[l,s]=useState(e.ownerName),[c,a]=useState(""),[d,u]=useState([]),[p,g]=useState([]),[h,R]=useState([]),[v,x]=useState(null),[y,f]=useState(null),[E,b]=useState(false),[C,D]=useState(false),[S,k]=useState(null),[I,G]=useState(null),[z,Y]=useState(0),H=useRef(false),Z=useRef(false),oe=useRef(0),Ee=useRef(0),U=useRef(nr()),w=useRef(null),T=useRef(null);useEffect(()=>(H.current=true,Z.current=false,b(false),()=>{H.current=false,Ee.current+=1,oe.current+=1,w.current=null,T.current?.abort();}),[t,r]),useEffect(()=>{let F=true;return x(null),w.current=null,t.getAuthorizationCopy().then(Re=>{F&&(Re.ok?(x(Re.value),f(null)):f(Re.error));}).catch(()=>{F&&f(q("internalError"));}),()=>{F=false;}},[t,z]),useEffect(()=>{let F=true;return g([]),t.recentClinics({limit:5}).then(Re=>{F&&Re.ok&&g(Re.value.clinics);}).catch(()=>{}),()=>{F=false;}},[t]);let O=i(()=>{w.current=null,f(null);},"invalidate"),M=h.map(Rn),X=v?M.map(F=>gn(v,l.trim(),e.petName,F)):[],ye=X.every(F=>F!==null)?X.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, scopeEpoch } = 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, scopeEpoch]);
|
|
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=>!hn(F)||zm.test(F.email.trim())),ie=h.length>=Br,we=!!(v&&ye&&l.trim()&&e.petName.trim()&&Ve&&o)&&S===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(!H.current||F!==oe.current)return;Re.ok?(u(Re.value.clinics),f(null)):f(Re.error);}catch{H.current&&F===oe.current&&f(q("internalError"));}finally{H.current&&F===oe.current&&D(false);}},"search"),Xe=i(F=>{Z.current||ie||S!==null||F.clinic!==null&&h.some(Re=>Re.clinic?.id===F.clinic?.id)||(O(),R(Re=>[...Re,{...F,key:U.current(),idempotencyKey:U.current()}]),u([]),a(""));},"add"),qt=i(async()=>{if(Z.current||S!==null||!we||!v||!ye||!o)return;Z.current=true;let F=Ee.current,Re=i(()=>H.current&&Ee.current===F,"current");b(true),f(null);try{if(w.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(w.current=xt,xt.signaturePngBase64!==void 0&&n!==void 0){let Hd=await n(xt.signaturePngBase64,T.current.signal);if(!Re())return;w.current={signatureId:Hd.signatureId};}}let Ft=w.current,en=h.map(xt=>({...xt.clinic!==null&&(!hn(xt)||xt.clinic.emailStatus==="none")?{clinicId:xt.clinic.id}:{clinicFreeText:Rn(xt)},...hn(xt)?{clinicEmail:xt.email.trim().toLowerCase()}:{},...Ft.signatureId!==void 0?{signatureId:Ft.signatureId}:{signaturePngBase64:Ft.signaturePngBase64},idempotencyKey:xt.idempotencyKey})),tn=await r.createClinicRequestBatch({petRef:e.petRef,ownerName:l.trim(),authorizationVersion:v.authorizationVersion,clinics:en});if(!Re())return;if(!tn.ok){f(tn.error);return}k(tn.value),e.onCreated?.(tn.value),zt(tn.value.requestGroupId,F);}catch{Re()&&f(q("internalError"));}finally{Z.current=false,Re()&&b(false);}},"submit"),zt=i(async(F,Re)=>{try{let Ft=await t.getRequestGroup(F);if(!H.current||Ee.current!==Re)return;Ft.ok&&Ft.value.petRef===e.petRef&&G(Ft.value);}catch{}},"loadGroup"),Se=i(async()=>{S===null||Z.current||await zt(S.requestGroupId,Ee.current);},"refreshGroup");return {ownerName:l,query:c,clinics:d,copy:v,scopeText:ye,error:y,busy:E,searching:C,drafts:h,outcome:S,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||(O(),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||(O(),R(Ft=>Ft.map(en=>en.key===F?{...en,email:Re}:en)));},removeDraft(F){Z.current||S!==null||(O(),R(Re=>Re.filter(Ft=>Ft.key!==F)));},submit:qt,refreshGroup:Se,retryCopy(){f(null),Y(F=>F+1);}}}i(Ml,"useClinicBatchForm");function Bl(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(Bl,"trustedSignatureUploadUrl");var Fm="Signature upload failed",Nm=3e4;function Mm(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-t}i(Mm,"base64ByteLength");async function qi(e,t,r,o){let n=i(()=>new Error(Fm),"fail"),l=Mm(e);if(l<=0||r.aborted)throw n();let s=await t.initiateSignatureUpload(l);if(!s.ok||r.aborted||!Bl(s.value.uploadUrl))throw n();let c=new FormData;for(let[g,h]of Object.entries(s.value.uploadFields))c.append(g,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,Nm);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(qi,"registerRnSignature");var Wr=Object.freeze({width:360,height:120});function $l(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i($l,"blank");function Wl(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(Wl,"stamp");var Bm=16384;function Hm(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(Hm,"padPoint");function Um(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,g=s<a?1:-1,h=d+u,R=0;for(;R<n&&(Wl(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+=g);}return R}i(Um,"line");function Gl(e,t=1){let r=$l(Wr.width,Wr.height);for(let o of e){let n=[];for(let s of o){let c=Hm(s,r);c!==null&&n.push(c);}if(n.length===0)continue;if(n.length===1){let[s,c]=n[0];Wl(r,s,c,t);continue}let l=Bm;for(let s=1;s<n.length&&l>0;s+=1)l-=Um(r,n[s-1],n[s],t,l);}return r}i(Gl,"rasterizeStrokes");var jm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",$m="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",Wm="0123456789abcdefghijklmnopqrstuv",Hi=5,Ui=7,zi=Hi+1;function Gm(e,t){let r=jm.indexOf(e);return r<0?0:Wm.indexOf($m.charAt(r*Ui+t))}i(Gm,"glyphRow");function Yl(e){let t=$l(Wr.width,Wr.height),r=e.trim();if(r.length===0)return t;let o=[...r],n=4;for(;n>1&&(o.length*zi-1)*n>t.width-8;)n-=1;let l=(o.length*zi-1)*n,s=Math.max(0,Math.floor((t.width-l)/2)),c=Math.floor((t.height-Ui*n)/2);return o.forEach((a,d)=>{let u=s+d*zi*n;for(let p=0;p<Ui;p+=1){let g=Gm(a,p);for(let h=0;h<Hi;h+=1)if((g>>Hi-1-h&1)!==0)for(let R=0;R<n;R+=1)for(let v=0;v<n;v+=1){let x=u+h*n+v,y=c+p*n+R;x<t.width&&y<t.height&&(t.pixels[y*t.width+x]=1);}}}),t}i(Yl,"rasterizeTypedName");var Gi=class Gi{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(Gi,"BitWriter");var ji=Gi;function $i(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($i,"writeLiteral");var Fi=[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],Hl=[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],Ni=[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],Ul=[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 Ym(e,t,r){let o=Fi.length-1;for(;Fi[o]>t;)o-=1;$i(e,257+o),Hl[o]>0&&e.writeBits(t-Fi[o],Hl[o]);let n=Ni.length-1;for(;Ni[n]>r;)n-=1;e.writeCode(n,5),Ul[n]>0&&e.writeBits(r-Ni[n],Ul[n]);}i(Ym,"writeMatch");var Km=32768,Mi=3,Qm=258,jl=15,Xm=64;function Jm(e){let t=new ji;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<jl).fill(-1),o=new Int32Array(e.length).fill(-1),n=i(c=>(e[c]<<10^e[c+1]<<5^e[c+2])&(1<<jl)-1,"hashAt"),l=i(c=>{if(c+Mi>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+Mi<=e.length){let d=r[n(s)],u=0,p=Math.min(Qm,e.length-s);for(;d>=0&&u<Xm&&s-d<=Km;){let g=0;for(;g<p&&e[d+g]===e[s+g];)g+=1;if(g>c&&(c=g,a=s-d,g===p))break;d=o[d],u+=1;}}if(c>=Mi){Ym(t,c,a);for(let d=0;d<c;d+=1)l(s+d);s+=c;}else $i(t,e[s]),l(s),s+=1;}return $i(t,256),t.finish()}i(Jm,"deflate");function Zm(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(Zm,"adler32");var lo=null;function ey(e){if(lo===null){lo=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;lo[r]=o>>>0;}}let t=4294967295;for(let r of e)t=lo[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(ey,"crc32");function vn(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(vn,"u32");function Bi(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),[...vn(t.length),...o,...vn(ey(o))]}i(Bi,"chunk");var co="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function ty(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+=co.charAt(s>>18&63)+co.charAt(s>>12&63),t+=r+1<e.length?co.charAt(s>>6&63):"=",t+=r+2<e.length?co.charAt(s&63):"=";}return t}i(ty,"toBase64");function Wi(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 g=0;g<t;g+=1)if(o[u*t+g]===1){let h=p+1+(g>>3);l[h]=l[h]&~(128>>(g&7));}}let s=Jm(l),c=new Uint8Array(2+s.length+4);c[0]=120,c[1]=1,c.set(s,2),c.set(vn(Zm(l)),2+s.length);let a=Uint8Array.from([...vn(t),...vn(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...Bi("IHDR",a),...Bi("IDAT",c),...Bi("IEND",new Uint8Array(0))]);return ty(d)}i(Wi,"encodeSignaturePng");var iy=8,Xl=2,xn=3;function Vr({onChange:e,disabled:t=false}){let r=ay(),[o,n]=useState("draw"),[l,s]=useState(""),[c,a]=useState([]),[d,u]=useState(0),p=useRef([]),g=useRef(null),h=d>0?Wr.width/d:1,R=useRef(h);R.current=h;let v=useRef(t);v.current=t,useEffect(()=>{if(o==="type"){$n(e,l.trim().length>0?Wi(Yl(l)):null);return}let C=c.reduce((D,S)=>D+S.length,0);$n(e,C>=iy?Wi(Gl(c)):null);},[o,l,c,e]);let x=i(C=>{let{locationX:D,locationY:S}=C.nativeEvent;return [D*R.current,S*R.current]},"point"),y=useMemo(()=>PanResponder.create({onStartShouldSetPanResponder:i(()=>!v.current,"onStartShouldSetPanResponder"),onMoveShouldSetPanResponder:i(()=>!v.current,"onMoveShouldSetPanResponder"),onPanResponderTerminationRequest:i(()=>false,"onPanResponderTerminationRequest"),onPanResponderGrant:i(C=>{p.current=[x(C)];},"onPanResponderGrant"),onPanResponderMove:i(C=>{let D=x(C),S=p.current[p.current.length-1];S!==void 0&&Math.abs(S[0]-D[0])<Xl&&Math.abs(S[1]-D[1])<Xl||(p.current=[...p.current,D],a(k=>[...k.filter(I=>I!==g.current),g.current=p.current]));},"onPanResponderMove"),onPanResponderRelease:i(()=>{let C=p.current;p.current=[],a(D=>[...D.filter(S=>S!==g.current),C]),g.current=null;},"onPanResponderRelease"),onPanResponderTerminate:i(()=>{let C=p.current;p.current=[],a(D=>[...D.filter(S=>S!==g.current),C]),g.current=null;},"onPanResponderTerminate")}),[]),f=useCallback(()=>{v.current||(p.current=[],g.current=null,a([]),s(""));},[]),E=useCallback(()=>{f(),n(C=>C==="draw"?"type":"draw");},[f]),b=i(C=>u(C.nativeEvent.layout.width),"onLayout");return jsxs(View,{style:r.container,testID:"records-signature-pad",children:[jsx(m,{style:r.label,children:o==="draw"?$.draw:$.type}),o==="type"?jsx(qe,{accessibilityLabel:$.type,style:r.input,value:l,maxLength:100,editable:!t,autoComplete:"off",autoCorrect:false,onChangeText:C=>{v.current||s(C);}}):null,jsx(View,{onLayout:b,style:[r.canvas,{height:d>0?d/3:120}],accessible:true,accessibilityLabel:$.sign,accessibilityRole:"image",testID:"records-signature-canvas",...o==="draw"?y.panHandlers:{},children:o==="type"?jsx(m,{style:r.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:l.trim()}):c.map((C,D)=>C.map(([S,k],I)=>jsx(View,{pointerEvents:"none",style:[r.dot,{left:S/h-xn/2,top:k/h-xn/2}]},`${D}-${I}`)))}),jsxs(View,{style:r.actions,children:[jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:$.clear,accessibilityState:{disabled:t},disabled:t,onPress:f,style:r.button,children:jsx(m,{style:r.buttonLabel,children:$.clear})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:o==="draw"?$.toType:$.toDraw,accessibilityState:{disabled:t},disabled:t,onPress:E,style:r.button,children:jsx(m,{style:r.buttonLabel,children:o==="draw"?$.toType:$.toDraw})})]})]})}i(Vr,"SignaturePad");function ay(){let e=V();return useMemo(()=>sy(e),[e])}i(ay,"useStyles");function sy(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:xn,height:xn,borderRadius:xn/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(sy,"makeStyles");function Ki(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",...Be(e.onClose,$.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:de.sessionRequired}):jsx(dy,{...ze(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(Ki,"EverfurClinicRequestBatch");function dy(e){let t=Mt(),r=hi(),o=e.controller??t,[n,l]=useState(null),s=useCallback(async()=>n===null?null:{signaturePngBase64:n},[n]),c=useCallback((x,y)=>qi(x,o,y),[o]),a=Ml(e,o,e.batchClient??r,e.onCaptureSignature??s,e.onCaptureSignature?void 0:c),d=e.onCaptureSignature!==void 0||n!==null,u=V(),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},g={color:u.color.text.primary,fontSize:u.type.size.body},h={color:u.color.text.muted,fontSize:u.type.size.bodyTight},R=i((x,y,f=false,E=x)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:E,accessibilityState:{disabled:f},disabled:f,onPress:y,style:[p,{justifyContent:"center",opacity:f?.5:1}],children:jsx(m,{style:g,children:x})}),"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:[g,{..._(u,"bold"),fontSize:u.type.size.heading}],children:a.outcome?Oe.resultTitle:Oe.title}),jsx(m,{style:g,children:e.petName}),a.outcome?jsxs(View,{style:{gap:u.space.sm},testID:"records-batch-result",children:[jsx(m,{accessibilityRole:"summary",accessibilityLiveRegion:"polite",style:g,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:g,children:Oe.perClinic}),a.outcome.results.map((x,y)=>{let f=x.request?.clinicName??a.drafts[y]?.clinic?.name??x.clinicFreeText??"",E=x.created?Oe.sent:Oe.notSent;return jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:[`${f}. ${E}.`,x.created?x.request?.statusLabel:x.failureReason].filter(Boolean).join(" "),testID:`records-batch-row-${x.created?"created":"failed"}`,children:[jsx(m,{style:g,children:f}),jsx(m,{style:h,children:E}),x.created&&x.request?.statusLabel?jsx(m,{style:h,children:x.request.statusLabel}):null,!x.created&&x.failureReason?jsx(m,{style:h,children:x.failureReason}):null]},x.idempotencyKey)}),a.group?jsx(m,{accessibilityLiveRegion:"polite",style:g,children:Oe.responded(a.group.responded,a.group.total)}):null,a.group?.members.map(x=>x.statusLabel?jsx(m,{style:h,children:[x.clinicName,x.statusLabel].filter(Boolean).join(": ")},x.id):null)]}):jsxs(Fragment,{children:[jsx(m,{style:g,children:$.ownerName}),jsx(qe,{accessibilityLabel:$.ownerName,style:p,value:a.ownerName,maxLength:200,editable:!a.busy,autoComplete:"name",onChangeText:a.setOwnerName}),a.drafts.map(x=>jsxs(View,{style:{gap:u.space.xs},testID:`records-batch-draft-${x.key}`,children:[jsx(m,{style:g,children:Rn(x)}),hn(x)?jsxs(Fragment,{children:[jsx(m,{style:h,children:x.email.trim()?x.email:Oe.emailToAdd}),jsx(qe,{accessibilityLabel:$.email,style:p,value:x.email,placeholder:$.emailPlaceholder,placeholderTextColor:u.color.text.placeholder,maxLength:320,editable:!a.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:y=>a.setDraftEmail(x.key,y)})]}):null,R(Oe.remove(Rn(x)),()=>a.removeDraft(x.key),a.busy)]},x.key)),jsx(m,{style:g,children:a.atCap?Oe.atCap:Oe.addClinic}),!a.atCap&&jsxs(Fragment,{children:[jsx(qe,{accessibilityLabel:$.clinic,style:p,value:a.query,placeholder:$.placeholder,placeholderTextColor:u.color.text.placeholder,maxLength:200,editable:!a.busy,onChangeText:a.setQuery}),R($.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:g,children:de.loading}),a.recent.length>0&&jsx(m,{accessibilityRole:"header",style:g,children:$.recentlyUsed}),a.recent.map(x=>jsx(View,{children:R([x.name,x.address,x.phone].filter(Boolean).join(", "),()=>a.addClinic(x),a.busy)},`recent-${x.id}`)),a.clinics.map(x=>jsx(View,{children:R([x.name,x.address,x.phone].filter(Boolean).join(", "),()=>a.addClinic(x),a.busy)},x.id))]}),jsx(m,{accessibilityRole:"header",style:g,children:$.scopeHeading}),a.copy?jsx(m,{style:g,children:a.drafts.length>0&&a.ownerName.trim()?a.scopeText??q("internalError").displayMessage:de.consentRequired}):!a.error&&jsx(m,{accessibilityLiveRegion:"polite",style:g,children:de.loading}),!e.onCaptureSignature&&jsx(Vr,{onChange:l,disabled:a.busy}),!d&&jsx(m,{accessibilityRole:"alert",style:g,children:$.missingSignature}),a.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:g,children:a.error.displayMessage}),!a.copy&&a.error&&R(de.retry,a.retryCopy),R(v,()=>{a.submit();},a.busy||!a.ready||!d,Oe.sendA11y(a.drafts.length))]}),e.onClose&&R($.cancel,e.onClose,a.busy),jsx(Me,{})]})}i(dy,"BatchBody");var le=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 uy="value_text",tc=64,rc=512;function nc(e){return e!==null&&e.httpStatus===409&&!rr(e)}i(nc,"isFactReviewerLocked");var wn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:uy}),oc=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,ic=/^\d{4}-\d{2}-\d{2}$/;function ac(e){if(e==null)return "text";let t=e.trim();return oc.test(t)?"num":ic.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(ac,"inferFactValueKind");function Qi(e,t){let r=t.trim(),o=ac(e);if(o==="num"&&oc.test(r)){let n=Number(r);if(Number.isFinite(n))return Object.freeze({[wn.num]:n})}return o==="date"&&ic.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[wn.date]:r}):Object.freeze(o==="bool"&&(r==="true"||r==="false")?{[wn.bool]:r==="true"}:{[wn.text]:r})}i(Qi,"factCorrectionFor");var Ie=z.string().nullish(),yo=z.number().nullish(),py=z.object({collected_at:Ie,at:Ie,value:yo,unit:Ie,qualitative_result:Ie,ref_low:yo,ref_high:yo,status:Ie,source_clinic:Ie,source_doc_id:Ie,doc_id:Ie,reviewed:z.boolean().nullish()}),my=z.object({collected_at:Ie,at:Ie,value:yo,unit:Ie,qualitative_result:Ie,status:Ie}),yy=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:my.nullish(),trajectory:Ie,points:z.array(py).optional()}),fy=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()}),gy=z.object({markers:z.array(yy).optional(),summary:fy.nullish(),disclaimer:z.string().optional(),featured_marker_id:Ie});function by(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(by,"isObject");function sc(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(sc,"withheldMarkers");function lc(e,t){let r=by(t)?t:{},o=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return sc(o);let n=gy.safeParse(r);if(!n.success)return sc(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(lc,"mapRecordMarkers");var hy=z.string().min(1).refine(e=>e.startsWith("https://")),Ry=z.object({source_doc_id:z.string().min(1),file_name:z.string().nullish(),doc_format:z.string().nullish(),byte_size:z.number().int().nonnegative().nullish(),received_at:z.string().nullish(),download_url:hy,expires_in_seconds:z.number().int().nonnegative().nullish()}),vy=z.object({items:z.array(z.unknown()).optional()});function cc(e){let t=vy.safeParse(e);if(!t.success)return null;let r=[];for(let o of t.data.items??[]){let n=Ry.safeParse(o);n.success&&r.push(Object.freeze({sourceDocId:n.data.source_doc_id,fileName:n.data.file_name??null,docFormat:n.data.doc_format??null,byteSize:n.data.byte_size??null,receivedAt:n.data.received_at??null,downloadUrl:n.data.download_url,expiresInSeconds:n.data.expires_in_seconds??0}));}return Object.freeze(r)}i(cc,"mapRequestDocuments");var xy=z.string().min(1).refine(e=>e.startsWith("https://")),Cn=z.string().nullish(),wy=z.object({share_id:z.string().min(1),share_url:z.string().min(1),expires_at:Cn}),Cy=z.object({shares:z.array(z.object({share_id:z.string().min(1),expires_at:Cn,created_at:Cn,view_count:z.number().int().nonnegative().nullish(),last_viewed_at:Cn})).optional()}),Ey=z.object({download_url:xy,expires_at:Cn});function Sy(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(Sy,"resolveShareUrl");function dc(e,t){let r=wy.safeParse(e);if(!r.success)return null;let o=Sy(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(dc,"mapRecordShareLink");function uc(e){let t=Cy.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(uc,"mapRecordShareList");function pc(e){let t=Ey.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(pc,"mapRecordPdfLink");var ky=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 mc(e){let t=ky.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(mc,"mapSignatureSuggestions");var N=z.string().nullish(),En=z.number().nullish(),Ty=z.object({at:N,value:En,unit:N,qualitative_result:N,ref_low:En,ref_high:En,status:N,doc_id:N}),_y=z.object({marker_id:z.string(),name:z.string(),loinc_code:N,unit:N,panel:N,meaning:N,latest:z.object({at:N,value:En,unit:N,qualitative_result:N,status:N}).nullish(),trajectory:N,points:z.array(Ty).optional()}),Py=z.object({encounter_id:z.string(),date:N,type:N,clinic_name:N,veterinarian:N,doc_id:N}),Iy=z.object({note_id:z.string(),encounter_id:N,observed_on:N,sections:z.array(z.object({section:z.string(),text:z.string()})).optional()}),Dy=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()}),Ay=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()}),Oy=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()}),Ly=z.object({lab_results:z.array(_y).optional(),encounters:z.array(Py).optional(),clinician_notes:z.array(Iy).optional(),physical_exams:z.array(Dy).optional(),completeness:Ay.nullish(),conflicts:z.array(Oy).optional()}),Vy=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:En,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()}),qy=z.object({document:$o,contributions:z.array(jo),contribution_count:z.number().int().nonnegative().optional()});function Ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Ji,"isObject");function Zi(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(Zi,"petOf");function Xi(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(Xi,"emptyDepth");function zy(e,t){let r=Ji(t)?t:{},o=Zi(r,e);if(r.withheld===true)return Xi(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return Xi(o,false);let l=Ly.safeParse(r);if(!l.success)return Xi(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(zy,"mapRecordDepth");function yc(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(yc,"withheldTimeline");function Fy(e,t){let r=Ji(t)?t:{},o=Zi(r,e);if(r.withheld===true)return yc(o);let n=Vy.safeParse(r);if(!n.success)return yc(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(Fy,"mapRecordsTimeline");function Ny(e,t){let r=Ji(t)?t:{},o=Zi(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=qy.safeParse(r);if(!l.success)return n();let s=Object.freeze(l.data.contributions.map(Wo));return Object.freeze({petRef:o,withheld:false,document:Go(l.data.document),contributions:s,contributionCount:l.data.contribution_count??s.length})}i(Ny,"mapDocumentContributions");var My="/widget/v1/records/pets";function fc(e){let t=e.funnel??fr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!gr(a)&&[...a].length<=d,"segment"),o=i(async(a,d,u,p)=>{if(!r(d,mt))return lr();let g=await t.send(a,{method:"GET",path:u});if(!g.ok)return g;let h=p(g.value);return h.petRef===d?_e(h):B(q("internalError",{retryable:false}))},"read"),n=i(a=>`${My}/${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 g=u(p.value);return g===null?B(q("internalError",{retryable:false})):_e(g)},"parsed"),c=i((a,d)=>!r(a.entityType,tc)||!r(a.canonicalKey,rc)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,nn)||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=>zy(a,d)),"getRecordDepth"),getTimeline:i(a=>o("records.depth.timeline",a,`${n(a)}/timeline`,d=>Fy(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?o("records.depth.contributions",a,`${n(a)}/documents/${encodeURIComponent(d)}/contributions`,u=>Ny(a,u)):lr()},getMarkers:i(a=>o("records.depth.markers",a,`${n(a)}/markers`,d=>lc(a,d)),"getMarkers"),createShare(a){return r(a,mt)?s("records.share.create",{method:"POST",path:`${l(a)}/share`},d=>dc(d,e.apiBaseUrl)):lr()},listShares(a){return r(a,mt)?s("records.share.list",{method:"GET",path:`${l(a)}/shares`},uc):lr()},async revokeShare(a,d){if(!r(a,mt)||!r(d,64))return lr();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`},pc):lr()},async editFact(a,d){let u=r(a,mt)?c(d,d.correctedFields):null;if(u===null)return lr();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 lr();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},listRequestDocuments(a){return r(a,64)?s("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(a)}/documents`},cc):lr()},listAuthorizationSignatures:i(()=>s("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},mc),"listAuthorizationSignatures")}}i(fc,"createRecordsDepthClient");function lr(){return Promise.resolve(B(q("validationFailed",{retryable:false})))}i(lr,"invalid");function cr(){let{runtime:e,userRef:t,scopeEpoch:r}=ke();return useMemo(()=>{let{services:o}=e.registry;return fc({auth:o.authFor(t),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,t,r])}i(cr,"useEverfurRecordsDepthClient");function $t(e,t,r,o=""){let n=cr(),{userRef:l}=ke(),s=Bn(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 y=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 f=await t(n,e);y===u.current&&(f.ok?d({scope:c,value:f.value,error:null,loading:false}):d({scope:c,value:null,error:f.error,loading:false}));},[n,e,t,c,l]);useEffect(()=>(p(),()=>{u.current+=1;}),[p]);let g=a.scope===c?a:{value:null,error:null,loading:true},h=useCallback(()=>{p();},[p]),R=g.error===null||g.error.httpStatus!==404,v=R?g.error:null,x=g.loading?"loading":v!==null?"error":g.value===null?"empty":g.value.withheld?"populated":r(g.value)?"empty":"populated";return useMemo(()=>({status:x,value:g.value,error:v,available:R,refresh:h}),[x,g.value,v,R,h])}i($t,"useRecordsDepthRead");function xr(e){return e!==null&&e.httpStatus===404}i(xr,"isDarkRouteError");var $y=i((e,t)=>e.getMarkers(t),"readMarkers"),Wy=i(e=>e.markers.length===0,"markersEmpty");function ta(e){let t=$t(e,$y,Wy);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(ta,"useRecordsMarkers");var Gy=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function hc(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),[g,h]=useState(t.email),[R,v]=useState(false),[x,y]=useState(null),[f,E]=useState(null),[b,C]=useState(0),[D,S]=useState(null),[k,I]=useState(false),[G,z]=useState(null),[Y,H]=useState([]),[Z,oe]=useState(null),[Ee,U]=useState(false),w=useRef(false),T=useRef(true),O=useRef(nr()),M=useRef(null);useEffect(()=>(T.current=true,()=>{T.current=false,M.current=null;}),[r]),useEffect(()=>{let Se=true;return y(null),M.current=null,r.getAuthorizationCopy().then(F=>{Se&&(F.ok?(y(F.value),E(null)):E(F.error));}).catch(()=>{Se&&E(q("internalError"));}),()=>{Se=false;}},[r,b]),useEffect(()=>{if(o===void 0)return;let Se=true;return o.listAuthorizationSignatures().then(F=>{Se&&(F.ok?H(F.value):xr(F.error)||H([]));}).catch(()=>{}),()=>{Se=false;}},[o]);let X=bn(t.clinic),ye=g.trim().toLowerCase(),Ve=Gy.test(ye),ie=X&&(R||ye.length>0)&&!Ve?le.emailRequired:null,we=x?gn(x,u.trim(),He(e.petName),s):null,vt=e.hostCapture===true||Ee||Z!==null,Xe=!!(a&&x&&we&&u.trim()&&s&&vt&&(!X||Ve)),qt=useCallback(async()=>{if(!(w.current||G!==null||!x||!we)){if(!s){S(le.missingDraftError);return}if(X&&!Ve){v(true),S(le.emailRequired);return}if(!(!a||!u.trim())){w.current=true,I(true),S(null);try{if(M.current===null){let F=Z!==null?{signatureId:Z}:await n();if(!T.current)return;if(F===null){S(le.missingSignatureError);return}let Re=t.clinic&&(!X||t.clinic.emailStatus==="none")?{clinicId:t.clinic.id}:{clinicFreeText:s};M.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:x.authorizationVersion,...Re,...X?{clinicEmail:ye}:{},...F.signatureId!==void 0?{signatureId:F.signatureId}:{signaturePngBase64:F.signaturePngBase64},idempotencyKey:O.current()};}let Se=await r.createClinicRequest(M.current);if(!T.current)return;if(!Se.ok){S(Se.error.displayMessage);return}if(Se.value.petRef!==e.petRef){S(q("internalError").displayMessage);return}z(Se.value),M.current=null,l?.(Se.value);}catch{T.current&&S(q("internalError").displayMessage);}finally{w.current=false,T.current&&I(false);}}}},[a,n,t.clinic,s,r,x,G,e.petRef,X,ye,l,u,Z,we,Ve]),zt=useCallback(()=>{M.current=null,S(null);},[]);return {title:c?le.titleFreeText:le.titleDirectory,clinicName:s,isFreeText:c,authorized:a,ownerName:u,email:g,emailError:ie,needsEmail:X,directoryClinicNoEmail:X&&t.clinic!==null,copy:x,copyError:f,scope:we,error:D,busy:k,created:G,ready:Xe,signatures:Y,reuseSignatureId:Z,hasSignature:vt,setAuthorized(Se){w.current||(zt(),d(Se));},setOwnerName(Se){w.current||(zt(),p(Se));},setEmail(Se){w.current||(zt(),v(false),h(Se));},setSigned(Se){w.current||(zt(),U(Se),Se&&oe(null));},pickReuseSignature(Se){w.current||(zt(),oe(Se));},retryCopy(){E(null),C(Se=>Se+1);},submit:qt}}i(hc,"useRecordsConsentForm");function oa(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:de.sessionRequired}):jsx(Jy,{...ze(e,["onCreated","onNavigate","onBack"])},JSON.stringify([t,r,e.petRef,e.clinic.key]))})}i(oa,"EverfurRecordsConsent");function Jy({petRef:e,petName:t,clinic:r,ownerName:o,onCaptureSignature:n,onCreated:l,controller:s,onNavigate:c,onBack:a,style:d}){let u=be(),p=Zy(),g=V(),h=Mt(),R=cr(),[v,x]=useState(null),[y,f]=useState("draw"),E=useCallback(async()=>v===null?null:{signaturePngBase64:v},[v]),b=hc({petRef:e,petName:t,ownerName:o??"",clinic:r,controller:s??h,depthClient:R,capture:n?()=>n({petRef:e,petName:He(t),ownerName:b.ownerName,clinicName:b.clinicName,authorizationVersion:b.copy?.authorizationVersion??"",scopeText:b.scope??"",signal:new AbortController().signal}):E,hostCapture:n!==void 0,onCreated:i(k=>{l?.(k),c?.({name:"dashboard"});},"onCreated")}),C=useRef(b);C.current=b;let D=useCallback(k=>{x(k),C.current.setSigned(k!==null);},[]),S=b.busy;return jsxs(View,{style:[u.root,d],children:[jsx(et,{title:b.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:le.scopeHeading}),jsx(m,{style:p.scopeBody,children:le.scopeBody}),jsx(View,{style:p.bullets,children:le.whatWeDo.map(k=>jsxs(View,{style:p.bulletRow,children:[jsx(m,{style:p.check,children:"\u2713"}),jsx(m,{style:p.bulletText,children:k})]},k))}),jsx(View,{style:p.retentionRow,children:jsx(m,{style:p.retentionText,children:le.retentionNote})}),b.copy&&b.scope?jsx(m,{style:p.serverScope,testID:"records-consent-scope",children:b.scope}):b.copyError?jsxs(Fragment,{children:[jsx(m,{style:u.errorText,accessibilityRole:"alert",children:b.copyError.displayMessage}),jsx(re,{label:de.retry,kind:"outline",onPress:b.retryCopy,testID:"records-consent-copy-retry"})]}):jsx(m,{style:u.muted,accessibilityLiveRegion:"polite",children:de.loading})]}),jsxs(Pressable,{onPress:()=>b.setAuthorized(!b.authorized),accessibilityRole:"checkbox",accessibilityState:{checked:b.authorized},accessibilityLabel:le.authorizeLabel(t,b.clinicName),hitSlop:6,style:[p.toggle,b.authorized?p.toggleChecked:null],testID:"records-authorize-toggle",children:[jsx(View,{style:[p.box,b.authorized?p.boxChecked:null],accessibilityElementsHidden:true,importantForAccessibility:"no",children:b.authorized?jsx(m,{style:p.boxCheck,children:"\u2713"}):null}),jsx(m,{style:p.toggleLabel,children:le.authorizeLabel(t,b.clinicName)})]}),jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:le.fullName}),jsx(qe,{accessibilityLabel:le.fullName,style:u.field,value:b.ownerName,placeholder:le.fullNamePlaceholder,placeholderTextColor:g.color.text.placeholder,maxLength:200,editable:!S,autoComplete:"name",autoCapitalize:"words",onChangeText:b.setOwnerName,testID:"records-consent-owner-name"})]}),b.needsEmail?jsxs(View,{style:p.block,testID:"records-consent-email-block",children:[b.directoryClinicNoEmail?jsx(View,{style:u.cautionNote,testID:"records-consent-no-email-note",children:jsx(m,{style:u.cautionNoteText,children:le.noEmailNote(t,b.clinicName)})}):null,jsx(m,{style:u.fieldLabel,children:le.emailLabel}),jsx(qe,{accessibilityLabel:le.emailLabel,style:u.field,value:b.email,placeholder:le.emailPlaceholder,placeholderTextColor:g.color.text.placeholder,maxLength:320,editable:!S,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:b.setEmail,testID:"records-consent-clinic-email"}),b.emailError?jsx(m,{style:u.errorText,accessibilityRole:"alert",children:b.emailError}):null,jsx(m,{style:u.muted,testID:"records-consent-review-note",children:le.newClinicDirectSendNote})]}):null,n?null:jsxs(View,{style:p.signatureBlock,children:[b.signatures.length>0?jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:le.reuseSignature}),jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:p.gallery,children:b.signatures.map(k=>{let I=b.reuseSignatureId===k.signatureId;return jsx(Pressable,{onPress:()=>b.pickReuseSignature(I?null:k.signatureId),accessibilityRole:"button",accessibilityLabel:I?le.reuseTileSelectedA11y:le.reuseTileA11y,style:[p.tile,I?p.tileSelected:null],testID:`records-consent-reuse-${k.signatureId}`,children:jsx(Image,{source:{uri:k.previewUrl},style:p.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},k.signatureId)})}),jsx(m,{style:u.muted,children:le.reuseHint})]}):null,jsx(View,{style:p.signatureHeader,children:jsx(m,{style:u.fieldLabel,children:y==="type"?le.signType:le.signDraw})}),jsx(Vr,{onChange:D,disabled:S}),jsx(Pressable,{onPress:()=>f(k=>k==="draw"?"type":"draw"),accessibilityRole:"button",accessibilityLabel:y==="draw"?le.toTypeA11y:le.toDraw,style:p.modeToggle,testID:"records-consent-sign-mode-toggle",children:jsx(m,{style:p.modeToggleText,children:y==="draw"?le.toType:le.toDraw})}),jsx(m,{style:u.muted,children:le.signatureHint(b.clinicName)})]}),b.error?jsx(View,{style:u.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:jsx(m,{style:u.errorText,children:b.error})}):null,b.created?jsx(m,{accessibilityLiveRegion:"polite",style:u.bodyText,children:b.created.statusLabel||de.records}):null]}),jsx(View,{style:p.footer,children:jsx(re,{label:S?le.submitting:le.submit,accessibilityLabel:le.submitA11y,disabled:!b.ready,busy:S,onPress:()=>{b.submit();},style:p.submit,testID:"records-consent-submit"})})]}),jsx(Me,{})]})}i(Jy,"ConsentBody");function Zy(){let e=V();return useMemo(()=>ef(e),[e])}i(Zy,"useLocalStyles");function ef(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(ef,"makeLocalStyles");function go(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(go,"markerStatusTone");function rf(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(rf,"markerStatusSpoken");function nf(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(nf,"rangePhrase");function bo(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(bo,"formatReferenceRange");function Cc(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)}, ${rf(t.status)}${nf(t)}${o}${r}`}i(Cc,"markerPointSpoken");function Ge(e){return e?.trim()||"my pet"}i(Ge,"lead");function Ec(e){let t=e.trim();return /[.!?]$/.test(t)?t:`${t}.`}i(Ec,"clause");function Sc(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(Ec(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(Sc,"buildMarkerAskPrompt");function kc(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(kc,"buildMarkerSummaryAskPrompt");function Tc(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(Tc,"buildMarkerReadingAskPrompt");function _c(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(_c,"buildRecordsRequestAskPrompt");var of=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function ia(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:of[r]??r,id:o,payload:{kind:n,title:l,...s?{detail:s}:{}}}}}i(ia,"buildEntityRowAskPrompt");function Pc(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(Pc,"buildUpcomingCareAskPrompt");function Ic(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(Ic,"buildPhysicalExamAskPrompt");function Dc(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"}: ${Ec(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(Dc,"buildVisitNoteAskPrompt");function Ac(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(Ac,"buildConflictAskPrompt");function Sn(e){return e!==void 0}i(Sn,"canUploadRecords");function aa(e,t){return e??t?.version??""}i(aa,"resolveConsentVersion");function zr(e,t){return aa(e,t).length>0}i(zr,"canGrantConsent");function wr(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(wr,"selectErrorView");function ho(e){let t=e.clinicName?.trim()??"";return t.length>0?t:e.source==="owner_provided"?Oc.ownerUpload:Oc.clinicRequest}i(ho,"selectRequestTitle");var Oc=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function af(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(af,"selectRequestList");function kn(e){let t=e.actionNeededLabel?.trim()??"";return t.length>0?t:e.statusLabel}i(kn,"selectPrimaryLabel");function Ro(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(Ro,"selectClinicCall");var gt=200,Vc=16;function lf(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(lf,"buildRingSegments");function zc({summary:e,onAsk:t,testID:r}){let o=df(),n=V(),{totalMarkers:l,inRangeCount:s,outOfRangeCount:c,unknownCount:a}=e,d=useMemo(()=>lf(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:Bt.title}),jsx(View,{style:o.ringRow,accessible:true,accessibilityRole:"image",accessibilityLabel:Bt.a11y(l,s,c,a),children:jsxs(View,{style:o.ringWrap,children:[jsx(View,{style:o.track}),d===null?null:d.map(p=>jsx(cf,{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?Bt.marker:Bt.markers})]})]})}),u||d===null?jsxs(View,{style:o.badges,children:[jsx(sa,{count:c,label:Bt.outOfRange,color:n.color.danger,styles:o}),jsx(sa,{count:s,label:Bt.inRange,color:n.color.success,styles:o}),a>0?jsx(sa,{count:a,label:Bt.noRange,color:n.color.text.muted,styles:o}):null]}):null,jsx(m,{style:o.subtitle,children:Bt.subtitle}),t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Bt.askA11y,style:o.ask,testID:"marker-summary-ask",children:jsx(m,{style:o.askLabel,children:Bt.ask})}):null]})}i(zc,"MarkerSummaryCard");function cf({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(cf,"Arc");function sa({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(sa,"Badge");function df(){let e=V();return useMemo(()=>uf(e),[e])}i(df,"useStyles");function uf(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:Vc,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:Vc,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(uf,"makeStyles");function pf(e){return e.value!==null&&Number.isFinite(e.value)}i(pf,"numeric");function Fc(e){let t=e.points.filter(pf);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(y=>y.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,g=i(y=>(u-y)/p*100,"y"),h=6,R=t.length,v=t.map((y,f)=>({index:f,xPct:R<=1?50:h+f/(R-1)*(100-2*h),yPct:g(y.value),status:y.status,point:y})),x=o!==null||n!==null?{topPct:n!==null?g(n):0,bottomPct:o!==null?g(o):100}:null;return {points:v,band:x,firstDate:t[0]?.at??null,lastDate:t[t.length-1]?.at??null}}i(Fc,"buildMarkerChart");var ff=416,gf=140;function xo(e){return `${e}%`}i(xo,"pct");function bf({marker:e,width:t,onPointPress:r,onAsk:o}){let n=la(),l=be(),s=Xt(e.latest?.status??null),c=go(e.latest?.status??null),a=jr(e.trajectory,e.points.length),d=useMemo(()=>Fc(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:ir.status(s.label),children:jsx(Ht,{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:ir.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:xo(d.band.topPct),height:xo(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:xo(p.xPct),top:xo(p.yPct)}],testID:`marker-point-${e.markerId}-${p.index}`},p.index))]}),jsx(View,{style:n.a11yTable,accessibilityRole:"summary",accessibilityLabel:ir.readingsA11y(e.name),children:e.points.map((p,g)=>jsx(View,{accessibilityRole:"text",accessibilityLabel:Cc(e,p)},g))}),jsx(m,{style:e.points.length===1?n.singleHint:n.tapHint,children:e.points.length===1?ir.singleHint:ir.tapHint})]}):jsx(View,{style:n.emptyBody,accessibilityRole:"text",children:jsx(m,{style:n.emptyText,children:ir.empty})}),o?jsx(Pressable,{onPress:()=>o(e),accessibilityRole:"button",accessibilityLabel:ir.askA11y(e.name),style:[l.pill,l.pillAsk],testID:`marker-ask-${e.markerId}`,children:jsx(m,{style:l.pillAskLabel,children:ir.ask})}):null]})})}i(bf,"MarkerTrendCard");function Hc({markers:e,onPointPress:t,onAsk:r}){let o=la(),[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 g=Math.round(p.nativeEvent.contentOffset.x/n);c(Math.max(0,Math.min(g,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(bf,{marker:p,width:n>0?n:void 0,onPointPress:t,onAsk:r},p.markerId))}),jsxs(View,{style:o.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:Ti.a11y(u?.name??null,s,e.length),children:[jsx(View,{style:o.dots,children:e.map((p,g)=>jsx(View,{style:[o.dot,g===s?o.dotActive:null]},p.markerId))}),jsx(m,{style:o.counter,children:Ti.counter(s,e.length)})]})]})}i(Hc,"MarkerTrendCarousel");function Uc({marker:e,point:t,onClose:r,onAsk:o}){let n=la(),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?bo(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(Uc,"MarkerProvenanceSheet");function la(){let e=V();return useMemo(()=>hf(e),[e])}i(la,"useStyles");function hf(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=StyleSheet.hairlineWidth,c=r.md,a=i((g,h,R,v="regular")=>({..._(e,v),fontSize:g,lineHeight:Math.round(g*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:gf,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:ff},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:ro},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(hf,"makeStyles");var K=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",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",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"})}),jc=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 Fr(e){return Object.prototype.hasOwnProperty.call(jc,e)?jc[e]:ar(e)}i(Fr,"entityTypeLabel");var $c=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function Wc(e){let t=$c.filter(o=>e.includes(o)),r=e.filter(o=>!$c.includes(o));return [...t,...r]}i(Wc,"orderEntityTypes");function wo(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(wo,"conflictSeverityMeta");function _n(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?K.overdue:K.due(Q(e)),overdue:o}}i(_n,"dueBadge");function Gc(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(Gc,"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 Yc(e,t){return rr(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.":nc(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(Yc,"factEditErrorMessage");var Rf=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function ca(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(ca,"applyFactOverlay");function Eo(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(Eo,"isFactEditable");function vf(){return `records-fact-${Date.now().toString(36)}`}i(vf,"defaultFactKey");function da(e,t={}){let r=cr(),{userRef:o}=ke(),[n,l]=useState(Rf),[s,c]=useState(false),[a,d]=useState(null),u=useMemo(()=>({}),[r,e,o]),[p,g]=useState(null),h=useCallback(()=>g(u),[u]),R=o!==null&&p!==u,v=useRef(false),x=useRef(t.newIdempotencyKey);x.current=t.newIdempotencyKey;let y=useCallback(()=>(x.current??vf)(),[]),f=useCallback((D,S,k)=>{if(c(false),!D.ok){if(S(),xr(D.error)){h();return}d(Yc(D.error,k));}},[h]),E=useCallback(async(D,S)=>{let k=D.canonicalKey??"",I=S.trim();if(v.current||k.length===0||I.length===0)return B(q("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let G=n;l(Y=>({...Y,edits:{...Y.edits,[k]:I}}));let z=await r.editFact(e,{entityType:D.category,canonicalKey:k,correctedFields:Qi(D.value,I),idempotencyKey:y()});return v.current=false,f(z,()=>l(G),"edit"),z},[r,e,n,f,y]),b=useCallback(async D=>{let S=D.canonicalKey??"";if(v.current||S.length===0)return B(q("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let k=n;l(G=>({...G,removed:[...G.removed,S]}));let I=await r.removeFact(e,{entityType:D.category,canonicalKey:S,idempotencyKey:y()});return v.current=false,f(I,()=>l(k),"remove"),I},[r,e,n,f,y]),C=useCallback(()=>d(null),[]);return useMemo(()=>({overlay:n,busy:s,error:a,available:R,edit:E,remove:b,clearError:C}),[n,s,a,R,E,b,C])}i(da,"useRecordFactEdit");var ua=Object.freeze(["vaccination","parasite_prevention"]),So="Undated",xf=Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),Xc=Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function ko(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(ko,"toMillis");function wf(e){let t=e.status?.toLowerCase()??"";return /overdue|lapsed|expired/.test(t)}i(wf,"isLapsed");function Cf(e){return e.category==="parasite_prevention"?"prevention":ko(e.observedAt)===null?"noDate":wf(e)?"overdue":"given"}i(Cf,"vaccineTone");function Ef(e){let t=ko(e);return t===null?So:String(new Date(t).getUTCFullYear())}i(Ef,"yearOf");function Sf(e){let t=Cf(e),r=[e.value!==null&&e.value.length>0?e.value:null,e.observedAt!==null?Q(e.observedAt):null].filter(o=>o!==null&&o.length>0);return {key:e.key,name:e.label,detail:r.length>0?r.join(" \xB7 "):null,statusLabel:xf[t],tone:t,entity:e}}i(Sf,"buildRow");function Jc(e){let t=new Map;for(let o of e){if(!ua.includes(o.category))continue;let n=Ef(o.observedAt),l=t.get(n),s={row:Sf(o),at:o.observedAt};l===void 0?t.set(n,[s]):l.push(s);}let r=[...t.keys()].sort((o,n)=>o===So?1:n===So?-1:Number(n)-Number(o));return Object.freeze(r.map(o=>{let n=t.get(o)??[],l=o===So?n:[...n].sort((s,c)=>(ko(c.at)??0)-(ko(s.at)??0));return Object.freeze({year:o,items:Object.freeze(l.map(s=>s.row))})}))}i(Jc,"selectVaccineGroups");function pa({entity:e,factEdit:t,children:r}){let o=ed(),[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(If,{entity:e,title:s,factEdit:t,onClose:()=>l(false)}):null]})}i(pa,"FactEditAffordance");function If({entity:e,title:t,factEdit:r,onClose:o}){let n=ed(),l=be(),s=V(),[c,a]=useState(e.value??""),[d,u]=useState(null),[p,g]=useState(false);useEffect(()=>{r.clearError();},[r]);let h=c.trim().length>0&&c.trim()!==(e.value??"").trim(),R=d??r.error,v=r.busy,x=i(()=>{if(!h){u(at.noChange);return}u(null),r.edit(e,c).then(f=>{f.ok&&o();});},"submitEdit"),y=i(()=>{u(null),r.remove(e).then(f=>{f.ok?o():g(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:f=>{a(f),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:y,style:n.confirmButton,testID:"fact-edit-remove-confirm"}),jsx(re,{label:at.keep,kind:"outline",disabled:v,onPress:()=>g(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:x,testID:"fact-edit-save"}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:at.removeA11y(t),disabled:v,onPress:()=>{u(null),g(true);},style:[n.removeButton,v?n.removeDisabled:null],testID:"fact-edit-remove",children:jsx(m,{style:n.removeText,children:at.remove})})]})]})]})})}i(If,"FactEditSheet");function ed(){let e=V();return useMemo(()=>Df(e),[e])}i(ed,"useStyles");function Df(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:ro},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(Df,"makeStyles");function Io({record:e,depth:t,petName:r,showLabs:o=true,onNavigate:n,onAsk:l,factEdit:s,nowMs:c}){let a=be(),d=Af(),u=c??Date.now(),p=useMemo(()=>s?ca(e.entities,s.overlay):e.entities,[e.entities,s]),g=useMemo(()=>{let y=[],f=new Map;for(let E of p){let b=E.category.trim();if(b.length===0||ua.includes(b))continue;let C=f.get(b);C===void 0?(y.push(b),f.set(b,[E])):C.push(E);}return {order:Wc(y),groups:f}},[p]),h=useMemo(()=>Jc(p),[p]),R=Object.values(e.documents),v=i((y,f,E)=>l?jsx(Pressable,{onPress:()=>{let b=y();l(b.prompt,b.entityRef);},accessibilityRole:"button",accessibilityLabel:f,style:[a.pill,a.pillAsk,d.ask],testID:E,children:jsx(m,{style:a.pillAskLabel,children:f})}):null,"ask"),x=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(Pt,{title:K.needsAttention,count:t.conflicts.length}),[...t.conflicts].sort((y,f)=>wo(y.severity).rank-wo(f.severity).rank).map(y=>{let f=wo(y.severity),E=ar(y.field??y.entityType);return jsxs(View,{style:[d.conflictCard,{borderColor:a.chipTones[f.tone].fg.color}],accessibilityRole:"summary",children:[jsxs(View,{style:d.conflictHead,children:[jsx(m,{style:d.conflictTitle,children:f.label}),jsx(Ht,{label:E,tone:f.tone})]}),jsx(m,{style:a.rowDetail,children:K.conflictSub}),y.candidates.map((b,C)=>jsxs(View,{style:d.candidate,children:[jsx(m,{style:a.rowTitle,children:b.value}),jsx(m,{style:a.rowMuted,children:[b.docId?e.documents[b.docId]?.title??K.uploadedDocument:K.uploadedDocument,b.collectedAt?Q(b.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},C)),v(()=>Ac(r,{scopeLabel:E,severity:y.severity,candidates:y.candidates.map(b=>({value:b.value,clinicName:b.docId?e.documents[b.docId]?.title??null:null}))},y.conflictId),K.askConflict,`records-ask-conflict-${y.conflictId}`)]},y.conflictId)})]}):null,t?.completeness?jsxs(View,{style:a.section,testID:"record-section-completeness",children:[jsx(Pt,{title:K.whatsOnFile}),jsxs(View,{style:a.card,children:[jsx(View,{style:d.coverageRow,children:[[K.coverage.labs,t.completeness.hasLabHistory],[K.coverage.vaccines,t.completeness.hasVaccinationHistory],[K.coverage.weight,t.completeness.hasWeightHistory],[K.coverage.vitals,t.completeness.hasVitalsHistory],[K.coverage.exams,t.completeness.hasPhysicalExamHistory],[K.coverage.procedures,t.completeness.hasProcedureHistory],[K.coverage.genetics,t.completeness.hasGeneticHistory],[K.coverage.parasite,t.completeness.hasParasitePreventionHistory],[K.coverage.reproductive,t.completeness.hasReproductiveHistory]].map(([y,f])=>jsx(View,{style:[d.coveragePill,f?a.chipTones.positive.bg:a.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${y}: ${f?K.onFile:K.noneOnFile}`,children:jsx(m,{style:[d.coverageText,f?a.chipTones.positive.fg:{color:a.rowMuted.color}],children:y})},y))}),jsxs(View,{style:d.metaRow,children:[jsx(m,{style:d.metaText,children:K.documentsOnFile(t.completeness.documentsIngested)}),t.completeness.documentsInReview>0?jsx(Ht,{label:K.inReviewChip(t.completeness.documentsInReview),tone:"warning"}):null,ma(t.completeness.heldTotal,t.completeness.entitiesPendingReview)>0?jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:K.beingVerifiedA11y(ma(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),children:jsx(Ht,{label:K.beingVerified(ma(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:K.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:[K.pendingReview,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).map(([y,f])=>`${Fr(y)} (${f})`).join(", ")]}):null]})]}):null,R.length>0?jsxs(View,{style:a.section,testID:"record-section-documents",children:[jsx(Pt,{title:K.documents,count:R.length}),jsx(View,{style:a.card,children:R.map((y,f)=>{let E=y.title?.trim()||K.uploadedDocument,b=y.receivedAt?Q(y.receivedAt):null,C=jsxs(Fragment,{children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:E}),b?jsx(m,{style:a.rowDetail,children:b}):null]}),n?jsx(Ir,{}):null]});return n?jsx(Pressable,{onPress:()=>n({name:"contributions",docId:y.docId}),accessibilityRole:"button",accessibilityLabel:K.documentRowA11y(E),style:[a.row,f>0?a.rowDivider:null],testID:`records-document-row-${y.docId}`,children:C},y.docId):jsx(View,{style:[a.row,f>0?a.rowDivider:null],children:C},y.docId)})})]}):null,e.identity.length>0?jsxs(View,{style:a.section,testID:"record-section-identity",children:[jsx(Pt,{title:K.identity}),jsx(View,{style:a.card,children:e.identity.map((y,f)=>jsxs(View,{style:[a.row,f>0?a.rowDivider:null],children:[jsx(m,{style:d.identityLabel,children:y.label}),jsx(m,{style:d.identityValue,children:y.value})]},`${f}:${y.label}`))})]}):null,e.forwardLooking.length>0?jsxs(View,{style:a.section,testID:"record-section-upcoming",children:[jsx(Pt,{title:K.upcomingCare,count:e.forwardLooking.length}),jsx(View,{style:a.card,children:e.forwardLooking.map((y,f)=>{let E=_n(y.dueAt,u);return jsxs(View,{style:[a.row,f>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]}),E?jsx(Ht,{label:E.label,tone:E.overdue?"critical":"info"}):null]},`${y.title}-${f}`)})}),v(()=>Pc(r,e.forwardLooking.map(y=>{let f=_n(y.dueAt,u);return {label:y.title,relativeText:f?.label??"",tone:f?.overdue?"overdue":"upcoming"}}),e.petRef),K.askUpcomingCare,"records-ask-upcoming-care")]}):null,h.length>0?jsxs(View,{style:a.section,testID:"record-section-vaccination",children:[jsx(Pt,{title:Fr("vaccination"),count:h.reduce((y,f)=>y+f.items.length,0)}),h.map(y=>jsxs(View,{style:d.vaccineGroup,testID:`records-vaccine-group-${y.year}`,children:[jsx(m,{style:d.vaccineYear,accessibilityRole:"header",children:y.year.toUpperCase()}),jsx(View,{style:a.card,children:y.items.map((f,E)=>{let b=jsxs(View,{style:[a.row,E>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:f.name}),f.detail?jsx(m,{style:a.rowDetail,children:f.detail}):null,v(()=>ia(r,{entityTypeLabel:Fr(f.entity.category),title:f.name,detail:f.detail},f.entity.category,f.key),K.askEverfur,`records-ask-entity-${f.key}`)]}),jsx(Ht,{label:f.statusLabel,tone:Xc[f.tone]})]});return x&&Eo(f.entity)&&s?jsx(pa,{entity:f.entity,factEdit:s,children:b},f.key):jsx(View,{children:b},f.key)})})]},y.year))]}):null,g.order.map(y=>{let f=g.groups.get(y)??[];if(f.length===0)return null;let E=Fr(y);return jsxs(View,{style:a.section,testID:`record-section-${y}`,children:[jsx(Pt,{title:E,count:f.length}),jsx(View,{style:a.card,children:f.map((b,C)=>{let S=[Ur(b.value,b.unit),b.observedAt?Q(b.observedAt):null].filter(I=>I&&I.length>0).join(" \xB7 "),k=jsxs(View,{style:[a.row,C>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:b.label}),S?jsx(m,{style:a.rowDetail,children:S}):null,v(()=>ia(r,{entityTypeLabel:E,title:b.label,detail:S||null},y,b.key),K.askEverfur,`records-ask-entity-${b.key}`)]}),b.status?jsx(Ht,{label:ar(b.status)}):null]});return x&&Eo(b)&&s?jsx(pa,{entity:b,factEdit:s,children:k},b.key):jsx(View,{children:k},b.key)})})]},y)}),t&&t.physicalExams.length>0?jsxs(View,{style:a.section,testID:"record-section-exams",children:[jsx(Pt,{title:K.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((f,E)=>{let b=f.findingStatus==="abnormal",C=b?fe.abnormal:f.findingStatus==="not_examined"?fe.notExamined:fe.normal;return jsxs(View,{style:[a.row,E>0?a.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[Dr(f.system),C,b?f.finding:null].filter(Boolean).join(", "),children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:Dr(f.system)}),b&&f.finding?jsx(m,{style:a.rowDetail,children:f.finding}):null]}),jsx(Ht,{label:C,tone:b?"warning":f.findingStatus==="not_examined"?"neutral":"positive"})]},f.system)}),v(()=>Ic(r,{observedOn:y.observedOn?Q(y.observedOn):null,abnormal:y.systems.filter(f=>f.findingStatus==="abnormal").map(f=>({system:Dr(f.system),finding:f.finding??""}))},y.examId),K.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(Pt,{title:K.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((f,E)=>jsxs(View,{style:[d.noteSection,E>0?a.rowDivider:null],children:[jsx(m,{style:d.noteLabel,children:$r(f.section)}),jsx(m,{style:f.text?d.noteBody:d.noteBodyMuted,children:f.text||fe.notRecorded})]},`${f.section}:${E}`)),v(()=>Dc(r,{observedOn:y.observedOn?Q(y.observedOn):null,sections:y.sections.map(f=>({label:$r(f.section),text:f.text}))},y.noteId),K.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(Pt,{title:K.labResults,count:t.labResults.length}),jsx(View,{style:a.card,children:t.labResults.map((y,f)=>{let E=Xt(y.latest.status),b=Pi(y.latest.at,y.trajectory,y.points.length);return jsxs(View,{style:[a.row,f>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)}),b?jsx(m,{style:a.rowDetail,children:b}):null]}),jsx(Ht,{label:E.label,tone:go(y.latest.status)})]},y.markerId)})})]}):null,t&&t.encounters.length>0?jsxs(View,{style:a.section,testID:"record-section-visits",children:[jsx(Pt,{title:K.visits,count:t.encounters.length}),jsx(View,{style:a.card,children:t.encounters.map((y,f)=>{let E=[y.date?Q(y.date):null,y.clinicName,y.veterinarian].filter(b=>b&&b!=="-").join(" \xB7 ");return jsx(View,{style:[a.row,f>0?a.rowDivider:null],children:jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:y.type?ar(y.type):fe.visit}),E?jsx(m,{style:a.rowDetail,children:E}):null]})},y.encounterId)})})]}):null]}),jsx(vr,{disclaimer:e.disclaimer})]})}i(Io,"RecordSections");function ma(e,t){return e>0?e:Object.values(t).reduce((r,o)=>r+o,0)}i(ma,"heldCount");function Af(){let e=V();return useMemo(()=>Of(e),[e])}i(Af,"useLocalStyles");function Of(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth;return StyleSheet.create({sections:{gap:r.lg+r.xs},vaccineGroup:{gap:r.xs+1,marginBottom:r.sm},vaccineYear:{..._(e,"monoMedium"),fontSize:n.size.micro,lineHeight:n.size.micro+r.xs,color:t.text.muted,letterSpacing:n.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:r.xs+2},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(Of,"makeLocalStyles");var Pn=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 Lf=Math.round(mr/(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 ${Lf} 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 od=Math.round(mr/(1024*1024)),Nr=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 id(e){let t=Math.round(e.progress*100);switch(e.status){case "done":return Nr.done;case "failed":return Nr.failed;case "uploading":return e.progress>=1?Nr.verifying:`${t}%`;case "queued":return Nr.queued;default:return null}}i(id,"uploadItemStatusLabel");function ad(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 ${od} MB`),`Didn\u2019t upload: ${n.join("; ")}. We can only read PDFs up to ${od} MB right now.`}i(ad,"skippedFilesMessage");function sd(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(sd,"skippedOf");var Lt=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 ld({request:e,onRecovered:t,canUpload:r=false},o){let[n,l]=useState(""),[s,c]=useState(false),[a,d]=useState(null),[u,p]=useState(false),[g,h]=useState(null),R=useRef(false),v=useRef(false),x=useRef(0);useEffect(()=>(v.current=true,()=>{v.current=false,x.current+=1;}),[o]);let y=g!==null&&g.before===e.updatedAt?{...g.value,canRetrySend:e.canRetrySend===true&&g.value.canRetrySend===true,canUpdateClinicEmail:e.canUpdateClinicEmail===true&&g.value.canUpdateClinicEmail===true,canRevoke:e.canRevoke===true&&g.value.canRevoke===true,canConvertToUpload:e.canConvertToUpload===true&&g.value.canConvertToUpload===true}:e,f=n.trim(),E=f.length<=320&&!Array.from(f).some(I=>I.charCodeAt(0)<=32||I.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f),b=y.canUpdateClinicEmail===true&&f.length>0,C=y.canRetrySend===true&&!s&&!b,D=y.canUpdateClinicEmail===true&&!s&&E,S=y.canConvertToUpload===true&&r,k=i(async I=>{let G={retry:C,email:D,revoke:y.canRevoke===true&&u,convert:S};if(R.current||!v.current||!G[I])return;R.current=true,c(true),d(null);let z=x.current,Y=i(()=>v.current&&z===x.current,"live");try{let H=I==="retry"?await o.retryRequest(e.id):I==="email"?await o.updateClinicEmail(e.id,f):I==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!Y())return;if(!H.ok){d(H.error);return}if(H.value.id!==e.id||H.value.petRef!==e.petRef){d(q("internalError"));return}h({before:e.updatedAt,value:H.value}),l(""),p(!1),t();}catch{Y()&&d(q("internalError"));}finally{R.current=false,Y()&&c(false);}},"run");return {request:y,email:n,busy:s,error:a,canRetry:C,canUpdateEmail:D,canConvert:S,hasEmailEdit:b,confirmingRevoke:u&&y.canRevoke===true,emailInvalid:f.length>0&&!E,setEmail(I){R.current||(l(I),d(null));},retry:i(()=>k("retry"),"retry"),updateEmail:i(()=>k("email"),"updateEmail"),revoke:i(()=>k("revoke"),"revoke"),convert:i(()=>k("convert"),"convert"),askRevoke(){!R.current&&y.canRevoke===true&&p(true);},keepRequest(){R.current||p(false);}}}i(ld,"useRecordsRecovery");var qf=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],zf=["requested","awaiting_upload","records_received","processing","ready"],Ff=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],Dn=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"}),Nf=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"}),Mf=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 Bf(e){return e.wireStatus??Mf[e.status]??"sent"}i(Bf,"wireStatusOf");function Hf(e,t){return e!=="awaiting_response"||t<=0?null:`${t} ${t===1?"reminder":"reminders"} sent`}i(Hf,"reminderProgressLabel");function Uf(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(Uf,"reachedRailIndex");function jf(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(jf,"deliveryDetail");function $f(e,t){return Hf(t,e.reminderCount??0)??kt.waiting}i($f,"awaitingDetail");function Wf(e){return e.source==="owner_provided"||!!e.convertedToUploadAt}i(Wf,"isOwnerSourcedRequest");function Gf(e,t,r){let o=Wf(t);switch(e){case "sent_to_clinic":return jf(t);case "awaiting_clinic":return $f(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(Gf,"railDetail");function Yf(e,t){return !!e.reviewStartedAt||t==="parsing_failed"||t==="review_email_failed"}i(Yf,"tookReviewBranch");function Kf(e,t,r){if(e.key!=="processing"||!Yf(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:Dn.parsing_failed,detail:kt.parsingFailed,at:null,state:l},{key:"manual_review",title:Dn.manual_review,detail:kt.manualReview,at:t.reviewStartedAt??null,state:s}]}i(Kf,"expandProcessingPhase");function Qf(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(Qf,"convertedReachedIndex");function cd(e){return {key:"awaiting_clinic",title:kt.switchedTitle,detail:kt.switched,at:e.convertedToUploadAt??null,state:"done"}}i(cd,"convertedClinicSwitchEvent");function Xf(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(Xf,"ownerReachedIndex");function Jf(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(Jf,"railTimestamp");function dd(e,t,r,o){return {key:e,title:Dn[e],detail:Gf(e,t,r),at:Jf(e,t,r),state:o}}i(dd,"railEvent");function dr(e,t){return {key:e,title:Dn[e],detail:Nf[e]??null,at:t.updatedAt||null,state:"failed"}}i(dr,"terminalEvent");function fa(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 dd(l,r,o,a)}).flatMap(l=>Kf(l,r,o))}i(fa,"walkRail");function ga(e){let t=Bf(e),r=i(n=>dd(n,e,t,"done"),"done");if(t==="revoked")return [r("requested"),dr("revoked",e)];if(e.convertedToUploadAt)return t==="failed"?[r("requested"),r("sent_to_clinic"),cd(e),r("awaiting_upload"),r("records_received"),dr("processing_failed",e)]:fa(Ff,Qf(t),e,t,n=>n==="awaiting_clinic"?cd(e):null);if(e.source==="owner_provided"){if(t==="failed"||t==="clinic_declined")return [r("requested"),r("awaiting_upload"),r("records_received"),dr("processing_failed",e)];let n=Xf(t);return fa(zf,n<0?1:n,e,t)}if(t==="clinic_declined")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),dr("clinic_declined",e)];if(t==="clinic_responded_no_records")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),dr("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"),dr("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[r("requested"),dr("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),r("records_received"),dr("processing_failed",e)]:[r("requested"),dr("delivery_failed",e)]}let o=Uf(t);return fa(qf,o<0?1:o,e,t)}i(ga,"buildRequestTimeline");var tg=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),Do=24,ba=10;function Oo({request:e}){let t=og(),r=ga(e);return jsx(View,{style:t.container,accessibilityRole:"summary",children:r.map((o,n)=>jsx(rg,{event:o,isLast:n===r.length-1,styles:t},o.key))})}i(Oo,"RequestTimeline");function rg({event:e,isLast:t,styles:r}){let o=e.at?Q(e.at):null,n=[e.title,e.detail,o,tg[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(ng,{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(rg,"TimelineRow");function ng({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(ng,"TimelineDot");function og(){let e=V();return useMemo(()=>ig(e),[e])}i(og,"useStyles");function ig(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:Do},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:8},dot:{width:Do,height:Do,borderRadius:Do/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:t.brand},dotFailed:{backgroundColor:t.danger},dotCurrent:{borderWidth:2,borderColor:t.brand,backgroundColor:t.surface},dotCurrentCore:{width:ba,height:ba,borderRadius:ba/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(ig,"makeStyles");function Qr(e,t,r){let o=wr(e,r);switch(o.kind){case "consent_required":return jsx(lg,{onGrant:t});case "consent_unavailable":return jsx(cg,{});case "session_required":return jsx(dg,{});case "withheld":return jsx(ug,{});case "pet_not_found":case "error":return jsx(pg,{error:o.error,onRetry:e.refresh});default:return yr(o)}}i(Qr,"renderErrorFamily");function Xr(e,t){return ()=>{let r=aa(t,e.consent);if(r.length===0)return;let o=`records-consent-${Date.now().toString(36)}`;e.grantConsent(r,o);}}i(Xr,"makeGrantHandler");function md({records:e}){let t=On(),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=ad(sd(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?Nr.uploading(n,o.length):Nr.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:id(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(md,"UploadQueue");function lg({onGrant:e}){let t=On();return jsx(View,{style:t.centered,accessible:true,accessibilityRole:"alert",accessibilityLabel:de.consentRequired,children:jsx(Pressable,{onPress:e,accessibilityRole:"button",accessibilityLabel:de.allow,style:t.primaryButton,children:jsx(m,{style:t.primaryLabel,children:de.allow})})})}i(lg,"ConsentRequiredState");function va({label:e,glyph:t}){let r=On();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(va,"AlertState");function cg(){return jsx(va,{label:de.consentRequired,glyph:"empty"})}i(cg,"ConsentUnavailableState");function dg(){return jsx(va,{label:de.sessionRequired,glyph:"empty"})}i(dg,"SessionRequiredState");function ug(){return jsx(va,{label:de.recordUnavailable,glyph:"withheld"})}i(ug,"WithheldState");function pg({error:e,onRetry:t}){let r=On();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:de.retry,style:r.primaryButton,children:jsx(m,{style:r.primaryLabel,children:de.retry})}):null]})}i(pg,"ErrorState");function yd({call:e,prompt:t}){let r=On(),o=t.trim().length>0?t:Pn.fallbackPrompt;return jsxs(View,{style:r.callCard,accessibilityRole:"summary",children:[jsx(m,{style:r.timelineLabel,children:Pn.heading}),jsx(m,{style:r.timelineMeta,children:o}),jsx(Pressable,{onPress:()=>{Linking?.openURL?.(e.dial);},accessibilityRole:"button",accessibilityLabel:Pn.callAt(e.phone),style:r.linkButton,testID:"records-call-clinic",children:jsx(m,{style:r.linkLabel,children:Pn.call})})]})}i(yd,"ClinicCallCard");function On(){let e=V();return useMemo(()=>mg(e),[e])}i(On,"useStyles");function mg(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((f,E)=>Math.round(f*E),"lh"),g=StyleSheet.hairlineWidth,h=r.xxl*3+r.xl,R=r.xxl+r.md,v=r.xxl+r.sm,x=e.brightness==="dark"?t.errorRed:t.danger,y={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:g,borderColor:t.brandBorder},withheldGlyph:{width:v,height:v,borderRadius:o.sm,backgroundColor:t.badgeBgCaution,borderWidth:g,borderColor:t.cautionAccent},errorText:{..._(e,"regular"),fontSize:s.subtitle,lineHeight:p(s.subtitle,c.snug),color:x,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,...y,...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,...y,...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:g,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:g,borderColor:t.brandBorder,gap:r.xs,...y,...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:g,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:g,borderColor:t.brandBorder,...y,...d},row:{flexDirection:"row",justifyContent:"space-between",gap:r.md,paddingVertical:r.xs,borderBottomWidth:g,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(mg,"makeStyles");var gg=i((e,t)=>e.getRecordDepth(t),"readDepth"),bg=i(e=>!e.available,"depthEmpty");function Ea(e){let{style:t,renderPending:r,...o}=ze(e,["onNavigate","onBack","onAsk"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(hg,{...o,style:t})})}i(Ea,"EverfurRecordsDashboard");function hg({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:s,style:c}){let a=be(),d=Sa(),u=yt(r?{petRef:e,controller:r}:{petRef:e}),p=ta(e),g=$t(e,gg,bg),[h,R]=useState(null),v=useCallback((w,T)=>R({marker:w,point:T}),[]),x=useMemo(()=>zr(o,u.consent),[o,u.consent]),y=useMemo(()=>Xr(u,o),[u,o]),f=p.markers?.markers??[],E=f.length>0,b=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,C=Xn(u.requests,e),D=pi({hasMarkers:E,requests:u.requests,petRef:e}),S=mi({recordLoading:u.status==="loading",hasFullRecord:b,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:E,requestsLoading:u.status==="loading",dashboardState:D,drivingRequest:C}),k=p.markers?.disclaimer??u.record?.disclaimer??"",I=i(()=>{u.refresh(),p.refresh(),g.refresh();},"retryAll"),G=g.value!==null&&!g.value.withheld&&g.value.available?g.value:null,z=He(t),Y=s&&p.markers?.summary?()=>{let w=kc(t,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);s(w.prompt,w.entityRef);}:void 0,H=s?w=>{let T=Sc(t,{canonicalName:w.name,markerId:w.markerId,latestValueText:w.latest?Et(w.latest.value,w.unit,w.latest.qualitativeResult):null,statusText:w.latest?Xt(w.latest.status).label:null,trajectoryText:jr(w.trajectory,w.points.length),meaningText:w.meaning});s(T.prompt,T.entityRef);}:void 0,Z=s&&h?()=>{let{marker:w,point:T}=h,O=Tc(t,{canonicalName:w.name,valueText:Et(T.value,w.unit,T.qualitativeResult),collectedAt:Q(T.at),sourceClinic:T.sourceClinic,referenceText:T.refLow!==null||T.refHigh!==null?bo(T,w.unit):null,flagged:T.status==="above"?"above":T.status==="below"?"below":null,reviewed:T.reviewed,entityId:T.docId??w.markerId});R(null),s(O.prompt,O.entityRef);}:void 0,oe=jsxs(Fragment,{children:[p.markers?.summary?jsx(View,{style:a.inset,children:jsx(zc,{summary:p.markers.summary,onAsk:Y,testID:"dashboard-marker-summary"})}):null,jsx(m,{style:a.lead,children:dt.lead(t)}),jsx(Hc,{markers:f,onPointPress:v,onAsk:H})]}),Ee=i(w=>n?jsxs(View,{style:[a.inset,d.actions],children:[w?jsx(xa,{label:dt.viewFullRecord,onPress:()=>n({name:"record"}),testID:"dashboard-full-record-action"}):null,jsx(xa,{label:dt.viewTimeline,onPress:()=>n({name:"timeline"}),testID:"dashboard-timeline-action"})]}):null,"actions"),U;if(u.status==="error"){let w=wr(u,x);U=w.kind==="error"||w.kind==="pet_not_found"?jsx(Qe,{variant:wt(w.error),message:w.error.displayMessage,onAction:w.error.retryable?I:void 0,testID:"dashboard-error"}):Qr(u,y,x);}else switch(S){case "loading":U=jsx(ao,{testID:"dashboard-loading"});break;case "record":U=jsxs(ScrollView,{contentContainerStyle:a.contentTight,testID:"dashboard-record",children:[E?oe:p.status==="error"?jsx(View,{style:[a.inset,d.actions],children:jsx(xa,{label:dt.retryMarkers,onPress:I,testID:"dashboard-markers-retry"})}):null,jsx(View,{style:a.inset,children:u.record?jsx(Io,{record:u.record,depth:G,petName:t,showLabs:!E,onNavigate:n,onAsk:s}):null}),Ee(true)]});break;case "error":U=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":U=jsxs(ScrollView,{contentContainerStyle:a.content,testID:"dashboard-in-progress",children:[C?jsx(Rg,{request:C,petName:z,onOpen:n?()=>n({name:"request",requestId:C.id}):void 0,onAsk:s?()=>{let w=_c(t,{clinicName:C.clinicName??null,statusLabel:kn(C),status:C.status,heldItemCount:C.heldItemCount},C.id);s(w.prompt,w.entityRef);}:void 0}):null,jsx(vr,{disclaimer:k})]});break;case "none":U=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:Pr.title(t)})]}),jsx(m,{style:d.promptBody,children:Pr.body}),n?jsxs(Fragment,{children:[jsx(re,{label:Pr.requestFromClinic,accessibilityLabel:Pr.requestFromClinicA11y(t),onPress:()=>n({name:"clinicPicker"}),style:d.promptCta,testID:"dashboard-request-prompt-clinic"}),jsx(re,{label:Pr.uploadDocument,kind:"outline",accessibilityLabel:Pr.uploadDocumentA11y(t),onPress:()=>n({name:"upload"}),style:d.promptCtaSecondary,testID:"dashboard-request-prompt-upload"})]}):null]}),jsx(vr,{disclaimer:k})]});break;case "labs_only":U=jsxs(ScrollView,{contentContainerStyle:a.contentTight,testID:"dashboard-labs-only",children:[oe,jsx(View,{style:a.inset,children:jsx(vr,{disclaimer:k})}),Ee(false)]});break;default:U=yr(S);}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(xl,{})}):void 0}),jsx(View,{style:a.body,children:U}),jsx(Uc,{marker:h?.marker??null,point:h?.point??null,onClose:()=>R(null),onAsk:Z}),jsx(Me,{})]})}i(hg,"DashboardBody");function xa({label:e,onPress:t,testID:r}){let o=Sa();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(Ir,{})]})}i(xa,"ActionRow");function Rg({request:e,petName:t,onOpen:r,onAsk:o}){let n=be(),l=Sa(),s=e.clinicName?.trim()||Hr.title(t),c=kn(e),a=jsxs(View,{style:l.inProgressInner,children:[jsxs(View,{style:l.inProgressHead,children:[jsx(m,{style:l.inProgressTitle,children:s}),r?jsx(Ir,{}):null]}),jsx(Oo,{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:Hr.a11y(t),children:[r?jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Hr.openA11y(t,c),testID:"dashboard-in-progress-open",children:a}):a,o?jsx(re,{label:Hr.ask,kind:"ask",accessibilityLabel:Hr.askA11y,onPress:o,testID:"dashboard-in-progress-ask"}):null]})}i(Rg,"InProgressCard");function Sa(){let e=V();return useMemo(()=>vg(e),[e])}i(Sa,"useLocalStyles");function vg(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(vg,"makeLocalStyles");var Vo=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function bd(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(bd,"toMillis");function hd(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:Pl(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=bd(r.at),l=bd(o.at);return n===null&&l===null?Vo[r.kind]-Vo[o.kind]:n===null?1:l===null?-1:l!==n?l-n:Vo[r.kind]-Vo[o.kind]}))}i(hd,"buildTimelineRows");var kg=300,Tg=i((e,t)=>e.getTimeline(t),"readTimeline"),_g=i(e=>e.isEmpty,"timelineEmpty");var Pg=i(e=>e.contributions.length===0,"contributionsEmpty");function xd({petRef:e,style:t,onBack:r}){let o=$t(e,Tg,_g);return jsx(Cd,{state:o,style:t,onBack:r,header:jsx(et,{title:fe.timeline,onBack:ln(r),testID:"timeline-header"}),loading:jsx(Vl,{testID:"timeline-loading"}),empty:jsx(Qe,{variant:"no_records",testID:"timeline-empty"}),render:n=>jsx(Ag,{timeline:n})})}i(xd,"EverfurRecordsTimeline");function wd({petRef:e,docId:t,style:r,onBack:o}){let n=useCallback((c,a)=>c.getDocumentContributions(a,t),[t]),l=$t(e,n,Pg,t),s=l.value?.document?.title?.trim()||fe.uploadedDocument;return jsx(Cd,{state:l,style:r,onBack:o,header:jsx(et,{title:s,onBack:ln(o),testID:"contributions-header"}),empty:jsx(Qe,{variant:"no_records",testID:"contributions-empty"}),render:c=>jsx(Og,{view:c})})}i(wd,"EverfurDocumentContributions");function Cd({state:e,style:t,header:r,loading:o,empty:n,render:l,onBack:s}){let c=ka();return jsx(Ne,{capability:"records",style:t,...Be(ln(s),Ze),children:jsxs(View,{style:[c.container,t],children:[r??null,jsx(View,{style:c.body,children:Ig(e,l,c,o,n)}),jsx(Me,{})]})})}i(Cd,"DepthSurface");function Ig(e,t,r,o,n){switch(e.status){case "loading":return o??jsx(Dg,{styles:r});case "empty":return n??jsx(View,{style:r.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:de.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(Ig,"renderState");function Dg({styles:e}){let[t,r]=useState(false);return useEffect(()=>{let o=setTimeout(()=>r(true),kg);return ()=>clearTimeout(o)},[]),jsx(View,{style:e.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:de.loading,children:t?jsx(ActivityIndicator,{}):null})}i(Dg,"LoadingState");function Ag({timeline:e}){let t=ka(),r=hd(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(Ag,"TimelineBody");function Og({view:e}){let t=ka();return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.listContent,accessibilityLabel:de.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:Ur(r.value,r.unit)}),r.observedAt?jsx(m,{style:t.rowDetail,children:Q(r.observedAt)}):null]},r.key))})]})}i(Og,"ContributionsBody");function ka(){let e=V();return useMemo(()=>Lg(e),[e])}i(ka,"useStyles");function Lg(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c}=n,a=i((x,y)=>Math.round(x*y),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl*3+r.xl,p=r.xxl+r.md,g=e.brightness==="dark"?t.errorRed:t.danger,h=ot(l.recordCard),R=i((x,y,f,E="regular")=>({..._(e,E),fontSize:x,lineHeight:a(x,y),color:f}),"text"),v=i((x,y,f,E="regular")=>({...R(x,y,f,E),...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,g),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:Ai},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(Lg,"makeStyles");function Ta(e,t={}){let r=cr(),{userRef:o}=ke(),n=t.now??Date.now,[l,s]=useState(null),[c,a]=useState(true),[d,u]=useState(null),[p,g]=useState(null),h=p===true,[R,v]=useState({}),[x,y]=useState(false),[f,E]=useState(null),[b,C]=useState(false),[D,S]=useState(false),k=Bn(e),I=useRef(0),G=useRef(true),z=useCallback(async()=>{let T=I.current+=1;if(a(true),u(null),o===null){s(null),a(false);return}let O=await r.listShares(e);T!==I.current||!G.current||(O.ok?(s(O.value),g(true)):xr(O.error)?(s(null),g(false)):(s(null),u(O.error),Ed(O)&&g(true)),a(false));},[r,e,o]);useEffect(()=>(G.current=true,z(),()=>{G.current=false,I.current+=1;}),[z]);let Y=useRef(k);useEffect(()=>{Y.current!==k&&(Y.current=k,v({}),S(true),z());},[k,z]);let H=useCallback(async()=>{y(true);let T=await r.createShare(e);return G.current&&(y(false),T.ok?(v(O=>({...O,[T.value.shareId]:T.value.shareUrl})),z()):xr(T.error)?g(false):rr(T.error)&&S(true)),T},[r,e,z]),Z=useCallback(async T=>{E(T);let O=await r.revokeShare(e,T);return G.current&&(E(null),z()),O},[r,e,z]),oe=useCallback(async()=>{C(true);let T=await r.getPdfLink(e);return G.current&&(C(false),!T.ok&&rr(T.error)&&S(true)),T},[r,e]),Ee=useCallback(()=>{S(false),z();},[z]),U=useMemo(()=>Il(l??[],R,n()),[l,R,n]),w=c?"loading":d!==null?"error":U.length===0?"empty":"populated";return useMemo(()=>({status:w,rows:U,available:h,consentRequired:D,error:d,creating:x,revokingId:f,preparingPdf:b,createLink:H,revoke:Z,pdfLink:oe,refresh:Ee}),[w,U,h,D,d,x,f,b,H,Z,oe,Ee])}i(Ta,"useRecordShares");function Ed(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(Ed,"answeredBehindGate");function Sd(e){return e.available||e.status!=="empty"}i(Sd,"sharesListShown");function _a(e){let t=cr(),{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&&xr(a.error)?l({scope:o,lit:false}):Ed(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(_a,"useRecordsDepthProbe");function Pa(e){let t=cr(),o=_a(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(Pa,"useRecordPdfLink");var Tt=K.document,_d=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),Fg=i((e,t)=>e.getRecordDepth(t),"readDepth"),Ng=i(e=>!e.available,"depthEmpty");function Ia(e){let{style:t,renderPending:r,...o}=ze(e,["onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(Bg,{...o,style:t})})}i(Ia,"EverfurRecordDocument");function Mg(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(Mg,"documentIsEmpty");function Bg({petRef:e,petName:t,controller:r,consentVersion:o,onBack:n,onOpenUrl:l,style:s}){let c=be(),a=Pd(),d=V(),u=yt(r?{petRef:e,controller:r}:{petRef:e}),p=$t(e,Fg,Ng),g=Pa(e),h=useMemo(()=>zr(o,u.consent),[o,u.consent]),R=useMemo(()=>Xr(u,o),[u,o]),v=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,x=u.record,y=i(()=>{g.pdfLink().then(b=>{if(!b.ok)return;Tr(l??(D=>Linking.openURL(D)),b.value.downloadUrl,"record_pdf");});},"download"),f,E=false;if(u.status==="loading"||p.status==="loading"&&x!==null)f=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 b=wr(u,h);f=b.kind==="error"||b.kind==="pet_not_found"?jsx(Qe,{variant:wt(b.error),message:b.error.displayMessage,onAction:b.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):Qr(u,R,h);}else x===null||Mg(x,v)?f=jsx(View,{style:a.centered,testID:"record-document-empty",children:jsx(m,{style:a.emptyText,children:Tt.empty})}):(E=true,f=jsx(Hg,{record:x,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:g.available&&E?jsx(Pressable,{onPress:y,disabled:g.preparing,accessibilityRole:"button",accessibilityLabel:Tt.download,accessibilityState:{disabled:g.preparing,busy:g.preparing},hitSlop:8,style:a.download,testID:"record-document-download",children:g.preparing?jsx(ActivityIndicator,{size:"small",color:d.color.brandInk}):jsx(El,{})}):void 0}),g.error?jsx(m,{style:[c.errorText,a.inset],accessibilityRole:"alert",children:g.error.displayMessage}):null,jsx(View,{style:c.body,children:f}),jsx(Me,{})]})}i(Bg,"DocumentBody");function Hg({record:e,depth:t,petName:r,wordmark:o}){let n=Pd(),l=useMemo(()=>{let a=[],d=new Map;for(let g of e.entities){let h=g.category.trim();if(h.length===0)continue;let R=d.get(h);R===void 0?(a.push(h),d.set(h,[g])):R.push(g);}let u=_d.filter(g=>a.includes(g)),p=a.filter(g=>!_d.includes(g));return [...u,...p].map(g=>({type:g,rows:d.get(g)??[]}))},[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=Xt(a.latest.status),p=Gc(a.points[a.points.length-1]??null),g=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:[g!=="-"?jsx(m,{style:[n.rowValue,u.outOfRange?n.rowValueAlert:null],children:g}):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(Fr(a),d.map((u,p)=>{let g=[Ur(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}),g?jsx(m,{style:n.rowMeta,children:g}):null]})},u.key)}),`record-document-${a}`)),e.forwardLooking.length>0?c(Tt.upcomingCare,e.forwardLooking.map((a,d)=>{let u=_n(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:Dr(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:$r(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(Hg,"RecordDocument");function Pd(){let e=V();return useMemo(()=>Ug(e),[e])}i(Pd,"useLocalStyles");function Ug(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(Ug,"makeLocalStyles");function Ad({petRef:e,onClose:t,onNavigate:r,onOpenUrl:o,onCopy:n}){let l=Yg(),s=be(),c=Ta(e),[a,d]=useState(null),[u,p]=useState(null),g=c.available&&!c.consentRequired,h=i((f,E)=>{Tr(o??(C=>Linking.openURL(C)),f,E).then(C=>{C.ok||d(ue.toasts.shareSheet);});},"open"),R=i(()=>{d(null),c.createLink().then(f=>{f.ok?h(f.value.shareUrl,"share_link"):d(no(f.error,"create"));});},"onCreateLink"),v=i(()=>{d(null),c.pdfLink().then(f=>{f.ok?h(f.value.downloadUrl,"record_pdf"):d(no(f.error,"download"));});},"onDownload"),x=i(f=>{!n||f.shareUrl===null||Tr(n,f.shareUrl).then(E=>d(E.ok?ue.toasts.copied:ue.toasts.copyFailed));},"onCopyRow"),y=i(f=>{c.revoke(f).then(E=>{p(null),d(E.ok?ue.toasts.turnedOff:no(E.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:ue.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:ue.title}),jsx(m,{style:l.helper,children:ue.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:ue.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:ue.viewDocument,onPress:()=>{t(),r({name:"document"});},testID:"share-view-document"}):null,g?jsx(re,{label:c.creating?ue.creatingLink:ue.createLink,kind:"outline",busy:c.creating,onPress:R,testID:"share-create-link"}):null,g?jsx(re,{label:c.preparingPdf?ue.preparingPdf:ue.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:ue.consentOffTitle}),jsx(m,{style:l.stateBody,children:ue.consentOffBody}),jsx(re,{label:ue.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,Sd(c)?jsxs(View,{style:l.section,children:[jsx(m,{style:l.sectionLabel,accessibilityRole:"header",children:ue.activeLinks}),c.status==="loading"?jsx(zl,{testID:"share-record-loading"}):c.status==="error"?jsxs(View,{style:l.stateCard,testID:"share-record-error",children:[jsx(m,{style:l.stateTitle,children:ue.errorTitle}),jsx(m,{style:l.stateBody,children:ue.errorBody}),jsx(re,{label:ue.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:ue.emptyTitle}),jsx(m,{style:l.stateBody,children:ue.emptyBody})]}):jsx(View,{style:l.list,children:c.rows.map(f=>jsxs(View,{style:l.row,testID:`share-row-${f.shareId}`,children:[jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:f.a11yLabel,children:[jsxs(View,{style:l.statusLine,children:[jsx(View,{style:[l.statusDot,{backgroundColor:f.active?l.active.color:l.inactive.color}],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:l.status,children:f.statusLabel}),jsx(m,{style:l.expiry,children:f.expiryLabel})]}),f.createdLabel?jsx(m,{style:l.created,children:f.createdLabel}):null]}),f.shareUrl!==null&&!n?jsx(m,{selectable:true,style:l.url,testID:`share-url-${f.shareId}`,children:f.shareUrl}):null,u===f.shareId?jsxs(View,{style:l.confirm,testID:`share-revoke-confirm-${f.shareId}`,children:[jsx(m,{style:l.confirmText,children:ue.confirmTurnOff}),jsxs(View,{style:l.rowActions,children:[jsx(re,{label:c.revokingId===f.shareId?ue.turningOff:ue.turnOff,kind:"danger",busy:c.revokingId===f.shareId,onPress:()=>y(f.shareId),testID:`share-revoke-do-${f.shareId}`}),jsx(re,{label:ue.keep,kind:"outline",disabled:c.revokingId===f.shareId,onPress:()=>p(null),testID:`share-revoke-cancel-${f.shareId}`})]})]}):jsxs(View,{style:l.rowActions,children:[n?jsx(re,{label:ue.copyLink,kind:"outline",disabled:f.shareUrl===null,accessibilityLabel:ue.copyLinkA11y(f.actionContext),onPress:()=>x(f),testID:`share-copy-${f.shareId}`}):null,jsx(re,{label:ue.turnOff,kind:"danger",accessibilityLabel:ue.turnOffA11y(f.actionContext),onPress:()=>p(f.shareId),testID:`share-ask-revoke-${f.shareId}`})]})]},f.shareId))})]}):null]}),jsx(View,{style:s.inset})]})]})})}i(Ad,"ShareSheet");function Yg(){let e=V();return useMemo(()=>Kg(e),[e])}i(Yg,"useStyles");function Kg(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(Kg,"makeStyles");var Jg=i((e,t)=>e.getRecordDepth(t),"readDepth"),Zg=i(e=>!e.available,"depthEmpty");function La(e){let{style:t,renderPending:r,...o}=ze(e,["onNavigate","onBack","onAsk"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(eb,{...o,style:t})})}i(La,"EverfurRecordDetail");function eb({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:s,onOpenUrl:c,onCopy:a,style:d}){let u=be(),p=tb(),g=yt(r?{petRef:e,controller:r}:{petRef:e}),h=$t(e,Jg,Zg),R=da(e),v=_a(e),[x,y]=useState(false),f=useMemo(()=>zr(o,g.consent),[o,g.consent]),E=useMemo(()=>Xr(g,o),[g,o]),b=h.value!==null&&!h.value.withheld&&h.value.available?h.value:null,C=g.record,D=i(()=>{g.refresh(),h.refresh();},"retry"),S=n!==void 0||v.lit===true,k;if(g.status==="loading"||h.status==="loading"&&C!==null&&!C.isEmpty)k=jsx(ao,{testID:"everfur-record-loading"});else if(g.status==="error"){let I=wr(g,f);k=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"}):Qr(g,E,f);}else if(C===null||C.isEmpty){let I=b?.completeness?.documentsInReview??0;k=jsxs(ScrollView,{contentContainerStyle:u.content,testID:"everfur-record-empty",children:[jsx(Qe,{variant:"no_records",message:I>0?K.inReview(I):void 0}),jsx(vr,{disclaimer:C?.disclaimer??""})]});}else k=jsx(ScrollView,{contentContainerStyle:p.content,testID:"everfur-record",children:jsx(Io,{record:C,depth:b,petName:t,onNavigate:n,onAsk:s,factEdit:R})});return jsxs(View,{style:[u.root,d],children:[jsx(et,{title:K.title,onBack:l,testID:"everfur-record-header",right:S||n?jsxs(Fragment,{children:[n?jsx(Pressable,{onPress:()=>n({name:"clinicBatch"}),accessibilityRole:"button",accessibilityLabel:K.requestClinicsA11y,hitSlop:8,style:p.share,testID:"everfur-record-request-clinics",children:jsx(Cl,{})}):null,S?jsx(Pressable,{onPress:()=>y(true),accessibilityRole:"button",accessibilityLabel:K.shareA11y,hitSlop:8,style:p.share,testID:"everfur-record-share",children:jsx(wl,{})}):null]}):void 0}),jsx(View,{style:u.body,children:k}),x?jsx(Ad,{petRef:e,onClose:()=>y(false),onNavigate:n,...c?{onOpenUrl:c}:{},...a?{onCopy:a}:{}}):null,jsx(Me,{})]})}i(eb,"RecordBody");function tb(){let e=V();return useMemo(()=>rb(e),[e])}i(tb,"useLocalStyles");function rb(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(rb,"makeLocalStyles");function qa(e){let{style:t,renderPending:r,...o}=ze(e,["onNavigate","onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(ab,{...o,style:t})})}i(qa,"EverfurRecordsUpload");function ab({petRef:e,petName:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:s,style:c}){let a=be(),d=Nd(),{runtime:u}=ke(),p=yt(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),g=Sn(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(za,{records:p,requestId:null,onPickDocument:o,canUpload:g,onDone:l?h=>l({name:"request",requestId:h}):void 0})]}),jsx(Me,{})]})}i(ab,"UploadBody");function za({records:e,requestId:t,onPickDocument:r,canUpload:o,onDone:n}){let l=be(),s=Nd(),[c,a]=useState(null),[d,u]=useState(0),p=useRef(t),g=useRef([]),h=e.uploadQueue.filter(b=>b.status!=="skipped"),R=h.filter(b=>b.status==="done").length,v=h.filter(b=>b.status==="failed").length,x=!e.isUploading&&d>0,y=useCallback(async b=>{if(b.length===0)return;a(null);let C=p.current;if(C===null){let S=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!S.ok){a(rt.errors.start);return}C=S.value.id,p.current=C;}u(S=>S+1);let D=await e.uploadDocuments(C,b);g.current=D.flatMap((S,k)=>S.status==="failed"&&b[k]!==void 0?[b[k]]:[]);},[e]),f=useCallback(()=>{!r||!o||Tr(r).then(b=>{if(!b.ok){a(rt.errors.startPlain);return}let C=b.value;C!==null&&y(Array.isArray(C)?C:[C]);});},[r,o,y]),E=useCallback(()=>{y(g.current);},[y]);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(md,{records:e}),e.isUploading?jsx(View,{style:s.uploadingRow,children:jsx(m,{style:s.progressText,children:rt.uploading(R,h.length)})}):x?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:E,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:f,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:f,testID:"records-upload-choose"})]})}i(za,"UploadRecordCard");function Nd(){let e=V();return useMemo(()=>sb(e),[e])}i(Nd,"useLocalStyles");function sb(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(sb,"makeLocalStyles");function Na(e){let{style:t,renderPending:r,...o}=ze(e,["onNavigate","onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(yb,{...o,style:t})})}i(Na,"EverfurRecordsRequest");function yb({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:g}=ke(),h=yt(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),R=h.requests.find(f=>f.id===t)??null,v=Sn(o)&&(r!==void 0||n!==void 0||Fn(u.registry.services.uploadTransport)),x=R?ho(R):"",y;return h.status==="loading"?y=jsx(Ll,{testID:"records-request-loading"}):h.status==="error"&&h.error?y=jsx(Qe,{variant:wt(h.error),message:h.error.displayMessage,onAction:h.error.retryable?h.refresh:void 0,testID:"records-request-error"}):R===null?y=jsx(Qe,{variant:"no_requests",testID:"records-request-missing"}):p===null?y=jsx(Qe,{variant:"error",testID:"records-request-error"}):y=jsx(fb,{request:R,records:h,canUpload:v,onPickDocument:o,onNavigate:l,nowMs:a},JSON.stringify([p,g,R.id])),jsxs(View,{style:[d.root,c],children:[jsx(et,{title:x,onBack:s,testID:"records-request-header"}),jsx(KeyboardAvoidingView,{behavior:"padding",style:d.body,children:y}),jsx(Me,{})]})}i(yb,"RequestBody");function fb({request:e,records:t,canUpload:r,onPickDocument:o,onNavigate:n,nowMs:l}){let s=be(),c=gb(),a=V(),d=ld({request:e,onRecovered:t.refresh,canUpload:r},Mt()),[u,p]=useState(null),[g,h]=useState(false),[R,v]=useState(null),x=useRef(true);useEffect(()=>(x.current=true,()=>{x.current=false;}),[]);let y=d.request,f=l??Date.now(),E=y.status==="published",b=y.status==="published"||y.status==="failed"||y.status==="revoked",C=fi(y),D=y.wireStatus==="clinic_responded_no_records",S=js(y,f),k=yi(y,f),I=b?null:y.waitingExpectation?.trim()||null,G=Ro(y),z=$s(y),Y=d.canConvert,H=b&&!E,Z=d.error!==null&&u!==null&&u!=="start"?u==="revoke"?ge.errors.cancel:ge.errors[u]:null,oe=i((U,w)=>{p(U),w();},"run"),Ee=i(()=>{g||(h(true),v(null),t.createRequest(`records-upload-${Date.now().toString(36)}`).then(U=>{if(x.current){if(h(false),!U.ok){v(ge.errors.start);return}n?.({name:"request",requestId:U.value.id});}}));},"startFresh");return jsxs(ScrollView,{contentContainerStyle:c.content,keyboardShouldPersistTaps:"handled",testID:`records-request-${y.id}`,children:[jsx(Oo,{request:y}),y.status==="awaiting_upload"?jsx(za,{records:t,requestId:y.id,onPickDocument:o,canUpload:r}):null,y.statusLabel.length>0?jsx(View,{style:s.statusCard,accessibilityRole:"summary",children:jsx(m,{style:s.statusText,children:y.statusLabel})}):null,I&&!S?jsx(View,{style:s.infoNote,accessibilityRole:"summary",children:jsx(m,{style:s.infoNoteText,children:I})}):y.wireStatus==="awaiting_response"&&!S?jsx(View,{style:s.infoNote,accessibilityRole:"summary",children:jsx(m,{style:s.infoNoteText,children:ge.awaitingNote})}):null,S?jsx(View,{style:s.cautionNote,accessibilityRole:"summary",testID:"records-request-waiting-banner",children:jsx(m,{style:s.cautionNoteText,children:ge.waitingBanner(k)})}):null,E&&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,C?c.failureCritical:c.failureCaution],accessibilityRole:"summary",testID:"records-failure-card",children:[jsx(m,{style:[c.failureTitle,C?c.failureTitleCritical:c.failureTitleCaution],children:Us(y)}),y.canUpdateClinicEmail!==true&&y.canRetrySend!==true?jsx(m,{style:s.rowDetail,children:ge.nextStep}):null,y.canUpdateClinicEmail===true?jsxs(View,{style:c.emailBlock,children:[jsx(m,{style:s.fieldLabel,children:Lt.email}),jsx(qe,{style:s.field,accessibilityLabel:Lt.email,placeholder:Lt.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:Lt.updateEmail,accessibilityLabel:Lt.updateEmailA11y,disabled:!d.canUpdateEmail,busy:d.busy&&u==="email",onPress:()=>oe("email",d.updateEmail),testID:"records-failure-update-email"})]}):null,y.canRetrySend===true?jsx(re,{label:Lt.retry,kind:"outline",accessibilityLabel:Lt.retryA11y,disabled:!d.canRetry,busy:d.busy&&u==="retry",onPress:()=>oe("retry",d.retry),testID:"records-failure-retry-send"}):null,y.canRetrySend===true&&d.hasEmailEdit?jsx(m,{style:s.rowDetail,children:Lt.retryHint}):null,Z&&(u==="email"||u==="retry")?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:Z})}):null]}):null,(C||D)&&n?jsx(re,{label:ge.tryAnotherClinic,kind:"outline",accessibilityLabel:ge.tryAnotherClinicA11y,onPress:()=>n({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,G!==null?jsxs(View,{style:c.callBlock,children:[jsx(yd,{call:G,prompt:y.statusLabel}),y.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,Y?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,H?jsxs(View,{style:c.block,children:[jsx(re,{label:g?ge.freshUploadStarting:ge.freshUpload,kind:C||D?"outline":"primary",busy:g,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,y.canRevoke===true?d.confirmingRevoke?jsxs(View,{style:c.block,testID:"records-revoke-confirm",children:[jsx(m,{style:c.confirmTitle,accessibilityRole:"header",children:Lt.cancelQuestion}),jsx(m,{style:s.bodyText,children:Lt.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:Lt.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(fb,"RequestDetail");function gb(){let e=V();return useMemo(()=>bb(e),[e])}i(gb,"useLocalStyles");function bb(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(bb,"makeLocalStyles");function Md(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:g,renderPending:h,onOpenUrl:R,onCopy:v,onAsk:x,location:y}=ze(e,["onExit"]),[f,E]=useReducer(ai,u,Wn),b=Gn(f),C=f.stack.length;useEffect(()=>{let Y=i(()=>C<=1?false:(E({type:"pop"}),true),"onBackPress"),H=BackHandler.addEventListener("hardwareBackPress",Y);return ()=>{H.remove();}},[C]);let D=useCallback(Y=>E({type:"navigate",screen:Y}),[]),S=useMemo(()=>Yn(f).handled?()=>E({type:"pop"}):p,[f,p]),k={onNavigate:D,...S?{onBack:S}:{},...r!==void 0?{petName:r}:{},...R?{onOpenUrl:R}:{},...v?{onCopy:v}:{},...x?{onAsk:x}:{},...y?{location:y}:{}},I={...o?{controller:o}:{},...c!==void 0?{consentVersion:c}:{}},G={...l?{onPickDocument:l}:{},...s?{uploadTransport:s}:{}},z=h?{renderPending:h}:{};switch(b.name){case "dashboard":return jsx(Ea,{petRef:t,...k,...I,...z,style:g});case "request":return jsx(Na,{petRef:t,requestId:b.requestId,...k,...I,...G,...z,style:g});case "timeline":return jsx(xd,{petRef:t,...k,style:g});case "record":return jsx(La,{petRef:t,...k,...I,...z,style:g});case "document":return jsx(Ia,{petRef:t,...k,...I,...z,style:g});case "contributions":return jsx(wd,{petRef:t,docId:b.docId,...k,style:g});case "clinicPicker":return jsx(Oi,{petRef:t,...k,...n?{controller:n}:{},...o?{recordsController:o}:{},style:g});case "clinicBatch":return jsx(Ki,{petRef:t,petName:r??"",ownerName:a??"",...S?{onClose:S}:{},onCreated:()=>E({type:"navigate",screen:{name:"dashboard"}}),...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:g});case "consent":return jsx(oa,{petRef:t,clinic:b.clinic,...k,...a!==void 0?{ownerName:a}:{},...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:g});case "upload":return jsx(qa,{petRef:t,...k,...o?{controller:o}:{},...G,...z,style:g});default:return yr(b)}}i(Md,"EverfurRecordsFlow");var Cb=Md;function Tb(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",...Be(e.onClose,$.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:de.sessionRequired}):jsx(_b,{...ze(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(Tb,"EverfurClinicRequest");function _b(e){let t=Mt(),[r,o]=useState(null),n=useCallback(async()=>r===null?null:{signaturePngBase64:r},[r]),l=Nl(e,e.controller??t,e.onCaptureSignature??n),s=e.onCaptureSignature!==void 0||r!==null,c=V(),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,g,h=false)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:p,accessibilityState:{disabled:h},disabled:h,onPress:g,style:[a,{justifyContent:"center",opacity:h?.5:1}],children:jsx(m,{style:d,children:p})}),"button");return jsxs(View,{accessibilityLabel:$.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:$.title}),jsx(m,{style:d,children:e.petName}),l.created?jsx(m,{accessibilityLiveRegion:"polite",style:d,children:l.created.statusLabel||de.records}):jsxs(Fragment,{children:[jsx(m,{style:d,children:$.ownerName}),jsx(qe,{accessibilityLabel:$.ownerName,style:a,value:l.ownerName,maxLength:200,editable:!l.busy,autoComplete:"name",onChangeText:l.setOwnerName}),jsx(m,{style:d,children:$.clinic}),jsx(qe,{accessibilityLabel:$.clinic,style:a,value:l.query,placeholder:$.placeholder,placeholderTextColor:c.color.text.placeholder,maxLength:200,editable:!l.busy,onChangeText:l.setQuery}),u($.search,()=>{l.search();},l.busy||l.searching||l.query.trim().length<2),l.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:de.loading}),l.recent.length>0&&jsx(m,{accessibilityRole:"header",style:d,testID:"records-clinic-recent-label",children:$.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:$.email}),jsx(qe,{accessibilityLabel:$.email,style:a,value:l.email,placeholder:$.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:$.scopeHeading}),l.copy?jsx(m,{style:d,children:l.query.trim()&&l.ownerName.trim()?l.scope??q("internalError").displayMessage:de.consentRequired}):!l.error&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:de.loading}),!e.onCaptureSignature&&jsx(Vr,{onChange:o,disabled:l.busy}),!s&&jsx(m,{accessibilityRole:"alert",style:d,children:$.missingSignature}),l.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:d,children:l.error.displayMessage}),!l.copy&&l.error&&u(de.retry,l.retryCopy),u(l.busy?$.sending:$.send,()=>{l.submit();},l.busy||!l.ready||!s)]}),e.onClose&&u($.cancel,e.onClose,l.busy),jsx(Me,{})]})}i(_b,"ClinicRequestBody");
|
|
4
|
+
export{Oi as EverfurClinicPicker,Tb as EverfurClinicRequest,Ki as EverfurClinicRequestBatch,La as EverfurRecordDetail,Ia as EverfurRecordDocument,Cb as EverfurRecords,oa as EverfurRecordsConsent,Ea as EverfurRecordsDashboard,Md as EverfurRecordsFlow,Na as EverfurRecordsRequest,qa as EverfurRecordsUpload,Br as RECORDS_CLINIC_BATCH_MAX,as as RECORDS_TERMINAL,Dn as REQUEST_TIMELINE_TITLES,Vr as SignaturePad,ca as applyFactOverlay,ga as buildRequestTimeline,Gn as currentRecordsScreen,pi as deriveRecordsDashboardState,Wn as initialRecordsNav,Eo as isFactEditable,Mr as isTerminalStatus,Xn as pickPetRecordsRequest,Yn as popRecordsNav,ni as pushRecordsNav,pr as recordsDenialReasonOf,ai as recordsNavReducer,qi as registerRnSignature,oi as replaceRecordsNav,ii as resetRecordsNav,Ro as selectClinicCall,mi as selectDashboardView,kn as selectPrimaryLabel,af as selectRequestList,ho as selectRequestTitle,Ts as transitionRecordsNav,yt as useEverfurRecords,Mt as useEverfurRecordsClinic,hi as useEverfurRecordsClinicBatch,da as useRecordFactEdit,Pa as useRecordPdfLink,Ta as useRecordShares,ta as useRecordsMarkers};
|