@everfur/sdk 0.12.0 → 0.13.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 +174 -0
- package/README.md +2 -1
- package/dist/{Chat-BOG0SXKV.d.cts → Chat.d-DUNTfzqC.d.ts} +170 -8
- package/dist/{Chat-CIolBgjJ.d.ts → Chat.d-Dts8u_1a.d.cts} +170 -8
- package/dist/{DepthViews-BR6VQ3Ta.d.cts → DepthViews.d-BIp599lz.d.cts} +1 -1
- package/dist/{DepthViews-280t3BcQ.d.ts → DepthViews.d-BMU2jFPw.d.cts} +1 -1
- package/dist/{DepthViews-DlBuFsgN.d.ts → DepthViews.d-Ce2Zhnrb.d.ts} +1 -1
- package/dist/{DepthViews-BTbF_DJY.d.cts → DepthViews.d-CubkMPbU.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-10s3HJCt.d.cts → ErrorPolicyPort.d-68yrE3BE.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-C3nNSS_j.d.ts → ErrorPolicyPort.d-DirW9hgO.d.cts} +1 -1
- package/dist/{EverfurError-DeBqRpQV.d.cts → EverfurError.d-8NHtlgzA.d.cts} +11 -1
- package/dist/{EverfurError-DeBqRpQV.d.ts → EverfurError.d-8NHtlgzA.d.ts} +11 -1
- package/dist/{EverfurResult-ClPTS0P2.d.ts → EverfurResult.d-BFH-3s6E.d.cts} +1 -1
- package/dist/{EverfurResult-COlXj1wq.d.cts → EverfurResult.d-D_-254ZY.d.ts} +1 -1
- package/dist/{IntakeMedia-BH0fYDT2.d.cts → IntakeMedia.d-4a89XrP7.d.ts} +1 -1
- package/dist/{IntakeMedia-B-_vA9ZB.d.cts → IntakeMedia.d-DGxrhgIW.d.ts} +1 -1
- package/dist/{IntakeMedia-CIoTXAWs.d.ts → IntakeMedia.d-DUPR4lVM.d.cts} +1 -1
- package/dist/{IntakeMedia-Bavl7E4Z.d.ts → IntakeMedia.d-JJCUvQu7.d.cts} +1 -1
- package/dist/LifecyclePort.d-Cr1p33a7.d.cts +23 -0
- package/dist/LifecyclePort.d-Cr1p33a7.d.ts +23 -0
- package/dist/{PhotoController-vzY5bfY_.d.ts → PhotoController.d-BzCJOE7e.d.cts} +2 -2
- package/dist/{PhotoController-3l7MT9jA.d.cts → PhotoController.d-D0XiUUOl.d.ts} +2 -2
- package/dist/animations/index.cjs +5 -1
- package/dist/animations/index.d.cts +24 -24
- package/dist/animations/index.d.ts +24 -24
- package/dist/animations/index.js +5 -1
- package/dist/{attachments-CGxvnYu4.d.ts → attachments.d-Bp2qbHxn.d.cts} +22 -26
- package/dist/{attachments-CWNj1ZkM.d.ts → attachments.d-D1yhJjcZ.d.ts} +4 -4
- package/dist/{attachments-waXcJWCp.d.cts → attachments.d-DisnvB9R.d.cts} +4 -4
- package/dist/{attachments-B6h4cJU-.d.cts → attachments.d-Djy9z_0Z.d.ts} +22 -26
- package/dist/{bookingCopy-CjPKeg75.d.ts → bookingCopy.d-BJF6gd1A.d.ts} +24 -9
- package/dist/{bookingCopy-8aEU6ZmR.d.cts → bookingCopy.d-BlBmhAJc.d.cts} +24 -9
- package/dist/{branding-DJf4h12Q.d.ts → branding.d-DI8S400y.d.cts} +9 -2
- package/dist/{branding-BCfwLj0h.d.cts → branding.d-OIGLbQeM.d.ts} +9 -2
- package/dist/{callRoom-BhIdadyV.d.cts → callRoom.d-B1DoYdJe.d.cts} +1 -1
- package/dist/{callRoom-B92eH_ij.d.ts → callRoom.d-Dqm1rUqT.d.ts} +1 -1
- package/dist/{casesRepository-CGdhvzTu.d.cts → casesRepository.d-CT2LTicS.d.cts} +3 -3
- package/dist/{casesRepository-ZG9Sg0e4.d.ts → casesRepository.d-UsWOz9bv.d.ts} +3 -3
- package/dist/chat/index.cjs +132 -57
- package/dist/chat/index.d.cts +18 -16
- package/dist/chat/index.d.ts +18 -16
- package/dist/chat/index.js +133 -58
- package/dist/client/index.cjs +15 -10
- package/dist/client/index.d.cts +19 -18
- package/dist/client/index.d.ts +19 -18
- package/dist/client/index.js +15 -10
- package/dist/{config-B0p6Lygh.d.cts → config.d-BR3DT9ho.d.cts} +3 -3
- package/dist/{config-DmFAZJOx.d.ts → config.d-Dy6igYlH.d.ts} +3 -3
- package/dist/consent/index.cjs +5 -1
- package/dist/consent/index.d.cts +10 -10
- package/dist/consent/index.d.ts +10 -10
- package/dist/consent/index.js +5 -1
- package/dist/{context-BNreNLtL.d.ts → context.d-Cwks0p3C.d.cts} +15 -15
- package/dist/{context-BgS2a57J.d.cts → context.d-QcCgguzA.d.ts} +15 -15
- package/dist/{copy-DLJriGQS.d.ts → copy.d-CiMn2IIt.d.ts} +6 -6
- package/dist/{copy-lWp-Lkv5.d.cts → copy.d-DLJTyRfT.d.cts} +6 -6
- package/dist/core/index.cjs +17 -13
- package/dist/core/index.d.cts +33 -29
- package/dist/core/index.d.ts +33 -29
- package/dist/core/index.js +17 -13
- package/dist/{depth-BYb3RXoA.d.cts → depth.d-CjPGVPDL.d.cts} +9 -115
- package/dist/{depth-COz-sSG5.d.ts → depth.d-OSALbYM7.d.ts} +9 -115
- package/dist/{entitlementRepository-D-Lse67w.d.cts → entitlementRepository.d-CVQa1DA1.d.cts} +10 -5
- package/dist/{entitlementRepository-CrTOP_-o.d.ts → entitlementRepository.d-Cf3LbTwD.d.ts} +10 -5
- package/dist/features.d-fNsGcg0R.d.cts +108 -0
- package/dist/features.d-fNsGcg0R.d.ts +108 -0
- package/dist/focus.d-DMg2ngHI.d.ts +1178 -0
- package/dist/focus.d-az9cqUz3.d.cts +1178 -0
- package/dist/health-plan/index.cjs +370 -0
- package/dist/health-plan/index.d.cts +251 -0
- package/dist/health-plan/index.d.ts +251 -0
- package/dist/health-plan/index.js +370 -0
- package/dist/idempotency.d-D461_DPD.d.cts +910 -0
- package/dist/idempotency.d-WpXx9zQo.d.ts +910 -0
- package/dist/{identity-Cw07BKZp.d.ts → identity.d-60LeJt_s.d.cts} +3 -3
- package/dist/{identity-DFVGYn1o.d.cts → identity.d-DzTijonw.d.ts} +3 -3
- package/dist/index.cjs +141 -66
- package/dist/index.d.cts +31 -29
- package/dist/index.d.ts +31 -29
- package/dist/index.js +142 -67
- package/dist/{models-A4A5S7AG.d.cts → models.d-BagXhafD.d.ts} +8 -3
- package/dist/{models-CnXY5LuO.d.ts → models.d-BnLm3VAA.d.cts} +8 -3
- package/dist/notifications/index.cjs +5 -1
- package/dist/notifications/index.d.cts +9 -9
- package/dist/notifications/index.d.ts +9 -9
- package/dist/notifications/index.js +5 -1
- package/dist/optInView.d-CEyHR6PK.d.cts +325 -0
- package/dist/optInView.d-acKpV8V2.d.ts +325 -0
- package/dist/parse.d-C8CXyS58.d.ts +210 -0
- package/dist/parse.d-tEzufgJX.d.cts +210 -0
- package/dist/{pets-BYALZTSu.d.ts → pets.d-C_53_fzo.d.ts} +3 -3
- package/dist/{pets-CcyPQS-H.d.cts → pets.d-NbJvP_kh.d.cts} +3 -3
- package/dist/{petsRepository-B_Q1gFkE.d.cts → petsRepository.d-BuGHymNx.d.ts} +4 -4
- package/dist/{petsRepository-518QkPxH.d.ts → petsRepository.d-lp1BHRqM.d.cts} +4 -4
- package/dist/photo/index.cjs +6 -2
- package/dist/photo/index.d.cts +9 -9
- package/dist/photo/index.d.ts +9 -9
- package/dist/photo/index.js +6 -2
- package/dist/{ports-BN6RHF9W.d.ts → ports.d-BX4f4UsB.d.cts} +14 -1
- package/dist/{ports-BN6RHF9W.d.cts → ports.d-BX4f4UsB.d.ts} +14 -1
- package/dist/{ports-RuNJmBA-.d.cts → ports.d-CEROoqnA.d.cts} +16 -10
- package/dist/{ports-DmQeMArX.d.ts → ports.d-COIyN624.d.ts} +16 -10
- package/dist/presentation.d-DMbdad7G.d.cts +90 -0
- package/dist/presentation.d-DMbdad7G.d.ts +90 -0
- package/dist/records/depth/index.cjs +11 -7
- package/dist/records/depth/index.d.cts +14 -12
- package/dist/records/depth/index.d.ts +14 -12
- package/dist/records/depth/index.js +11 -7
- package/dist/records/index.cjs +225 -62
- package/dist/records/index.d.cts +159 -20
- package/dist/records/index.d.ts +159 -20
- package/dist/records/index.js +225 -62
- package/dist/recordsAsk.d-C5CGSi3j.d.cts +14 -0
- package/dist/recordsAsk.d-C5CGSi3j.d.ts +14 -0
- package/dist/{requestFunnel-B9fdXMi5.d.ts → requestFunnel.d-CXUMPw1K.d.ts} +5 -5
- package/dist/{requestFunnel-BBjNNwc9.d.cts → requestFunnel.d-DWQQpjFR.d.cts} +5 -5
- package/dist/{resolve-D4Ywz5OS.d.ts → resolve.d-jI8FmBj3.d.cts} +3 -3
- package/dist/{resolve-D4Ywz5OS.d.cts → resolve.d-jI8FmBj3.d.ts} +3 -3
- package/dist/{runtimeTypes-CstDBX8w.d.cts → runtimeTypes.d-4yFNNuYR.d.ts} +20 -13
- package/dist/{runtimeTypes-N_K4BVZB.d.ts → runtimeTypes.d-D6N_fhxx.d.cts} +20 -13
- package/dist/server/events/index.cjs +7 -3
- package/dist/server/events/index.d.cts +51 -9
- package/dist/server/events/index.d.ts +51 -9
- package/dist/server/events/index.js +7 -3
- package/dist/server/index.cjs +12 -6
- package/dist/server/index.d.cts +152 -8
- package/dist/server/index.d.ts +152 -8
- package/dist/server/index.js +12 -6
- package/dist/sheetCopy.d-CAhLOxjc.d.cts +4 -0
- package/dist/sheetCopy.d-CAhLOxjc.d.ts +4 -0
- package/dist/sheetSeam.d-Cviqk89n.d.ts +45 -0
- package/dist/sheetSeam.d-DCS3LW8g.d.cts +45 -0
- package/dist/shop/index.cjs +262 -0
- package/dist/shop/index.d.cts +193 -0
- package/dist/shop/index.d.ts +193 -0
- package/dist/shop/index.js +262 -0
- package/dist/televet/booking/index.cjs +16 -12
- package/dist/televet/booking/index.d.cts +36 -22
- package/dist/televet/booking/index.d.ts +36 -22
- package/dist/televet/booking/index.js +16 -12
- package/dist/televet/call/index.d.cts +5 -5
- package/dist/televet/call/index.d.ts +5 -5
- package/dist/televet/index.cjs +7 -3
- package/dist/televet/index.d.cts +12 -12
- package/dist/televet/index.d.ts +12 -12
- package/dist/televet/index.js +7 -3
- package/dist/{televetGlobal-C5dTUACe.d.cts → televetGlobal.d-CC-DrqkQ.d.ts} +7 -2
- package/dist/{televetGlobal-CnjrfhT4.d.ts → televetGlobal.d-CKwDCbmN.d.cts} +7 -2
- package/dist/testing/index.cjs +7 -3
- package/dist/testing/index.d.cts +3 -3
- package/dist/testing/index.d.ts +3 -3
- package/dist/testing/index.js +7 -3
- package/dist/testing/rn/index.cjs +5 -1
- package/dist/testing/rn/index.d.cts +23 -22
- package/dist/testing/rn/index.d.ts +23 -22
- package/dist/testing/rn/index.js +5 -1
- package/dist/testing/web/index.cjs +5 -1
- package/dist/testing/web/index.d.cts +23 -22
- package/dist/testing/web/index.d.ts +23 -22
- package/dist/testing/web/index.js +5 -1
- package/dist/texting/index.cjs +158 -0
- package/dist/texting/index.d.cts +36 -0
- package/dist/texting/index.d.ts +36 -0
- package/dist/texting/index.js +158 -0
- package/dist/threadOptions.d-B1pTMmDF.d.cts +260 -0
- package/dist/threadOptions.d-B1pTMmDF.d.ts +260 -0
- package/dist/{timelineRows-7yjHyh8i.d.ts → timelineRows.d-BNxgzYRW.d.cts} +1 -1
- package/dist/{timelineRows-WvnL-Lds.d.cts → timelineRows.d-CU5GvvLk.d.ts} +1 -1
- package/dist/{tokens-DLj8OnLH.d.cts → tokens.d-DarDaV39.d.cts} +10 -2
- package/dist/{tokens-DLj8OnLH.d.ts → tokens.d-DarDaV39.d.ts} +10 -2
- package/dist/{typeStyle-BxVyF71R.d.ts → typeStyle.d-Bl8pzbBy.d.cts} +2 -2
- package/dist/{typeStyle-DJedEu14.d.cts → typeStyle.d-C1HBRAI3.d.ts} +2 -2
- package/dist/{uploadTransport-BM_pnEWj.d.cts → uploadTransport.d-CWL7CdWP.d.cts} +1 -1
- package/dist/{uploadTransport-C6kGP1Kd.d.ts → uploadTransport.d-EGoUl7gX.d.ts} +1 -1
- package/dist/usePresentation.d-D6qsFzBz.d.cts +9 -0
- package/dist/usePresentation.d-DuGQe_Do.d.ts +9 -0
- package/dist/useRecords.d-Cb-36SF5.d.cts +121 -0
- package/dist/useRecords.d-aQTzQZoV.d.ts +121 -0
- package/dist/{useRecordsDepth-Bp6L4M5P.d.ts → useRecordsDepth.d-DFcCfiXm.d.ts} +8 -20
- package/dist/{useRecordsDepth-DPdAK_81.d.cts → useRecordsDepth.d-sAq2Qkhr.d.cts} +8 -20
- package/dist/{useVetVisit-DmWa7lt1.d.ts → useVetVisit.d-BtdwhmgD.d.cts} +15 -4
- package/dist/{useVetVisit-PtBjNwZr.d.cts → useVetVisit.d-DoYQimyt.d.ts} +15 -4
- package/dist/video/index.cjs +6 -2
- package/dist/video/index.d.cts +7 -7
- package/dist/video/index.d.ts +7 -7
- package/dist/video/index.js +6 -2
- package/dist/{view-C6go2uUt.d.ts → view.d-C-SNpDJX.d.ts} +10 -122
- package/dist/{view-CiF_HVFQ.d.cts → view.d-Dps5C8-s.d.cts} +10 -122
- package/dist/web/consent/index.cjs +5 -1
- package/dist/web/consent/index.d.cts +10 -10
- package/dist/web/consent/index.d.ts +10 -10
- package/dist/web/consent/index.js +5 -1
- package/dist/web/health-plan/index.cjs +414 -0
- package/dist/web/health-plan/index.d.cts +335 -0
- package/dist/web/health-plan/index.d.ts +335 -0
- package/dist/web/health-plan/index.js +414 -0
- package/dist/web/index.cjs +150 -82
- package/dist/web/index.d.cts +152 -38
- package/dist/web/index.d.ts +152 -38
- package/dist/web/index.js +150 -82
- package/dist/web/notifications/index.cjs +16 -3
- package/dist/web/notifications/index.d.cts +39 -209
- package/dist/web/notifications/index.d.ts +39 -209
- package/dist/web/notifications/index.js +16 -3
- package/dist/web/records/depth/index.cjs +11 -7
- package/dist/web/records/depth/index.d.cts +14 -12
- package/dist/web/records/depth/index.d.ts +14 -12
- package/dist/web/records/depth/index.js +11 -7
- package/dist/web/records/index.cjs +95 -68
- package/dist/web/records/index.d.cts +66 -21
- package/dist/web/records/index.d.ts +66 -21
- package/dist/web/records/index.js +95 -68
- package/dist/web/records/upload/index.d.cts +2 -2
- package/dist/web/records/upload/index.d.ts +2 -2
- package/dist/web/records-sheet/index.cjs +278 -0
- package/dist/web/records-sheet/index.d.cts +102 -0
- package/dist/web/records-sheet/index.d.ts +102 -0
- package/dist/web/records-sheet/index.js +278 -0
- package/dist/web/shop/index.cjs +301 -0
- package/dist/web/shop/index.d.cts +42 -0
- package/dist/web/shop/index.d.ts +42 -0
- package/dist/web/shop/index.js +301 -0
- package/dist/web/televet/booking/index.cjs +16 -12
- package/dist/web/televet/booking/index.d.cts +37 -23
- package/dist/web/televet/booking/index.d.ts +37 -23
- package/dist/web/televet/booking/index.js +16 -12
- package/dist/web/televet/call/index.d.cts +4 -4
- package/dist/web/televet/call/index.d.ts +4 -4
- package/dist/web/televet/index.cjs +7 -3
- package/dist/web/televet/index.d.cts +12 -12
- package/dist/web/televet/index.d.ts +12 -12
- package/dist/web/televet/index.js +7 -3
- package/dist/web/texting/index.cjs +157 -0
- package/dist/web/texting/index.d.cts +36 -0
- package/dist/web/texting/index.d.ts +36 -0
- package/dist/web/texting/index.js +157 -0
- package/health-plan/package.json +8 -0
- package/package.json +106 -4
- package/shop/package.json +8 -0
- package/texting/package.json +8 -0
- package/web/health-plan/native-blocked.cjs +12 -0
- package/web/health-plan/package.json +8 -0
- package/web/records-sheet/native-blocked.cjs +12 -0
- package/web/records-sheet/package.json +8 -0
- package/web/shop/native-blocked.cjs +12 -0
- package/web/shop/package.json +8 -0
- package/web/texting/native-blocked.cjs +12 -0
- package/web/texting/package.json +8 -0
- /package/dist/{CameraPort-Cv31Pz7g.d.cts → CameraPort.d-Cv31Pz7g.d.cts} +0 -0
- /package/dist/{CameraPort-Cv31Pz7g.d.ts → CameraPort.d-Cv31Pz7g.d.ts} +0 -0
- /package/dist/{TelemetryPort-BDNr00hu.d.cts → TelemetryPort.d-BDNr00hu.d.cts} +0 -0
- /package/dist/{TelemetryPort-BDNr00hu.d.ts → TelemetryPort.d-BDNr00hu.d.ts} +0 -0
- /package/dist/{cacheEpoch-DknKn3S0.d.cts → cacheEpoch.d-DknKn3S0.d.cts} +0 -0
- /package/dist/{cacheEpoch-DknKn3S0.d.ts → cacheEpoch.d-DknKn3S0.d.ts} +0 -0
- /package/dist/{callCopy-Bw6oZT54.d.cts → callCopy.d-Bw6oZT54.d.cts} +0 -0
- /package/dist/{callCopy-Bw6oZT54.d.ts → callCopy.d-Bw6oZT54.d.ts} +0 -0
- /package/dist/{ids-B2GAAifq.d.cts → ids.d-B2GAAifq.d.cts} +0 -0
- /package/dist/{ids-B2GAAifq.d.ts → ids.d-B2GAAifq.d.ts} +0 -0
- /package/dist/{optionalModule-DbJmsq5f.d.cts → optionalModule.d-DbJmsq5f.d.cts} +0 -0
- /package/dist/{optionalModule-DbJmsq5f.d.ts → optionalModule.d-DbJmsq5f.d.ts} +0 -0
- /package/dist/{profile-CSs1wlXT.d.cts → profile.d-CSs1wlXT.d.cts} +0 -0
- /package/dist/{profile-CSs1wlXT.d.ts → profile.d-CSs1wlXT.d.ts} +0 -0
- /package/dist/{projection-CeIUsbSk.d.cts → projection.d-CeIUsbSk.d.cts} +0 -0
- /package/dist/{projection-CeIUsbSk.d.ts → projection.d-CeIUsbSk.d.ts} +0 -0
- /package/dist/{species-BXAIMh7I.d.cts → species.d-BXAIMh7I.d.cts} +0 -0
- /package/dist/{species-BXAIMh7I.d.ts → species.d-BXAIMh7I.d.ts} +0 -0
- /package/dist/{visitIntent-D7_yVp1I.d.cts → visitIntent.d-D7_yVp1I.d.cts} +0 -0
- /package/dist/{visitIntent-D7_yVp1I.d.ts → visitIntent.d-D7_yVp1I.d.ts} +0 -0
package/dist/records/index.cjs
CHANGED
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
/* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
22
22
|
/* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
|
|
23
23
|
/* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
24
|
+
/* @__PURE__ */Object.freeze({wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
25
|
+
/* @__PURE__ */Object.freeze({wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
24
26
|
/* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
25
27
|
/* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
26
28
|
/* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
@@ -45,6 +47,7 @@
|
|
|
45
47
|
/* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
46
48
|
/* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
47
49
|
/* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
50
|
+
/* @__PURE__ */Object.freeze({wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
48
51
|
/* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
49
52
|
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
50
53
|
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
|
|
@@ -81,39 +84,42 @@
|
|
|
81
84
|
/* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
82
85
|
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
83
86
|
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
87
|
+
/* @__PURE__ */Object.freeze({wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
84
88
|
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
85
89
|
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
86
90
|
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
87
91
|
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
88
92
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
89
93
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
90
|
-
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"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"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,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:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.";function displayFor(code,wireCode){return(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:displayFor(code,opts?.wireCode)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
|
|
94
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,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:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
|
|
91
95
|
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
92
96
|
return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var RECORD_SHARE_AUDIENCES=/* @__PURE__ */Object.freeze(["vet","groomer","boarding"]),https=/* @__PURE__ */zod.z.string().min(1).refine(value=>value.startsWith("https://")),str=/* @__PURE__ */zod.z.string().nullish(),audienceField=/* @__PURE__ */zod.z.unknown().optional(),linkSchema=/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),share_url:/* @__PURE__ */zod.z.string().min(1),expires_at:str,audience:audienceField}),listSchema=/* @__PURE__ */zod.z.object({shares:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),expires_at:str,created_at:str,view_count:/* @__PURE__ */zod.z.number().int().nonnegative().nullish(),last_viewed_at:str,audience:audienceField})).optional()}),pdfSchema=/* @__PURE__ */zod.z.object({download_url:https,expires_at:str}),emailSchema=/* @__PURE__ */zod.z.object({share_id:/* @__PURE__ */zod.z.string().min(1),expires_at:str,audience:audienceField}),scopeSchema=/* @__PURE__ */zod.z.object({audience:/* @__PURE__ */zod.z.string().min(1),sections:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()),entity_types:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()).nullable()}),SHARE_RECIPIENT_EMAIL_MAX=254;function isShareRecipientEmail(value){let trimmed=value.trim();return trimmed.length>0&&trimmed.length<=SHARE_RECIPIENT_EMAIL_MAX&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed)}var isAudience=value=>typeof value=="string"&&RECORD_SHARE_AUDIENCES.includes(value);function audienceOf(value){return isAudience(value)?value:null}function mapShareAudiences(wire){let parsed=zod.z.array(scopeSchema).safeParse(wire);if(!parsed.success)/* @__PURE__ */return Object.freeze([]);let seen=/* @__PURE__ */new Set,scopes=[];for(let scope of parsed.data)!isAudience(scope.audience)||seen.has(scope.audience)||(seen.add(scope.audience),scopes.push(/* @__PURE__ */Object.freeze({audience:scope.audience,sections:/* @__PURE__ */Object.freeze([...scope.sections]),entityTypes:scope.entity_types===null?null:/* @__PURE__ */Object.freeze([...scope.entity_types])}))/* @__PURE__ */);return Object.freeze(scopes)}function resolveShareUrl(shareUrl,apiBaseUrl){let trimmed=shareUrl.trim();if(trimmed.length===0)return null;try{let absolute=/^[a-z][a-z0-9+.-]*:/i.test(trimmed)?new URL(trimmed):apiBaseUrl!==void 0?new URL(trimmed,apiBaseUrl):null;return absolute===null||absolute.protocol!=="https:"?null:absolute.toString()}catch{return null}}function mapRecordShareLink(wire,apiBaseUrl){let parsed=linkSchema.safeParse(wire);if(!parsed.success)return null;let shareUrl=resolveShareUrl(parsed.data.share_url,apiBaseUrl);return shareUrl===null?null:/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,shareUrl:shareUrl,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)})}function mapRecordShareList(wire){let parsed=listSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze((parsed.data.shares??[]).map(share=>/* @__PURE__ */Object.freeze({shareId:share.share_id,expiresAt:share.expires_at??null,createdAt:share.created_at??null,viewCount:share.view_count??0,lastViewedAt:share.last_viewed_at??null,audience:audienceOf(share.audience)}))):null}function mapRecordShareEmailReceipt(wire){let parsed=emailSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)}):null}function mapRecordPdfLink(wire){let parsed=pdfSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({downloadUrl:parsed.data.download_url,expiresAt:parsed.data.expires_at??null}):null}var RECORDS_PDF_CONTENT_TYPE="application/pdf",RECORDS_PHOTO_CONTENT_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),isPhotoType=value=>RECORDS_PHOTO_CONTENT_TYPES.includes(value);function isAcceptedUploadType(type,types){return type===RECORDS_PDF_CONTENT_TYPE||types!==void 0&&isPhotoType(type)&&types.includes(type)}var RECORDS_FEATURES_PDF_ONLY=/* @__PURE__ */Object.freeze({features:/* @__PURE__ */Object.freeze({}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE]),shareAudiences:/* @__PURE__ */Object.freeze([])}),featuresSchema=/* @__PURE__ */zod.z.object({features:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.boolean()),upload_content_types:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.string()).nullish(),share_audiences:/* @__PURE__ */zod.z.unknown().optional()});function mapRecordsFeatures(wire){let parsed=featuresSchema.safeParse(wire);if(!parsed.success)return RECORDS_FEATURES_PDF_ONLY;let listed=parsed.data.upload_content_types??[],photos=RECORDS_PHOTO_CONTENT_TYPES.filter(type=>listed.includes(type));/* @__PURE__ */
|
|
93
97
|
return Object.freeze({features:/* @__PURE__ */Object.freeze({...parsed.data.features}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE,...photos]),shareAudiences:mapShareAudiences(parsed.data.share_audiences)})}function acceptsPhotos(types){return types!==void 0&&types.some(isPhotoType)}var KNOWN_STATUSES=/* @__PURE__ */new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),STATUS_ALIASES=/* @__PURE__ */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 normalizeStatus(raw){let aliased=Object.prototype.hasOwnProperty.call(STATUS_ALIASES,raw)?STATUS_ALIASES[raw]:void 0;if(aliased!==void 0)return aliased;let value=raw;return KNOWN_STATUSES.has(value)?value:"parsing"}function normalizeOrigin(raw){return raw==="owner_reported"||raw==="clinic_document"?raw:null}var requestSchema=/* @__PURE__ */zod.z.object({request_id:/* @__PURE__ */zod.z.string().min(1),pet_ref:/* @__PURE__ */zod.z.string().min(1),status:/* @__PURE__ */zod.z.string(),simple_status:/* @__PURE__ */zod.z.string().nullish(),simple_status_detail:/* @__PURE__ */zod.z.string().nullish(),status_label:/* @__PURE__ */zod.z.string().optional(),dispatch_status:/* @__PURE__ */zod.z.string().nullish(),can_retry_send:/* @__PURE__ */zod.z.boolean().optional(),can_revoke:/* @__PURE__ */zod.z.boolean().optional(),can_convert_to_upload:/* @__PURE__ */zod.z.boolean().optional(),can_update_clinic_email:/* @__PURE__ */zod.z.boolean().optional(),reminder_count:/* @__PURE__ */zod.z.number().int().nonnegative().optional(),last_reminder_at:/* @__PURE__ */zod.z.string().nullish(),waiting_expectation:/* @__PURE__ */zod.z.string().nullish(),document_count:/* @__PURE__ */zod.z.number().optional(),held_item_count:/* @__PURE__ */zod.z.number().optional(),received_at:/* @__PURE__ */zod.z.string().nullish(),parsing_started_at:/* @__PURE__ */zod.z.string().nullish(),review_started_at:/* @__PURE__ */zod.z.string().nullish(),created_at:/* @__PURE__ */zod.z.string().optional(),updated_at:/* @__PURE__ */zod.z.string().optional(),source:/* @__PURE__ */zod.z.string().nullish().catch(null),action_needed_label:/* @__PURE__ */zod.z.string().nullish().catch(null),failure_reason:/* @__PURE__ */zod.z.string().nullish().catch(null),failure_code:/* @__PURE__ */zod.z.string().nullish().catch(null),recovery_stage:/* @__PURE__ */zod.z.string().nullish().catch(null),show_clinic_phone:/* @__PURE__ */zod.z.boolean().optional().catch(void 0),clinic_name:/* @__PURE__ */zod.z.string().nullish().catch(null),clinic_email:/* @__PURE__ */zod.z.string().nullish().catch(null),clinic_phone:/* @__PURE__ */zod.z.string().nullish().catch(null),converted_to_upload_at:/* @__PURE__ */zod.z.string().nullish().catch(null),request_group_id:/* @__PURE__ */zod.z.string().nullish().catch(null)}).passthrough();function mapRequestView(wire){let parsed=requestSchema.safeParse(wire);if(!parsed.success)return null;let w=parsed.data,simpleStatus=normalizeSimpleStatus(w.simple_status),status=simpleStatus==="requested"&&(w.status==="awaiting_upload"||w.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":simpleStatus==="parsing"&&(w.simple_status_detail==="in_review"||w.simple_status_detail==="review_email_failed")?"in_review":simpleStatus??normalizeStatus(w.status);/* @__PURE__ */
|
|
94
98
|
return Object.freeze({id:w.request_id,petRef:w.pet_ref,status:status,simpleStatus:simpleStatus,simpleStatusDetail:w.simple_status_detail??null,statusLabel:w.status_label??"",dispatchStatus:w.dispatch_status??null,canRetrySend:w.can_retry_send===true,canRevoke:w.can_revoke===true,canConvertToUpload:w.can_convert_to_upload===true,canUpdateClinicEmail:w.can_update_clinic_email===true,reminderCount:w.reminder_count??0,lastReminderAt:w.last_reminder_at??null,waitingExpectation:w.waiting_expectation??null,documentCount:numberOr(w.document_count,0),heldItemCount:numberOr(w.held_item_count,0),receivedAt:w.received_at??null,parsingStartedAt:w.parsing_started_at??null,reviewStartedAt:w.review_started_at??null,createdAt:w.created_at??"",updatedAt:w.updated_at??"",wireStatus:w.status,source:w.source??null,actionNeededLabel:w.action_needed_label??null,failureReason:w.failure_reason??null,failureCode:w.failure_code??null,recoveryStage:w.recovery_stage??null,showClinicPhone:w.show_clinic_phone===true,clinicName:w.clinic_name??null,clinicEmail:w.clinic_email??null,clinicPhone:w.clinic_phone??null,convertedToUploadAt:w.converted_to_upload_at??null,requestGroupId:w.request_group_id??null})}var groupSchema=/* @__PURE__ */zod.z.object({request_group_id:/* @__PURE__ */zod.z.string().min(1),pet_ref:/* @__PURE__ */zod.z.string().min(1),total:/* @__PURE__ */zod.z.number().int().nonnegative(),responded:/* @__PURE__ */zod.z.number().int().nonnegative(),pending:/* @__PURE__ */zod.z.number().int().nonnegative(),members:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.unknown())});function mapRequestGroup(wire){let parsed=groupSchema.safeParse(wire);if(!parsed.success)return null;let g=parsed.data,members=mapRequestList(g.members);return members.some(member=>member.petRef!==g.pet_ref)?null:/* @__PURE__ */Object.freeze({requestGroupId:g.request_group_id,petRef:g.pet_ref,total:g.total,responded:g.responded,pending:g.pending,members:members})}function normalizeSimpleStatus(raw){return!raw||raw==="awaiting_upload"||raw==="in_review"?null:KNOWN_STATUSES.has(raw)?raw:null}function mapRequestList(wire){let list=Array.isArray(wire)?wire:[],out=[];for(let entry of list){let view=mapRequestView(entry);view!==null&&out.push(view)}/* @__PURE__ */
|
|
95
|
-
return Object.freeze(out)}var acceptedSchema=/* @__PURE__ */zod.z.object({source_doc_id:/* @__PURE__ */zod.z.string().min(1),request_id:/* @__PURE__ */zod.z.string().min(1)});function mapUploadedDocument(wire){let parsed=acceptedSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({documentId:parsed.data.source_doc_id,requestId:parsed.data.request_id,status:"received"}):null}var identitySchema=/* @__PURE__ */zod.z.object({label:/* @__PURE__ */zod.z.string(),value:/* @__PURE__ */zod.z.string()}),entitySchema=/* @__PURE__ */zod.z.object({key:/* @__PURE__ */zod.z.string(),category:/* @__PURE__ */zod.z.string().optional(),label:/* @__PURE__ */zod.z.string().optional(),value:/* @__PURE__ */zod.z.string().nullish(),unit:/* @__PURE__ */zod.z.string().nullish(),observed_at:/* @__PURE__ */zod.z.string().nullish(),status:/* @__PURE__ */zod.z.string().nullish(),origin:/* @__PURE__ */zod.z.string().nullish(),canonical_key:/* @__PURE__ */zod.z.string().nullish()}),seriesPointSchema=/* @__PURE__ */zod.z.object({at:/* @__PURE__ */zod.z.string(),value:/* @__PURE__ */zod.z.number().nullish(),display:/* @__PURE__ */zod.z.string().nullish(),origin:/* @__PURE__ */zod.z.string().nullish()}),seriesSchema=/* @__PURE__ */zod.z.object({key:/* @__PURE__ */zod.z.string(),label:/* @__PURE__ */zod.z.string().optional(),points:/* @__PURE__ */zod.z.array(seriesPointSchema).optional()}),forwardSchema=/* @__PURE__ */zod.z.object({title:/* @__PURE__ */zod.z.string(),detail:/* @__PURE__ */zod.z.string().nullish(),due_at:/* @__PURE__ */zod.z.string().nullish()}),documentSchema=/* @__PURE__ */zod.z.object({doc_id:/* @__PURE__ */zod.z.string(),title:/* @__PURE__ */zod.z.string().nullish(),page_count:/* @__PURE__ */zod.z.number().nullish(),received_at:/* @__PURE__ */zod.z.string().nullish()});function mapEntityRow(e){/* @__PURE__ */
|
|
99
|
+
return Object.freeze(out)}var acceptedSchema=/* @__PURE__ */zod.z.object({source_doc_id:/* @__PURE__ */zod.z.string().min(1),request_id:/* @__PURE__ */zod.z.string().min(1)});function mapUploadedDocument(wire){let parsed=acceptedSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({documentId:parsed.data.source_doc_id,requestId:parsed.data.request_id,status:"received"}):null}var identitySchema=/* @__PURE__ */zod.z.object({label:/* @__PURE__ */zod.z.string(),value:/* @__PURE__ */zod.z.string()}),entitySchema=/* @__PURE__ */zod.z.object({key:/* @__PURE__ */zod.z.string(),category:/* @__PURE__ */zod.z.string().optional(),label:/* @__PURE__ */zod.z.string().optional(),value:/* @__PURE__ */zod.z.string().nullish(),unit:/* @__PURE__ */zod.z.string().nullish(),observed_at:/* @__PURE__ */zod.z.string().nullish(),status:/* @__PURE__ */zod.z.string().nullish(),origin:/* @__PURE__ */zod.z.string().nullish(),canonical_key:/* @__PURE__ */zod.z.string().nullish()}),seriesPointSchema=/* @__PURE__ */zod.z.object({at:/* @__PURE__ */zod.z.string(),value:/* @__PURE__ */zod.z.number().nullish(),display:/* @__PURE__ */zod.z.string().nullish(),origin:/* @__PURE__ */zod.z.string().nullish()}),seriesSchema=/* @__PURE__ */zod.z.object({key:/* @__PURE__ */zod.z.string(),label:/* @__PURE__ */zod.z.string().optional(),points:/* @__PURE__ */zod.z.array(seriesPointSchema).optional()}),forwardSchema=/* @__PURE__ */zod.z.object({title:/* @__PURE__ */zod.z.string(),detail:/* @__PURE__ */zod.z.string().nullish(),due_at:/* @__PURE__ */zod.z.string().nullish()}),documentSchema=/* @__PURE__ */zod.z.object({doc_id:/* @__PURE__ */zod.z.string(),title:/* @__PURE__ */zod.z.string().nullish(),document_class:/* @__PURE__ */zod.z.string().nullish(),page_count:/* @__PURE__ */zod.z.number().nullish(),received_at:/* @__PURE__ */zod.z.string().nullish()});function mapEntityRow(e){/* @__PURE__ */
|
|
96
100
|
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:normalizeOrigin(e.origin),canonicalKey:e.canonical_key??null})}function mapDocumentRow(d){/* @__PURE__ */
|
|
97
|
-
return Object.freeze({docId:d.doc_id,title:d.title??null,pageCount:d.page_count??null,receivedAt:d.received_at??null})}var contentSchema=/* @__PURE__ */zod.z.object({identity:/* @__PURE__ */zod.z.array(identitySchema).optional(),entities:/* @__PURE__ */zod.z.array(entitySchema).optional(),entity_series:/* @__PURE__ */zod.z.array(seriesSchema).optional(),forward_looking:/* @__PURE__ */zod.z.array(forwardSchema).optional(),documents:/* @__PURE__ */zod.z.array(documentSchema).optional()});function mapRecordView(petRef,wire){let w=isObject(wire)?wire:{},schemaVersion=strOr(w.schema_version,"epdf/1.0"),disclaimer=strOr(w.disclaimer,""),pet=typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef;if(w.withheld===true)return withheldView(pet,schemaVersion,disclaimer);let content=contentSchema.safeParse(w);if(!content.success)return withheldView(pet,schemaVersion,disclaimer);let c=content.data,identity=(c.identity??[]).map(i=>/* @__PURE__ */Object.freeze({label:i.label,value:i.value})),entities=(c.entities??[]).map(mapEntityRow),entitySeries=(c.entity_series??[]).map(s=>/* @__PURE__ */Object.freeze({key:s.key,label:s.label??s.key,points:/* @__PURE__ */Object.freeze((s.points??[]).map(p=>/* @__PURE__ */Object.freeze({at:p.at,value:p.value??null,display:p.display??null,origin:normalizeOrigin(p.origin)})))})),forwardLooking=(c.forward_looking??[]).map(f=>/* @__PURE__ */Object.freeze({title:f.title,detail:f.detail??null,dueAt:f.due_at??null})),documents={};for(let d of c.documents??[])documents[d.doc_id]=mapDocumentRow(d);let isEmpty=w.is_empty===true||identity.length===0&&entities.length===0&&entitySeries.length===0&&forwardLooking.length===0&&Object.keys(documents).length===0;/* @__PURE__ */
|
|
101
|
+
return Object.freeze({docId:d.doc_id,title:d.title??null,documentClass:d.document_class??null,pageCount:d.page_count??null,receivedAt:d.received_at??null})}var contentSchema=/* @__PURE__ */zod.z.object({identity:/* @__PURE__ */zod.z.array(identitySchema).optional(),entities:/* @__PURE__ */zod.z.array(entitySchema).optional(),entity_series:/* @__PURE__ */zod.z.array(seriesSchema).optional(),forward_looking:/* @__PURE__ */zod.z.array(forwardSchema).optional(),documents:/* @__PURE__ */zod.z.array(documentSchema).optional()});function mapRecordView(petRef,wire){let w=isObject(wire)?wire:{},schemaVersion=strOr(w.schema_version,"epdf/1.0"),disclaimer=strOr(w.disclaimer,""),pet=typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef;if(w.withheld===true)return withheldView(pet,schemaVersion,disclaimer);let content=contentSchema.safeParse(w);if(!content.success)return withheldView(pet,schemaVersion,disclaimer);let c=content.data,identity=(c.identity??[]).map(i=>/* @__PURE__ */Object.freeze({label:i.label,value:i.value})),entities=(c.entities??[]).map(mapEntityRow),entitySeries=(c.entity_series??[]).map(s=>/* @__PURE__ */Object.freeze({key:s.key,label:s.label??s.key,points:/* @__PURE__ */Object.freeze((s.points??[]).map(p=>/* @__PURE__ */Object.freeze({at:p.at,value:p.value??null,display:p.display??null,origin:normalizeOrigin(p.origin)})))})),forwardLooking=(c.forward_looking??[]).map(f=>/* @__PURE__ */Object.freeze({title:f.title,detail:f.detail??null,dueAt:f.due_at??null})),documents={};for(let d of c.documents??[])documents[d.doc_id]=mapDocumentRow(d);let isEmpty=w.is_empty===true||identity.length===0&&entities.length===0&&entitySeries.length===0&&forwardLooking.length===0&&Object.keys(documents).length===0;/* @__PURE__ */
|
|
98
102
|
return Object.freeze({petRef:pet,schemaVersion:schemaVersion,isEmpty:isEmpty,withheld:false,generatedAt:strOrNull(w.generated_at),identity:/* @__PURE__ */Object.freeze(identity),entities:/* @__PURE__ */Object.freeze(entities),entitySeries:/* @__PURE__ */Object.freeze(entitySeries),forwardLooking:/* @__PURE__ */Object.freeze(forwardLooking),documents:/* @__PURE__ */Object.freeze(documents),disclaimer:disclaimer})}function withheldView(petRef,schemaVersion,disclaimer){/* @__PURE__ */
|
|
99
103
|
return Object.freeze({petRef:petRef,schemaVersion:schemaVersion,isEmpty:false,withheld:true,generatedAt:null,identity:/* @__PURE__ */Object.freeze([]),entities:/* @__PURE__ */Object.freeze([]),entitySeries:/* @__PURE__ */Object.freeze([]),forwardLooking:/* @__PURE__ */Object.freeze([]),documents:/* @__PURE__ */Object.freeze({}),disclaimer:disclaimer})}var consentSchema=/* @__PURE__ */zod.z.object({pet_ref:/* @__PURE__ */zod.z.string().optional(),granted:/* @__PURE__ */zod.z.boolean().optional(),version:/* @__PURE__ */zod.z.string().nullish(),granted_at:/* @__PURE__ */zod.z.string().nullish()});function mapConsent(petRef,wire){let parsed=consentSchema.safeParse(wire),data=parsed.success?parsed.data:{};/* @__PURE__ */
|
|
100
104
|
return Object.freeze({petRef:typeof data.pet_ref=="string"&&data.pet_ref.length>0?data.pet_ref:petRef,granted:data.granted===true,version:data.version??null,grantedAt:data.granted_at??null})}function isObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function numberOr(v,fallback){return typeof v=="number"&&Number.isFinite(v)?v:fallback}function strOr(v,fallback){return typeof v=="string"&&v.length>0?v:fallback}function strOrNull(v){return typeof v=="string"&&v.length>0?v:null}var RECORDS_TERMINAL=/* @__PURE__ */Object.freeze(["published","failed","revoked"]);function isTerminalStatus(status){return RECORDS_TERMINAL.includes(status)}function recordsDenialReasonOf(error){if(error===null)return null;let reason=error.recordsReason;return reason==="consent_required"||reason==="session_required"||reason==="entitlement"||reason==="pet_not_found"?reason:null}var RECORDS_CONSENT_REQUIRED_WIRE_CODE="records_consent_required";function recordsWireCodeOf(error){let raw=error.raw;if(raw===null||typeof raw!="object")return null;let body=raw,code=typeof body.error=="object"&&body.error!==null?body.error.code:body.code;return typeof code=="string"&&code.length>0?code:null}function isRecordsConsentRequired(error){return error===null||error.httpStatus!==409?false:recordsWireCodeOf(error)===RECORDS_CONSENT_REQUIRED_WIRE_CODE}var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var noopRecordsTelemetry=/* @__PURE__ */Object.freeze({record(){}}),MAX_UPLOAD_BYTES=25*1024*1024,CONSENT_VERSION_MAX=64,IDEMPOTENCY_KEY_MAX=128,PET_REF_MAX=128;var UPLOAD_DEADLINE_MS=9e4;function createRecordsController(deps){return new RecordsControllerImpl(deps)}var RecordsControllerImpl=class{constructor(deps){this.recordCache=/* @__PURE__ */new Map;this.consentEpoch=/* @__PURE__ */new Map;this.reportedGaps=/* @__PURE__ */new Set;this.features=RECORDS_FEATURES_PDF_ONLY;this.repository=deps.repository,this.uploads=deps.uploads,this.telemetry=deps.telemetry??noopRecordsTelemetry,this.newIdempotencyKey=deps.newIdempotencyKey??defaultIdempotencyFactory(),this.timers=deps.timers??defaultTimers,this.uploadDeadlineMs=deps.uploadDeadlineMs??UPLOAD_DEADLINE_MS}async createUploadRequest(input){let res=await this.repository.createRequest({pet_ref:input.petRef,idempotency_key:input.idempotencyKey});if(!res.ok)return this.onRequestError(res.error);let view=mapRequestView(res.value);return view===null?err(internal()):(this.observeRequest(view),ok(view))}async getRequest(id){let res=await this.repository.getRequest(id);if(!res.ok)return this.onRequestError(res.error);let view=mapRequestView(res.value);return view===null?err(internal()):(this.observeRequest(view),ok(view))}async listRequests(){let res=await this.repository.listRequests();if(!res.ok)return this.onRequestError(res.error);let views=mapRequestList(res.value);for(let view of views)this.observeRequest(view);return ok(views)}async readFeatures(){let read=this.repository.getFeatures;if(read===void 0)return this.features=RECORDS_FEATURES_PDF_ONLY;let features=RECORDS_FEATURES_PDF_ONLY;try{let res=await read.call(this.repository);res.ok&&(features=mapRecordsFeatures(res.value))}catch{}return this.features=features,features}async uploadDocument(input){let{requestId:requestId2,file:file}=input,rejection=validateFile(file,this.features.uploadContentTypes);if(rejection!==null)return this.telemetry.record("records.upload.rejected",{reason:rejection}),err(uploadFailed(`upload rejected: ${rejection}`));let initiated=await this.repository.initiateUpload(requestId2,{content_type:file.mimeType,file_size:file.sizeBytes});if(!initiated.ok)return this.onRequestError(initiated.error);let s3=await this.postToS3(initiated.value,file,input);if(!s3.ok)return this.telemetry.record("records.upload.failed",{reason:s3.reason}),err(uploadFailed(s3.reason));let completed=await this.repository.completeUpload(requestId2,{upload_id:initiated.value.upload_id});if(!completed.ok)return completed.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:reasonFromWire(completed.error)??"corrupt"}),this.onRequestError(completed.error);let doc=mapUploadedDocument(completed.value);return doc===null?err(internal()):ok(doc)}async postToS3(policy,file,input){let deadline=new AbortController,signal=mergeSignals(deadline.signal,input.signal),handle=this.timers.setTimeout(()=>deadline.abort(),this.uploadDeadlineMs);try{let opts={signal:signal};return input.onProgress&&(opts.onProgress=input.onProgress),await this.uploads.postMultipart(policy,file,opts),{ok:!0}}catch{return{ok:false,reason:deadline.signal.aborted&&input.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(handle)}}async getRecord(pet){let epoch=this.consentEpoch.get(pet)??0,res=await this.repository.getRecord(pet);if(epoch!==(this.consentEpoch.get(pet)??0))return err(/* @__PURE__ */Object.freeze({...makeEverfurError("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!res.ok){let reason=recordsDenialReasonOf(res.error);return reason==="consent_required"?(this.recordCache.delete(pet),this.telemetry.record("records.consent.denied",{pet_ref:pet})):reason==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:pet}),err(res.error)}let view=mapRecordView(pet,res.value);return view.petRef!==pet?err(internal()):view.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:pet}),this.recordCache.delete(pet),ok(view)):(this.recordCache.set(pet,view),ok(view))}peekCachedRecord(pet){return this.recordCache.get(pet)??null}async getConsent(pet){let res=await this.repository.getConsent(pet);return res.ok?ok(mapConsent(pet,res.value)):err(res.error)}async grantConsent(input){let res=await this.repository.putConsent(input.petRef,{consent_version:input.consentVersion,idempotency_key:input.idempotencyKey});return res.ok?ok(mapConsent(input.petRef,res.value)):(recordsDenialReasonOf(res.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:input.petRef}),err(res.error))}async revokeConsent(pet){let res=await this.repository.deleteConsent(pet);return res.ok?(this.consentEpoch.set(pet,(this.consentEpoch.get(pet)??0)+1),this.recordCache.delete(pet),ok(mapConsent(pet,res.value))):err(res.error)}reportCapabilityDenied(pet){this.telemetry.record("records.capability.denied",pet?{pet_ref:pet}:{})}observeRequest(view){view.reviewStartedAt!==null&&!this.reportedGaps.has(view.id)&&(this.reportedGaps.add(view.id),this.telemetry.record("records.parse.gap",{request_id:view.id}))}onRequestError(error){return recordsDenialReasonOf(error)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),err(error)}};function validateFile(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported_format";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"oversize":null}function reasonFromWire(error){let raw=error.wireMessage;return raw==="unsupported_format"||raw==="oversize"||raw==="corrupt"?raw:null}function uploadFailed(wireMessage){return makeEverfurError("mediaUploadFailed",{retryable:false,wireMessage:wireMessage})}function internal(){return makeEverfurError("internalError",{retryable:true})}var defaultTimers={setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle)};function mergeSignals(a,b){if(!b)return a;let ctrl=new AbortController;if(a.aborted||b.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return a.addEventListener("abort",onAbort,{once:true}),b.addEventListener("abort",onAbort,{once:true}),ctrl.signal}function defaultIdempotencyFactory(){let counter=0;return()=>`records-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
|
|
101
|
-
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,
|
|
105
|
+
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base2=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals2(deadline.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp2({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
102
106
|
/* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
|
|
103
|
-
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals2(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}var BASE="/widget/v1/records";function createHttpRecordsRepository(deps){let{auth:auth}=deps,mode=auth.mode,funnel=deps.funnel??createRequestFunnel({auth:auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=async(call,req,kind)=>{let res=await funnel.send(call,req);return res.ok?res:err(tagReason(res.error,mode,kind))},segmentError=(field,value)=>typeof value!="string"||value.length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is required and must be a non-empty string`}):hasLoneSurrogate(value)?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} contains an unpaired surrogate and cannot be encoded`}):null,boundsError=(field,value,max)=>{let unusable=segmentError(field,value);if(unusable!==null)return unusable;let length=[...value].length;return length>max?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is ${length} characters; the server accepts at most ${max}`}):null},firstError=(...checks)=>checks.find(c=>c!==null)??null;return{createRequest:body=>{let
|
|
107
|
+
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals2(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var BASE="/widget/v1/records";function createHttpRecordsRepository(deps){let{auth:auth}=deps,mode=auth.mode,funnel=deps.funnel??createRequestFunnel({auth:auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=async(call,req,kind)=>{let res=await funnel.send(call,req);return res.ok?res:err(tagReason(plainNotFound(res.error),mode,kind))},segmentError=(field,value)=>typeof value!="string"||value.length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is required and must be a non-empty string`}):hasLoneSurrogate(value)?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} contains an unpaired surrogate and cannot be encoded`}):null,boundsError=(field,value,max)=>{let unusable=segmentError(field,value);if(unusable!==null)return unusable;let length=[...value].length;return length>max?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is ${length} characters; the server accepts at most ${max}`}):null},firstError=(...checks)=>checks.find(c=>c!==null)??null;return{createRequest:body=>{let invalid5=firstError(boundsError("idempotency_key",body.idempotency_key,IDEMPOTENCY_KEY_MAX),boundsError("pet_ref",body.pet_ref,PET_REF_MAX));return invalid5?Promise.resolve(err(invalid5)):send("records.createRequest",post(`${BASE}/requests`,body),"request")},initiateUpload:(requestId2,body)=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.initiateUpload",post(`${BASE}/requests/${encodeURIComponent(requestId2)}/uploads/initiate`,body),"request")},completeUpload:(requestId2,body)=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.completeUpload",post(`${BASE}/requests/${encodeURIComponent(requestId2)}/uploads/complete`,body),"request")},getRequest:requestId2=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.getRequest",get(`${BASE}/requests/${encodeURIComponent(requestId2)}`),"request")},listRequests:async()=>{let res=await send("records.listRequests",get(`${BASE}/requests`),"request");if(!res.ok)return res;let value=res.value;return{ok:true,value:Array.isArray(value)?value:value.items??[]}},getRecord:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.getRecord",get(`${BASE}/pets/${encodeURIComponent(petRef)}/record`),"content")},getConsent:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.getConsent",get(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),"consent")},putConsent:(petRef,body)=>{let invalid5=firstError(boundsError("consent_version",body.consent_version,CONSENT_VERSION_MAX),boundsError("idempotency_key",body.idempotency_key,IDEMPOTENCY_KEY_MAX),boundsError("pet_ref",petRef,PET_REF_MAX));return invalid5?Promise.resolve(err(invalid5)):send("records.putConsent",put(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`,body),"consent")},getFeatures:()=>send("records.getFeatures",get(`${BASE}/features`),"request"),deleteConsent:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.deleteConsent",del(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),"consent")}}}function withReason(error,reason){let tagged={...error,recordsReason:reason};for(let key of["wireMessage","raw"]){let descriptor=Object.getOwnPropertyDescriptor(error,key);descriptor!==void 0&&Object.defineProperty(tagged,key,descriptor)}/* @__PURE__ */
|
|
104
108
|
return Object.freeze(tagged)}var PET_NOT_REGISTERED="pet_not_registered";function recordsErrorReasonFor(error){return error.httpStatus!==404?null:error.reasonCode===PET_NOT_REGISTERED?"pet_not_found":"entitlement"}function tagReason(error,mode,kind){let notFound=recordsErrorReasonFor(error);return notFound!==null?withReason(error,notFound):error.code!=="accessDenied"?error:withReason(error,mode==="anonymous"?"session_required":kind==="content"?"consent_required":"entitlement")}function get(path){return{method:"GET",path:path}}function post(path,body){return{method:"POST",path:path,body:body}}function put(path,body){return{method:"PUT",path:path,body:body}}function del(path){return{method:"DELETE",path:path}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var epochs=/* @__PURE__ */new Map,listeners=/* @__PURE__ */new Set;function notifyRecordsConsentWithdrawn(petRef){epochs.set(petRef,(epochs.get(petRef)??0)+1);for(let listener of[...listeners])listener()}function recordsConsentEpochOf(petRef){return epochs.get(petRef)??0}function subscribe(onStoreChange){return listeners.add(onStoreChange),()=>{listeners.delete(onStoreChange)}}function useRecordsConsentEpoch(petRef){let snapshot=react.useCallback(()=>recordsConsentEpochOf(petRef),[petRef]);return react.useSyncExternalStore(subscribe,snapshot,snapshot)}var INITIAL={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[],uploadContentTypes:RECORDS_FEATURES_PDF_ONLY.uploadContentTypes},POLL_INTERVAL_MS=4e3,MAX_POLLS=30;function useEverfurRecords(opts){let{petRef:petRef}=opts,ownTransport=react.useRef(opts.uploadTransport);ownTransport.current=opts.uploadTransport;let hasOwnTransport=opts.uploadTransport!==void 0,{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),scope=react.useMemo(()=>({}),[runtime,userRef,petRef,scopeEpoch,opts.controller]),activeScope=react.useRef(scope),[binding,setBinding]=react.useState({scope:scope,controller:opts.controller??null}),controller=opts.controller??(binding.scope===scope?binding.controller:null),[snapshot,setSnapshot]=react.useState({scope:scope,value:INITIAL}),snap=snapshot.scope===scope?snapshot.value:INITIAL,setSnap=react.useCallback(update=>{setSnapshot(current=>current.scope===scope?{scope:scope,value:update(current.value)}:current)},[scope]),generation=react.useRef(0);react.useEffect(()=>(activeScope.current=scope,setSnapshot({scope:scope,value:INITIAL}),()=>{activeScope.current=null,generation.current+=1}),[scope]),react.useEffect(()=>{if(opts.controller)return;let{services:services}=runtime.registry,telemetry={record:(event,props)=>services.telemetry.track(event,props)},acquired=runtime.registry.acquire("records",`${userRef??""}|${petRef}${hasOwnTransport?"|own-upload":""}`,()=>createRecordsController({repository:createHttpRecordsRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),uploads:hasOwnTransport?{postMultipart:(policy,file,o)=>(ownTransport.current??services.uploadTransport).postMultipart(policy,file,o)}:services.uploadTransport,telemetry:telemetry}),()=>{});return setBinding({scope:scope,controller:acquired}),()=>{runtime.registry.release(acquired)}},[runtime,userRef,petRef,opts.controller,scopeEpoch,scope,hasOwnTransport]);let patch=react.useCallback(partial=>{setSnap(current=>({...current,...partial}))},[setSnap]),load=react.useCallback(async()=>{if(!controller||activeScope.current!==scope)return;let gen=generation.current+=1;pollsRef.current=0,rearmPolls(),patch({loading:true,error:null,denialReason:null,withheld:false});let[consentRes,listRes]=await Promise.all([controller.getConsent(petRef),controller.listRequests()]);if(gen!==generation.current)return;let consent=consentRes.ok?consentRes.value:null,requests=listRes.ok?listRes.value.filter(request=>request.petRef===petRef):[],listError=listRes.ok?null:listRes.error;if(consent&&consent.granted){let recordRes=await controller.getRecord(petRef);if(gen!==generation.current)return;if(recordRes.ok){patch({consent:consent,requests:requests,record:recordRes.value,withheld:recordRes.value.withheld,error:recordRes.value.withheld?withheldSentinel():listError,denialReason:null,loading:false});return}patch({consent:consent,requests:requests,record:null,error:recordRes.error,denialReason:recordsDenialReasonOf(recordRes.error),withheld:false,loading:false});return}patch({consent:consent,requests:requests,record:null,error:consentRes.ok?listError:consentRes.error,denialReason:consent?"consent_required":consentDenial(consentRes),withheld:false,loading:false})},[controller,petRef,patch,scope]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let readUploadFeatures=opts.readUploadFeatures===true;react.useEffect(()=>{if(!readUploadFeatures||!controller?.readFeatures)return;let live=true;return controller.readFeatures().then(features=>{live&&activeScope.current===scope&&patch({uploadContentTypes:features.uploadContentTypes})}),()=>{live=false}},[controller,readUploadFeatures,patch,scope]);let activeRequest=react.useMemo(()=>newestRequest(snap.requests),[snap.requests]),activeId=activeRequest?.id??null,activeStatus=activeRequest?.status??null,pollsRef=react.useRef(0),polledIdRef=react.useRef(null),[pollEpoch,rearmPolls]=react.useReducer(n=>n+1,0);react.useEffect(()=>{if(!controller||activeId===null||activeStatus===null||isTerminalStatus(activeStatus)||activeStatus==="in_review")return;polledIdRef.current!==String(activeId)&&(polledIdRef.current=String(activeId),pollsRef.current=0);let cancelled=false,tick=async()=>{if(cancelled||pollsRef.current>=MAX_POLLS)return;pollsRef.current+=1;let res=await controller.getRequest(activeId);if(!cancelled){if(res.ok&&res.value.petRef===petRef){if(setSnap(current=>({...current,requests:replaceRequest(current.requests,res.value)})),isTerminalStatus(res.value.status)){res.value.status==="published"&&load();return}if(res.value.status==="in_review")return}handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS)}},handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS);return()=>{cancelled=true,clearTimeout(handle)}},[controller,activeId,activeStatus,load,pollEpoch,petRef,setSnap]);let createRequest=react.useCallback(async idempotencyKey=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.createUploadRequest({petRef:petRef,idempotencyKey:idempotencyKey});return activeScope.current===scope&&res.ok&&res.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,res.value)})),res},[controller,petRef,scope,setSnap]),patchItem=react.useCallback((key,update)=>{setSnap(c=>({...c,uploadQueue:c.uploadQueue.map(item=>item.key===key?update(item):item)}))},[setSnap]),uploadDocuments=react.useCallback(async(requestId2,files)=>{let batch=Date.now().toString(36),queue=files.map((file,index)=>{let skipReason=skipReasonFor(file,snap.uploadContentTypes);return{key:`${batch}-${index}`,name:file.name??null,status:skipReason===null?"queued":"skipped",progress:0,skipReason:skipReason,error:null}}),settled=[...queue];if(!controller||activeScope.current!==scope)/* @__PURE__ */return Object.freeze(settled);setSnap(c=>({...c,uploadQueue:queue,isUploading:true,uploadProgress:0}));for(let[index,file]of files.entries()){let item=queue[index];if(item.status==="skipped")continue;if(activeScope.current!==scope)break;patchItem(item.key,current=>({...current,status:"uploading",progress:0})),patch({uploadProgress:0});let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{if(activeScope.current!==scope)return;let bounded=Math.min(1,Math.max(0,fraction));patchItem(item.key,current=>({...current,progress:Math.max(current.progress,bounded)})),patch({uploadProgress:bounded})}});if(activeScope.current!==scope)break;let next=res.ok?{...item,status:"done",progress:1}:{...item,status:"failed",error:res.error};if(settled[index]=next,patchItem(item.key,()=>next),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}}return activeScope.current===scope&&patch({isUploading:false,uploadProgress:null}),/* @__PURE__ */Object.freeze(settled)},[controller,patch,patchItem,petRef,scope,setSnap,snap.uploadContentTypes]),uploadDocument=react.useCallback(async(requestId2,file)=>{if(!controller||activeScope.current!==scope)return notReady();let key=`${Date.now().toString(36)}-0`;setSnap(c=>({...c,isUploading:true,uploadProgress:0,uploadQueue:[{key:key,name:file.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{activeScope.current===scope&&(patch({uploadProgress:fraction}),patchItem(key,current=>({...current,progress:Math.max(current.progress,Math.min(1,fraction))})))}});if(activeScope.current!==scope)return res;if(patch({isUploading:false,uploadProgress:null}),patchItem(key,current=>res.ok?{...current,status:"done",progress:1}:{...current,status:"failed",error:res.error}),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}return res},[controller,patch,patchItem,petRef,scope,setSnap]),grantConsent=react.useCallback(async(consentVersion,idempotencyKey)=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.grantConsent({petRef:petRef,consentVersion:consentVersion,idempotencyKey:idempotencyKey});return res.ok&&activeScope.current===scope&&load(),res},[controller,petRef,load,scope]),revokeConsent=react.useCallback(async()=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.revokeConsent(petRef);return res.ok&¬ifyRecordsConsentWithdrawn(petRef),res.ok&&activeScope.current===scope&&(generation.current+=1,patch({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:res.value})),res},[controller,petRef,patch,scope]),refresh=react.useCallback(()=>load(),[load]),status=selectStatus(snap,controller!==null);return react.useMemo(()=>({status:status,record:snap.record,requests:snap.requests,activeRequest:activeRequest,consent:snap.consent,error:snap.error,denialReason:snap.denialReason,withheld:snap.withheld,isUploading:snap.isUploading,uploadProgress:snap.uploadProgress,uploadQueue:snap.uploadQueue,uploadContentTypes:snap.uploadContentTypes,createRequest:createRequest,uploadDocument:uploadDocument,uploadDocuments:uploadDocuments,grantConsent:grantConsent,revokeConsent:revokeConsent,refresh:refresh}),[status,snap,activeRequest,createRequest,uploadDocument,uploadDocuments,grantConsent,revokeConsent,refresh])}function skipReasonFor(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"too_large":null}function classifyPick(files,types){let uploadable=[],skipped=[];for(let file of files){let reason=skipReasonFor(file,types);reason===null?uploadable.push(file):skipped.push({name:file.name??null,reason:reason})}return{uploadable:uploadable,skipped:skipped}}function selectStatus(snap,hasController){return snap.loading||!hasController?"loading":snap.withheld||snap.denialReason!==null||snap.error!==null?"error":snap.record!==null&&!snap.record.isEmpty||snap.requests.length>0?"populated":"empty"}function newestRequest(requests){if(requests.length===0)return null;let newest=requests[0];for(let r of requests)r.updatedAt>newest.updatedAt&&(newest=r);return newest}function replaceRequest(requests,next){let filtered=requests.filter(r=>r.id!==next.id);return[next,...filtered]}function consentDenial(res){return res.ok?"consent_required":recordsDenialReasonOf(res.error)??"consent_required"}function withheldSentinel(){return makeEverfurError("internalError",{retryable:false})}function notReady(){return{ok:false,error:makeEverfurError("internalError",{retryable:true})}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var RECORDS_DASHBOARD=/* @__PURE__ */Object.freeze({name:"dashboard"});function initialRecordsNav(initial=RECORDS_DASHBOARD){/* @__PURE__ */
|
|
105
109
|
return Object.freeze({stack:/* @__PURE__ */Object.freeze([initial])})}function currentRecordsScreen(state){return state.stack[state.stack.length-1]??RECORDS_DASHBOARD}function pushRecordsNav(state,screen){/* @__PURE__ */
|
|
106
110
|
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack,screen])})}function replaceRecordsNav(state,screen){/* @__PURE__ */
|
|
107
|
-
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack.slice(0,-1),screen])})}function resetRecordsNav(screen){return initialRecordsNav(screen)}function popRecordsNav(state){return state.stack.length<=1?{state:state,handled:false}:{state:/* @__PURE__ */Object.freeze({stack:/* @__PURE__ */Object.freeze(state.stack.slice(0,-1))}),handled:true}}function transitionRecordsNav(state,to){return to.name==="dashboard"?resetRecordsNav(to):currentRecordsScreen(state).name==="upload"&&to.name==="request"?replaceRecordsNav(state,to):pushRecordsNav(state,to)}function recordsNavReducer(state,action){switch(action.type){case"push":return pushRecordsNav(state,action.screen);case"pop":return popRecordsNav(state).state;case"replace":return replaceRecordsNav(state,action.screen);case"reset":return resetRecordsNav(action.screen);case"navigate":return transitionRecordsNav(state,action.screen);default:return state}}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function recordCardSlot(slots){return slots.recordCard??slots.card}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base=face(theme,fallback);return base.fontWeight===void 0||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}var CLINIC_REQUEST_COPY=/* @__PURE__ */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’re authorizing",send:"Send request",sending:"Sending…",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:name=>`Typed signature: ${name}`,missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used",moreClinics:"Load more"});var CLINIC_PICKER_COPY=/* @__PURE__ */Object.freeze({title:CLINIC_REQUEST_COPY.title,titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Request ${name}’s records`:CLINIC_REQUEST_COPY.title},leadWeb:"Find the clinic that has them. We send a secure request and read every page they send back.",leadNative:"Find the clinic that has them.",searchLabelWeb:"Find the clinic",howItWorks:"How it works",howSteps:petName=>[{title:"We send a secure request",body:"With your permission, straight to the clinic’s records team."},{title:"The clinic sends the file",body:"Most clinics respond within 3 to 5 business days. We follow up for you."},{title:"Everfur reads every page",body:`Visits, vaccines, labs and prescriptions land in ${petName}’s records.`}],placeholder:CLINIC_REQUEST_COPY.placeholder,searchA11y:CLINIC_REQUEST_COPY.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload…",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:CLINIC_REQUEST_COPY.recentlyUsed,noMatch:query=>`No clinics match “${query}”. You can still request records using the option above.`,loadingMore:"Loading more…",loadMoreFailed:"Couldn’t load more. Tap to retry.",selectA11y:summary=>`Request records from ${summary}`,resultsCount:count=>count===1?"Showing 1 clinic":`Showing ${String(count)} clinics`,fallback:/* @__PURE__ */Object.freeze({title:"Can’t find your clinic?",subtitle:"Add it by email and we’ll request your records.",nameLabel:"Clinic name",namePlaceholder:"Your clinic’s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue"})});function clinicEmailStatusBadge(status){switch(status){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"}}}var KM_PER_MILE=1.609344;function milesLabel(km){return km===null||!Number.isFinite(km)?null:(km/KM_PER_MILE).toFixed(1)}function formatClinicDistanceLabel(km){let miles=milesLabel(km);return miles===null?"":`${miles} mi`}function formatClinicDistanceForA11y(km){let miles=milesLabel(km);return miles===null?"":`${miles} ${miles==="1.0"?"mile":"miles"} away`}var CLINIC_SEARCH_DEBOUNCE_MS=300,CLINIC_SEARCH_MIN_CHARS=2;var RECORDS_COPY=/* @__PURE__ */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"}),RECORDS_FOOTNOTE="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";var NAMELESS_PET="your pet";function petNameOr(petName){let trimmed=petName?.trim()??"";return trimmed.length>0?trimmed:NAMELESS_PET}var DASHBOARD_COPY=/* @__PURE__ */Object.freeze({title:"Health records",titleWeb:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s Records`:"Health records"},titleNative:petName=>{let name=petName?.trim()??"";return name.length>0?name:"Health records"},openTimeline:"Open timeline",loading:"Loading health records",lead:petName=>`${petNameOr(petName)}’s lab trends`,retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:disclaimer=>`Important: ${disclaimer}`}),MARKER_SUMMARY_COPY=/* @__PURE__ */Object.freeze({title:"At a glance",marker:"Marker",markers:"Markers",outOfRange:"out of range",inRange:"in range",noRange:"NO RANGE",subtitle:"Summary of your pet’s biomarkers",ask:"Ask about these markers",a11y:(total,inRange,outOfRange,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange} out of range${unknown>0?`, ${unknown} without a range`:""}.`}),MARKER_CAROUSEL_COPY=/* @__PURE__ */Object.freeze({counter:(index,total)=>`${index+1} of ${total}`,a11y:(name,index,total)=>name!==null?`${name}, marker ${index+1} of ${total}. Swipe left or right to see more markers.`:`Marker ${index+1} of ${total}`}),MARKER_CARD_COPY=/* @__PURE__ */Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we’ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askNamed:name=>{let trimmed=name?.trim()??"";return trimmed.length>0?`Ask about ${trimmed}`:"Ask about this marker"},status:label=>`Status: ${label}`,latestA11y:(reading,status,date)=>`Latest reading ${reading}, ${status}, collected ${date}`,readingsA11y:name=>`${name} readings, oldest to newest`}),PROVENANCE_COPY=/* @__PURE__ */Object.freeze({title:"Where this comes 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’t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading"}),IN_PROGRESS_COPY=/* @__PURE__ */Object.freeze({title:petName=>`${petNameOr(petName)}’s records are on the way`,anotherClinic:"Another clinic",anotherClinicSub:"Seen more than one vet? We ask each one.",uploadDocumentPhotoSub:"A PDF, or a photo of a paper record.",body:petName=>`We’re requesting ${petNameOr(petName)}’s records from your vet. This usually takes a few days; we’ll show lab trends here as soon as they arrive.`,a11y:petName=>`Records request in progress for ${petNameOr(petName)}.`,ask:"Ask about this request"}),REQUEST_PROMPT_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Add ${petNameOr(petName)}’s records`,firstRecordTitle:petName=>`Add ${petNameOr(petName)}’s first record`,body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicSub:"We send a secure request and read every page they send back.",uploadDocument:"Upload a document"});function isRecordsInProgress(request){return!isTerminalStatus(request.status)}function pickPetRecordsRequest(requests,petRef){if(petRef===null)return null;let forPet=requests.filter(r=>r.petRef===petRef);if(forPet.length===0)return null;let published=forPet.find(r=>r.status==="published");return published!==void 0?published:forPet.filter(isRecordsInProgress).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))[0]??null}function deriveRecordsDashboardState(args){if(args.hasMarkers)return"published";let request=pickPetRecordsRequest(args.requests,args.petRef);return request===null?"none":request.status==="published"||isRecordsInProgress(request)?"in_progress":"none"}function selectDashboardLoading(input){return input.recordLoading?true:input.hasFullRecord?false:input.markersLoading||!input.hasMarkers&&input.requestsLoading}function selectDashboardView(input){return selectDashboardLoading(input)?"loading":input.hasFullRecord?"record":input.markersError||input.recordError&&!input.hasMarkers?"error":input.dashboardState==="in_progress"&&input.drivingRequest!==null?"in_progress":input.dashboardState==="none"?"none":"labs_only"}function recordsEmptyVariantForError(error){return error?.httpStatus===429?"rate_limited":error?.httpStatus===502?"service_unavailable":"error"}var REQUEST_SCREEN_COPY=/* @__PURE__ */Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:(clinicName,petName)=>`${clinicName} has the request. We’ll let you know when ${petName}’s file arrives.`,sentLeadNative:petName=>`We’ll let you know when ${petName}’s file arrives.`,whereItStands:"Where it stands",details:"Request details",detailsClinic:"Clinic",detailsSent:"Sent",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there’s no reply by day 14.",waitingBanner:elapsedDays=>`It’s been ${elapsedDays} ${elapsedDays===1?"day":"days"}. Some clinics take a little longer; we’ve been following up automatically and are still on it. If there’s no reply by day 14, we’ll let you know.`,viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",convert:"Upload my own records instead",converting:"Switching…",convertHint:"We’ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we’ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting…",cancel:"Cancel request",cancelling:"Cancelling…",resend:"Resend email",resending:"Resending…",errors:/* @__PURE__ */Object.freeze({cancel:"We couldn’t cancel this request. Please try again.",retry:"We couldn’t retry this request. Please try again.",email:"We couldn’t update the clinic email. Please try again.",convert:"We couldn’t switch this to an upload. Please try again.",start:"We couldn’t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function fallbackFailureTitle(request){if(request.wireStatus==="clinic_declined")return"The clinic declined to release the records.";if(request.wireStatus==="clinic_responded_no_records")return"The clinic replied but didn’t include your records.";switch(request.failureCode){case"no_response":return"The clinic didn’t reply after several reminders over 14 days.";case"parse_timeout":case"parse_error":return"We received the records but couldn’t read them. Uploading a clean copy usually fixes this.";case"hard_bounce":case"dispatch_failed":return"We couldn’t deliver the email to the clinic.";default:return"This request didn’t go through."}}function failureTitle(request){let reason=request.failureReason?.trim()??"";return reason.length>0?reason:fallbackFailureTitle(request)}var MS_PER_DAY=1440*60*1e3;function requestElapsedDays(request,nowMs){if(!request.createdAt)return 0;let created=Date.parse(request.createdAt);if(Number.isNaN(created))return 0;let diff=nowMs-created;return diff<=0?0:Math.floor(diff/MS_PER_DAY)}var RECORDS_WAITING_LONG_DAYS=7;function requestWaitingTooLong(request,nowMs){return request.wireStatus!=="awaiting_response"?false:requestElapsedDays(request,nowMs)>=RECORDS_WAITING_LONG_DAYS}function isTerminalFailure(request){return request.status==="failed"}function shouldOfferRecovery(request){return isTerminalFailure(request)||request.canUpdateClinicEmail===true||request.canRetrySend===true}function useClinicPicker(controller,location){let[query,setQueryValue]=react.useState(""),[debouncedQuery,setDebounced]=react.useState(""),[clinics,setClinics]=react.useState([]),[cursor,setCursor]=react.useState(null),[recent,setRecent]=react.useState([]),[recentLoading,setRecentLoading]=react.useState(true),[initialLoading,setInitialLoading]=react.useState(false),[loadingMore,setLoadingMore]=react.useState(false),[error,setError]=react.useState(null),[pageError,setPageError]=react.useState(null),[attempt,setAttempt]=react.useState(0),generation=react.useRef(0),live=react.useRef(true),lat=location?.latitude,lng=location?.longitude,bias=react.useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);react.useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),react.useEffect(()=>{let alive=true;return setRecentLoading(true),controller.recentClinics({limit:5}).then(result=>{alive&&(result.ok&&setRecent(result.value.clinics),setRecentLoading(false))}).catch(()=>{alive&&setRecentLoading(false)}),()=>{alive=false}},[controller]),react.useEffect(()=>{let trimmed=query.trim();if(trimmed.length<CLINIC_SEARCH_MIN_CHARS){setDebounced("");return}let handle=setTimeout(()=>setDebounced(trimmed),CLINIC_SEARCH_DEBOUNCE_MS);return()=>clearTimeout(handle)},[query]);let isSearchActive=debouncedQuery.length>=CLINIC_SEARCH_MIN_CHARS;react.useEffect(()=>{let revision=generation.current+=1;if(setClinics([]),setCursor(null),setError(null),setPageError(null),!isSearchActive){setInitialLoading(false);return}setInitialLoading(true),controller.searchClinics({query:debouncedQuery,limit:25,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(result.value.clinics),setCursor(result.value.nextCursor)):setError(result.error),setInitialLoading(false))}).catch(()=>{live.current&&revision===generation.current&&setInitialLoading(false)})},[controller,debouncedQuery,isSearchActive,bias,attempt]);let loadMore=react.useCallback(()=>{if(!isSearchActive||cursor===null||loadingMore)return;let revision=generation.current;setLoadingMore(true),setPageError(null),controller.searchClinics({query:debouncedQuery,limit:25,cursor:cursor,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(current=>[...current,...result.value.clinics]),setCursor(result.value.nextCursor)):setPageError(result.error),setLoadingMore(false))}).catch(()=>{live.current&&revision===generation.current&&setLoadingMore(false)})},[controller,cursor,debouncedQuery,isSearchActive,loadingMore,bias]),setQuery=react.useCallback(value=>setQueryValue(value),[]),retry=react.useCallback(()=>setAttempt(n=>n+1),[]);return react.useMemo(()=>({query:query,debouncedQuery:debouncedQuery,isSearchActive:isSearchActive,clinics:clinics,recent:recent,recentLoading:recentLoading,initialLoading:initialLoading,loadingMore:loadingMore,hasNextPage:cursor!==null,error:error,pageError:pageError,setQuery:setQuery,loadMore:loadMore,retry:retry}),[query,debouncedQuery,isSearchActive,clinics,recent,recentLoading,initialLoading,loadingMore,cursor,error,pageError,setQuery,loadMore,retry])}function clinicDraftFor(clinic,freeText,email2,idempotencyKey){/* @__PURE__ */
|
|
108
|
-
return Object.freeze({key:clinic?.id??`free:${freeText??""}`,clinic:clinic,freeText:freeText,email:email2,idempotencyKey:idempotencyKey})}var RECORDS_CLINIC_BATCH_MAX=10,uuid=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),clinicSchema=/* @__PURE__ */zod.z.object({clinicId:/* @__PURE__ */uuid.optional(),clinicFreeText:text(200).refine(value=>value.trim().length>0).optional(),clinicEmail:text(320,3).refine(value=>!hasControl(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())).optional(),signatureId:/* @__PURE__ */uuid.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0)),inputSchema=/* @__PURE__ */zod.z.object({petRef:text(128),ownerName:text(200).refine(value=>value.trim().length>0&&!hasControl(value)),authorizationVersion:text(64),clinics:/* @__PURE__ */zod.z.array(clinicSchema).min(1).max(RECORDS_CLINIC_BATCH_MAX)}).strict(),responseSchema=/* @__PURE__ */zod.z.object({request_group_id:uuid,pet_ref:/* @__PURE__ */zod.z.string(),created_count:/* @__PURE__ */zod.z.number().int().nonnegative(),failed_count:/* @__PURE__ */zod.z.number().int().nonnegative(),results:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({idempotency_key:/* @__PURE__ */zod.z.string(),clinic_id:/* @__PURE__ */uuid.nullable().optional(),clinic_free_text:/* @__PURE__ */zod.z.string().nullable().optional(),created:/* @__PURE__ */zod.z.boolean(),request:/* @__PURE__ */zod.z.unknown().optional(),failure_code:/* @__PURE__ */zod.z.string().nullable().optional(),failure_reason:/* @__PURE__ */zod.z.string().nullable().optional()}))});function createRecordsClinicBatchClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async createClinicRequestBatch(input){if(!inputSchema.safeParse(input).success)return err(makeEverfurError("validationFailed",{retryable:false}));let result=await funnel.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,clinics:input.clinics.map(clinic=>({...clinic.clinicId!==void 0?{clinic_id:clinic.clinicId}:{clinic_free_text:clinic.clinicFreeText},...clinic.clinicEmail!==void 0?{clinic_email:clinic.clinicEmail}:{},...clinic.signatureId!==void 0?{signature_id:clinic.signatureId}:{signature_png_base64:clinic.signaturePngBase64},idempotency_key:clinic.idempotencyKey}))}});if(!result.ok)return result;let parsed=responseSchema.safeParse(result.value);if(!parsed.success||parsed.data.pet_ref!==input.petRef)return malformed();let results=[];for(let row of parsed.data.results){let request=row.request===void 0||row.request===null?null:mapRequestView(row.request);if(row.created!==(request!==null))return malformed();results.push(/* @__PURE__ */Object.freeze({idempotencyKey:row.idempotency_key,clinicId:row.clinic_id??null,clinicFreeText:row.clinic_free_text??null,created:row.created,request:request,failureCode:row.failure_code??null,failureReason:row.failure_reason??null}))}return ok(/* @__PURE__ */Object.freeze({requestGroupId:parsed.data.request_group_id,petRef:parsed.data.pet_ref,results:/* @__PURE__ */Object.freeze(results),createdCount:parsed.data.created_count,failedCount:parsed.data.failed_count}))}}}function malformed(){return err(makeEverfurError("internalError",{retryable:false}))}var uuid2=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),clinicPageSchema=/* @__PURE__ */zod.z.object({clinics:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({clinic_id:uuid2,name:/* @__PURE__ */zod.z.string().min(1),address:/* @__PURE__ */zod.z.string().nullable(),phone:/* @__PURE__ */zod.z.string().nullable(),email_status:/* @__PURE__ */zod.z.string(),distance_km:/* @__PURE__ */zod.z.number().finite().nonnegative().nullable()})),next_cursor:/* @__PURE__ */zod.z.string().nullable().optional()}),copySchema=/* @__PURE__ */zod.z.object({authorization_version:/* @__PURE__ */zod.z.string().min(1),scope_template:/* @__PURE__ */zod.z.string().min(1),authorization_template:/* @__PURE__ */zod.z.string().min(1)}),signaturePolicySchema=/* @__PURE__ */zod.z.object({upload_id:/* @__PURE__ */zod.z.string().min(1),upload_url:/* @__PURE__ */zod.z.string().url().refine(value=>value.startsWith("https://")),upload_fields:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string())});function createRecordsClinicController(deps){let{repository:repository}=deps,request=async pending=>{let result=await pending;if(!result.ok)return result;let mapped=mapRequestView(result.value);return mapped===null?malformed2():ok(mapped)},page=async pending=>{let result=await pending;if(!result.ok)return result;let parsed=clinicPageSchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({clinics:/* @__PURE__ */Object.freeze(parsed.data.clinics.map(clinic=>/* @__PURE__ */Object.freeze({id:clinic.clinic_id,name:clinic.name,address:clinic.address,phone:clinic.phone,emailStatus:clinic.email_status,distanceKm:clinic.distance_km}))),nextCursor:parsed.data.next_cursor??null})):malformed2()};return{searchClinics:(input={})=>page(repository.searchClinics(input)),recentClinics:(input={})=>page(repository.recentClinics(input)),async getRequestGroup(requestGroupId){let result=await repository.getRequestGroup(requestGroupId);if(!result.ok)return result;let group=mapRequestGroup(result.value);return group===null?malformed2():ok(group)},async getAuthorizationCopy(){let result=await repository.getAuthorizationCopy();if(!result.ok)return result;let parsed=copySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({authorizationVersion:parsed.data.authorization_version,scopeTemplate:parsed.data.scope_template,authorizationTemplate:parsed.data.authorization_template})):malformed2()},async createClinicRequest(input){let result=await request(repository.createClinicRequest(input));return result.ok&&result.value.petRef!==input.petRef?malformed2():result},retryRequest:id=>request(repository.retryRequest(id)),revokeRequest:id=>request(repository.revokeRequest(id)),updateClinicEmail:(id,clinicEmail)=>request(repository.updateClinicEmail(id,clinicEmail)),convertToUpload:id=>request(repository.convertToUpload(id)),async initiateSignatureUpload(fileSize){let result=await repository.initiateSignatureUpload(fileSize);if(!result.ok)return result;let parsed=signaturePolicySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({uploadId:parsed.data.upload_id,uploadUrl:parsed.data.upload_url,uploadFields:/* @__PURE__ */Object.freeze(parsed.data.upload_fields)})):malformed2()},async completeSignatureUpload(uploadId){let result=await repository.completeSignatureUpload(uploadId);if(!result.ok)return result;let parsed=zod.z.object({signature_id:uuid2}).safeParse(result.value);return parsed.success?ok(parsed.data.signature_id):malformed2()}}}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}var BASE2="/widget/v1/records",uuid3=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text2=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl2=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),email=text2(320,3).refine(value=>!hasControl2(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())),requestId=text2(64),recentSchema=/* @__PURE__ */zod.z.object({limit:/* @__PURE__ */zod.z.number().int().min(1).max(25).optional()}).strict(),searchSchema=/* @__PURE__ */zod.z.object({query:text2(200,0).optional(),location:/* @__PURE__ */zod.z.object({latitude:/* @__PURE__ */zod.z.number().finite().min(-90).max(90),longitude:/* @__PURE__ */zod.z.number().finite().min(-180).max(180)}).strict().optional(),limit:/* @__PURE__ */zod.z.number().int().min(1).max(100).optional(),cursor:text2(512,0).optional()}).strict(),createSchema=/* @__PURE__ */zod.z.object({petRef:text2(128),ownerName:text2(200).refine(value=>value.trim().length>0&&!hasControl2(value)),authorizationVersion:text2(64),clinicId:/* @__PURE__ */uuid3.optional(),clinicFreeText:text2(200).refine(value=>value.trim().length>0).optional(),clinicEmail:email.optional(),signatureId:/* @__PURE__ */uuid3.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0));function createHttpRecordsClinicRepository(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=(call,request,deduplicated=false)=>funnel.send(`records.clinic.${call}`,request,request.method==="GET"||deduplicated?void 0:{idempotent:false,maxAttempts:1}),recover=(id,action,body)=>requestId.safeParse(id).success?send(action,{method:"POST",path:`${BASE2}/requests/${encodeURIComponent(id)}/${action}`,...body?{body:body}:{}}):invalid();return{searchClinics(input){return searchSchema.safeParse(input).success?send("search",{method:"GET",path:`${BASE2}/clinics/search`,query:{q:input.query??"",lat:input.location?.latitude,lng:input.location?.longitude,limit:input.limit,cursor:input.cursor}}):invalid()},recentClinics(input){return recentSchema.safeParse(input).success?send("recent",{method:"GET",path:`${BASE2}/clinics/recent`,query:{limit:input.limit}}):invalid()},getRequestGroup(requestGroupId){return requestId.safeParse(requestGroupId).success?send("requestGroup",{method:"GET",path:`${BASE2}/request-groups/${encodeURIComponent(requestGroupId)}`}):invalid()},getAuthorizationCopy:()=>send("authorizationCopy",{method:"GET",path:`${BASE2}/authorization-copy`}),createClinicRequest(input){return createSchema.safeParse(input).success?send("create",{method:"POST",path:`${BASE2}/clinic-requests`,body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,idempotency_key:input.idempotencyKey,...input.clinicId!==void 0?{clinic_id:input.clinicId}:{clinic_free_text:input.clinicFreeText},...input.clinicEmail!==void 0?{clinic_email:input.clinicEmail}:{},...input.signatureId!==void 0?{signature_id:input.signatureId}:{signature_png_base64:input.signaturePngBase64}}},true):invalid()},retryRequest:id=>recover(id,"retry"),revokeRequest:id=>recover(id,"revoke"),convertToUpload:id=>recover(id,"convert-to-upload"),updateClinicEmail(id,clinicEmail){return email.safeParse(clinicEmail).success?recover(id,"clinic-email",{clinic_email:clinicEmail}):invalid()},initiateSignatureUpload(fileSize){return!Number.isInteger(fileSize)||fileSize<=0||fileSize>2*1024*1024?invalid():send("signatureInitiate",{method:"POST",path:`${BASE2}/signatures/initiate`,body:{content_type:"image/png",file_size:fileSize}})},completeSignatureUpload(uploadId){return/^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(uploadId)?send("signatureComplete",{method:"POST",path:`${BASE2}/signatures/complete`,body:{upload_id:uploadId}}):invalid()}}}function invalid(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsClinic(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),controller=react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicController({repository:createHttpRecordsClinicRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})})},[runtime,userRef,scopeEpoch]),active=react.useRef(controller);return react.useEffect(()=>(active.current=controller,()=>{active.current=null}),[controller]),react.useMemo(()=>{let run=async operation=>{if(userRef===null||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation();return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{searchClinics:input=>run(()=>controller.searchClinics(input)),recentClinics:input=>run(()=>controller.recentClinics(input)),getRequestGroup:id=>run(()=>controller.getRequestGroup(id)),getAuthorizationCopy:()=>run(()=>controller.getAuthorizationCopy()),createClinicRequest:input=>run(()=>controller.createClinicRequest(input)),retryRequest:id=>run(()=>controller.retryRequest(id)),revokeRequest:id=>run(()=>controller.revokeRequest(id)),updateClinicEmail:(id,email2)=>run(()=>controller.updateClinicEmail(id,email2)),convertToUpload:id=>run(()=>controller.convertToUpload(id)),initiateSignatureUpload:size=>run(()=>controller.initiateSignatureUpload(size)),completeSignatureUpload:id=>run(()=>controller.completeSignatureUpload(id))}},[controller,userRef])}function useEverfurRecordsClinicBatch(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicBatchClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch]),active=react.useRef(client);return react.useEffect(()=>(active.current=client,()=>{active.current=null}),[client]),react.useMemo(()=>({async createClinicRequestBatch(input){if(userRef===null||active.current!==client)return err(makeEverfurError("accessDenied"));let result=await client.createClinicRequestBatch(input);return active.current===client?result:err(makeEverfurError("accessDenied"))}}),[client,userRef])}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
|
|
111
|
+
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack.slice(0,-1),screen])})}function resetRecordsNav(screen){return initialRecordsNav(screen)}function popRecordsNav(state){return state.stack.length<=1?{state:state,handled:false}:{state:/* @__PURE__ */Object.freeze({stack:/* @__PURE__ */Object.freeze(state.stack.slice(0,-1))}),handled:true}}function transitionRecordsNav(state,to){return to.name==="dashboard"?resetRecordsNav(to):currentRecordsScreen(state).name==="upload"&&to.name==="request"?replaceRecordsNav(state,to):pushRecordsNav(state,to)}function recordsNavReducer(state,action){switch(action.type){case"push":return pushRecordsNav(state,action.screen);case"pop":return popRecordsNav(state).state;case"replace":return replaceRecordsNav(state,action.screen);case"reset":return resetRecordsNav(action.screen);case"navigate":return transitionRecordsNav(state,action.screen);default:return state}}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function recordCardSlot(slots){return slots.recordCard??slots.card}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var CLINIC_REQUEST_COPY=/* @__PURE__ */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’re authorizing",send:"Send request",sending:"Sending…",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:name=>`Typed signature: ${name}`,missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used",moreClinics:"Load more"});var CLINIC_PICKER_COPY=/* @__PURE__ */Object.freeze({title:CLINIC_REQUEST_COPY.title,titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Request ${name}’s records`:CLINIC_REQUEST_COPY.title},leadWeb:"Find the clinic that has them. We send a secure request and read every page they send back.",leadNative:"Find the clinic that has them.",searchLabelWeb:"Find the clinic",howItWorks:"How it works",howSteps:petName=>[{title:"We send a secure request",body:"With your permission, straight to the clinic’s records team."},{title:"The clinic sends the file",body:"Most clinics respond within 3 to 5 business days. We follow up for you."},{title:"Everfur reads every page",body:`Visits, vaccines, labs and prescriptions land in ${petName}’s records.`}],placeholder:CLINIC_REQUEST_COPY.placeholder,searchA11y:CLINIC_REQUEST_COPY.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload…",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:CLINIC_REQUEST_COPY.recentlyUsed,noMatch:query=>`No clinics match “${query}”. You can still request records using the option above.`,loadingMore:"Loading more…",loadMoreFailed:"Couldn’t load more. Tap to retry.",selectA11y:summary=>`Request records from ${summary}`,resultsCount:count=>count===1?"Showing 1 clinic":`Showing ${String(count)} clinics`,fallback:/* @__PURE__ */Object.freeze({title:"Can’t find your clinic?",subtitle:"Add it by email and we’ll request your records.",nameLabel:"Clinic name",namePlaceholder:"Your clinic’s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue"})});function clinicEmailStatusBadge(status){switch(status){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"}}}var KM_PER_MILE=1.609344;function milesLabel(km){return km===null||!Number.isFinite(km)?null:(km/KM_PER_MILE).toFixed(1)}function formatClinicDistanceLabel(km){let miles=milesLabel(km);return miles===null?"":`${miles} mi`}function formatClinicDistanceForA11y(km){let miles=milesLabel(km);return miles===null?"":`${miles} ${miles==="1.0"?"mile":"miles"} away`}var CLINIC_SEARCH_DEBOUNCE_MS=300,CLINIC_SEARCH_MIN_CHARS=2;var RECORDS_COPY=/* @__PURE__ */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"}),RECORDS_FOOTNOTE="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";var NAMELESS_PET="your pet";function petNameOr(petName){let trimmed=petName?.trim()??"";return trimmed.length>0?trimmed:NAMELESS_PET}var DASHBOARD_COPY=/* @__PURE__ */Object.freeze({title:"Health records",titleWeb:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s Records`:"Health records"},titleNative:petName=>{let name=petName?.trim()??"";return name.length>0?name:"Health records"},openTimeline:"Open timeline",loading:"Loading health records",lead:petName=>`${petNameOr(petName)}’s lab trends`,retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:disclaimer=>`Important: ${disclaimer}`}),MARKER_SUMMARY_COPY=/* @__PURE__ */Object.freeze({title:"At a glance",marker:"Marker",markers:"Markers",outOfRange:"out of range",inRange:"in range",noRange:"NO RANGE",subtitle:"Summary of your pet’s biomarkers",ask:"Ask about these markers",a11y:(total,inRange,outOfRange2,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange2} out of range${unknown>0?`, ${unknown} without a range`:""}.`}),MARKER_CAROUSEL_COPY=/* @__PURE__ */Object.freeze({counter:(index,total)=>`${index+1} of ${total}`,a11y:(name,index,total)=>name!==null?`${name}, marker ${index+1} of ${total}. Swipe left or right to see more markers.`:`Marker ${index+1} of ${total}`}),MARKER_CARD_COPY=/* @__PURE__ */Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we’ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askNamed:name=>{let trimmed=name?.trim()??"";return trimmed.length>0?`Ask about ${trimmed}`:"Ask about this marker"},status:label=>`Status: ${label}`,latestA11y:(reading,status,date2)=>`Latest reading ${reading}, ${status}, collected ${date2}`,readingsA11y:name=>`${name} readings, oldest to newest`}),PROVENANCE_COPY=/* @__PURE__ */Object.freeze({title:"Where this comes 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’t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading"}),IN_PROGRESS_COPY=/* @__PURE__ */Object.freeze({title:petName=>`${petNameOr(petName)}’s records are on the way`,anotherClinic:"Another clinic",anotherClinicSub:"Seen more than one vet? We ask each one.",uploadDocumentPhotoSub:"A PDF, or a photo of a paper record.",body:petName=>`We’re requesting ${petNameOr(petName)}’s records from your vet. This usually takes a few days; we’ll show lab trends here as soon as they arrive.`,a11y:petName=>`Records request in progress for ${petNameOr(petName)}.`,ask:"Ask about this request"}),REQUEST_PROMPT_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Add ${petNameOr(petName)}’s records`,firstRecordTitle:petName=>`Add ${petNameOr(petName)}’s first record`,body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicSub:"We send a secure request and read every page they send back.",uploadDocument:"Upload a document"});function isRecordsInProgress(request){return!isTerminalStatus(request.status)}function pickPetRecordsRequest(requests,petRef){if(petRef===null)return null;let forPet=requests.filter(r=>r.petRef===petRef);if(forPet.length===0)return null;let published=forPet.find(r=>r.status==="published");return published!==void 0?published:forPet.filter(isRecordsInProgress).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))[0]??null}function deriveRecordsDashboardState(args){if(args.hasMarkers)return"published";let request=pickPetRecordsRequest(args.requests,args.petRef);return request===null?"none":request.status==="published"||isRecordsInProgress(request)?"in_progress":"none"}function selectDashboardLoading(input){return input.recordLoading?true:input.hasFullRecord?false:input.markersLoading||!input.hasMarkers&&input.requestsLoading}function selectDashboardView(input){return selectDashboardLoading(input)?"loading":input.hasFullRecord?"record":input.markersError||input.recordError&&!input.hasMarkers?"error":input.dashboardState==="in_progress"&&input.drivingRequest!==null?"in_progress":input.dashboardState==="none"?"none":"labs_only"}function recordsEmptyVariantForError(error){return error?.httpStatus===429?"rate_limited":error?.httpStatus===502?"service_unavailable":"error"}var REQUEST_SCREEN_COPY=/* @__PURE__ */Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:(clinicName,petName)=>`${clinicName} has the request. We’ll let you know when ${petName}’s file arrives.`,sentLeadNative:petName=>`We’ll let you know when ${petName}’s file arrives.`,whereItStands:"Where it stands",details:"Request details",detailsClinic:"Clinic",detailsSent:"Sent",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there’s no reply by day 14.",waitingBanner:elapsedDays=>`It’s been ${elapsedDays} ${elapsedDays===1?"day":"days"}. Some clinics take a little longer; we’ve been following up automatically and are still on it. If there’s no reply by day 14, we’ll let you know.`,viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",convert:"Upload my own records instead",converting:"Switching…",convertHint:"We’ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we’ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting…",cancel:"Cancel request",cancelling:"Cancelling…",resend:"Resend email",resending:"Resending…",errors:/* @__PURE__ */Object.freeze({cancel:"We couldn’t cancel this request. Please try again.",retry:"We couldn’t retry this request. Please try again.",email:"We couldn’t update the clinic email. Please try again.",convert:"We couldn’t switch this to an upload. Please try again.",start:"We couldn’t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function fallbackFailureTitle(request){if(request.wireStatus==="clinic_declined")return"The clinic declined to release the records.";if(request.wireStatus==="clinic_responded_no_records")return"The clinic replied but didn’t include your records.";switch(request.failureCode){case"no_response":return"The clinic didn’t reply after several reminders over 14 days.";case"parse_timeout":case"parse_error":return"We received the records but couldn’t read them. Uploading a clean copy usually fixes this.";case"hard_bounce":case"dispatch_failed":return"We couldn’t deliver the email to the clinic.";default:return"This request didn’t go through."}}function failureTitle(request){let reason=request.failureReason?.trim()??"";return reason.length>0?reason:fallbackFailureTitle(request)}var MS_PER_DAY=1440*60*1e3;function requestElapsedDays(request,nowMs){if(!request.createdAt)return 0;let created=Date.parse(request.createdAt);if(Number.isNaN(created))return 0;let diff=nowMs-created;return diff<=0?0:Math.floor(diff/MS_PER_DAY)}var RECORDS_WAITING_LONG_DAYS=7;function requestWaitingTooLong(request,nowMs){return request.wireStatus!=="awaiting_response"?false:requestElapsedDays(request,nowMs)>=RECORDS_WAITING_LONG_DAYS}function isTerminalFailure(request){return request.status==="failed"}function shouldOfferRecovery(request){return isTerminalFailure(request)||request.canUpdateClinicEmail===true||request.canRetrySend===true}function useClinicPicker(controller,location){let[query,setQueryValue]=react.useState(""),[debouncedQuery,setDebounced]=react.useState(""),[clinics,setClinics]=react.useState([]),[cursor,setCursor]=react.useState(null),[recent,setRecent]=react.useState([]),[recentLoading,setRecentLoading]=react.useState(true),[initialLoading,setInitialLoading]=react.useState(false),[loadingMore,setLoadingMore]=react.useState(false),[error,setError]=react.useState(null),[pageError,setPageError]=react.useState(null),[attempt,setAttempt]=react.useState(0),generation=react.useRef(0),live=react.useRef(true),lat=location?.latitude,lng=location?.longitude,bias=react.useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);react.useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),react.useEffect(()=>{let alive=true;return setRecentLoading(true),controller.recentClinics({limit:5}).then(result=>{alive&&(result.ok&&setRecent(result.value.clinics),setRecentLoading(false))}).catch(()=>{alive&&setRecentLoading(false)}),()=>{alive=false}},[controller]),react.useEffect(()=>{let trimmed=query.trim();if(trimmed.length<CLINIC_SEARCH_MIN_CHARS){setDebounced("");return}let handle=setTimeout(()=>setDebounced(trimmed),CLINIC_SEARCH_DEBOUNCE_MS);return()=>clearTimeout(handle)},[query]);let isSearchActive=debouncedQuery.length>=CLINIC_SEARCH_MIN_CHARS;react.useEffect(()=>{let revision=generation.current+=1;if(setClinics([]),setCursor(null),setError(null),setPageError(null),!isSearchActive){setInitialLoading(false);return}setInitialLoading(true),controller.searchClinics({query:debouncedQuery,limit:25,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(result.value.clinics),setCursor(result.value.nextCursor)):setError(result.error),setInitialLoading(false))}).catch(()=>{live.current&&revision===generation.current&&setInitialLoading(false)})},[controller,debouncedQuery,isSearchActive,bias,attempt]);let loadMore=react.useCallback(()=>{if(!isSearchActive||cursor===null||loadingMore)return;let revision=generation.current;setLoadingMore(true),setPageError(null),controller.searchClinics({query:debouncedQuery,limit:25,cursor:cursor,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(current=>[...current,...result.value.clinics]),setCursor(result.value.nextCursor)):setPageError(result.error),setLoadingMore(false))}).catch(()=>{live.current&&revision===generation.current&&setLoadingMore(false)})},[controller,cursor,debouncedQuery,isSearchActive,loadingMore,bias]),setQuery=react.useCallback(value=>setQueryValue(value),[]),retry=react.useCallback(()=>setAttempt(n=>n+1),[]);return react.useMemo(()=>({query:query,debouncedQuery:debouncedQuery,isSearchActive:isSearchActive,clinics:clinics,recent:recent,recentLoading:recentLoading,initialLoading:initialLoading,loadingMore:loadingMore,hasNextPage:cursor!==null,error:error,pageError:pageError,setQuery:setQuery,loadMore:loadMore,retry:retry}),[query,debouncedQuery,isSearchActive,clinics,recent,recentLoading,initialLoading,loadingMore,cursor,error,pageError,setQuery,loadMore,retry])}function clinicDraftFor(clinic,freeText,email2,idempotencyKey){/* @__PURE__ */
|
|
112
|
+
return Object.freeze({key:clinic?.id??`free:${freeText??""}`,clinic:clinic,freeText:freeText,email:email2,idempotencyKey:idempotencyKey})}var RECORDS_CLINIC_BATCH_MAX=10,uuid=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),clinicSchema=/* @__PURE__ */zod.z.object({clinicId:/* @__PURE__ */uuid.optional(),clinicFreeText:text(200).refine(value=>value.trim().length>0).optional(),clinicEmail:text(320,3).refine(value=>!hasControl(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())).optional(),signatureId:/* @__PURE__ */uuid.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0)),inputSchema=/* @__PURE__ */zod.z.object({petRef:text(128),ownerName:text(200).refine(value=>value.trim().length>0&&!hasControl(value)),authorizationVersion:text(64),clinics:/* @__PURE__ */zod.z.array(clinicSchema).min(1).max(RECORDS_CLINIC_BATCH_MAX)}).strict(),responseSchema=/* @__PURE__ */zod.z.object({request_group_id:uuid,pet_ref:/* @__PURE__ */zod.z.string(),created_count:/* @__PURE__ */zod.z.number().int().nonnegative(),failed_count:/* @__PURE__ */zod.z.number().int().nonnegative(),results:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({idempotency_key:/* @__PURE__ */zod.z.string(),clinic_id:/* @__PURE__ */uuid.nullable().optional(),clinic_free_text:/* @__PURE__ */zod.z.string().nullable().optional(),created:/* @__PURE__ */zod.z.boolean(),request:/* @__PURE__ */zod.z.unknown().optional(),failure_code:/* @__PURE__ */zod.z.string().nullable().optional(),failure_reason:/* @__PURE__ */zod.z.string().nullable().optional()}))});function createRecordsClinicBatchClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async createClinicRequestBatch(input){if(!inputSchema.safeParse(input).success)return err(makeEverfurError("validationFailed",{retryable:false}));let result=await funnel.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,clinics:input.clinics.map(clinic=>({...clinic.clinicId!==void 0?{clinic_id:clinic.clinicId}:{clinic_free_text:clinic.clinicFreeText},...clinic.clinicEmail!==void 0?{clinic_email:clinic.clinicEmail}:{},...clinic.signatureId!==void 0?{signature_id:clinic.signatureId}:{signature_png_base64:clinic.signaturePngBase64},idempotency_key:clinic.idempotencyKey}))}});if(!result.ok)return result;let parsed=responseSchema.safeParse(result.value);if(!parsed.success||parsed.data.pet_ref!==input.petRef)return malformed();let results=[];for(let row of parsed.data.results){let request=row.request===void 0||row.request===null?null:mapRequestView(row.request);if(row.created!==(request!==null))return malformed();results.push(/* @__PURE__ */Object.freeze({idempotencyKey:row.idempotency_key,clinicId:row.clinic_id??null,clinicFreeText:row.clinic_free_text??null,created:row.created,request:request,failureCode:row.failure_code??null,failureReason:row.failure_reason??null}))}return ok(/* @__PURE__ */Object.freeze({requestGroupId:parsed.data.request_group_id,petRef:parsed.data.pet_ref,results:/* @__PURE__ */Object.freeze(results),createdCount:parsed.data.created_count,failedCount:parsed.data.failed_count}))}}}function malformed(){return err(makeEverfurError("internalError",{retryable:false}))}var uuid2=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),clinicPageSchema=/* @__PURE__ */zod.z.object({clinics:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({clinic_id:uuid2,name:/* @__PURE__ */zod.z.string().min(1),address:/* @__PURE__ */zod.z.string().nullable(),phone:/* @__PURE__ */zod.z.string().nullable(),email_status:/* @__PURE__ */zod.z.string(),distance_km:/* @__PURE__ */zod.z.number().finite().nonnegative().nullable()})),next_cursor:/* @__PURE__ */zod.z.string().nullable().optional()}),copySchema=/* @__PURE__ */zod.z.object({authorization_version:/* @__PURE__ */zod.z.string().min(1),scope_template:/* @__PURE__ */zod.z.string().min(1),authorization_template:/* @__PURE__ */zod.z.string().min(1)}),signaturePolicySchema=/* @__PURE__ */zod.z.object({upload_id:/* @__PURE__ */zod.z.string().min(1),upload_url:/* @__PURE__ */zod.z.string().url().refine(value=>value.startsWith("https://")),upload_fields:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string())});function createRecordsClinicController(deps){let{repository:repository}=deps,request=async pending=>{let result=await pending;if(!result.ok)return result;let mapped=mapRequestView(result.value);return mapped===null?malformed2():ok(mapped)},page=async pending=>{let result=await pending;if(!result.ok)return result;let parsed=clinicPageSchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({clinics:/* @__PURE__ */Object.freeze(parsed.data.clinics.map(clinic=>/* @__PURE__ */Object.freeze({id:clinic.clinic_id,name:clinic.name,address:clinic.address,phone:clinic.phone,emailStatus:clinic.email_status,distanceKm:clinic.distance_km}))),nextCursor:parsed.data.next_cursor??null})):malformed2()};return{searchClinics:(input={})=>page(repository.searchClinics(input)),recentClinics:(input={})=>page(repository.recentClinics(input)),async getRequestGroup(requestGroupId){let result=await repository.getRequestGroup(requestGroupId);if(!result.ok)return result;let group=mapRequestGroup(result.value);return group===null?malformed2():ok(group)},async getAuthorizationCopy(){let result=await repository.getAuthorizationCopy();if(!result.ok)return result;let parsed=copySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({authorizationVersion:parsed.data.authorization_version,scopeTemplate:parsed.data.scope_template,authorizationTemplate:parsed.data.authorization_template})):malformed2()},async createClinicRequest(input){let result=await request(repository.createClinicRequest(input));return result.ok&&result.value.petRef!==input.petRef?malformed2():result},retryRequest:id=>request(repository.retryRequest(id)),revokeRequest:id=>request(repository.revokeRequest(id)),updateClinicEmail:(id,clinicEmail)=>request(repository.updateClinicEmail(id,clinicEmail)),convertToUpload:id=>request(repository.convertToUpload(id)),async initiateSignatureUpload(fileSize){let result=await repository.initiateSignatureUpload(fileSize);if(!result.ok)return result;let parsed=signaturePolicySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({uploadId:parsed.data.upload_id,uploadUrl:parsed.data.upload_url,uploadFields:/* @__PURE__ */Object.freeze(parsed.data.upload_fields)})):malformed2()},async completeSignatureUpload(uploadId){let result=await repository.completeSignatureUpload(uploadId);if(!result.ok)return result;let parsed=zod.z.object({signature_id:uuid2}).safeParse(result.value);return parsed.success?ok(parsed.data.signature_id):malformed2()}}}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}var BASE2="/widget/v1/records",uuid3=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text2=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl2=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),email=text2(320,3).refine(value=>!hasControl2(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())),requestId=text2(64),recentSchema=/* @__PURE__ */zod.z.object({limit:/* @__PURE__ */zod.z.number().int().min(1).max(25).optional()}).strict(),searchSchema=/* @__PURE__ */zod.z.object({query:text2(200,0).optional(),location:/* @__PURE__ */zod.z.object({latitude:/* @__PURE__ */zod.z.number().finite().min(-90).max(90),longitude:/* @__PURE__ */zod.z.number().finite().min(-180).max(180)}).strict().optional(),limit:/* @__PURE__ */zod.z.number().int().min(1).max(100).optional(),cursor:text2(512,0).optional()}).strict(),createSchema=/* @__PURE__ */zod.z.object({petRef:text2(128),ownerName:text2(200).refine(value=>value.trim().length>0&&!hasControl2(value)),authorizationVersion:text2(64),clinicId:/* @__PURE__ */uuid3.optional(),clinicFreeText:text2(200).refine(value=>value.trim().length>0).optional(),clinicEmail:email.optional(),signatureId:/* @__PURE__ */uuid3.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0));function createHttpRecordsClinicRepository(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=(call,request,deduplicated=false)=>funnel.send(`records.clinic.${call}`,request,request.method==="GET"||deduplicated?void 0:{idempotent:false,maxAttempts:1}),recover=(id,action,body)=>requestId.safeParse(id).success?send(action,{method:"POST",path:`${BASE2}/requests/${encodeURIComponent(id)}/${action}`,...body?{body:body}:{}}):invalid();return{searchClinics(input){return searchSchema.safeParse(input).success?send("search",{method:"GET",path:`${BASE2}/clinics/search`,query:{q:input.query??"",lat:input.location?.latitude,lng:input.location?.longitude,limit:input.limit,cursor:input.cursor}}):invalid()},recentClinics(input){return recentSchema.safeParse(input).success?send("recent",{method:"GET",path:`${BASE2}/clinics/recent`,query:{limit:input.limit}}):invalid()},getRequestGroup(requestGroupId){return requestId.safeParse(requestGroupId).success?send("requestGroup",{method:"GET",path:`${BASE2}/request-groups/${encodeURIComponent(requestGroupId)}`}):invalid()},getAuthorizationCopy:()=>send("authorizationCopy",{method:"GET",path:`${BASE2}/authorization-copy`}),createClinicRequest(input){return createSchema.safeParse(input).success?send("create",{method:"POST",path:`${BASE2}/clinic-requests`,body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,idempotency_key:input.idempotencyKey,...input.clinicId!==void 0?{clinic_id:input.clinicId}:{clinic_free_text:input.clinicFreeText},...input.clinicEmail!==void 0?{clinic_email:input.clinicEmail}:{},...input.signatureId!==void 0?{signature_id:input.signatureId}:{signature_png_base64:input.signaturePngBase64}}},true):invalid()},retryRequest:id=>recover(id,"retry"),revokeRequest:id=>recover(id,"revoke"),convertToUpload:id=>recover(id,"convert-to-upload"),updateClinicEmail(id,clinicEmail){return email.safeParse(clinicEmail).success?recover(id,"clinic-email",{clinic_email:clinicEmail}):invalid()},initiateSignatureUpload(fileSize){return!Number.isInteger(fileSize)||fileSize<=0||fileSize>2*1024*1024?invalid():send("signatureInitiate",{method:"POST",path:`${BASE2}/signatures/initiate`,body:{content_type:"image/png",file_size:fileSize}})},completeSignatureUpload(uploadId){return/^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(uploadId)?send("signatureComplete",{method:"POST",path:`${BASE2}/signatures/complete`,body:{upload_id:uploadId}}):invalid()}}}function invalid(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsClinic(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),controller=react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicController({repository:createHttpRecordsClinicRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})})},[runtime,userRef,scopeEpoch]),active=react.useRef(controller);return react.useEffect(()=>(active.current=controller,()=>{active.current=null}),[controller]),react.useMemo(()=>{let run=async operation=>{if(userRef===null||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation();return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{searchClinics:input=>run(()=>controller.searchClinics(input)),recentClinics:input=>run(()=>controller.recentClinics(input)),getRequestGroup:id=>run(()=>controller.getRequestGroup(id)),getAuthorizationCopy:()=>run(()=>controller.getAuthorizationCopy()),createClinicRequest:input=>run(()=>controller.createClinicRequest(input)),retryRequest:id=>run(()=>controller.retryRequest(id)),revokeRequest:id=>run(()=>controller.revokeRequest(id)),updateClinicEmail:(id,email2)=>run(()=>controller.updateClinicEmail(id,email2)),convertToUpload:id=>run(()=>controller.convertToUpload(id)),initiateSignatureUpload:size=>run(()=>controller.initiateSignatureUpload(size)),completeSignatureUpload:id=>run(()=>controller.completeSignatureUpload(id))}},[controller,userRef])}function useEverfurRecordsClinicBatch(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicBatchClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch]),active=react.useRef(client);return react.useEffect(()=>(active.current=client,()=>{active.current=null}),[client]),react.useMemo(()=>({async createClinicRequestBatch(input){if(userRef===null||active.current!==client)return err(makeEverfurError("accessDenied"));let result=await client.createClinicRequestBatch(input);return active.current===client?result:err(makeEverfurError("accessDenied"))}}),[client,userRef])}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
|
|
109
113
|
return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
|
|
110
|
-
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let
|
|
114
|
+
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base2={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base2.disabled=d.disabled),/* @__PURE__ */Object.freeze(base2)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return react.useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=react.useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
111
115
|
return jsxRuntime.jsx(reactNative.View,{style:[styles.offstate,style],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${capability}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.skeletonBar})})}function OffState({decision:decision,style:style}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
|
|
112
116
|
return jsxRuntime.jsx(reactNative.View,{style:[styles.offstate,style],accessible:true,accessibilityRole:"text",accessibilityLabel:message,children:message.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return reactNative.StyleSheet.create({offstate:{minHeight:MIN_OFFSTATE_HEIGHT,justifyContent:"center",paddingHorizontal:space.lg,paddingVertical:space.md,backgroundColor:color.surfaceCream,borderRadius:radius.md,borderWidth:reactNative.StyleSheet.hairlineWidth,borderColor:color.brandBorder},offstateText:{...face(theme,"regular"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.normal),color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}})}var HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function MenuGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),bar2={width:size*.82,height:w,borderRadius:w,backgroundColor:color};/* @__PURE__ */
|
|
113
117
|
return jsxRuntime.jsxs(reactNative.View,{style:[box(size),{gap:size*.22}],...HIDDEN,children:[
|
|
114
118
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2}),
|
|
115
119
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2}),
|
|
116
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2})]})}function
|
|
120
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2})]})}function CheckGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
|
|
121
|
+
return jsxRuntime.jsx(reactNative.View,{style:box(size),...HIDDEN,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:size*.36,height:size*.66,marginTop:-size*.14,borderBottomWidth:w,borderRightWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})})}var CHEVRON_POSE={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:size,color:color,strokeWidth:strokeWidth,direction:direction}){let w=stroke(size,strokeWidth),side=size*.46,pose=CHEVRON_POSE[direction];/* @__PURE__ */
|
|
122
|
+
return jsxRuntime.jsx(reactNative.View,{style:box(size),...HIDDEN,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:side,height:side,borderRightWidth:w,borderBottomWidth:w,borderColor:color,marginTop:side*pose.marginTop,marginLeft:side*pose.marginLeft,transform:[{rotate:pose.rotate}]}})})}function UploadGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),head=size*.34;/* @__PURE__ */
|
|
117
123
|
return jsxRuntime.jsxs(reactNative.View,{style:box(size),...HIDDEN,children:[
|
|
118
124
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.06,width:head,height:head,borderTopWidth:w,borderLeftWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}}),
|
|
119
125
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:size*.1,width:w,height:size*.56,borderRadius:w,backgroundColor:color}}),
|
|
@@ -164,15 +170,15 @@ return jsxRuntime.jsx(WifiOffGlyph,{size:size,color:color});default:return null}
|
|
|
164
170
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.container,accessibilityRole:"summary",testID:testID,children:[
|
|
165
171
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"records-empty-glyph",children:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyGlyph,{variant:variant,size:GLYPH_SIZE,color:theme.color.brandInk})}),
|
|
166
172
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.title,children:copy.title}),
|
|
167
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.body,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAction,disabled:cooling,accessibilityRole:"button",accessibilityLabel:cooling?COOLING_A11Y_LABEL:label,accessibilityState:{disabled:cooling},style:[styles.action,cooling?styles.actionDisabled:null],testID:testID?`${testID}-action`:`records-empty-${variant}-action`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.actionLabel,children:label})}):null]})}function useStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles3(theme),[theme])}var GLYPH_SIZE=22,GLYPH_BOX=48;function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return reactNative.StyleSheet.create({container:{paddingVertical:space.xxl,paddingHorizontal:space.xl,alignItems:"center",gap:space.sm+space.xs/2},glyph:{width:GLYPH_BOX,height:GLYPH_BOX,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug)-1,color:color.brandInk,textAlign:"center"},body:{...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.normal),color:color.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:space.sm,minHeight:space.xxl+space.sm,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,backgroundColor:color.brand,alignItems:"center",justifyContent:"center",...slotBox(slots.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug)-1,...slotText(slots.primaryButton)}})}var RECORDS_SANDBOX_COPY=/* @__PURE__ */Object.freeze({note:"Test account: clinics are never contacted. Use records test mode to move a request forward.",clinicNotContacted:"Clinic not contacted",notEmailed:email2=>`This is a test account, so no email went to ${email2}.`,newClinicDirectSendNote:"This is a test account, so this clinic will not be emailed."});var NO_SUBSCRIPTION=()=>()=>{};function isSandboxSnapshot(snapshot){return snapshot?.livemode===false}function useEntitlementSource(){try{return useEverfurContext().runtime.entitlements??null}catch{return null}}function useRecordsSandboxTenant(){let source=useEntitlementSource(),subscribe2=react.useCallback(listener=>source===null?NO_SUBSCRIPTION():source.subscribe(listener),[source]),read=react.useCallback(()=>source===null?false:isSandboxSnapshot(source.getSnapshot()),[source]);return react.useSyncExternalStore(subscribe2,read,read)}function useBrandImage(uri){let[failed,setFailed]=react.useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandLogo({logoUrl:logoUrl,name:name,barStyle:barStyle,logoStyle:logoStyle,testID:testID}){let image=useBrandImage(logoUrl);return logoUrl===null||!image.shown?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}var RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var normalize=
|
|
173
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.body,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAction,disabled:cooling,accessibilityRole:"button",accessibilityLabel:cooling?COOLING_A11Y_LABEL:label,accessibilityState:{disabled:cooling},style:[styles.action,cooling?styles.actionDisabled:null],testID:testID?`${testID}-action`:`records-empty-${variant}-action`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.actionLabel,children:label})}):null]})}function useStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles3(theme),[theme])}var GLYPH_SIZE=22,GLYPH_BOX=48;function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return reactNative.StyleSheet.create({container:{paddingVertical:space.xxl,paddingHorizontal:space.xl,alignItems:"center",gap:space.sm+space.xs/2},glyph:{width:GLYPH_BOX,height:GLYPH_BOX,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug)-1,color:color.brandInk,textAlign:"center"},body:{...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.normal),color:color.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:space.sm,minHeight:space.xxl+space.sm,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,backgroundColor:color.brand,alignItems:"center",justifyContent:"center",...slotBox(slots.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug)-1,...slotText(slots.primaryButton)}})}var RECORDS_SANDBOX_COPY=/* @__PURE__ */Object.freeze({note:"Test account: clinics are never contacted. Use records test mode to move a request forward.",clinicNotContacted:"Clinic not contacted",notEmailed:email2=>`This is a test account, so no email went to ${email2}.`,newClinicDirectSendNote:"This is a test account, so this clinic will not be emailed."});var NO_SUBSCRIPTION=()=>()=>{};function isSandboxSnapshot(snapshot){return snapshot?.livemode===false}function useEntitlementSource(){try{return useEverfurContext().runtime.entitlements??null}catch{return null}}function useRecordsSandboxTenant(){let source=useEntitlementSource(),subscribe2=react.useCallback(listener=>source===null?NO_SUBSCRIPTION():source.subscribe(listener),[source]),read=react.useCallback(()=>source===null?false:isSandboxSnapshot(source.getSnapshot()),[source]);return react.useSyncExternalStore(subscribe2,read,read)}function useBrandImage(uri){let[failed,setFailed]=react.useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandLogo({logoUrl:logoUrl,name:name,barStyle:barStyle,logoStyle:logoStyle,testID:testID}){let image=useBrandImage(logoUrl);return logoUrl===null||!image.shown?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}var RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var normalize=text4=>text4.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text4=normalize(disclaimer);return text4.length===0||text4===FOOTNOTE}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds){let worst=ink=>grounds.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds,pole,target){let first=grounds[0];if(first===void 0)return pole;let reads=candidate=>grounds.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same2=(a,b)=>parseColor(a)===parseColor(b);return{success:!same2(c.success,compiled.success),warning:!same2(c.warningStrong,compiled.warningStrong)||!same2(c.cautionAccent,compiled.cautionAccent),info:!(same2(c.info,c.brandInk)&&same2(c.badgeBgInfo,c.brandSoft)&&same2(c.infoEdge,c.structureEdge))}}var SLOT_MIN_CONTRAST=4.5;function brandedSuccessInk(theme){if(!brandedStatus(theme).success)return null;let grounds=[theme.color.surface];return pushToContrast(theme.color.success,grounds,poleForGrounds(grounds),SLOT_MIN_CONTRAST)}var BUTTON_HEIGHT=52,SHEET_SCRIM="rgba(0,0,0,0.4)";function useScreenStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeScreenStyles(theme),[theme])}function DisclaimerBand({disclaimer:disclaimer,style:style}){let styles=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.band,style],accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(disclaimer),testID:"records-disclaimer-band",children:[
|
|
168
174
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.infoGlyphText,children:"i"})}),
|
|
169
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bandText,children:disclaimer})]})}function Pill({label:label,onPress:onPress,kind:kind="primary",disabled:disabled=false,busy:busy=false,accessibilityLabel:accessibilityLabel,accessibilityHint:accessibilityHint,testID:testID,style:style}){let styles=useScreenStyles(),theme=useEverfurTheme(),still=theme.motion.reducedMotion,box3=kind==="primary"?styles.pillPrimary:kind==="outline"?styles.pillOutline:kind==="danger"?styles.pillDanger:kind==="ask"?styles.pillAsk:styles.pillLink,
|
|
175
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bandText,children:disclaimer})]})}function Pill({label:label,onPress:onPress,kind:kind="primary",disabled:disabled=false,busy:busy=false,accessibilityLabel:accessibilityLabel,accessibilityHint:accessibilityHint,testID:testID,style:style}){let styles=useScreenStyles(),theme=useEverfurTheme(),still=theme.motion.reducedMotion,box3=kind==="primary"?styles.pillPrimary:kind==="outline"?styles.pillOutline:kind==="danger"?styles.pillDanger:kind==="ask"?styles.pillAsk:styles.pillLink,text4=kind==="primary"?styles.pillPrimaryLabel:kind==="danger"?styles.pillDangerLabel:kind==="ask"?styles.pillAskLabel:kind==="link"?styles.pillLinkLabel:styles.pillOutlineLabel;/* @__PURE__ */
|
|
170
176
|
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,disabled:disabled||busy,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??label,accessibilityHint:accessibilityHint,accessibilityState:{disabled:disabled||busy,busy:busy},style:({pressed:pressed})=>[styles.pill,box3,disabled?styles.pillDisabled:null,pressed&&!still?styles.pressed:null,style],testID:testID,children:[busy?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:kind==="primary"?theme.color.onPrimary:theme.color.brandInk}):null,
|
|
171
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:
|
|
177
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:label})]})}function Chip({label:label,tone:tone="neutral",testID:testID}){let styles=useScreenStyles(),{bg:bg,fg:fg}=styles.chipTones[tone],sentence=label.length>CHIP_WORD_MAX;/* @__PURE__ */
|
|
172
178
|
return jsxRuntime.jsx(reactNative.View,{style:[styles.chip,sentence?styles.chipSentence:null,bg],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.chipText,sentence?styles.chipSentenceText:null,fg],children:label})})}var CHIP_WORD_MAX=24;function SectionHeader({title:title,count:count}){let styles=useScreenStyles();/* @__PURE__ */
|
|
173
179
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.sectionHeader,children:[
|
|
174
180
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionTitle,accessibilityRole:"header",children:title}),count!==void 0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionCount,children:count}):null]})}function Chevron({direction:direction="right"}){let styles=useScreenStyles(),rotate=direction==="right"?"45deg":direction==="down"?"135deg":"-45deg";/* @__PURE__ */
|
|
175
|
-
return jsxRuntime.jsx(reactNative.View,{style:[styles.chevron,{transform:[{rotate:rotate}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function makeScreenStyles(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,
|
|
181
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.chevron,{transform:[{rotate:rotate}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function makeScreenStyles(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),recordCard=recordCardSlot(slots),cardText=slotText(recordCard),bannerText=slotText(slots.banner),bannerInk=slots.banner?.textColor,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,tone=(bg,fg)=>({bg:{backgroundColor:bg,borderColor:"transparent"},fg:{color:fg}}),edge=(line2,fg)=>({bg:{backgroundColor:color.surface,borderColor:line2},fg:{color:fg}});return{chipTones:{neutral:edge(color.brandBorderStrong,color.text.primary),info:tone(color.brandSoft,color.brandInk),warning:edge(color.cautionAccent,color.text.primary),critical:edge(color.danger,color.danger),positive:edge(color.success,brandedSuccessInk(theme)??color.brandInk)},...reactNative.StyleSheet.create({root:{flex:1,backgroundColor:color.background},body:{flex:1},content:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.lg},contentTight:{paddingHorizontal:space.sm,paddingBottom:space.xxl,gap:space.lg},inset:{paddingHorizontal:space.sm},section:{gap:space.sm+space.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.xs},sectionTitle:{...text4(size.subtitle,lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4},sectionCount:{...text4(size.bodyTight,lineHeight.snug,color.text.muted,"medium")},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.xs,...slotBox(recordCard,hairline)},creamCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.md,...slotBox(recordCard,hairline)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.md,paddingVertical:space.md},rowDivider:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:space.xs+space.xs/2},rowTitle:{...text4(size.body,lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text4(size.caption,lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text4(size.body+1,lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text4(size.caption,lineHeight.normal,color.text.muted),...cardText},chip:{minHeight:24,justifyContent:"center",borderRadius:radius.pill,borderWidth:1.5,paddingHorizontal:space.sm+space.xs/2,alignSelf:"flex-start"},chipText:{...text4(size.tiny+1,lineHeight.snug,color.text.primary,"monoBold"),letterSpacing:.7,textTransform:"uppercase"},chipSentence:{borderRadius:radius.md,paddingVertical:space.xs,alignSelf:"stretch"},chipSentenceText:{...text4(size.caption,lineHeight.normal,color.text.primary,"medium"),letterSpacing:0,textTransform:"none"},pill:{minHeight:BUTTON_HEIGHT,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm},pillPrimary:{backgroundColor:color.brand,...slotBox(slots.primaryButton)},pillPrimaryLabel:{...text4(size.body,lineHeight.snug,color.onPrimary,"bold"),...slotText(slots.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...text4(size.body,lineHeight.snug,color.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:color.danger,backgroundColor:color.surface},pillDangerLabel:{...text4(size.bodyTight,lineHeight.snug,color.danger,"bold")},pillAsk:{borderWidth:hairline,borderColor:color.borderRingCream,backgroundColor:color.surface},pillAskLabel:{...text4(size.body,lineHeight.snug,color.text.primary,"bold")},pillLink:{minHeight:touch,backgroundColor:"transparent",paddingHorizontal:space.sm},pillLinkLabel:{...text4(size.body,lineHeight.snug,color.linkInk,"bold")},pillDisabled:{opacity:.5},pressed:{transform:[{scale:RECORDS_MOTION.pressScale}]},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2,...slotBox(slots.banner)},infoNoteText:{flex:1,...text4(size.bodyTight,lineHeight.normal,color.text.primary),...bannerText},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCaution,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2},cautionNoteText:{flex:1,...text4(size.bodyTight,lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},statusText:text4(size.bodyTight,lineHeight.relaxed,color.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCritical,padding:space.md},errorText:{flex:1,...text4(size.bodyTight,lineHeight.normal,errorColor)},band:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,...slotBox(slots.banner)},bandText:{flex:1,...text4(size.caption,lineHeight.normal,color.text.secondary),...bannerText},infoGlyph:{width:space.md+space.xs/2,height:space.md+space.xs/2,borderRadius:radius.pill,borderWidth:1,borderColor:bannerInk??color.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...text4(size.small,lineHeight.tight,color.text.secondary,"bold"),...bannerText},chevron:{width:space.sm,height:space.sm,borderTopWidth:space.xs/2,borderRightWidth:space.xs/2,borderColor:color.text.muted},lead:{paddingHorizontal:space.sm,...text4(size.body+1,lineHeight.snug,color.text.primary,"bold")},field:{minHeight:touch,paddingHorizontal:space.md,paddingVertical:space.sm,borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...face(theme,"regular"),fontSize:size.body,...slotBox(slots.input,1),...slotText(slots.input)},fieldLabel:{...text4(size.bodyTight,lineHeight.normal,color.text.secondary,"medium")},muted:text4(size.caption,lineHeight.normal,color.text.muted),bodyText:text4(size.body,lineHeight.normal,color.text.primary)})}}var LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,BACK_LABEL="Back";function ScreenHeader({title:title,onBack:onBack,right:right,testID:testID,variant:variant="brand"}){let styles=useStyles2(),theme=useEverfurTheme(),logoUrl=theme.meta.logoUrl,row=/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:logoUrl===null?styles.row:styles.rowUnderLogo,testID:testID,children:[onBack?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onBack,accessibilityRole:"button",accessibilityLabel:BACK_LABEL,hitSlop:12,style:styles.back,testID:testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.back}),title.trim().length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:variant==="document"?styles.documentTitle:styles.title,accessibilityRole:"header",numberOfLines:1,children:title}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.spacer,accessibilityElementsHidden:true,importantForAccessibility:"no",testID:testID?`${testID}-spacer`:void 0}),
|
|
176
182
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.right,children:right??/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.back})})]}),header=logoUrl===null?row:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.bar,children:[
|
|
177
183
|
/* @__PURE__ */jsxRuntime.jsx(BrandLogo,{logoUrl:logoUrl,name:theme.meta.displayName,barStyle:styles.logoBar,logoStyle:styles.logo,testID:testID?`${testID}-logo`:void 0}),row]});/* @__PURE__ */
|
|
178
184
|
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[header,
|
|
@@ -195,7 +201,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:styles.downloadGlyph,accessibilit
|
|
|
195
201
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadHead}),
|
|
196
202
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadTray})]})}function useStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type}=theme,header=theme.slots.header,ink=header?.textColor??color.brandInk,rowBase={flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md,gap:space.sm},touch=space.xxl+space.md,chevron=space.md,stroke3=space.xs/2,glyph=space.lg+space.xs+space.xs/2;return reactNative.StyleSheet.create({row:{...rowBase,...slotBox(header)},rowUnderLogo:rowBase,bar:{...slotBox(header)},logoBar:{alignItems:"center",paddingTop:space.sm,paddingHorizontal:space.lg},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH},back:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},chevron:{width:chevron,height:chevron,borderLeftWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginLeft:space.xs},title:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.heading,lineHeight:Math.round(type.size.heading*type.lineHeight.tight)+1,color:ink},spacer:{flex:1},sandboxNote:{marginHorizontal:space.lg,marginBottom:space.md},documentTitle:{flex:1,textAlign:"center",...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),color:color.text.primary,...slotText(header)},right:{flexDirection:"row",alignItems:"center",gap:space.sm+space.xs/2},listGlyph:{width:glyph,height:glyph,justifyContent:"space-evenly"},listBar:{height:stroke3,borderRadius:stroke3,backgroundColor:ink},shareGlyph:{width:glyph-space.xs,height:glyph-space.xs},shareDot:{position:"absolute",width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs,borderWidth:stroke3,borderColor:ink},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:space.xs+space.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:space.xs,top:space.sm,width:space.sm+space.xs/2,height:stroke3,backgroundColor:ink},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:glyph-space.xs,height:glyph-space.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],borderRadius:stroke3},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:stroke3,backgroundColor:ink},downloadGlyph:{width:glyph-space.xs,height:glyph-space.xs,alignItems:"center"},downloadStem:{width:stroke3,height:space.sm+space.xs/2,backgroundColor:ink},downloadHead:{width:space.sm,height:space.sm,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginTop:-space.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:space.xs+space.xs/2,borderLeftWidth:stroke3,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink}})}var MIN_HEIGHT=120,MIN_TARGET=44;function RecordsGateOffState({reason:reason,onExit:onExit,exitLabel:exitLabel,style:style}){let{color:color,space:space,radius:radius,type:type}=useEverfurTheme();/* @__PURE__ */
|
|
197
203
|
return jsxRuntime.jsxs(reactNative.View,{testID:"records-gate-off",style:[{minHeight:MIN_HEIGHT,justifyContent:"center",gap:space.md,padding:space.lg,borderRadius:radius.md,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surfaceCream},style],children:[reason.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.bodyTight,color:color.text.muted},children:reason}):null,
|
|
198
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onExit,accessibilityRole:"button",accessibilityLabel:exitLabel,testID:"records-gate-off-exit",style:{minHeight:MIN_TARGET,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1.5,borderColor:color.brandInk},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsxRuntime.jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null)return dayLabel(Number(iso[1]),Number(iso[2])-1,Number(iso[3]));let ms=Date.parse(at);if(Number.isNaN(ms))return"-";let date=new Date(ms);return dayLabel(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate())}function dayLabel(year,month,day){let name=MONTHS[month];return name===void 0?"-":`${name} ${day}, ${year}`}function formatRecordsInstant(at){let parts=at?/^([\d-]{10}T[\d:]+)(\.\d+)?(.*)$/.exec(at):null,ms=parts?Date.parse(`${parts[1]}${(parts[2]??"").slice(0,4)}${parts[3]||"Z"}`):Number.NaN;if(Number.isNaN(ms))return formatRecordsDate(at);let date=new Date(ms);return dayLabel(date.getFullYear(),date.getMonth(),date.getDate())}function formatIdentityValue(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return value;let formatted=formatRecordsDate(value),day=Number(value.slice(8,10));return formatted==="-"||day<1||day>31?value:formatted}var DEPTH_COPY=/* @__PURE__ */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:date=>`Measured ${date}`,uploadedDocument:"Uploaded document",kind:/* @__PURE__ */Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:name=>`Dr. ${name}`,lot:lot=>`Lot ${lot}`,expires:date=>`Expires ${date}`});function markerStatusLabel(status){switch(status){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}}}function trajectoryLabel(trajectory,visitCount){return visitCount<2?null:`${trajectory==="flat"?"Holding steady":`Trending ${trajectory==="down"?"down":trajectory==="up"?"up":"steady"}`} over ${visitCount} visits`}function humanize(key){let spaced=key.replace(/_/g," ").trim();return spaced.length===0?key:spaced.charAt(0).toUpperCase()+spaced.slice(1)}var BODY_SYSTEM_LABEL=/* @__PURE__ */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 bodySystemLabel(system){return Object.prototype.hasOwnProperty.call(BODY_SYSTEM_LABEL,system)?BODY_SYSTEM_LABEL[system]:humanize(system)}var SOAP_SECTION_LABEL=/* @__PURE__ */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 soapSectionLabel(section){return Object.prototype.hasOwnProperty.call(SOAP_SECTION_LABEL,section)?SOAP_SECTION_LABEL[section]:humanize(section)}function formatWeightKg(weightKg){return weightKg===null||!Number.isFinite(weightKg)?"-":`${weightKg.toFixed(3).replace(/\.?0+$/,"")} kg`}function formatMarkerReading(value,unit,qualitative){if((value===null||!Number.isFinite(value))&&qualitative)return qualitative;if(value===null||!Number.isFinite(value))return"-";let num3=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num3} ${unit}`:num3}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}var RECORD_SCREEN_COPY=/* @__PURE__ */Object.freeze({title:"Visits & records",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:count=>`${count} ${count===1?"document":"documents"} from your vet ${count===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,needsAttention:"Needs 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:/* @__PURE__ */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:count=>`${count} ${count===1?"document":"documents"} on file`,inReviewChip:count=>`${count} in review`,beingVerified:count=>`${count} being verified`,beingVerifiedA11y:count=>`${count} ${count===1?"fact is":"facts are"} being verified`,pendingReview:"Pending review: ",dateRange:(from,to)=>`${formatRecordsDate(from)} to ${formatRecordsDate(to)}`,documents:"Sources on file",uploadedDocument:DEPTH_COPY.uploadedDocument,documentRowA11y:title=>`View what ${title} contributed to this record`,documentMeta:(pageCount,receivedAt)=>{let date=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date].filter(part=>part!==null);return parts.length>0?parts.join(" · "):null},identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:date=>`Last done ${date}`,overdue:"Overdue",due:date=>`Due ${date}`,askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:DEPTH_COPY.labResults,visits:DEPTH_COPY.visits,physicalExams:DEPTH_COPY.physicalExams,visitNotes:DEPTH_COPY.visitNotes,document:/* @__PURE__ */Object.freeze({title:"Health Record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s health record`:"Health Record"},download:"Download PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:date=>`Generated ${formatRecordsDate(date)}`,identity:"Identity",labs:"Blood & Lab Work",ref:band=>`Ref ${band}`,noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),ENTITY_SECTION_TITLE=/* @__PURE__ */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 entityTypeLabel(entityType){return Object.prototype.hasOwnProperty.call(ENTITY_SECTION_TITLE,entityType)?ENTITY_SECTION_TITLE[entityType]:humanize(entityType)}var ENTITY_SECTION_ORDER=/* @__PURE__ */Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function orderEntityTypes(types){let known=ENTITY_SECTION_ORDER.filter(type=>types.includes(type)),rest=types.filter(type=>!ENTITY_SECTION_ORDER.includes(type));return[...known,...rest]}function conflictSeverityMeta(severity){switch(severity){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"}}}function dueBadge(dueAt,nowMs){if(!dueAt)return null;let due=Date.parse(dueAt);if(Number.isNaN(due))return null;let overdue=due<nowMs-1440*60*1e3;return{label:overdue?RECORD_SCREEN_COPY.overdue:RECORD_SCREEN_COPY.due(formatRecordsDate(dueAt)),overdue:overdue}}function formatReferenceBand(point){return point===null?null:point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}`:point.refLow!==null?`≥ ${point.refLow}`:point.refHigh!==null?`≤ ${point.refHigh}`:null}var SHARE_COPY=/* @__PURE__ */Object.freeze({openA11y:"Share medical record",openA11yFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share ${name}’s record`:"Share medical record"},title:"Share medical record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Send ${name}’s record`:"Share medical record"},helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",leadNative:"Pick who it’s for; we include the right pages.",leadWebFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share a snapshot of what ${name}’s vets recorded. Pick who it’s for and we include the right pages.`:"Pick who it’s for; we include the right pages."},audienceLabel:"Who it’s for",audiences:/* @__PURE__ */Object.freeze({vet:"Vet",groomer:"Groomer",boarding:"Boarding"}),included:"What’s included",sendTo:"Send to",sendToPlaceholder:"vet@example.com…",send:"Send",sending:"Sending…",addEmailFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Add an email to send ${name}’s record.`:"Add an email to send the record."},emailInvalid:"That email doesn’t look right. Check it and try again.",emailFailed:"Could not send the email. Please try again.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",previewNative:"Preview what they get",createLink:"Create link and share",shareLinkNative:"Share link",linkTerms:"Sent as a secure link that works for 7 days. You can stop sharing it any time.",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn’t 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",turnOff:"Turn off",turnOffA11y:context=>`Turn off share link, ${context}`,turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",shareMessage:url=>`View this medical record: ${url}`,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:/* @__PURE__ */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.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",copiedNative:"Link copied. It works for 7 days.",copyFailedNative:url=>`Couldn’t copy. The link is ${url}`,turnedOff:"Link turned off.",sentTo:email2=>`Sent to ${email2}. The link works for 7 days.`})}),FULL_RECORD_LINES=/* @__PURE__ */Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),DEPTH_SECTIONS=/* @__PURE__ */Object.freeze([["encounters","encounters",DEPTH_COPY.visits],["lab_results","markers",DEPTH_COPY.labResults],["physical_exams","physical_exams",DEPTH_COPY.physicalExams]]);function shareIncludedLines(scope,features){let lines=[];scope.sections.includes("entities")&&(scope.entityTypes===null?lines.push(...FULL_RECORD_LINES):lines.push(...orderEntityTypes(scope.entityTypes).map(entityTypeLabel)));for(let[section,feature,label]of DEPTH_SECTIONS)scope.sections.includes(section)&&features[feature]===true&&lines.push(label);return scope.sections.includes("forward_looking")&&lines.push(RECORD_SCREEN_COPY.upcomingCare),/* @__PURE__ */Object.freeze(lines)}function isShareExpired(expiresAt,nowMs){if(!expiresAt)return false;let ms=Date.parse(expiresAt);return Number.isNaN(ms)?false:ms<=nowMs}function formatShareExpiry(expiresAt,expired){let date=formatRecordsDate(expiresAt);return date==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date}`:`Expires ${date}`}function buildShareRows(shares,urls,nowMs){let rows=shares.map(share=>{let expired=isShareExpired(share.expiresAt,nowMs),expiryLabel=formatShareExpiry(share.expiresAt,expired),createdDate=formatRecordsDate(share.createdAt),statusLabel=expired?"Expired":"Active",actionContext=expiryLabel.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return{shareId:share.shareId,shareUrl:urls[share.shareId]??null,active:!expired,statusLabel:statusLabel,expiryLabel:expiryLabel,createdLabel:createdDate==="-"?null:`Created ${createdDate}`,a11yLabel:`Share link. ${statusLabel}. ${expiryLabel}.`,actionContext:actionContext}});/* @__PURE__ */
|
|
204
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onExit,accessibilityRole:"button",accessibilityLabel:exitLabel,testID:"records-gate-off-exit",style:{minHeight:MIN_TARGET,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1.5,borderColor:color.brandInk},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsxRuntime.jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null)return dayLabel(Number(iso[1]),Number(iso[2])-1,Number(iso[3]));let ms=Date.parse(at);if(Number.isNaN(ms))return"-";let date2=new Date(ms);return dayLabel(date2.getUTCFullYear(),date2.getUTCMonth(),date2.getUTCDate())}function dayLabel(year,month,day){let name=MONTHS[month];return name===void 0?"-":`${name} ${day}, ${year}`}function formatRecordsInstant(at){let parts=at?/^([\d-]{10}T[\d:]+)(\.\d+)?(.*)$/.exec(at):null,ms=parts?Date.parse(`${parts[1]}${(parts[2]??"").slice(0,4)}${parts[3]||"Z"}`):Number.NaN;if(Number.isNaN(ms))return formatRecordsDate(at);let date2=new Date(ms);return dayLabel(date2.getFullYear(),date2.getMonth(),date2.getDate())}function formatIdentityValue(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return value;let formatted=formatRecordsDate(value),day=Number(value.slice(8,10));return formatted==="-"||day<1||day>31?value:formatted}function documentsNewestFirst(documents){let at=doc=>{let ms=doc.receivedAt===null?Number.NaN:Date.parse(doc.receivedAt);return Number.isNaN(ms)?Number.NEGATIVE_INFINITY:ms};return Object.values(documents).map((doc,index)=>({doc:doc,index:index,ms:at(doc)})).sort((a,b)=>b.ms===a.ms?a.index-b.index:b.ms>a.ms?1:-1).map(entry=>entry.doc)}var DEPTH_COPY=/* @__PURE__ */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:date2=>`Measured ${date2}`,uploadedDocument:"Uploaded document",kind:/* @__PURE__ */Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:name=>`Dr. ${name}`,lot:lot=>`Lot ${lot}`,expires:date2=>`Expires ${date2}`});function markerStatusLabel(status){switch(status){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}}}function trajectoryLabel(trajectory,visitCount){return visitCount<2?null:`${trajectory==="flat"?"Holding steady":`Trending ${trajectory==="down"?"down":trajectory==="up"?"up":"steady"}`} over ${visitCount} visits`}function humanize(key){let spaced=key.replace(/_/g," ").trim();return spaced.length===0?key:spaced.charAt(0).toUpperCase()+spaced.slice(1)}var BODY_SYSTEM_LABEL=/* @__PURE__ */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 bodySystemLabel(system){return Object.prototype.hasOwnProperty.call(BODY_SYSTEM_LABEL,system)?BODY_SYSTEM_LABEL[system]:humanize(system)}var SOAP_SECTION_LABEL=/* @__PURE__ */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 soapSectionLabel(section){return Object.prototype.hasOwnProperty.call(SOAP_SECTION_LABEL,section)?SOAP_SECTION_LABEL[section]:humanize(section)}function formatWeightKg(weightKg){return weightKg===null||!Number.isFinite(weightKg)?"-":`${weightKg.toFixed(3).replace(/\.?0+$/,"")} kg`}function formatMarkerReading(value,unit,qualitative){if((value===null||!Number.isFinite(value))&&qualitative)return qualitative;if(value===null||!Number.isFinite(value))return"-";let num5=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num5} ${unit}`:num5}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}var DOCUMENT_CLASS_LABELS=/* @__PURE__ */Object.freeze({lab_report:"Lab report",pims_export:"Practice export",vaccination_certificate:"Vaccination certificate",imaging_report:"Imaging report",discharge_summary:"Discharge summary",referral_letter:"Referral letter",clinician_note:"Clinician note",consent_form:"Consent form",invoice_estimate:"Invoice",prescription:"Prescription",genetic_report:"Genetic report"});function documentTitle(doc){let title=doc.title?.trim()??"";if(title.length>0)return title;let cls=doc.documentClass;return(cls&&Object.prototype.hasOwnProperty.call(DOCUMENT_CLASS_LABELS,cls)?DOCUMENT_CLASS_LABELS[cls]:void 0)??DEPTH_COPY.uploadedDocument}var RECORD_SCREEN_COPY=/* @__PURE__ */Object.freeze({title:"Visits & records",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:count=>`${count} ${count===1?"document":"documents"} from your vet ${count===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,needsAttention:"Needs 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:/* @__PURE__ */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:count=>`${count} ${count===1?"document":"documents"} on file`,inReviewChip:count=>`${count} in review`,beingVerified:count=>`${count} being verified`,beingVerifiedA11y:count=>`${count} ${count===1?"fact is":"facts are"} being verified`,pendingReview:"Pending review: ",dateRange:(from,to)=>`${formatRecordsDate(from)} to ${formatRecordsDate(to)}`,documents:"Sources on file",uploadedDocument:DEPTH_COPY.uploadedDocument,documentRowA11y:title=>`View what ${title} contributed to this record`,documentMeta:(pageCount,receivedAt)=>{let date2=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date2].filter(part=>part!==null);return parts.length>0?parts.join(" · "):null},identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:date2=>`Last done ${date2}`,overdue:"Overdue",due:date2=>`Due ${date2}`,askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:DEPTH_COPY.labResults,visits:DEPTH_COPY.visits,physicalExams:DEPTH_COPY.physicalExams,visitNotes:DEPTH_COPY.visitNotes,document:/* @__PURE__ */Object.freeze({title:"Health Record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s health record`:"Health Record"},download:"Download PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:date2=>`Generated ${formatRecordsDate(date2)}`,identity:"Identity",labs:"Blood & Lab Work",ref:band=>`Ref ${band}`,noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),ENTITY_SECTION_TITLE=/* @__PURE__ */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 entityTypeLabel(entityType){return Object.prototype.hasOwnProperty.call(ENTITY_SECTION_TITLE,entityType)?ENTITY_SECTION_TITLE[entityType]:humanize(entityType)}var ENTITY_SECTION_ORDER=/* @__PURE__ */Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function orderEntityTypes(types){let known=ENTITY_SECTION_ORDER.filter(type=>types.includes(type)),rest=types.filter(type=>!ENTITY_SECTION_ORDER.includes(type));return[...known,...rest]}function conflictSeverityMeta(severity){switch(severity){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"}}}function dueBadge(dueAt,nowMs){if(!dueAt)return null;let due=Date.parse(dueAt);if(Number.isNaN(due))return null;let overdue=due<nowMs-1440*60*1e3;return{label:overdue?RECORD_SCREEN_COPY.overdue:RECORD_SCREEN_COPY.due(formatRecordsDate(dueAt)),overdue:overdue}}function formatReferenceBand(point){return point===null?null:point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}`:point.refLow!==null?`≥ ${point.refLow}`:point.refHigh!==null?`≤ ${point.refHigh}`:null}var SHARE_COPY=/* @__PURE__ */Object.freeze({openA11y:"Share medical record",openA11yFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share ${name}’s record`:"Share medical record"},title:"Share medical record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Send ${name}’s record`:"Share medical record"},helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",leadNative:"Pick who it’s for; we include the right pages.",leadWebFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share a snapshot of what ${name}’s vets recorded. Pick who it’s for and we include the right pages.`:"Pick who it’s for; we include the right pages."},audienceLabel:"Who it’s for",audiences:/* @__PURE__ */Object.freeze({vet:"Vet",groomer:"Groomer",boarding:"Boarding"}),included:"What’s included",sendTo:"Send to",sendToPlaceholder:"vet@example.com…",send:"Send",sending:"Sending…",addEmailFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Add an email to send ${name}’s record.`:"Add an email to send the record."},emailInvalid:"That email doesn’t look right. Check it and try again.",emailFailed:"Could not send the email. Please try again.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",previewNative:"Preview what they get",createLink:"Create link and share",shareLinkNative:"Share link",linkTerms:"Sent as a secure link that works for 7 days. You can stop sharing it any time.",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn’t 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",turnOff:"Turn off",turnOffA11y:context=>`Turn off share link, ${context}`,turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",shareMessage:url=>`View this medical record: ${url}`,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:/* @__PURE__ */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.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",copiedNative:"Link copied. It works for 7 days.",copyFailedNative:url=>`Couldn’t copy. The link is ${url}`,turnedOff:"Link turned off.",sentTo:email2=>`Sent to ${email2}. The link works for 7 days.`})}),FULL_RECORD_LINES=/* @__PURE__ */Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),DEPTH_SECTIONS=/* @__PURE__ */Object.freeze([["encounters","encounters",DEPTH_COPY.visits],["lab_results","markers",DEPTH_COPY.labResults],["physical_exams","physical_exams",DEPTH_COPY.physicalExams]]);function shareIncludedLines(scope,features){let lines=[];scope.sections.includes("entities")&&(scope.entityTypes===null?lines.push(...FULL_RECORD_LINES):lines.push(...orderEntityTypes(scope.entityTypes).map(entityTypeLabel)));for(let[section,feature,label]of DEPTH_SECTIONS)scope.sections.includes(section)&&features[feature]===true&&lines.push(label);return scope.sections.includes("forward_looking")&&lines.push(RECORD_SCREEN_COPY.upcomingCare),/* @__PURE__ */Object.freeze(lines)}function isShareExpired(expiresAt,nowMs){if(!expiresAt)return false;let ms=Date.parse(expiresAt);return Number.isNaN(ms)?false:ms<=nowMs}function formatShareExpiry(expiresAt,expired){let date2=formatRecordsDate(expiresAt);return date2==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date2}`:`Expires ${date2}`}function buildShareRows(shares,urls,nowMs){let rows=shares.map(share=>{let expired=isShareExpired(share.expiresAt,nowMs),expiryLabel=formatShareExpiry(share.expiresAt,expired),createdDate=formatRecordsDate(share.createdAt),statusLabel=expired?"Expired":"Active",actionContext=expiryLabel.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return{shareId:share.shareId,shareUrl:urls[share.shareId]??null,active:!expired,statusLabel:statusLabel,expiryLabel:expiryLabel,createdLabel:createdDate==="-"?null:`Created ${createdDate}`,a11yLabel:`Share link. ${statusLabel}. ${expiryLabel}.`,actionContext:actionContext}});/* @__PURE__ */
|
|
199
205
|
return Object.freeze([...rows.filter(r=>r.active),...rows.filter(r=>!r.active)])}function shareErrorMessage(error,action){let status=error?.httpStatus;if(isRecordsConsentRequired(error)){if(action==="create"||action==="email")return"Records access for this pet is off, so a new link cannot be created.";if(action==="download")return"Records access for this pet is off, so the PDF cannot be downloaded."}if(status===429)return"You are creating links a little too fast. Wait a moment, then try again.";if(action==="revoke"&&(status===404||status===409||status===410))return"That link was already turned off.";if(status===401||status===403)return"You need to be signed in as this pet's owner to do that.";if(action==="email"&&(status===400||status===422||error?.code==="validationFailed"))return SHARE_COPY.emailInvalid;switch(action){case"create":return"Could not create a share link. Please try again.";case"revoke":return"Could not turn off that link. Please try again.";case"email":return SHARE_COPY.emailFailed;default:return"Could not download the record PDF. Please try again."}}function SkeletonBlock({width:width,height:height,radius:radius,style:style}){let{color:color,radius:radii}=useEverfurTheme();/* @__PURE__ */
|
|
200
206
|
return jsxRuntime.jsx(reactNative.View,{style:[{width:width,height:height,borderRadius:radius??radii.xs,backgroundColor:color.skeleton},style],accessibilityElementsHidden:true,importantForAccessibility:"no"})}var DONUT=180,BADGE_W=70,BADGE_H=22,CAROUSEL_H=300,DISCLAIMER_H=44,RAIL_DOT=24,TIMELINE_BUBBLE=34,TIMELINE_ROWS=6,CLINIC_ROWS=5;function DashboardSkeleton({testID:testID}){let styles=useStyles3(),action=key=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actionRow,children:[
|
|
201
207
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actionLeft,children:[
|
|
@@ -276,7 +282,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
|
276
282
|
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>onSelect(clinic),accessibilityRole:"button",accessibilityLabel:CLINIC_PICKER_COPY.selectA11y(summary),hitSlop:8,style:styles.item,testID:`records-clinic-${clinic.id}`,children:[
|
|
277
283
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.itemHeader,children:[
|
|
278
284
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemName,numberOfLines:1,children:clinic.name}),distance?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:distance}):null]}),clinic.address?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemAddress,numberOfLines:2,children:clinic.address}):null,clinic.phone?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:clinic.phone}):null,
|
|
279
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.badge,badge.tone==="positive"?styles.badgePositive:badge.tone==="caution"?styles.badgeCaution:styles.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.badgeLabel,badge.tone==="positive"?styles.badgePositiveText:badge.tone==="caution"?styles.badgeCautionText:styles.badgeNeutralText],children:badge.label})})]})}function useLocalStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles(theme),[theme])}function makeLocalStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),card=theme.slots.card,cardText=slotText(card);return reactNative.StyleSheet.create({lead:{...text3(type.size.body,type.lineHeight.normal,color.text.muted),paddingHorizontal:space.lg,paddingBottom:space.md},howCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.md,marginTop:space.sm,...slotBox(card)},howTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...cardText},howRow:{flexDirection:"row",gap:space.md},howNumber:{...face(theme,"monoBold"),fontSize:type.size.caption,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.brandInk,minWidth:space.xl},howText:{flex:1,gap:space.xs/2},howStepTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},howStepBody:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary),...cardText},searchBar:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.md+space.xs/2,height:space.xxl+space.md,marginHorizontal:space.lg,marginBottom:space.sm,borderRadius:radius.lg+space.xs/2,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.borderHairlineGreen,...slotBox(theme.slots.input,hairline)},searchInput:{flex:1,...text3(type.size.body,type.lineHeight.snug,color.text.primary),paddingVertical:0,...slotText(theme.slots.input)},clearGlyph:text3(type.size.heading,type.lineHeight.tight,color.text.muted),uploadWrap:{paddingHorizontal:space.lg,paddingBottom:space.md,gap:space.sm},list:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.md},sectionLabel:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:radius.lg-space.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:color.brandBorder,backgroundColor:color.surfaceCream,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.md,...slotBox(card,1)},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:space.md,minHeight:space.xxl+space.md},fallbackCopy:{flex:1,gap:space.xs/2},fallbackTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},fallbackSubtitle:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},fallbackForm:{gap:space.sm},item:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(card,1)},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},itemName:{flex:1,...text3(type.size.body,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),...cardText},itemDistance:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},itemAddress:{...text3(type.size.caption,type.lineHeight.normal,color.text.primary),...cardText},itemPhone:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},badge:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+1,paddingVertical:space.xs},badgePositive:{backgroundColor:color.badgeBgPositive},badgeCaution:{backgroundColor:color.badgeBgCaution},badgeNeutral:{backgroundColor:color.badgeBgNeutral},badgeLabel:{...text3(type.size.micro,type.lineHeight.snug,color.text.muted,"bold")},badgePositiveText:{color:color.success},badgeCautionText:{color:color.cautionAccent},badgeNeutralText:{color:color.text.muted},footer:{gap:space.sm,paddingTop:space.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,minHeight:space.xxl+space.md},footerRetry:{minHeight:space.xxl+space.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...text3(type.size.bodyTight,type.lineHeight.snug,color.brandInk,"bold")}})}var CLINIC_BATCH_COPY=/* @__PURE__ */Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${RECORDS_CLINIC_BATCH_MAX} clinics`,send:n=>`Send ${n} ${n===1?"request":"requests"}`,sending:"Sending…",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:name=>`Remove ${name}`,emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn’t send any of these requests. See the details below and try again.",partial:(created,total,failed)=>`${created} of ${total} requests sent. ${failed} couldn’t be sent.`,allSent:created=>`${created} ${created===1?"request":"requests"} sent.`,responded:(responded,total)=>`${responded} of ${total} ${total===1?"clinic":"clinics"} responded`});var CLINIC_FORM_SEARCH_LIMIT=25,CLINIC_FORM_RESULTS_STEP=5;function useVisibleClinics(clinics){let[state,setState]=react.useState({list:clinics,shown:CLINIC_FORM_RESULTS_STEP}),shown=state.list===clinics?state.shown:CLINIC_FORM_RESULTS_STEP,showMore=react.useCallback(()=>{setState(previous=>({list:clinics,shown:(previous.list===clinics?previous.shown:CLINIC_FORM_RESULTS_STEP)+CLINIC_FORM_RESULTS_STEP}))},[clinics]);return{visible:clinics.slice(0,shown),hasMore:clinics.length>shown,showMore:showMore}}var SignatureUploadLegError=class extends Error{constructor(){super("Signature upload failed"),this.name="SignatureUploadLegError"}};function isSignatureUploadLegFailure(error){return error instanceof SignatureUploadLegError}function renderClinicScope(copy,owner,pet,clinic){let fields={owner_name:owner,pet_name:pet,clinic_name:clinic},unknown=false,text3=copy.scopeTemplate.replace(/\{([^{}]+)\}/g,(_,key)=>Object.prototype.hasOwnProperty.call(fields,key)?fields[key]??"":(unknown=true,""));return unknown||/[{}]/.test(text3)?null:text3}function clinicNeedsEmail(clinic){return clinic===null||clinic.emailStatus!=="verified"&&clinic.emailStatus!=="unverified"}function useClinicRequestForm(props,controller,capture){let[ownerName,setOwner]=react.useState(props.ownerName),[query,setQueryValue]=react.useState(""),[clinic,setClinic]=react.useState(null),[email2,setEmail]=react.useState(""),[clinics,setClinics]=react.useState([]),[recent,setRecent]=react.useState([]),[copy,setCopy]=react.useState(null),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[searching,setSearching]=react.useState(false),[created,setCreated]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),active=react.useRef(false),locked=react.useRef(false),generation=react.useRef(0),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),attempt=react.useRef(null),captureAbort=react.useRef(null),lifetime=react.useRef(0);react.useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,attempt.current=null,captureAbort.current?.abort()}),[controller]),react.useEffect(()=>{let live=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),react.useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let invalidate=()=>{attempt.current=null,setError(null)},clinicName=clinic?.name??query.trim(),scope=copy?renderClinicScope(copy,ownerName.trim(),props.petName,clinicName):null,needsEmail=clinicNeedsEmail(clinic),results=useVisibleClinics(clinics),ready=!!(copy&&scope&&ownerName.trim()&&props.petName.trim()&&clinicName&&(!needsEmail||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email2.trim()))&&capture),search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},submit=async()=>{if(locked.current||created||!ready||!copy||!scope||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(!attempt.current){captureAbort.current=new AbortController;let signature=await capture({petRef:props.petRef,petName:props.petName,ownerName:ownerName.trim(),clinicName:clinicName,authorizationVersion:copy.authorizationVersion,scopeText:scope,signal:captureAbort.current.signal});if(!current()||signature===null)return;let target=clinic&&(!needsEmail||clinic.emailStatus==="none")?{clinicId:clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:email2.trim().toLowerCase()}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}if(!current())return;let result=await controller.createClinicRequest(attempt.current);if(!current())return;if(!result.ok){setError(result.error);return}if(result.value.petRef!==props.petRef){setError(makeEverfurError("internalError"));return}setCreated(result.value),attempt.current=null,props.onCreated?.(result.value)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}};return{ownerName:ownerName,query:query,clinic:clinic,email:email2,clinics:clinics,copy:copy,scope:scope,error:error,busy:busy,searching:searching,created:created,ready:ready,needsEmail:needsEmail,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0&&clinic===null?recent:[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(null),setEmail(""),setQueryValue(value))},setEmail(value){locked.current||(invalidate(),setEmail(value))},selectClinic(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(value),setQueryValue(value.name),setEmail(""))},invalidate:invalidate,search:search,submit:submit,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var EMAIL2=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function draftName(draft){return draft.clinic?.name??draft.freeText??""}function draftNeedsEmail(draft){return clinicNeedsEmail(draft.clinic)}function useClinicBatchForm(props,controller,batchClient,capture,registerSignature){let[ownerName,setOwner]=react.useState(props.ownerName),[query,setQueryValue]=react.useState(""),[clinics,setClinics]=react.useState([]),[recent,setRecent]=react.useState([]),[drafts,setDrafts]=react.useState([]),[copy,setCopy]=react.useState(null),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[searching,setSearching]=react.useState(false),[outcome,setOutcome]=react.useState(null),[group,setGroup]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),active=react.useRef(false),locked=react.useRef(false),generation=react.useRef(0),lifetime=react.useRef(0),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),signature=react.useRef(null),captureAbort=react.useRef(null);react.useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,signature.current=null,captureAbort.current?.abort()}),[controller,batchClient]),react.useEffect(()=>{let live=true;return setCopy(null),signature.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),react.useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let results=useVisibleClinics(clinics),invalidate=()=>{signature.current=null,setError(null)},names=drafts.map(draftName),scopes=copy?names.map(name=>renderClinicScope(copy,ownerName.trim(),props.petName,name)):[],scopeText=scopes.every(s=>s!==null)?scopes.join(`\n\n`):null,draftsReady=drafts.length>0&&drafts.every(draft=>!draftNeedsEmail(draft)||EMAIL2.test(draft.email.trim())),atCap=drafts.length>=RECORDS_CLINIC_BATCH_MAX,ready=!!(copy&&scopeText&&ownerName.trim()&&props.petName.trim()&&draftsReady&&capture)&&outcome===null,search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},add=draft=>{locked.current||atCap||outcome!==null||draft.clinic!==null&&drafts.some(d=>d.clinic?.id===draft.clinic?.id)||(invalidate(),setDrafts(current=>[...current,{...draft,key:keyFactory.current(),idempotencyKey:keyFactory.current()}]),setClinics([]),setQueryValue(""))},submit=async()=>{if(locked.current||outcome!==null||!ready||!copy||!scopeText||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(signature.current===null){captureAbort.current=new AbortController;let captured=await capture({petRef:props.petRef,petName:props.petName,ownerName:ownerName.trim(),clinicName:names.join(", "),authorizationVersion:copy.authorizationVersion,scopeText:scopeText,signal:captureAbort.current.signal});if(!current()||captured===null)return;if(signature.current=captured,captured.signaturePngBase64!==void 0&®isterSignature!==void 0){let abort=captureAbort.current;try{let registered=await registerSignature(captured.signaturePngBase64,abort.signal);if(!current())return;signature.current={signatureId:registered.signatureId}}catch(registrationError){if(!isSignatureUploadLegFailure(registrationError)||abort.signal.aborted)throw registrationError;if(!current())return}}}let signed=signature.current,items=drafts.map(draft=>({...draft.clinic!==null&&(!draftNeedsEmail(draft)||draft.clinic.emailStatus==="none")?{clinicId:draft.clinic.id}:{clinicFreeText:draftName(draft)},...draftNeedsEmail(draft)?{clinicEmail:draft.email.trim().toLowerCase()}:{},...signed.signatureId!==void 0?{signatureId:signed.signatureId}:{signaturePngBase64:signed.signaturePngBase64},idempotencyKey:draft.idempotencyKey})),result=await batchClient.createClinicRequestBatch({petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,clinics:items});if(!current())return;if(!result.ok){setError(result.error);return}setOutcome(result.value),props.onCreated?.(result.value),loadGroup(result.value.requestGroupId,run)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}},loadGroup=async(requestGroupId,run)=>{try{let result=await controller.getRequestGroup(requestGroupId);if(!active.current||lifetime.current!==run)return;result.ok&&result.value.petRef===props.petRef&&setGroup(result.value)}catch{}},refreshGroup=async()=>{outcome===null||locked.current||await loadGroup(outcome.requestGroupId,lifetime.current)};return{ownerName:ownerName,query:query,clinics:clinics,copy:copy,scopeText:scopeText,error:error,busy:busy,searching:searching,drafts:drafts,outcome:outcome,group:group,ready:ready,atCap:atCap,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0?recent.filter(clinic=>!drafts.some(d=>d.clinic?.id===clinic.id)):[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(generation.current+=1,setSearching(false),setClinics([]),setQueryValue(value))},search:search,addClinic(clinic){add({clinic:clinic,freeText:null,email:""})},addFreeText(){let name=query.trim();name.length!==0&&add({clinic:null,freeText:name,email:""})},setDraftEmail(key,email2){locked.current||(invalidate(),setDrafts(current=>current.map(draft=>draft.key===key?{...draft,email:email2}:draft)))},removeDraft(key){locked.current||outcome!==null||(invalidate(),setDrafts(current=>current.filter(draft=>draft.key!==key)))},submit:submit,refreshGroup:refreshGroup,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number",probeRef=react.useRef(null),[reading,setReading]=react.useState(null),frame=react.useRef(null),retry=react.useRef(null),mounted=react.useRef(true),stopRetry=react.useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);react.useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=react.useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,reactNative.Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=react.useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return react.useMemo(()=>{if(!lifts)return{avoidingProps:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function trustedSignatureUploadUrl(value){try{let url=new URL(value);if(url.protocol!=="https:"||url.username||url.password||url.port&&url.port!=="443")return!1;let host=url.hostname.toLowerCase();return host==="s3.amazonaws.com"||host.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(host)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(host)||host==="s3-accelerate.amazonaws.com"||host.endsWith(".s3-accelerate.amazonaws.com")||host==="s3-accelerate.dualstack.amazonaws.com"||host.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}var FAILED="Signature upload failed",UPLOAD_TIMEOUT_MS=3e4;function base64ByteLength(base64){let padding=base64.endsWith("==")?2:base64.endsWith("=")?1:0;return Math.floor(base64.length*3/4)-padding}async function registerRnSignature(signaturePngBase64,controller,signal,fetchImpl){let fail=()=>new Error(FAILED),size=base64ByteLength(signaturePngBase64);if(size<=0||signal.aborted)throw fail();let initiated=await controller.initiateSignatureUpload(size);if(!initiated.ok||signal.aborted||!trustedSignatureUploadUrl(initiated.value.uploadUrl))throw fail();let form=new FormData;for(let[key,value]of Object.entries(initiated.value.uploadFields))form.append(key,value);form.append("file",{uri:`data:image/png;base64,${signaturePngBase64}`,name:"signature.png",type:"image/png"});let uploadAbort=new AbortController,onAbort=()=>uploadAbort.abort();signal.addEventListener("abort",onAbort,{once:true});let timer=setTimeout(onAbort,UPLOAD_TIMEOUT_MS);try{if(!(await(fetchImpl??fetch)(initiated.value.uploadUrl,{method:"POST",body:form,credentials:"omit",signal:uploadAbort.signal})).ok||signal.aborted)throw fail()}catch{throw signal.aborted?fail():new SignatureUploadLegError}finally{clearTimeout(timer),signal.removeEventListener("abort",onAbort)}let completed=await controller.completeSignatureUpload(initiated.value.uploadId);if(!completed.ok||signal.aborted)throw fail();return{signatureId:completed.value}}var SIGNATURE_CANVAS=/* @__PURE__ */Object.freeze({width:360,height:120});function blank(width,height){return{width:width,height:height,pixels:new Uint8Array(width*height)}}function stamp(bitmap,cx,cy,radius){for(let dy=-radius;dy<=radius;dy+=1)for(let dx=-radius;dx<=radius;dx+=1){if(dx*dx+dy*dy>radius*radius+radius)continue;let x=cx+dx,y=cy+dy;x<0||y<0||x>=bitmap.width||y>=bitmap.height||(bitmap.pixels[y*bitmap.width+x]=1)}}var MAX_STEPS_PER_STROKE=16384;function padPoint(point,bitmap){let[x,y]=point;if(!Number.isFinite(x)||!Number.isFinite(y))return null;let cx=Math.min(2*bitmap.width,Math.max(-bitmap.width,Math.round(x))),cy=Math.min(2*bitmap.height,Math.max(-bitmap.height,Math.round(y)));return[cx,cy]}function line(bitmap,from,to,radius,budget){let[x0,y0]=from,[x1,y1]=to,dx=Math.abs(x1-x0),dy=-Math.abs(y1-y0),sx=x0<x1?1:-1,sy=y0<y1?1:-1,error=dx+dy,steps=0;for(;steps<budget&&(stamp(bitmap,x0,y0,radius),steps+=1,!(x0===x1&&y0===y1));){let twice=2*error;twice>=dy&&(error+=dy,x0+=sx),twice<=dx&&(error+=dx,y0+=sy)}return steps}function rasterizeStrokes(strokes,penRadius=1){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height);for(let stroke3 of strokes){let points=[];for(let point of stroke3){let clamped=padPoint(point,bitmap);clamped!==null&&points.push(clamped)}if(points.length===0)continue;if(points.length===1){let[x,y]=points[0];stamp(bitmap,x,y,penRadius);continue}let budget=MAX_STEPS_PER_STROKE;for(let i=1;i<points.length&&budget>0;i+=1)budget-=line(bitmap,points[i-1],points[i],penRadius,budget)}return bitmap}var FONT_ORDER="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",FONT_ROWS="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",FONT_DIGITS="0123456789abcdefghijklmnopqrstuv",GLYPH_W=5,GLYPH_H=7,ADVANCE=GLYPH_W+1;function glyphRow(char,row){let index=FONT_ORDER.indexOf(char);return index<0?0:FONT_DIGITS.indexOf(FONT_ROWS.charAt(index*GLYPH_H+row))}function rasterizeTypedName(name){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height),text3=name.trim();if(text3.length===0)return bitmap;let chars=[...text3],scale=4;for(;scale>1&&(chars.length*ADVANCE-1)*scale>bitmap.width-8;)scale-=1;let textWidth=(chars.length*ADVANCE-1)*scale,x0=Math.max(0,Math.floor((bitmap.width-textWidth)/2)),y0=Math.floor((bitmap.height-GLYPH_H*scale)/2);return chars.forEach((char,i)=>{let gx=x0+i*ADVANCE*scale;for(let row=0;row<GLYPH_H;row+=1){let bits=glyphRow(char,row);for(let col=0;col<GLYPH_W;col+=1)if((bits>>GLYPH_W-1-col&1)!==0)for(let sy=0;sy<scale;sy+=1)for(let sx=0;sx<scale;sx+=1){let x=gx+col*scale+sx,y=y0+row*scale+sy;x<bitmap.width&&y<bitmap.height&&(bitmap.pixels[y*bitmap.width+x]=1)}}}),bitmap}var BitWriter=class{constructor(){this.bytes=[];this.acc=0;this.count=0}writeBits(value,count){for(this.acc|=value<<this.count,this.count+=count;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8}writeCode(code,length){let reversed=0;for(let i=0;i<length;i+=1)reversed=reversed<<1|code>>i&1;this.writeBits(reversed,length)}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};function writeLiteral(out,symbol){symbol<144?out.writeCode(48+symbol,8):symbol<256?out.writeCode(400+(symbol-144),9):symbol<280?out.writeCode(symbol-256,7):out.writeCode(192+(symbol-280),8)}var LENGTH_BASE=[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],LENGTH_EXTRA=[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],DIST_BASE=[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],DIST_EXTRA=[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 writeMatch(out,length,distance){let li=LENGTH_BASE.length-1;for(;LENGTH_BASE[li]>length;)li-=1;writeLiteral(out,257+li),LENGTH_EXTRA[li]>0&&out.writeBits(length-LENGTH_BASE[li],LENGTH_EXTRA[li]);let di=DIST_BASE.length-1;for(;DIST_BASE[di]>distance;)di-=1;out.writeCode(di,5),DIST_EXTRA[di]>0&&out.writeBits(distance-DIST_BASE[di],DIST_EXTRA[di])}var WINDOW=32768,MIN_MATCH=3,MAX_MATCH=258,HASH_BITS=15,CHAIN_LIMIT=64;function deflate(input){let out=new BitWriter;out.writeBits(1,1),out.writeBits(1,2);let head=new Int32Array(1<<HASH_BITS).fill(-1),prev=new Int32Array(input.length).fill(-1),hashAt=i2=>(input[i2]<<10^input[i2+1]<<5^input[i2+2])&(1<<HASH_BITS)-1,insert=i2=>{if(i2+MIN_MATCH>input.length)return;let h=hashAt(i2);prev[i2]=head[h],head[h]=i2},i=0;for(;i<input.length;){let bestLength=0,bestDistance=0;if(i+MIN_MATCH<=input.length){let candidate=head[hashAt(i)],chain=0,limit=Math.min(MAX_MATCH,input.length-i);for(;candidate>=0&&chain<CHAIN_LIMIT&&i-candidate<=WINDOW;){let length=0;for(;length<limit&&input[candidate+length]===input[i+length];)length+=1;if(length>bestLength&&(bestLength=length,bestDistance=i-candidate,length===limit))break;candidate=prev[candidate],chain+=1}}if(bestLength>=MIN_MATCH){writeMatch(out,bestLength,bestDistance);for(let k=0;k<bestLength;k+=1)insert(i+k);i+=bestLength}else writeLiteral(out,input[i]),insert(i),i+=1}return writeLiteral(out,256),out.finish()}function adler32(bytes){let a=1,b=0;for(let byte2 of bytes)a=(a+byte2)%65521,b=(b+a)%65521;return(b<<16|a)>>>0}var crcTable=null;function crc32(bytes){if(crcTable===null){crcTable=new Uint32Array(256);for(let n=0;n<256;n+=1){let c=n;for(let k=0;k<8;k+=1)c=c&1?3988292384^c>>>1:c>>>1;crcTable[n]=c>>>0}}let crc=4294967295;for(let byte2 of bytes)crc=crcTable[(crc^byte2)&255]^crc>>>8;return(crc^4294967295)>>>0}function u32(value){return[value>>>24&255,value>>>16&255,value>>>8&255,value&255]}function chunk(type,data){let typed=Uint8Array.from([...type].map(c=>c.charCodeAt(0))),body=new Uint8Array(typed.length+data.length);return body.set(typed,0),body.set(data,typed.length),[...u32(data.length),...body,...u32(crc32(body))]}var BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function toBase64(bytes){let out="";for(let i=0;i<bytes.length;i+=3){let a=bytes[i],b=i+1<bytes.length?bytes[i+1]:0,c=i+2<bytes.length?bytes[i+2]:0,triple=a<<16|b<<8|c;out+=BASE64.charAt(triple>>18&63)+BASE64.charAt(triple>>12&63),out+=i+1<bytes.length?BASE64.charAt(triple>>6&63):"=",out+=i+2<bytes.length?BASE64.charAt(triple&63):"="}return out}function encodeSignaturePng(bitmap){let{width:width,height:height,pixels:pixels}=bitmap,stride=Math.ceil(width/8)+1,raw=new Uint8Array(stride*height);for(let y=0;y<height;y+=1){let rowStart=y*stride;raw[rowStart]=0,raw.fill(255,rowStart+1,rowStart+stride);for(let x=0;x<width;x+=1)if(pixels[y*width+x]===1){let index=rowStart+1+(x>>3);raw[index]=raw[index]&~(128>>(x&7))}}let compressed=deflate(raw),idat=new Uint8Array(2+compressed.length+4);idat[0]=120,idat[1]=1,idat.set(compressed,2),idat.set(u32(adler32(raw)),2+compressed.length);let ihdr=Uint8Array.from([...u32(width),...u32(height),1,0,0,0,0]),png=Uint8Array.from([137,80,78,71,13,10,26,10,...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))]);return toBase64(png)}var SIGNATURE_STROKE_WIDTH=2.6,INK="#111111";function strokeSegments(strokes,scale){let segments=[];return strokes.forEach((stroke3,s)=>{let at=i=>{let p=stroke3[i];return[p[0]/scale,p[1]/scale]};if(stroke3.length===1){let[x,y]=at(0);segments.push({key:`${s}-0`,cx:x,cy:y,length:0,angle:0});return}for(let i=1;i<stroke3.length;i+=1){let[x0,y0]=at(i-1),[x1,y1]=at(i);segments.push({key:`${s}-${i}`,cx:(x0+x1)/2,cy:(y0+y1)/2,length:Math.hypot(x1-x0,y1-y0),angle:Math.atan2(y1-y0,x1-x0)})}}),segments}var MIN_DRAWN_POINTS=8,MIN_MOVE=2;function SignaturePad({onChange:onChange,disabled:disabled=false}){let styles=useStyles4(),[mode,setMode]=react.useState("draw"),[typed,setTyped]=react.useState(""),[strokes,setStrokes]=react.useState([]),[width,setWidth]=react.useState(0),current=react.useRef([]),drawing=react.useRef(null),scale=width>0?SIGNATURE_CANVAS.width/width:1,scaleRef=react.useRef(scale);scaleRef.current=scale;let disabledRef=react.useRef(disabled);disabledRef.current=disabled,react.useEffect(()=>{if(mode==="type"){callHost(onChange,typed.trim().length>0?encodeSignaturePng(rasterizeTypedName(typed)):null);return}let points=strokes.reduce((n,stroke3)=>n+stroke3.length,0);callHost(onChange,points>=MIN_DRAWN_POINTS?encodeSignaturePng(rasterizeStrokes(strokes)):null)},[mode,typed,strokes,onChange]);let point=event=>{let{locationX:locationX,locationY:locationY}=event.nativeEvent;return[locationX*scaleRef.current,locationY*scaleRef.current]},commitStroke=()=>{let finished=current.current,inProgress=drawing.current;current.current=[],drawing.current=null,setStrokes(committed=>[...committed.filter(s=>s!==inProgress),finished])},responder=react.useMemo(()=>reactNative.PanResponder.create({onStartShouldSetPanResponder:()=>!disabledRef.current,onMoveShouldSetPanResponder:()=>!disabledRef.current,onPanResponderTerminationRequest:()=>false,onPanResponderGrant:event=>{current.current=[point(event)]},onPanResponderMove:event=>{let next=point(event),last=current.current[current.current.length-1];if(last!==void 0&&Math.abs(last[0]-next[0])<MIN_MOVE&&Math.abs(last[1]-next[1])<MIN_MOVE)return;current.current=[...current.current,next];let previous=drawing.current,trail=current.current;drawing.current=trail,setStrokes(committed=>[...committed.filter(s=>s!==previous),trail])},onPanResponderRelease:()=>commitStroke(),onPanResponderTerminate:()=>commitStroke()}),[]),clear=react.useCallback(()=>{disabledRef.current||(current.current=[],drawing.current=null,setStrokes([]),setTyped(""))},[]),toggle=react.useCallback(()=>{clear(),setMode(m=>m==="draw"?"type":"draw")},[clear]),onLayout=event=>setWidth(event.nativeEvent.layout.width);/* @__PURE__ */
|
|
285
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.badge,badge.tone==="positive"?styles.badgePositive:badge.tone==="caution"?styles.badgeCaution:styles.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.badgeLabel,badge.tone==="positive"?styles.badgePositiveText:badge.tone==="caution"?styles.badgeCautionText:styles.badgeNeutralText],children:badge.label})})]})}function useLocalStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles(theme),[theme])}function makeLocalStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),card=theme.slots.card,cardText=slotText(card);return reactNative.StyleSheet.create({lead:{...text4(type.size.body,type.lineHeight.normal,color.text.muted),paddingHorizontal:space.lg,paddingBottom:space.md},howCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.md,marginTop:space.sm,...slotBox(card)},howTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...cardText},howRow:{flexDirection:"row",gap:space.md},howNumber:{...face(theme,"monoBold"),fontSize:type.size.caption,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.brandInk,minWidth:space.xl},howText:{flex:1,gap:space.xs/2},howStepTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},howStepBody:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary),...cardText},searchBar:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.md+space.xs/2,height:space.xxl+space.md,marginHorizontal:space.lg,marginBottom:space.sm,borderRadius:radius.lg+space.xs/2,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.borderHairlineGreen,...slotBox(theme.slots.input,hairline)},searchInput:{flex:1,...text4(type.size.body,type.lineHeight.snug,color.text.primary),paddingVertical:0,...slotText(theme.slots.input)},clearGlyph:text4(type.size.heading,type.lineHeight.tight,color.text.muted),uploadWrap:{paddingHorizontal:space.lg,paddingBottom:space.md,gap:space.sm},list:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.md},sectionLabel:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:radius.lg-space.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:color.brandBorder,backgroundColor:color.surfaceCream,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.md,...slotBox(card,1)},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:space.md,minHeight:space.xxl+space.md},fallbackCopy:{flex:1,gap:space.xs/2},fallbackTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},fallbackSubtitle:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},fallbackForm:{gap:space.sm},item:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(card,1)},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},itemName:{flex:1,...text4(type.size.body,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),...cardText},itemDistance:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},itemAddress:{...text4(type.size.caption,type.lineHeight.normal,color.text.primary),...cardText},itemPhone:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},badge:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+1,paddingVertical:space.xs},badgePositive:{backgroundColor:color.badgeBgPositive},badgeCaution:{backgroundColor:color.badgeBgCaution},badgeNeutral:{backgroundColor:color.badgeBgNeutral},badgeLabel:{...text4(type.size.micro,type.lineHeight.snug,color.text.muted,"bold")},badgePositiveText:{color:color.success},badgeCautionText:{color:color.cautionAccent},badgeNeutralText:{color:color.text.muted},footer:{gap:space.sm,paddingTop:space.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,minHeight:space.xxl+space.md},footerRetry:{minHeight:space.xxl+space.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...text4(type.size.bodyTight,type.lineHeight.snug,color.brandInk,"bold")}})}var CLINIC_BATCH_COPY=/* @__PURE__ */Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${RECORDS_CLINIC_BATCH_MAX} clinics`,send:n=>`Send ${n} ${n===1?"request":"requests"}`,sending:"Sending…",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:name=>`Remove ${name}`,emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn’t send any of these requests. See the details below and try again.",partial:(created,total,failed)=>`${created} of ${total} requests sent. ${failed} couldn’t be sent.`,allSent:created=>`${created} ${created===1?"request":"requests"} sent.`,responded:(responded,total)=>`${responded} of ${total} ${total===1?"clinic":"clinics"} responded`});var CLINIC_FORM_SEARCH_LIMIT=25,CLINIC_FORM_RESULTS_STEP=5;function useVisibleClinics(clinics){let[state,setState]=react.useState({list:clinics,shown:CLINIC_FORM_RESULTS_STEP}),shown=state.list===clinics?state.shown:CLINIC_FORM_RESULTS_STEP,showMore=react.useCallback(()=>{setState(previous=>({list:clinics,shown:(previous.list===clinics?previous.shown:CLINIC_FORM_RESULTS_STEP)+CLINIC_FORM_RESULTS_STEP}))},[clinics]);return{visible:clinics.slice(0,shown),hasMore:clinics.length>shown,showMore:showMore}}var SignatureUploadLegError=class extends Error{constructor(){super("Signature upload failed"),this.name="SignatureUploadLegError"}};function isSignatureUploadLegFailure(error){return error instanceof SignatureUploadLegError}function renderClinicScope(copy,owner,pet,clinic){let fields={owner_name:owner,pet_name:pet,clinic_name:clinic},unknown=false,text4=copy.scopeTemplate.replace(/\{([^{}]+)\}/g,(_,key)=>Object.prototype.hasOwnProperty.call(fields,key)?fields[key]??"":(unknown=true,""));return unknown||/[{}]/.test(text4)?null:text4}function clinicNeedsEmail(clinic){return clinic===null||clinic.emailStatus!=="verified"&&clinic.emailStatus!=="unverified"}function useClinicRequestForm(props,controller,capture){let[ownerName,setOwner]=react.useState(props.ownerName),[query,setQueryValue]=react.useState(""),[clinic,setClinic]=react.useState(null),[email2,setEmail]=react.useState(""),[clinics,setClinics]=react.useState([]),[recent,setRecent]=react.useState([]),[copy,setCopy]=react.useState(null),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[searching,setSearching]=react.useState(false),[created,setCreated]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),active=react.useRef(false),locked=react.useRef(false),generation=react.useRef(0),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),attempt=react.useRef(null),captureAbort=react.useRef(null),lifetime=react.useRef(0);react.useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,attempt.current=null,captureAbort.current?.abort()}),[controller]),react.useEffect(()=>{let live=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),react.useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let invalidate=()=>{attempt.current=null,setError(null)},clinicName=clinic?.name??query.trim(),scope=copy?renderClinicScope(copy,ownerName.trim(),props.petName,clinicName):null,needsEmail=clinicNeedsEmail(clinic),results=useVisibleClinics(clinics),ready=!!(copy&&scope&&ownerName.trim()&&props.petName.trim()&&clinicName&&(!needsEmail||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email2.trim()))&&capture),search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},submit=async()=>{if(locked.current||created||!ready||!copy||!scope||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(!attempt.current){captureAbort.current=new AbortController;let signature=await capture({petRef:props.petRef,petName:props.petName,ownerName:ownerName.trim(),clinicName:clinicName,authorizationVersion:copy.authorizationVersion,scopeText:scope,signal:captureAbort.current.signal});if(!current()||signature===null)return;let target=clinic&&(!needsEmail||clinic.emailStatus==="none")?{clinicId:clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:email2.trim().toLowerCase()}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}if(!current())return;let result=await controller.createClinicRequest(attempt.current);if(!current())return;if(!result.ok){setError(result.error);return}if(result.value.petRef!==props.petRef){setError(makeEverfurError("internalError"));return}setCreated(result.value),attempt.current=null,props.onCreated?.(result.value)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}};return{ownerName:ownerName,query:query,clinic:clinic,email:email2,clinics:clinics,copy:copy,scope:scope,error:error,busy:busy,searching:searching,created:created,ready:ready,needsEmail:needsEmail,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0&&clinic===null?recent:[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(null),setEmail(""),setQueryValue(value))},setEmail(value){locked.current||(invalidate(),setEmail(value))},selectClinic(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(value),setQueryValue(value.name),setEmail(""))},invalidate:invalidate,search:search,submit:submit,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var EMAIL2=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function draftName(draft){return draft.clinic?.name??draft.freeText??""}function draftNeedsEmail(draft){return clinicNeedsEmail(draft.clinic)}function useClinicBatchForm(props,controller,batchClient,capture,registerSignature){let[ownerName,setOwner]=react.useState(props.ownerName),[query,setQueryValue]=react.useState(""),[clinics,setClinics]=react.useState([]),[recent,setRecent]=react.useState([]),[drafts,setDrafts]=react.useState([]),[copy,setCopy]=react.useState(null),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[searching,setSearching]=react.useState(false),[outcome,setOutcome]=react.useState(null),[group,setGroup]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),active=react.useRef(false),locked=react.useRef(false),generation=react.useRef(0),lifetime=react.useRef(0),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),signature=react.useRef(null),captureAbort=react.useRef(null);react.useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,signature.current=null,captureAbort.current?.abort()}),[controller,batchClient]),react.useEffect(()=>{let live=true;return setCopy(null),signature.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),react.useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let results=useVisibleClinics(clinics),invalidate=()=>{signature.current=null,setError(null)},names=drafts.map(draftName),pet=petNameOr(props.petName),scopes=copy?names.map(name=>renderClinicScope(copy,ownerName.trim(),pet,name)):[],scopeText=scopes.every(s=>s!==null)?scopes.join(`\n\n`):null,draftsReady=drafts.length>0&&drafts.every(draft=>!draftNeedsEmail(draft)||EMAIL2.test(draft.email.trim())),atCap=drafts.length>=RECORDS_CLINIC_BATCH_MAX,ready=!!(copy&&scopeText&&ownerName.trim()&&draftsReady&&capture)&&outcome===null,search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},add=draft=>{locked.current||atCap||outcome!==null||draft.clinic!==null&&drafts.some(d=>d.clinic?.id===draft.clinic?.id)||(invalidate(),setDrafts(current=>[...current,{...draft,key:keyFactory.current(),idempotencyKey:keyFactory.current()}]),setClinics([]),setQueryValue(""))},submit=async()=>{if(locked.current||outcome!==null||!ready||!copy||!scopeText||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(signature.current===null){captureAbort.current=new AbortController;let captured=await capture({petRef:props.petRef,petName:pet,ownerName:ownerName.trim(),clinicName:names.join(", "),authorizationVersion:copy.authorizationVersion,scopeText:scopeText,signal:captureAbort.current.signal});if(!current()||captured===null)return;if(signature.current=captured,captured.signaturePngBase64!==void 0&®isterSignature!==void 0){let abort=captureAbort.current;try{let registered=await registerSignature(captured.signaturePngBase64,abort.signal);if(!current())return;signature.current={signatureId:registered.signatureId}}catch(registrationError){if(!isSignatureUploadLegFailure(registrationError)||abort.signal.aborted)throw registrationError;if(!current())return}}}let signed=signature.current,items=drafts.map(draft=>({...draft.clinic!==null&&(!draftNeedsEmail(draft)||draft.clinic.emailStatus==="none")?{clinicId:draft.clinic.id}:{clinicFreeText:draftName(draft)},...draftNeedsEmail(draft)?{clinicEmail:draft.email.trim().toLowerCase()}:{},...signed.signatureId!==void 0?{signatureId:signed.signatureId}:{signaturePngBase64:signed.signaturePngBase64},idempotencyKey:draft.idempotencyKey})),result=await batchClient.createClinicRequestBatch({petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,clinics:items});if(!current())return;if(!result.ok){setError(result.error);return}setOutcome(result.value),props.onCreated?.(result.value),loadGroup(result.value.requestGroupId,run)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}},loadGroup=async(requestGroupId,run)=>{try{let result=await controller.getRequestGroup(requestGroupId);if(!active.current||lifetime.current!==run)return;result.ok&&result.value.petRef===props.petRef&&setGroup(result.value)}catch{}},refreshGroup=async()=>{outcome===null||locked.current||await loadGroup(outcome.requestGroupId,lifetime.current)};return{ownerName:ownerName,query:query,clinics:clinics,copy:copy,scopeText:scopeText,error:error,busy:busy,searching:searching,drafts:drafts,outcome:outcome,group:group,ready:ready,atCap:atCap,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0?recent.filter(clinic=>!drafts.some(d=>d.clinic?.id===clinic.id)):[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(generation.current+=1,setSearching(false),setClinics([]),setQueryValue(value))},search:search,addClinic(clinic){add({clinic:clinic,freeText:null,email:""})},addFreeText(){let name=query.trim();name.length!==0&&add({clinic:null,freeText:name,email:""})},setDraftEmail(key,email2){locked.current||(invalidate(),setDrafts(current=>current.map(draft=>draft.key===key?{...draft,email:email2}:draft)))},removeDraft(key){locked.current||outcome!==null||(invalidate(),setDrafts(current=>current.filter(draft=>draft.key!==key)))},submit:submit,refreshGroup:refreshGroup,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number",probeRef=react.useRef(null),[reading,setReading]=react.useState(null),frame=react.useRef(null),retry=react.useRef(null),mounted=react.useRef(true),stopRetry=react.useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);react.useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=react.useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,reactNative.Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=react.useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return react.useMemo(()=>{if(!lifts)return{avoidingProps:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function trustedSignatureUploadUrl(value){try{let url=new URL(value);if(url.protocol!=="https:"||url.username||url.password||url.port&&url.port!=="443")return!1;let host=url.hostname.toLowerCase();return host==="s3.amazonaws.com"||host.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(host)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(host)||host==="s3-accelerate.amazonaws.com"||host.endsWith(".s3-accelerate.amazonaws.com")||host==="s3-accelerate.dualstack.amazonaws.com"||host.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}var FAILED="Signature upload failed",UPLOAD_TIMEOUT_MS=3e4;function base64ByteLength(base64){let padding=base64.endsWith("==")?2:base64.endsWith("=")?1:0;return Math.floor(base64.length*3/4)-padding}async function registerRnSignature(signaturePngBase64,controller,signal,fetchImpl){let fail=()=>new Error(FAILED),size=base64ByteLength(signaturePngBase64);if(size<=0||signal.aborted)throw fail();let initiated=await controller.initiateSignatureUpload(size);if(!initiated.ok||signal.aborted||!trustedSignatureUploadUrl(initiated.value.uploadUrl))throw fail();let form=new FormData;for(let[key,value]of Object.entries(initiated.value.uploadFields))form.append(key,value);form.append("file",{uri:`data:image/png;base64,${signaturePngBase64}`,name:"signature.png",type:"image/png"});let uploadAbort=new AbortController,onAbort=()=>uploadAbort.abort();signal.addEventListener("abort",onAbort,{once:true});let timer=setTimeout(onAbort,UPLOAD_TIMEOUT_MS);try{if(!(await(fetchImpl??fetch)(initiated.value.uploadUrl,{method:"POST",body:form,credentials:"omit",signal:uploadAbort.signal})).ok||signal.aborted)throw fail()}catch{throw signal.aborted?fail():new SignatureUploadLegError}finally{clearTimeout(timer),signal.removeEventListener("abort",onAbort)}let completed=await controller.completeSignatureUpload(initiated.value.uploadId);if(!completed.ok||signal.aborted)throw fail();return{signatureId:completed.value}}var SIGNATURE_CANVAS=/* @__PURE__ */Object.freeze({width:360,height:120});function blank(width,height){return{width:width,height:height,pixels:new Uint8Array(width*height)}}function stamp(bitmap,cx,cy,radius){for(let dy=-radius;dy<=radius;dy+=1)for(let dx=-radius;dx<=radius;dx+=1){if(dx*dx+dy*dy>radius*radius+radius)continue;let x=cx+dx,y=cy+dy;x<0||y<0||x>=bitmap.width||y>=bitmap.height||(bitmap.pixels[y*bitmap.width+x]=1)}}var MAX_STEPS_PER_STROKE=16384;function padPoint(point,bitmap){let[x,y]=point;if(!Number.isFinite(x)||!Number.isFinite(y))return null;let cx=Math.min(2*bitmap.width,Math.max(-bitmap.width,Math.round(x))),cy=Math.min(2*bitmap.height,Math.max(-bitmap.height,Math.round(y)));return[cx,cy]}function line(bitmap,from,to,radius,budget){let[x0,y0]=from,[x1,y1]=to,dx=Math.abs(x1-x0),dy=-Math.abs(y1-y0),sx=x0<x1?1:-1,sy=y0<y1?1:-1,error=dx+dy,steps=0;for(;steps<budget&&(stamp(bitmap,x0,y0,radius),steps+=1,!(x0===x1&&y0===y1));){let twice=2*error;twice>=dy&&(error+=dy,x0+=sx),twice<=dx&&(error+=dx,y0+=sy)}return steps}function rasterizeStrokes(strokes,penRadius=1){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height);for(let stroke3 of strokes){let points=[];for(let point of stroke3){let clamped=padPoint(point,bitmap);clamped!==null&&points.push(clamped)}if(points.length===0)continue;if(points.length===1){let[x,y]=points[0];stamp(bitmap,x,y,penRadius);continue}let budget=MAX_STEPS_PER_STROKE;for(let i=1;i<points.length&&budget>0;i+=1)budget-=line(bitmap,points[i-1],points[i],penRadius,budget)}return bitmap}var FONT_ORDER="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",FONT_ROWS="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",FONT_DIGITS="0123456789abcdefghijklmnopqrstuv",GLYPH_W=5,GLYPH_H=7,ADVANCE=GLYPH_W+1;function glyphRow(char,row){let index=FONT_ORDER.indexOf(char);return index<0?0:FONT_DIGITS.indexOf(FONT_ROWS.charAt(index*GLYPH_H+row))}function rasterizeTypedName(name){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height),text4=name.trim();if(text4.length===0)return bitmap;let chars=[...text4],scale=4;for(;scale>1&&(chars.length*ADVANCE-1)*scale>bitmap.width-8;)scale-=1;let textWidth=(chars.length*ADVANCE-1)*scale,x0=Math.max(0,Math.floor((bitmap.width-textWidth)/2)),y0=Math.floor((bitmap.height-GLYPH_H*scale)/2);return chars.forEach((char,i)=>{let gx=x0+i*ADVANCE*scale;for(let row=0;row<GLYPH_H;row+=1){let bits=glyphRow(char,row);for(let col=0;col<GLYPH_W;col+=1)if((bits>>GLYPH_W-1-col&1)!==0)for(let sy=0;sy<scale;sy+=1)for(let sx=0;sx<scale;sx+=1){let x=gx+col*scale+sx,y=y0+row*scale+sy;x<bitmap.width&&y<bitmap.height&&(bitmap.pixels[y*bitmap.width+x]=1)}}}),bitmap}var BitWriter=class{constructor(){this.bytes=[];this.acc=0;this.count=0}writeBits(value,count){for(this.acc|=value<<this.count,this.count+=count;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8}writeCode(code,length){let reversed=0;for(let i=0;i<length;i+=1)reversed=reversed<<1|code>>i&1;this.writeBits(reversed,length)}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};function writeLiteral(out,symbol){symbol<144?out.writeCode(48+symbol,8):symbol<256?out.writeCode(400+(symbol-144),9):symbol<280?out.writeCode(symbol-256,7):out.writeCode(192+(symbol-280),8)}var LENGTH_BASE=[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],LENGTH_EXTRA=[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],DIST_BASE=[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],DIST_EXTRA=[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 writeMatch(out,length,distance){let li=LENGTH_BASE.length-1;for(;LENGTH_BASE[li]>length;)li-=1;writeLiteral(out,257+li),LENGTH_EXTRA[li]>0&&out.writeBits(length-LENGTH_BASE[li],LENGTH_EXTRA[li]);let di=DIST_BASE.length-1;for(;DIST_BASE[di]>distance;)di-=1;out.writeCode(di,5),DIST_EXTRA[di]>0&&out.writeBits(distance-DIST_BASE[di],DIST_EXTRA[di])}var WINDOW=32768,MIN_MATCH=3,MAX_MATCH=258,HASH_BITS=15,CHAIN_LIMIT=64;function deflate(input){let out=new BitWriter;out.writeBits(1,1),out.writeBits(1,2);let head=new Int32Array(1<<HASH_BITS).fill(-1),prev=new Int32Array(input.length).fill(-1),hashAt=i2=>(input[i2]<<10^input[i2+1]<<5^input[i2+2])&(1<<HASH_BITS)-1,insert=i2=>{if(i2+MIN_MATCH>input.length)return;let h=hashAt(i2);prev[i2]=head[h],head[h]=i2},i=0;for(;i<input.length;){let bestLength=0,bestDistance=0;if(i+MIN_MATCH<=input.length){let candidate=head[hashAt(i)],chain=0,limit=Math.min(MAX_MATCH,input.length-i);for(;candidate>=0&&chain<CHAIN_LIMIT&&i-candidate<=WINDOW;){let length=0;for(;length<limit&&input[candidate+length]===input[i+length];)length+=1;if(length>bestLength&&(bestLength=length,bestDistance=i-candidate,length===limit))break;candidate=prev[candidate],chain+=1}}if(bestLength>=MIN_MATCH){writeMatch(out,bestLength,bestDistance);for(let k=0;k<bestLength;k+=1)insert(i+k);i+=bestLength}else writeLiteral(out,input[i]),insert(i),i+=1}return writeLiteral(out,256),out.finish()}function adler32(bytes){let a=1,b=0;for(let byte2 of bytes)a=(a+byte2)%65521,b=(b+a)%65521;return(b<<16|a)>>>0}var crcTable=null;function crc32(bytes){if(crcTable===null){crcTable=new Uint32Array(256);for(let n=0;n<256;n+=1){let c=n;for(let k=0;k<8;k+=1)c=c&1?3988292384^c>>>1:c>>>1;crcTable[n]=c>>>0}}let crc=4294967295;for(let byte2 of bytes)crc=crcTable[(crc^byte2)&255]^crc>>>8;return(crc^4294967295)>>>0}function u32(value){return[value>>>24&255,value>>>16&255,value>>>8&255,value&255]}function chunk(type,data){let typed=Uint8Array.from([...type].map(c=>c.charCodeAt(0))),body=new Uint8Array(typed.length+data.length);return body.set(typed,0),body.set(data,typed.length),[...u32(data.length),...body,...u32(crc32(body))]}var BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function toBase64(bytes){let out="";for(let i=0;i<bytes.length;i+=3){let a=bytes[i],b=i+1<bytes.length?bytes[i+1]:0,c=i+2<bytes.length?bytes[i+2]:0,triple=a<<16|b<<8|c;out+=BASE64.charAt(triple>>18&63)+BASE64.charAt(triple>>12&63),out+=i+1<bytes.length?BASE64.charAt(triple>>6&63):"=",out+=i+2<bytes.length?BASE64.charAt(triple&63):"="}return out}function encodeSignaturePng(bitmap){let{width:width,height:height,pixels:pixels}=bitmap,stride=Math.ceil(width/8)+1,raw=new Uint8Array(stride*height);for(let y=0;y<height;y+=1){let rowStart=y*stride;raw[rowStart]=0,raw.fill(255,rowStart+1,rowStart+stride);for(let x=0;x<width;x+=1)if(pixels[y*width+x]===1){let index=rowStart+1+(x>>3);raw[index]=raw[index]&~(128>>(x&7))}}let compressed=deflate(raw),idat=new Uint8Array(2+compressed.length+4);idat[0]=120,idat[1]=1,idat.set(compressed,2),idat.set(u32(adler32(raw)),2+compressed.length);let ihdr=Uint8Array.from([...u32(width),...u32(height),1,0,0,0,0]),png=Uint8Array.from([137,80,78,71,13,10,26,10,...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))]);return toBase64(png)}var SIGNATURE_STROKE_WIDTH=2.6,INK="#111111";function strokeSegments(strokes,scale){let segments=[];return strokes.forEach((stroke3,s)=>{let at=i=>{let p=stroke3[i];return[p[0]/scale,p[1]/scale]};if(stroke3.length===1){let[x,y]=at(0);segments.push({key:`${s}-0`,cx:x,cy:y,length:0,angle:0});return}for(let i=1;i<stroke3.length;i+=1){let[x0,y0]=at(i-1),[x1,y1]=at(i);segments.push({key:`${s}-${i}`,cx:(x0+x1)/2,cy:(y0+y1)/2,length:Math.hypot(x1-x0,y1-y0),angle:Math.atan2(y1-y0,x1-x0)})}}),segments}var MIN_DRAWN_POINTS=8,MIN_MOVE=2;function SignaturePad({onChange:onChange,disabled:disabled=false}){let styles=useStyles4(),[mode,setMode]=react.useState("draw"),[typed,setTyped]=react.useState(""),[strokes,setStrokes]=react.useState([]),[width,setWidth]=react.useState(0),current=react.useRef([]),drawing=react.useRef(null),scale=width>0?SIGNATURE_CANVAS.width/width:1,scaleRef=react.useRef(scale);scaleRef.current=scale;let disabledRef=react.useRef(disabled);disabledRef.current=disabled,react.useEffect(()=>{if(mode==="type"){callHost(onChange,typed.trim().length>0?encodeSignaturePng(rasterizeTypedName(typed)):null);return}let points=strokes.reduce((n,stroke3)=>n+stroke3.length,0);callHost(onChange,points>=MIN_DRAWN_POINTS?encodeSignaturePng(rasterizeStrokes(strokes)):null)},[mode,typed,strokes,onChange]);let point=event=>{let{locationX:locationX,locationY:locationY}=event.nativeEvent;return[locationX*scaleRef.current,locationY*scaleRef.current]},commitStroke=()=>{let finished=current.current,inProgress=drawing.current;current.current=[],drawing.current=null,setStrokes(committed=>[...committed.filter(s=>s!==inProgress),finished])},responder=react.useMemo(()=>reactNative.PanResponder.create({onStartShouldSetPanResponder:()=>!disabledRef.current,onMoveShouldSetPanResponder:()=>!disabledRef.current,onPanResponderTerminationRequest:()=>false,onPanResponderGrant:event=>{current.current=[point(event)]},onPanResponderMove:event=>{let next=point(event),last=current.current[current.current.length-1];if(last!==void 0&&Math.abs(last[0]-next[0])<MIN_MOVE&&Math.abs(last[1]-next[1])<MIN_MOVE)return;current.current=[...current.current,next];let previous=drawing.current,trail=current.current;drawing.current=trail,setStrokes(committed=>[...committed.filter(s=>s!==previous),trail])},onPanResponderRelease:()=>commitStroke(),onPanResponderTerminate:()=>commitStroke()}),[]),clear=react.useCallback(()=>{disabledRef.current||(current.current=[],drawing.current=null,setStrokes([]),setTyped(""))},[]),toggle=react.useCallback(()=>{clear(),setMode(m=>m==="draw"?"type":"draw")},[clear]),onLayout=event=>setWidth(event.nativeEvent.layout.width);/* @__PURE__ */
|
|
280
286
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.container,testID:"records-signature-pad",children:[
|
|
281
287
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.label,children:mode==="draw"?CLINIC_REQUEST_COPY.draw:CLINIC_REQUEST_COPY.type}),mode==="type"?/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.type,style:styles.input,value:typed,maxLength:100,editable:!disabled,autoComplete:"off",autoCorrect:false,onChangeText:value=>{disabledRef.current||setTyped(value)}}):null,
|
|
282
288
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{onLayout:onLayout,style:[styles.canvas,{height:width>0?width/3:120}],accessible:true,accessibilityLabel:CLINIC_REQUEST_COPY.sign,accessibilityRole:"image",testID:"records-signature-canvas",...mode==="draw"?responder.panHandlers:{},children:mode==="type"?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:typed.trim()}):strokeSegments(strokes,scale).map(segment=>{let box3=segment.length+SIGNATURE_STROKE_WIDTH;/* @__PURE__ */
|
|
@@ -310,8 +316,8 @@ return jsxRuntime.jsxs(reactNative.View,{style:local.option,accessible:true,acce
|
|
|
310
316
|
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.clinic,style:styles.field,value:form.query,placeholder:CLINIC_REQUEST_COPY.placeholder,placeholderTextColor:theme.color.text.placeholder,maxLength:200,editable:!form.busy,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",onSubmitEditing:search,onChangeText:form.setQuery,testID:"records-batch-search-input"}),
|
|
311
317
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_REQUEST_COPY.search,kind:"outline",disabled:!canSearch,onPress:search,testID:"records-batch-search"}),form.query.trim().length>0&&form.clinics.length===0&&!form.searching?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_BATCH_COPY.addClinic,kind:"link",disabled:form.busy,onPress:form.addFreeText,testID:"records-batch-add-typed"}):null,form.searching?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.muted,children:RECORDS_COPY.loading}):null,form.recent.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:styles.fieldLabel,children:CLINIC_REQUEST_COPY.recentlyUsed}):null,form.recent.map(clinic=>option(`recent-${clinic.id}`,clinic)),form.visibleClinics.map(clinic=>option(clinic.id,clinic)),form.hasMoreClinics?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_REQUEST_COPY.moreClinics,kind:"link",disabled:form.busy,onPress:form.showMoreClinics}):null]})]}),
|
|
312
318
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.scopeCard,accessibilityRole:"summary",testID:"records-batch-scope",children:[
|
|
313
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:local.sectionTitle,children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeText,testID:"records-batch-scope-text",children:form.
|
|
314
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]}),form.outcome?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.footer,{paddingBottom:Math.max(insets.bottom,theme.space.md)}],testID:"records-batch-footer",children:/* @__PURE__ */jsxRuntime.jsx(Pill,{label:sendLabel,disabled:form.busy||!form.ready||!signed,busy:form.busy,onPress:()=>{reactNative.Keyboard.dismiss(),form.submit()},testID:"records-batch-send"})})]})]})}function useLocalStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles2(theme),[theme])}function makeLocalStyles2(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,
|
|
319
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:local.sectionTitle,children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?form.drafts.length>0&&form.ownerName.trim()?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeText,testID:"records-batch-scope-text",children:form.scopeText??makeEverfurError("internalError").displayMessage}):null:!form.error&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.muted,children:RECORDS_COPY.loading})]}),!props.onCaptureSignature&&/* @__PURE__ */jsxRuntime.jsx(SignaturePad,{onChange:setPng,disabled:form.busy}),!signed&&form.ready&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",style:styles.bodyText,children:CLINIC_REQUEST_COPY.missingSignature}),form.error&&/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:form.error.displayMessage})}),!form.copy&&form.error&&/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_COPY.retry,kind:"outline",onPress:form.retryCopy})]}),
|
|
320
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]}),form.outcome?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.footer,{paddingBottom:Math.max(insets.bottom,theme.space.md)}],testID:"records-batch-footer",children:/* @__PURE__ */jsxRuntime.jsx(Pill,{label:sendLabel,disabled:form.busy||!form.ready||!signed,busy:form.busy,onPress:()=>{reactNative.Keyboard.dismiss(),form.submit()},testID:"records-batch-send"})})]})]})}function useLocalStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles2(theme),[theme])}function makeLocalStyles2(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({header:{flexDirection:"row",alignItems:"center",gap:space.md,paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md,...slotBox(theme.slots.header)},title:{flex:1,...text4(type.size.heading,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),...slotText(theme.slots.header)},close:{minHeight:touch,minWidth:touch,alignItems:"center",justifyContent:"center"},closeLabel:text4(type.size.body,type.lineHeight.snug,color.linkInk,"bold"),content:{paddingHorizontal:space.lg,paddingBottom:space.xl,gap:space.lg},lead:text4(type.size.body,type.lineHeight.normal,color.text.muted),block:{gap:space.sm},sectionTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},option:{minHeight:touch,justifyContent:"center",gap:space.xs/2,borderRadius:radius.md,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2,...slotBox(theme.slots.card,1)},optionName:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...slotText(theme.slots.card)},draft:{gap:space.sm,borderRadius:radius.md,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,padding:space.md,...slotBox(theme.slots.card,1)},remove:{alignSelf:"flex-start",minHeight:touch,paddingHorizontal:0},scopeCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.sm,...slotBox(theme.slots.card,1)},scopeText:{...text4(type.size.bodyTight,type.lineHeight.relaxed,color.text.secondary),...slotText(theme.slots.card)},footer:{paddingHorizontal:space.lg,paddingTop:space.md,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,backgroundColor:color.background}})}var RECORDS_CONSENT_COPY=/* @__PURE__ */Object.freeze({scopeHeading:"What we ask for",scopeBody:"You’re asking your pet’s clinic to release their medical records to Everfur, on your behalf, so we can organize them for you.",whatWeDo:/* @__PURE__ */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:petName=>`I’m ${petNameOr(petName)}’s owner. I authorize Everfur to request these records on my behalf.`,missingSignatureError:"Please add your signature before submitting.",missingDraftError:"Something went wrong with your selection. Please go back and pick the clinic again.",newClinicDirectSendNote:"We’ll email this clinic directly to request your pet’s medical records. Clinics usually reply within a week.",titleFreeText:"Check and send",titleDirectory:"Check and send",leadWeb:petName=>`The clinic gets a secure request, with your permission to release ${petNameOr(petName)}’s records to Everfur.`,leadNative:"The clinic gets a secure request, with your permission.",whatHappensNext:"What happens next",whatHappensNextBody:"Most clinics respond within 3 to 5 business days. We follow up automatically, and you can cancel any time before the records arrive.",noEmailNote:(petName,clinicName)=>`We don’t have an email on file for ${clinicName}. Add it so we can request ${petNameOr(petName)}’s records.`,emailLabel:"Clinic email for records",emailPlaceholder:"records@clinic.com",emailRequired:"Add the clinic’s records email to send the request.",emailInvalid:"That email doesn’t look right. Check it and try again.",reuseSignature:"Reuse a previous signature",reuseHint:"…or 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’t draw? Type your name instead",toDraw:"Draw your signature instead",signatureHint:clinicName=>`Your signature is added to the authorization sent to ${clinicName}.`,submit:"Send request",submitting:"Sending…"});var FACT_VALUE_FIELD="value_text",FACT_ENTITY_TYPE_MAX=64,FACT_CANONICAL_KEY_MAX=512;function isFactReviewerLocked(error){return error!==null&&error.httpStatus===409&&!isRecordsConsentRequired(error)}var FACT_FIELD_BY_KIND=/* @__PURE__ */Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:FACT_VALUE_FIELD}),NUMERIC=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,ISO_DATE=/^\d{4}-\d{2}-\d{2}$/;function inferFactValueKind(value){if(value==null)return"text";let trimmed=value.trim();return NUMERIC.test(trimmed)?"num":ISO_DATE.test(trimmed)&&!Number.isNaN(Date.parse(trimmed))?"date":trimmed==="true"||trimmed==="false"?"bool":"text"}function factCorrectionFor(original,corrected){let next=corrected.trim(),kind=inferFactValueKind(original);if(kind==="num"&&NUMERIC.test(next)){let parsed=Number(next);if(Number.isFinite(parsed))/* @__PURE__ */return Object.freeze({[FACT_FIELD_BY_KIND.num]:parsed})}return kind==="date"&&ISO_DATE.test(next)&&!Number.isNaN(Date.parse(next))?/* @__PURE__ */Object.freeze({[FACT_FIELD_BY_KIND.date]:next}):/* @__PURE__ */Object.freeze(kind==="bool"&&(next==="true"||next==="false")?{[FACT_FIELD_BY_KIND.bool]:next==="true"}:{[FACT_FIELD_BY_KIND.text]:next})}var str2=/* @__PURE__ */zod.z.string().nullish(),num=/* @__PURE__ */zod.z.number().nullish(),pointSchema=/* @__PURE__ */zod.z.object({collected_at:str2,at:str2,value:num,unit:str2,qualitative_result:str2,ref_low:num,ref_high:num,status:str2,source_clinic:str2,source_doc_id:str2,doc_id:str2,reviewed:/* @__PURE__ */zod.z.boolean().nullish()}),latestSchema=/* @__PURE__ */zod.z.object({collected_at:str2,at:str2,value:num,unit:str2,qualitative_result:str2,status:str2}),markerSchema=/* @__PURE__ */zod.z.object({marker_id:/* @__PURE__ */zod.z.string().min(1),canonical_name:str2,name:str2,loinc_code:str2,canonical_unit:str2,unit:str2,panel_name:str2,panel:str2,meaning_text:str2,meaning:str2,latest:/* @__PURE__ */latestSchema.nullish(),trajectory:str2,points:/* @__PURE__ */zod.z.array(pointSchema).optional()}),summarySchema=/* @__PURE__ */zod.z.object({total_markers:/* @__PURE__ */zod.z.number().int().nonnegative(),in_range_count:/* @__PURE__ */zod.z.number().int().nonnegative(),out_of_range_count:/* @__PURE__ */zod.z.number().int().nonnegative(),unknown_count:/* @__PURE__ */zod.z.number().int().nonnegative()}),markersSchema=/* @__PURE__ */zod.z.object({markers:/* @__PURE__ */zod.z.array(markerSchema).optional(),summary:/* @__PURE__ */summarySchema.nullish(),disclaimer:/* @__PURE__ */zod.z.string().optional(),featured_marker_id:str2});function isObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function withheldMarkers(pet){/* @__PURE__ */
|
|
315
321
|
return Object.freeze({petRef:pet,withheld:true,markers:/* @__PURE__ */Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}function mapRecordMarkers(petRef,wire){let w=isObject2(wire)?wire:{},pet=typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef;if(w.withheld===true)return withheldMarkers(pet);let parsed=markersSchema.safeParse(w);if(!parsed.success)return withheldMarkers(pet);let m=parsed.data,point=p=>/* @__PURE__ */Object.freeze({at:p.collected_at??p.at??null,value:p.value??null,unit:p.unit??null,qualitativeResult:p.qualitative_result??null,refLow:p.ref_low??null,refHigh:p.ref_high??null,status:p.status??null,sourceClinic:p.source_clinic??null,docId:p.source_doc_id??p.doc_id??null,reviewed:p.reviewed===true}),markers=(m.markers??[]).map(marker=>/* @__PURE__ */Object.freeze({markerId:marker.marker_id,name:marker.canonical_name??marker.name??marker.marker_id,loincCode:marker.loinc_code??null,unit:marker.canonical_unit??marker.unit??null,panel:marker.panel_name??marker.panel??null,meaning:marker.meaning_text??marker.meaning??null,latest:marker.latest?/* @__PURE__ */Object.freeze({at:marker.latest.collected_at??marker.latest.at??null,value:marker.latest.value??null,unit:marker.latest.unit??null,qualitativeResult:marker.latest.qualitative_result??null,status:marker.latest.status??null}):null,trajectory:marker.trajectory??null,points:/* @__PURE__ */Object.freeze((marker.points??[]).map(point))}));/* @__PURE__ */
|
|
316
322
|
return Object.freeze({petRef:pet,withheld:false,markers:/* @__PURE__ */Object.freeze(markers),summary:m.summary?/* @__PURE__ */Object.freeze({totalMarkers:m.summary.total_markers,inRangeCount:m.summary.in_range_count,outOfRangeCount:m.summary.out_of_range_count,unknownCount:m.summary.unknown_count}):null,disclaimer:m.disclaimer??"",featuredMarkerId:m.featured_marker_id??null})}var https2=/* @__PURE__ */zod.z.string().min(1).refine(value=>value.startsWith("https://")),itemSchema=/* @__PURE__ */zod.z.object({source_doc_id:/* @__PURE__ */zod.z.string().min(1),file_name:/* @__PURE__ */zod.z.string().nullish(),doc_format:/* @__PURE__ */zod.z.string().nullish(),byte_size:/* @__PURE__ */zod.z.number().int().nonnegative().nullish(),received_at:/* @__PURE__ */zod.z.string().nullish(),download_url:https2,expires_in_seconds:/* @__PURE__ */zod.z.number().int().nonnegative().nullish()}),listSchema2=/* @__PURE__ */zod.z.object({items:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.unknown()).optional()});function mapRequestDocuments(wire){let parsed=listSchema2.safeParse(wire);if(!parsed.success)return null;let rows=[];for(let raw of parsed.data.items??[]){let item=itemSchema.safeParse(raw);item.success&&rows.push(
|
|
317
323
|
/* @__PURE__ */Object.freeze({sourceDocId:item.data.source_doc_id,fileName:item.data.file_name??null,docFormat:item.data.doc_format??null,byteSize:item.data.byte_size??null,receivedAt:item.data.received_at??null,downloadUrl:item.data.download_url,expiresInSeconds:item.data.expires_in_seconds??0}))}/* @__PURE__ */
|
|
@@ -320,7 +326,7 @@ return Object.freeze({petRef:pet,available:false,withheld:withheld,labResults:/*
|
|
|
320
326
|
return Object.freeze({petRef:pet,available:true,withheld:false,labResults:/* @__PURE__ */Object.freeze((d.lab_results??[]).map(m=>/* @__PURE__ */Object.freeze({markerId:m.marker_id,name:m.name,loincCode:m.loinc_code??null,unit:m.unit??null,panel:m.panel??null,meaning:m.meaning??null,latest:/* @__PURE__ */Object.freeze({at:m.latest?.at??null,value:m.latest?.value??null,unit:m.latest?.unit??null,qualitativeResult:m.latest?.qualitative_result??null,status:m.latest?.status??null}),trajectory:m.trajectory??null,points:/* @__PURE__ */Object.freeze((m.points??[]).map(point))}))),encounters:/* @__PURE__ */Object.freeze((d.encounters??[]).map(e=>/* @__PURE__ */Object.freeze({encounterId:e.encounter_id,date:e.date??null,type:e.type??null,clinicName:e.clinic_name??null,veterinarian:e.veterinarian??null,docId:e.doc_id??null}))),clinicianNotes:/* @__PURE__ */Object.freeze((d.clinician_notes??[]).map(n=>/* @__PURE__ */Object.freeze({noteId:n.note_id,encounterId:n.encounter_id??null,observedOn:n.observed_on??null,sections:/* @__PURE__ */Object.freeze((n.sections??[]).map(s=>/* @__PURE__ */Object.freeze({section:s.section,text:s.text})))}))),physicalExams:/* @__PURE__ */Object.freeze((d.physical_exams??[]).map(x=>/* @__PURE__ */Object.freeze({examId:x.exam_id,encounterId:x.encounter_id??null,observedOn:x.observed_on??null,docId:x.doc_id??null,systems:/* @__PURE__ */Object.freeze(Object.entries(x.systems??{}).map(([system,field])=>/* @__PURE__ */Object.freeze({system:system,findingStatus:field.finding_status??null,finding:field.finding??null})))}))),completeness:d.completeness?/* @__PURE__ */Object.freeze({hasLabHistory:d.completeness.has_lab_history===true,hasVaccinationHistory:d.completeness.has_vaccination_history===true,hasWeightHistory:d.completeness.has_weight_history===true,hasVitalsHistory:d.completeness.has_vitals_history===true,hasPhysicalExamHistory:d.completeness.has_physical_exam_history===true,hasProcedureHistory:d.completeness.has_procedure_history===true,hasGeneticHistory:d.completeness.has_genetic_history===true,hasReproductiveHistory:d.completeness.has_reproductive_history===true,hasParasitePreventionHistory:d.completeness.has_parasite_prevention_history===true,earliestRecordAt:d.completeness.earliest_record_at??null,latestRecordAt:d.completeness.latest_record_at??null,documentsIngested:d.completeness.documents_ingested??0,documentsInReview:d.completeness.documents_in_review??0,entitiesPendingReview:/* @__PURE__ */Object.freeze({...d.completeness.entities_pending_review??{}}),heldTotal:d.completeness.held_total??0}):null,conflicts:/* @__PURE__ */Object.freeze((d.conflicts??[]).map(c=>/* @__PURE__ */Object.freeze({conflictId:c.conflict_id,entityType:c.entity_type,field:c.field??null,severity:c.severity??"needs_review",candidates:/* @__PURE__ */Object.freeze((c.candidates??[]).map(k=>/* @__PURE__ */Object.freeze({value:k.value,docId:k.source_doc_id??k.doc_id??null,collectedAt:k.collected_at??null})))})))})}function withheldTimeline(pet){/* @__PURE__ */
|
|
321
327
|
return Object.freeze({petRef:pet,withheld:true,isEmpty:false,visits:/* @__PURE__ */Object.freeze([]),vaccines:/* @__PURE__ */Object.freeze([]),weights:/* @__PURE__ */Object.freeze([]),medications:/* @__PURE__ */Object.freeze([]),disclaimer:""})}function mapRecordsTimeline(petRef,wire){let w=isObject3(wire)?wire:{},pet=petOf(w,petRef);if(w.withheld===true)return withheldTimeline(pet);let parsed=timelineSchema.safeParse(w);if(!parsed.success)return withheldTimeline(pet);let t=parsed.data,visits=t.visits.map(v=>/* @__PURE__ */Object.freeze({visitId:v.visit_id,visitDate:v.visit_date??null,veterinarian:v.veterinarian??null,summary:v.summary??null,docId:v.doc_id??null})),vaccines=t.vaccines.map(v=>/* @__PURE__ */Object.freeze({vaccineId:v.vaccine_id,product:v.product??null,lot:v.lot??null,administeredOn:v.administered_on??null,expiresOn:v.expires_on??null,docId:v.doc_id??null})),weights=t.weights.map(v=>/* @__PURE__ */Object.freeze({weightId:v.weight_id,observedOn:v.observed_on??null,weightKg:v.weight_kg??null,docId:v.doc_id??null})),medications=t.medications.map(m=>/* @__PURE__ */Object.freeze({medicationId:m.medication_id,drugName:m.drug_name??null,dose:m.dose??null,route:m.route??null,frequency:m.frequency??null,sig:m.sig??null,rxNumber:m.rx_number??null,startedOn:m.started_on??null,stoppedOn:m.stopped_on??null,docId:m.doc_id??null}));/* @__PURE__ */
|
|
322
328
|
return Object.freeze({petRef:pet,withheld:false,isEmpty:visits.length===0&&vaccines.length===0&&weights.length===0&&medications.length===0,visits:/* @__PURE__ */Object.freeze(visits),vaccines:/* @__PURE__ */Object.freeze(vaccines),weights:/* @__PURE__ */Object.freeze(weights),medications:/* @__PURE__ */Object.freeze(medications),disclaimer:t.disclaimer??""})}function mapDocumentContributions(petRef,wire){let w=isObject3(wire)?wire:{},pet=petOf(w,petRef),withheld=()=>/* @__PURE__ */Object.freeze({petRef:pet,withheld:true,document:null,contributions:/* @__PURE__ */Object.freeze([]),contributionCount:0});if(w.withheld===true)return withheld();let parsed=contributionsSchema.safeParse(w);if(!parsed.success)return withheld();let contributions=/* @__PURE__ */Object.freeze(parsed.data.contributions.map(mapEntityRow));/* @__PURE__ */
|
|
323
|
-
return Object.freeze({petRef:pet,withheld:false,document:mapDocumentRow(parsed.data.document),contributions:contributions,contributionCount:parsed.data.contribution_count??contributions.length})}var BASE3="/widget/v1/records/pets";function createRecordsDepthClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),segment=(value,max)=>typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)&&[...value].length<=max,read=async(call,petRef,path,map)=>{if(!segment(petRef,PET_REF_MAX))return invalid2();let result=await funnel.send(call,{method:"GET",path:path});if(!result.ok)return result;let view=map(result.value);return view.petRef===petRef?ok(view):err(makeEverfurError("internalError",{retryable:false}))},pet=petRef=>`${BASE3}/${encodeURIComponent(petRef)}`,record=petRef=>`${pet(petRef)}/everfur_record`,parsed=async(call,req,map)=>{let result=await funnel.send(call,req,req.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!result.ok)return result;let value=map(result.value);return value===null?err(makeEverfurError("internalError",{retryable:false})):ok(value)},factBody=(input,corrected)=>!segment(input.entityType,FACT_ENTITY_TYPE_MAX)||!segment(input.canonicalKey,FACT_CANONICAL_KEY_MAX)||input.idempotencyKey!==void 0&&!segment(input.idempotencyKey,IDEMPOTENCY_KEY_MAX)||corrected!==void 0&&Object.keys(corrected).length===0?null:{entity_type:input.entityType,canonical_key:input.canonicalKey,...corrected!==void 0?{corrected_fields:corrected}:{},...input.idempotencyKey!==void 0?{idempotency_key:input.idempotencyKey}:{}};return{getRecordDepth:petRef=>read("records.depth.record",petRef,`${pet(petRef)}/record`,wire=>mapRecordDepth(petRef,wire)),getTimeline:petRef=>read("records.depth.timeline",petRef,`${pet(petRef)}/timeline`,wire=>mapRecordsTimeline(petRef,wire)),getDocumentContributions(petRef,docId){return segment(docId,64)?read("records.depth.contributions",petRef,`${pet(petRef)}/documents/${encodeURIComponent(docId)}/contributions`,wire=>mapDocumentContributions(petRef,wire)):invalid2()},getMarkers:petRef=>read("records.depth.markers",petRef,`${pet(petRef)}/markers`,wire=>mapRecordMarkers(petRef,wire)),createShare(petRef,opts){if(!segment(petRef,PET_REF_MAX))return invalid2();let audience=opts?.audience;return audience!==void 0&&!RECORD_SHARE_AUDIENCES.includes(audience)?invalid2():parsed("records.share.create",{method:"POST",path:`${record(petRef)}/share`,...audience!==void 0?{body:{audience:audience}}:{}},wire=>mapRecordShareLink(wire,deps.apiBaseUrl))},emailShare(petRef,input){let kind=input.recipientKind,email2=typeof input.recipientEmail=="string"?input.recipientEmail.trim():"",kindOk=kind==="other"||RECORD_SHARE_AUDIENCES.includes(kind);return!segment(petRef,PET_REF_MAX)||!kindOk||!isShareRecipientEmail(email2)||hasLoneSurrogate(email2)?invalid2():parsed("records.share.email",{method:"POST",path:`${record(petRef)}/share/email`,body:{recipient_email:email2,recipient_kind:kind}},mapRecordShareEmailReceipt)},async readFeatures(){try{let result=await funnel.send("records.getFeatures",{method:"GET",path:"/widget/v1/records/features"});return result.ok?mapRecordsFeatures(result.value):RECORDS_FEATURES_PDF_ONLY}catch{return RECORDS_FEATURES_PDF_ONLY}},listShares(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.share.list",{method:"GET",path:`${record(petRef)}/shares`},mapRecordShareList):invalid2()},async revokeShare(petRef,shareId){if(!segment(petRef,PET_REF_MAX)||!segment(shareId,64))return invalid2();let result=await funnel.send("records.share.revoke",{method:"DELETE",path:`${record(petRef)}/shares/${encodeURIComponent(shareId)}`},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},getPdfLink(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.pdf.link",{method:"GET",path:`${record(petRef)}/pdf-link`},mapRecordPdfLink):invalid2()},async editFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input,input.correctedFields):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.edit",{method:"POST",path:`${record(petRef)}/facts/edit`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},async removeFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.remove",{method:"POST",path:`${record(petRef)}/facts/remove`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},listRequestDocuments(requestId2){return segment(requestId2,64)?parsed("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(requestId2)}/documents`},mapRequestDocuments):invalid2()},listAuthorizationSignatures:()=>parsed("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},mapSignatureSuggestions)}}function invalid2(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsDepthClient(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();return react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsDepthClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{},...typeof services.apiBaseUrl=="string"?{apiBaseUrl:services.apiBaseUrl}:{}})},[runtime,userRef,scopeEpoch])}function useRecordsDepthRead(petRef,read,isEmpty,extraKey=""){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),consentEpoch=useRecordsConsentEpoch(petRef),scope=react.useMemo(()=>({}),[client,petRef,extraKey,consentEpoch]),[state,setState]=react.useState({scope:scope,value:null,error:null,loading:true}),generation=react.useRef(0),load=react.useCallback(async()=>{let gen=generation.current+=1;if(setState({scope:scope,value:null,error:null,loading:true}),userRef===null){setState({scope:scope,value:null,error:null,loading:false});return}let result=await read(client,petRef);gen===generation.current&&(result.ok?setState({scope:scope,value:result.value,error:null,loading:false}):setState({scope:scope,value:null,error:result.error,loading:false}))},[client,petRef,read,scope,userRef]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let current=state.scope===scope?state:{value:null,error:null,loading:true},refresh=react.useCallback(()=>{load()},[load]),available=current.error===null||current.error.httpStatus!==404,error=available?current.error:null,status=current.loading?"loading":error!==null?"error":current.value===null?"empty":current.value.withheld?"populated":isEmpty(current.value)?"empty":"populated";return react.useMemo(()=>({status:status,value:current.value,error:error,available:available,refresh:refresh}),[status,current.value,error,available,refresh])}function isDarkRouteError(error){return error!==null&&error.httpStatus===404}var readMarkers=(client,petRef)=>client.getMarkers(petRef),markersEmpty=value=>value.markers.length===0;function useRecordsMarkers(petRef){let state=useRecordsDepthRead(petRef,readMarkers,markersEmpty);return react.useMemo(()=>{let markers=state.available&&state.value!==null&&!state.value.withheld?state.value:null;return{status:state.status,markers:markers,available:state.available,error:state.error,refresh:state.refresh}},[state])}var EMAIL3=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function useRecordsConsentForm(input){let{clinic:clinic,controller:controller,depthClient:depthClient,capture:capture,onCreated:onCreated}=input,clinicName=clinic.clinic?.name??clinic.freeText??"",isFreeText=clinic.clinic===null,[authorized,setAuthorized]=react.useState(false),[ownerName,setOwnerName]=react.useState(input.ownerName),[email2,setEmail]=react.useState(clinic.email),[emailTouched,setEmailTouched]=react.useState(false),[copy,setCopy]=react.useState(null),[copyError,setCopyError]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[created,setCreated]=react.useState(null),[signatures,setSignatures]=react.useState([]),[reuseSignatureId,setReuseSignatureId]=react.useState(null),[signed,setSigned]=react.useState(false),locked=react.useRef(false),live=react.useRef(true),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),attempt=react.useRef(null);react.useEffect(()=>(live.current=true,()=>{live.current=false,attempt.current=null}),[controller]),react.useEffect(()=>{let alive=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{alive&&(result.ok?(setCopy(result.value),setCopyError(null)):setCopyError(result.error))}).catch(()=>{alive&&setCopyError(makeEverfurError("internalError"))}),()=>{alive=false}},[controller,copyAttempt]),react.useEffect(()=>{if(depthClient===void 0)return;let alive=true;return depthClient.listAuthorizationSignatures().then(result=>{alive&&(result.ok?setSignatures(result.value):isDarkRouteError(result.error)||setSignatures([]))}).catch(()=>{}),()=>{alive=false}},[depthClient]);let needsEmail=clinicNeedsEmail(clinic.clinic),normalizedEmail=email2.trim().toLowerCase(),validEmail=EMAIL3.test(normalizedEmail),emailError=needsEmail&&(emailTouched||normalizedEmail.length>0)&&!validEmail?normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired:null,named=ownerName.trim().length>0,scope=copy&&named?renderClinicScope(copy,ownerName.trim(),petNameOr(input.petName),clinicName):null,hasSignature=input.hostCapture===true||signed||reuseSignatureId!==null,readyButSigned=!!(authorized&©&&scope&&named&&clinicName&&(!needsEmail||validEmail)),ready=readyButSigned&&hasSignature,submit=react.useCallback(async()=>{if(!(locked.current||created!==null||!copy||!scope)){if(!clinicName){setError(RECORDS_CONSENT_COPY.missingDraftError);return}if(needsEmail&&!validEmail){setEmailTouched(true),setError(normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired);return}if(!(!authorized||!ownerName.trim())){locked.current=true,setBusy(true),setError(null);try{if(attempt.current===null){let signature=reuseSignatureId!==null?{signatureId:reuseSignatureId}:await capture();if(!live.current)return;if(signature===null){setError(RECORDS_CONSENT_COPY.missingSignatureError);return}let target=clinic.clinic&&(!needsEmail||clinic.clinic.emailStatus==="none")?{clinicId:clinic.clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:input.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:normalizedEmail}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}let result=await controller.createClinicRequest(attempt.current);if(!live.current)return;if(!result.ok){setError(result.error.displayMessage);return}if(result.value.petRef!==input.petRef){setError(makeEverfurError("internalError").displayMessage);return}setCreated(result.value),attempt.current=null,onCreated?.(result.value)}catch{live.current&&setError(makeEverfurError("internalError").displayMessage)}finally{locked.current=false,live.current&&setBusy(false)}}}},[authorized,capture,clinic.clinic,clinicName,controller,copy,created,input.petRef,needsEmail,normalizedEmail,onCreated,ownerName,reuseSignatureId,scope,validEmail]),invalidate=react.useCallback(()=>{attempt.current=null,setError(null)},[]);return{title:isFreeText?RECORDS_CONSENT_COPY.titleFreeText:RECORDS_CONSENT_COPY.titleDirectory,clinicName:clinicName,isFreeText:isFreeText,authorized:authorized,ownerName:ownerName,email:email2,emailError:emailError,needsEmail:needsEmail,directoryClinicNoEmail:needsEmail&&clinic.clinic!==null,copy:copy,copyError:copyError,scope:scope,error:error,busy:busy,created:created,ready:ready,signatures:signatures,reuseSignatureId:reuseSignatureId,hasSignature:hasSignature,scopeAwaitingName:copy!==null&&!named,signatureLastMissing:readyButSigned&&!hasSignature,setAuthorized(value){locked.current||(invalidate(),setAuthorized(value))},setOwnerName(value){locked.current||(invalidate(),setOwnerName(value))},setEmail(value){locked.current||(invalidate(),setEmailTouched(false),setEmail(value))},setSigned(value){locked.current||(invalidate(),setSigned(value),value&&setReuseSignatureId(null))},pickReuseSignature(signatureId){locked.current||(invalidate(),setReuseSignatureId(signatureId))},retryCopy(){setCopyError(null),setCopyAttempt(n=>n+1)},submit:submit}}function EverfurRecordsConsent(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
329
|
+
return Object.freeze({petRef:pet,withheld:false,document:mapDocumentRow(parsed.data.document),contributions:contributions,contributionCount:parsed.data.contribution_count??contributions.length})}var BASE3="/widget/v1/records/pets";function createRecordsDepthClient(deps){let funnel=withPlainNotFound(deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}})),segment=(value,max)=>typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)&&[...value].length<=max,read=async(call,petRef,path,map)=>{if(!segment(petRef,PET_REF_MAX))return invalid2();let result=await funnel.send(call,{method:"GET",path:path});if(!result.ok)return result;let view=map(result.value);return view.petRef===petRef?ok(view):err(makeEverfurError("internalError",{retryable:false}))},pet=petRef=>`${BASE3}/${encodeURIComponent(petRef)}`,record=petRef=>`${pet(petRef)}/everfur_record`,parsed=async(call,req,map)=>{let result=await funnel.send(call,req,req.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!result.ok)return result;let value=map(result.value);return value===null?err(makeEverfurError("internalError",{retryable:false})):ok(value)},factBody=(input,corrected)=>!segment(input.entityType,FACT_ENTITY_TYPE_MAX)||!segment(input.canonicalKey,FACT_CANONICAL_KEY_MAX)||input.idempotencyKey!==void 0&&!segment(input.idempotencyKey,IDEMPOTENCY_KEY_MAX)||corrected!==void 0&&Object.keys(corrected).length===0?null:{entity_type:input.entityType,canonical_key:input.canonicalKey,...corrected!==void 0?{corrected_fields:corrected}:{},...input.idempotencyKey!==void 0?{idempotency_key:input.idempotencyKey}:{}};return{getRecordDepth:petRef=>read("records.depth.record",petRef,`${pet(petRef)}/record`,wire=>mapRecordDepth(petRef,wire)),getTimeline:petRef=>read("records.depth.timeline",petRef,`${pet(petRef)}/timeline`,wire=>mapRecordsTimeline(petRef,wire)),getDocumentContributions(petRef,docId){return segment(docId,64)?read("records.depth.contributions",petRef,`${pet(petRef)}/documents/${encodeURIComponent(docId)}/contributions`,wire=>mapDocumentContributions(petRef,wire)):invalid2()},getMarkers:petRef=>read("records.depth.markers",petRef,`${pet(petRef)}/markers`,wire=>mapRecordMarkers(petRef,wire)),createShare(petRef,opts){if(!segment(petRef,PET_REF_MAX))return invalid2();let audience=opts?.audience;return audience!==void 0&&!RECORD_SHARE_AUDIENCES.includes(audience)?invalid2():parsed("records.share.create",{method:"POST",path:`${record(petRef)}/share`,...audience!==void 0?{body:{audience:audience}}:{}},wire=>mapRecordShareLink(wire,deps.apiBaseUrl))},emailShare(petRef,input){let kind=input.recipientKind,email2=typeof input.recipientEmail=="string"?input.recipientEmail.trim():"",kindOk=kind==="other"||RECORD_SHARE_AUDIENCES.includes(kind);return!segment(petRef,PET_REF_MAX)||!kindOk||!isShareRecipientEmail(email2)||hasLoneSurrogate(email2)?invalid2():parsed("records.share.email",{method:"POST",path:`${record(petRef)}/share/email`,body:{recipient_email:email2,recipient_kind:kind}},mapRecordShareEmailReceipt)},async readFeatures(){try{let result=await funnel.send("records.getFeatures",{method:"GET",path:"/widget/v1/records/features"});return result.ok?mapRecordsFeatures(result.value):RECORDS_FEATURES_PDF_ONLY}catch{return RECORDS_FEATURES_PDF_ONLY}},listShares(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.share.list",{method:"GET",path:`${record(petRef)}/shares`},mapRecordShareList):invalid2()},async revokeShare(petRef,shareId){if(!segment(petRef,PET_REF_MAX)||!segment(shareId,64))return invalid2();let result=await funnel.send("records.share.revoke",{method:"DELETE",path:`${record(petRef)}/shares/${encodeURIComponent(shareId)}`},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},getPdfLink(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.pdf.link",{method:"GET",path:`${record(petRef)}/pdf-link`},mapRecordPdfLink):invalid2()},async editFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input,input.correctedFields):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.edit",{method:"POST",path:`${record(petRef)}/facts/edit`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},async removeFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.remove",{method:"POST",path:`${record(petRef)}/facts/remove`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},listRequestDocuments(requestId2){return segment(requestId2,64)?parsed("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(requestId2)}/documents`},mapRequestDocuments):invalid2()},listAuthorizationSignatures:()=>parsed("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},mapSignatureSuggestions)}}function invalid2(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsDepthClient(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();return react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsDepthClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{},...typeof services.apiBaseUrl=="string"?{apiBaseUrl:services.apiBaseUrl}:{}})},[runtime,userRef,scopeEpoch])}function useRecordsDepthRead(petRef,read,isEmpty,extraKey=""){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),consentEpoch=useRecordsConsentEpoch(petRef),scope=react.useMemo(()=>({}),[client,petRef,extraKey,consentEpoch]),[state,setState]=react.useState({scope:scope,value:null,error:null,loading:true}),generation=react.useRef(0),load=react.useCallback(async()=>{let gen=generation.current+=1;if(setState({scope:scope,value:null,error:null,loading:true}),userRef===null){setState({scope:scope,value:null,error:null,loading:false});return}let result=await read(client,petRef);gen===generation.current&&(result.ok?setState({scope:scope,value:result.value,error:null,loading:false}):setState({scope:scope,value:null,error:result.error,loading:false}))},[client,petRef,read,scope,userRef]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let current=state.scope===scope?state:{value:null,error:null,loading:true},refresh=react.useCallback(()=>{load()},[load]),available=current.error===null||current.error.httpStatus!==404,error=available?current.error:null,status=current.loading?"loading":error!==null?"error":current.value===null?"empty":current.value.withheld?"populated":isEmpty(current.value)?"empty":"populated";return react.useMemo(()=>({status:status,value:current.value,error:error,available:available,refresh:refresh}),[status,current.value,error,available,refresh])}function isDarkRouteError(error){return error!==null&&error.httpStatus===404}var readMarkers=(client,petRef)=>client.getMarkers(petRef),markersEmpty=value=>value.markers.length===0;function useRecordsMarkers(petRef){let state=useRecordsDepthRead(petRef,readMarkers,markersEmpty);return react.useMemo(()=>{let markers=state.available&&state.value!==null&&!state.value.withheld?state.value:null;return{status:state.status,markers:markers,available:state.available,error:state.error,refresh:state.refresh}},[state])}var EMAIL3=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function useRecordsConsentForm(input){let{clinic:clinic,controller:controller,depthClient:depthClient,capture:capture,onCreated:onCreated}=input,clinicName=clinic.clinic?.name??clinic.freeText??"",isFreeText=clinic.clinic===null,[authorized,setAuthorized]=react.useState(false),[ownerName,setOwnerName]=react.useState(input.ownerName),[email2,setEmail]=react.useState(clinic.email),[emailTouched,setEmailTouched]=react.useState(false),[copy,setCopy]=react.useState(null),[copyError,setCopyError]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[created,setCreated]=react.useState(null),[signatures,setSignatures]=react.useState([]),[reuseSignatureId,setReuseSignatureId]=react.useState(null),[signed,setSigned]=react.useState(false),locked=react.useRef(false),live=react.useRef(true),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),attempt=react.useRef(null);react.useEffect(()=>(live.current=true,()=>{live.current=false,attempt.current=null}),[controller]),react.useEffect(()=>{let alive=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{alive&&(result.ok?(setCopy(result.value),setCopyError(null)):setCopyError(result.error))}).catch(()=>{alive&&setCopyError(makeEverfurError("internalError"))}),()=>{alive=false}},[controller,copyAttempt]),react.useEffect(()=>{if(depthClient===void 0)return;let alive=true;return depthClient.listAuthorizationSignatures().then(result=>{alive&&(result.ok?setSignatures(result.value):isDarkRouteError(result.error)||setSignatures([]))}).catch(()=>{}),()=>{alive=false}},[depthClient]);let needsEmail=clinicNeedsEmail(clinic.clinic),normalizedEmail=email2.trim().toLowerCase(),validEmail=EMAIL3.test(normalizedEmail),emailError=needsEmail&&(emailTouched||normalizedEmail.length>0)&&!validEmail?normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired:null,named=ownerName.trim().length>0,scope=copy&&named?renderClinicScope(copy,ownerName.trim(),petNameOr(input.petName),clinicName):null,hasSignature=input.hostCapture===true||signed||reuseSignatureId!==null,readyButSigned=!!(authorized&©&&scope&&named&&clinicName&&(!needsEmail||validEmail)),ready=readyButSigned&&hasSignature,submit=react.useCallback(async()=>{if(!(locked.current||created!==null||!copy||!scope)){if(!clinicName){setError(RECORDS_CONSENT_COPY.missingDraftError);return}if(needsEmail&&!validEmail){setEmailTouched(true),setError(normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired);return}if(!(!authorized||!ownerName.trim())){locked.current=true,setBusy(true),setError(null);try{if(attempt.current===null){let signature=reuseSignatureId!==null?{signatureId:reuseSignatureId}:await capture();if(!live.current)return;if(signature===null){setError(RECORDS_CONSENT_COPY.missingSignatureError);return}let target=clinic.clinic&&(!needsEmail||clinic.clinic.emailStatus==="none")?{clinicId:clinic.clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:input.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:normalizedEmail}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}let result=await controller.createClinicRequest(attempt.current);if(!live.current)return;if(!result.ok){setError(result.error.displayMessage);return}if(result.value.petRef!==input.petRef){setError(makeEverfurError("internalError").displayMessage);return}setCreated(result.value),attempt.current=null,onCreated?.(result.value)}catch{live.current&&setError(makeEverfurError("internalError").displayMessage)}finally{locked.current=false,live.current&&setBusy(false)}}}},[authorized,capture,clinic.clinic,clinicName,controller,copy,created,input.petRef,needsEmail,normalizedEmail,onCreated,ownerName,reuseSignatureId,scope,validEmail]),invalidate=react.useCallback(()=>{attempt.current=null,setError(null)},[]);return{title:isFreeText?RECORDS_CONSENT_COPY.titleFreeText:RECORDS_CONSENT_COPY.titleDirectory,clinicName:clinicName,isFreeText:isFreeText,authorized:authorized,ownerName:ownerName,email:email2,emailError:emailError,needsEmail:needsEmail,directoryClinicNoEmail:needsEmail&&clinic.clinic!==null,copy:copy,copyError:copyError,scope:scope,error:error,busy:busy,created:created,ready:ready,signatures:signatures,reuseSignatureId:reuseSignatureId,hasSignature:hasSignature,scopeAwaitingName:copy!==null&&!named,signatureLastMissing:readyButSigned&&!hasSignature,setAuthorized(value){locked.current||(invalidate(),setAuthorized(value))},setOwnerName(value){locked.current||(invalidate(),setOwnerName(value))},setEmail(value){locked.current||(invalidate(),setEmailTouched(false),setEmail(value))},setSigned(value){locked.current||(invalidate(),setSigned(value),value&&setReuseSignatureId(null))},pickReuseSignature(signatureId){locked.current||(invalidate(),setReuseSignatureId(signatureId))},retryCopy(){setCopyError(null),setCopyAttempt(n=>n+1)},submit:submit}}function EverfurRecordsConsent(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
324
330
|
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(ConsentBody,{...guardHostProps(props,["onCreated","onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.clinic.key]))})}var IOS2=reactNative.Platform.OS==="ios";function ConsentBody({petRef:petRef,petName:petName,clinic:clinic,ownerName:ownerName,onCaptureSignature:onCaptureSignature,onCreated:onCreated,controller:controller,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=useLocalStyles3(),theme=useEverfurTheme(),runtimeController=useEverfurRecordsClinic(),directSendNote=useRecordsSandboxTenant()?RECORDS_SANDBOX_COPY.newClinicDirectSendNote:RECORDS_CONSENT_COPY.newClinicDirectSendNote,depthClient=useEverfurRecordsDepthClient(),[png,setPng]=react.useState(null),[mode,setMode]=react.useState("draw"),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),form=useRecordsConsentForm({petRef:petRef,petName:petName,ownerName:ownerName??"",clinic:clinic,controller:controller??runtimeController,depthClient:depthClient,capture:onCaptureSignature?()=>onCaptureSignature({petRef:petRef,petName:petNameOr(petName),ownerName:form.ownerName,clinicName:form.clinicName,authorizationVersion:form.copy?.authorizationVersion??"",scopeText:form.scope??"",signal:(new AbortController).signal}):padCapture,hostCapture:onCaptureSignature!==void 0,onCreated:request=>{onCreated?.(request),onNavigate?.({name:"dashboard"})}}),formRef=react.useRef(form);formRef.current=form;let onPadChange=react.useCallback(next=>{setPng(next),formRef.current.setSigned(next!==null)},[]),busy=form.busy,keyboard=useChatKeyboardOffset(void 0,IOS2);/* @__PURE__ */
|
|
325
331
|
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
326
332
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:form.title,onBack:onBack,testID:"records-consent-header"}),
|
|
@@ -358,10 +364,10 @@ return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>form.pickReuseSignature
|
|
|
358
364
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeHeading,accessibilityRole:"header",children:RECORDS_CONSENT_COPY.whatHappensNext}),
|
|
359
365
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeBody,children:RECORDS_CONSENT_COPY.whatHappensNextBody})]}),form.error?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:form.error})}):null,form.created?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.bodyText,children:form.created.statusLabel||RECORDS_COPY.records}):null]}),
|
|
360
366
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.footer,testID:"records-consent-footer",children:/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?RECORDS_CONSENT_COPY.submitting:RECORDS_CONSENT_COPY.submit,disabled:!form.ready,busy:busy,onPress:()=>{reactNative.Keyboard.dismiss(),form.submit()},style:local.submit,testID:"records-consent-submit"})})]}),
|
|
361
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function useLocalStyles3(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles3(theme),[theme])}function makeLocalStyles3(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,
|
|
362
|
-
return Object.freeze({mode:mode})}function isCaptureAvailable(camera){return camera!=null&&camera.isAvailable===true}function markerStatusTone(status){return status==="above"||status==="below"?"critical":status==="in_range"?"positive":"neutral"}function markerStatusSpoken(status){switch(status){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"}}function rangePhrase(point){return point.refLow!==null&&point.refHigh!==null?`, reference range ${point.refLow} to ${point.refHigh}`:point.refLow!==null?`, reference range at least ${point.refLow}`:point.refHigh!==null?`, reference range up to ${point.refHigh}`:""}function formatReferenceRange(point,unit){let u=unit?` ${unit}`:"";return point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}${u}`:point.refLow!==null?`≥ ${point.refLow}${u}`:point.refHigh!==null?`≤ ${point.refHigh}${u}`:"-"}function markerPointSpoken(marker,point){let reviewed=point.reviewed?", reviewed by our team":"",clinic=point.sourceClinic?`, from ${point.sourceClinic}`:"";return`${formatRecordsDate(point.at)}: ${formatMarkerReading(point.value,marker.unit,point.qualitativeResult)}, ${markerStatusSpoken(point.status)}${rangePhrase(point)}${clinic}${reviewed}`}function lead(petName){return petName?.trim()||"my pet"}function clause(
|
|
367
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function useLocalStyles3(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles3(theme),[theme])}function makeLocalStyles3(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xl+space.xs,gap:space.lg+space.xs/2},lead:text4(type.size.body,type.lineHeight.normal,color.text.muted),scopeCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.md,...slotBox(theme.slots.card,1)},nextCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.sm,...slotBox(theme.slots.card)},scopeHeading:{...text4(type.size.subtitle,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...slotText(theme.slots.card)},scopeBody:{...text4(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary),...slotText(theme.slots.card)},bullets:{gap:space.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:space.sm},check:{...text4(type.size.body,type.lineHeight.normal,color.brandInk,"bold")},bulletText:{flex:1,...text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary)},retentionRow:{paddingTop:space.xs,borderTopWidth:1,borderTopColor:color.borderHairlineGreen},retentionText:text4(type.size.tiny,type.lineHeight.normal,color.text.muted),serverScope:{...text4(type.size.bodyTight,type.lineHeight.relaxed,color.text.secondary),paddingTop:space.xs},toggle:{flexDirection:"row",alignItems:"flex-start",gap:space.md,borderRadius:radius.lg-space.xs,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md+space.xs/2},toggleChecked:{borderColor:color.brandInk,backgroundColor:color.brandSoft},box:{width:space.xl,height:space.xl,borderRadius:radius.xs+1,borderWidth:1.6,borderColor:color.brandInk,alignItems:"center",justifyContent:"center",backgroundColor:color.surface},boxChecked:{backgroundColor:color.brandInk},boxCheck:{...text4(type.size.body,type.lineHeight.tight,color.surface,"bold")},toggleLabel:{flex:1,...text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary,"bold")},block:{gap:space.sm},signatureBlock:{gap:space.sm},gallery:{gap:space.sm,paddingVertical:space.xs},tile:{width:space.xxl*3+space.lg,height:space.xxl+space.lg+space.sm,borderRadius:radius.sm,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,overflow:"hidden"},tileSelected:{borderColor:color.brandInk,borderWidth:2},tileImage:{width:"100%",height:"100%"},signatureHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},modeToggle:{minHeight:space.xxl+space.md,alignItems:"center",justifyContent:"center"},modeToggleText:{...text4(type.size.bodyTight,type.lineHeight.snug,color.linkInk,"bold"),textDecorationLine:"underline"},footer:{paddingHorizontal:space.lg,paddingTop:space.md,paddingBottom:space.xxl,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,backgroundColor:color.background},submit:{minHeight:space.xxl+space.lg+space.xs+space.xs/2}})}function fileHandleFromMedia(source){let handle={uri:source.uri,mimeType:source.mimeType},size=mediaByteSize(source);return size!==null&&(handle.sizeBytes=size),/* @__PURE__ */Object.freeze(handle)}function mediaByteSize(source){let candidate=source.byteSize??source.sizeBytes;return typeof candidate=="number"&&Number.isFinite(candidate)&&candidate>=0?candidate:null}function captureOptionsFor(mode,maxDurationSeconds){/* @__PURE__ */
|
|
368
|
+
return Object.freeze({mode:mode})}function isCaptureAvailable(camera){return camera!=null&&camera.isAvailable===true}function markerStatusTone(status){return status==="above"||status==="below"?"critical":status==="in_range"?"positive":"neutral"}function markerStatusSpoken(status){switch(status){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"}}function rangePhrase(point){return point.refLow!==null&&point.refHigh!==null?`, reference range ${point.refLow} to ${point.refHigh}`:point.refLow!==null?`, reference range at least ${point.refLow}`:point.refHigh!==null?`, reference range up to ${point.refHigh}`:""}function formatReferenceRange(point,unit){let u=unit?` ${unit}`:"";return point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}${u}`:point.refLow!==null?`≥ ${point.refLow}${u}`:point.refHigh!==null?`≤ ${point.refHigh}${u}`:"-"}function markerPointSpoken(marker,point){let reviewed=point.reviewed?", reviewed by our team":"",clinic=point.sourceClinic?`, from ${point.sourceClinic}`:"";return`${formatRecordsDate(point.at)}: ${formatMarkerReading(point.value,marker.unit,point.qualitativeResult)}, ${markerStatusSpoken(point.status)}${rangePhrase(point)}${clinic}${reviewed}`}function markersFeaturedFirst(markers,featuredMarkerId){if(!featuredMarkerId)return markers;let at=markers.findIndex(marker=>marker.markerId===featuredMarkerId);return at<=0?markers:[markers[at],...markers.slice(0,at),...markers.slice(at+1)]}var MARKER_CAROUSEL_MAX_DOTS=7;function markerDotWindow(activeIndex,total,max=MARKER_CAROUSEL_MAX_DOTS){let count=Math.max(0,Math.min(total,max)),start=total<=max?0:Math.max(0,Math.min(activeIndex-Math.floor(max/2),total-max));return Array.from({length:count},(_,i)=>start+i)}function lead(petName){return petName?.trim()||"my pet"}function clause(text4){let t=text4.trim();return/[.!?]$/.test(t)?t:`${t}.`}function buildMarkerAskPrompt(petName,input){let name=input.canonicalName.trim()||"a lab marker",parts=[`I'm looking at ${lead(petName)}'s ${name}`],stats=[input.latestValueText?.trim(),input.statusText?.trim(),input.trajectoryText?.trim()].filter(Boolean).join(", ");return parts[0]+=stats?`: ${stats}.`:".",input.meaningText?.trim()&&parts.push(clause(input.meaningText)),parts.push(`What does this trend tell me, and should I do anything differently for ${lead(petName)}?`),{prompt:parts.join(" "),entityRef:{type:"marker",id:input.markerId,payload:{marker:name,...input.statusText?.trim()?{status:input.statusText.trim()}:{}}}}}function buildMarkerSummaryAskPrompt(petName,summary,petId){let{totalMarkers:totalMarkers,inRangeCount:inRangeCount,outOfRangeCount:outOfRangeCount,unknownCount:unknownCount}=summary;if(totalMarkers===0)return{prompt:`I'm looking at ${lead(petName)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${lead(petName)}?`,entityRef:{type:"marker_summary",id:petId,payload:{total:0}}};let tail=unknownCount>0?`, ${unknownCount} without a reference range`:"";return{prompt:`I'm looking at ${lead(petName)}'s lab markers: ${totalMarkers} total, ${inRangeCount} in range, ${outOfRangeCount} out of range${tail}. What should I focus on?`,entityRef:{type:"marker_summary",id:petId,payload:{total:totalMarkers,inRange:inRangeCount,outOfRange:outOfRangeCount,unknown:unknownCount}}}}function buildMarkerReadingAskPrompt(petName,input){let name=input.canonicalName.trim()||"a lab marker",bits=[`${name}: ${input.valueText.trim()}`];input.collectedAt?.trim()&&bits.push(`collected ${input.collectedAt.trim()}`),input.sourceClinic?.trim()&&bits.push(`from ${input.sourceClinic.trim()}`),input.referenceText?.trim()&&bits.push(`reference range ${input.referenceText.trim()}`),input.flagged&&bits.push(`flagged ${input.flagged}`);let payload={marker:name};return input.flagged&&(payload.status=input.flagged),input.reviewed!==void 0&&(payload.reviewed=input.reviewed),{prompt:`I'm looking at ${lead(petName)}'s ${bits.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:input.entityId,payload:payload}}}function buildRecordsRequestAskPrompt(petName,input,requestId2){let clinic=input.clinicName?.trim(),held=input.heldItemCount??0,heldPhrase=held>0?`, ${held} fact${held===1?"":"s"} being verified`:"";return{prompt:`I'm looking at ${lead(petName)}'s records request${clinic?` to ${clinic}`:""}, status: ${input.statusLabel.trim()}${heldPhrase}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:requestId2,payload:{status:input.status,held:held,...clinic?{clinic:clinic}:{}}}}}var ENTITY_TYPE_MAP=/* @__PURE__ */Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function buildEntityRowAskPrompt(petName,input,entityType,entityId){let kind=input.entityTypeLabel.trim()||"record",title=input.title.trim()||kind,detail=input.detail?.trim();return{prompt:`I'm looking at ${lead(petName)}'s ${kind.toLowerCase()}: ${title}${detail?`, ${detail}`:""}. What does this mean, and what should I keep on top of for ${lead(petName)}?`,entityRef:{type:ENTITY_TYPE_MAP[entityType]??entityType,id:entityId,payload:{kind:kind,title:title,...detail?{detail:detail}:{}}}}}function buildUpcomingCareAskPrompt(petName,items,petId){let list=items.filter(i=>i.label.trim()),entityRef={type:"upcoming_care",id:petId};if(list.length===0)return{prompt:`I'm looking at ${lead(petName)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${lead(petName)} be on?`,entityRef:entityRef};let named=[...list].sort((a,b)=>(a.tone==="overdue"?0:1)-(b.tone==="overdue"?0:1)).slice(0,4).map(i=>i.relativeText.trim()?`${i.label.trim()} (${i.relativeText.trim().toLowerCase()})`:i.label.trim());return{prompt:`I'm looking at ${lead(petName)}'s upcoming care: ${named.join(", ")}. What should I prioritize for ${lead(petName)}, and how do I stay on top of these?`,entityRef:entityRef}}function buildPhysicalExamAskPrompt(petName,input,examId){let parts=[`I'm looking at ${lead(petName)}'s physical exam${input.observedOn?.trim()?` from ${input.observedOn.trim()}`:""}.`],abnormal=input.abnormal.filter(a=>a.system.trim());return abnormal.length>0?(parts.push(`Abnormal: ${abnormal.slice(0,6).map(a=>`${a.system.trim()}: ${a.finding.trim()}`).join("; ")}.`),parts.push(`What do these findings mean, and what should I follow up on for ${lead(petName)}?`)):parts.push(`Everything examined came back normal. What does this tell me about ${lead(petName)}'s health?`),{prompt:parts.join(" "),entityRef:{type:"physical_exam",id:examId}}}function buildVisitNoteAskPrompt(petName,input,noteId){let parts=[`I'm looking at ${lead(petName)}'s visit notes${input.observedOn?.trim()?` from ${input.observedOn.trim()}`:""}.`];for(let s of input.sections.filter(section=>section.text.trim()).slice(0,3))parts.push(`${s.label.trim()||"Note"}: ${clause(s.text)}`);return parts.push(`Can you summarize what happened and what I should follow up on for ${lead(petName)}?`),{prompt:parts.join(" "),entityRef:{type:"visit",id:noteId}}}function buildConflictAskPrompt(petName,input,conflictId){let scope=input.scopeLabel.trim()||"a detail",cands=input.candidates.filter(c=>c.value.trim()),rendered=cands.slice(0,3).map(c=>`"${c.value.trim()}"${c.clinicName?.trim()?` (${c.clinicName.trim()})`:""}`).join(" vs ");return{prompt:`Two of ${lead(petName)}'s documents disagree on ${scope}: ${rendered}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:conflictId,payload:{field:scope,severity:input.severity,values:cands.map(c=>c.value.trim()).join(" | ")}}}}var REQUEST_LIST_COPY=/* @__PURE__ */Object.freeze({title:"Medical records",subtitle:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s uploads and clinic requests`:"Every upload and clinic request"},requestRecords:"Request records",requestRecordsA11y:"Request records from a clinic",uploadOwn:"I already have the records",ownerUpload:"Records you uploaded",clinicRequest:"Clinic request",meta:(ownerUpload,createdAt)=>`${ownerUpload?"Uploaded":"Requested"} ${formatRecordsInstant(createdAt)}`,rowA11y:(source,meta,status)=>`${source}, ${meta}, status ${status}`,allRequests:"Your record requests"}),STEP_LABELS=/* @__PURE__ */Object.freeze({preparing:"Preparing",sent:"Sent",processing:"Processing",done:"Ready"});function stepLabel(status){switch(status){case"awaiting_clinic":return STEP_LABELS.sent;case"received":case"parsing":case"in_review":return STEP_LABELS.processing;case"published":return STEP_LABELS.done;default:return STEP_LABELS.preparing}}function requestRowView(request){let ownerUpload=request.source==="owner_provided",source=request.clinicName?.trim()||(ownerUpload?REQUEST_LIST_COPY.ownerUpload:REQUEST_LIST_COPY.clinicRequest),status=request.statusLabel.trim()||stepLabel(request.status),meta=REQUEST_LIST_COPY.meta(ownerUpload,request.createdAt);/* @__PURE__ */
|
|
363
369
|
return Object.freeze({source:source,meta:meta,status:status,ownerUpload:ownerUpload,a11yLabel:REQUEST_LIST_COPY.rowA11y(source,meta,status)})}var PROCESSING_WIRE=/* @__PURE__ */new Set(["records_received","parsing","parsing_failed","in_review","review_email_failed"]),PROCESSING_FOLDED=/* @__PURE__ */new Set(["received","parsing","in_review"]);function isProcessing(request){return request.wireStatus!==void 0?PROCESSING_WIRE.has(request.wireStatus):PROCESSING_FOLDED.has(request.status)}function requestsStatusCardView(requests,petName,opts={}){let active=requests.filter(r=>!isTerminalStatus(r.status));if(requests.length===0||opts.activeOnly===true&&active.length===0)return null;let processing=requests.filter(isProcessing).length,title=processing>0?`${processing} document${processing===1?"":"s"} being read`:active.length>0?`${active.length} active record request${active.length===1?"":"s"}`:REQUEST_LIST_COPY.allRequests,subtitle=processing>0?`We’ll add ${processing===1?"it":"them"} to ${petName}’s records once ready.`:active.length>0?"See each clinic’s status and what happens next.":"See the status of every upload and clinic request.";/* @__PURE__ */
|
|
364
|
-
return Object.freeze({title:title,subtitle:subtitle,processing:processing>0,a11yLabel:`${title}. ${subtitle}`})}function canUploadRecords(onPickDocument){return onPickDocument!==void 0}function resolveConsentVersion(consentVersion,consent){return consentVersion??consent?.version??""}function canGrantConsent(consentVersion,consent){return resolveConsentVersion(consentVersion,consent).length>0}function selectErrorView(state,canGrant){return state.denialReason==="consent_required"?canGrant?{kind:"consent_required"}:{kind:"consent_unavailable"}:state.denialReason==="pet_not_found"?{kind:"pet_not_found",error:makeEverfurError("petNotFound",{retryable:false})}:state.denialReason==="entitlement"?{kind:"error",error:makeEverfurError("accessDenied")}:state.denialReason==="session_required"?{kind:"session_required"}:state.withheld?{kind:"withheld"}:state.error===null?{kind:"withheld"}:{kind:"error",error:state.error}}function selectRequestTitle(request){let clinic=request.clinicName?.trim()??"";return clinic.length>0?clinic:request.source==="owner_provided"?REQUEST_TITLE_COPY.ownerUpload:REQUEST_TITLE_COPY.clinicRequest}var REQUEST_TITLE_COPY=/* @__PURE__ */Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function selectResumableUploadRequest(_record,activeRequest){return activeRequest===null||activeRequest.status!=="awaiting_upload"?null:activeRequest}function selectRequestList(requests){let sorted=[...requests].sort((a,b)=>a.updatedAt!==b.updatedAt?a.updatedAt>b.updatedAt?-1:1:a.createdAt!==b.createdAt?a.createdAt>b.createdAt?-1:1:0);/* @__PURE__ */
|
|
370
|
+
return Object.freeze({title:title,subtitle:subtitle,processing:processing>0,a11yLabel:`${title}. ${subtitle}`})}function canUploadRecords(onPickDocument){return onPickDocument!==void 0}function resolveConsentVersion(consentVersion,consent){return consentVersion??consent?.version??""}function canGrantConsent(consentVersion,consent){return resolveConsentVersion(consentVersion,consent).length>0}function selectErrorView(state,canGrant){return state.denialReason==="consent_required"?canGrant?{kind:"consent_required"}:{kind:"consent_unavailable"}:state.denialReason==="pet_not_found"?{kind:"pet_not_found",error:makeEverfurError("petNotFound",{retryable:false})}:state.denialReason==="entitlement"?{kind:"error",error:makeEverfurError("accessDenied")}:state.denialReason==="session_required"?{kind:"session_required"}:state.withheld?{kind:"withheld"}:state.error===null?{kind:"withheld"}:{kind:"error",error:state.error}}function isConsentGate(view){return view.kind==="consent_required"||view.kind==="consent_unavailable"}function selectRequestTitle(request){let clinic=request.clinicName?.trim()??"";return clinic.length>0?clinic:request.source==="owner_provided"?REQUEST_TITLE_COPY.ownerUpload:REQUEST_TITLE_COPY.clinicRequest}var REQUEST_TITLE_COPY=/* @__PURE__ */Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function selectResumableUploadRequest(_record,activeRequest){return activeRequest===null||activeRequest.status!=="awaiting_upload"?null:activeRequest}function selectRequestList(requests){let sorted=[...requests].sort((a,b)=>a.updatedAt!==b.updatedAt?a.updatedAt>b.updatedAt?-1:1:a.createdAt!==b.createdAt?a.createdAt>b.createdAt?-1:1:0);/* @__PURE__ */
|
|
365
371
|
return Object.freeze(sorted)}function selectPrimaryLabel(request){let action=request.actionNeededLabel?.trim()??"";return action.length>0?action:request.statusLabel}function selectClinicCall(request){if(request.showClinicPhone!==true)return null;let phone=request.clinicPhone?.trim()??"";return phone.length===0?null:{phone:phone,dial:`tel:${phone.replace(/[^+\d]/g,"")}`,clinicName:request.clinicName?.trim()||null}}function selectRequestStatusTone(request){switch(request.wireStatus??request.status){case"published":return"positive";case"failed":case"clinic_declined":return"critical";case"revoked":return"neutral";case"clinic_responded_no_records":case"awaiting_upload":case"records_received":case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return"warning";default:return"info"}}var RING_SIZE=200,RING_STROKE=16;function buildRingSegments(summary,colors){let denominator=summary.inRangeCount+summary.outOfRangeCount+summary.unknownCount;if(!Number.isFinite(denominator)||denominator<=0)return[];let buckets=[{key:"in_range",color:colors.inRange,count:summary.inRangeCount},{key:"out_of_range",color:colors.outOfRange,count:summary.outOfRangeCount},{key:"unknown",color:colors.unknown,count:summary.unknownCount}],cumulative=0,out=[];for(let bucket of buckets){if(!(bucket.count>0))continue;let sweepDeg=bucket.count/denominator*360;if(!Number.isFinite(sweepDeg))return null;out.push({key:bucket.key,color:bucket.color,startDeg:cumulative,sweepDeg:sweepDeg}),cumulative+=sweepDeg}return out}function MarkerSummaryCard({summary:summary,onAsk:onAsk,testID:testID}){let styles=useStyles5(),theme=useEverfurTheme(),{totalMarkers:totalMarkers,inRangeCount:inRangeCount,outOfRangeCount:outOfRangeCount,unknownCount:unknownCount}=summary,segments=react.useMemo(()=>buildRingSegments(summary,{inRange:theme.color.success,outOfRange:theme.color.danger,unknown:theme.color.text.muted}),[summary,theme]),hasArcs=segments!==null&&segments.length>0;/* @__PURE__ */
|
|
366
372
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.card,accessibilityRole:"summary",testID:testID,children:[
|
|
367
373
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.title,children:MARKER_SUMMARY_COPY.title}),
|
|
@@ -383,11 +389,11 @@ return jsxRuntime.jsx(reactNative.View,{style:[styles.page,width!==void 0?{width
|
|
|
383
389
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.latestDate,children:formatRecordsDate(marker.latest.at)})]}):null,traj?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.trajectory,accessibilityRole:"text",children:traj}):null,chart!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.chartWrap,children:[
|
|
384
390
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.plot,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[chart.band?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.band,{top:pct(chart.band.topPct),height:pct(Math.max(0,chart.band.bottomPct-chart.band.topPct))}]}):null,chart.points.map(p=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onPointPress(marker,p.point),hitSlop:12,style:[styles.point,p.status==="above"||p.status==="below"?styles.pointDanger:null,{left:pct(p.xPct),top:pct(p.yPct)}],testID:`marker-point-${marker.markerId}-${p.index}`},p.index))]}),
|
|
385
391
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.a11yTable,accessibilityRole:"summary",accessibilityLabel:MARKER_CARD_COPY.readingsA11y(marker.name),children:marker.points.map((point,index)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityRole:"text",accessibilityLabel:markerPointSpoken(marker,point)},index))}),
|
|
386
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:marker.points.length===1?styles.singleHint:styles.tapHint,children:marker.points.length===1?MARKER_CARD_COPY.singleHint:MARKER_CARD_COPY.tapHint})]}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.emptyBody,accessibilityRole:"text",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.emptyText,children:MARKER_CARD_COPY.empty})}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onAsk(marker),accessibilityRole:"button",accessibilityLabel:MARKER_CARD_COPY.askNamed(marker.name),style:[screen.pill,screen.pillAsk],testID:`marker-ask-${marker.markerId}`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:screen.pillAskLabel,children:MARKER_CARD_COPY.askNamed(marker.name)})}):null]})})}function MarkerTrendCarousel({markers:
|
|
392
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:marker.points.length===1?styles.singleHint:styles.tapHint,children:marker.points.length===1?MARKER_CARD_COPY.singleHint:MARKER_CARD_COPY.tapHint})]}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.emptyBody,accessibilityRole:"text",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.emptyText,children:MARKER_CARD_COPY.empty})}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onAsk(marker),accessibilityRole:"button",accessibilityLabel:MARKER_CARD_COPY.askNamed(marker.name),style:[screen.pill,screen.pillAsk],testID:`marker-ask-${marker.markerId}`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:screen.pillAskLabel,children:MARKER_CARD_COPY.askNamed(marker.name)})}):null]})})}function MarkerTrendCarousel({markers:given,onPointPress:onPointPress,onAsk:onAsk,featuredMarkerId:featuredMarkerId}){let markers=react.useMemo(()=>markersFeaturedFirst(given,featuredMarkerId),[given,featuredMarkerId]),styles=useStyles6(),[width,setWidth]=react.useState(0),[activeIndex,setActiveIndex]=react.useState(0),onLayout=event=>setWidth(event.nativeEvent.layout.width),onMomentumEnd=event=>{if(width<=0)return;let next=Math.round(event.nativeEvent.contentOffset.x/width);setActiveIndex(Math.max(0,Math.min(next,markers.length-1)))},active=markers[activeIndex]??null;/* @__PURE__ */
|
|
387
393
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.carousel,onLayout:onLayout,testID:"marker-carousel",children:[
|
|
388
394
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,pagingEnabled:true,showsHorizontalScrollIndicator:false,onMomentumScrollEnd:onMomentumEnd,snapToAlignment:"start",children:markers.map(marker=>/* @__PURE__ */jsxRuntime.jsx(MarkerTrendCard,{marker:marker,width:width>0?width:void 0,onPointPress:onPointPress,onAsk:onAsk},marker.markerId))}),
|
|
389
395
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:MARKER_CAROUSEL_COPY.a11y(active?.name??null,activeIndex,markers.length),children:[
|
|
390
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.dots,children:markers.map(
|
|
396
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.dots,testID:"marker-carousel-dots",children:markerDotWindow(activeIndex,markers.length).map(index=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,index===activeIndex?styles.dotActive:null]},markers[index]?.markerId??index))}),
|
|
391
397
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.counter,children:MARKER_CAROUSEL_COPY.counter(activeIndex,markers.length)})]})]})}function MarkerProvenanceSheet({marker:marker,point:point,onClose:onClose,onAsk:onAsk}){let styles=useStyles6(),screen=useScreenStyles();if(marker===null||point===null)return null;let row=(label,value)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.detailRow,accessible:true,accessibilityRole:"text",accessibilityLabel:`${label}: ${value}`,children:[
|
|
392
398
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.detailLabel,children:label}),
|
|
393
399
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.detailValue,children:value})]},label);/* @__PURE__ */
|
|
@@ -401,8 +407,8 @@ return jsxRuntime.jsxs(reactNative.Modal,{transparent:true,visible:true,animatio
|
|
|
401
407
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheetBody,children:[
|
|
402
408
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.valueRow,children:[
|
|
403
409
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sheetName,children:marker.name}),
|
|
404
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sheetValue,children:formatMarkerReading(point.value,marker.unit,point.qualitativeResult)})]}),point.reviewed?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.reviewed,accessibilityRole:"text",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.reviewedText,children:PROVENANCE_COPY.reviewed})}):null,row(PROVENANCE_COPY.collected,formatRecordsDate(point.at)),point.sourceClinic?row(PROVENANCE_COPY.clinic,point.sourceClinic):null,row(PROVENANCE_COPY.referenceRange,point.refLow!==null||point.refHigh!==null?formatReferenceRange(point,marker.unit):PROVENANCE_COPY.noRange),point.docId?row(PROVENANCE_COPY.sourceDocument,point.docId):null,point.reviewed?null:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.unverified,accessibilityRole:"text",children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.ask,style:[screen.pill,screen.pillAsk],testID:"marker-provenance-ask",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:screen.pillAskLabel,children:PROVENANCE_COPY.ask})}):null]})]})]})}function useStyles6(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=reactNative.StyleSheet.hairlineWidth,dot=space.md,
|
|
405
|
-
return Object.freeze(out)}function isFactEditable(entity){return typeof entity.canonicalKey=="string"&&entity.canonicalKey.length>0}function defaultFactKey(){return`records-fact-${Date.now().toString(36)}`}function useRecordFactEdit(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),[overlay,setOverlay]=react.useState(EMPTY_FACT_OVERLAY),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),scope=react.useMemo(()=>({}),[client,petRef,userRef]),[darkScope,setDarkScope]=react.useState(null),markDark=react.useCallback(()=>setDarkScope(scope),[scope]),available=userRef!==null&&darkScope!==scope,locked=react.useRef(false),mintRef=react.useRef(opts.newIdempotencyKey);mintRef.current=opts.newIdempotencyKey;let mint=react.useCallback(()=>(mintRef.current??defaultFactKey)(),[]),settle=react.useCallback((result,rollback,mode)=>{if(setBusy(false),!result.ok){if(rollback(),isDarkRouteError(result.error)){markDark();return}setError(factEditErrorMessage(result.error,mode))}},[markDark]),edit=react.useCallback(async(entity,value)=>{let key=entity.canonicalKey??"",next=value.trim();if(locked.current||key.length===0||next.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,edits:{...current.edits,[key]:next}}));let result=await client.editFact(petRef,{entityType:entity.category,canonicalKey:key,correctedFields:factCorrectionFor(entity.value,next),idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"edit"),result},[client,petRef,overlay,settle,mint]),remove=react.useCallback(async entity=>{let key=entity.canonicalKey??"";if(locked.current||key.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,removed:[...current.removed,key]}));let result=await client.removeFact(petRef,{entityType:entity.category,canonicalKey:key,idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"remove"),result},[client,petRef,overlay,settle,mint]),clearError=react.useCallback(()=>setError(null),[]);return react.useMemo(()=>({overlay:overlay,busy:busy,error:error,available:available,edit:edit,remove:remove,clearError:clearError}),[overlay,busy,error,available,edit,remove,clearError])}var VACCINE_CATEGORIES=/* @__PURE__ */Object.freeze(["vaccination","parasite_prevention"]),VACCINE_UNDATED_GROUP="Undated",VACCINE_STATUS_LABEL=/* @__PURE__ */Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),VACCINE_CHIP_TONE=/* @__PURE__ */Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function toMillis(value){if(!value)return null;let ms=Date.parse(value);return Number.isNaN(ms)?null:ms}function isLapsed(entity){let status=entity.status?.toLowerCase()??"";return/overdue|lapsed|expired/.test(status)}function vaccineTone(entity){return entity.category==="parasite_prevention"?"prevention":toMillis(entity.observedAt)===null?"noDate":isLapsed(entity)?"overdue":"given"}function yearOf(at){let ms=toMillis(at);return ms===null?VACCINE_UNDATED_GROUP:String(new Date(ms).getUTCFullYear())}function buildRow(entity){let tone=vaccineTone(entity),parts=[entity.value!==null&&entity.value.length>0?entity.value:null,entity.observedAt!==null?formatRecordsDate(entity.observedAt):null].filter(part=>part!==null&&part.length>0);return{key:entity.key,name:entity.label,detail:parts.length>0?parts.join(" · "):null,statusLabel:VACCINE_STATUS_LABEL[tone],tone:tone,entity:entity}}function selectVaccineGroups(entities){let byYear=/* @__PURE__ */new Map;for(let entity of entities){if(!VACCINE_CATEGORIES.includes(entity.category))continue;let year=yearOf(entity.observedAt),bucket=byYear.get(year),item={row:buildRow(entity),at:entity.observedAt};bucket===void 0?byYear.set(year,[item]):bucket.push(item)}let years=[...byYear.keys()].sort((a,b)=>a===VACCINE_UNDATED_GROUP?1:b===VACCINE_UNDATED_GROUP?-1:Number(b)-Number(a));/* @__PURE__ */
|
|
410
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sheetValue,children:formatMarkerReading(point.value,marker.unit,point.qualitativeResult)})]}),point.reviewed?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.reviewed,accessibilityRole:"text",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.reviewedText,children:PROVENANCE_COPY.reviewed})}):null,row(PROVENANCE_COPY.collected,formatRecordsDate(point.at)),point.sourceClinic?row(PROVENANCE_COPY.clinic,point.sourceClinic):null,row(PROVENANCE_COPY.referenceRange,point.refLow!==null||point.refHigh!==null?formatReferenceRange(point,marker.unit):PROVENANCE_COPY.noRange),point.docId?row(PROVENANCE_COPY.sourceDocument,point.docId):null,point.reviewed?null:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.unverified,accessibilityRole:"text",children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.ask,style:[screen.pill,screen.pillAsk],testID:"marker-provenance-ask",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:screen.pillAskLabel,children:PROVENANCE_COPY.ask})}):null]})]})]})}function useStyles6(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=reactNative.StyleSheet.hairlineWidth,dot=space.md,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),cardText=slotText(recordCardSlot(slots)),dialogText=slotText(slots.dialog),nameText={...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},valueText=text4(type.size.verdict+space.xs,type.lineHeight.tight,color.text.primary,"bold");return reactNative.StyleSheet.create({page:{paddingHorizontal:space.sm},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,gap:space.md,...slotBox(recordCardSlot(slots),1)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm+space.xs/2},nameColumn:{flex:1,gap:space.xs/2},markerName:{...nameText,...cardText},sheetName:{...nameText,...dialogText},unit:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted,...cardText},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.md},latestValue:{...valueText,...cardText},sheetValue:{...valueText,...dialogText},latestValueDanger:{color:color.danger},latestDate:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},trajectory:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...cardText},chartWrap:{gap:space.sm},plot:{height:PLOT_HEIGHT,borderRadius:radius.sm,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:color.badgeBgPositive},point:{position:"absolute",width:dot,height:dot,borderRadius:dot/2,marginLeft:-dot/2,marginTop:-dot/2,backgroundColor:color.brand,borderWidth:2,borderColor:color.surface},pointDanger:{backgroundColor:color.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...text4(type.size.tiny,type.lineHeight.normal,color.text.placeholder),textAlign:"center",...cardText},singleHint:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center",...cardText},emptyBody:{alignItems:"center",justifyContent:"center",gap:space.sm,paddingVertical:space.xxl+space.xs},emptyText:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),textAlign:"center",...cardText},carousel:{height:CAROUSEL_HEIGHT},footer:{alignItems:"center",gap:space.sm,paddingTop:space.md},dots:{flexDirection:"row",gap:space.xs+space.xs/2},dot:{width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs-1,backgroundColor:color.borderHairlineGreen},dotActive:{width:space.lg+space.xs/2,backgroundColor:color.brand},counter:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,letterSpacing:type.letterSpacing.eyebrow/3,color:color.text.muted},backdrop:{flex:1,backgroundColor:SHEET_SCRIM},sheet:{backgroundColor:color.surfaceCream,borderTopLeftRadius:radius.xl-space.xs,borderTopRightRadius:radius.xl-space.xs,paddingHorizontal:space.lg+space.xs,paddingTop:space.sm,paddingBottom:space.xxl+space.xs,maxHeight:"80%",gap:space.md,...sheetSlotBox(slots.dialog)},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},sheetTitle:{flex:1,...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...dialogText},closeButton:{width:space.xxl+space.md,height:space.xxl+space.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...text4(type.size.verdict,type.lineHeight.tight,color.text.primary),...dialogText},sheetBody:{gap:space.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.md},reviewed:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs,backgroundColor:color.badgeBgPositive},reviewedText:{...text4(type.size.tiny,type.lineHeight.normal,color.success,"medium")},detailRow:{gap:space.xs/2},detailLabel:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted,"medium"),...dialogText},detailValue:{...text4(type.size.body,type.lineHeight.normal,color.text.primary),...dialogText},unverified:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...dialogText}})}var FACT_EDIT_COPY=/* @__PURE__ */Object.freeze({editA11y:label=>`Edit ${label}. Correct or remove this record detail.`,title:label=>`Edit ${label}`,helper:"Corrects your record. Your vet can still review it.",close:"Close",closeEditorA11y:"Close editor",save:"Save changes",saving:"Saving...",remove:"Remove this detail",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 factEditErrorMessage(error,mode){return isRecordsConsentRequired(error)?mode==="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.":isFactReviewerLocked(error)?mode==="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.":mode==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}var EMPTY_FACT_OVERLAY=/* @__PURE__ */Object.freeze({edits:/* @__PURE__ */Object.freeze({}),removed:/* @__PURE__ */Object.freeze([])});function applyFactOverlay(entities,overlay){if(Object.keys(overlay.edits).length===0&&overlay.removed.length===0)return entities;let out=[];for(let entity of entities){let key=entity.canonicalKey??null;if(key!==null&&overlay.removed.includes(key))continue;let edited=key!==null?overlay.edits[key]:void 0;out.push(edited===void 0?entity:/* @__PURE__ */Object.freeze({...entity,value:edited}))}/* @__PURE__ */
|
|
411
|
+
return Object.freeze(out)}function isFactEditable(entity){return typeof entity.canonicalKey=="string"&&entity.canonicalKey.length>0}function defaultFactKey(){return`records-fact-${Date.now().toString(36)}`}function useRecordFactEdit(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),[overlay,setOverlay]=react.useState(EMPTY_FACT_OVERLAY),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),scope=react.useMemo(()=>({}),[client,petRef,userRef]),[darkScope,setDarkScope]=react.useState(null),markDark=react.useCallback(()=>setDarkScope(scope),[scope]),[refused,setRefused]=react.useState(null);react.useEffect(()=>{if(userRef===null||client.readFeatures===void 0)return;let current=true;return client.readFeatures().then(value=>{current&&value.features.fact_edit===false&&setRefused(scope)},()=>{}),()=>{current=false}},[client,userRef,scope]);let available=userRef!==null&&darkScope!==scope&&refused!==scope,locked=react.useRef(false),mintRef=react.useRef(opts.newIdempotencyKey);mintRef.current=opts.newIdempotencyKey;let mint=react.useCallback(()=>(mintRef.current??defaultFactKey)(),[]),settle=react.useCallback((result,rollback,mode)=>{if(setBusy(false),!result.ok){if(rollback(),isDarkRouteError(result.error)){markDark();return}setError(factEditErrorMessage(result.error,mode))}},[markDark]),edit=react.useCallback(async(entity,value)=>{let key=entity.canonicalKey??"",next=value.trim();if(locked.current||key.length===0||next.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,edits:{...current.edits,[key]:next}}));let result=await client.editFact(petRef,{entityType:entity.category,canonicalKey:key,correctedFields:factCorrectionFor(entity.value,next),idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"edit"),result},[client,petRef,overlay,settle,mint]),remove=react.useCallback(async entity=>{let key=entity.canonicalKey??"";if(locked.current||key.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,removed:[...current.removed,key]}));let result=await client.removeFact(petRef,{entityType:entity.category,canonicalKey:key,idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"remove"),result},[client,petRef,overlay,settle,mint]),clearError=react.useCallback(()=>setError(null),[]);return react.useMemo(()=>({overlay:overlay,busy:busy,error:error,available:available,edit:edit,remove:remove,clearError:clearError}),[overlay,busy,error,available,edit,remove,clearError])}var VACCINE_CATEGORIES=/* @__PURE__ */Object.freeze(["vaccination","parasite_prevention"]),VACCINE_UNDATED_GROUP="Undated",VACCINE_STATUS_LABEL=/* @__PURE__ */Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),VACCINE_CHIP_TONE=/* @__PURE__ */Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function toMillis(value){if(!value)return null;let ms=Date.parse(value);return Number.isNaN(ms)?null:ms}function isLapsed(entity){let status=entity.status?.toLowerCase()??"";return/overdue|lapsed|expired/.test(status)}function vaccineTone(entity){return entity.category==="parasite_prevention"?"prevention":toMillis(entity.observedAt)===null?"noDate":isLapsed(entity)?"overdue":"given"}function yearOf(at){let ms=toMillis(at);return ms===null?VACCINE_UNDATED_GROUP:String(new Date(ms).getUTCFullYear())}function buildRow(entity){let tone=vaccineTone(entity),parts=[entity.value!==null&&entity.value.length>0?entity.value:null,entity.observedAt!==null?formatRecordsDate(entity.observedAt):null].filter(part=>part!==null&&part.length>0);return{key:entity.key,name:entity.label,detail:parts.length>0?parts.join(" · "):null,statusLabel:VACCINE_STATUS_LABEL[tone],tone:tone,entity:entity}}function selectVaccineGroups(entities){let byYear=/* @__PURE__ */new Map;for(let entity of entities){if(!VACCINE_CATEGORIES.includes(entity.category))continue;let year=yearOf(entity.observedAt),bucket=byYear.get(year),item={row:buildRow(entity),at:entity.observedAt};bucket===void 0?byYear.set(year,[item]):bucket.push(item)}let years=[...byYear.keys()].sort((a,b)=>a===VACCINE_UNDATED_GROUP?1:b===VACCINE_UNDATED_GROUP?-1:Number(b)-Number(a));/* @__PURE__ */
|
|
406
412
|
return Object.freeze(years.map(year=>{let items=byYear.get(year)??[],ordered=year===VACCINE_UNDATED_GROUP?items:[...items].sort((a,b)=>(toMillis(b.at)??0)-(toMillis(a.at)??0));/* @__PURE__ */
|
|
407
413
|
return Object.freeze({year:year,items:/* @__PURE__ */Object.freeze(ordered.map(i=>i.row))})}))}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});function FactEditAffordance({entity:entity,factEdit:factEdit,children:children}){let styles=useStyles7(),[open,setOpen]=react.useState(false),label=entity.label.trim()||FACT_EDIT_COPY.detail;/* @__PURE__ */
|
|
408
414
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.row,children:[
|
|
@@ -424,7 +430,7 @@ return jsxRuntime.jsx(reactNative.Modal,{transparent:true,visible:true,animation
|
|
|
424
430
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?FACT_EDIT_COPY.removing:FACT_EDIT_COPY.removeConfirm,kind:"danger",busy:busy,onPress:submitRemove,style:styles.confirmButton,testID:"fact-edit-remove-confirm"}),
|
|
425
431
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:FACT_EDIT_COPY.keep,kind:"outline",disabled:busy,onPress:()=>setConfirmingRemove(false),style:styles.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actions,children:[
|
|
426
432
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?FACT_EDIT_COPY.saving:FACT_EDIT_COPY.save,busy:busy,disabled:!changed,onPress:submitEdit,testID:"fact-edit-save"}),
|
|
427
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.remove,disabled:busy,onPress:()=>{setLocalError(null),setConfirmingRemove(true)},style:[styles.removeButton,busy?styles.removeDisabled:null],testID:"fact-edit-remove",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.removeText,children:FACT_EDIT_COPY.remove})})]})]})]})})}function useStyles7(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles9(theme),[theme])}function makeStyles9(theme){let{color:color,space:space,radius:radius,type:type}=theme,touch=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,
|
|
433
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.remove,disabled:busy,onPress:()=>{setLocalError(null),setConfirmingRemove(true)},style:[styles.removeButton,busy?styles.removeDisabled:null],testID:"fact-edit-remove",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.removeText,children:FACT_EDIT_COPY.remove})})]})]})]})})}function useStyles7(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles9(theme),[theme])}function makeStyles9(theme){let{color:color,space:space,radius:radius,type:type}=theme,touch=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:space.sm},main:{flex:1},editButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},pencil:{width:space.md+space.xs/2,height:space.xs/2,backgroundColor:color.brandInk,borderRadius:radius.pill,transform:[{rotate:"-45deg"}]},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:SHEET_SCRIM},sheet:{backgroundColor:color.surface,borderTopLeftRadius:radius.xl-1,borderTopRightRadius:radius.xl-1,paddingHorizontal:space.lg+space.xs+space.xs/2,paddingTop:space.md,paddingBottom:radius.xl,maxHeight:"88%",gap:space.md,...sheetSlotBox(theme.slots.dialog)},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm},headerText:{flex:1,gap:space.xs},title:{...text4(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...slotText(theme.slots.dialog)},helper:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...slotText(theme.slots.dialog)},helperError:{color:errorColor},closeButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},closeGlyph:{...text4(type.size.verdict,type.lineHeight.tight,color.text.primary),...slotText(theme.slots.dialog)},actions:{gap:space.sm},removeButton:{minHeight:touch,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...text4(type.size.bodyTight,type.lineHeight.snug,color.danger,"bold")},confirmBlock:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.badgeBgCritical},confirmText:text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary),confirmRow:{flexDirection:"row",gap:space.sm},confirmButton:{flex:1}})}function RecordSections({record:record,depth:depth,petName:petName,showLabs:showLabs=true,onNavigate:onNavigate,onAsk:onAsk,factEdit:factEdit,nowMs:nowMs}){let styles=useScreenStyles(),local=useLocalStyles4(),now=nowMs??Date.now(),entities=react.useMemo(()=>factEdit?applyFactOverlay(record.entities,factEdit.overlay):record.entities,[record.entities,factEdit]),byType=react.useMemo(()=>{let order=[],groups=/* @__PURE__ */new Map;for(let entity of entities){let category=entity.category.trim();if(category.length===0||VACCINE_CATEGORIES.includes(category))continue;let bucket=groups.get(category);bucket===void 0?(order.push(category),groups.set(category,[entity])):bucket.push(entity)}return{order:orderEntityTypes(order),groups:groups}},[entities]),vaccineGroups=react.useMemo(()=>selectVaccineGroups(entities),[entities]),documents=react.useMemo(()=>documentsNewestFirst(record.documents),[record.documents]),ask=(build,label,testID)=>onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{let built=build();onAsk(built.prompt,built.entityRef)},accessibilityRole:"button",accessibilityLabel:label,style:[styles.pill,styles.pillAsk,local.ask],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.pillAskLabel,children:label})}):null,editable=factEdit!==void 0&&factEdit.available;/* @__PURE__ */
|
|
428
434
|
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
429
435
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.sections,children:[depth&&depth.conflicts.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-conflicts",children:[
|
|
430
436
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.needsAttention,count:depth.conflicts.length}),[...depth.conflicts].sort((a,b)=>conflictSeverityMeta(a.severity).rank-conflictSeverityMeta(b.severity).rank).map(conflict=>{let meta=conflictSeverityMeta(conflict.severity),scope=humanize(conflict.field??conflict.entityType);/* @__PURE__ */
|
|
@@ -434,14 +440,14 @@ return jsxRuntime.jsxs(reactNative.View,{style:[local.conflictCard,{borderColor:
|
|
|
434
440
|
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:scope,tone:meta.tone})]}),
|
|
435
441
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:RECORD_SCREEN_COPY.conflictSub}),conflict.candidates.map((candidate,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.candidate,children:[
|
|
436
442
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:candidate.value}),
|
|
437
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowMuted,children:[candidate.docId?record.documents[candidate.docId]
|
|
443
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowMuted,children:[candidate.docId?documentTitle(record.documents[candidate.docId]??{title:null}):RECORD_SCREEN_COPY.uploadedDocument,candidate.collectedAt?formatRecordsDate(candidate.collectedAt):null].filter(Boolean).join(" · ")})]},index)),ask(()=>buildConflictAskPrompt(petName,{scopeLabel:scope,severity:conflict.severity,candidates:conflict.candidates.map(c=>({value:c.value,clinicName:c.docId?record.documents[c.docId]?.title??null:null}))},conflict.conflictId),RECORD_SCREEN_COPY.askConflict,`records-ask-conflict-${conflict.conflictId}`)]},conflict.conflictId)})]}):null,depth?.completeness?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-completeness",children:[
|
|
438
444
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.whatsOnFile}),
|
|
439
445
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.card,children:[
|
|
440
446
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.coverageRow,children:[[RECORD_SCREEN_COPY.coverage.labs,depth.completeness.hasLabHistory],[RECORD_SCREEN_COPY.coverage.vaccines,depth.completeness.hasVaccinationHistory],[RECORD_SCREEN_COPY.coverage.weight,depth.completeness.hasWeightHistory],[RECORD_SCREEN_COPY.coverage.vitals,depth.completeness.hasVitalsHistory],[RECORD_SCREEN_COPY.coverage.exams,depth.completeness.hasPhysicalExamHistory],[RECORD_SCREEN_COPY.coverage.procedures,depth.completeness.hasProcedureHistory],[RECORD_SCREEN_COPY.coverage.genetics,depth.completeness.hasGeneticHistory],[RECORD_SCREEN_COPY.coverage.parasite,depth.completeness.hasParasitePreventionHistory],[RECORD_SCREEN_COPY.coverage.reproductive,depth.completeness.hasReproductiveHistory]].map(([label,present])=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.coveragePill,present?[styles.chipTones.positive.bg,local.coverageOnFile]:[styles.chipTones.neutral.bg,local.coverageRest]],accessible:true,accessibilityRole:"text",accessibilityLabel:`${label}: ${present?RECORD_SCREEN_COPY.onFile:RECORD_SCREEN_COPY.noneOnFile}`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[local.coverageText,present?styles.chipTones.positive.fg:[{color:styles.rowMuted.color},local.coverageRestText]],children:label})},label))}),
|
|
441
447
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.metaRow,children:[
|
|
442
448
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.metaText,children:RECORD_SCREEN_COPY.documentsOnFile(depth.completeness.documentsIngested)}),depth.completeness.documentsInReview>0?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:RECORD_SCREEN_COPY.inReviewChip(depth.completeness.documentsInReview),tone:"warning"}):null,heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:RECORD_SCREEN_COPY.beingVerifiedA11y(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),children:/* @__PURE__ */jsxRuntime.jsx(Chip,{label:RECORD_SCREEN_COPY.beingVerified(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),depth.completeness.earliestRecordAt||depth.completeness.latestRecordAt?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.metaRow,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.metaText,children:RECORD_SCREEN_COPY.dateRange(depth.completeness.earliestRecordAt,depth.completeness.latestRecordAt)})}):null,Object.entries(depth.completeness.entitiesPendingReview).filter(([,count])=>count>0).length>0?/* @__PURE__ */jsxRuntime.jsxs(Text,{style:local.pendingText,children:[RECORD_SCREEN_COPY.pendingReview,Object.entries(depth.completeness.entitiesPendingReview).filter(([,count])=>count>0).map(([type,count])=>`${entityTypeLabel(type)} (${count})`).join(", ")]}):null]})]}):null,documents.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-documents",children:[
|
|
443
449
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.documents,count:documents.length}),
|
|
444
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:documents.map((doc,index)=>{let title=doc
|
|
450
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:documents.map((doc,index)=>{let title=documentTitle(doc),meta=RECORD_SCREEN_COPY.documentMeta(doc.pageCount,doc.receivedAt),body=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
445
451
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
446
452
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:title}),meta?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:meta}):null]}),onNavigate?/* @__PURE__ */jsxRuntime.jsx(Chevron,{}):null]});return onNavigate?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onNavigate({name:"contributions",docId:doc.docId}),accessibilityRole:"button",accessibilityLabel:RECORD_SCREEN_COPY.documentRowA11y(title),style:[styles.row,index>0?styles.rowDivider:null],testID:`records-document-row-${doc.docId}`,children:body},doc.docId):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:body},doc.docId)})})]}):null,record.identity.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-identity",children:[
|
|
447
453
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.identity}),
|
|
@@ -485,27 +491,27 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDiv
|
|
|
485
491
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:depth.encounters.map((encounter,index)=>{let detail=[encounter.date?formatRecordsDate(encounter.date):null,encounter.clinicName,encounter.veterinarian].filter(p=>p&&p!=="-").join(" · ");/* @__PURE__ */
|
|
486
492
|
return jsxRuntime.jsx(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
487
493
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:encounter.type?humanize(encounter.type):DEPTH_COPY.visit}),detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:detail}):null]})},encounter.encounterId)})})]}):null]}),
|
|
488
|
-
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record.disclaimer})]})}function heldCount(heldTotal,pending){return heldTotal>0?heldTotal:Object.values(pending).reduce((sum,count)=>sum+count,0)}function useLocalStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({sections:{gap:space.lg+space.xs},vaccineGroup:{gap:space.xs+1,marginBottom:space.sm},vaccineYear:{...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:type.size.micro+space.xs,color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:space.xs+2},ask:{marginTop:space.lg},conflictCard:{borderRadius:radius.md,borderWidth:1,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(recordCardSlot(theme.slots),1)},conflictHead:{flexDirection:"row",alignItems:"center",gap:space.sm},conflictTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...slotText(recordCardSlot(theme.slots))},candidate:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,paddingTop:space.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:space.sm,paddingVertical:space.md},coveragePill:{borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs+1},coverageText:{...face(theme,"medium"),fontSize:type.size.caption,lineHeight:type.size.caption+space.xs-1},coverageRest:slotBox(theme.slots.chip),coverageRestText:slotText(theme.slots.chip),coverageOnFile:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},metaRow:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingBottom:space.md},metaText:{flex:1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},pendingText:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,paddingBottom:space.md},identityLabel:{...face(theme,"medium"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},cardTitle:{paddingTop:space.sm},noteSection:{paddingVertical:space.md,gap:space.xs},noteLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,color:color.text.secondary,textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},noteBody:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.primary},noteBodyMuted:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.muted,fontStyle:"italic"}})}var CALL_CLINIC_COPY=/* @__PURE__ */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:phone=>`Call the clinic at ${phone}`});function presentConsentText(consentText){return typeof consentText=="string"&&consentText.trim().length>0?consentText:null}function isConsentTextMissing(consentVersion,consentText){return typeof consentVersion=="string"&&consentVersion.length>0&&presentConsentText(consentText)===null}var CONSENT_TEXT_MISSING_WARNING="[everfur] consentVersion was passed without consentText, so the records consent gate shows no consent text above Allow. Pass the consent text your member agrees to as consentText, next to its consentVersion.",warned=false;function warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment3()===!0}catch{development=false}if(!development)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(CONSENT_TEXT_MISSING_WARNING)}catch{}}function useConsentTextWarning(consentVersion,consentText,isDevelopment3){react.useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=reactNative.useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable2(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=react.useState(false);return react.useEffect(()=>{let mounted=true,query=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(reactNative.AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=reactNative.PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(reactNative.PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=reactNative.Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(reactNative.Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return react.useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=reactNative.Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=react.useState(false);return react.useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=reactNative.AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(reactNative.AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=reactNative.AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(reactNative.AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var warnedRemoteFonts=/* @__PURE__ */new Set;function remoteFontFields(theme){let fields=[];return theme.type.fontSources.length>0&&fields.push("fontSources"),Object.values(theme.type.fontUrls).some(url=>typeof url=="string"&&url.length>0)&&fields.push("fontUrls"),fields}var REMOTE_FONT_LABEL=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function warnRemoteFonts(theme){if(!isDevelopment())return;let fresh=remoteFontFields(theme).filter(field=>!warnedRemoteFonts.has(field));if(fresh.length===0)return;for(let field of fresh)warnedRemoteFonts.add(field);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme sets ${fresh.map(field=>REMOTE_FONT_LABEL[field]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function useRnResolvedTheme(theme){react.useEffect(()=>{try{warnRemoteFonts(theme)}catch{}},[theme])}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,useResolvedTheme:useRnResolvedTheme,isDevelopment:isDevelopment});var isDevelopment2=()=>rnThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment2)}var MAX_MB=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Upload ${petNameOr(petName)}’s records`,screenTitle:"Upload a document",subtitle:petName=>`Already have lab results, a vet summary, or test reports? Add them here and we’ll read them and pull out ${petNameOr(petName)}’s health markers.`,noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${MAX_MB} MB each. You can pick several at once. We’ll read them and add the results to your records.`,chooseFiles:"Choose a file",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total}…`,cancel:"Cancel",cancelA11y:"Cancel these uploads",received:done=>`${done===1?"Record received.":`${done} records received.`} We’ll read and review ${done===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,retryFailed:failed=>`Retry ${failed} that didn’t upload`,haveMore:"Have more?",addMore:"Upload another document",addMoreA11y:"Upload another document",done:"Done",doneA11y:"Done, view records",errors:/* @__PURE__ */Object.freeze({start:"We couldn’t start that upload. Check your connection and try again.",startPlain:"We couldn’t start that upload. Please try again.",upload:"We couldn’t upload that record. Check your connection and try again."})}),UPLOAD_PHOTO_COPY=/* @__PURE__ */Object.freeze({note:"A PDF, or a photo of a paper record. Add them all; we sort them by date.",takePhoto:"Take a photo",takePhotoMeta:"of a paper record",choosePhotos:"Choose from photos",chooseFileMeta:"PDF",haveMoreLead:"PDFs and photos of paper records both work. Add them all; we sort them by date.",unreadable:"We can’t read this kind of file. Upload a PDF or a photo of the record."});function uploadActionA11y(label,meta){return`${label} ${meta}`}var MAX_MB2=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_QUEUE_COPY=/* @__PURE__ */Object.freeze({queued:"Queued",verifying:"Verifying…",done:"Done",failed:"Failed",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total} records`,uploaded:(done,total)=>`${done} of ${total} records uploaded`});function uploadItemStatusLabel(item){let pct2=Math.round(item.progress*100);switch(item.status){case"done":return UPLOAD_QUEUE_COPY.done;case"failed":return UPLOAD_QUEUE_COPY.failed;case"uploading":return item.progress>=1?UPLOAD_QUEUE_COPY.verifying:`${pct2}%`;case"queued":return UPLOAD_QUEUE_COPY.queued;default:return null}}function skippedFilesMessage(skipped,photosLive=false){if(skipped.length===0)return null;let nameList=entries=>{let names=entries.map(e=>e.name??"");return names.length<=3?names.join(", "):`${names.slice(0,3).join(", ")} and ${names.length-3} more`},tooLarge=skipped.filter(s=>s.reason==="too_large"),unsupported=skipped.filter(s=>s.reason==="unsupported");if(photosLive){let lines=[];return unsupported.length>0&&lines.push(UPLOAD_PHOTO_COPY.unreadable),tooLarge.length>0&&lines.push(`Didn’t upload: ${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB.`),lines.join(" ")}let parts=[];return unsupported.length>0&&parts.push(`${nameList(unsupported)} ${unsupported.length>1?"are not PDFs":"is not a PDF"}`),tooLarge.length>0&&parts.push(`${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB`),`Didn’t upload: ${parts.join("; ")}. We can only read PDFs up to ${MAX_MB2} MB right now.`}function skippedOf(queue){let out=[];for(let item of queue)item.status==="skipped"&&item.skipReason!==null&&out.push({name:item.name,reason:item.skipReason});return out}var RECORDS_RECOVERY_COPY=/* @__PURE__ */Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep it",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We’ll 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 useRecordsRecovery({request:request,onRecovered:onRecovered,canUpload:canUpload=false},controller){let[email2,setEmailValue]=react.useState(""),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),[confirmingRevoke,setConfirmingRevoke]=react.useState(false),[settled,setSettled]=react.useState(null),locked=react.useRef(false),active=react.useRef(false),generation=react.useRef(0);react.useEffect(()=>(active.current=true,()=>{active.current=false,generation.current+=1}),[controller]);let current=settled!==null&&settled.before===request.updatedAt?{...settled.value,canRetrySend:request.canRetrySend===true&&settled.value.canRetrySend===true,canUpdateClinicEmail:request.canUpdateClinicEmail===true&&settled.value.canUpdateClinicEmail===true,canRevoke:request.canRevoke===true&&settled.value.canRevoke===true,canConvertToUpload:request.canConvertToUpload===true&&settled.value.canConvertToUpload===true}:request,trimmed=email2.trim(),validEmail=trimmed.length<=320&&!Array.from(trimmed).some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed),hasEmailEdit=current.canUpdateClinicEmail===true&&trimmed.length>0,canRetry=current.canRetrySend===true&&!busy&&!hasEmailEdit,canUpdateEmail=current.canUpdateClinicEmail===true&&!busy&&validEmail,canConvert=current.canConvertToUpload===true&&canUpload,run=async kind=>{let allowed={retry:canRetry,email:canUpdateEmail,revoke:current.canRevoke===true&&confirmingRevoke,convert:canConvert};if(locked.current||!active.current||!allowed[kind])return;locked.current=true,setBusy(true),setError(null);let revision=generation.current,live=()=>active.current&&revision===generation.current;try{let result=kind==="retry"?await controller.retryRequest(request.id):kind==="email"?await controller.updateClinicEmail(request.id,trimmed):kind==="revoke"?await controller.revokeRequest(request.id):await controller.convertToUpload(request.id);if(!live())return;if(!result.ok){setError(result.error);return}if(result.value.id!==request.id||result.value.petRef!==request.petRef){setError(makeEverfurError("internalError"));return}setSettled({before:request.updatedAt,value:result.value}),setEmailValue(""),setConfirmingRevoke(!1),onRecovered()}catch{live()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,live()&&setBusy(false)}};return{request:current,email:email2,busy:busy,error:error,canRetry:canRetry,canUpdateEmail:canUpdateEmail,canConvert:canConvert,hasEmailEdit:hasEmailEdit,confirmingRevoke:confirmingRevoke&¤t.canRevoke===true,emailInvalid:trimmed.length>0&&!validEmail,setEmail(value){locked.current||(setEmailValue(value),setError(null))},retry:()=>run("retry"),updateEmail:()=>run("email"),revoke:()=>run("revoke"),convert:()=>run("convert"),askRevoke(){!locked.current&¤t.canRevoke===true&&setConfirmingRevoke(true)},keepRequest(){locked.current||setConfirmingRevoke(false)}}}var RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],OWNER_RAIL_STAGES=["requested","awaiting_upload","records_received","processing","ready"],CONVERTED_RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],REQUEST_TIMELINE_TITLES=/* @__PURE__ */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"}),CLINIC_RAIL_TITLES=/* @__PURE__ */Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records…"}),CLINIC_RAIL_DETAILS=/* @__PURE__ */Object.freeze({notified:email2=>`A secure request went to ${email2}.`,received:"Everfur reads every page: dates, vaccines, labs and prescriptions.",added:petName=>`Added to ${petName}’s records`}),DETAILS=/* @__PURE__ */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’t read this one automatically",manualReview:"Checking these by hand so nothing’s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),TERMINAL_DETAILS=/* @__PURE__ */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"}),WIRE_FROM_STATUS=/* @__PURE__ */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 wireStatusOf(request){return request.wireStatus??WIRE_FROM_STATUS[request.status]??"sent"}function reminderProgressLabel(status,reminderCount){return status!=="awaiting_response"||reminderCount<=0?null:`${reminderCount} ${reminderCount===1?"reminder":"reminders"} sent`}function reachedRailIndex(status){switch(status){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}}function deliveryDetail(request){switch(request.dispatchStatus){case"sent":return DETAILS.delivered;case"preparing":case"queued":case"sending":return DETAILS.emailing;case"failed":return DETAILS.bounced;default:return null}}function awaitingDetail(request,status){return reminderProgressLabel(status,request.reminderCount??0)??DETAILS.waiting}function isOwnerSourcedRequest(request){return request.source==="owner_provided"||!!request.convertedToUploadAt}function railDetail(key,request,status){let isOwnerSourced=isOwnerSourcedRequest(request);switch(key){case"sent_to_clinic":return deliveryDetail(request);case"awaiting_clinic":return awaitingDetail(request,status);case"awaiting_upload":return DETAILS.upload;case"records_received":return isOwnerSourced?DETAILS.ownerAdded:DETAILS.clinicSent;case"processing":return DETAILS.preparing;case"ready":return DETAILS.ready;default:return null}}function tookReviewBranch(request,status){return!!request.reviewStartedAt||status==="parsing_failed"||status==="review_email_failed"}function expandProcessingPhase(event,request,status){if(event.key!=="processing"||!tookReviewBranch(request,status))return[event];let atParsingFailed=status==="parsing_failed",published=status==="published",parsingFailedState=published?"done":atParsingFailed?"current":"done",reviewState=published?"done":atParsingFailed?"upcoming":"current";return[{key:"parsing_failed",title:REQUEST_TIMELINE_TITLES.parsing_failed,detail:DETAILS.parsingFailed,at:null,state:parsingFailedState},{key:"manual_review",title:REQUEST_TIMELINE_TITLES.manual_review,detail:DETAILS.manualReview,at:request.reviewStartedAt??null,state:reviewState}]}function convertedReachedIndex(status){switch(status){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}}function convertedClinicSwitchEvent(request){return{key:"awaiting_clinic",title:DETAILS.switchedTitle,detail:DETAILS.switched,at:request.convertedToUploadAt??null,state:"done"}}function ownerReachedIndex(status){switch(status){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}}function railTimestamp(key,request,status){switch(key){case"requested":return request.createdAt||null;case"awaiting_clinic":return request.lastReminderAt??null;case"processing":return request.parsingStartedAt??request.reviewStartedAt??null;case"ready":return status==="published"&&request.updatedAt||null;default:return null}}function railEvent(key,request,status,state){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:railDetail(key,request,status),at:railTimestamp(key,request,status),state:state}}function terminalEvent(key,request){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:TERMINAL_DETAILS[key]??null,at:request.updatedAt||null,state:"failed"}}function walkRail(stages,reached,request,status,replace){return stages.map((key,idx)=>{let replaced=replace?.(key)??null;if(replaced!==null)return replaced;let state=status==="published"||idx<reached?"done":idx===reached?"current":"upcoming";return railEvent(key,request,status,state)}).flatMap(event=>expandProcessingPhase(event,request,status))}function buildRequestTimeline(request,options={}){return inArtifactWords(buildRailEvents(request),request,options.petName??null,options.sandbox===true)}function inArtifactWords(events,request,petName,sandbox){let clinicRail=request.source!=="owner_provided"&&!events.some(event=>event.key==="delivery_failed"),email2=request.clinicEmail?.trim()??"";return events.map(event=>{if(event.title!==REQUEST_TIMELINE_TITLES[event.key])return event;if(event.key==="ready")return{...event,title:CLINIC_RAIL_DETAILS.added(petNameOr(petName))};if(!clinicRail)return event;if(sandbox&&event.key==="sent_to_clinic")return{...event,title:RECORDS_SANDBOX_COPY.clinicNotContacted,detail:email2.length>0?RECORDS_SANDBOX_COPY.notEmailed(email2):null};let title=CLINIC_RAIL_TITLES[event.key]??event.title;return event.key==="sent_to_clinic"&&request.dispatchStatus==="sent"&&email2.length>0?{...event,title:title,detail:CLINIC_RAIL_DETAILS.notified(email2)}:event.key==="records_received"&&!isOwnerSourcedRequest(request)?{...event,title:title,detail:CLINIC_RAIL_DETAILS.received}:{...event,title:title}})}function buildRailEvents(request){let status=wireStatusOf(request),done=key=>railEvent(key,request,status,"done");if(status==="revoked")return[done("requested"),terminalEvent("revoked",request)];if(request.convertedToUploadAt)return status==="failed"?[done("requested"),done("sent_to_clinic"),convertedClinicSwitchEvent(request),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)]:walkRail(CONVERTED_RAIL_STAGES,convertedReachedIndex(status),request,status,key=>key==="awaiting_clinic"?convertedClinicSwitchEvent(request):null);if(request.source==="owner_provided"){if(status==="failed"||status==="clinic_declined")return[done("requested"),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)];let reached2=ownerReachedIndex(status);return walkRail(OWNER_RAIL_STAGES,reached2<0?1:reached2,request,status)}if(status==="clinic_declined")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_declined",request)];if(status==="clinic_responded_no_records")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_no_records",request)];if(status==="failed"){let code=request.failureCode??null;return code==="no_response"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("no_response",request)]:code==="hard_bounce"||code==="dispatch_failed"?[done("requested"),terminalEvent("delivery_failed",request)]:code==="parse_timeout"||code==="parse_error"||request.dispatchStatus==="sent"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),done("records_received"),terminalEvent("processing_failed",request)]:[done("requested"),terminalEvent("delivery_failed",request)]}let reached=reachedRailIndex(status);return walkRail(RAIL_STAGES,reached<0?1:reached,request,status)}var A11Y_STATE=/* @__PURE__ */Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),DOT_SIZE=28,NOW="Now",DOT_CORE_SIZE=10;function RequestTimeline({request:request,petName:petName}){let styles=useStyles8(),sandbox=useRecordsSandboxTenant(),events=buildRequestTimeline(request,{petName:petName??null,sandbox:sandbox});/* @__PURE__ */
|
|
489
|
-
return jsxRuntime.jsx(reactNative.View,{style:styles.container,accessibilityRole:"summary",children:events.map((event,idx)=>/* @__PURE__ */jsxRuntime.jsx(TimelineRow,{event:event,isLast:idx===events.length-1,styles:styles},event.key))})}function TimelineRow({event:event,isLast:isLast,styles:styles}){let
|
|
494
|
+
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record.disclaimer})]})}function heldCount(heldTotal,pending){return heldTotal>0?heldTotal:Object.values(pending).reduce((sum,count)=>sum+count,0)}function useLocalStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({sections:{gap:space.lg+space.xs},vaccineGroup:{gap:space.xs+1,marginBottom:space.sm},vaccineYear:{...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:type.size.micro+space.xs,color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:space.xs+2},ask:{marginTop:space.lg},conflictCard:{borderRadius:radius.md,borderWidth:1,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(recordCardSlot(theme.slots),1)},conflictHead:{flexDirection:"row",alignItems:"center",gap:space.sm},conflictTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...slotText(recordCardSlot(theme.slots))},candidate:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,paddingTop:space.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:space.sm,paddingVertical:space.md},coveragePill:{borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs+1},coverageText:{...face(theme,"medium"),fontSize:type.size.caption,lineHeight:type.size.caption+space.xs-1},coverageRest:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},coverageRestText:{},coverageOnFile:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},metaRow:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingBottom:space.md},metaText:{flex:1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},pendingText:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,paddingBottom:space.md},identityLabel:{...face(theme,"medium"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},cardTitle:{paddingTop:space.sm},noteSection:{paddingVertical:space.md,gap:space.xs},noteLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,color:color.text.secondary,textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},noteBody:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.primary},noteBodyMuted:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.muted,fontStyle:"italic"}})}var CALL_CLINIC_COPY=/* @__PURE__ */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:phone=>`Call the clinic at ${phone}`});function presentConsentText(consentText){return typeof consentText=="string"&&consentText.trim().length>0?consentText:null}function isConsentTextMissing(consentVersion,consentText){return typeof consentVersion=="string"&&consentVersion.length>0&&presentConsentText(consentText)===null}var CONSENT_TEXT_MISSING_WARNING="[everfur] consentVersion was passed without consentText, so the records consent gate shows no consent text above Allow. Pass the consent text your member agrees to as consentText, next to its consentVersion.",warned=false;function warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment3()===!0}catch{development=false}if(!development)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(CONSENT_TEXT_MISSING_WARNING)}catch{}}function useConsentTextWarning(consentVersion,consentText,isDevelopment3){react.useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=reactNative.useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable2(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=react.useState(false);return react.useEffect(()=>{let mounted=true,query=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(reactNative.AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=reactNative.PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(reactNative.PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=reactNative.Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(reactNative.Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return react.useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=reactNative.Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=react.useState(false);return react.useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=reactNative.AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(reactNative.AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=reactNative.AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(reactNative.AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var warnedRemoteFonts=/* @__PURE__ */new Set;function remoteFontFields(theme){let fields=[];return theme.type.fontSources.length>0&&fields.push("fontSources"),Object.values(theme.type.fontUrls).some(url=>typeof url=="string"&&url.length>0)&&fields.push("fontUrls"),fields}var REMOTE_FONT_LABEL=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function warnRemoteFonts(theme){if(!isDevelopment())return;let fresh=remoteFontFields(theme).filter(field=>!warnedRemoteFonts.has(field));if(fresh.length===0)return;for(let field of fresh)warnedRemoteFonts.add(field);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme sets ${fresh.map(field=>REMOTE_FONT_LABEL[field]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function useRnResolvedTheme(theme){react.useEffect(()=>{try{warnRemoteFonts(theme)}catch{}},[theme])}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,useResolvedTheme:useRnResolvedTheme,isDevelopment:isDevelopment});var isDevelopment2=()=>rnThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment2)}var MAX_MB=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Upload ${petNameOr(petName)}’s records`,screenTitle:"Upload a document",subtitle:petName=>`Already have lab results, a vet summary, or test reports? Add them here and we’ll read them and pull out ${petNameOr(petName)}’s health markers.`,noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${MAX_MB} MB each. You can pick several at once. We’ll read them and add the results to your records.`,chooseFiles:"Choose a file",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total}…`,cancel:"Cancel",cancelA11y:"Cancel these uploads",received:done=>`${done===1?"Record received.":`${done} records received.`} We’ll read and review ${done===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,retryFailed:failed=>`Retry ${failed} that didn’t upload`,haveMore:"Have more?",addMore:"Upload another document",addMoreA11y:"Upload another document",done:"Done",doneA11y:"Done, view records",errors:/* @__PURE__ */Object.freeze({start:"We couldn’t start that upload. Check your connection and try again.",startPlain:"We couldn’t start that upload. Please try again.",upload:"We couldn’t upload that record. Check your connection and try again."})}),UPLOAD_PHOTO_COPY=/* @__PURE__ */Object.freeze({note:"A PDF, or a photo of a paper record. Add them all; we sort them by date.",takePhoto:"Take a photo",takePhotoMeta:"of a paper record",choosePhotos:"Choose from photos",chooseFileMeta:"PDF",haveMoreLead:"PDFs and photos of paper records both work. Add them all; we sort them by date.",unreadable:"We can’t read this kind of file. Upload a PDF or a photo of the record."});function uploadActionA11y(label,meta){return`${label} ${meta}`}var MAX_MB2=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_QUEUE_COPY=/* @__PURE__ */Object.freeze({queued:"Queued",verifying:"Verifying…",done:"Done",failed:"Failed",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total} records`,uploaded:(done,total)=>`${done} of ${total} records uploaded`});function uploadItemStatusLabel(item){let pct2=Math.round(item.progress*100);switch(item.status){case"done":return UPLOAD_QUEUE_COPY.done;case"failed":return UPLOAD_QUEUE_COPY.failed;case"uploading":return item.progress>=1?UPLOAD_QUEUE_COPY.verifying:`${pct2}%`;case"queued":return UPLOAD_QUEUE_COPY.queued;default:return null}}function skippedFilesMessage(skipped,photosLive=false){if(skipped.length===0)return null;let nameList=entries=>{let names=entries.map(e=>e.name??"");return names.length<=3?names.join(", "):`${names.slice(0,3).join(", ")} and ${names.length-3} more`},tooLarge=skipped.filter(s=>s.reason==="too_large"),unsupported=skipped.filter(s=>s.reason==="unsupported");if(photosLive){let lines=[];return unsupported.length>0&&lines.push(UPLOAD_PHOTO_COPY.unreadable),tooLarge.length>0&&lines.push(`Didn’t upload: ${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB.`),lines.join(" ")}let parts=[];return unsupported.length>0&&parts.push(`${nameList(unsupported)} ${unsupported.length>1?"are not PDFs":"is not a PDF"}`),tooLarge.length>0&&parts.push(`${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB`),`Didn’t upload: ${parts.join("; ")}. We can only read PDFs up to ${MAX_MB2} MB right now.`}function skippedOf(queue){let out=[];for(let item of queue)item.status==="skipped"&&item.skipReason!==null&&out.push({name:item.name,reason:item.skipReason});return out}var RECORDS_RECOVERY_COPY=/* @__PURE__ */Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep it",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We’ll 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 useRecordsRecovery({request:request,onRecovered:onRecovered,canUpload:canUpload=false},controller){let[email2,setEmailValue]=react.useState(""),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),[confirmingRevoke,setConfirmingRevoke]=react.useState(false),[settled,setSettled]=react.useState(null),locked=react.useRef(false),active=react.useRef(false),generation=react.useRef(0);react.useEffect(()=>(active.current=true,()=>{active.current=false,generation.current+=1}),[controller]);let current=settled!==null&&settled.before===request.updatedAt?{...settled.value,canRetrySend:request.canRetrySend===true&&settled.value.canRetrySend===true,canUpdateClinicEmail:request.canUpdateClinicEmail===true&&settled.value.canUpdateClinicEmail===true,canRevoke:request.canRevoke===true&&settled.value.canRevoke===true,canConvertToUpload:request.canConvertToUpload===true&&settled.value.canConvertToUpload===true}:request,trimmed=email2.trim(),validEmail=trimmed.length<=320&&!Array.from(trimmed).some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed),hasEmailEdit=current.canUpdateClinicEmail===true&&trimmed.length>0,canRetry=current.canRetrySend===true&&!busy&&!hasEmailEdit,canUpdateEmail=current.canUpdateClinicEmail===true&&!busy&&validEmail,canConvert=current.canConvertToUpload===true&&canUpload,run=async kind=>{let allowed={retry:canRetry,email:canUpdateEmail,revoke:current.canRevoke===true&&confirmingRevoke,convert:canConvert};if(locked.current||!active.current||!allowed[kind])return;locked.current=true,setBusy(true),setError(null);let revision=generation.current,live=()=>active.current&&revision===generation.current;try{let result=kind==="retry"?await controller.retryRequest(request.id):kind==="email"?await controller.updateClinicEmail(request.id,trimmed):kind==="revoke"?await controller.revokeRequest(request.id):await controller.convertToUpload(request.id);if(!live())return;if(!result.ok){setError(result.error);return}if(result.value.id!==request.id||result.value.petRef!==request.petRef){setError(makeEverfurError("internalError"));return}setSettled({before:request.updatedAt,value:result.value}),setEmailValue(""),setConfirmingRevoke(!1),onRecovered()}catch{live()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,live()&&setBusy(false)}};return{request:current,email:email2,busy:busy,error:error,canRetry:canRetry,canUpdateEmail:canUpdateEmail,canConvert:canConvert,hasEmailEdit:hasEmailEdit,confirmingRevoke:confirmingRevoke&¤t.canRevoke===true,emailInvalid:trimmed.length>0&&!validEmail,setEmail(value){locked.current||(setEmailValue(value),setError(null))},retry:()=>run("retry"),updateEmail:()=>run("email"),revoke:()=>run("revoke"),convert:()=>run("convert"),askRevoke(){!locked.current&¤t.canRevoke===true&&setConfirmingRevoke(true)},keepRequest(){locked.current||setConfirmingRevoke(false)}}}var RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],OWNER_RAIL_STAGES=["requested","awaiting_upload","records_received","processing","ready"],CONVERTED_RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],REQUEST_TIMELINE_TITLES=/* @__PURE__ */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"}),CLINIC_RAIL_TITLES=/* @__PURE__ */Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records…"}),CLINIC_RAIL_DETAILS=/* @__PURE__ */Object.freeze({notified:email2=>`A secure request went to ${email2}.`,received:"Everfur reads every page: dates, vaccines, labs and prescriptions.",added:petName=>`Added to ${petName}’s records`}),DETAILS=/* @__PURE__ */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’t read this one automatically",manualReview:"Checking these by hand so nothing’s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),TERMINAL_DETAILS=/* @__PURE__ */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"}),WIRE_FROM_STATUS=/* @__PURE__ */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 wireStatusOf(request){return request.wireStatus??WIRE_FROM_STATUS[request.status]??"sent"}function reminderProgressLabel(status,reminderCount){return status!=="awaiting_response"||reminderCount<=0?null:`${reminderCount} ${reminderCount===1?"reminder":"reminders"} sent`}function reachedRailIndex(status){switch(status){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}}function deliveryDetail(request){switch(request.dispatchStatus){case"sent":return DETAILS.delivered;case"preparing":case"queued":case"sending":return DETAILS.emailing;case"failed":return DETAILS.bounced;default:return null}}function awaitingDetail(request,status){return reminderProgressLabel(status,request.reminderCount??0)??DETAILS.waiting}function isOwnerSourcedRequest(request){return request.source==="owner_provided"||!!request.convertedToUploadAt}function railDetail(key,request,status){let isOwnerSourced=isOwnerSourcedRequest(request);switch(key){case"sent_to_clinic":return deliveryDetail(request);case"awaiting_clinic":return awaitingDetail(request,status);case"awaiting_upload":return DETAILS.upload;case"records_received":return isOwnerSourced?DETAILS.ownerAdded:DETAILS.clinicSent;case"processing":return DETAILS.preparing;case"ready":return DETAILS.ready;default:return null}}function tookReviewBranch(request,status){return!!request.reviewStartedAt||status==="parsing_failed"||status==="review_email_failed"}function expandProcessingPhase(event,request,status){if(event.key!=="processing"||!tookReviewBranch(request,status))return[event];let atParsingFailed=status==="parsing_failed",published=status==="published",parsingFailedState=published?"done":atParsingFailed?"current":"done",reviewState=published?"done":atParsingFailed?"upcoming":"current";return[{key:"parsing_failed",title:REQUEST_TIMELINE_TITLES.parsing_failed,detail:DETAILS.parsingFailed,at:null,state:parsingFailedState},{key:"manual_review",title:REQUEST_TIMELINE_TITLES.manual_review,detail:DETAILS.manualReview,at:request.reviewStartedAt??null,state:reviewState}]}function convertedReachedIndex(status){switch(status){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}}function convertedClinicSwitchEvent(request){return{key:"awaiting_clinic",title:DETAILS.switchedTitle,detail:DETAILS.switched,at:request.convertedToUploadAt??null,state:"done"}}function ownerReachedIndex(status){switch(status){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}}function railTimestamp(key,request,status){switch(key){case"requested":return request.createdAt||null;case"awaiting_clinic":return request.lastReminderAt??null;case"processing":return request.parsingStartedAt??request.reviewStartedAt??null;case"ready":return status==="published"&&request.updatedAt||null;default:return null}}function railEvent(key,request,status,state){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:railDetail(key,request,status),at:railTimestamp(key,request,status),state:state}}function terminalEvent(key,request){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:TERMINAL_DETAILS[key]??null,at:request.updatedAt||null,state:"failed"}}function walkRail(stages,reached,request,status,replace){return stages.map((key,idx)=>{let replaced=replace?.(key)??null;if(replaced!==null)return replaced;let state=status==="published"||idx<reached?"done":idx===reached?"current":"upcoming";return railEvent(key,request,status,state)}).flatMap(event=>expandProcessingPhase(event,request,status))}function buildRequestTimeline(request,options={}){return inArtifactWords(buildRailEvents(request),request,options.petName??null,options.sandbox===true)}function inArtifactWords(events,request,petName,sandbox){let clinicRail=request.source!=="owner_provided"&&!events.some(event=>event.key==="delivery_failed"),email2=request.clinicEmail?.trim()??"";return events.map(event=>{if(event.title!==REQUEST_TIMELINE_TITLES[event.key])return event;if(event.key==="ready")return{...event,title:CLINIC_RAIL_DETAILS.added(petNameOr(petName))};if(!clinicRail)return event;if(sandbox&&event.key==="sent_to_clinic")return{...event,title:RECORDS_SANDBOX_COPY.clinicNotContacted,detail:email2.length>0?RECORDS_SANDBOX_COPY.notEmailed(email2):null};let title=CLINIC_RAIL_TITLES[event.key]??event.title;return event.key==="sent_to_clinic"&&request.dispatchStatus==="sent"&&email2.length>0?{...event,title:title,detail:CLINIC_RAIL_DETAILS.notified(email2)}:event.key==="records_received"&&!isOwnerSourcedRequest(request)?{...event,title:title,detail:CLINIC_RAIL_DETAILS.received}:{...event,title:title}})}function buildRailEvents(request){let status=wireStatusOf(request),done=key=>railEvent(key,request,status,"done");if(status==="revoked")return[done("requested"),terminalEvent("revoked",request)];if(request.convertedToUploadAt)return status==="failed"?[done("requested"),done("sent_to_clinic"),convertedClinicSwitchEvent(request),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)]:walkRail(CONVERTED_RAIL_STAGES,convertedReachedIndex(status),request,status,key=>key==="awaiting_clinic"?convertedClinicSwitchEvent(request):null);if(request.source==="owner_provided"){if(status==="failed"||status==="clinic_declined")return[done("requested"),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)];let reached2=ownerReachedIndex(status);return walkRail(OWNER_RAIL_STAGES,reached2<0?1:reached2,request,status)}if(status==="clinic_declined")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_declined",request)];if(status==="clinic_responded_no_records")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_no_records",request)];if(status==="failed"){let code=request.failureCode??null;return code==="no_response"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("no_response",request)]:code==="hard_bounce"||code==="dispatch_failed"?[done("requested"),terminalEvent("delivery_failed",request)]:code==="parse_timeout"||code==="parse_error"||request.dispatchStatus==="sent"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),done("records_received"),terminalEvent("processing_failed",request)]:[done("requested"),terminalEvent("delivery_failed",request)]}let reached=reachedRailIndex(status);return walkRail(RAIL_STAGES,reached<0?1:reached,request,status)}var A11Y_STATE=/* @__PURE__ */Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),DOT_SIZE=28,NOW="Now",DOT_CORE_SIZE=10;function RequestTimeline({request:request,petName:petName}){let styles=useStyles8(),sandbox=useRecordsSandboxTenant(),events=buildRequestTimeline(request,{petName:petName??null,sandbox:sandbox});/* @__PURE__ */
|
|
495
|
+
return jsxRuntime.jsx(reactNative.View,{style:styles.container,accessibilityRole:"summary",children:events.map((event,idx)=>/* @__PURE__ */jsxRuntime.jsx(TimelineRow,{event:event,isLast:idx===events.length-1,styles:styles},event.key))})}function TimelineRow({event:event,isLast:isLast,styles:styles}){let date2=event.at?formatRecordsInstant(event.at):null,a11yParts=[event.title,event.detail,date2,A11Y_STATE[event.state]].filter(Boolean);/* @__PURE__ */
|
|
490
496
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.row,accessible:true,accessibilityRole:"text",accessibilityLabel:a11yParts.join(", "),testID:`records-timeline-${event.key}`,children:[
|
|
491
497
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.railColumn,children:[
|
|
492
498
|
/* @__PURE__ */jsxRuntime.jsx(TimelineDot,{state:event.state,styles:styles}),isLast?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.connector,event.state==="done"&&styles.connectorDone],accessibilityElementsHidden:true,importantForAccessibility:"no"})]}),
|
|
493
499
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.body,children:[
|
|
494
500
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.titleRow,children:[
|
|
495
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.title,event.state==="current"&&(event.key==="ready"?styles.titleReadyCurrent:styles.titleCurrent),event.state==="failed"&&styles.titleFailed,event.state==="upcoming"&&styles.titleUpcoming],children:event.title}),event.state==="current"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.now,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.nowText,children:NOW})}):null,
|
|
501
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.title,event.state==="current"&&(event.key==="ready"?styles.titleReadyCurrent:styles.titleCurrent),event.state==="failed"&&styles.titleFailed,event.state==="upcoming"&&styles.titleUpcoming],children:event.title}),event.state==="current"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.now,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.nowText,children:NOW})}):null,date2?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.date,children:date2}):null]}),event.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.detail,event.state==="upcoming"&&styles.detailUpcoming],children:event.detail}):null]})]})}function TimelineDot({state:state,styles:styles}){return state==="done"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:[styles.glyph,styles.glyphOnBrand],children:"✓"})}):state==="failed"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.glyph,children:"!"})}):state==="current"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.dotCurrentCore})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function useStyles8(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles10(theme),[theme])}function makeStyles10(theme){let{color:color,type:type}=theme,{size:size}=type;return reactNative.StyleSheet.create({container:{gap:0},row:{flexDirection:"row",alignItems:"flex-start",gap:12},railColumn:{alignItems:"center",width:DOT_SIZE},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",gap:8},dot:{width:DOT_SIZE,height:DOT_SIZE,borderRadius:DOT_SIZE/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:color.brand,borderWidth:2,borderColor:color.primaryEdge},dotFailed:{backgroundColor:color.danger},dotCurrent:{borderWidth:2,borderColor:color.brandInk,backgroundColor:color.surface},dotCurrentCore:{width:DOT_CORE_SIZE,height:DOT_CORE_SIZE,borderRadius:DOT_CORE_SIZE/2,backgroundColor:color.mark},now:{borderRadius:theme.radius.pill,backgroundColor:color.highlight,paddingHorizontal:theme.space.sm,paddingVertical:theme.space.xs/2},nowText:{...face(theme,"monoBold"),fontSize:size.tiny,lineHeight:size.tiny+4,letterSpacing:.6,color:color.onHighlight,textTransform:"uppercase"},dotUpcoming:{borderWidth:2,borderColor:color.structureEdge,backgroundColor:color.surface},glyph:{...face(theme,"bold"),fontSize:size.caption,lineHeight:size.caption+2,color:color.surface},glyphOnBrand:{color:color.onPrimary},connector:{width:2,flex:1,minHeight:22,backgroundColor:color.structureEdge,marginVertical:2},connectorDone:{backgroundColor:color.primaryEdge},title:{flexShrink:1,...face(theme,"bold"),fontSize:size.bodyTight,lineHeight:size.bodyTight+4,color:color.text.primary},titleCurrent:{color:color.brandInk},titleReadyCurrent:{color:brandedSuccessInk(theme)??color.brandInk},titleFailed:{color:color.danger},titleUpcoming:{color:color.text.muted,...face(theme,"regular")},date:{marginLeft:"auto",...face(theme,"regular"),fontSize:size.caption,lineHeight:size.caption+4,color:color.text.muted},detail:{...face(theme,"regular"),fontSize:size.caption,lineHeight:size.caption+5,color:color.text.muted},detailUpcoming:{color:color.text.muted,opacity:.7}})}function failureOf(result){if(typeof result!="object"||result===null||result.ok!==false)return null;let error=result.error;return typeof error=="object"&&error!==null&&typeof error.displayMessage=="string"?error:makeEverfurError("internalError")}function useConsentGrant(onGrant){let[pending,setPending]=react.useState(false),[error,setError]=react.useState(null),inFlight=react.useRef(false),mounted=react.useRef(true);react.useEffect(()=>(mounted.current=true,()=>{mounted.current=false}),[]);let latest=react.useRef(onGrant);latest.current=onGrant;let grant=react.useCallback(()=>{if(inFlight.current)return;let out;try{out=latest.current()}catch{setError(makeEverfurError("internalError"));return}if(out==null||typeof out.then!="function")return;inFlight.current=true,setPending(true),setError(null);let settle=failure=>{inFlight.current=false,mounted.current&&(setPending(false),setError(failure))};out.then(result=>settle(failureOf(result)),()=>settle(makeEverfurError("internalError")))},[]);return{pending:pending,error:error,grant:grant}}function renderErrorFamily(records,onGrant,canGrant,consentText){let errorView=selectErrorView(records,canGrant);switch(errorView.kind){case"consent_required":/* @__PURE__ */
|
|
496
502
|
return jsxRuntime.jsx(ConsentRequiredState,{onGrant:onGrant,consentText:consentText});case"consent_unavailable":/* @__PURE__ */
|
|
497
503
|
return jsxRuntime.jsx(ConsentUnavailableState,{});case"session_required":/* @__PURE__ */
|
|
498
504
|
return jsxRuntime.jsx(SessionRequiredState,{});case"withheld":/* @__PURE__ */
|
|
499
505
|
return jsxRuntime.jsx(WithheldState,{});case"pet_not_found":case"error":/* @__PURE__ */
|
|
500
|
-
return jsxRuntime.jsx(ErrorState,{error:errorView.error,onRetry:records.refresh});default:return assertNever(errorView)}}function makeGrantHandler(records,consentVersion){return()=>{let version=resolveConsentVersion(consentVersion,records.consent);if(version.length===0)return;let key=`records-consent-${Date.now().toString(36)}`;records.grantConsent(version,key)}}function UploadQueue({records:records}){let styles=useStyles9(),queue=records.uploadQueue;if(queue.length===0)return null;let rows=queue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,skipped=skippedFilesMessage(skippedOf(queue));/* @__PURE__ */
|
|
506
|
+
return jsxRuntime.jsx(ErrorState,{error:errorView.error,onRetry:records.refresh});default:return assertNever(errorView)}}function makeGrantHandler(records,consentVersion){return()=>{let version=resolveConsentVersion(consentVersion,records.consent);if(version.length===0)return;let key=`records-consent-${Date.now().toString(36)}`;return records.grantConsent(version,key)}}function UploadQueue({records:records}){let styles=useStyles9(),queue=records.uploadQueue;if(queue.length===0)return null;let rows=queue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,skipped=skippedFilesMessage(skippedOf(queue));/* @__PURE__ */
|
|
501
507
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.timeline,testID:"records-upload-queue",children:[skipped!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:styles.errorText,children:skipped}):null,rows.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityLiveRegion:"polite",accessibilityLabel:records.isUploading?UPLOAD_QUEUE_COPY.uploading(done,rows.length):UPLOAD_QUEUE_COPY.uploaded(done,rows.length),children:rows.map(item=>{let pct2=Math.round(item.progress*100);
|
|
502
508
|
/* @__PURE__ */
|
|
503
509
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.uploadRow,testID:`records-upload-file-${item.status}`,children:[
|
|
504
510
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.uploadRowHead,children:[
|
|
505
511
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowLabel,children:item.name??""}),
|
|
506
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:uploadItemStatusLabel(item)})]}),item.status==="uploading"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:pct2},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.progressFill,{width:`${pct2}%`}]})}):null,item.status==="failed"&&item.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineMeta,children:item.error.displayMessage}):null]},item.key)})}):null]})}function ConsentRequiredState({onGrant:onGrant,consentText:consentText}){let styles=useStyles9(),
|
|
507
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.askText,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:RECORDS_COPY.consentRequired}),
|
|
508
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:
|
|
512
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:uploadItemStatusLabel(item)})]}),item.status==="uploading"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:pct2},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.progressFill,{width:`${pct2}%`}]})}):null,item.status==="failed"&&item.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineMeta,children:item.error.displayMessage}):null]},item.key)})}):null]})}function ConsentRequiredState({onGrant:onGrant,consentText:consentText}){let styles=useStyles9(),text4=presentConsentText(consentText),{pending:pending,error:error,grant:grant}=useConsentGrant(onGrant);return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(RECORDS_COPY.consentRequired)},[]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.centered,testID:"records-consent-gate",children:[
|
|
513
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.askText,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:RECORDS_COPY.consentRequired}),text4!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.disclaimer,testID:"records-consent-gate-body",children:text4}):null,
|
|
514
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:grant,disabled:pending,accessibilityRole:"button",accessibilityLabel:RECORDS_COPY.allow,accessibilityState:{disabled:pending,busy:pending},style:pending?styles.disabledButton:styles.primaryButton,testID:"records-consent-allow",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:pending?styles.disabledLabel:styles.primaryLabel,children:RECORDS_COPY.allow})}),error!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",testID:"records-consent-grant-error",children:error.displayMessage}):null]})}function AlertState({label:label,glyph:glyph}){let styles=useStyles9();return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(label)},[label]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:label,children:[
|
|
509
515
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:glyph==="withheld"?styles.withheldGlyph:styles.emptyGlyph}),
|
|
510
516
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:label})]})}function ConsentUnavailableState(){/* @__PURE__ */
|
|
511
517
|
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.consentRequired,glyph:"empty"})}function SessionRequiredState(){/* @__PURE__ */
|
|
@@ -535,7 +541,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:local.row,testID:`records-request
|
|
|
535
541
|
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function useLocalStyles5(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles5(theme),[theme])}function makeLocalStyles5(theme){let{color:color,space:space,radius:radius,type:type}=theme,lh=(size,m)=>Math.round(size*m),bubble=space.xxl+space.xs/2;return reactNative.StyleSheet.create({subtitle:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),color:color.text.muted,paddingHorizontal:space.lg,paddingBottom:space.md},list:{paddingHorizontal:space.lg,paddingBottom:space.xl,gap:space.md},row:{borderRadius:radius.lg,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm},rowInner:{flexDirection:"row",alignItems:"center",gap:space.md},bubble:{width:bubble,height:bubble,borderRadius:bubble/2},copy:{flex:1,gap:space.xs+1},source:{...face(theme,"bold"),fontSize:type.size.body,lineHeight:lh(type.size.body,type.lineHeight.snug),color:color.text.primary},meta:{...face(theme,"regular"),fontSize:type.size.tiny,lineHeight:lh(type.size.tiny,type.lineHeight.normal),color:color.text.muted},footer:{paddingHorizontal:space.lg,paddingTop:space.sm+space.xs/2,paddingBottom:space.lg,gap:space.sm+space.xs/2,borderTopWidth:1,borderTopColor:color.borderHairlineGreen},card:{flexDirection:"row",alignItems:"center",gap:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,paddingHorizontal:space.md+space.xs,paddingVertical:space.md,...slotBox(recordCardSlot(theme.slots),1)},cardBubble:{width:space.xl+space.xs/2,height:space.xl+space.xs/2,borderRadius:radius.pill,borderWidth:2,borderColor:color.brandInk},cardBubbleProcessing:{borderColor:color.warningStrong,backgroundColor:color.badgeBgCaution},cardText:{flex:1,gap:2},cardTitle:{...headingFace(theme,"bold"),fontSize:type.size.bodyTight,lineHeight:lh(type.size.bodyTight,type.lineHeight.snug),color:color.brandInk,...slotText(recordCardSlot(theme.slots))},cardSubtitle:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),color:color.text.muted,...slotText(recordCardSlot(theme.slots))}})}var readDepth=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty=value=>!value.available;function EverfurRecordsDashboard(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]);/* @__PURE__ */
|
|
536
542
|
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(DashboardBody,{...rest,style:style})})}function DashboardBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,style:style}){let styles=useScreenStyles(),local=useLocalStyles6(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),{runtime:runtime}=useEverfurContext(),photoWay=acceptsPhotos(records.uploadContentTypes)&&isCaptureAvailable(runtime.registry.services.camera),markers=useRecordsMarkers(petRef),depth=useRecordsDepthRead(petRef,readDepth,depthEmpty),[provenance,setProvenance]=react.useState(null),onPointPress=react.useCallback((marker,point)=>setProvenance({marker:marker,point:point}),[]);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),clinicDecision=useCapability("recordsClinic"),canRequestFromClinic=clinicDecision.enabled||clinicDecision.isPending,markerList=markers.markers?.markers??[],hasMarkers=markerList.length>0,hasFullRecord=records.record!==null&&!records.record.isEmpty&&!records.record.withheld,drivingRequest=pickPetRecordsRequest(records.requests,petRef),petRequests=records.requests.filter(r=>r.petRef===petRef),openRequests=onNavigate?()=>onNavigate({name:"requests"}):void 0,dashboardState=deriveRecordsDashboardState({hasMarkers:hasMarkers,requests:records.requests,petRef:petRef}),view=selectDashboardView({recordLoading:records.status==="loading",hasFullRecord:hasFullRecord,recordError:records.status==="error",markersLoading:markers.status==="loading",markersError:markers.status==="error",hasMarkers:hasMarkers,requestsLoading:records.status==="loading",dashboardState:dashboardState,drivingRequest:drivingRequest}),disclaimer=markers.markers?.disclaimer??records.record?.disclaimer??"",retryAll=()=>{records.refresh(),markers.refresh(),depth.refresh()},depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,name=petNameOr(petName),askSummary=onAsk&&markers.markers?.summary?()=>{let built=buildMarkerSummaryAskPrompt(petName,markers.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},petRef);onAsk(built.prompt,built.entityRef)}:void 0,askMarker=onAsk?marker=>{let built=buildMarkerAskPrompt(petName,{canonicalName:marker.name,markerId:marker.markerId,latestValueText:marker.latest?formatMarkerReading(marker.latest.value,marker.unit,marker.latest.qualitativeResult):null,statusText:marker.latest?markerStatusLabel(marker.latest.status).label:null,trajectoryText:trajectoryLabel(marker.trajectory,marker.points.length),meaningText:marker.meaning});onAsk(built.prompt,built.entityRef)}:void 0,askReading=onAsk&&provenance?()=>{let{marker:marker,point:point}=provenance,built=buildMarkerReadingAskPrompt(petName,{canonicalName:marker.name,valueText:formatMarkerReading(point.value,marker.unit,point.qualitativeResult),collectedAt:formatRecordsDate(point.at),sourceClinic:point.sourceClinic,referenceText:point.refLow!==null||point.refHigh!==null?formatReferenceRange(point,marker.unit):null,flagged:point.status==="above"?"above":point.status==="below"?"below":null,reviewed:point.reviewed,entityId:point.docId??marker.markerId});setProvenance(null),onAsk(built.prompt,built.entityRef)}:void 0,labs=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[markers.markers?.summary?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(MarkerSummaryCard,{summary:markers.markers.summary,onAsk:askSummary,testID:"dashboard-marker-summary"})}):null,
|
|
537
543
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.lead,children:DASHBOARD_COPY.lead(petName)}),
|
|
538
|
-
/* @__PURE__ */jsxRuntime.jsx(MarkerTrendCarousel,{markers:markerList,onPointPress:onPointPress,onAsk:askMarker})]}),actions=withRecord=>onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.inset,local.actions],children:[withRecord?/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"record",label:DASHBOARD_COPY.viewFullRecord,onPress:()=>onNavigate({name:"record"}),testID:"dashboard-full-record-action"}):null,
|
|
544
|
+
/* @__PURE__ */jsxRuntime.jsx(MarkerTrendCarousel,{markers:markerList,featuredMarkerId:markers.markers?.featuredMarkerId??null,onPointPress:onPointPress,onAsk:askMarker})]}),actions=withRecord=>onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.inset,local.actions],children:[withRecord?/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"record",label:DASHBOARD_COPY.viewFullRecord,onPress:()=>onNavigate({name:"record"}),testID:"dashboard-full-record-action"}):null,
|
|
539
545
|
/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"timeline",label:DASHBOARD_COPY.viewTimeline,onPress:()=>onNavigate({name:"timeline"}),testID:"dashboard-timeline-action"}),
|
|
540
546
|
/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"requests",label:REQUEST_LIST_COPY.allRequests,onPress:()=>onNavigate({name:"requests"}),testID:"dashboard-requests-action"})]}):null,addActions=inset=>onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.inset,local.addActions],testID:"dashboard-actions",children:[canRequestFromClinic?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.requestFromClinic,onPress:()=>onNavigate({name:"clinicPicker"}),style:local.addCta,testID:"dashboard-actions-clinic"}):null,
|
|
541
547
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.uploadDocument,kind:"outline",onPress:()=>onNavigate({name:"upload"}),style:local.addCta,testID:"dashboard-actions-upload"})]}):null,body;if(records.status==="error"){let errorView=selectErrorView(records,canGrant);body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?retryAll:void 0,testID:"dashboard-error"}):renderErrorFamily(records,onGrant,canGrant,consentText)}else switch(view){case"loading":body=/* @__PURE__ */jsxRuntime.jsx(DashboardSkeleton,{testID:"dashboard-loading"});break;case"record":body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.contentTight,testID:"dashboard-record",children:[hasMarkers?labs:markers.status==="error"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.inset,local.actions],children:/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"retry",label:DASHBOARD_COPY.retryMarkers,onPress:retryAll,testID:"dashboard-markers-retry"})}):null,
|
|
@@ -575,7 +581,7 @@ return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:
|
|
|
575
581
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.wayTitle,children:title}),sub?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.waySub,children:sub}):null]}),
|
|
576
582
|
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function useLocalStyles6(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles6(theme),[theme])}function makeLocalStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,card=theme.slots.card,cardText=slotText(card);return reactNative.StyleSheet.create({headerButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},actions:{gap:space.sm+space.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.lg,...slotBox(card,1)},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:space.md},actionIcon:{width:ACTION_GLYPH_SIZE,height:ACTION_GLYPH_SIZE,alignItems:"center",justifyContent:"center"},actionLabel:{flex:1,...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...cardText},inProgressCard:{borderRadius:radius.lg,backgroundColor:color.surface,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.lg,...slotBox(card,1)},inProgressHeadText:{flex:1,gap:space.xs/2},ways:{gap:space.sm},way:{flexDirection:"row",alignItems:"center",gap:space.md,borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,...slotBox(card,1)},wayDashed:{borderStyle:"dashed",borderColor:color.brandBorderStrong},wayText:{flex:1,gap:space.xs/2},wayTitle:{...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...cardText},waySub:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,...cardText},inProgressInner:{gap:space.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},inProgressTitle:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),letterSpacing:-.4,color:color.brandInk,...cardText},promptCard:{borderRadius:radius.sm,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderRingCream,paddingHorizontal:space.lg+space.xs,paddingVertical:space.lg+space.xs/2,...slotBox(card,hairline)},promptHeader:{flexDirection:"row",alignItems:"center",gap:space.xs+1},promptGlyph:{width:space.xl+1,height:space.xl+1,borderRadius:radius.xs,borderWidth:2,borderColor:color.warningStrong},promptTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),letterSpacing:type.letterSpacing.headerBrand,color:color.brandInk,...cardText},promptBody:{marginTop:space.sm-1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:space.lg+space.xs,color:color.text.primary,...cardText},promptCta:{marginTop:space.sm-1,minHeight:space.xxl+space.sm},promptCtaSecondary:{marginTop:space.sm,minHeight:space.xxl+space.sm},addActions:{gap:space.sm},addCta:{minHeight:space.xxl+space.sm}})}var KIND_ORDER=/* @__PURE__ */Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function toMillis2(iso){if(!iso)return null;let ms=Date.parse(iso);return Number.isNaN(ms)?null:ms}function buildTimelineRows(timeline){let rows=[...timeline.visits.map((visit,index)=>({key:`visit-${index}-${visit.visitId}`,kind:"visit",kindLabel:DEPTH_COPY.kind.visit,at:visit.visitDate,date:formatRecordsDate(visit.visitDate),title:visit.summary??DEPTH_COPY.clinicVisit,detail:visit.veterinarian?DEPTH_COPY.doctor(visit.veterinarian):null,docId:visit.docId})),...timeline.vaccines.map((vaccine,index)=>{let parts=[];return vaccine.lot&&parts.push(DEPTH_COPY.lot(vaccine.lot)),vaccine.expiresOn&&parts.push(DEPTH_COPY.expires(formatRecordsDate(vaccine.expiresOn))),{key:`vaccine-${index}-${vaccine.vaccineId}`,kind:"vaccine",kindLabel:DEPTH_COPY.kind.vaccine,at:vaccine.administeredOn,date:formatRecordsDate(vaccine.administeredOn),title:vaccine.product||DEPTH_COPY.kind.vaccine,detail:parts.length?parts.join(" · "):null,docId:vaccine.docId}}),...timeline.weights.map((weight,index)=>({key:`weight-${index}-${weight.weightId}`,kind:"weight",kindLabel:DEPTH_COPY.kind.weight,at:weight.observedOn,date:formatRecordsDate(weight.observedOn),title:formatWeightKg(weight.weightKg),detail:null,docId:weight.docId})),...timeline.medications.map((medication,index)=>{let parts=[medication.dose,medication.route,medication.frequency].filter(p=>!!p);return{key:`medication-${index}-${medication.medicationId}`,kind:"medication",kindLabel:DEPTH_COPY.kind.medication,at:medication.startedOn,date:formatRecordsDate(medication.startedOn),title:medication.drugName||DEPTH_COPY.kind.medication,detail:parts.length?parts.join(" · "):null,docId:medication.docId}})];/* @__PURE__ */
|
|
577
583
|
return Object.freeze(rows.sort((a,b)=>{let am=toMillis2(a.at),bm=toMillis2(b.at);return am===null&&bm===null?KIND_ORDER[a.kind]-KIND_ORDER[b.kind]:am===null?1:bm===null?-1:bm!==am?bm-am:KIND_ORDER[a.kind]-KIND_ORDER[b.kind]}))}var SPINNER_DELAY_MS=300,readTimeline=(client,petRef)=>client.getTimeline(petRef),timelineEmpty=value=>value.isEmpty;var contributionsEmpty=value=>value.contributions.length===0;function EverfurRecordsTimeline({petRef:petRef,style:style,onBack:onBack}){let state=useRecordsDepthRead(petRef,readTimeline,timelineEmpty);/* @__PURE__ */
|
|
578
|
-
return jsxRuntime.jsx(DepthSurface,{state:state,style:style,onBack:onBack,header:/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:DEPTH_COPY.timeline,onBack:guardHost(onBack),testID:"timeline-header"}),loading:/* @__PURE__ */jsxRuntime.jsx(TimelineSkeleton,{testID:"timeline-loading"}),empty:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",testID:"timeline-empty"}),render:timeline=>/* @__PURE__ */jsxRuntime.jsx(TimelineBody,{timeline:timeline})})}function EverfurDocumentContributions({petRef:petRef,docId:docId,style:style,onBack:onBack}){let read=react.useCallback((client,pet)=>client.getDocumentContributions(pet,docId),[docId]),state=useRecordsDepthRead(petRef,read,contributionsEmpty,docId),
|
|
584
|
+
return jsxRuntime.jsx(DepthSurface,{state:state,style:style,onBack:onBack,header:/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:DEPTH_COPY.timeline,onBack:guardHost(onBack),testID:"timeline-header"}),loading:/* @__PURE__ */jsxRuntime.jsx(TimelineSkeleton,{testID:"timeline-loading"}),empty:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",testID:"timeline-empty"}),render:timeline=>/* @__PURE__ */jsxRuntime.jsx(TimelineBody,{timeline:timeline})})}function EverfurDocumentContributions({petRef:petRef,docId:docId,style:style,onBack:onBack}){let read=react.useCallback((client,pet)=>client.getDocumentContributions(pet,docId),[docId]),state=useRecordsDepthRead(petRef,read,contributionsEmpty,docId),shown=state.value?.document??null,title=shown!==null?documentTitle(shown):DEPTH_COPY.uploadedDocument;/* @__PURE__ */
|
|
579
585
|
return jsxRuntime.jsx(DepthSurface,{state:state,style:style,onBack:onBack,header:/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:title,onBack:guardHost(onBack),testID:"contributions-header"}),empty:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",testID:"contributions-empty"}),render:view=>/* @__PURE__ */jsxRuntime.jsx(ContributionsBody,{view:view})})}function DepthSurface({state:state,style:style,header:header,loading:loading,empty:empty,render:render,onBack:onBack}){let styles=useStyles10();/* @__PURE__ */
|
|
580
586
|
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...recordsGateExit(guardHost(onBack),BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.container,style],children:[header??null,
|
|
581
587
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:renderState(state,render,styles,loading,empty)}),
|
|
@@ -591,7 +597,7 @@ return jsxRuntime.jsxs(reactNative.ScrollView,{style:styles.list,contentContaine
|
|
|
591
597
|
return jsxRuntime.jsxs(reactNative.ScrollView,{style:styles.list,contentContainerStyle:styles.listContent,accessibilityLabel:RECORDS_COPY.records,children:[view.document?.receivedAt?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:formatRecordsInstant(view.document.receivedAt)}):null,
|
|
592
598
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:view.contributions.map(entity=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.row,accessible:true,accessibilityRole:"text",children:[
|
|
593
599
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:entity.label}),
|
|
594
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useStyles10(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles12(theme),[theme])}function makeStyles12(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,minSurface=space.xxl*3+space.xl,touchTarget=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,cardText=slotText(recordCardSlot(slots)),text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),inCard=(fontSize,multiplier,fg,weight="regular")=>({...text3(fontSize,multiplier,fg,weight),...cardText});return reactNative.StyleSheet.create({container:{flex:1,minHeight:minSurface,backgroundColor:color.background},body:{flex:1},centered:{minHeight:minSurface,flexGrow:1,alignItems:"center",justifyContent:"center",padding:space.xl,gap:space.lg},emptyGlyph:{width:space.xxl+space.sm,height:space.xxl+space.sm,borderRadius:radius.lg,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},errorText:{...text3(size.subtitle,lineHeight.snug,errorColor),textAlign:"center",marginBottom:space.md},primaryButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.primaryButton)},primaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,...slotText(slots.primaryButton)},list:{flex:1},listContent:{padding:space.lg,gap:space.md},section:{gap:space.sm},heading:{...text3(size.heading,lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},card:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...slotBox(recordCardSlot(slots),hairline)},row:{gap:space.xs,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:space.md},kindLabel:{...inCard(size.caption,lineHeight.normal,color.text.muted,"medium")},date:inCard(size.caption,lineHeight.normal,color.text.muted),rowTitle:{...inCard(size.body,lineHeight.normal,color.text.primary,"bold"),...headingFace(theme,"bold")},rowValue:{...inCard(size.body,lineHeight.normal,color.text.primary,"medium")},rowDetail:inCard(size.bodyTight,lineHeight.normal,color.text.muted),rowMuted:{...inCard(size.bodyTight,lineHeight.normal,color.text.muted),opacity:.7},chip:{...text3(size.caption,lineHeight.normal,color.text.primary),alignSelf:"flex-start",paddingHorizontal:space.sm,paddingVertical:space.xs,borderRadius:radius.pill},chipNeutral:{backgroundColor:color.badgeBgNeutral},chipCaution:{backgroundColor:color.badgeBgCaution},chipCritical:{backgroundColor:color.badgeBgCritical},disclaimer:{...text3(size.caption,lineHeight.normal,color.text.muted),marginTop:space.md},timelineContent:{paddingBottom:space.xxl},timelineBand:{flexDirection:"row",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,marginHorizontal:space.lg,marginTop:space.xs,marginBottom:space.md},timelineBandText:{flex:1,...text3(size.caption,lineHeight.normal,color.text.secondary)},timelineSeparator:{height:hairline,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},timelineRow:{flexDirection:"row",gap:space.md,paddingHorizontal:space.lg,paddingVertical:space.md+space.xs/2},timelineBubble:{width:space.xxl+space.xs/2,height:space.xxl+space.xs/2,borderRadius:radius.pill,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},timelineBody:{flex:1,gap:space.xs-1},timelineKind:{...face(theme,"mono"),fontSize:size.micro,lineHeight:size.bodyTight,letterSpacing:type.letterSpacing.eyebrow/3,textTransform:"uppercase",color:color.text.secondary},timelineTitle:{...text3(size.body,lineHeight.normal,color.text.primary,"medium")}})}function useRecordShares(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),now=opts.now??Date.now,[shares,setShares]=react.useState(null),[loading,setLoading]=react.useState(true),[error,setError]=react.useState(null),[lit,setLit]=react.useState(null),available=lit===true,[urls,setUrls]=react.useState({}),[creating,setCreating]=react.useState(false),[revokingId,setRevokingId]=react.useState(null),[preparingPdf,setPreparingPdf]=react.useState(false),[consentRequired,setConsentRequired]=react.useState(false),[sending,setSending]=react.useState(false),[featuresState,setFeaturesState]=react.useState(null),recordsFeatures=featuresState!==null&&featuresState.client===client?featuresState.value:RECORDS_FEATURES_PDF_ONLY,shareAudiences=recordsFeatures.shareAudiences,consentEpoch=useRecordsConsentEpoch(petRef),generation=react.useRef(0),live=react.useRef(true),load=react.useCallback(async()=>{let gen=generation.current+=1;if(setLoading(true),setError(null),userRef===null){setShares(null),setLoading(false);return}let result=await client.listShares(petRef);gen!==generation.current||!live.current||(result.ok?(setShares(result.value),setLit(true)):isDarkRouteError(result.error)?(setShares(null),setLit(false)):(setShares(null),setError(result.error),answeredBehindGate(result)&&setLit(true)),setLoading(false))},[client,petRef,userRef]);react.useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]),react.useEffect(()=>{if(userRef===null||client.readFeatures===void 0)return;let current=true;return client.readFeatures().then(value=>{current&&setFeaturesState({client:client,value:value})},()=>{}),()=>{current=false}},[client,userRef]);let seenEpoch=react.useRef(consentEpoch);react.useEffect(()=>{seenEpoch.current!==consentEpoch&&(seenEpoch.current=consentEpoch,setUrls({}),setConsentRequired(true),load())},[consentEpoch,load]);let createLink=react.useCallback(async audience=>{setCreating(true);let result=await(audience!==void 0&&shareAudiences.some(scope=>scope.audience===audience)?client.createShare(petRef,{audience:audience}):client.createShare(petRef));return live.current&&(setCreating(false),result.ok?(setUrls(current=>({...current,[result.value.shareId]:result.value.shareUrl})),load()):isDarkRouteError(result.error)?setLit(false):isRecordsConsentRequired(result.error)&&setConsentRequired(true)),result},[client,petRef,load,shareAudiences]),sendEmail=react.useCallback(async input=>{setSending(true);let result=await client.emailShare(petRef,input);return live.current&&(setSending(false),result.ok?load():isDarkRouteError(result.error)?setLit(false):isRecordsConsentRequired(result.error)?setConsentRequired(true):result.error.httpStatus===502&&load()),result},[client,petRef,load]),revoke=react.useCallback(async shareId=>{setRevokingId(shareId);let result=await client.revokeShare(petRef,shareId);return live.current&&(setRevokingId(null),load()),result},[client,petRef,load]),pdfLink=react.useCallback(async()=>{setPreparingPdf(true);let result=await client.getPdfLink(petRef);return live.current&&(setPreparingPdf(false),!result.ok&&isRecordsConsentRequired(result.error)&&setConsentRequired(true)),result},[client,petRef]),refresh=react.useCallback(()=>{setConsentRequired(false),load()},[load]),rows=react.useMemo(()=>buildShareRows(shares??[],urls,now()),[shares,urls,now]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated",features=recordsFeatures.features;return react.useMemo(()=>({status:status,rows:rows,available:available,consentRequired:consentRequired,error:error,creating:creating,revokingId:revokingId,preparingPdf:preparingPdf,shareAudiences:shareAudiences,features:features,sending:sending,createLink:createLink,sendEmail:sendEmail,revoke:revoke,pdfLink:pdfLink,refresh:refresh}),[status,rows,available,consentRequired,error,creating,revokingId,preparingPdf,shareAudiences,features,sending,createLink,sendEmail,revoke,pdfLink,refresh])}function answeredBehindGate(result){return result.ok||result.error.httpStatus!==void 0&&result.error.httpStatus!==404}function sharesListShown(shares){return shares.available||shares.status!=="empty"}function useRecordsDepthProbe(petRef){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),scope=react.useMemo(()=>({}),[client,petRef,userRef]),[state,setState]=react.useState({scope:scope,lit:null});react.useEffect(()=>{if(userRef===null)return;let live=true;return client.listShares(petRef).then(result=>{live&&(!result.ok&&isDarkRouteError(result.error)?setState({scope:scope,lit:false}):answeredBehindGate(result)&&setState({scope:scope,lit:true}))},()=>{}),()=>{live=false}},[client,petRef,userRef,scope]);let lit=state.scope===scope?state.lit:null;return react.useMemo(()=>({lit:lit}),[lit])}function useRecordPdfLink(petRef){let client=useEverfurRecordsDepthClient(),available=useRecordsDepthProbe(petRef).lit===true,[preparing,setPreparing]=react.useState(false),[error,setError]=react.useState(null),live=react.useRef(true);react.useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let pdfLink=react.useCallback(async()=>{setPreparing(true),setError(null);let result=await client.getPdfLink(petRef);return live.current&&(setPreparing(false),result.ok||setError(result.error)),result},[client,petRef]);return react.useMemo(()=>({preparing:preparing,available:available,error:error,pdfLink:pdfLink}),[preparing,available,error,pdfLink])}async function shareLinkViaOs(url){await reactNative.Share.share({message:SHARE_COPY.shareMessage(url),url:url})}async function shareFileLinkViaOs(url){await reactNative.Share.share(reactNative.Platform.OS==="ios"?{url:url}:{message:url})}var COPY=RECORD_SCREEN_COPY.document,DOCUMENT_ENTITY_ORDER=/* @__PURE__ */Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),readDepth2=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty2=value=>!value.available;function EverfurRecordDocument(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onBack"]);/* @__PURE__ */
|
|
600
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useStyles10(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles12(theme),[theme])}function makeStyles12(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,minSurface=space.xxl*3+space.xl,touchTarget=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,cardText=slotText(recordCardSlot(slots)),text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),inCard=(fontSize,multiplier,fg,weight="regular")=>({...text4(fontSize,multiplier,fg,weight),...cardText});return reactNative.StyleSheet.create({container:{flex:1,minHeight:minSurface,backgroundColor:color.background},body:{flex:1},centered:{minHeight:minSurface,flexGrow:1,alignItems:"center",justifyContent:"center",padding:space.xl,gap:space.lg},emptyGlyph:{width:space.xxl+space.sm,height:space.xxl+space.sm,borderRadius:radius.lg,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},errorText:{...text4(size.subtitle,lineHeight.snug,errorColor),textAlign:"center",marginBottom:space.md},primaryButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.primaryButton)},primaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,...slotText(slots.primaryButton)},list:{flex:1},listContent:{padding:space.lg,gap:space.md},section:{gap:space.sm},heading:{...text4(size.heading,lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},card:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...slotBox(recordCardSlot(slots),hairline)},row:{gap:space.xs,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:space.md},kindLabel:{...inCard(size.caption,lineHeight.normal,color.text.muted,"medium")},date:inCard(size.caption,lineHeight.normal,color.text.muted),rowTitle:{...inCard(size.body,lineHeight.normal,color.text.primary,"bold"),...headingFace(theme,"bold")},rowValue:{...inCard(size.body,lineHeight.normal,color.text.primary,"medium")},rowDetail:inCard(size.bodyTight,lineHeight.normal,color.text.muted),rowMuted:{...inCard(size.bodyTight,lineHeight.normal,color.text.muted),opacity:.7},chip:{...text4(size.caption,lineHeight.normal,color.text.primary),alignSelf:"flex-start",paddingHorizontal:space.sm,paddingVertical:space.xs,borderRadius:radius.pill},chipNeutral:{backgroundColor:color.badgeBgNeutral},chipCaution:{backgroundColor:color.badgeBgCaution},chipCritical:{backgroundColor:color.badgeBgCritical},disclaimer:{...text4(size.caption,lineHeight.normal,color.text.muted),marginTop:space.md},timelineContent:{paddingBottom:space.xxl},timelineBand:{flexDirection:"row",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,marginHorizontal:space.lg,marginTop:space.xs,marginBottom:space.md},timelineBandText:{flex:1,...text4(size.caption,lineHeight.normal,color.text.secondary)},timelineSeparator:{height:hairline,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},timelineRow:{flexDirection:"row",gap:space.md,paddingHorizontal:space.lg,paddingVertical:space.md+space.xs/2},timelineBubble:{width:space.xxl+space.xs/2,height:space.xxl+space.xs/2,borderRadius:radius.pill,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},timelineBody:{flex:1,gap:space.xs-1},timelineKind:{...face(theme,"mono"),fontSize:size.micro,lineHeight:size.bodyTight,letterSpacing:type.letterSpacing.eyebrow/3,textTransform:"uppercase",color:color.text.secondary},timelineTitle:{...text4(size.body,lineHeight.normal,color.text.primary,"medium")}})}function useRecordShares(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),now=opts.now??Date.now,[shares,setShares]=react.useState(null),[loading,setLoading]=react.useState(true),[error,setError]=react.useState(null),[lit,setLit]=react.useState(null),available=lit===true,[urls,setUrls]=react.useState({}),[creating,setCreating]=react.useState(false),[revokingId,setRevokingId]=react.useState(null),[preparingPdf,setPreparingPdf]=react.useState(false),[consentRequired,setConsentRequired]=react.useState(false),[sending,setSending]=react.useState(false),[featuresState,setFeaturesState]=react.useState(null),recordsFeatures=featuresState!==null&&featuresState.client===client?featuresState.value:RECORDS_FEATURES_PDF_ONLY,shareAudiences=recordsFeatures.shareAudiences,consentEpoch=useRecordsConsentEpoch(petRef),generation=react.useRef(0),live=react.useRef(true),load=react.useCallback(async()=>{let gen=generation.current+=1;if(setLoading(true),setError(null),userRef===null){setShares(null),setLoading(false);return}let result=await client.listShares(petRef);gen!==generation.current||!live.current||(result.ok?(setShares(result.value),setLit(true)):isDarkRouteError(result.error)?(setShares(null),setLit(false)):(setShares(null),setError(result.error),answeredBehindGate(result)&&setLit(true)),setLoading(false))},[client,petRef,userRef]);react.useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]),react.useEffect(()=>{if(userRef===null||client.readFeatures===void 0)return;let current=true;return client.readFeatures().then(value=>{current&&setFeaturesState({client:client,value:value})},()=>{}),()=>{current=false}},[client,userRef]);let seenEpoch=react.useRef(consentEpoch);react.useEffect(()=>{seenEpoch.current!==consentEpoch&&(seenEpoch.current=consentEpoch,setUrls({}),setConsentRequired(true),load())},[consentEpoch,load]);let createLink=react.useCallback(async audience=>{setCreating(true);let result=await(audience!==void 0&&shareAudiences.some(scope=>scope.audience===audience)?client.createShare(petRef,{audience:audience}):client.createShare(petRef));return live.current&&(setCreating(false),result.ok?(setUrls(current=>({...current,[result.value.shareId]:result.value.shareUrl})),load()):isDarkRouteError(result.error)?setLit(false):isRecordsConsentRequired(result.error)&&setConsentRequired(true)),result},[client,petRef,load,shareAudiences]),sendEmail=react.useCallback(async input=>{setSending(true);let result=await client.emailShare(petRef,input);return live.current&&(setSending(false),result.ok?load():isDarkRouteError(result.error)?setLit(false):isRecordsConsentRequired(result.error)?setConsentRequired(true):result.error.httpStatus===502&&load()),result},[client,petRef,load]),revoke=react.useCallback(async shareId=>{setRevokingId(shareId);let result=await client.revokeShare(petRef,shareId);return live.current&&(setRevokingId(null),load()),result},[client,petRef,load]),pdfLink=react.useCallback(async()=>{setPreparingPdf(true);let result=await client.getPdfLink(petRef);return live.current&&(setPreparingPdf(false),!result.ok&&isRecordsConsentRequired(result.error)&&setConsentRequired(true)),result},[client,petRef]),refresh=react.useCallback(()=>{setConsentRequired(false),load()},[load]),rows=react.useMemo(()=>buildShareRows(shares??[],urls,now()),[shares,urls,now]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated",features=recordsFeatures.features;return react.useMemo(()=>({status:status,rows:rows,available:available,consentRequired:consentRequired,error:error,creating:creating,revokingId:revokingId,preparingPdf:preparingPdf,shareAudiences:shareAudiences,features:features,sending:sending,createLink:createLink,sendEmail:sendEmail,revoke:revoke,pdfLink:pdfLink,refresh:refresh}),[status,rows,available,consentRequired,error,creating,revokingId,preparingPdf,shareAudiences,features,sending,createLink,sendEmail,revoke,pdfLink,refresh])}function answeredBehindGate(result){return result.ok||result.error.httpStatus!==void 0&&result.error.httpStatus!==404}function sharesListShown(shares){return shares.available||shares.status!=="empty"}function useRecordsDepthProbe(petRef){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),scope=react.useMemo(()=>({}),[client,petRef,userRef]),[state,setState]=react.useState({scope:scope,lit:null});react.useEffect(()=>{if(userRef===null)return;let live=true;return client.listShares(petRef).then(result=>{live&&(!result.ok&&isDarkRouteError(result.error)?setState({scope:scope,lit:false}):answeredBehindGate(result)&&setState({scope:scope,lit:true}))},()=>{}),()=>{live=false}},[client,petRef,userRef,scope]);let lit=state.scope===scope?state.lit:null;return react.useMemo(()=>({lit:lit}),[lit])}function useRecordPdfLink(petRef){let client=useEverfurRecordsDepthClient(),available=useRecordsDepthProbe(petRef).lit===true,[preparing,setPreparing]=react.useState(false),[error,setError]=react.useState(null),live=react.useRef(true);react.useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let pdfLink=react.useCallback(async()=>{setPreparing(true),setError(null);let result=await client.getPdfLink(petRef);return live.current&&(setPreparing(false),result.ok||setError(result.error)),result},[client,petRef]);return react.useMemo(()=>({preparing:preparing,available:available,error:error,pdfLink:pdfLink}),[preparing,available,error,pdfLink])}async function shareLinkViaOs(url){await reactNative.Share.share({message:SHARE_COPY.shareMessage(url),url:url})}async function shareFileLinkViaOs(url){await reactNative.Share.share(reactNative.Platform.OS==="ios"?{url:url}:{message:url})}var COPY=RECORD_SCREEN_COPY.document,DOCUMENT_ENTITY_ORDER=/* @__PURE__ */Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),readDepth2=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty2=value=>!value.available;function EverfurRecordDocument(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onBack"]);/* @__PURE__ */
|
|
595
601
|
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(DocumentBody,{...rest,style:style})})}function documentIsEmpty(record,depth){return record.identity.length===0&&record.entities.length===0&&record.forwardLooking.length===0&&(depth===null||depth.labResults.length===0&&depth.physicalExams.length===0&&depth.clinicianNotes.length===0)}function DocumentBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onBack:onBack,onOpenUrl:onOpenUrl,style:style}){let styles=useScreenStyles(),local=useLocalStyles7(),theme=useEverfurTheme(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),depth=useRecordsDepthRead(petRef,readDepth2,depthEmpty2),pdf=useRecordPdfLink(petRef);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,record=records.record,[shareFailed,setShareFailed]=react.useState(false),download=()=>{setShareFailed(false),pdf.pdfLink().then(result=>{if(!result.ok)return;callHostAsync(onOpenUrl??(target=>shareFileLinkViaOs(target)),result.value.downloadUrl,"record_pdf").then(outcome=>{!outcome.ok&&!onOpenUrl&&setShareFailed(true)})})},body,documentShown=false;if(records.status==="loading"||depth.status==="loading"&&record!==null)body=/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:DASHBOARD_COPY.loading,testID:"record-document-loading",children:/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{color:theme.color.brandInk})});else if(records.status==="error"){let errorView=selectErrorView(records,canGrant);body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?()=>{records.refresh(),depth.refresh()}:void 0,testID:"record-document-error"}):renderErrorFamily(records,onGrant,canGrant,consentText)}else record===null||documentIsEmpty(record,depthView)?body=/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.centered,testID:"record-document-empty",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.emptyText,children:COPY.empty})}):(documentShown=true,body=/* @__PURE__ */jsxRuntime.jsx(RecordDocument,{record:record,depth:depthView,petName:petName,wordmark:theme.meta.displayName})/* @__PURE__ */);return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,local.root,style],children:[
|
|
596
602
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:COPY.titleFor(petName),variant:"document",onBack:onBack,testID:"record-document-header",right:pdf.available&&documentShown?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:download,disabled:pdf.preparing,accessibilityRole:"button",accessibilityLabel:COPY.download,accessibilityState:{disabled:pdf.preparing,busy:pdf.preparing},hitSlop:8,style:local.download,testID:"record-document-download",children:pdf.preparing?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:theme.slots.header?.textColor??theme.color.brandInk}):/* @__PURE__ */jsxRuntime.jsx(DownloadGlyph,{})}):void 0}),pdf.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.errorText,local.inset],accessibilityRole:"alert",children:pdf.error.displayMessage}):shareFailed?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.errorText,local.inset],accessibilityRole:"alert",testID:"record-document-share-failed",children:SHARE_COPY.toasts.pdfShareSheet}):null,
|
|
597
603
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),
|
|
@@ -622,7 +628,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[local.row,index>0?local.rowDivid
|
|
|
622
628
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.fieldLabel,children:bodySystemLabel(system.system)}),
|
|
623
629
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.fieldValue,children:system.finding})]},system.system))]},exam.examId)),"record-document-exams"):null,depth&&depth.clinicianNotes.length>0?section(COPY.clinicianNotes,depth.clinicianNotes.map((note,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[local.block,index>0?local.rowDivider:null],children:[note.observedOn?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.blockDate,children:formatRecordsDate(note.observedOn)}):null,note.sections.filter(s=>s.text).map((s,i)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.noteSection,children:[
|
|
624
630
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.noteLabel,children:soapSectionLabel(s.section)}),
|
|
625
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.noteBody,children:s.text})]},`${s.section}-${i}`))]},note.noteId)),"record-document-notes"):null,disclaimerRepeatsFootnote(record.disclaimer)?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.disclaimer,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.disclaimerText,children:record.disclaimer})})]})}function useLocalStyles7(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles7(theme),[theme])}function makeLocalStyles7(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,
|
|
631
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.noteBody,children:s.text})]},`${s.section}-${i}`))]},note.noteId)),"record-document-notes"):null,disclaimerRepeatsFootnote(record.disclaimer)?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.disclaimer,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.disclaimerText,children:record.disclaimer})})]})}function useLocalStyles7(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles7(theme),[theme])}function makeLocalStyles7(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),mono=(fontSize,fg)=>({...face(theme,"mono"),fontSize:fontSize,lineHeight:fontSize+space.xs-1,color:fg,letterSpacing:type.letterSpacing.eyebrow/2,textTransform:"uppercase"});return reactNative.StyleSheet.create({root:{backgroundColor:color.surface},inset:{paddingHorizontal:space.lg},download:{width:space.xxl+space.xs+space.xs/2,height:space.xxl+space.xs+space.xs/2,borderRadius:radius.pill,alignItems:"center",justifyContent:"center"},centered:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xxl,minHeight:space.xxl*3+space.xl},emptyText:{...text4(type.size.body,type.lineHeight.normal,color.text.muted,"medium"),textAlign:"center"},page:{paddingHorizontal:space.lg+space.xs,paddingBottom:space.xxl+space.lg},letterhead:{alignItems:"center",paddingTop:space.md,paddingBottom:space.lg+space.xs+space.xs/2,borderBottomWidth:2,borderBottomColor:color.brandInk,gap:space.xs+space.xs/2,marginBottom:space.sm},wordmark:{...text4(type.size.heading,type.lineHeight.snug,color.brandInk,"bold"),letterSpacing:type.letterSpacing.headerBrand},docTitle:{...mono(type.size.caption,color.brandInk),marginTop:space.sm+space.xs/2,letterSpacing:type.letterSpacing.eyebrow+.4},petName:text4(type.size.verdict+space.xs/2,type.lineHeight.tight,color.text.primary),generated:{...mono(type.size.tiny,color.text.muted),textTransform:"none"},section:{marginTop:space.lg+space.xs+space.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:space.sm+space.xs/2,marginBottom:space.sm},sectionTitle:mono(type.size.tiny,color.brandInk),rule:{flex:1,height:hairline,backgroundColor:color.borderHairlineGreen},row:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.md+space.xs/2,paddingVertical:space.sm+1},rowDivider:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},rowFlag:{backgroundColor:color.badgeBgCritical,marginHorizontal:-space.sm,paddingHorizontal:space.sm,borderRadius:radius.xs},rowMain:{flexShrink:1},rowRight:{alignItems:"flex-end",gap:space.xs/2},rowLabel:{flexShrink:1,...text4(type.size.body,type.lineHeight.normal,color.text.primary,"medium")},rowValue:{...text4(type.size.body,type.lineHeight.normal,color.text.primary,"bold"),textAlign:"right"},rowValueAlert:{color:color.danger},rowMeta:{marginTop:space.xs/2,...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},markerStatus:mono(type.size.micro,color.text.muted),block:{paddingVertical:space.sm+space.xs/2},blockDate:{...mono(type.size.tiny,color.text.muted),marginBottom:space.xs+space.xs/2},fieldRow:{flexDirection:"row",alignItems:"flex-start",gap:space.md+space.xs/2,paddingVertical:space.xs-1},fieldLabel:{width:120,...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted,"medium")},fieldValue:{flex:1,...text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary,"medium")},noteSection:{marginTop:space.sm},noteLabel:{...mono(type.size.tiny,color.brandInk),marginBottom:space.xs/2},noteBody:text4(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary),disclaimer:{marginTop:radius.xl,paddingTop:space.md+space.xs/2,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},disclaimerText:text4(type.size.tiny,type.lineHeight.relaxed,color.text.muted)})}function ShareSheet({petRef:petRef,petName:petName,onClose:onClose,onNavigate:onNavigate,onOpenUrl:onOpenUrl,onCopy:onCopy}){let styles=useStyles11(),screen=useScreenStyles(),shares=useRecordShares(petRef),[notice,setNotice]=react.useState(null),[pendingRevokeId,setPendingRevokeId]=react.useState(null),[audience,setAudience]=react.useState("vet"),[email2,setEmail]=react.useState(""),exportable=shares.available&&!shares.consentRequired,linkWritable=shares.features.sharing!==false,mintable=exportable&&linkWritable,armed=shares.shareAudiences.length>0,scope=shares.shareAudiences.find(served=>served.audience===audience)??null,included=scope!==null?shareIncludedLines(scope,shares.features):[],open=(url,kind)=>{let opener=onOpenUrl??((target,what)=>what==="share_link"?shareLinkViaOs(target):shareFileLinkViaOs(target)),failure=kind==="share_link"?SHARE_COPY.toasts.shareSheet:SHARE_COPY.toasts.pdfShareSheet;callHostAsync(opener,url,kind).then(outcome=>{outcome.ok||setNotice(failure)})},onCreateLink=()=>{setNotice(null),shares.createLink(armed?audience:void 0).then(result=>{result.ok?open(result.value.shareUrl,"share_link"):setNotice(shareErrorMessage(result.error,"create"))})},onSend=()=>{if(shares.sending)return;setNotice(null);let address=email2.trim();if(address.length===0){setNotice(SHARE_COPY.addEmailFor(petName));return}if(!isShareRecipientEmail(address)){setNotice(SHARE_COPY.emailInvalid);return}shares.sendEmail({recipientEmail:address,recipientKind:audience}).then(result=>{result.ok?(setEmail(""),setNotice(SHARE_COPY.toasts.sentTo(address))):setNotice(shareErrorMessage(result.error,"email"))})},onDownload=()=>{setNotice(null),shares.pdfLink().then(result=>{result.ok?open(result.value.downloadUrl,"record_pdf"):setNotice(shareErrorMessage(result.error,"download"))})},onCopyRow=row=>{if(!onCopy||row.shareUrl===null)return;let url=row.shareUrl;callHostAsync(onCopy,url).then(outcome=>setNotice(outcome.ok?SHARE_COPY.toasts.copiedNative:SHARE_COPY.toasts.copyFailedNative(url)))},onConfirmRevoke=shareId=>{shares.revoke(shareId).then(result=>{setPendingRevokeId(null),setNotice(result.ok?SHARE_COPY.toasts.turnedOff:shareErrorMessage(result.error,"revoke"))})};/* @__PURE__ */
|
|
626
632
|
return jsxRuntime.jsx(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:onClose,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.backdrop,children:[
|
|
627
633
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:ABSOLUTE_FILL,accessibilityRole:"button",accessibilityLabel:SHARE_COPY.closeSheetA11y,onPress:onClose}),
|
|
628
634
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheet,accessibilityViewIsModal:true,testID:"share-record-sheet",children:[
|
|
@@ -642,7 +648,7 @@ return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setAudience(option),acc
|
|
|
642
648
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.includedLine,styles.includedText],testID:`share-included-line-${line2}`,children:line2})]},line2))]}):null,onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.previewNative,onPress:()=>{onClose(),onNavigate({name:"document"})},testID:"share-view-document"}):null,
|
|
643
649
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:SHARE_COPY.sendTo}),
|
|
644
650
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.TextInput,{accessibilityLabel:SHARE_COPY.sendTo,style:styles.field,value:email2,placeholder:SHARE_COPY.sendToPlaceholder,placeholderTextColor:styles.placeholder.color,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,autoComplete:"email",maxLength:SHARE_RECIPIENT_EMAIL_MAX,editable:!shares.sending,returnKeyType:"send",onChangeText:setEmail,onSubmitEditing:onSend,testID:"share-email-input"}),
|
|
645
|
-
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.sending?SHARE_COPY.sending:SHARE_COPY.send,busy:shares.sending,onPress:onSend,testID:"share-email-send"})]}):onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.previewNative,onPress:()=>{onClose(),onNavigate({name:"document"})},testID:"share-view-document"}):null,mintable?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.creating?SHARE_COPY.creatingLink:SHARE_COPY.shareLinkNative,kind:"outline",busy:shares.creating,onPress:onCreateLink,testID:"share-create-link"}):null,
|
|
651
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.sending?SHARE_COPY.sending:SHARE_COPY.send,busy:shares.sending,onPress:onSend,testID:"share-email-send"})]}):onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.previewNative,onPress:()=>{onClose(),onNavigate({name:"document"})},testID:"share-view-document"}):null,mintable?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.creating?SHARE_COPY.creatingLink:SHARE_COPY.shareLinkNative,kind:"outline",busy:shares.creating,onPress:onCreateLink,testID:"share-create-link"}):null,exportable?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.preparingPdf?SHARE_COPY.preparingPdf:SHARE_COPY.downloadPdf,kind:"outline",busy:shares.preparingPdf,onPress:onDownload,testID:"share-download-pdf"}):null,mintable?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.terms,testID:"share-link-terms",children:SHARE_COPY.linkTerms}):null]}),shares.consentRequired?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.stateCard,testID:"share-consent-off",children:[
|
|
646
652
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.stateTitle,accessibilityRole:"header",children:SHARE_COPY.consentOffTitle}),
|
|
647
653
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.stateBody,children:SHARE_COPY.consentOffBody}),
|
|
648
654
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.retry,kind:"outline",onPress:shares.refresh,testID:"share-consent-retry"})]}):null,notice?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.notice,accessibilityRole:"alert",accessibilityLiveRegion:"polite",testID:"share-notice",children:notice}):null,sharesListShown(shares)?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,children:[
|
|
@@ -656,18 +662,17 @@ return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setAudience(option),acc
|
|
|
656
662
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.statusLine,children:[
|
|
657
663
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.statusDot,{backgroundColor:row.active?styles.active.color:styles.inactive.color}],accessibilityElementsHidden:true,importantForAccessibility:"no"}),
|
|
658
664
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.status,children:row.statusLabel}),
|
|
659
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.expiry,children:row.expiryLabel})]}),row.createdLabel?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.created,children:row.createdLabel}):null]}),row.shareUrl!==null&&!onCopy?/* @__PURE__ */jsxRuntime.jsx(Text,{selectable:true,style:styles.url,testID:`share-url-${row.shareId}`,children:row.shareUrl}):null,pendingRevokeId===row.shareId?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.confirm,testID:`share-revoke-confirm-${row.shareId}`,children:[
|
|
665
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.expiry,children:row.expiryLabel})]}),row.createdLabel?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.created,children:row.createdLabel}):null]}),row.shareUrl!==null&&!onCopy?/* @__PURE__ */jsxRuntime.jsx(Text,{selectable:true,style:styles.url,testID:`share-url-${row.shareId}`,children:row.shareUrl}):null,linkWritable&&pendingRevokeId===row.shareId?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.confirm,testID:`share-revoke-confirm-${row.shareId}`,children:[
|
|
660
666
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.confirmText,children:SHARE_COPY.confirmTurnOff}),
|
|
661
667
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowActions,children:[
|
|
662
668
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.revokingId===row.shareId?SHARE_COPY.turningOff:SHARE_COPY.turnOff,kind:"danger",busy:shares.revokingId===row.shareId,onPress:()=>onConfirmRevoke(row.shareId),testID:`share-revoke-do-${row.shareId}`}),
|
|
663
|
-
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.keep,kind:"outline",disabled:shares.revokingId===row.shareId,onPress:()=>setPendingRevokeId(null),testID:`share-revoke-cancel-${row.shareId}`})]})]}):/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowActions,children:[onCopy?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.copyLink,kind:"outline",disabled:row.shareUrl===null,accessibilityHint:row.a11yLabel,onPress:()=>onCopyRow(row),testID:`share-copy-${row.shareId}`}):null,
|
|
664
|
-
/* @__PURE__ */jsxRuntime.jsx(
|
|
665
|
-
|
|
666
|
-
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(RecordBody,{...rest,style:style})})}function RecordBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,onOpenUrl:onOpenUrl,onCopy:onCopy,style:style}){let styles=useScreenStyles(),local=useLocalStyles8(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),depth=useRecordsDepthRead(petRef,readDepth3,depthEmpty3),factEdit=useRecordFactEdit(petRef),shareProbe=useRecordsDepthProbe(petRef),[sharing,setSharing]=react.useState(false);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,record=records.record,retry=()=>{records.refresh(),depth.refresh()},shareable=onNavigate!==void 0||shareProbe.lit===true,body;if(records.status==="loading"||depth.status==="loading"&&record!==null&&!record.isEmpty)body=/* @__PURE__ */jsxRuntime.jsx(DashboardSkeleton,{testID:"everfur-record-loading"});else if(records.status==="error"){let errorView=selectErrorView(records,canGrant);body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?retry:void 0,testID:"everfur-record-error"}):renderErrorFamily(records,onGrant,canGrant,consentText)}else if(record===null||record.isEmpty){let inReview=depthView?.completeness?.documentsInReview??0;body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.content,testID:"everfur-record-empty",children:[
|
|
669
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.keep,kind:"outline",disabled:shares.revokingId===row.shareId,onPress:()=>setPendingRevokeId(null),testID:`share-revoke-cancel-${row.shareId}`})]})]}):/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowActions,children:[onCopy?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.copyLink,kind:"outline",disabled:row.shareUrl===null,accessibilityHint:row.a11yLabel,onPress:()=>onCopyRow(row),testID:`share-copy-${row.shareId}`}):null,linkWritable?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.turnOff,kind:"danger",accessibilityLabel:SHARE_COPY.turnOffA11y(row.actionContext),onPress:()=>setPendingRevokeId(row.shareId),testID:`share-ask-revoke-${row.shareId}`}):null]})]},row.shareId))})]}):null]}),
|
|
670
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:screen.inset})]})]})})}function useStyles11(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles13(theme),[theme])}function makeStyles13(theme){let{color:color,space:space,radius:radius,type:type}=theme,touch=space.xxl+space.md,hairline=reactNative.StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),{dialog:dialog,tab:tab,input:input,card:card}=theme.slots,dialogText=slotText(dialog);return reactNative.StyleSheet.create({active:{color:color.success},inactive:{color:color.text.muted},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:"rgba(0,0,0,0.4)"},sheet:{backgroundColor:color.surface,borderTopLeftRadius:radius.xl-1,borderTopRightRadius:radius.xl-1,paddingHorizontal:space.lg+space.xs+space.xs/2,paddingTop:space.md,paddingBottom:radius.xl,maxHeight:"88%",gap:space.md,...sheetSlotBox(dialog)},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm},headerText:{flex:1,gap:space.xs},title:{...text4(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...dialogText},helper:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...dialogText},terms:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center"},closeButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},closeGlyph:{...text4(type.size.verdict,type.lineHeight.tight,color.text.primary),...dialogText},scroll:{flexGrow:0},body:{gap:space.lg,paddingBottom:space.sm},actions:{gap:space.sm},form:{gap:space.sm,paddingBottom:space.sm},fieldLabel:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.secondary,"medium")},choices:{flexDirection:"row",gap:space.sm},choice:{flex:1,minHeight:touch,alignItems:"center",justifyContent:"center",paddingHorizontal:space.sm,borderRadius:radius.md,borderWidth:hairline,borderColor:color.borderHairlineGreen,backgroundColor:color.surface,...slotBox(tab,hairline)},choiceOn:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:color.brandSoft},choiceTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"medium"),...slotText(tab)},choiceTitleOn:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},included:{gap:space.xs},includedRow:{flexDirection:"row",gap:space.sm},includedLine:text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary),includedText:{flex:1},field:{...text4(type.size.body,type.lineHeight.normal,color.text.primary),minHeight:touch,paddingHorizontal:space.md,borderRadius:radius.sm,borderWidth:hairline,borderColor:color.borderHairlineGreen,backgroundColor:color.surface,...slotBox(input,hairline),...slotText(input)},placeholder:{color:color.text.placeholder},notice:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.secondary),padding:space.md,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft},section:{gap:space.sm},sectionLabel:{...text4(type.size.bodyTight,type.lineHeight.snug,color.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},stateCard:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...slotBox(card,hairline)},stateTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},stateBody:text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),list:{gap:space.md},row:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...slotBox(card,hairline)},statusLine:{flexDirection:"row",alignItems:"center",gap:space.sm},statusDot:{width:space.sm,height:space.sm,borderRadius:space.xs},status:{...text4(type.size.bodyTight,type.lineHeight.snug,color.text.primary,"bold")},expiry:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted)},created:text4(type.size.tiny,type.lineHeight.normal,color.text.muted),url:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:space.sm},confirm:{gap:space.sm},confirmText:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary,"medium")}})}var readDepth3=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty3=value=>!value.available;function EverfurRecordDetail(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]);/* @__PURE__ */
|
|
671
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(RecordBody,{...rest,style:style})})}function RecordBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,onOpenUrl:onOpenUrl,onCopy:onCopy,style:style}){let styles=useScreenStyles(),local=useLocalStyles8(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),depth=useRecordsDepthRead(petRef,readDepth3,depthEmpty3),factEdit=useRecordFactEdit(petRef),shareProbe=useRecordsDepthProbe(petRef),[sharing,setSharing]=react.useState(false);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,record=records.record,retry=()=>{records.refresh(),depth.refresh()},shareable=onNavigate!==void 0||shareProbe.lit===true,clinicDecision=useCapability("recordsClinic"),canRequestFromClinics=onNavigate!==void 0&&(clinicDecision.enabled||clinicDecision.isPending),body;if(records.status==="loading"||depth.status==="loading"&&record!==null&&!record.isEmpty)body=/* @__PURE__ */jsxRuntime.jsx(DashboardSkeleton,{testID:"everfur-record-loading"});else if(records.status==="error"){let errorView=selectErrorView(records,canGrant);body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?retry:void 0,testID:"everfur-record-error"}):renderErrorFamily(records,onGrant,canGrant,consentText)}else if(record===null||record.isEmpty){let inReview=depthView?.completeness?.documentsInReview??0;body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.content,testID:"everfur-record-empty",children:[
|
|
667
672
|
/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",message:inReview>0?RECORD_SCREEN_COPY.inReview(inReview):void 0}),
|
|
668
673
|
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record?.disclaimer??""})]})}else body=/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:local.content,testID:"everfur-record",children:/* @__PURE__ */jsxRuntime.jsx(RecordSections,{record:record,depth:depthView,petName:petName,onNavigate:onNavigate,onAsk:onAsk,factEdit:factEdit})});/* @__PURE__ */
|
|
669
674
|
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
670
|
-
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:RECORD_SCREEN_COPY.title,onBack:onBack,testID:"everfur-record-header",right:shareable||
|
|
675
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:RECORD_SCREEN_COPY.title,onBack:onBack,testID:"everfur-record-header",right:shareable||canRequestFromClinics?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[canRequestFromClinics&&onNavigate?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onNavigate({name:"clinicBatch"}),accessibilityRole:"button",accessibilityLabel:RECORD_SCREEN_COPY.requestClinicsA11y,hitSlop:8,style:local.share,testID:"everfur-record-request-clinics",children:/* @__PURE__ */jsxRuntime.jsx(SendGlyph,{})}):null,shareable?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setSharing(true),accessibilityRole:"button",accessibilityLabel:SHARE_COPY.openA11yFor(petName),hitSlop:8,style:local.share,testID:"everfur-record-share",children:/* @__PURE__ */jsxRuntime.jsx(ShareGlyph,{})}):null]}):void 0}),
|
|
671
676
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),sharing?/* @__PURE__ */jsxRuntime.jsx(ShareSheet,{petRef:petRef,petName:petName,onClose:()=>setSharing(false),onNavigate:onNavigate,...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{}}):null,
|
|
672
677
|
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function useLocalStyles8(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles8(theme),[theme])}function makeLocalStyles8(theme){let{space:space,radius:radius}=theme;return reactNative.StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xxl+space.sm,gap:space.lg+space.xs},share:{width:space.xxl+space.sm,height:space.xxl+space.sm,borderRadius:radius.pill,alignItems:"center",justifyContent:"center"}})}function useRecordsPullToRefresh(refresh,testID){let theme=useEverfurTheme(),[refreshing,setRefreshing]=react.useState(false),onRefresh=react.useCallback(()=>{setRefreshing(true),refresh().finally(()=>setRefreshing(false))},[refresh]);/* @__PURE__ */
|
|
673
678
|
return jsxRuntime.jsx(reactNative.RefreshControl,{refreshing:refreshing,onRefresh:onRefresh,tintColor:theme.color.brandInk,colors:[theme.color.brandInk],testID:testID})}function EverfurRecordsUpload(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]);/* @__PURE__ */
|
|
@@ -680,19 +685,19 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
|
680
685
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.title,accessibilityRole:"header",children:UPLOAD_COPY.screenTitle}),
|
|
681
686
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.subtitle,children:UPLOAD_COPY.subtitle(petName)})]}),
|
|
682
687
|
/* @__PURE__ */jsxRuntime.jsx(UploadRecordCard,{records:records,requestId:null,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onNavigate?requestId2=>onNavigate({name:"request",requestId:requestId2}):void 0})]}),
|
|
683
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function UploadRecordCard({records:records,requestId:requestId2,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onDone}){let styles=useScreenStyles(),local=useLocalStyles9(),{runtime:runtime}=useEverfurContext(),camera=runtime.registry.services.camera,types=records.uploadContentTypes,photosLive=acceptsPhotos(types),canTakePhoto=photosLive&&isCaptureAvailable(camera),canChoosePhotos=photosLive&&onPickPhotos!==void 0,photoCopy=canTakePhoto||canChoosePhotos,[pickError,setPickError]=react.useState(null),[batchCount,setBatchCount]=react.useState(0),resolvedId=react.useRef(requestId2),failedFiles=react.useRef([]),rows=records.uploadQueue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,failed=rows.filter(item=>item.status==="failed").length,settled=!records.isUploading&&batchCount>0,run=react.useCallback(async picked=>{let{uploadable:uploadable,skipped:skipped}=classifyPick(picked,types),refusal=skippedFilesMessage(skipped,photoCopy);if(uploadable.length===0){refusal!==null&&setPickError(refusal);return}setPickError(refusal);let target=resolvedId.current;if(target===null){let created=await records.createRequest(`records-upload-${Date.now().toString(36)}`);if(!created.ok){setPickError(UPLOAD_COPY.errors.start);return}target=created.value.id,resolvedId.current=target}setBatchCount(n=>n+1);let outcome=await records.uploadDocuments(target,uploadable);failedFiles.current=outcome.flatMap((item,index)=>item.status==="failed"&&uploadable[index]!==void 0?[uploadable[index]]:[])},[records,types,photoCopy]),pickFrom=react.useCallback(picker=>{!picker||!canUpload||callHostAsync(picker).then(outcome=>{if(!outcome.ok){setPickError(UPLOAD_COPY.errors.startPlain);return}let picked=outcome.value;picked!==null&&run(Array.isArray(picked)?picked:[picked])})},[canUpload,run]),
|
|
688
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function UploadRecordCard({records:records,requestId:requestId2,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onDone}){let styles=useScreenStyles(),local=useLocalStyles9(),{runtime:runtime}=useEverfurContext(),camera=runtime.registry.services.camera,types=records.uploadContentTypes,photosLive=acceptsPhotos(types),canTakePhoto=photosLive&&isCaptureAvailable(camera),canChoosePhotos=photosLive&&onPickPhotos!==void 0,photoCopy=canTakePhoto||canChoosePhotos,[pickError,setPickError]=react.useState(null),[batchCount,setBatchCount]=react.useState(0),resolvedId=react.useRef(requestId2),failedFiles=react.useRef([]),rows=records.uploadQueue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,failed=rows.filter(item=>item.status==="failed").length,settled=!records.isUploading&&batchCount>0,run=react.useCallback(async picked=>{let{uploadable:uploadable,skipped:skipped}=classifyPick(picked,types),refusal=skippedFilesMessage(skipped,photoCopy);if(uploadable.length===0){refusal!==null&&setPickError(refusal);return}setPickError(refusal);let target=resolvedId.current;if(target===null){let created=await records.createRequest(`records-upload-${Date.now().toString(36)}`);if(!created.ok){setPickError(UPLOAD_COPY.errors.start);return}target=created.value.id,resolvedId.current=target}setBatchCount(n=>n+1);let outcome=await records.uploadDocuments(target,uploadable);failedFiles.current=outcome.flatMap((item,index)=>item.status==="failed"&&uploadable[index]!==void 0?[uploadable[index]]:[])},[records,types,photoCopy]),pickFrom=react.useCallback(picker=>{!picker||!canUpload||callHostAsync(picker).then(outcome=>{if(!outcome.ok){setPickError(UPLOAD_COPY.errors.startPlain);return}let picked=outcome.value;picked!==null&&run(Array.isArray(picked)?picked:[picked])})},[canUpload,run]),pick2=react.useCallback(()=>{pickFrom(onPickDocument)},[pickFrom,onPickDocument]),pickPhotos=react.useCallback(()=>{pickFrom(onPickPhotos)},[pickFrom,onPickPhotos]),takePhoto=react.useCallback(()=>{!canTakePhoto||!canUpload||callHostAsync(()=>camera.capture(captureOptionsFor("photo"))).then(outcome=>{if(!outcome.ok)return;let handle=fileHandleFromMedia(outcome.value);if(handle.sizeBytes===void 0){setPickError(UPLOAD_COPY.errors.startPlain);return}run([handle])})},[camera,canTakePhoto,canUpload,run]),retryFailed=react.useCallback(()=>{run(failedFiles.current)},[run]);/* @__PURE__ */
|
|
684
689
|
return jsxRuntime.jsxs(reactNative.View,{style:local.card,testID:"records-upload-card",children:[
|
|
685
690
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:UPLOAD_COPY.cardTitle}),
|
|
686
691
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardSubtitle,children:photoCopy?UPLOAD_PHOTO_COPY.note:UPLOAD_COPY.cardSubtitle}),pickError?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:pickError})}):null,
|
|
687
692
|
/* @__PURE__ */jsxRuntime.jsx(UploadQueue,{records:records}),records.isUploading?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.uploadingRow,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.progressText,children:UPLOAD_COPY.uploading(done,rows.length)})}):settled?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.settled,children:[done>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.success,accessibilityRole:"alert",children:UPLOAD_COPY.received(done)}):null,failed>0?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.retryFailed(failed),kind:"link",onPress:retryFailed,testID:"records-upload-retry-failed"}):null,
|
|
688
693
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:UPLOAD_COPY.haveMore}),photoCopy?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardSubtitle,children:UPLOAD_PHOTO_COPY.haveMoreLead}):null,
|
|
689
694
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.settledActions,children:[
|
|
690
|
-
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.addMore,kind:"link",accessibilityLabel:UPLOAD_COPY.addMoreA11y,disabled:!canUpload,onPress:
|
|
695
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.addMore,kind:"link",accessibilityLabel:UPLOAD_COPY.addMoreA11y,disabled:!canUpload,onPress:pick2,testID:"records-upload-another"}),onDone&&resolvedId.current!==null&&done>0?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.done,accessibilityLabel:UPLOAD_COPY.doneA11y,onPress:()=>onDone(resolvedId.current),testID:"records-upload-done"}):null]})]}):photoCopy?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.actions,children:[canTakePhoto?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.action,children:[
|
|
691
696
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_PHOTO_COPY.takePhoto,kind:"outline",accessibilityLabel:uploadActionA11y(UPLOAD_PHOTO_COPY.takePhoto,UPLOAD_PHOTO_COPY.takePhotoMeta),disabled:!canUpload,onPress:takePhoto,testID:"records-upload-take-photo"}),
|
|
692
697
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.takePhotoMeta})]}):null,canChoosePhotos?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.action,children:/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_PHOTO_COPY.choosePhotos,kind:"outline",disabled:!canUpload,onPress:pickPhotos,testID:"records-upload-choose-photos"})}):null,
|
|
693
698
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.action,children:[
|
|
694
|
-
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:
|
|
695
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.chooseFileMeta})]})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:
|
|
699
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:pick2,testID:"records-upload-choose"}),
|
|
700
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.chooseFileMeta})]})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:pick2,testID:"records-upload-choose"})]})}function useLocalStyles9(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles9(theme),[theme])}var UPLOAD_GLYPH=24;function makeLocalStyles9(theme){let{color:color,space:space,radius:radius,type:type}=theme,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({content:{padding:space.lg+space.xs,gap:space.lg+space.xs},header:{gap:space.sm,alignItems:"center"},iconBubble:{width:space.xxl+space.lg+space.xs,height:space.xxl+space.lg+space.xs,borderRadius:radius.pill,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...text4(type.size.heading+space.xs/2,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),textAlign:"center"},subtitle:{...text4(type.size.body,type.lineHeight.normal,color.text.muted),textAlign:"center",maxWidth:340},card:{borderRadius:radius.lg,backgroundColor:color.surface,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.md,...slotBox(theme.slots.card,1)},cardTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...slotText(theme.slots.card)},cardSubtitle:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...slotText(theme.slots.card)},uploadingRow:{flexDirection:"row",alignItems:"center",gap:space.sm},progressText:{flex:1,...text4(type.size.bodyTight,type.lineHeight.normal,color.text.secondary)},settled:{gap:space.sm},success:text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary),settledActions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:space.sm},actions:{gap:space.md},action:{gap:space.xs},actionMeta:text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted)})}function EverfurRecordsRequest(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]);/* @__PURE__ */
|
|
696
701
|
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(RequestBody,{...rest,style:style})})}function RequestBody({petRef:petRef,petName:petName,requestId:requestId2,controller:controller,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,onNavigate:onNavigate,onBack:onBack,style:style,nowMs:nowMs}){let styles=useScreenStyles(),{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:uploadTransport?{petRef:petRef,uploadTransport:uploadTransport,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),request=records.requests.find(r=>r.id===requestId2)??null,canUpload=canUploadRecords(onPickDocument)&&(controller!==void 0||uploadTransport!==void 0||isUploadTransportAvailable(runtime.registry.services.uploadTransport)),title=request?selectRequestTitle(request):"",refreshControl=useRecordsPullToRefresh(records.refresh,"records-request-refresh"),body;return records.status==="loading"&&request===null?body=/* @__PURE__ */jsxRuntime.jsx(RequestSkeleton,{testID:"records-request-loading"}):records.status==="error"&&records.error?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(records.error),message:records.error.displayMessage,onAction:records.error.retryable?records.refresh:void 0,testID:"records-request-error"}):request===null?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_requests",testID:"records-request-missing"}):userRef===null?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"error",testID:"records-request-error"}):body=/* @__PURE__ */jsxRuntime.jsx(RequestDetail,{petName:petName,request:request,records:records,canUpload:canUpload,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,onNavigate:onNavigate,nowMs:nowMs,refreshControl:refreshControl},JSON.stringify([userRef,scopeEpoch,request.id])),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
697
702
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:title,onBack:onBack,testID:"records-request-header"}),
|
|
698
703
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.KeyboardAvoidingView,{behavior:"padding",style:styles.body,children:body}),
|
|
@@ -720,27 +725,185 @@ return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.conte
|
|
|
720
725
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.confirmTitle,accessibilityRole:"header",children:RECORDS_RECOVERY_COPY.cancelQuestion}),
|
|
721
726
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bodyText,children:RECORDS_RECOVERY_COPY.cancelConsequence}),
|
|
722
727
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:form.busy&&lastAction==="revoke"?REQUEST_SCREEN_COPY.cancelling:REQUEST_SCREEN_COPY.cancel,kind:"danger",busy:form.busy&&lastAction==="revoke",onPress:()=>run("revoke",form.revoke),testID:"records-revoke-do"}),
|
|
723
|
-
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_RECOVERY_COPY.keepRequest,kind:"outline",disabled:form.busy,onPress:form.keepRequest,testID:"records-revoke-keep"})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.cancel,kind:"danger",disabled:form.busy,onPress:form.askRevoke,testID:"records-revoke"}):null]})}function useLocalStyles10(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles10(theme),[theme])}function makeLocalStyles10(theme){let{color:color,space:space,radius:radius,type:type}=theme,
|
|
724
|
-
return
|
|
728
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_RECOVERY_COPY.keepRequest,kind:"outline",disabled:form.busy,onPress:form.keepRequest,testID:"records-revoke-keep"})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.cancel,kind:"danger",disabled:form.busy,onPress:form.askRevoke,testID:"records-revoke"}):null]})}function useLocalStyles10(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles10(theme),[theme])}function makeLocalStyles10(theme){let{color:color,space:space,radius:radius,type:type}=theme,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.lg+space.xs/2},readyCta:{minHeight:space.xxl+space.lg+space.xs/2},sent:{gap:space.xs},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,gap:space.md,...slotBox(recordCardSlot(theme.slots),1)},cardTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...slotText(recordCardSlot(theme.slots))},detailRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.lg},detailValue:{flexShrink:1,textAlign:"right",...text4(type.size.body,type.lineHeight.normal,color.text.primary)},failureCard:{borderRadius:radius.lg-space.xs,borderWidth:1,padding:space.md+space.xs/2,gap:space.md},failureCritical:{borderColor:color.badgeBgCritical,backgroundColor:color.badgeBgCritical},failureCaution:{borderColor:color.badgeBgCaution,backgroundColor:color.badgeBgCaution},failureTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},failureTitleCritical:{color:color.danger},failureTitleCaution:{color:color.warningStrong},emailBlock:{gap:space.sm},callBlock:{gap:space.sm},block:{gap:space.sm},confirmTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")}})}var REF_MAX=128;var ICONS=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame"]),obj=value=>value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null,str4=(value,max=1e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null,kindOf=value=>typeof value=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(value)?value:null,iconOf=value=>typeof value=="string"&&ICONS.has(value)?value:null;function imageOf(value){let s=str4(value,2048);return s===null||/\s/.test(s)?null:/^https:\/\/[^/]/i.test(s)||/^\/(?![/\\])/.test(s)?s:null}var idOf=value=>typeof value=="number"&&Number.isInteger(value)?String(value):str4(value,REF_MAX);function weightOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:null}function clean(fields){/* @__PURE__ */
|
|
729
|
+
return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str4(v,len),max);function focusOf(value){let o=obj(value),kicker=str4(o?.kicker,120),title=str4(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let label=str4(obj(r)?.label,60);return label===null?null:clean({label:label,kind:kindOf(obj(r)?.kind)})},6),risk:str4(risk?.lead,300)===null?null:clean({lead:str4(risk?.lead,300),body:str4(risk?.body),kind:kindOf(risk?.kind)}),odds:str4(odds?.label,120)===null||str4(odds?.from,20)===null||str4(odds?.to,20)===null?null:clean({label:str4(odds?.label,120),tag:str4(odds?.tag,40),from:str4(odds?.from,20),to:str4(odds?.to,20),toLabel:str4(odds?.toLabel,120)}),quote:str4(quote?.kicker,120)===null||str4(quote?.text)===null?null:clean({kicker:str4(quote?.kicker,120),tag:str4(quote?.tag,40),text:str4(quote?.text)}),jump:str4(jump?.title,300)===null||str4(jump?.go,60)===null?null:clean({title:str4(jump?.title,300),go:str4(jump?.go,60)})})}function routineOf(value){let o=obj(value),title=str4(o?.title,300),steps=listOf(o?.steps,r=>{let s=obj(r),t=str4(s?.title,300);return t===null?null:clean({title:t,body:str4(s?.body),source:str4(s?.source,200)})});return title===null||steps===null?null:clean({title:title,label:str4(o?.label,60),steps:steps})}function pickOf(value){let o=obj(value),title=str4(o?.title,300);if(o===null||title===null)return null;let rating=obj(o.rating),reviews=obj(o.reviews),why=obj(o.why),score=obj(why?.score),dose=obj(o.dose),ingredients=obj(o.ingredients),reviewItems=listOf(reviews?.items,r=>{let v=obj(r),stars=v?.stars,text4=str4(v?.text),by=str4(v?.by,80);return typeof stars!="number"||!Number.isFinite(stars)||stars<1||stars>5||text4===null||by===null?null:clean({stars:Math.round(stars),text:text4,by:by})},5),whyRows=listOf(why?.rows,r=>{let v=obj(r),chip=str4(v?.chip,40),t=str4(v?.title,300);return chip===null||t===null?null:clean({chip:chip,kind:kindOf(v?.kind),title:t,body:str4(v?.body)})}),stats=listOf(dose?.stats,r=>{let v=obj(r),val=str4(v?.value,40),label=str4(v?.label,120);return val===null||label===null?null:clean({value:val,label:label})},6),ingredientItems=words(ingredients?.items,12,80);return clean({title:title,productId:idOf(o.productId),partnerSku:str4(o.partnerSku,200),rating:str4(rating?.value,20)===null?null:clean({value:str4(rating?.value,20),label:str4(rating?.label,120)}),line:str4(o.line),reviews:str4(reviews?.label,200)===null||reviewItems===null?null:clean({label:str4(reviews?.label,200),items:reviewItems}),checkoutLine:str4(o.checkoutLine,300),why:str4(why?.title,200)===null||whyRows===null?null:clean({title:str4(why?.title,200),rows:whyRows,score:str4(score?.text,200)===null||str4(score?.value,20)===null?null:clean({text:str4(score?.text,200),value:str4(score?.value,20)})}),dose:str4(dose?.title,200)===null||stats===null?null:clean({title:str4(dose?.title,200),stats:stats,note:str4(dose?.note)}),ingredients:ingredientItems===null?null:clean({label:str4(ingredients?.label,200),items:ingredientItems}),proof:str4(o.proof,300),trust:listOf(o.trust,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str4(v?.label,120);return icon===null||label===null?null:clean({icon:icon,label:label})},6),more:str4(o.more,120),fine:str4(o.fine),checkin:str4(o.checkin,200)})}function signsOf(value){let o=obj(value),title=str4(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),t=str4(v?.title,300),body=str4(v?.body);return t===null||body===null?null:clean({title:t,body:body,urgent:v?.urgent===true?true:null})});return title===null||items===null?null:clean({title:title,items:items})}function checkupOf(value){let o=obj(value),title=str4(o?.title,200),questions=words(o?.questions,12,300),add=str4(o?.add,80),added=str4(o?.added,80);return title===null||questions===null||add===null||added===null?null:clean({title:title,questions:questions,add:add,added:added})}function extrasOf(value){let o=obj(value),title=str4(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),key=str4(v?.key,REF_MAX),t=str4(v?.title,300),action=str4(v?.action,80),added=str4(v?.added,80);return key===null||t===null||action===null||added===null?null:clean({key:key,title:t,body:str4(v?.body),price:str4(v?.price,40),was:str4(v?.was,40),tag:str4(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added})},6);return title===null||items===null?null:clean({title:title,items:items})}function healthPlanFocusDesignFromWire(raw){let o=obj(raw),title=str4(o?.title,300),pick2=pickOf(o?.pick);if(o===null||title===null||pick2===null)return null;let byline=obj(o.byline);return clean({eyebrow:str4(o.eyebrow,120),title:title,subtitle:str4(o.subtitle,300),headImageUrl:imageOf(o.headImageUrl),byline:str4(byline?.name,120)===null?null:clean({name:str4(byline?.name,120),role:str4(byline?.role,120),imageUrl:imageOf(byline?.imageUrl)}),focus:focusOf(o.focus),routine:routineOf(o.routine),pick:pick2,signs:signsOf(o.signs),checkup:checkupOf(o.checkup),extras:extrasOf(o.extras),fine:str4(o.fine),checkoutRows:listOf(o.checkoutRows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str4(v?.label,60),val=str4(v?.value,200);return icon===null||label===null||val===null?null:clean({icon:icon,label:label,value:val})},6)})}function healthPlanPageFromWire(raw,petRef){let o=obj(raw);if(o===null||!("page"in o))return null;let pet=obj(o.pet),sex=pet?.sex;/* @__PURE__ */
|
|
730
|
+
return Object.freeze({petRef:str4(o.pet_ref,REF_MAX)??petRef,pet:/* @__PURE__ */Object.freeze({name:str4(pet?.name,120),species:str4(pet?.species,60),sex:sex==="female"||sex==="male"?sex:null,breed:str4(pet?.breed,120),weightKg:weightOf(pet?.weight_kg),weightLb:weightOf(pet?.weight_lb)}),checkout:o.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(o.page),vetReviewed:o.vet_reviewed===true,trackingTextsEnabled:o.tracking_texts_enabled===true})}function invalid3(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed3(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the expected shape`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX;function base(petRef){return`/widget/v1/pets/${encodeURIComponent(petRef)}/plan`}async function readPage(funnel,petRef,opts){if(!validRef(petRef))return err(invalid3("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.page.read",{method:"GET",path:`${base(petRef)}/page`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let page=healthPlanPageFromWire(res.value,petRef);return page===null?err(malformed3("healthPlan.page.read")):ok(page)}var readers=/* @__PURE__ */new WeakMap;function createHealthPlanPageReader(runtime){let known=readers.get(runtime);if(known!==void 0)return known;let reader=makeHealthPlanPageReader(runtime);return readers.set(runtime,reader),reader}function makeHealthPlanPageReader(runtime){return{getPage:(petRef,opts)=>{if(runtime.isDisposed)return Promise.resolve(err(disposed("getPage")));let{services:services}=runtime.registry,funnel=withPlainNotFound(createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}));return readPage(funnel,petRef,opts)}}}var HEALTH_PLAN_STALE_MS=6e4;function useHealthPlanRevalidation({lifecycle:lifecycle,refreshKey:refreshKey,readyAt:readyAt,revalidate:revalidate,refresh:refresh,now:now=Date.now}){let latest=react.useRef({readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now});latest.current={readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now},react.useEffect(()=>{if(lifecycle==null)return;let stop=callHost(()=>lifecycle.onForeground(()=>{let{readyAt:at,revalidate:run,now:clock}=latest.current;at!==null&&clock()-at>=HEALTH_PLAN_STALE_MS&&run()}));return()=>{typeof stop=="function"&&callHost(stop)}},[lifecycle]);let seenKey=react.useRef(refreshKey);react.useEffect(()=>{Object.is(seenKey.current,refreshKey)||(seenKey.current=refreshKey,latest.current.refresh())},[refreshKey])}var HEALTH_PLAN_PAGE_SHARE_MS=5e3,sharedReads=/* @__PURE__ */new WeakMap;function readShared(reader,userRef,petRef,fresh){let reads=sharedReads.get(reader);reads===void 0&&(reads=/* @__PURE__ */new Map,sharedReads.set(reader,reads));let map=reads,key=`${userRef}\0${petRef}`,hit=map.get(key);if(!fresh&&hit!==void 0&&(hit.at===null||Date.now()-hit.at<HEALTH_PLAN_PAGE_SHARE_MS))return hit.promise;let entry={at:null,promise:reader.getPage(petRef).then(res=>(map.get(key)===entry&&(res.ok||isNotFoundError(res.error)?entry.at=Date.now():map.delete(key)),res))};return map.set(key,entry),entry.promise}function useHealthPlanPage(options){let{userRef:userRef,runtime:runtime}=useEverfurContext(),own=react.useMemo(()=>createHealthPlanPageReader(runtime),[runtime]),hostRepository=options.repository,repository=hostRepository??own,getPage=react.useCallback((pet,fresh)=>hostRepository!==void 0||userRef==null?repository.getPage(pet):readShared(own,userRef,pet,fresh),[hostRepository,repository,own,userRef]),{petRef:petRef}=options,enabled=options.enabled!==false&&userRef!=null&&petRef!==null,[state,setState]=react.useState({phase:"idle",petRef:null,page:null,error:null}),epoch=react.useRef(0),quiet=react.useRef(0),read=react.useCallback(async fresh=>{let mine=++epoch.current;if(!enabled||petRef===null){setState(prev=>prev.phase==="idle"&&prev.petRef===null?prev:{phase:"idle",petRef:null,page:null,error:null});return}setState(prev=>({phase:"loading",petRef:petRef,page:prev.petRef===petRef?prev.page:null,error:null}));let res=await getPage(petRef,fresh);mine===epoch.current&&(res.ok?setState({phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}):isNotFoundError(res.error)?setState({phase:"ready",petRef:petRef,page:null,error:null,missing:true,readyAt:Date.now()}):setState({phase:"failed",petRef:petRef,page:null,error:res.error}))},[enabled,petRef,getPage]),load=react.useCallback(()=>read(true),[read]),ready=state.phase==="ready"&&state.petRef===petRef,revalidate=react.useCallback(async()=>{if(!enabled||petRef===null||!ready)return;let mine=epoch.current,seq=++quiet.current,res=await getPage(petRef,true);mine!==epoch.current||seq!==quiet.current||!res.ok||setState(prev=>prev.phase==="ready"&&prev.petRef===petRef?{phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}:prev)},[enabled,petRef,ready,getPage]);useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?state.readyAt??null:null,revalidate:()=>{revalidate()},refresh:()=>{ready?revalidate():load()}}),react.useEffect(()=>(read(false),()=>{epoch.current+=1}),[read]);let stale=enabled&&state.petRef!==petRef;return react.useMemo(()=>({phase:stale?"loading":state.phase,page:stale?null:state.page,error:stale?null:state.error,missing:!stale&&state.missing===true,refresh:load}),[stale,state,load])}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX2=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE2=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE2.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text3=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text3(FOOD_MAX),foodType:text3(FOOD_MAX),microchipId:text3(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text3(REF_MAX2,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text3(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text3(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text3(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text3(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text3(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text3(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str5=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str5(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str5(o.ref),name:name,dose:str5(o.dose),frequency:str5(o.frequency),startDate:str5(o.start_date),endDate:str5(o.end_date),notes:str5(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
|
|
731
|
+
return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str5(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str5(o.food_brand),foodType:str5(o.food_type),microchipId:str5(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str5(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str5(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str5(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str5(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str5(row.ref),conditionName:conditionName,diagnosedDate:str5(row.diagnosed_date),notes:str5(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX2=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid4(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid4(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid4(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid4(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid4("pet_ref must be a string");if(petRef.trim().length===0)return invalid4("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid4("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid4("profile must be an object");let checks=[checkString("pet_ref",petRef,PET_REF_MAX2)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid4(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid4("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid4("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str6=v=>typeof v=="string"?v:null,num3=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
|
|
732
|
+
return Object.freeze({petRef:str6(o.pet_ref)??petRef,name:str6(o.name),species:str6(o.species),breed:str6(o.breed),ageYears:num3(o.age_years),weightKg:num3(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef=str6(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str6(o.pet_id),petRef:petRef,name:str6(o.name),species:str6(o.species),breed:str6(o.breed),ageYears:num3(o.age_years),weightKg:num3(o.weight_kg),updatedAt:str6(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
|
|
733
|
+
return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid5=validate(petRef,profile);if(invalid5!==null)return err(invalid5);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base2={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base2,signal:opts.signal}:base2);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var listeners2=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners2.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners2.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=react.useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=react.useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=react.useRef(0),load=react.useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]),react.useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=react.useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return react.useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}var DEFAULT_PRESENTATION=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark"}),PRESENTATION_WIRE_NAMES=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button"}),FIELDS=Object.keys(PRESENTATION_WIRE_NAMES),PRESENTATION_LOCK="presentation",PRESENTATION_LOCK_PREFIX="presentation.";var ENUMS={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},BOOLS=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner"]);function parseField(field,value){if(value==null)return;let allowed=ENUMS[field];return allowed!==void 0?typeof value=="string"&&allowed.includes(value)?value:void 0:BOOLS.has(field)?typeof value=="boolean"?value:void 0:typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=3?value:void 0}function parsePresentation(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let source=raw,out={};for(let field of FIELDS){let wire=PRESENTATION_WIRE_NAMES[field],value=Object.prototype.hasOwnProperty.call(source,wire)?source[wire]:source[field],parsed=parseField(field,value);parsed!==void 0&&(out[field]=parsed)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function isPresentationFieldLocked(field,locked){if(locked==null)return false;let one=`${PRESENTATION_LOCK_PREFIX}${PRESENTATION_WIRE_NAMES[field]}`;for(let name of locked)if(name===PRESENTATION_LOCK||name===one)return true;return false}function resolvePresentation(input){let server=parsePresentation(input?.server??null)??{},client=parsePresentation(input?.client??null)??{},locked=input?.locked?[...input.locked]:null,out={};for(let field of FIELDS){let fromServer=server[field],fromClient=isPresentationFieldLocked(field,locked)?void 0:client[field];out[field]=fromClient??fromServer??DEFAULT_PRESENTATION[field]}/* @__PURE__ */
|
|
734
|
+
return Object.freeze(out)}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentation(client){return useEverfurPresentationState(client).presentation}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=react.useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=react.useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf(client);return react.useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}var capital=text4=>text4.charAt(0).toUpperCase()+text4.slice(1);function sheetPetWords(name,pronoun){let trimmed=name.trim(),shown=trimmed.length>0?trimmed:NAMELESS_PET,Name=capital(shown);return pronoun==="her"?{name:shown,Name:Name,poss:"her",Poss:"Her",subj:"she"}:pronoun==="his"?{name:shown,Name:Name,poss:"his",Poss:"His",subj:"he"}:{name:shown,Name:Name,poss:`${shown}'s`,Poss:`${Name}'s`,subj:shown}}var SHEET_COPY=/* @__PURE__ */Object.freeze({vitalsFrom:(w,visit,date2)=>`Vitals from ${w.poss} ${visit}, ${date2}`,temperature:"Temperature",heartRate:"Heart rate",breathing:"Breathing",upcomingCare:"Upcoming care",overdueBy:date2=>`Overdue · due by ${date2}`,dueSoon:"Due soon",later:"Later",recordsHistory:"Records & history",labs:"Labs & bloodwork",results:"results",screenings:"Screenings",visits:"Visits & records",timeline:"Timeline",events:n=>`${n} ${n===1?"event":"events"}`,weight:"Weight",vetVisits:n=>`${n} vet ${n===1?"visit":"visits"}`,history:"History",theirClinic:w=>`${w.Poss} clinic`,bloodPanel:"Blood panel",aboveRange:"above range",belowRange:"below range",othersInRange:"Other values in range.",addRecords:w=>`Add ${w.name}'s records`,moreThanOneClinic:"Records can come from more than one clinic over a lifetime.",visitsCount:n=>`${n} ${n===1?"visit":"visits"}`,panelsCount:n=>`${n} blood ${n===1?"panel":"panels"}`,requestFromClinic:"Request from a clinic",uploadDocument:"Upload a document",onFileNow:"On file now",firstRecord:w=>`Add ${w.name}'s first record`,firstLead:w=>`Records can come from more than one clinic over a lifetime. Start with the one ${w.subj} sees most, and this page fills in from there.`,requestFromTheirClinic:w=>`Request from ${w.poss} clinic`,requestDetail:"We send a secure request and read every page they send back.",uploadDetail:"A PDF, or a photo of a paper record.",sayBeats:/* @__PURE__ */Object.freeze(["Hmmm","I wonder","what I may be","hiding"]),sayStill:"I wonder what I may be hiding",sample:"Sample",peekLead:w=>`A sneak peek at how ${w.name}'s records will read. Every number links back to the page it came from.`,sampleNote:w=>`Sample data until ${w.poss} records arrive.`,onTheWay:w=>`${w.Name}'s records are on the way`,clinicsTake:"Clinics usually take 2 to 5 days.",anotherClinic:"Another clinic",anotherClinicDetail:"Seen more than one vet? We ask each one.",noDueDate:"No due date on file",noLabs:w=>`No lab results on file for ${w.name} yet. They show up here when a record includes a blood or urine panel.`,noVisits:w=>`No visits in ${w.name}'s records yet. They show up here when a record includes one.`,oneReading:"One reading so far: we'll plot a trend as more come in.",takingNow:"Taking now",noCurrentMeds:"No current medications on file.",topRisk:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`,panelOn:date2=>`${date2} blood panel`,latestReading:"Latest reading",rangeLine:(low,high,unit)=>`range ${low} to ${high}${unit?` ${unit}`:""}`,noRange:"No range on the report",above:"Above",inRange:"In range",below:"Below",high:"High",belowRangePill:"Below range",changeUp:(delta,unit)=>`Up ${delta}${unit?` ${unit}`:""}`,changeDown:(delta,unit)=>`Down ${delta}${unit?` ${unit}`:""}`,changeSince:(date2,pct2)=>` since ${date2}, about ${pct2}%.`,whatIs:name=>`What ${name} is`,otherValues:panel=>`Other ${panel} values`,panelTitle:(panel,date2)=>`${panel} · ${date2}`,askAboutThis:"Ask about this"}),SHEET_SAMPLE=/* @__PURE__ */Object.freeze({labsTitle:"Labs & bloodwork",group:"Liver",groupLead:"What the liver makes and clears.",markers:/* @__PURE__ */Object.freeze([{name:"ALT",value:"118",unit:"U/L",range:"10 to 100 U/L",at:92,high:true},{name:"ALP",value:"64",unit:"U/L",range:"23 to 212 U/L",at:33,high:false},{name:"GGT",value:"3",unit:"U/L",range:"0 to 11 U/L",at:36,high:false},{name:"Total bilirubin",value:"0.2",unit:"mg/dL",range:"0 to 0.9 mg/dL",at:33,high:false}]),more:/* @__PURE__ */Object.freeze([{tint:"emb",icon:"efi-shield",title:"Screenings",lead:()=>"Tests that look for common problems early, and what came back.",rows:/* @__PURE__ */Object.freeze([{label:"Heartworm test",pill:"Negative",tone:"clear"},{label:"Tick panel (4Dx)",pill:"Negative",tone:"clear"}])},{tint:"blue",icon:"efi-folder",title:"Visits & records",lead:()=>"Every visit, with the vet's notes and the pages they came from.",rows:/* @__PURE__ */Object.freeze([{label:"Wellness exam",when:"38 pages"},{label:"Video visit",when:"3 pages"}])},{tint:"yellow",icon:"efi-clock",title:"Timeline",lead:w=>`${w.Poss} whole history in order, with what's due next.`,rows:/* @__PURE__ */Object.freeze([{label:"Rabies vaccine",pill:"Due soon",tone:"watch"},{label:"Heartworm test",when:"Apr 18"}])}])});var DAY_MS=864e5,DUE_SOON_DAYS=30,LB_PER_KG=2.20462,MONTHS2=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function dayMs(value){if(value==null||value.length===0)return null;let ms=Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(value)?`${value}T00:00:00Z`:value);return Number.isNaN(ms)?null:ms}function shortDate(ms){let d=new Date(ms);return`${MONTHS2[d.getUTCMonth()]??""} ${d.getUTCDate()}`}function longDate(ms){return`${shortDate(ms)}, ${new Date(ms).getUTCFullYear()}`}function monthTick(ms){let d=new Date(ms);return`${d.getUTCMonth()+1}/${String(d.getUTCFullYear()%100).padStart(2,"0")}`}var dayKey=ms=>new Date(ms).toISOString().slice(0,10);function num4(value){return String(Math.round(value*100)/100)}var lb=kg=>Math.round(kg*LB_PER_KG*10)/10;function midSentence(text4){let t=text4.trim();return t.length<2||t[1]===t[1]?.toUpperCase()?t:t.charAt(0).toLowerCase()+t.slice(1)}function vitalKind(text4){return/temp/i.test(text4)?"temp":/heart|pulse/i.test(text4)?"heart":/resp|breath/i.test(text4)?"breath":null}var VITAL_ORDER=["temp","heart","breath"],VITAL_LABEL={temp:SHEET_COPY.temperature,heart:SHEET_COPY.heartRate,breath:SHEET_COPY.breathing};function sheetVitals(record){if(record===null||record.withheld)return{vitals:[],observedMs:null};let best=/* @__PURE__ */new Map;for(let e of record.entities){if(e.category!=="vital"||e.value===null||e.value.trim().length===0)continue;let kind=vitalKind(`${e.canonicalKey??""} ${e.key} ${e.label}`);if(kind===null)continue;let ms=dayMs(e.observedAt)??0,prev=best.get(kind);(prev===void 0||ms>prev.ms)&&best.set(kind,{value:e.value.trim(),unit:e.unit,ms:ms})}let vitals=VITAL_ORDER.flatMap(kind=>{let v=best.get(kind);return v===void 0?[]:[{kind:kind,value:v.value,unit:v.unit,label:VITAL_LABEL[kind]}]}),observed=[...best.values()].map(v=>v.ms).filter(ms=>ms>0);return{vitals:vitals,observedMs:observed.length>0?Math.max(...observed):null}}function encounterOn(encounters,ms){let key=dayKey(ms);return encounters.find(e=>{let at=dayMs(e.date);return at!==null&&dayKey(at)===key})??null}function dueIcon(title){return/vaccin|rabies|dhpp|booster|bordetella|lepto|lyme|parvo|distemper/i.test(title)?"efi-shield":/\b(alt|alp|lab|labs|blood|panel|bloodwork|urinalysis|chemistry|cbc)\b/i.test(title)?"efi-flask-sm":"efi-calendar"}function sheetDue(items,nowMs){return items.map(item=>{let due=dayMs(item.dueAt),icon=dueIcon(item.title);if(due!==null&&due<nowMs-DAY_MS+1)return{item:item,title:item.title,when:SHEET_COPY.overdueBy(shortDate(due)),tone:"alert",pill:null,icon:icon};let when=item.detail??(due===null?SHEET_COPY.noDueDate:longDate(due));if(due===null)return{item:item,title:item.title,when:when,tone:"none",pill:null,icon:icon};let soon=due-nowMs<=DUE_SOON_DAYS*DAY_MS;return{item:item,title:item.title,when:when,tone:soon?"watch":"later",pill:soon?SHEET_COPY.dueSoon:SHEET_COPY.later,icon:icon}})}function pointFlag(status){return status==null?null:/above|high/i.test(status)?"above":/below|low/i.test(status)?"below":/in_range|normal|in range/i.test(status)?"in":null}var kgShown=kg=>Math.round(kg*10)/10;function weightText(kg,unit){let pounds=`${num4(lb(kg))} lb`,kilos=`${num4(kgShown(kg))} kg`;return unit==="kg"?{main:kilos,other:pounds}:{main:pounds,other:kilos}}function weightModel(timeline,unit){if(timeline===null||timeline.withheld)return null;let readings=timeline.weights.flatMap(w=>{let ms=dayMs(w.observedOn);return ms===null||w.weightKg===null?[]:[{ms:ms,kg:w.weightKg}]}).sort((a,b)=>a.ms-b.ms),last=readings[readings.length-1];if(last===void 0)return null;let lbs=readings.map(r=>lb(r.kg)),lo=Math.min(...lbs),hi=Math.max(...lbs),t0=readings[0]?.ms??last.ms,span=last.ms-t0,points=readings.map((r,i)=>({x:span>0?Math.round((3.55+93.45*(r.ms-t0)/span)*100)/100:50,y:hi>lo?Math.round((75-50*((lbs[i]??lo)-lo)/(hi-lo))*10)/10:50,lb:lbs[i]??0,value:unit==="kg"?kgShown(r.kg):lbs[i]??0,ms:r.ms})),tickPoints=points.length<=4?points:[points[0],points[points.length-1]].filter(p=>p!==void 0),text4=weightText(last.kg,unit);return{latest:text4.main,sub:`${text4.other} · ${shortDate(last.ms)}`,single:points.length===1,points:points,ticks:tickPoints.map(p=>({x:p.x,label:monthTick(p.ms)})),vetCount:points.length}}function labDays(markers){let days=/* @__PURE__ */new Map;if(markers===null||markers.withheld)return days;for(let marker of markers.markers)for(let point of marker.points){let ms=dayMs(point.at);if(ms===null)continue;let key=dayKey(ms),day=days.get(key)??{ms:ms,flagged:[],total:0,inRange:0,clinics:/* @__PURE__ */new Set};day.total+=1;let flag=pointFlag(point.status);flag==="in"&&(day.inRange+=1),(flag==="above"||flag==="below")&&day.flagged.push({marker:marker,point:point,ms:ms,flag:flag}),point.sourceClinic&&day.clinics.add(point.sourceClinic),days.set(key,day)}return days}function historyModel(inputs,days){let items=[];for(let[key,day]of days)day.flagged.forEach((f,i)=>{let value=f.point.value===null?f.point.qualitativeResult??"":num4(f.point.value),unit=f.point.unit??f.marker.unit,others=day.flagged.length===1&&day.inRange===day.total-1&&day.total>1;items.push({key:`lab-${key}-${f.marker.markerId}-${i}`,ms:day.ms,date:`${shortDate(day.ms)} · ${SHEET_COPY.bloodPanel}`,title:`${f.marker.name} ${value}${unit?` ${unit}`:""}, ${f.flag==="above"?SHEET_COPY.aboveRange:SHEET_COPY.belowRange}`,text:others?SHEET_COPY.othersInRange:null,alert:true,markerId:f.marker.markerId,order:0})});let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],visits=inputs.timeline?.withheld===false?inputs.timeline.visits:[],usedVisits=/* @__PURE__ */new Set;encounters.forEach((e,i)=>{let ms=dayMs(e.date);if(ms===null)return;let visit=visits.find(v=>e.docId!==null&&v.docId===e.docId||dayMs(v.visitDate)!==null&&dayKey(dayMs(v.visitDate)??0)===dayKey(ms))??null;visit!==null&&usedVisits.add(visit.visitId);let summary=visit?.summary?.trim()||null,type=e.type?.trim()||null,title=summary??type;title!==null&&items.push({key:`enc-${e.encounterId}-${i}`,ms:ms,date:summary!==null&&type!==null?`${shortDate(ms)} · ${type}`:shortDate(ms),title:title,text:null,alert:false,markerId:null,order:1})});for(let v of visits){let ms=dayMs(v.visitDate),summary=v.summary?.trim()||null;usedVisits.has(v.visitId)||ms===null||summary===null||items.push({key:`visit-${v.visitId}`,ms:ms,date:shortDate(ms),title:summary,text:null,alert:false,markerId:null,order:1})}items.sort((a,b)=>b.ms-a.ms||a.order-b.order);let years=[];for(let entry of items){let item={key:entry.key,ms:entry.ms,date:entry.date,title:entry.title,text:entry.text,alert:entry.alert,markerId:entry.markerId},year=String(new Date(item.ms).getUTCFullYear()),last=years[years.length-1];last!==void 0&&last.year===year?last.items.push(item):years.push({year:year,items:[item]})}return{years:years,count:items.length}}function sourcesModel(inputs,days){let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],clinicLabel=name=>name?.trim()||SHEET_COPY.theirClinic(inputs.words),visits=/* @__PURE__ */new Map;for(let e of encounters)visits.set(clinicLabel(e.clinicName),(visits.get(clinicLabel(e.clinicName))??0)+1);let panels=/* @__PURE__ */new Map,onlyClinic=visits.size===1?[...visits.keys()][0]:void 0;for(let day of days.values()){let names=day.clinics.size>0?[...day.clinics].map(clinicLabel):[onlyClinic??SHEET_COPY.theirClinic(inputs.words)];for(let n of names)panels.set(n,(panels.get(n)??0)+1)}return[.../* @__PURE__ */new Set([...visits.keys(),...panels.keys()])].map(label=>({label:label,detail:[(visits.get(label)??0)>0?SHEET_COPY.visitsCount(visits.get(label)??0):null,(panels.get(label)??0)>0?SHEET_COPY.panelsCount(panels.get(label)??0):null].filter(p=>p!==null).join(" · ")}))}var PULL_PCT={requested:15,awaiting_clinic:35,awaiting_upload:35,received:60,parsing:75,in_review:90};function sheetPull(requests){let open=requests.filter(r=>!isTerminalStatus(r.status)).sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(open===void 0)return null;let step=(open.waitingExpectation?.trim()||open.statusLabel).trim();return step.length===0?null:{step:step,pct:PULL_PCT[open.status]??15}}function sheetMedications(timeline){if(timeline===null||timeline.withheld)return null;let named=timeline.medications.filter(m=>(m.drugName?.trim()??"")!=="");return named.length===0?null:{current:named.filter(m=>(m.stoppedOn?.trim()??"")==="").map(m=>{let parts=[m.dose,m.frequency,m.route].map(p=>p?.trim()??"").filter(p=>p!==""),detail=m.sig?.trim()||(parts.length>0?parts.join(" · "):null);return{key:m.medicationId,name:(m.drugName??"").trim(),detail:detail}})}}function sheetFailedRequest(requests){if(requests.some(r=>!isTerminalStatus(r.status)))return null;let newest=[...requests].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(newest===void 0||newest.status!=="failed")return null;let words2=newest.statusLabel.trim();return words2.length>0?words2:null}function sheetHasRecord(record,markers,depth){return record!==null&&!record.withheld&&!record.isEmpty||markers!==null&&!markers.withheld&&markers.markers.length>0?true:depth!==null&&!depth.withheld&&depth.encounters.length>0}function buildRecordsSheetModel(inputs){let{record:record,depth:depth,markers:markers,nowMs:nowMs}=inputs,has=sheetHasRecord(record,markers,depth),pull=sheetPull(inputs.requests),days=labDays(markers),{vitals:vitals,observedMs:observedMs}=sheetVitals(record),encounters=depth?.withheld===false?depth.encounters:[],visitAt=observedMs===null?null:encounterOn(encounters,observedMs),vitalsFrom=observedMs!==null&&visitAt?.type?SHEET_COPY.vitalsFrom(inputs.words,midSentence(visitAt.type),shortDate(observedMs)):null,unit=inputs.weightUnit??"lb",weight=weightModel(inputs.timeline,unit),latestKg=weight!==null?null:inputs.petWeightKg,meta=[inputs.breed?.trim()||null,weight?.latest??(latestKg!==null?weightText(latestKg,unit).main:null)].filter(p=>p!==null),timelineVisits=inputs.timeline?.withheld===false?inputs.timeline.visits.length:0,history=historyModel(inputs,days),encounterDays=encounters.map(e=>dayMs(e.date)).filter(ms=>ms!==null),markerList=markers?.withheld===false?markers.markers:[],featured=markers?.featuredMarkerId??markerList.find(m=>pointFlag(m.latest?.status)==="above"||pointFlag(m.latest?.status)==="below")?.markerId??markerList[0]?.markerId??null;return{state:has?"full":pull!==null?"onTheWay":"none",meta:meta.length>0?meta.join(" · "):null,vitals:vitals,vitalsFrom:vitalsFrom,due:record!==null&&!record.withheld?sheetDue(record.forwardLooking,nowMs):[],labsCount:markers?.withheld===false?markers.summary?.totalMarkers??markers.markers.length:0,featuredMarkerId:featured,latestVisit:encounterDays.length>0?longDate(Math.max(...encounterDays)):null,weight:weight,history:history.years,historyCount:history.count,sources:sourcesModel(inputs,days),pull:pull,hasVisits:encounters.length>0||timelineVisits>0,medications:sheetMedications(inputs.timeline),failedRequest:pull===null?sheetFailedRequest(inputs.requests):null}}function lastPoint(marker){let dated=marker.points.filter(p=>p.value!==null);return dated[dated.length-1]??marker.points[marker.points.length-1]??null}function rangeOf(point){return point===null||point.refLow===null||point.refHigh===null||!Number.isFinite(point.refLow)||!Number.isFinite(point.refHigh)||point.refHigh<=point.refLow?null:{low:point.refLow,high:point.refHigh}}function markerRow(marker,point=lastPoint(marker)){let range=rangeOf(point),unit=point?.unit??marker.unit,value=point?.value??null;return{markerId:marker.markerId,name:marker.name,value:value===null?point?.qualitativeResult??"":num4(value),unit:unit,range:range===null?null:`${num4(range.low)} to ${num4(range.high)}${unit?` ${unit}`:""}`,at:range===null||value===null?null:Math.round(Math.min(100,Math.max(0,20+60*(value-range.low)/(range.high-range.low)))),flag:pointFlag(point?.status??marker.latest?.status??null)}}function flagPill(flag){return flag==="above"?SHEET_COPY.high:flag==="below"?SHEET_COPY.belowRangePill:flag==="in"?SHEET_COPY.inRange:null}var panelWord=panel=>{let name=panel.replace(/\s+panel$/i,"").trim()||panel;return name.length>1&&name[1]===name[1]?.toUpperCase()?name:name.charAt(0).toLowerCase()+name.slice(1)};function buildSheetLabModel(markers,markerId){let marker=markers.markers.find(m=>m.markerId===markerId);if(marker===void 0)return null;let last=lastPoint(marker),row=markerRow(marker,last),lastMs=dayMs(last?.at??marker.latest?.at??null),range=rangeOf(last),latestSub=[lastMs===null?null:shortDate(lastMs),range===null?SHEET_COPY.noRange:SHEET_COPY.rangeLine(num4(range.low),num4(range.high),row.unit)].filter(p=>p!==null).join(" · "),numeric2=marker.points.flatMap(p=>{let ms=dayMs(p.at);return p.value===null||ms===null?[]:[{p:p,ms:ms,v:p.value}]}),chart=[];if(numeric2.length>0){let values=numeric2.map(n=>n.v),lo=range?.low??Math.min(...values),hi=range?.high??Math.max(...values);chart=numeric2.map((n,i)=>({x:numeric2.length===1?50:Math.round((18+64*i/(numeric2.length-1))*100)/100,y:hi>lo?Math.min(98,Math.max(2,Math.round((75-50*(n.v-lo)/(hi-lo))*10)/10)):50,label:num4(n.v),out:pointFlag(n.p.status)==="above"||pointFlag(n.p.status)==="below",tick:shortDate(n.ms)}))}let first=numeric2[0],final=numeric2[numeric2.length-1],change=null;if(first!==void 0&&final!==void 0&&numeric2.length>=2&&final.v!==first.v){let delta=Math.abs(final.v-first.v),pct2=first.v!==0?Math.round(delta/Math.abs(first.v)*100):null,lead2=final.v>first.v?SHEET_COPY.changeUp(num4(delta),row.unit):SHEET_COPY.changeDown(num4(delta),row.unit);change=pct2===null?null:{lead:lead2,rest:SHEET_COPY.changeSince(shortDate(first.ms),pct2)}}let groups=[],lastKey=lastMs===null?null:dayKey(lastMs),others=markers.markers.filter(m=>m.markerId!==marker.markerId),samePanel=others.filter(m=>m.panel!==null&&m.panel===marker.panel);if(samePanel.length>0&&marker.panel!==null){let rows=samePanel.map(m=>markerRow(m));groups.push({title:SHEET_COPY.otherValues(panelWord(marker.panel)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}if(lastKey!==null&&lastMs!==null){let byPanel=/* @__PURE__ */new Map;for(let m of others){if(m.panel===null||m.panel===marker.panel)continue;let p=[...m.points].reverse().find(pt=>{let ms=dayMs(pt.at);return ms!==null&&dayKey(ms)===lastKey});p!==void 0&&byPanel.set(m.panel,[...byPanel.get(m.panel)??[],markerRow(m,p)])}for(let[panel,rows]of byPanel)groups.push({title:SHEET_COPY.panelTitle(panel,shortDate(lastMs)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}return{markerId:marker.markerId,name:marker.name,meta:lastMs===null?null:SHEET_COPY.panelOn(longDate(lastMs)),pill:flagPill(row.flag),flagged:row.flag==="above"||row.flag==="below",latest:`${row.value}${row.unit?` ${row.unit}`:""}`,latestSub:latestSub,hasRange:range!==null,chart:chart,change:change,meaning:(marker.meaning??"").split(/\n\s*\n/).map(p=>p.trim()).filter(p=>p.length>0),groups:groups}}var RAPH_V3_LIGHT=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),cache=/* @__PURE__ */new WeakMap;function v3Palette(theme){let hit=cache.get(theme);if(hit!==void 0)return hit;let c=theme.color,dark=theme.brightness==="dark",neutrals=dark?{dark:dark,ink:c.text.primary,ink2:c.text.secondary,ink3:c.text.muted,paper:c.background,card:c.surface,line:c.borderRingCream,tile:c.surfaceSubtle,shadow:c.shadow,riskBg:c.badgeBgCritical,riskInk:c.danger,riskDot:c.danger,clearBg:c.badgeBgPositive,clearInk:c.success,clearDot:c.success,watchDot:c.warningStrong}:{dark:dark,...RAPH_V3_LIGHT},textOn=(ink,grounds)=>pushToContrast(ink,grounds,poleForGrounds(grounds),V3_TEXT_CONTRAST),labelOn=(ink,fill)=>contrastRatio(ink,fill)>=V3_TEXT_CONTRAST?ink:legibleOn(fill,V3_TEXT_CONTRAST),badgeGrounds=[neutrals.card,neutrals.paper].map(under=>flattenOnto(c.brandSoft,under)??under),brand={primary:c.primary,onPrimary:labelOn(c.onPrimary,c.primary),accent:c.accent,onAccent:labelOn(c.onAccent,c.accent),link:textOn(c.linkInk,[neutrals.card,neutrals.paper,neutrals.tile]),badge:c.brandSoft,onBadge:textOn(c.brandInk,badgeGrounds)},palette=/* @__PURE__ */Object.freeze({...neutrals,...brand});return cache.set(theme,palette),palette}var V3_TEXT_CONTRAST=4.5;function v3InkOn(fill,inks){for(let ink of inks)if(contrastRatio(ink,fill)>=V3_TEXT_CONTRAST)return ink;return legibleOn(fill,V3_TEXT_CONTRAST)}var RAPH_RN_PALETTE=/* @__PURE__ */Object.freeze({ink:"#10462E",go:"#07C168",muted:"#6B6B6B",line:"#E4E4E4",alert:"#C03410",alertDeep:"#6D1D14",tintSage:"#E6ECE8",tintBlue:"#EAEEF6",tintYellow:"#FCF0D6",tintRed:"#FBF1EE",tintGo:"#DCF6EA",icoSage:"#819E90",efWhite:"#FFFFFF",efBlack:"#000000",efCharcoal:"#3D3D3D",efSkyBlue:"#4E98C9",embCyan1:"#E0FDFF",bgMist:"#F1F5F2",watch:"#F9E6B9",barTrack:"#ECECEC",topCard:"#FFCE34",topKicker:"#4A4845",topInk:"#262523"}),RAPH_RN_METRICS=/* @__PURE__ */Object.freeze({gap:12,sheetPadTop:20,sheetPadX:16,sheetPadBottom:28,sheetRadius:28,cardPad:16,cardRadius:20,name:22,cardTitle:18,rowTitle:17,body:15,small:13,mono:12,tileNum:20,big:32,button:48,rowButton:40,pill:24,plot:148,rowRadius:10,tileGap:10,icon:22});function sameColour(a,b){return a.trim().toLowerCase()===b.trim().toLowerCase()}function mix(a,b,t){let over=withAlpha(a,t);return(over!==null?flattenOnto(over,b):null)??b}var same=(a,b)=>parseColor(a)===parseColor(b);function raphIdentity(theme){if(theme.brightness!=="light")return false;let c=theme.color,k=EVERFUR_LIGHT.color;return same(c.primary,k.primary)&&same(c.brandInk,k.brandInk)&&same(c.onPrimary,k.onPrimary)&&same(c.accent,k.accent)&&same(c.accentEdge,k.accentEdge)}function brandTints(theme){let c=theme.color,P=RAPH_RN_PALETTE,v=v3Palette(theme),dark=theme.brightness==="dark",identity=raphIdentity(theme),compiled=(dark?EVERFUR_DARK:EVERFUR_LIGHT).color,accentSet=!same(c.accent,compiled.accent),ground=dark?c.surface:P.efWhite,tint=(hue,lightT)=>mix(hue,ground,dark?.18:lightT),tintSage=identity?P.tintSage:tint(v.primary,.105),topFill=accentSet?v.accent:tintSage;return{tintSage:tintSage,chevron:identity?P.icoSage:mix(c.brandInk,ground,.527),rowGround:identity?P.bgMist:tint(v.primary,.059),tintPartner:accentSet?tint(v.accent,.14):P.embCyan1,topFill:topFill,topKicker:v3InkOn(topFill,[accentSet?v.onAccent:dark?v.ink3:P.topKicker,P.topInk]),topInk:v3InkOn(topFill,[accentSet?v.onAccent:dark?v.ink:P.topInk,P.topInk])}}function recordsSheetLook(theme){let c=theme.color,P=RAPH_RN_PALETTE,v=v3Palette(theme),tints=brandTints(theme),accentOnFill=sameColour(c.accent,c.primary)?c.onPrimary:c.accent;return theme.brightness==="dark"?/* @__PURE__ */Object.freeze({dark:true,ground:c.background,card:v.card,text:v.ink,muted:v.ink3,line:c.structureEdge,ink:c.brandInk,fill:v.primary,onFill:v.onPrimary,accentOnFill:accentOnFill,accent:v.accent,go:c.success,goTint:c.badgeBgPositive,alert:v.riskInk,alertDeep:v.riskInk,alertTint:c.badgeBgCritical,watch:c.badgeBgCaution,tintBlue:c.surfaceSubtle,tintYellow:c.surfaceSubtle,barTrack:c.structureEdge,...tints}):/* @__PURE__ */Object.freeze({dark:false,ground:P.efWhite,card:P.efWhite,text:P.efBlack,muted:P.muted,line:P.line,ink:c.brandInk,fill:v.primary,onFill:v.onPrimary,accentOnFill:accentOnFill,accent:v.accent,go:P.go,goTint:P.tintGo,alert:P.alert,alertDeep:P.alertDeep,alertTint:P.tintRed,watch:P.watch,tintBlue:P.tintBlue,tintYellow:P.tintYellow,barTrack:P.barTrack,...tints})}function iconKindOf(efi){switch(efi){case"efi-flask":case"efi-flask-sm":return"flask";case"efi-shield":return"shield";case"efi-folder":return"folder";case"efi-clock":return"clock";case"efi-calendar":return"calendar";default:return"clock"}}var HIDDEN3={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"};function SheetIcon({kind:kind,size:size=RAPH_RN_METRICS.icon,color:color}){let glyph;switch(kind){case"flask":case"thermo":case"heart":case"wind":glyph=/* @__PURE__ */jsxRuntime.jsx(ActivityGlyph,{size:size,color:color});break;case"shield":glyph=/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:size,color:color});break;case"folder":case"clip":glyph=/* @__PURE__ */jsxRuntime.jsx(FileTextGlyph,{size:size,color:color});break;case"clock":case"calendar":glyph=/* @__PURE__ */jsxRuntime.jsx(ClockGlyph,{size:size,color:color});break;case"chevron":glyph=/* @__PURE__ */jsxRuntime.jsx(ChevronGlyph,{size:size,color:color,direction:"right"});break;case"upload":glyph=/* @__PURE__ */jsxRuntime.jsx(UploadGlyph,{size:size,color:color});break;case"download":glyph=/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{transform:[{rotate:"180deg"}]},children:/* @__PURE__ */jsxRuntime.jsx(UploadGlyph,{size:size,color:color})});break;default:glyph=null}/* @__PURE__ */
|
|
735
|
+
return jsxRuntime.jsx(reactNative.View,{style:{width:size,height:size,alignItems:"center",justifyContent:"center"},...HIDDEN3,children:glyph})}var SheetKitContext=react.createContext(null);function useSheetKitValue(){let theme=useEverfurTheme();return react.useMemo(()=>{let look=recordsSheetLook(theme);return{theme:theme,look:look,s:makeSheetStyles(theme,look)}},[theme])}var SheetKitProvider=SheetKitContext.Provider;function useSheetKit(){let own=useSheetKitValue();return react.useContext(SheetKitContext)??own}function SheetPill({label:label,tone:tone,small:small=false,testID:testID}){let{s:s,look:look}=useSheetKit();if(label.trim().length===0)return null;let tones={watch:{backgroundColor:look.watch},stable:{backgroundColor:look.goTint},later:{backgroundColor:look.card,borderWidth:1.25,borderColor:look.line},clear:{backgroundColor:look.card,borderWidth:1.5,borderColor:look.go},plain:{backgroundColor:look.card,borderWidth:1.5,borderColor:look.line},high:{backgroundColor:look.card,borderWidth:1.25,borderColor:look.alert}},ink=tone==="later"?look.muted:tone==="clear"?look.go:tone==="high"?look.alert:look.ink;/* @__PURE__ */
|
|
736
|
+
return jsxRuntime.jsx(reactNative.View,{style:[s.pill,small?s.pillSmall:null,tones[tone]],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:[s.pillText,small?s.pillTextSmall:null,{color:ink}],children:label})})}function SheetCard({children:children,style:style,testID:testID}){let{s:s}=useSheetKit();/* @__PURE__ */
|
|
737
|
+
return jsxRuntime.jsx(reactNative.View,{style:[s.card,style],testID:testID,children:children})}function SheetButton({kind:kind,label:label,icon:icon,onPress:onPress,row:row=false,testID:testID}){let{s:s,look:look,theme:theme}=useSheetKit(),still=theme.motion.reducedMotion,ink=kind==="ink"?look.onFill:look.ink;/* @__PURE__ */
|
|
738
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label,testID:testID,style:({pressed:pressed})=>[s.button,row?s.buttonRow:null,kind==="ink"?{backgroundColor:look.fill}:{backgroundColor:look.card,borderWidth:1.5,borderColor:look.ink},pressed&&!still?{transform:[{scale:RECORDS_MOTION.pressScale}]}:null],children:[icon!==void 0?/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:icon,size:20,color:ink}):null,
|
|
739
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[s.buttonText,row?s.buttonTextRow:null,{color:ink}],children:label})]})}function SheetWay({kind:kind,icon:icon,title:title,detail:detail,onPress:onPress,testID:testID}){let{s:s,look:look,theme:theme}=useSheetKit(),still=theme.motion.reducedMotion,ink=kind==="ink"?look.onFill:look.ink;/* @__PURE__ */
|
|
740
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:`${title}. ${detail}`,testID:testID,style:({pressed:pressed})=>[s.way,kind==="ink"?{backgroundColor:look.fill}:{backgroundColor:look.card,borderWidth:1.5,borderStyle:"dashed",borderColor:look.ink},pressed&&!still?{transform:[{scale:RECORDS_MOTION.pressScale}]}:null],children:[
|
|
741
|
+
/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:icon,size:26,color:ink}),
|
|
742
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.wayText,children:[
|
|
743
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.wayTitle,{color:ink}],children:title}),
|
|
744
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.wayDetail,{color:kind==="ink"?look.onFill:look.text}],children:detail})]}),
|
|
745
|
+
/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:"chevron",size:20,color:kind==="ink"?look.accentOnFill:look.ink})]})}function SheetMarkerRow({name:name,value:value,unit:unit,range:range,at:at,pill:pill,testID:testID}){let{s:s,look:look}=useSheetKit();/* @__PURE__ */
|
|
746
|
+
return jsxRuntime.jsxs(reactNative.View,{style:s.mk,testID:testID,children:[
|
|
747
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.mkText,children:[
|
|
748
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.mkNameRow,children:[
|
|
749
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.mkName,children:name}),pill!==null?/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:pill,tone:"high"}):null]}),
|
|
750
|
+
/* @__PURE__ */jsxRuntime.jsxs(Text,{style:s.mkLine,children:[
|
|
751
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.mkValue,children:value}),unit?` ${unit}`:"",range!==null?` · ${range}`:""]})]}),at!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.mkBar,...HIDDEN3,children:[
|
|
752
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.mkBarIn,{backgroundColor:look.go}]}),
|
|
753
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.mkBarDot,{left:`${at}%`,backgroundColor:look.ink,borderColor:look.card}]})]}):null]})}function ChartLine({points:points,color:color}){let[box3,setBox]=react.useState(null),onLayout=e=>{let{width:width,height:height}=e.nativeEvent.layout;(box3===null||box3.w!==width||box3.h!==height)&&setBox({w:width,h:height})},segments=box3===null?[]:points.slice(1).map((p,i)=>{let a=points[i]??p,x1=a.x/100*box3.w,y1=a.y/100*box3.h,x2=p.x/100*box3.w,y2=p.y/100*box3.h,length=Math.hypot(x2-x1,y2-y1),angle=Math.atan2(y2-y1,x2-x1)*180/Math.PI;return{key:i,left:(x1+x2)/2-length/2,top:(y1+y2)/2-.75,length:length,angle:angle}});/* @__PURE__ */
|
|
754
|
+
return jsxRuntime.jsx(reactNative.View,{style:ABSOLUTE_FILL,onLayout:onLayout,...HIDDEN3,children:segments.map(seg=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:seg.left,top:seg.top,width:seg.length,height:1.5,backgroundColor:color,transform:[{rotate:`${seg.angle}deg`}]}},seg.key))})}function makeSheetStyles(theme,look){let body=face(theme,"regular"),bold=face(theme,"bold"),heading=headingFace(theme,"bold"),mono=face(theme,"mono"),monoBold=face(theme,"monoBold"),lh=(size,ratio)=>Math.round(size*ratio);return reactNative.StyleSheet.create({sheet:{gap:RAPH_RN_METRICS.gap,paddingTop:RAPH_RN_METRICS.sheetPadTop,paddingHorizontal:RAPH_RN_METRICS.sheetPadX,paddingBottom:RAPH_RN_METRICS.sheetPadBottom,borderTopLeftRadius:RAPH_RN_METRICS.sheetRadius,borderTopRightRadius:RAPH_RN_METRICS.sheetRadius,backgroundColor:look.ground},card:{padding:RAPH_RN_METRICS.cardPad,backgroundColor:look.card,borderRadius:RAPH_RN_METRICS.cardRadius,shadowColor:"#000000",shadowOpacity:look.dark?0:.09,shadowRadius:3,shadowOffset:{width:0,height:1},elevation:look.dark?0:1,borderWidth:look.dark?1:0,borderColor:look.line},cardHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:12},cardTitle:{...heading,fontSize:RAPH_RN_METRICS.cardTitle,lineHeight:lh(RAPH_RN_METRICS.cardTitle,1.25),letterSpacing:-.36,color:look.ink},cardTitleGap:{marginBottom:12},sec:{marginTop:8,marginBottom:12},head:{gap:2,marginBottom:8},name:{...heading,fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.2),letterSpacing:-.44,color:look.ink,flexShrink:1},meta:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),letterSpacing:.26,textTransform:"uppercase",color:look.muted},label:{...monoBold,marginTop:12,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.72,textTransform:"uppercase",color:look.muted},vitals:{flexDirection:"row",gap:8,marginTop:8},vital:{flex:1,minWidth:0},vitalTop:{flexDirection:"row",alignItems:"center",gap:6},vitalValue:{...bold,fontSize:17,lineHeight:lh(17,1.2),color:look.ink},vitalUnit:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},vitalLabel:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},due:{gap:4,marginHorizontal:-12},dueRow:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:RAPH_RN_METRICS.rowRadius},dueText:{flex:1,minWidth:0,gap:2},dueTitle:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},dueWhen:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},pill:{minHeight:RAPH_RN_METRICS.pill,paddingHorizontal:10,borderRadius:999,alignItems:"center",justifyContent:"center",alignSelf:"flex-start"},pillSmall:{minHeight:22,paddingHorizontal:7},pillText:{...monoBold,fontSize:RAPH_RN_METRICS.mono,lineHeight:RAPH_RN_METRICS.mono+2,letterSpacing:.72,textTransform:"uppercase"},pillTextSmall:{fontSize:10.5,letterSpacing:.21},tiles:{flexDirection:"row",flexWrap:"wrap",gap:RAPH_RN_METRICS.tileGap},tile:{flexGrow:1,flexBasis:"45%",minWidth:0,gap:8,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},tileTop:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between"},tileTitle:{...bold,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.25),letterSpacing:-.15,color:look.ink},tileFoot:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:8,minHeight:28},tileNum:{...bold,fontSize:RAPH_RN_METRICS.tileNum,lineHeight:RAPH_RN_METRICS.tileNum+2,letterSpacing:-.4,color:look.ink},tileUnit:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},emptyLine:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.5),color:look.muted},wt:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:8},wtValue:{...bold,fontSize:RAPH_RN_METRICS.big,lineHeight:RAPH_RN_METRICS.big+4,letterSpacing:-.64,color:look.ink},wtSub:{...body,fontSize:RAPH_RN_METRICS.body,color:look.muted},chart:{marginTop:20},plot:{position:"relative",height:RAPH_RN_METRICS.plot},point:{position:"absolute",width:12,height:12,marginLeft:-6,marginTop:-6,borderRadius:6,borderWidth:1.5,borderColor:look.card},pointLabel:{...face(theme,"medium"),position:"absolute",bottom:16,width:64,left:-26,textAlign:"center",fontSize:RAPH_RN_METRICS.mono,lineHeight:RAPH_RN_METRICS.mono+2,color:look.dark?look.text:RAPH_CHARCOAL},xAxis:{position:"relative",height:18,marginTop:8},xTick:{...mono,position:"absolute",top:0,width:56,marginLeft:-28,textAlign:"center",fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.3),color:look.muted},key:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:12},keyDot:{width:12,height:12,borderRadius:6,backgroundColor:look.ink},keyText:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},tlKey:{flexDirection:"row",alignItems:"center",gap:6,marginBottom:4},tlKeyDot:{width:10,height:10,borderRadius:5,borderWidth:2.5,borderColor:look.ink,backgroundColor:look.card},tlYear:{...monoBold,marginTop:20,marginBottom:12,marginLeft:40,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.72,textTransform:"uppercase",color:look.muted},tlItem:{position:"relative",flexDirection:"row",gap:16,paddingBottom:24},tlItemLast:{paddingBottom:0},tlRail:{position:"absolute",left:11,top:22,bottom:-2,width:2,borderRadius:1,backgroundColor:look.line},tlRailEnd:{bottom:12},tlDot:{width:16,height:16,marginTop:3,marginHorizontal:4,borderRadius:8,borderWidth:3,borderColor:look.ink,backgroundColor:look.card},tlBody:{flex:1,minWidth:0},tlBtn:{marginTop:-8,marginHorizontal:-8,paddingVertical:8,paddingLeft:8,paddingRight:36,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.alertTint},tlChevron:{position:"absolute",right:8,top:"50%",marginTop:-10},tlDate:{...mono,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.48,textTransform:"uppercase",color:look.muted},tlTitle:{...bold,marginTop:2,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},tlText:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},pull:{paddingTop:4,paddingBottom:24,paddingLeft:40},pullNone:{paddingTop:14,paddingBottom:0,paddingLeft:0},pullStep:{...bold,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.ink},pullBar:{height:6,marginTop:10,overflow:"hidden",borderRadius:999,backgroundColor:look.line},pullFill:{height:"100%",backgroundColor:look.accent},failed:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.alertTint},failedText:{...bold,flex:1,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.alertDeep},add:{gap:12},addHead:{flexDirection:"row",alignItems:"center",gap:8},addLead:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},sources:{gap:6},source:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",columnGap:12,paddingVertical:10,paddingHorizontal:14,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.rowGround},sourceLabel:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.text},sourceDetail:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},addActs:{gap:12,paddingTop:4},button:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,minHeight:RAPH_RN_METRICS.button,paddingHorizontal:20,borderRadius:999},buttonRow:{minHeight:RAPH_RN_METRICS.rowButton,paddingHorizontal:16},buttonText:{...bold,fontSize:16,lineHeight:20},buttonTextRow:{fontSize:RAPH_RN_METRICS.body},noneTitle:{...heading,fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.15),letterSpacing:-.44,color:look.ink},noneLead:{...body,marginTop:8,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},ways:{gap:12,marginTop:16},way:{flexDirection:"row",alignItems:"center",gap:12,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},wayText:{flex:1,minWidth:0,gap:2},wayTitle:{...bold,fontSize:16,lineHeight:lh(16,1.3)},wayDetail:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.45)},peek:{gap:12,marginTop:12},peekHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:12},peekLead:{...body,marginTop:-4,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},peekGroup:{...body,marginTop:8,marginBottom:6,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.45),color:look.muted},peekGroupTitle:{...bold,fontSize:16,color:look.ink},more:{gap:10},moreCard:{gap:10,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},moreHead:{flexDirection:"row",alignItems:"center",gap:8},moreTitle:{...bold,fontSize:16,lineHeight:lh(16,1.3),color:look.ink},moreLead:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},moreRows:{gap:6},moreRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,minHeight:44,paddingVertical:8,paddingHorizontal:14,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.card},moreRowLabel:{...body,flexShrink:1,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.text},moreWhen:{...mono,fontSize:RAPH_RN_METRICS.mono,letterSpacing:.24,color:look.muted},note:{...body,marginTop:4,fontSize:12.5,textAlign:"center",color:look.muted},mks:{gap:2,marginHorizontal:-8},mk:{flexDirection:"row",alignItems:"center",gap:12,paddingVertical:10,paddingHorizontal:8},mkText:{flex:1,minWidth:0},mkNameRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:8},mkName:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},mkLine:{...body,marginTop:1,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},mkValue:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,color:look.text},mkBar:{position:"relative",width:96,height:6,borderRadius:999,backgroundColor:look.barTrack},mkBarIn:{position:"absolute",top:0,bottom:0,left:"20%",right:"20%",borderRadius:999},mkBarDot:{position:"absolute",top:-2,width:10,height:10,marginLeft:-5,borderRadius:5,borderWidth:2},topRisk:{gap:8,backgroundColor:look.topFill,borderRadius:22,borderWidth:0,shadowOpacity:0,elevation:0},topRiskKicker:{flexDirection:"row",alignItems:"center",gap:6},topRiskDot:{width:8,height:8,borderRadius:4,backgroundColor:look.alert},topRiskK:{...monoBold,fontSize:RAPH_RN_METRICS.mono,letterSpacing:.72,textTransform:"uppercase",color:look.topKicker},topRiskText:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.35),color:look.topInk},disclaimer:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.5),textAlign:"center",color:look.muted},lab:{gap:RAPH_RN_METRICS.gap,paddingTop:8,paddingHorizontal:16,paddingBottom:32,backgroundColor:look.ground},labTitle:{...face(theme,"medium"),fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.2),letterSpacing:-.33,color:look.ink},labMeta:{...mono,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.45),color:look.muted},latest:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",columnGap:12,rowGap:4},latestSub:{...body,fontSize:RAPH_RN_METRICS.body,color:look.muted},change:{...body,marginTop:12,fontSize:RAPH_RN_METRICS.body,color:look.text},changeLead:{...bold,color:look.ink},ctx:{gap:12},ctxText:{...body,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.55),color:look.text},labBody:{flexDirection:"row",gap:8},rail:{width:8,height:RAPH_RN_METRICS.plot,overflow:"hidden",borderRadius:2},legend:{width:82,height:RAPH_RN_METRICS.plot,position:"relative"},range:{...monoBold,position:"absolute",left:0,right:0,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.2),letterSpacing:.24,textTransform:"uppercase",color:look.dark?look.text:RAPH_CHARCOAL},band:{position:"absolute",left:0,right:0,top:"25%",height:"50%",backgroundColor:look.goTint}})}var RAPH_CHARCOAL="#3D3D3D";function EverfurRecordsLabDetail({petRef:petRef,petName:petName,markerId:markerId,renderExtra:renderExtra,onAsk:onAsk,renderAskButton:renderAskButton,style:style}){let view=useRecordsMarkers(petRef).markers,model=view===null||view.withheld?null:buildSheetLabModel(view,markerId);if(model===null)return null;let marker=view?.markers.find(m=>m.markerId===markerId)??null;/* @__PURE__ */
|
|
755
|
+
return jsxRuntime.jsx(LabBody,{model:model,renderExtra:renderExtra,ask:onAsk!==void 0&&marker!==null?()=>{let built=buildMarkerAskPrompt(petName,{canonicalName:marker.name,markerId:marker.markerId,latestValueText:model.latest,statusText:model.pill,trajectoryText:null,meaningText:marker.meaning});onAsk(built.prompt,built.entityRef)}:void 0,renderAskButton:renderAskButton,style:style})}function LabBody({model:model,renderExtra:renderExtra,ask:ask,renderAskButton:renderAskButton,style:style}){let{s:s,look:look}=useSheetKit();/* @__PURE__ */
|
|
756
|
+
return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:[s.lab,style],testID:`everfur-records-lab-${model.markerId}`,children:[
|
|
757
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{children:[
|
|
758
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.labTitle,accessibilityRole:"header",children:model.name}),model.meta!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.labMeta,children:model.meta}):null]}),
|
|
759
|
+
/* @__PURE__ */jsxRuntime.jsxs(SheetCard,{children:[
|
|
760
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.cardHead,children:[
|
|
761
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.cardTitle,accessibilityRole:"header",children:SHEET_COPY.latestReading}),model.pill!==null?/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:model.pill,tone:model.flagged?"high":"clear"}):null]}),
|
|
762
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.latest,children:[
|
|
763
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.wtValue,{color:model.flagged?look.alert:look.ink}],children:model.latest}),
|
|
764
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.latestSub,children:model.latestSub})]}),
|
|
765
|
+
/* @__PURE__ */jsxRuntime.jsx(LabChart,{model:model}),model.change!==null?/* @__PURE__ */jsxRuntime.jsxs(Text,{style:s.change,children:[
|
|
766
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.changeLead,children:model.change.lead}),model.change.rest]}):null]}),renderExtra!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderExtra(model.markerId),fallback:null,resetKey:model.markerId}):null,model.meaning.length>0?/* @__PURE__ */jsxRuntime.jsxs(SheetCard,{children:[
|
|
767
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.cardTitle,s.cardTitleGap],accessibilityRole:"header",children:SHEET_COPY.whatIs(model.name)}),
|
|
768
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.ctx,children:model.meaning.map((p,i)=>/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.ctxText,children:p},i))})]}):null,model.groups.map((g,gi)=>/* @__PURE__ */jsxRuntime.jsxs(SheetCard,{children:[
|
|
769
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.cardHead,children:[
|
|
770
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.cardTitle,accessibilityRole:"header",children:g.title}),g.allInRange?/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:SHEET_COPY.inRange,tone:"clear"}):null]}),
|
|
771
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.mks,children:g.rows.map(r=>/* @__PURE__ */jsxRuntime.jsx(SheetMarkerRow,{name:r.name,value:r.value,unit:r.unit,range:r.range,at:r.at,pill:r.flag==="above"?SHEET_COPY.high:r.flag==="below"?SHEET_COPY.belowRangePill:null},r.markerId))})]},`${g.title}-${gi}`)),ask===void 0?null:renderAskButton!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderAskButton(ask,SHEET_COPY.askAboutThis),fallback:null,resetKey:model.markerId}):/* @__PURE__ */jsxRuntime.jsx(SheetButton,{kind:"ink",label:SHEET_COPY.askAboutThis,onPress:ask,testID:"everfur-records-lab-ask"})]})}function LabChart({model:model}){let{s:s,look:look}=useSheetKit();if(model.chart.length===0)return null;let banded=model.hasRange;/* @__PURE__ */
|
|
772
|
+
return jsxRuntime.jsxs(reactNative.View,{style:s.chart,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[
|
|
773
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.labBody,children:[banded?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
774
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.rail,children:[
|
|
775
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:1,backgroundColor:look.alert}}),
|
|
776
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:2,backgroundColor:look.go}}),
|
|
777
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:1,backgroundColor:look.line}})]}),
|
|
778
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.legend,children:[
|
|
779
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.range,{top:"6%"}],children:SHEET_COPY.above}),
|
|
780
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.range,{top:"44%"}],children:SHEET_COPY.inRange}),
|
|
781
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.range,{top:"82%"}],children:SHEET_COPY.below})]})]}):null,
|
|
782
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[s.plot,{flex:1}],children:[banded?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.band}):null,model.chart.length>1?/* @__PURE__ */jsxRuntime.jsx(ChartLine,{points:model.chart,color:look.ink}):null,model.chart.map((p,i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.point,{left:`${p.x}%`,top:`${p.y}%`,backgroundColor:p.out?look.alert:look.ink}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.pointLabel,p.out?{color:look.alert}:null],children:p.label})},i))]})]}),
|
|
783
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.xAxis,banded?{marginLeft:106}:null],children:model.chart.map((p,i)=>/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.xTick,{left:`${p.x}%`}],children:p.tick},i))})]})}var LB_PER_KG2=2.20462,kgToLb=kg=>Math.round(kg*LB_PER_KG2*10)/10,kg1=kg=>Math.round(kg*10)/10;function capitalize(text4){return text4.length===0?text4:text4.charAt(0).toUpperCase()+text4.slice(1)}function pronounFromSex(sex){return sex==="female"?"her":sex==="male"?"his":null}function rnSheetWords(name,pronoun){let trimmed=name?.trim()??"",shown=trimmed.length>0?trimmed:NAMELESS_PET,words2=sheetPetWords(shown,pronoun);/* @__PURE__ */
|
|
784
|
+
return Object.freeze({...words2,Poss:capitalize(words2.Poss)})}function rnSheetHeading(name){let trimmed=name?.trim()??"";return trimmed.length>0?trimmed:RECORD_SCREEN_COPY.document.namelessPet}var DOG_ONLY_ROW=/heartworm|4dx/i;function rnSamplePeek(species){let dog=canonicalPetSpecies(species??null)==="dog",more=SHEET_SAMPLE.more.map(card=>({card:card,rows:dog?card.rows:card.rows.filter(row=>!DOG_ONLY_ROW.test(row.label))})).filter(entry=>entry.rows.length>0);return{labsTitle:SHEET_SAMPLE.labsTitle,group:SHEET_SAMPLE.group,groupLead:SHEET_SAMPLE.groupLead,markers:SHEET_SAMPLE.markers,more:more}}var ONE_READING_LINE="One reading so far: we’ll plot a trend as more come in.";function readingsKg(timeline){return timeline===null||timeline.withheld?[]:timeline.weights.flatMap(w=>{let ms=dayMs(w.observedOn);return ms===null||w.weightKg===null?[]:[{ms:ms,kg:w.weightKg}]}).sort((a,b)=>a.ms-b.ms)}function rnWeight(shared,timeline,unit){if(shared===null)return null;let readings=readingsKg(timeline),last=readings[readings.length-1];if(last===void 0||readings.length!==shared.points.length)return{latest:shared.latest,sub:shared.sub,points:shared.points.map(p=>({x:p.x,y:p.y,label:String(p.lb),ms:p.ms})),ticks:shared.ticks,vetCount:shared.vetCount,single:shared.points.length===1};let label=kg=>unit==="kg"?num4(kg1(kg)):num4(kgToLb(kg)),latest=unit==="kg"?`${num4(kg1(last.kg))} kg`:`${num4(kgToLb(last.kg))} lb`,sub=unit==="kg"?`${num4(kgToLb(last.kg))} lb · ${shortDate(last.ms)}`:`${num4(kg1(last.kg))} kg · ${shortDate(last.ms)}`;return{latest:latest,sub:sub,points:shared.points.map((p,i)=>({x:p.x,y:p.y,label:label(readings[i]?.kg??last.kg),ms:p.ms})),ticks:shared.ticks,vetCount:shared.vetCount,single:shared.points.length===1}}function rnMeta(breed,weight,petWeightKg,unit){let w=weight?.latest??(petWeightKg==null?null:unit==="kg"?`${num4(kg1(petWeightKg))} kg`:`${num4(kgToLb(petWeightKg))} lb`),parts=[breed?.trim()||null,w].filter(p=>p!==null);return parts.length>0?parts.join(" · "):null}var RN_SHEET_APP_COPY=/* @__PURE__ */Object.freeze({noDueDate:"No due date on file",noVisits:pet=>`No visits in ${pet}’s records yet. They show up here when a record includes one.`,medications:entityTypeLabel("medication"),noCurrentMedications:"No current medications on file.",oneReading:ONE_READING_LINE,topRiskKicker:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`}),RECORDS_SHEET_RN_COPY=/* @__PURE__ */Object.freeze({undatedPill:""});function rnCurrentMedications(timeline,nowMs){if(timeline===null||timeline.withheld)return null;let current=m=>{let stop=dayMs(m.stoppedOn);return stop===null||stop>=nowMs};return timeline.medications.filter(m=>current(m)&&(m.drugName?.trim()??"").length>0).map((m,i)=>{let parts=[m.dose,m.route,m.frequency].filter(p=>typeof p=="string"&&p.trim().length>0);return{key:`${m.medicationId}-${i}`,title:(m.drugName??"").trim(),detail:parts.length>0?parts.join(" · "):null}})}function rnFailedRequest(requests,petRef){let mine=requests.filter(r=>r.petRef===petRef);if(mine.some(r=>!isTerminalStatus(r.status)))return null;let latest=[...mine].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(latest===void 0||latest.status!=="failed"&&latest.status!=="revoked")return null;let label=selectPrimaryLabel(latest).trim();return label.length>0?{id:latest.id,label:label}:null}function rnTopRiskText(focus){if(focus==null)return null;let risk=[focus.risk?.lead?.trim()??"",focus.risk?.body?.trim()??""].filter(p=>p.length>0).join(" ");if(risk.length>0)return risk;let title=focus.title.trim();return title.length>0?title:null}function planPageSex(pet){return pet?.sex??null}function recordSex(record){if(record==null||record.withheld)return null;let value=record.identity.find(r=>r.label.trim().toLowerCase()==="sex")?.value.trim().toLowerCase()??"";return value.length===0?null:/\bfemale\b/.test(value)||/^(f|fs)$/.test(value)?"female":/\bmale\b/.test(value)||/^(m|mn)$/.test(value)?"male":null}var readDepth4=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty4=value=>!value.available,readTimeline2=(client,petRef)=>client.getTimeline(petRef),timelineEmpty2=value=>value.isEmpty,NO_OPTIONS=/* @__PURE__ */Object.freeze({});function EverfurRecordsSheet(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),kit=useSheetKitValue();/* @__PURE__ */
|
|
785
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(SheetKitProvider,{value:kit,children:/* @__PURE__ */jsxRuntime.jsx(SheetScreen,{...rest,style:style})})})}function SheetScreen({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,options:options=NO_OPTIONS,style:style}){let{s:s,look:look}=useSheetKit(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),markers=useRecordsMarkers(petRef),depth=useRecordsDepthRead(petRef,readDepth4,depthEmpty4),timeline=useRecordsDepthRead(petRef,readTimeline2,timelineEmpty2),{pets:pets}=useEverfurPets(),pet=pets.find(p=>p.petRef===petRef)??null,presentation=useEverfurPresentation(options.presentation??null);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),clinicDecision=useCapability("recordsClinic"),canRequest=clinicDecision.enabled||clinicDecision.isPending,[labOpen,setLabOpen]=react.useState(null),[clock]=react.useState(()=>options.nowMs??Date.now()),now=options.nowMs??clock,knownPronoun=options.pronoun??pronounFromSex(options.sex)??pronounFromSex(recordSex(records.record))??null,needPlanForSex=knownPronoun===null&&records.status!=="loading",planCapability=useCapability("healthPlan"),plan=useHealthPlanPage({petRef:petRef,enabled:planCapability.enabled&&(presentation.recordsTopRiskLine||needPlanForSex)}),planPet=plan.page?.pet??null,pronoun=knownPronoun??pronounFromSex(planPageSex(planPet)),name=petName?.trim()||pet?.name?.trim()||planPet?.name?.trim()||"",species=options.species??pet?.species??planPet?.species??null,unit=options.weightUnit??"lb",words2=rnSheetWords(name,pronoun),copy={...RECORDS_SHEET_RN_COPY,...options.copy??{}},model=react.useMemo(()=>buildRecordsSheetModel({words:words2,record:records.record,depth:depth.value,markers:markers.markers,timeline:timeline.value,requests:records.requests,breed:pet?.breed??planPet?.breed??null,petWeightKg:pet?.weightKg??planPet?.weightKg??null,nowMs:now}),[name,pronoun,records.record,records.requests,depth.value,markers.markers,timeline.value,pet,planPet,now]),weight=rnWeight(model.weight,timeline.value,unit),meta=rnMeta(pet?.breed??planPet?.breed??null,weight,pet?.weightKg??planPet?.weightKg??null,unit),failed=rnFailedRequest(records.requests,petRef),topRisk=presentation.recordsTopRiskLine?rnTopRiskText(plan.page?.page?.focus):null,meds=rnCurrentMedications(timeline.value,now),disclaimer=[markers.markers?.disclaimer,records.record?.disclaimer,timeline.value?.disclaimer].map(d=>d?.trim()??"").find(d=>d.length>0)??"";react.useEffect(()=>{if(labOpen===null)return;let sub=reactNative.BackHandler.addEventListener("hardwareBackPress",()=>(setLabOpen(null),true));return()=>{sub.remove()}},[labOpen]);let openMarker=markerId=>{options.onOpenMarker!==void 0?options.onOpenMarker(markerId):setLabOpen(markerId)},go={request:()=>onNavigate?.({name:"clinicPicker"}),upload:()=>onNavigate?.({name:"upload"}),record:()=>onNavigate?.({name:"record"}),timeline:()=>onNavigate?.({name:"timeline"})},retryAll=()=>{records.refresh(),markers.refresh(),depth.refresh(),timeline.refresh()},canAct=onNavigate!==void 0;if(labOpen!==null)/* @__PURE__ */
|
|
786
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[{flex:1,backgroundColor:look.ground},style],children:[
|
|
787
|
+
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:rnSheetHeading(name),onBack:()=>setLabOpen(null),testID:"everfur-records-lab-header"}),
|
|
788
|
+
/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsLabDetail,{petRef:petRef,markerId:labOpen,...name.length>0?{petName:name}:{},...onAsk?{onAsk:onAsk}:{}}),
|
|
789
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]});let body,state="full";if(records.status==="loading"&&records.record===null)body=/* @__PURE__ */jsxRuntime.jsx(DashboardSkeleton,{testID:"everfur-records-sheet-loading"}),state="loading";else if(records.status==="error"){let view=selectErrorView(records,canGrant);isConsentGate(view)?(state="consent",body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:[s.sheet,options.style],children:[renderErrorFamily(records,onGrant,canGrant,consentText),canAct?/* @__PURE__ */jsxRuntime.jsx(AddCard,{words:words2,model:null,canRequest:canRequest,onRequest:go.request,onUpload:go.upload}):null]})):view.kind==="error"||view.kind==="pet_not_found"?(state="error",body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(view.error),message:view.error.displayMessage,onAction:view.error.retryable?retryAll:void 0,testID:"everfur-records-sheet-error"})):(state=view.kind,body=renderErrorFamily(records,onGrant,canGrant,consentText))}else{state=model.state;let failedLine=failed!==null?/* @__PURE__ */jsxRuntime.jsx(FailedLine,{label:failed.label,onPress:canAct?()=>onNavigate?.({name:"request",requestId:failed.id}):void 0}):null,foot=disclaimer.length>0&&!disclaimerRepeatsFootnote(disclaimer)?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.disclaimer,testID:"everfur-records-sheet-disclaimer",children:disclaimer}):null;body=model.state!=="full"?/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:[s.sheet,options.style],children:[failedLine,
|
|
790
|
+
/* @__PURE__ */jsxRuntime.jsx(NoneCard,{words:words2,model:model,canAct:canAct,canRequest:canRequest,onRequest:go.request,onUpload:go.upload}),
|
|
791
|
+
/* @__PURE__ */jsxRuntime.jsx(SamplePeek,{words:words2,species:species}),
|
|
792
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.note,children:SHEET_COPY.sampleNote(words2)}),foot]}):/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:[s.sheet,options.style],children:[options.renderTopSlot!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>options.renderTopSlot?.({clearResultsFilter:presentation.recordsClearResultsFilter})??null,fallback:null,resetKey:petRef}):null,
|
|
793
|
+
/* @__PURE__ */jsxRuntime.jsx(Head,{words:words2,name:name,meta:meta,model:model,renderStage:options.renderStage}),topRisk!==null?/* @__PURE__ */jsxRuntime.jsx(TopRisk,{words:words2,text:topRisk,onOpenPlan:options.onOpenPlan}):null,failedLine,
|
|
794
|
+
/* @__PURE__ */jsxRuntime.jsx(Upcoming,{due:model.due,copy:copy,renderAction:options.renderUpcomingCareAction}),
|
|
795
|
+
/* @__PURE__ */jsxRuntime.jsx(Tiles,{words:words2,model:model,onOpenMarker:openMarker,onOpenScreenings:options.onOpenScreenings,onOpenRecord:canAct?go.record:void 0,onOpenTimeline:canAct?go.timeline:void 0}),
|
|
796
|
+
/* @__PURE__ */jsxRuntime.jsx(WeightCard,{weight:weight}),
|
|
797
|
+
/* @__PURE__ */jsxRuntime.jsx(History,{words:words2,model:model,onOpenMarker:openMarker}),meds!==null?/* @__PURE__ */jsxRuntime.jsx(Medications,{meds:meds}):null,canAct?/* @__PURE__ */jsxRuntime.jsx(AddCard,{words:words2,model:model,canRequest:canRequest,onRequest:go.request,onUpload:go.upload}):null,foot]})}/* @__PURE__ */
|
|
798
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[{flex:1,backgroundColor:look.ground},style],testID:"everfur-records-sheet",children:[onBack!==void 0?/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:DASHBOARD_COPY.titleNative(petName),onBack:onBack,testID:"everfur-records-sheet-header"}):null,
|
|
799
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:1},testID:`everfur-records-sheet-state-${state}`,children:body}),
|
|
800
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function Head({words:words2,name:name,meta:meta,model:model,renderStage:renderStage}){let{s:s,look:look}=useSheetKit(),vitals=model.vitals.length===0?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.vitals,testID:"everfur-records-sheet-vitals",children:model.vitals.map(v=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.vital,accessible:true,accessibilityLabel:`${v.label} ${v.value}${v.unit?` ${v.unit}`:""}`,children:[
|
|
801
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.vitalTop,children:[
|
|
802
|
+
/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:v.kind==="temp"?"thermo":v.kind==="heart"?"heart":"wind",size:18,color:v.kind==="heart"?look.alert:look.chevron}),
|
|
803
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.vitalValue,children:v.value}),v.unit?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.vitalUnit,children:v.unit}):null]}),
|
|
804
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.vitalLabel,children:v.label})]},v.kind))});/* @__PURE__ */
|
|
805
|
+
return jsxRuntime.jsxs(reactNative.View,{style:s.head,testID:"everfur-records-sheet-head",children:[
|
|
806
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.name,accessibilityRole:"header",testID:"everfur-records-sheet-name",children:name.length>0?words2.name:rnSheetHeading(name)}),meta!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.meta,testID:"everfur-records-sheet-meta",children:meta}):null,renderStage!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderStage,fallback:null,resetKey:name}):null,vitals,model.vitalsFrom!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.label,children:model.vitalsFrom}):null]})}function TopRisk({words:words2,text:text4,onOpenPlan:onOpenPlan}){let{s:s}=useSheetKit();/* @__PURE__ */
|
|
807
|
+
return jsxRuntime.jsxs(SheetCard,{style:s.topRisk,testID:"everfur-records-sheet-top-risk",children:[
|
|
808
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.topRiskKicker,children:[
|
|
809
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.topRiskDot}),
|
|
810
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.topRiskK,children:RN_SHEET_APP_COPY.topRiskKicker(words2)})]}),
|
|
811
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.topRiskText,children:text4}),onOpenPlan!==void 0?/* @__PURE__ */jsxRuntime.jsx(SheetButton,{kind:"ink",row:true,label:RN_SHEET_APP_COPY.seePlan(words2),onPress:onOpenPlan,testID:"everfur-records-sheet-top-risk-plan"}):null]})}function FailedLine({label:label,onPress:onPress}){let{s:s,look:look}=useSheetKit(),inner=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
812
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.failedText,children:label}),onPress!==void 0?/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:"chevron",size:20,color:look.alertDeep}):null]});return onPress!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label,style:s.failed,testID:"everfur-records-sheet-failed",children:inner}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.failed,testID:"everfur-records-sheet-failed",children:inner})}function Upcoming({due:due,copy:copy,renderAction:renderAction}){let{s:s,look:look}=useSheetKit();return due.length===0?null:/* @__PURE__ */jsxRuntime.jsxs(SheetCard,{testID:"everfur-records-sheet-upcoming",children:[
|
|
813
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.cardTitle,s.cardTitleGap],accessibilityRole:"header",children:SHEET_COPY.upcomingCare}),
|
|
814
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.due,children:due.map((d,index)=>{let alert=d.tone==="alert",undated=d.tone==="none"&&(d.item.dueAt??null)===null,when=d.when??(undated?RN_SHEET_APP_COPY.noDueDate:null);/* @__PURE__ */
|
|
815
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[s.dueRow,alert?{backgroundColor:look.alertTint}:null],testID:`everfur-records-sheet-due-${index}`,children:[
|
|
816
|
+
/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:iconKindOf(d.icon),color:alert?look.alert:look.chevron}),
|
|
817
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.dueText,children:[
|
|
818
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.dueTitle,children:d.title}),when!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.dueWhen,alert?{color:look.alertDeep}:null],children:when}):null]}),alert&&renderAction!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderAction(d.item),fallback:null,resetKey:d.item}):d.pill!==null?/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:d.pill,tone:d.tone==="watch"?"watch":"later"}):undated?/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:copy.undatedPill,tone:"later"}):null]},`${d.title}-${index}`)})})]})}function tileGround(tint,look){return tint==="sage"?look.tintSage:tint==="emb"?look.tintPartner:tint==="blue"?look.tintBlue:look.tintYellow}function Tile({tint:tint,icon:icon,title:title,foot:foot,onOpen:onOpen,testID:testID}){let{s:s,look:look}=useSheetKit(),inner=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
819
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.tileTop,children:[
|
|
820
|
+
/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:icon,color:look.ink}),onOpen!==void 0?/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:"chevron",size:20,color:look.chevron}):null]}),
|
|
821
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.tileTitle,children:title}),
|
|
822
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.tileFoot,children:foot})]}),box3=[s.tile,{backgroundColor:tileGround(tint,look)}];return onOpen!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:title,style:box3,testID:testID,children:inner}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:box3,testID:testID,children:inner})}function Tiles({words:words2,model:model,onOpenMarker:onOpenMarker,onOpenScreenings:onOpenScreenings,onOpenRecord:onOpenRecord,onOpenTimeline:onOpenTimeline}){let{s:s}=useSheetKit(),featured=model.featuredMarkerId;/* @__PURE__ */
|
|
823
|
+
return jsxRuntime.jsxs(reactNative.View,{testID:"everfur-records-sheet-tiles",children:[
|
|
824
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.cardTitle,s.sec],accessibilityRole:"header",children:SHEET_COPY.recordsHistory}),
|
|
825
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.tiles,children:[model.labsCount>0&&featured!==null?/* @__PURE__ */jsxRuntime.jsx(Tile,{tint:"sage",icon:"flask",title:SHEET_COPY.labs,onOpen:()=>onOpenMarker(featured),testID:"everfur-records-sheet-tile-labs",foot:/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
826
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.tileNum,children:model.labsCount}),
|
|
827
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.tileUnit,children:SHEET_COPY.results})]})}):null,onOpenScreenings!==void 0?/* @__PURE__ */jsxRuntime.jsx(Tile,{tint:"emb",icon:"shield",title:SHEET_COPY.screenings,onOpen:onOpenScreenings,foot:null,testID:"everfur-records-sheet-tile-screenings"}):null,
|
|
828
|
+
/* @__PURE__ */jsxRuntime.jsx(Tile,{tint:"blue",icon:"folder",title:SHEET_COPY.visits,onOpen:onOpenRecord,testID:"everfur-records-sheet-tile-record",foot:model.latestVisit!==null?/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:model.latestVisit,tone:"plain",small:true}):/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.emptyLine,testID:"everfur-records-sheet-no-visits",children:RN_SHEET_APP_COPY.noVisits(words2.name)})}),model.historyCount>0?/* @__PURE__ */jsxRuntime.jsx(Tile,{tint:"yellow",icon:"clock",title:SHEET_COPY.timeline,onOpen:onOpenTimeline,testID:"everfur-records-sheet-tile-timeline",foot:/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:SHEET_COPY.events(model.historyCount),tone:"plain",small:true})}):null]})]})}function WeightCard({weight:weight}){let{s:s,look:look}=useSheetKit();if(weight===null)return null;let labelAll=weight.points.length<=6;/* @__PURE__ */
|
|
829
|
+
return jsxRuntime.jsxs(SheetCard,{testID:"everfur-records-sheet-weight",children:[
|
|
830
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.cardHead,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.cardTitle,accessibilityRole:"header",children:SHEET_COPY.weight})}),
|
|
831
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.wt,children:[
|
|
832
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.wtValue,testID:"everfur-records-sheet-weight-latest",children:weight.latest}),
|
|
833
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.wtSub,children:weight.sub})]}),weight.single?
|
|
834
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.emptyLine,{marginTop:8}],testID:"everfur-records-sheet-weight-one",children:RN_SHEET_APP_COPY.oneReading}):/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.chart,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[
|
|
835
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.plot,children:[
|
|
836
|
+
/* @__PURE__ */jsxRuntime.jsx(ChartLine,{points:weight.points,color:look.ink}),weight.points.map((p,i)=>{let last=i===weight.points.length-1;/* @__PURE__ */
|
|
837
|
+
return jsxRuntime.jsx(reactNative.View,{style:[s.point,{left:`${p.x}%`,top:`${p.y}%`,backgroundColor:look.ink}],children:labelAll||last?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.pointLabel,children:p.label}):null},`${p.ms}-${i}`)})]}),
|
|
838
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.xAxis,children:weight.ticks.map((t,i)=>/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.xTick,{left:`${t.x}%`}],children:t.label},`${t.label}-${i}`))}),
|
|
839
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.key,children:[
|
|
840
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.keyDot}),
|
|
841
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.keyText,children:SHEET_COPY.vetVisits(weight.vetCount)})]})]})]})}function Pull({step:step,pct:pct2,none:none}){let{s:s}=useSheetKit();/* @__PURE__ */
|
|
842
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[s.pull,none===true?s.pullNone:null],accessibilityLiveRegion:"polite",testID:"everfur-records-sheet-pull",children:[
|
|
843
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.pullStep,children:step}),
|
|
844
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.pullBar,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.pullFill,{width:`${pct2}%`}]})})]})}function HistoryRow({item:item,last:last,onOpenMarker:onOpenMarker}){let{s:s,look:look}=useSheetKit(),markerId=item.markerId,text4=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
845
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.tlDate,children:item.date}),
|
|
846
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.tlTitle,children:item.title}),item.text!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.tlText,children:item.text}):null]});/* @__PURE__ */
|
|
847
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[s.tlItem,last?s.tlItemLast:null],children:[last?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.tlRail}),
|
|
848
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.tlDot,item.alert?{borderColor:look.alert}:null]}),
|
|
849
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.tlBody,children:markerId!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>onOpenMarker(markerId),accessibilityRole:"button",accessibilityLabel:`${item.date}. ${item.title}`,style:s.tlBtn,testID:`everfur-records-sheet-history-marker-${markerId}`,children:[text4,
|
|
850
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.tlChevron,children:/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:"chevron",size:20,color:look.alert})})]}):text4})]})}function History({words:words2,model:model,onOpenMarker:onOpenMarker}){let{s:s}=useSheetKit();if(model.history.length===0&&model.pull===null)return null;let first=model.history[0];/* @__PURE__ */
|
|
851
|
+
return jsxRuntime.jsxs(SheetCard,{testID:"everfur-records-sheet-history",children:[
|
|
852
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.cardTitle,s.cardTitleGap],accessibilityRole:"header",children:SHEET_COPY.history}),model.history.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.tlKey,children:[
|
|
853
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.tlKeyDot}),
|
|
854
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.keyText,children:SHEET_COPY.theirClinic(words2)})]}):null,first!==void 0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.tlYear,children:first.year}):null,model.pull!==null?/* @__PURE__ */jsxRuntime.jsx(Pull,{step:model.pull.step,pct:model.pull.pct}):null,model.history.map((year,y)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{children:[y>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.tlYear,children:year.year}):null,year.items.map((item,i)=>/* @__PURE__ */jsxRuntime.jsx(HistoryRow,{item:item,onOpenMarker:onOpenMarker,last:i===year.items.length-1},item.key))]},year.year))]})}function Medications({meds:meds}){let{s:s}=useSheetKit();/* @__PURE__ */
|
|
855
|
+
return jsxRuntime.jsxs(SheetCard,{testID:"everfur-records-sheet-meds",children:[
|
|
856
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.cardTitle,s.cardTitleGap],accessibilityRole:"header",children:RN_SHEET_APP_COPY.medications}),meds.length===0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.emptyLine,children:RN_SHEET_APP_COPY.noCurrentMedications}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.sources,children:meds.map(m=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.source,children:[
|
|
857
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.sourceLabel,children:m.title}),m.detail!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.sourceDetail,children:m.detail}):null]},m.key))})]})}function AddCard({words:words2,model:model,canRequest:canRequest,onRequest:onRequest,onUpload:onUpload}){let{s:s,look:look}=useSheetKit(),sources=model?.sources??[];/* @__PURE__ */
|
|
858
|
+
return jsxRuntime.jsxs(SheetCard,{style:s.add,testID:"everfur-records-sheet-add",children:[
|
|
859
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.addHead,children:[
|
|
860
|
+
/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:"clip",color:look.ink}),
|
|
861
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.cardTitle,{flexShrink:1}],accessibilityRole:"header",children:SHEET_COPY.addRecords(words2)})]}),
|
|
862
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.addLead,children:SHEET_COPY.moreThanOneClinic}),sources.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.sources,accessibilityLabel:SHEET_COPY.onFileNow,children:sources.map(src=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.source,children:[
|
|
863
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.sourceLabel,children:src.label}),
|
|
864
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.sourceDetail,children:src.detail})]},src.label))}):null,
|
|
865
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.addActs,children:[canRequest?/* @__PURE__ */jsxRuntime.jsx(SheetButton,{kind:"ink",icon:"download",label:SHEET_COPY.requestFromClinic,onPress:onRequest,testID:"everfur-records-sheet-request"}):null,
|
|
866
|
+
/* @__PURE__ */jsxRuntime.jsx(SheetButton,{kind:"outline",icon:"upload",label:SHEET_COPY.uploadDocument,onPress:onUpload,testID:"everfur-records-sheet-upload"})]})]})}function NoneCard({words:words2,model:model,canAct:canAct,canRequest:canRequest,onRequest:onRequest,onUpload:onUpload}){let{s:s}=useSheetKit(),onTheWay=model.state==="onTheWay";/* @__PURE__ */
|
|
867
|
+
return jsxRuntime.jsxs(SheetCard,{testID:"everfur-records-sheet-none",children:[
|
|
868
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.noneTitle,accessibilityRole:"header",children:onTheWay?SHEET_COPY.onTheWay(words2):SHEET_COPY.firstRecord(words2)}),
|
|
869
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.noneLead,children:onTheWay?SHEET_COPY.clinicsTake:SHEET_COPY.firstLead(words2)}),model.pull!==null?/* @__PURE__ */jsxRuntime.jsx(Pull,{step:model.pull.step,pct:model.pull.pct,none:true}):null,canAct?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.ways,testID:"everfur-records-sheet-none-ways",children:[canRequest?/* @__PURE__ */jsxRuntime.jsx(SheetWay,{kind:"ink",icon:"download",onPress:onRequest,testID:"everfur-records-sheet-none-request",title:onTheWay?SHEET_COPY.anotherClinic:SHEET_COPY.requestFromTheirClinic(words2),detail:onTheWay?SHEET_COPY.anotherClinicDetail:SHEET_COPY.requestDetail}):null,
|
|
870
|
+
/* @__PURE__ */jsxRuntime.jsx(SheetWay,{kind:"drop",icon:"upload",onPress:onUpload,testID:"everfur-records-sheet-none-upload",title:SHEET_COPY.uploadDocument,detail:SHEET_COPY.uploadDetail})]}):null]})}function SamplePeek({words:words2,species:species}){let{s:s,look:look}=useSheetKit(),peek=rnSamplePeek(species);/* @__PURE__ */
|
|
871
|
+
return jsxRuntime.jsxs(reactNative.View,{style:s.peek,testID:"everfur-records-sheet-sample",children:[
|
|
872
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.peekHead,children:[
|
|
873
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.cardTitle,accessibilityRole:"header",children:SHEET_COPY.recordsHistory}),
|
|
874
|
+
/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:SHEET_COPY.sample,tone:"plain"})]}),
|
|
875
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.peekLead,children:SHEET_COPY.peekLead(words2)}),
|
|
876
|
+
/* @__PURE__ */jsxRuntime.jsxs(SheetCard,{children:[
|
|
877
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.cardTitle,s.cardTitleGap],children:peek.labsTitle}),
|
|
878
|
+
/* @__PURE__ */jsxRuntime.jsxs(Text,{style:s.peekGroup,children:[
|
|
879
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.peekGroupTitle,children:peek.group}),` ${peek.groupLead}`]}),
|
|
880
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.mks,children:peek.markers.map(m=>/* @__PURE__ */jsxRuntime.jsx(SheetMarkerRow,{name:m.name,value:m.value,unit:m.unit,range:m.range,at:m.at,pill:m.high?SHEET_COPY.high:null},m.name))})]}),
|
|
881
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.more,testID:"everfur-records-sheet-sample-more",children:peek.more.map(({card:card,rows:rows})=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[s.moreCard,{backgroundColor:tileGround(card.tint,look)}],testID:`everfur-records-sheet-sample-${card.tint}`,children:[
|
|
882
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.moreHead,children:[
|
|
883
|
+
/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:iconKindOf(card.icon),color:look.ink}),
|
|
884
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.moreTitle,children:card.title})]}),
|
|
885
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.moreLead,children:card.lead(words2)}),
|
|
886
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.moreRows,children:rows.map(row=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.moreRow,children:[
|
|
887
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.moreRowLabel,children:row.label}),"pill"in row&&typeof row.pill=="string"?/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:row.pill,tone:row.tone==="clear"?"clear":"watch"}):/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.moreWhen,children:row.when})]},row.label))})]},card.title))})]})}function EverfurRecordsFlow(props){let{petRef:petRef,petName:petName,controller:controller,clinicController:clinicController,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,consentVersion:consentVersion,consentText:consentText,ownerName:ownerName,onCaptureSignature:onCaptureSignature,initialScreen:initialScreen,onExit:onExit,style:style,renderPending:renderPending,onOpenUrl:onOpenUrl,onCopy:onCopy,onAsk:onAsk,location:location,sheet:sheet=true}=guardHostProps(props,["onExit"]),[nav,dispatch]=react.useReducer(recordsNavReducer,initialScreen,initialRecordsNav),screen=currentRecordsScreen(nav),depth=nav.stack.length;react.useEffect(()=>{let onBackPress=()=>depth<=1?false:(dispatch({type:"pop"}),true),subscription=reactNative.BackHandler.addEventListener("hardwareBackPress",onBackPress);return()=>{subscription.remove()}},[depth]);let onNavigate=react.useCallback(to=>dispatch({type:"navigate",screen:to}),[]),onBack=react.useMemo(()=>popRecordsNav(nav).handled?()=>dispatch({type:"pop"}):onExit,[nav,onExit]),seams={onNavigate:onNavigate,...onBack?{onBack:onBack}:{},...petName!==void 0?{petName:petName}:{},...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{},...onAsk?{onAsk:onAsk}:{},...location?{location:location}:{}},records={...controller?{controller:controller}:{},...consentVersion!==void 0?{consentVersion:consentVersion}:{},...consentText!==void 0?{consentText:consentText}:{}},uploads={...onPickDocument?{onPickDocument:onPickDocument}:{},...onPickPhotos?{onPickPhotos:onPickPhotos}:{},...uploadTransport?{uploadTransport:uploadTransport}:{}},pending=renderPending?{renderPending:renderPending}:{};switch(screen.name){case"dashboard":return sheet!==false?/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsSheet,{petRef:petRef,...seams,...records,...pending,...typeof sheet=="object"?{options:sheet}:{},style:style}):/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsDashboard,{petRef:petRef,...seams,...records,...pending,style:style});case"request":/* @__PURE__ */
|
|
725
888
|
return jsxRuntime.jsx(EverfurRecordsRequest,{petRef:petRef,requestId:screen.requestId,...seams,...records,...uploads,...pending,style:style});case"timeline":/* @__PURE__ */
|
|
726
889
|
return jsxRuntime.jsx(EverfurRecordsTimeline,{petRef:petRef,...seams,style:style});case"record":/* @__PURE__ */
|
|
727
890
|
return jsxRuntime.jsx(EverfurRecordDetail,{petRef:petRef,...seams,...records,...pending,style:style});case"document":/* @__PURE__ */
|
|
728
891
|
return jsxRuntime.jsx(EverfurRecordDocument,{petRef:petRef,...seams,...records,...pending,style:style});case"contributions":/* @__PURE__ */
|
|
729
892
|
return jsxRuntime.jsx(EverfurDocumentContributions,{petRef:petRef,docId:screen.docId,...seams,style:style});case"clinicPicker":/* @__PURE__ */
|
|
730
893
|
return jsxRuntime.jsx(EverfurClinicPicker,{petRef:petRef,...seams,...clinicController?{controller:clinicController}:{},...controller?{recordsController:controller}:{},style:style});case"clinicBatch":/* @__PURE__ */
|
|
731
|
-
return jsxRuntime.jsx(EverfurClinicRequestBatch,{petRef:petRef,petName:petName??"",ownerName:ownerName??""
|
|
894
|
+
return jsxRuntime.jsx(EverfurClinicRequestBatch,{petRef:petRef,petName:petName??"",ownerName:ownerName??"",onClose:onBack??(()=>dispatch({type:"navigate",screen:{name:"dashboard"}})),...onCaptureSignature?{onCaptureSignature:onCaptureSignature}:{},...clinicController?{controller:clinicController}:{},style:style});case"consent":/* @__PURE__ */
|
|
732
895
|
return jsxRuntime.jsx(EverfurRecordsConsent,{petRef:petRef,clinic:screen.clinic,...seams,...ownerName!==void 0?{ownerName:ownerName}:{},...onCaptureSignature?{onCaptureSignature:onCaptureSignature}:{},...clinicController?{controller:clinicController}:{},style:style});case"upload":/* @__PURE__ */
|
|
733
896
|
return jsxRuntime.jsx(EverfurRecordsUpload,{petRef:petRef,...seams,...controller?{controller:controller}:{},...uploads,...pending,style:style});case"requests":/* @__PURE__ */
|
|
734
897
|
return jsxRuntime.jsx(EverfurRecordsRequests,{petRef:petRef,...seams,...controller?{controller:controller}:{},...pending,style:style});default:return assertNever(screen)}}var EverfurRecords=EverfurRecordsFlow;function EverfurClinicRequest(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
735
|
-
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(ClinicRequestBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}function ClinicRequestBody(props){let runtimeController=useEverfurRecordsClinic(),[png,setPng]=react.useState(null),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),form=useClinicRequestForm(props,props.controller??runtimeController,props.onCaptureSignature??padCapture),signed=props.onCaptureSignature!==void 0||png!==null,theme=useEverfurTheme(),field={minHeight:44,padding:theme.space.sm,borderWidth:1,borderColor:theme.color.borderHairlineGreen,borderRadius:theme.radius.sm,color:theme.color.text.primary,backgroundColor:theme.color.surface},input={...field,...slotBox(theme.slots.input,1),...slotText(theme.slots.input)},
|
|
898
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(ClinicRequestBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}function ClinicRequestBody(props){let runtimeController=useEverfurRecordsClinic(),[png,setPng]=react.useState(null),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),form=useClinicRequestForm(props,props.controller??runtimeController,props.onCaptureSignature??padCapture),signed=props.onCaptureSignature!==void 0||png!==null,theme=useEverfurTheme(),field={minHeight:44,padding:theme.space.sm,borderWidth:1,borderColor:theme.color.borderHairlineGreen,borderRadius:theme.radius.sm,color:theme.color.text.primary,backgroundColor:theme.color.surface},input={...field,...slotBox(theme.slots.input,1),...slotText(theme.slots.input)},text4={color:theme.color.text.primary,fontSize:theme.type.size.body},button=(label,action,disabled=false)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{disabled:disabled},disabled:disabled,onPress:action,style:[field,{justifyContent:"center",opacity:disabled?.5:1}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:label})});/* @__PURE__ */
|
|
736
899
|
return jsxRuntime.jsxs(reactNative.View,{accessibilityLabel:CLINIC_REQUEST_COPY.title,style:[{backgroundColor:theme.color.surface,padding:theme.space.lg,gap:theme.space.md,borderRadius:theme.radius.lg,minHeight:120},props.style],children:[
|
|
737
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:[
|
|
738
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:
|
|
739
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:
|
|
900
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:[text4,{...headingFace(theme,"bold"),fontSize:theme.type.size.heading}],children:CLINIC_REQUEST_COPY.title}),
|
|
901
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:props.petName}),form.created?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:text4,children:form.created.statusLabel||RECORDS_COPY.records}):/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
902
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:CLINIC_REQUEST_COPY.ownerName}),
|
|
740
903
|
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.ownerName,style:input,value:form.ownerName,maxLength:200,editable:!form.busy,autoComplete:"name",onChangeText:form.setOwnerName}),
|
|
741
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:
|
|
742
|
-
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.clinic,style:input,value:form.query,placeholder:CLINIC_REQUEST_COPY.placeholder,placeholderTextColor:theme.color.text.placeholder,maxLength:200,editable:!form.busy,onChangeText:form.setQuery}),button(CLINIC_REQUEST_COPY.search,()=>{form.search()},form.busy||form.searching||form.query.trim().length<2),form.searching&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:
|
|
743
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:
|
|
904
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:CLINIC_REQUEST_COPY.clinic}),
|
|
905
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.clinic,style:input,value:form.query,placeholder:CLINIC_REQUEST_COPY.placeholder,placeholderTextColor:theme.color.text.placeholder,maxLength:200,editable:!form.busy,onChangeText:form.setQuery}),button(CLINIC_REQUEST_COPY.search,()=>{form.search()},form.busy||form.searching||form.query.trim().length<2),form.searching&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:text4,children:RECORDS_COPY.loading}),form.recent.length>0&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:text4,testID:"records-clinic-recent-label",children:CLINIC_REQUEST_COPY.recentlyUsed}),form.recent.map(clinic=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:button([clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),()=>form.selectClinic(clinic),form.busy)},`recent-${clinic.id}`)),form.visibleClinics.map(clinic=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:button([clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),()=>form.selectClinic(clinic),form.busy)},clinic.id)),form.hasMoreClinics&&button(CLINIC_REQUEST_COPY.moreClinics,form.showMoreClinics,form.busy),form.needsEmail&&/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
906
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:CLINIC_REQUEST_COPY.email}),
|
|
744
907
|
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.email,style:input,value:form.email,placeholder:CLINIC_REQUEST_COPY.emailPlaceholder,placeholderTextColor:theme.color.text.placeholder,maxLength:320,editable:!form.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:form.setEmail})]}),
|
|
745
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:
|
|
746
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}exports.EverfurClinicPicker=EverfurClinicPicker;exports.EverfurClinicRequest=EverfurClinicRequest;exports.EverfurClinicRequestBatch=EverfurClinicRequestBatch;exports.EverfurRecordDetail=EverfurRecordDetail;exports.EverfurRecordDocument=EverfurRecordDocument;exports.EverfurRecords=EverfurRecords;exports.EverfurRecordsConsent=EverfurRecordsConsent;exports.EverfurRecordsDashboard=EverfurRecordsDashboard;exports.EverfurRecordsFlow=EverfurRecordsFlow;exports.EverfurRecordsRequest=EverfurRecordsRequest;exports.EverfurRecordsRequests=EverfurRecordsRequests;exports.EverfurRecordsUpload=EverfurRecordsUpload;exports.RECORDS_CLINIC_BATCH_MAX=RECORDS_CLINIC_BATCH_MAX;exports.RECORDS_TERMINAL=RECORDS_TERMINAL;exports.REQUEST_TIMELINE_TITLES=REQUEST_TIMELINE_TITLES;exports.SignaturePad=SignaturePad;exports.acceptsPhotos=acceptsPhotos;exports.applyFactOverlay=applyFactOverlay;exports.buildRequestTimeline=buildRequestTimeline;exports.currentRecordsScreen=currentRecordsScreen;exports.deriveRecordsDashboardState=deriveRecordsDashboardState;exports.initialRecordsNav=initialRecordsNav;exports.isFactEditable=isFactEditable;exports.isTerminalStatus=isTerminalStatus;exports.pickPetRecordsRequest=pickPetRecordsRequest;exports.popRecordsNav=popRecordsNav;exports.pushRecordsNav=pushRecordsNav;exports.recordsDenialReasonOf=recordsDenialReasonOf;exports.recordsNavReducer=recordsNavReducer;exports.registerRnSignature=registerRnSignature;exports.replaceRecordsNav=replaceRecordsNav;exports.resetRecordsNav=resetRecordsNav;exports.selectClinicCall=selectClinicCall;exports.selectDashboardView=selectDashboardView;exports.selectPrimaryLabel=selectPrimaryLabel;exports.selectRequestList=selectRequestList;exports.selectRequestTitle=selectRequestTitle;exports.transitionRecordsNav=transitionRecordsNav;exports.useEverfurRecords=useEverfurRecords;exports.useEverfurRecordsClinic=useEverfurRecordsClinic;exports.useEverfurRecordsClinicBatch=useEverfurRecordsClinicBatch;exports.useRecordFactEdit=useRecordFactEdit;exports.useRecordPdfLink=useRecordPdfLink;exports.useRecordShares=useRecordShares;exports.useRecordsMarkers=useRecordsMarkers;
|
|
908
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:text4,children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:form.query.trim()&&form.ownerName.trim()?form.scope??makeEverfurError("internalError").displayMessage:RECORDS_COPY.consentRequired}):!form.error&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:text4,children:RECORDS_COPY.loading}),!props.onCaptureSignature&&/* @__PURE__ */jsxRuntime.jsx(SignaturePad,{onChange:setPng,disabled:form.busy}),!signed&&form.ready&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",style:text4,children:CLINIC_REQUEST_COPY.missingSignature}),form.error&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:text4,children:form.error.displayMessage}),!form.copy&&form.error&&button(RECORDS_COPY.retry,form.retryCopy),button(form.busy?CLINIC_REQUEST_COPY.sending:CLINIC_REQUEST_COPY.send,()=>{form.submit()},form.busy||!form.ready||!signed)]}),props.onClose&&button(CLINIC_REQUEST_COPY.cancel,props.onClose,form.busy),
|
|
909
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}exports.EverfurClinicPicker=EverfurClinicPicker;exports.EverfurClinicRequest=EverfurClinicRequest;exports.EverfurClinicRequestBatch=EverfurClinicRequestBatch;exports.EverfurRecordDetail=EverfurRecordDetail;exports.EverfurRecordDocument=EverfurRecordDocument;exports.EverfurRecords=EverfurRecords;exports.EverfurRecordsConsent=EverfurRecordsConsent;exports.EverfurRecordsDashboard=EverfurRecordsDashboard;exports.EverfurRecordsFlow=EverfurRecordsFlow;exports.EverfurRecordsLabDetail=EverfurRecordsLabDetail;exports.EverfurRecordsRequest=EverfurRecordsRequest;exports.EverfurRecordsRequests=EverfurRecordsRequests;exports.EverfurRecordsSheet=EverfurRecordsSheet;exports.EverfurRecordsUpload=EverfurRecordsUpload;exports.RECORDS_CLINIC_BATCH_MAX=RECORDS_CLINIC_BATCH_MAX;exports.RECORDS_SHEET_RN_COPY=RECORDS_SHEET_RN_COPY;exports.RECORDS_TERMINAL=RECORDS_TERMINAL;exports.REQUEST_TIMELINE_TITLES=REQUEST_TIMELINE_TITLES;exports.SignaturePad=SignaturePad;exports.acceptsPhotos=acceptsPhotos;exports.applyFactOverlay=applyFactOverlay;exports.buildRequestTimeline=buildRequestTimeline;exports.currentRecordsScreen=currentRecordsScreen;exports.deriveRecordsDashboardState=deriveRecordsDashboardState;exports.initialRecordsNav=initialRecordsNav;exports.isFactEditable=isFactEditable;exports.isTerminalStatus=isTerminalStatus;exports.pickPetRecordsRequest=pickPetRecordsRequest;exports.popRecordsNav=popRecordsNav;exports.pushRecordsNav=pushRecordsNav;exports.recordsDenialReasonOf=recordsDenialReasonOf;exports.recordsNavReducer=recordsNavReducer;exports.recordsSheetLook=recordsSheetLook;exports.registerRnSignature=registerRnSignature;exports.replaceRecordsNav=replaceRecordsNav;exports.resetRecordsNav=resetRecordsNav;exports.selectClinicCall=selectClinicCall;exports.selectDashboardView=selectDashboardView;exports.selectPrimaryLabel=selectPrimaryLabel;exports.selectRequestList=selectRequestList;exports.selectRequestTitle=selectRequestTitle;exports.transitionRecordsNav=transitionRecordsNav;exports.useEverfurRecords=useEverfurRecords;exports.useEverfurRecordsClinic=useEverfurRecordsClinic;exports.useEverfurRecordsClinicBatch=useEverfurRecordsClinicBatch;exports.useRecordFactEdit=useRecordFactEdit;exports.useRecordPdfLink=useRecordPdfLink;exports.useRecordShares=useRecordShares;exports.useRecordsMarkers=useRecordsMarkers;
|