@everfur/sdk 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +1 -1
  3. package/dist/{Chat-Cb3Y8VwS.d.cts → Chat-B7oN62ww.d.cts} +3 -3
  4. package/dist/{Chat-ClhB_8sp.d.ts → Chat-Cugs9Dsl.d.ts} +3 -3
  5. package/dist/{DepthViews-DDiPxyzg.d.cts → DepthViews-C6qFJ3fV.d.ts} +1 -1
  6. package/dist/{DepthViews-CSCS-tZg.d.ts → DepthViews-CUNmy99u.d.cts} +1 -1
  7. package/dist/{DepthViews-CW1z8pnl.d.cts → DepthViews-CiYBIBEZ.d.ts} +1 -1
  8. package/dist/{DepthViews-BSkuUGBB.d.ts → DepthViews-GxV7wSzT.d.cts} +1 -1
  9. package/dist/{ErrorPolicyPort-NFDPe-5w.d.cts → ErrorPolicyPort-10s3HJCt.d.cts} +1 -1
  10. package/dist/{ErrorPolicyPort-DwSnmGcX.d.ts → ErrorPolicyPort-C3nNSS_j.d.ts} +1 -1
  11. package/dist/{EverfurError-pEXDbUJ1.d.cts → EverfurError-DeBqRpQV.d.cts} +1 -1
  12. package/dist/{EverfurError-pEXDbUJ1.d.ts → EverfurError-DeBqRpQV.d.ts} +1 -1
  13. package/dist/{EverfurResult-dtl8ERAw.d.cts → EverfurResult-COlXj1wq.d.cts} +1 -1
  14. package/dist/{EverfurResult-sKkoXew0.d.ts → EverfurResult-ClPTS0P2.d.ts} +1 -1
  15. package/dist/{IntakeMedia-BFZfBLjB.d.cts → IntakeMedia-B-_vA9ZB.d.cts} +2 -1
  16. package/dist/{IntakeMedia-C8GlN_GK.d.ts → IntakeMedia-CIoTXAWs.d.ts} +2 -1
  17. package/dist/animations/index.cjs +1 -1
  18. package/dist/animations/index.d.cts +6 -6
  19. package/dist/animations/index.d.ts +6 -6
  20. package/dist/animations/index.js +1 -1
  21. package/dist/{attachments-DAUy3vPR.d.ts → attachments-20X7Vuip.d.ts} +3 -3
  22. package/dist/{attachments-BD70jZZL.d.cts → attachments-CkaPnIUw.d.cts} +3 -3
  23. package/dist/{attachments-CC7aHpwZ.d.ts → attachments-DN2cNGwe.d.ts} +7 -7
  24. package/dist/{attachments-DaOaIBNf.d.cts → attachments-HXFmzk-D.d.cts} +7 -7
  25. package/dist/{bookingCopy-CUW9Gdzc.d.ts → bookingCopy-B5igVNE0.d.ts} +7 -6
  26. package/dist/{bookingCopy-oEjqkiNA.d.cts → bookingCopy-pJpizqgz.d.cts} +7 -6
  27. package/dist/{branding-ctD0B2Th.d.cts → branding-BCfwLj0h.d.cts} +1 -1
  28. package/dist/{branding-aGleD_ki.d.ts → branding-DJf4h12Q.d.ts} +1 -1
  29. package/dist/{callCopy-DHjem0R-.d.cts → callCopy-Bw6oZT54.d.cts} +7 -2
  30. package/dist/{callCopy-DHjem0R-.d.ts → callCopy-Bw6oZT54.d.ts} +7 -2
  31. package/dist/{callRoom-B1qq_D-4.d.ts → callRoom-B92eH_ij.d.ts} +1 -1
  32. package/dist/{callRoom-DfZTWFXh.d.cts → callRoom-BhIdadyV.d.cts} +1 -1
  33. package/dist/{casesRepository-Bzs7aw4t.d.cts → casesRepository-DFoK5N1O.d.cts} +2 -2
  34. package/dist/{casesRepository-CywqL6mj.d.ts → casesRepository-qAkKKgji.d.ts} +2 -2
  35. package/dist/chat/index.cjs +9 -9
  36. package/dist/chat/index.d.cts +12 -12
  37. package/dist/chat/index.d.ts +12 -12
  38. package/dist/chat/index.js +9 -9
  39. package/dist/client/index.cjs +4 -4
  40. package/dist/client/index.d.cts +14 -14
  41. package/dist/client/index.d.ts +14 -14
  42. package/dist/client/index.js +4 -4
  43. package/dist/{config-BysLVhku.d.ts → config-BB7e52FP.d.ts} +3 -3
  44. package/dist/{config-EZzEyS-c.d.cts → config-u6rK4mKt.d.cts} +3 -3
  45. package/dist/consent/index.cjs +2 -2
  46. package/dist/consent/index.d.cts +9 -9
  47. package/dist/consent/index.d.ts +9 -9
  48. package/dist/consent/index.js +2 -2
  49. package/dist/{context-DUwYArkM.d.cts → context-BZ1k4qE3.d.cts} +9 -9
  50. package/dist/{context-DpfgbnOU.d.ts → context-CJYmubjx.d.ts} +9 -9
  51. package/dist/{copy-LxZGnFXJ.d.ts → copy-CtfctY-J.d.ts} +5 -5
  52. package/dist/{copy-DK4r9oGz.d.cts → copy-DCO_lUXd.d.cts} +5 -5
  53. package/dist/core/index.cjs +4 -4
  54. package/dist/core/index.d.cts +19 -19
  55. package/dist/core/index.d.ts +19 -19
  56. package/dist/core/index.js +4 -4
  57. package/dist/{depth-DAd77kRe.d.cts → depth-C_ym3qyi.d.cts} +6 -6
  58. package/dist/{depth-Mk7quUNa.d.ts → depth-_vMRMm4x.d.ts} +6 -6
  59. package/dist/{entitlementRepository-Dra_4FU_.d.cts → entitlementRepository-DA04yM54.d.cts} +4 -4
  60. package/dist/{entitlementRepository-CrD0O7VR.d.ts → entitlementRepository-tSY9WWad.d.ts} +4 -4
  61. package/dist/{identity-75whJXyP.d.cts → identity-CUynm8S2.d.cts} +2 -2
  62. package/dist/{identity-BiyMDMrR.d.ts → identity-D5uywCtp.d.ts} +2 -2
  63. package/dist/index.cjs +14 -14
  64. package/dist/index.d.cts +19 -19
  65. package/dist/index.d.ts +19 -19
  66. package/dist/index.js +14 -14
  67. package/dist/{models-DzvqEjMm.d.cts → models-A4A5S7AG.d.cts} +1 -1
  68. package/dist/{models-CrbUwbuS.d.ts → models-CnXY5LuO.d.ts} +1 -1
  69. package/dist/notifications/index.cjs +1 -1
  70. package/dist/notifications/index.d.cts +5 -5
  71. package/dist/notifications/index.d.ts +5 -5
  72. package/dist/notifications/index.js +1 -1
  73. package/dist/{pets-DoXxTw4x.d.cts → pets-BrdkpNJH.d.cts} +2 -2
  74. package/dist/{pets-W2BuLYko.d.ts → pets-mnbN0kZG.d.ts} +2 -2
  75. package/dist/{petsRepository-yyoo0k2I.d.cts → petsRepository-CQgzEFyz.d.cts} +2 -2
  76. package/dist/{petsRepository-ByMzq1Z9.d.ts → petsRepository-RGI_xPK1.d.ts} +2 -2
  77. package/dist/photo/index.cjs +1 -1
  78. package/dist/photo/index.d.cts +3 -3
  79. package/dist/photo/index.d.ts +3 -3
  80. package/dist/photo/index.js +1 -1
  81. package/dist/{ports-zYl8S_lI.d.ts → ports-Cu_Wc5Aw.d.ts} +7 -7
  82. package/dist/{ports-BeVJYP0_.d.cts → ports-DibY-h60.d.cts} +7 -7
  83. package/dist/records/depth/index.cjs +7 -5
  84. package/dist/records/depth/index.d.cts +11 -11
  85. package/dist/records/depth/index.d.ts +11 -11
  86. package/dist/records/depth/index.js +7 -5
  87. package/dist/records/index.cjs +23 -21
  88. package/dist/records/index.d.cts +14 -14
  89. package/dist/records/index.d.ts +14 -14
  90. package/dist/records/index.js +23 -21
  91. package/dist/{requestFunnel-BPeBZdKp.d.ts → requestFunnel-BkSFsLKh.d.ts} +5 -5
  92. package/dist/{requestFunnel-DHeSzCT6.d.cts → requestFunnel-nmhlEdbM.d.cts} +5 -5
  93. package/dist/{runtimeTypes-Cc207nbn.d.ts → runtimeTypes-CU2xVmiQ.d.ts} +7 -7
  94. package/dist/{runtimeTypes-DgMizQKz.d.cts → runtimeTypes-CWG1Cm4N.d.cts} +7 -7
  95. package/dist/server/events/index.cjs +2 -2
  96. package/dist/server/events/index.d.cts +4 -4
  97. package/dist/server/events/index.d.ts +4 -4
  98. package/dist/server/events/index.js +2 -2
  99. package/dist/server/index.cjs +2 -2
  100. package/dist/server/index.d.cts +5 -5
  101. package/dist/server/index.d.ts +5 -5
  102. package/dist/server/index.js +2 -2
  103. package/dist/televet/booking/index.cjs +9 -8
  104. package/dist/televet/booking/index.d.cts +12 -12
  105. package/dist/televet/booking/index.d.ts +12 -12
  106. package/dist/televet/booking/index.js +9 -8
  107. package/dist/televet/call/index.cjs +3 -5
  108. package/dist/televet/call/index.d.cts +3 -3
  109. package/dist/televet/call/index.d.ts +3 -3
  110. package/dist/televet/call/index.js +3 -5
  111. package/dist/televet/index.cjs +2 -2
  112. package/dist/televet/index.d.cts +7 -7
  113. package/dist/televet/index.d.ts +7 -7
  114. package/dist/televet/index.js +2 -2
  115. package/dist/testing/index.cjs +2 -2
  116. package/dist/testing/index.d.cts +3 -3
  117. package/dist/testing/index.d.ts +3 -3
  118. package/dist/testing/index.js +2 -2
  119. package/dist/testing/rn/index.cjs +2 -2
  120. package/dist/testing/rn/index.d.cts +13 -13
  121. package/dist/testing/rn/index.d.ts +13 -13
  122. package/dist/testing/rn/index.js +2 -2
  123. package/dist/testing/web/index.cjs +1 -1
  124. package/dist/testing/web/index.d.cts +14 -14
  125. package/dist/testing/web/index.d.ts +14 -14
  126. package/dist/testing/web/index.js +1 -1
  127. package/dist/{timelineRows-DUQIWSjc.d.cts → timelineRows-CYF_I5Aq.d.cts} +1 -1
  128. package/dist/{timelineRows-D22vGN9t.d.ts → timelineRows-PWRoTntZ.d.ts} +1 -1
  129. package/dist/{tokens-RAKZj7M8.d.cts → tokens-DLj8OnLH.d.cts} +4 -2
  130. package/dist/{tokens-RAKZj7M8.d.ts → tokens-DLj8OnLH.d.ts} +4 -2
  131. package/dist/{typeStyle-DVj8iCC1.d.ts → typeStyle-BxVyF71R.d.ts} +2 -2
  132. package/dist/{typeStyle-Nt7w0rhE.d.cts → typeStyle-DJedEu14.d.cts} +2 -2
  133. package/dist/{useRecordsDepth-Mbysp548.d.cts → useRecordsDepth-Cg4cc4bQ.d.cts} +4 -4
  134. package/dist/{useRecordsDepth-C0Qfoghi.d.ts → useRecordsDepth-eS9BJv_a.d.ts} +4 -4
  135. package/dist/{useVetVisit-RPBOabl8.d.ts → useVetVisit-DmWa7lt1.d.ts} +2 -2
  136. package/dist/{useVetVisit-BQX_aTJs.d.cts → useVetVisit-PtBjNwZr.d.cts} +2 -2
  137. package/dist/video/index.cjs +1 -1
  138. package/dist/video/index.d.cts +3 -3
  139. package/dist/video/index.d.ts +3 -3
  140. package/dist/video/index.js +1 -1
  141. package/dist/{view-CskIgOFV.d.cts → view-D4UOm-yo.d.cts} +11 -5
  142. package/dist/{view-DqKXtxEZ.d.ts → view-n_oSGiiT.d.ts} +11 -5
  143. package/dist/web/consent/index.cjs +2 -2
  144. package/dist/web/consent/index.d.cts +9 -9
  145. package/dist/web/consent/index.d.ts +9 -9
  146. package/dist/web/consent/index.js +2 -2
  147. package/dist/web/index.cjs +10 -10
  148. package/dist/web/index.d.cts +22 -22
  149. package/dist/web/index.d.ts +22 -22
  150. package/dist/web/index.js +10 -10
  151. package/dist/web/notifications/index.cjs +1 -1
  152. package/dist/web/notifications/index.d.cts +7 -7
  153. package/dist/web/notifications/index.d.ts +7 -7
  154. package/dist/web/notifications/index.js +1 -1
  155. package/dist/web/records/depth/index.cjs +6 -5
  156. package/dist/web/records/depth/index.d.cts +11 -11
  157. package/dist/web/records/depth/index.d.ts +11 -11
  158. package/dist/web/records/depth/index.js +7 -6
  159. package/dist/web/records/index.cjs +13 -11
  160. package/dist/web/records/index.d.cts +15 -15
  161. package/dist/web/records/index.d.ts +15 -15
  162. package/dist/web/records/index.js +13 -11
  163. package/dist/web/televet/booking/index.cjs +6 -6
  164. package/dist/web/televet/booking/index.d.cts +14 -11
  165. package/dist/web/televet/booking/index.d.ts +14 -11
  166. package/dist/web/televet/booking/index.js +6 -6
  167. package/dist/web/televet/call/index.cjs +3 -5
  168. package/dist/web/televet/call/index.d.cts +3 -3
  169. package/dist/web/televet/call/index.d.ts +3 -3
  170. package/dist/web/televet/call/index.js +3 -5
  171. package/dist/web/televet/index.cjs +1 -1
  172. package/dist/web/televet/index.d.cts +5 -5
  173. package/dist/web/televet/index.d.ts +5 -5
  174. package/dist/web/televet/index.js +1 -1
  175. package/package.json +1 -1
@@ -1,24 +1,24 @@
1
- import { R as RecordsController } from '../../view-DqKXtxEZ.js';
2
- export { C as ClinicCall, F as FactOverlay, a as REQUEST_TIMELINE_TITLES, b as RecordSharesStatus, c as RecordsDashboardState, d as RecordsDashboardView, e as RecordsEmptyVariant, f as RecordsStatus, g as RequestTimelineEvent, h as RequestTimelineEventKey, i as RequestTimelineEventState, S as ShareRowView, U as UploadDocumentInput, j as UploadQueueItem, k as UploadSkipReason, l as UseEverfurRecordsState, m as UseRecordFactEditState, n as UseRecordPdfLinkState, o as UseRecordSharesState, p as UseRecordsMarkersState, q as applyFactOverlay, r as buildRequestTimeline, s as deriveRecordsDashboardState, t as isFactEditable, u as pickPetRecordsRequest, v as selectClinicCall, w as selectDashboardView, x as selectPrimaryLabel, y as selectRequestList, z as selectRequestTitle, A as useEverfurRecords, B as useEverfurRecordsClinic, D as useEverfurRecordsClinicBatch, E as useRecordFactEdit, G as useRecordPdfLink, H as useRecordShares, I as useRecordsMarkers } from '../../view-DqKXtxEZ.js';
1
+ import { R as RecordsController } from '../../view-n_oSGiiT.js';
2
+ export { C as ClinicCall, F as FactOverlay, a as REQUEST_TIMELINE_TITLES, b as RecordSharesStatus, c as RecordsDashboardState, d as RecordsDashboardView, e as RecordsEmptyVariant, f as RecordsStatus, g as RequestTimelineEvent, h as RequestTimelineEventKey, i as RequestTimelineEventState, S as ShareRowView, U as UploadDocumentInput, j as UploadQueueItem, k as UploadSkipReason, l as UseEverfurRecordsState, m as UseRecordFactEditState, n as UseRecordPdfLinkState, o as UseRecordSharesState, p as UseRecordsMarkersState, q as applyFactOverlay, r as buildRequestTimeline, s as deriveRecordsDashboardState, t as isFactEditable, u as pickPetRecordsRequest, v as selectClinicCall, w as selectDashboardView, x as selectPrimaryLabel, y as selectRequestList, z as selectRequestTitle, A as useEverfurRecords, B as useEverfurRecordsClinic, D as useEverfurRecordsClinicBatch, E as useRecordFactEdit, G as useRecordPdfLink, H as useRecordShares, I as useRecordsMarkers } from '../../view-n_oSGiiT.js';
3
3
  import { CSSProperties, ReactNode, PointerEvent } from 'react';
4
- import { f as RecordsScreenBaseProps, i as RecordsClinicController, j as CaptureRecordsSignature, d as RecordsHostSeams, e as RecordsScreen, C as ClinicDraft, k as ClinicRequestBaseProps, l as ClinicBatchBaseProps, m as CapturedRecordsSignature } from '../../useRecordsDepth-C0Qfoghi.js';
5
- export { a as ClinicLocation, n as RecordsAsk, R as RecordsAskEntityRef, b as RecordsAskHandler, c as RecordsDepthStatus, o as RecordsNavAction, p as RecordsNavState, q as RecordsSignatureContext, g as RecordsUrlKind, r as RegisterSignaturePng, s as currentRecordsScreen, t as initialRecordsNav, v as popRecordsNav, w as pushRecordsNav, x as recordsNavReducer, y as replaceRecordsNav, z as resetRecordsNav, A as transitionRecordsNav } from '../../useRecordsDepth-C0Qfoghi.js';
4
+ import { f as RecordsScreenBaseProps, i as RecordsClinicController, j as CaptureRecordsSignature, d as RecordsHostSeams, e as RecordsScreen, C as ClinicDraft, k as ClinicRequestBaseProps, l as ClinicBatchBaseProps, m as CapturedRecordsSignature } from '../../useRecordsDepth-eS9BJv_a.js';
5
+ export { a as ClinicLocation, n as RecordsAsk, R as RecordsAskEntityRef, b as RecordsAskHandler, c as RecordsDepthStatus, o as RecordsNavAction, p as RecordsNavState, q as RecordsSignatureContext, g as RecordsUrlKind, r as RegisterSignaturePng, s as currentRecordsScreen, t as initialRecordsNav, v as popRecordsNav, w as pushRecordsNav, x as recordsNavReducer, y as replaceRecordsNav, z as resetRecordsNav, A as transitionRecordsNav } from '../../useRecordsDepth-eS9BJv_a.js';
6
6
  import { P as PetRef, R as RecordsRequestId } from '../../ids-B2GAAifq.js';
7
7
  export { B as Brand, D as DocumentId, _ as __brand } from '../../ids-B2GAAifq.js';
8
- import { d as RecordsRequestView } from '../../models-CrbUwbuS.js';
9
- export { h as ConsentState, C as CreateUploadRequestInput, G as GrantConsentInput, j as RECORDS_TERMINAL, R as RecordDocumentMeta, a as RecordEntity, k as RecordForwardItem, l as RecordIdentityField, b as RecordOrigin, m as RecordSeries, n as RecordSeriesPoint, i as RecordsDenialReason, f as RecordsRequestGroupView, c as RecordsRequestStatus, e as RecordsSimpleStatus, g as RecordsView, U as UploadedDocument, o as isTerminalStatus, r as recordsDenialReasonOf } from '../../models-CrbUwbuS.js';
10
- import { E as EverfurError } from '../../EverfurError-pEXDbUJ1.js';
11
- export { a as EverfurErrorCategory, b as EverfurErrorCode } from '../../EverfurError-pEXDbUJ1.js';
12
- export { C as CreateClinicRequestBatchInput, ak as CreateClinicRequestInput, y as FactFieldValue, B as RECORDS_CLINIC_BATCH_MAX, R as RecordClinicianNote, a as RecordClinicianNoteSection, b as RecordCompleteness, c as RecordConflict, d as RecordConflictCandidate, e as RecordDepthView, f as RecordDocumentContributionsView, g as RecordEncounter, h as RecordExamSystem, E as RecordFactEditInput, G as RecordFactRemoveInput, i as RecordLabMarker, j as RecordLabPoint, I as RecordMarker, J as RecordMarkerLatest, K as RecordMarkerPoint, L as RecordMarkerSummary, M as RecordMarkersView, N as RecordPdfLink, k as RecordPhysicalExam, O as RecordShare, l as RecordShareAudience, P as RecordShareAudienceScope, Q as RecordShareEmailInput, S as RecordShareEmailReceipt, T as RecordShareLink, U as RecordShareRecipientKind, aj as RecordsAuthorizationCopy, V as RecordsAuthorizationSignature, m as RecordsClinic, W as RecordsClinicBatch, X as RecordsClinicBatchClient, Y as RecordsClinicBatchItem, Z as RecordsClinicBatchResult, ag as RecordsClinicSearchInput, ah as RecordsClinicSearchPage, _ as RecordsClinicTarget, n as RecordsDepthClient, am as RecordsFeatures, ao as RecordsPhotoContentType, ai as RecordsRecentClinicsInput, o as RecordsRequestDocument, $ as RecordsSignatureSuggestion, al as RecordsSignatureUploadPolicy, p as RecordsTimelineMedication, q as RecordsTimelineVaccine, r as RecordsTimelineView, s as RecordsTimelineVisit, t as RecordsTimelineWeight, an as RecordsUploadContentType, ap as acceptsPhotos } from '../../depth-Mk7quUNa.js';
13
- export { a as EverfurDocumentContributionsProps, c as EverfurRecordsDepthProps } from '../../DepthViews-BSkuUGBB.js';
8
+ import { d as RecordsRequestView } from '../../models-CnXY5LuO.js';
9
+ export { h as ConsentState, C as CreateUploadRequestInput, G as GrantConsentInput, j as RECORDS_TERMINAL, R as RecordDocumentMeta, a as RecordEntity, k as RecordForwardItem, l as RecordIdentityField, b as RecordOrigin, m as RecordSeries, n as RecordSeriesPoint, i as RecordsDenialReason, f as RecordsRequestGroupView, c as RecordsRequestStatus, e as RecordsSimpleStatus, g as RecordsView, U as UploadedDocument, o as isTerminalStatus, r as recordsDenialReasonOf } from '../../models-CnXY5LuO.js';
10
+ import { E as EverfurError } from '../../EverfurError-DeBqRpQV.js';
11
+ export { a as EverfurErrorCategory, b as EverfurErrorCode } from '../../EverfurError-DeBqRpQV.js';
12
+ export { C as CreateClinicRequestBatchInput, ak as CreateClinicRequestInput, y as FactFieldValue, B as RECORDS_CLINIC_BATCH_MAX, R as RecordClinicianNote, a as RecordClinicianNoteSection, b as RecordCompleteness, c as RecordConflict, d as RecordConflictCandidate, e as RecordDepthView, f as RecordDocumentContributionsView, g as RecordEncounter, h as RecordExamSystem, E as RecordFactEditInput, G as RecordFactRemoveInput, i as RecordLabMarker, j as RecordLabPoint, I as RecordMarker, J as RecordMarkerLatest, K as RecordMarkerPoint, L as RecordMarkerSummary, M as RecordMarkersView, N as RecordPdfLink, k as RecordPhysicalExam, O as RecordShare, l as RecordShareAudience, P as RecordShareAudienceScope, Q as RecordShareEmailInput, S as RecordShareEmailReceipt, T as RecordShareLink, U as RecordShareRecipientKind, aj as RecordsAuthorizationCopy, V as RecordsAuthorizationSignature, m as RecordsClinic, W as RecordsClinicBatch, X as RecordsClinicBatchClient, Y as RecordsClinicBatchItem, Z as RecordsClinicBatchResult, ag as RecordsClinicSearchInput, ah as RecordsClinicSearchPage, _ as RecordsClinicTarget, n as RecordsDepthClient, am as RecordsFeatures, ao as RecordsPhotoContentType, ai as RecordsRecentClinicsInput, o as RecordsRequestDocument, $ as RecordsSignatureSuggestion, al as RecordsSignatureUploadPolicy, p as RecordsTimelineMedication, q as RecordsTimelineVaccine, r as RecordsTimelineView, s as RecordsTimelineVisit, t as RecordsTimelineWeight, an as RecordsUploadContentType, ap as acceptsPhotos } from '../../depth-_vMRMm4x.js';
13
+ export { a as EverfurDocumentContributionsProps, c as EverfurRecordsDepthProps } from '../../DepthViews-C6qFJ3fV.js';
14
14
  export { WebRecordsUploadTransportOptions, createWebRecordsUploadTransport } from './upload/index.js';
15
15
  import { F as FileHandle } from '../../ports-BN6RHF9W.js';
16
16
  export { a as UploadPolicyWire, U as UploadTransport } from '../../ports-BN6RHF9W.js';
17
- export { E as EverfurResult } from '../../EverfurResult-sKkoXew0.js';
18
- import '../../requestFunnel-BPeBZdKp.js';
19
- import '../../ErrorPolicyPort-DwSnmGcX.js';
20
- import '../../config-BysLVhku.js';
21
- import '../../identity-BiyMDMrR.js';
17
+ export { E as EverfurResult } from '../../EverfurResult-ClPTS0P2.js';
18
+ import '../../requestFunnel-BkSFsLKh.js';
19
+ import '../../ErrorPolicyPort-C3nNSS_j.js';
20
+ import '../../config-BB7e52FP.js';
21
+ import '../../identity-D5uywCtp.js';
22
22
 
23
23
  interface EverfurRecordsPageProps extends RecordsScreenBaseProps {
24
24
  readonly controller?: RecordsController;
@@ -86,7 +86,7 @@ import{createContext,useRef,useMemo,useState,useCallback,useEffect,useReducer,us
86
86
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
87
87
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
88
88
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
89
- /* @__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",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),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",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"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.",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:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,unknown:"Something went wrong. Please try again."});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:userFacingError(code)};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__ */
89
+ /* @__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",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),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."});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:userFacingError(code)};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__ */
90
90
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
91
91
  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__ */z.string().min(1).refine(value=>value.startsWith("https://")),str=/* @__PURE__ */z.string().nullish(),audienceField=/* @__PURE__ */z.unknown().optional(),linkSchema=/* @__PURE__ */z.object({share_id:/* @__PURE__ */z.string().min(1),share_url:/* @__PURE__ */z.string().min(1),expires_at:str,audience:audienceField}),listSchema=/* @__PURE__ */z.object({shares:/* @__PURE__ */z.array(/* @__PURE__ */z.object({share_id:/* @__PURE__ */z.string().min(1),expires_at:str,created_at:str,view_count:/* @__PURE__ */z.number().int().nonnegative().nullish(),last_viewed_at:str,audience:audienceField})).optional()}),pdfSchema=/* @__PURE__ */z.object({download_url:https,expires_at:str}),emailSchema=/* @__PURE__ */z.object({share_id:/* @__PURE__ */z.string().min(1),expires_at:str,audience:audienceField}),scopeSchema=/* @__PURE__ */z.object({audience:/* @__PURE__ */z.string().min(1),sections:/* @__PURE__ */z.array(/* @__PURE__ */z.string()),entity_types:/* @__PURE__ */z.array(/* @__PURE__ */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=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 FILENAMES=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function recordsUploadFilename(type){return isAcceptedUploadType(type,RECORDS_PHOTO_CONTENT_TYPES)?FILENAMES[type]:FILENAMES["application/pdf"]}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__ */z.object({features:/* @__PURE__ */z.record(/* @__PURE__ */z.boolean()),upload_content_types:/* @__PURE__ */z.array(/* @__PURE__ */z.string()).nullish(),share_audiences:/* @__PURE__ */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__ */
92
92
  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__ */z.object({request_id:/* @__PURE__ */z.string().min(1),pet_ref:/* @__PURE__ */z.string().min(1),status:/* @__PURE__ */z.string(),simple_status:/* @__PURE__ */z.string().nullish(),simple_status_detail:/* @__PURE__ */z.string().nullish(),status_label:/* @__PURE__ */z.string().optional(),dispatch_status:/* @__PURE__ */z.string().nullish(),can_retry_send:/* @__PURE__ */z.boolean().optional(),can_revoke:/* @__PURE__ */z.boolean().optional(),can_convert_to_upload:/* @__PURE__ */z.boolean().optional(),can_update_clinic_email:/* @__PURE__ */z.boolean().optional(),reminder_count:/* @__PURE__ */z.number().int().nonnegative().optional(),last_reminder_at:/* @__PURE__ */z.string().nullish(),waiting_expectation:/* @__PURE__ */z.string().nullish(),document_count:/* @__PURE__ */z.number().optional(),held_item_count:/* @__PURE__ */z.number().optional(),received_at:/* @__PURE__ */z.string().nullish(),parsing_started_at:/* @__PURE__ */z.string().nullish(),review_started_at:/* @__PURE__ */z.string().nullish(),created_at:/* @__PURE__ */z.string().optional(),updated_at:/* @__PURE__ */z.string().optional(),source:/* @__PURE__ */z.string().nullish().catch(null),action_needed_label:/* @__PURE__ */z.string().nullish().catch(null),failure_reason:/* @__PURE__ */z.string().nullish().catch(null),failure_code:/* @__PURE__ */z.string().nullish().catch(null),recovery_stage:/* @__PURE__ */z.string().nullish().catch(null),show_clinic_phone:/* @__PURE__ */z.boolean().optional().catch(void 0),clinic_name:/* @__PURE__ */z.string().nullish().catch(null),clinic_email:/* @__PURE__ */z.string().nullish().catch(null),clinic_phone:/* @__PURE__ */z.string().nullish().catch(null),converted_to_upload_at:/* @__PURE__ */z.string().nullish().catch(null),request_group_id:/* @__PURE__ */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__ */
@@ -108,13 +108,14 @@ return Object.freeze(sorted)}function selectPrimaryLabel(request){let action=req
108
108
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
109
109
  return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return 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,className:className}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
110
110
  return jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${capability}`,className:className,style:{...styles.offstate,...style},children:/* @__PURE__ */jsx("div",{style:styles.skeletonBar})})}function OffState({decision:decision,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
111
- return jsx("div",{className:className,style:{...styles.offstate,...style},children:message.length>0?/* @__PURE__ */jsx("p",{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{offstate:{...SURFACE_ROOT_RESET,boxSizing:"border-box",minHeight:MIN_OFFSTATE_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${space.md}px ${space.lg}px`,backgroundColor:color.surfaceCream,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`},offstateText:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.body,lineHeight:`${Math.round(type.size.body*type.lineHeight.normal)}px`,color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}}}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level>=6?6:level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);createContext(NESTED_HEADING_LEVEL_DEFAULT);var RecordsFootnoteDrawnAbove=createContext(false);function RecordsFootnote(props){let theme=useEverfurTheme(),style=useMemo(()=>footnoteStyle(theme),[theme]);return useContext(RecordsFootnoteDrawnAbove)?null:/* @__PURE__ */jsx("p",{role:"note",className:props.className,style:{...style,...props.style},"data-testid":"records-footnote",children:RECORDS_FOOTNOTE})}function footnoteStyle(theme){let{color:color,space:space,type:type}=theme;return{...SURFACE_ROOT_RESET,boxSizing:"border-box",margin:0,padding:`${space.md}px ${space.lg}px ${space.lg}px`,textAlign:"center",...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:`${Math.round(type.size.caption*type.lineHeight.normal)}px`,color:color.text.muted,backgroundColor:color.background}}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"}),TYPED_SIGNATURE_MAX_LENGTH=100;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}`,resultsCountDraft:count=>`DRAFT COPY [[${String(count)} clinics found: the spoken count of search results]]`,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 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,location2){let[query,setQueryValue]=useState(""),[debouncedQuery,setDebounced]=useState(""),[clinics,setClinics]=useState([]),[cursor,setCursor]=useState(null),[recent,setRecent]=useState([]),[recentLoading,setRecentLoading]=useState(true),[initialLoading,setInitialLoading]=useState(false),[loadingMore,setLoadingMore]=useState(false),[error,setError]=useState(null),[pageError,setPageError]=useState(null),[attempt,setAttempt]=useState(0),generation=useRef(0),live=useRef(true),lat=location2?.latitude,lng=location2?.longitude,bias=useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),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]),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;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=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=useCallback(value=>setQueryValue(value),[]),retry=useCallback(()=>setAttempt(n=>n+1),[]);return 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__ */
111
+ return jsx("div",{className:className,style:{...styles.offstate,...style},children:message.length>0?/* @__PURE__ */jsx("p",{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{offstate:{...SURFACE_ROOT_RESET,boxSizing:"border-box",minHeight:MIN_OFFSTATE_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${space.md}px ${space.lg}px`,backgroundColor:color.surfaceCream,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`},offstateText:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.body,lineHeight:`${Math.round(type.size.body*type.lineHeight.normal)}px`,color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}}}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level>=6?6:level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);createContext(NESTED_HEADING_LEVEL_DEFAULT);var RecordsFootnoteDrawnAbove=createContext(false);function RecordsFootnote(props){let theme=useEverfurTheme(),style=useMemo(()=>footnoteStyle(theme),[theme]);return useContext(RecordsFootnoteDrawnAbove)?null:/* @__PURE__ */jsx("p",{role:"note",className:props.className,style:{...style,...props.style},"data-testid":"records-footnote",children:RECORDS_FOOTNOTE})}function footnoteStyle(theme){let{color:color,space:space,type:type}=theme;return{...SURFACE_ROOT_RESET,boxSizing:"border-box",margin:0,padding:`${space.md}px ${space.lg}px ${space.lg}px`,textAlign:"center",...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:`${Math.round(type.size.caption*type.lineHeight.normal)}px`,color:color.text.muted,backgroundColor:color.background}}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"}),TYPED_SIGNATURE_MAX_LENGTH=100;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 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,location2){let[query,setQueryValue]=useState(""),[debouncedQuery,setDebounced]=useState(""),[clinics,setClinics]=useState([]),[cursor,setCursor]=useState(null),[recent,setRecent]=useState([]),[recentLoading,setRecentLoading]=useState(true),[initialLoading,setInitialLoading]=useState(false),[loadingMore,setLoadingMore]=useState(false),[error,setError]=useState(null),[pageError,setPageError]=useState(null),[attempt,setAttempt]=useState(0),generation=useRef(0),live=useRef(true),lat=location2?.latitude,lng=location2?.longitude,bias=useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),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]),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;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=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=useCallback(value=>setQueryValue(value),[]),retry=useCallback(()=>setAttempt(n=>n+1),[]);return 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
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__ */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)=>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__ */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__ */z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */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__ */z.object({petRef:text(128),ownerName:text(200).refine(value=>value.trim().length>0&&!hasControl(value)),authorizationVersion:text(64),clinics:/* @__PURE__ */z.array(clinicSchema).min(1).max(RECORDS_CLINIC_BATCH_MAX)}).strict(),responseSchema=/* @__PURE__ */z.object({request_group_id:uuid,pet_ref:/* @__PURE__ */z.string(),created_count:/* @__PURE__ */z.number().int().nonnegative(),failed_count:/* @__PURE__ */z.number().int().nonnegative(),results:/* @__PURE__ */z.array(/* @__PURE__ */z.object({idempotency_key:/* @__PURE__ */z.string(),clinic_id:/* @__PURE__ */uuid.nullable().optional(),clinic_free_text:/* @__PURE__ */z.string().nullable().optional(),created:/* @__PURE__ */z.boolean(),request:/* @__PURE__ */z.unknown().optional(),failure_code:/* @__PURE__ */z.string().nullable().optional(),failure_reason:/* @__PURE__ */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__ */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__ */z.object({clinics:/* @__PURE__ */z.array(/* @__PURE__ */z.object({clinic_id:uuid2,name:/* @__PURE__ */z.string().min(1),address:/* @__PURE__ */z.string().nullable(),phone:/* @__PURE__ */z.string().nullable(),email_status:/* @__PURE__ */z.string(),distance_km:/* @__PURE__ */z.number().finite().nonnegative().nullable()})),next_cursor:/* @__PURE__ */z.string().nullable().optional()}),copySchema=/* @__PURE__ */z.object({authorization_version:/* @__PURE__ */z.string().min(1),scope_template:/* @__PURE__ */z.string().min(1),authorization_template:/* @__PURE__ */z.string().min(1)}),signaturePolicySchema=/* @__PURE__ */z.object({upload_id:/* @__PURE__ */z.string().min(1),upload_url:/* @__PURE__ */z.string().url().refine(value=>value.startsWith("https://")),upload_fields:/* @__PURE__ */z.record(/* @__PURE__ */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=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__ */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)=>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__ */z.object({limit:/* @__PURE__ */z.number().int().min(1).max(25).optional()}).strict(),searchSchema=/* @__PURE__ */z.object({query:text2(200,0).optional(),location:/* @__PURE__ */z.object({latitude:/* @__PURE__ */z.number().finite().min(-90).max(90),longitude:/* @__PURE__ */z.number().finite().min(-180).max(180)}).strict().optional(),limit:/* @__PURE__ */z.number().int().min(1).max(100).optional(),cursor:text2(512,0).optional()}).strict(),createSchema=/* @__PURE__ */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__ */z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */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=useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicController({repository:createHttpRecordsClinicRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})})},[runtime,userRef,scopeEpoch]),active=useRef(controller);return useEffect(()=>(active.current=controller,()=>{active.current=null}),[controller]),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=useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicBatchClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch]),active=useRef(client);return useEffect(()=>(active.current=client,()=>{active.current=null}),[client]),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 VISUALLY_HIDDEN=/* @__PURE__ */Object.freeze({position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0});var MIN_HEIGHT=120,MIN_TARGET=44;function RecordsGateOffState({reason:reason,onExit:onExit,exitLabel:exitLabel,style:style,className:className}){let{color:color,space:space,radius:radius,type:type}=useEverfurTheme();/* @__PURE__ */
113
113
  return jsxs("div",{className:className,"data-testid":"records-gate-off",style:{boxSizing:"border-box",minHeight:MIN_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"flex-start",gap:space.md,padding:space.lg,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`,backgroundColor:color.surfaceCream,color:color.text.primary,...style},children:[reason.length>0?/* @__PURE__ */jsx("p",{style:{margin:0,fontSize:type.size.bodyTight,color:color.text.muted},children:reason}):null,
114
- /* @__PURE__ */jsx("button",{type:"button",onClick:onExit,"data-testid":"records-gate-off-exit",style:{minHeight:MIN_TARGET,padding:`0 ${space.lg}px`,borderRadius:radius.pill,border:`1.5px solid ${color.brandInk}`,backgroundColor:"transparent",color:color.brandInk,font:"inherit",fontSize:type.size.body,cursor:"pointer"},children:exitLabel})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}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")}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same=(a,b)=>parseColor(a)===parseColor(b);return{success:!same(c.success,compiled.success),warning:!same(c.warningStrong,compiled.warningStrong)||!same(c.cautionAccent,compiled.cautionAccent),info:!(same(c.info,c.brandInk)&&same(c.badgeBgInfo,c.brandSoft)&&same(c.infoEdge,c.structureEdge))}}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 slotBoxCss(slot,borderWidth){let box=slotBox(slot,borderWidth),out={};return box.backgroundColor!==void 0&&(out.backgroundColor=box.backgroundColor),box.borderColor!==void 0&&(out.border=`${box.borderWidth??1}px solid ${box.borderColor}`),box.borderRadius!==void 0&&(out.borderRadius=box.borderRadius),out}function recordCardSlot(slots){return slots.recordCard??slots.card}var normalize=text3=>text3.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text3=normalize(disclaimer);return text3.length===0||text3===FOOTNOTE}function BrandImage({src:src,alt:alt,decorative:decorative=false,style:style,height:height,fallback:fallback=null,onFailed:onFailed}){let[failed,setFailed]=useState(null);return src===null||failed===src?fallback:/* @__PURE__ */jsx("img",{src:src,alt:decorative?"":alt,...decorative?{"aria-hidden":true}:{},...height===void 0?{}:{height:height},style:style,decoding:"async",referrerPolicy:"no-referrer",onError:()=>{setFailed(src),onFailed?.()}})}var LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,LOGO_STYLE=/* @__PURE__ */Object.freeze({display:"block",height:LOGO_HEIGHT,width:"auto",maxWidth:LOGO_MAX_WIDTH,objectFit:"contain"});function BrandLogo({logoUrl:logoUrl,name:name,styles:styles}){/* @__PURE__ */
115
- return jsx(BrandImage,{src:logoUrl,alt:name,height:LOGO_HEIGHT,style:styles?.logo??LOGO_STYLE})}function slotCss(slot,borderWidth){return{...slotBoxCss(slot,borderWidth),...slotText(slot)}}var RECORDS_EASE_OUT=/* @__PURE__ */Object.freeze([.23,1,.32,1]),RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var EASE=cssCubicBezier(RECORDS_EASE_OUT);function usePressScale(disabled=false){let theme=useEverfurTheme(),[pressed,setPressed]=useState(false),still=theme.motion.reducedMotion||disabled,down=useCallback(()=>setPressed(true),[]),up=useCallback(()=>setPressed(false),[]);return{style:still?{}:{transform:pressed?`scale(${RECORDS_MOTION.pressScale})`:"none",transition:`transform ${RECORDS_MOTION.pressMs}ms ${EASE}`},handlers:{onPointerDown:down,onPointerUp:up,onPointerLeave:up,onPointerCancel:up}}}function useSectionRise(){let reduced=useEverfurTheme().motion.reducedMotion,ran=useRef(false),animations=useRef([]);return useEffect(()=>()=>{for(let animation of animations.current)animation.cancel()},[]),useCallback(node=>{node===null||ran.current||reduced||(ran.current=true,Array.from(node.children).forEach((child,index)=>{if(typeof child.animate!="function")return;let delay=Math.min(index,RECORDS_MOTION.maxSteps-1)*RECORDS_MOTION.staggerMs;try{animations.current.push(child.animate([{transform:`translateY(${RECORDS_MOTION.riseWebPx}px)`},{transform:"none"}],{duration:RECORDS_MOTION.moveMs,delay:delay,easing:EASE,fill:"backwards"}),child.animate([{opacity:0},{opacity:1}],{duration:RECORDS_MOTION.fadeMs,delay:delay,easing:EASE,fill:"backwards"}))}catch{}}))},[reduced])}var SCREEN_HEADING_ATTR="data-ef-screen-heading";function focusTook(el){return el.focus(),document.activeElement===el}function focusScreen(root){let heading=root.querySelector(`[${SCREEN_HEADING_ATTR}]`);if(heading!==null&&(heading.textContent??"").trim().length>0&&focusTook(heading)||focusTook(root))return;let screenRoot=root.firstElementChild;screenRoot instanceof HTMLElement&&(screenRoot.hasAttribute("tabindex")||(screenRoot.setAttribute("tabindex","-1"),screenRoot.style.outline="none"),screenRoot.focus())}var NOT_SEEN=/* @__PURE__ */Symbol("records.screenFocus.notSeen");function useFocusScreenOnChange(screen,onMount=false){let rootRef=useRef(null),seen=useRef(onMount?NOT_SEEN:screen);return useEffect(()=>{if(Object.is(seen.current,screen))return;seen.current=screen;let root=rootRef.current;root!==null&&focusScreen(root)},[screen]),rootRef}var MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET=44,BUTTON_HEIGHT=52,BACK_LABEL="Back";function useScreenStyles(){let theme=useEverfurTheme(),styles=useMemo(()=>makeScreenStyles(theme),[theme]);return{theme:theme,styles:styles}}function ScreenHeader({title:title,onBack:onBack,right:right,testID:testID,variant:variant="brand"}){let{theme:theme,styles:styles}=useScreenStyles();/* @__PURE__ */
116
- return jsxs("header",{style:styles.headerRow,"data-testid":testID,children:[onBack?/* @__PURE__ */jsx("button",{type:"button",onClick:onBack,"aria-label":BACK_LABEL,style:{...styles.iconButton,...styles.headerText},"data-testid":testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.backChevron})}):/* @__PURE__ */jsx("span",{style:styles.iconButton}),title.trim().length>0?/* @__PURE__ */jsx("h2",{tabIndex:-1,[SCREEN_HEADING_ATTR]:"",style:variant==="document"?styles.documentTitle:styles.headerTitle,children:title}):/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.headerTitle,"data-testid":testID?`${testID}-spacer`:void 0}),
117
- /* @__PURE__ */jsxs("div",{style:styles.headerRight,children:[variant==="brand"?/* @__PURE__ */jsx(BrandLogo,{logoUrl:theme.meta.logoUrl,name:theme.meta.displayName,styles:styles.headerLogo}):null,right??/* @__PURE__ */jsx("span",{style:styles.iconButton})]})]})}function DisclaimerBand({disclaimer:disclaimer,style:style}){let{styles:styles}=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxs("p",{role:"note","aria-label":DASHBOARD_COPY.important(disclaimer),style:{...styles.band,...style},"data-testid":"records-disclaimer-band",children:[
114
+ /* @__PURE__ */jsx("button",{type:"button",onClick:onExit,"data-testid":"records-gate-off-exit",style:{minHeight:MIN_TARGET,padding:`0 ${space.lg}px`,borderRadius:radius.pill,border:`1.5px solid ${color.brandInk}`,backgroundColor:"transparent",color:color.brandInk,font:"inherit",fontSize:type.size.body,cursor:"pointer"},children:exitLabel})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}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")}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same=(a,b)=>parseColor(a)===parseColor(b);return{success:!same(c.success,compiled.success),warning:!same(c.warningStrong,compiled.warningStrong)||!same(c.cautionAccent,compiled.cautionAccent),info:!(same(c.info,c.brandInk)&&same(c.badgeBgInfo,c.brandSoft)&&same(c.infoEdge,c.structureEdge))}}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 slotBoxCss(slot,borderWidth){let box=slotBox(slot,borderWidth),out={};return box.backgroundColor!==void 0&&(out.backgroundColor=box.backgroundColor),box.borderColor!==void 0&&(out.border=`${box.borderWidth??1}px solid ${box.borderColor}`),box.borderRadius!==void 0&&(out.borderRadius=box.borderRadius),out}function recordCardSlot(slots){return slots.recordCard??slots.card}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=useCallback(listener=>source===null?NO_SUBSCRIPTION():source.subscribe(listener),[source]),read=useCallback(()=>source===null?false:isSandboxSnapshot(source.getSnapshot()),[source]);return useSyncExternalStore(subscribe2,read,read)}var normalize=text3=>text3.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text3=normalize(disclaimer);return text3.length===0||text3===FOOTNOTE}function BrandImage({src:src,alt:alt,decorative:decorative=false,style:style,height:height,fallback:fallback=null,onFailed:onFailed}){let[failed,setFailed]=useState(null);return src===null||failed===src?fallback:/* @__PURE__ */jsx("img",{src:src,alt:decorative?"":alt,...decorative?{"aria-hidden":true}:{},...height===void 0?{}:{height:height},style:style,decoding:"async",referrerPolicy:"no-referrer",onError:()=>{setFailed(src),onFailed?.()}})}var LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,LOGO_STYLE=/* @__PURE__ */Object.freeze({display:"block",height:LOGO_HEIGHT,width:"auto",maxWidth:LOGO_MAX_WIDTH,objectFit:"contain"});function BrandLogo({logoUrl:logoUrl,name:name,styles:styles}){/* @__PURE__ */
115
+ return jsx(BrandImage,{src:logoUrl,alt:name,height:LOGO_HEIGHT,style:styles?.logo??LOGO_STYLE})}function slotCss(slot,borderWidth){return{...slotBoxCss(slot,borderWidth),...slotText(slot)}}function slotRadius(slot){return slot?.borderRadius===void 0?{}:{borderRadius:slot.borderRadius}}var RECORDS_EASE_OUT=/* @__PURE__ */Object.freeze([.23,1,.32,1]),RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var EASE=cssCubicBezier(RECORDS_EASE_OUT);function usePressScale(disabled=false){let theme=useEverfurTheme(),[pressed,setPressed]=useState(false),still=theme.motion.reducedMotion||disabled,down=useCallback(()=>setPressed(true),[]),up=useCallback(()=>setPressed(false),[]);return{style:still?{}:{transform:pressed?`scale(${RECORDS_MOTION.pressScale})`:"none",transition:`transform ${RECORDS_MOTION.pressMs}ms ${EASE}`},handlers:{onPointerDown:down,onPointerUp:up,onPointerLeave:up,onPointerCancel:up}}}function useSectionRise(){let reduced=useEverfurTheme().motion.reducedMotion,ran=useRef(false),animations=useRef([]);return useEffect(()=>()=>{for(let animation of animations.current)animation.cancel()},[]),useCallback(node=>{node===null||ran.current||reduced||(ran.current=true,Array.from(node.children).forEach((child,index)=>{if(typeof child.animate!="function")return;let delay=Math.min(index,RECORDS_MOTION.maxSteps-1)*RECORDS_MOTION.staggerMs;try{animations.current.push(child.animate([{transform:`translateY(${RECORDS_MOTION.riseWebPx}px)`},{transform:"none"}],{duration:RECORDS_MOTION.moveMs,delay:delay,easing:EASE,fill:"backwards"}),child.animate([{opacity:0},{opacity:1}],{duration:RECORDS_MOTION.fadeMs,delay:delay,easing:EASE,fill:"backwards"}))}catch{}}))},[reduced])}var SCREEN_HEADING_ATTR="data-ef-screen-heading";function focusTook(el){return el.focus(),document.activeElement===el}function focusScreen(root){let heading=root.querySelector(`[${SCREEN_HEADING_ATTR}]`);if(heading!==null&&(heading.textContent??"").trim().length>0&&focusTook(heading)||focusTook(root))return;let screenRoot=root.firstElementChild;screenRoot instanceof HTMLElement&&(screenRoot.hasAttribute("tabindex")||(screenRoot.setAttribute("tabindex","-1"),screenRoot.style.outline="none"),screenRoot.focus())}var NOT_SEEN=/* @__PURE__ */Symbol("records.screenFocus.notSeen");function useFocusScreenOnChange(screen,onMount=false){let rootRef=useRef(null),seen=useRef(onMount?NOT_SEEN:screen);return useEffect(()=>{if(Object.is(seen.current,screen))return;seen.current=screen;let root=rootRef.current;root!==null&&focusScreen(root)},[screen]),rootRef}var MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET=44,BUTTON_HEIGHT=52,BACK_LABEL="Back";function useScreenStyles(){let theme=useEverfurTheme(),styles=useMemo(()=>makeScreenStyles(theme),[theme]);return{theme:theme,styles:styles}}function ScreenHeader({title:title,onBack:onBack,right:right,testID:testID,variant:variant="brand"}){let{theme:theme,styles:styles}=useScreenStyles(),sandbox=useRecordsSandboxTenant();/* @__PURE__ */
116
+ return jsxs(Fragment,{children:[
117
+ /* @__PURE__ */jsxs("header",{style:styles.headerRow,"data-testid":testID,children:[onBack?/* @__PURE__ */jsx("button",{type:"button",onClick:onBack,"aria-label":BACK_LABEL,style:{...styles.iconButton,...styles.headerText},"data-testid":testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.backChevron})}):/* @__PURE__ */jsx("span",{style:styles.iconButton}),title.trim().length>0?/* @__PURE__ */jsx("h2",{tabIndex:-1,[SCREEN_HEADING_ATTR]:"",style:variant==="document"?styles.documentTitle:styles.headerTitle,children:title}):/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.headerTitle,"data-testid":testID?`${testID}-spacer`:void 0}),
118
+ /* @__PURE__ */jsxs("div",{style:styles.headerRight,children:[variant==="brand"?/* @__PURE__ */jsx(BrandLogo,{logoUrl:theme.meta.logoUrl,name:theme.meta.displayName,styles:styles.headerLogo}):null,right??/* @__PURE__ */jsx("span",{style:styles.iconButton})]})]}),sandbox?/* @__PURE__ */jsx("p",{role:"note",style:{...styles.band,margin:`0 ${theme.space.lg}px ${theme.space.md}px`},"data-testid":"records-sandbox-note",children:/* @__PURE__ */jsx("span",{style:styles.bandText,children:RECORDS_SANDBOX_COPY.note})}):null]})}function DisclaimerBand({disclaimer:disclaimer,style:style}){let{styles:styles}=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxs("p",{role:"note","aria-label":DASHBOARD_COPY.important(disclaimer),style:{...styles.band,...style},"data-testid":"records-disclaimer-band",children:[
118
119
  /* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.infoGlyph,children:"i"}),
119
120
  /* @__PURE__ */jsx("span",{style:styles.bandText,children:disclaimer})]})}function Pill({label:label,onClick:onClick,kind:kind="primary",disabled:disabled=false,busy:busy=false,ariaLabel:ariaLabel,ariaDescribedBy:ariaDescribedBy,testID:testID,style:style}){let{styles:styles}=useScreenStyles(),press=usePressScale(disabled||busy),box=kind==="primary"?styles.pillPrimary:kind==="outline"?styles.pillOutline:kind==="danger"?styles.pillDanger:kind==="ask"?styles.pillAsk:styles.pillLink;/* @__PURE__ */
120
121
  return jsx("button",{type:"button",onClick:onClick,disabled:disabled||busy,"aria-busy":busy,"aria-label":ariaLabel,"aria-describedby":ariaDescribedBy,...press.handlers,style:{...styles.pill,...box,...disabled?styles.pillDisabled:{},...press.style,...style},"data-testid":testID,children:label})}function Chip({label:label,tone:tone="neutral",testID:testID}){let{styles:styles}=useScreenStyles(),sentence=label.length>CHIP_WORD_MAX;/* @__PURE__ */
@@ -181,7 +182,7 @@ return jsxs("section",{role:"status",style:s.empty,"data-testid":testID,children
181
182
  /* @__PURE__ */jsx("span",{"aria-hidden":"true",style:s.emptyGlyph}),
182
183
  /* @__PURE__ */jsx("h3",{style:s.emptyTitle,children:copy.title}),
183
184
  /* @__PURE__ */jsx("p",{style:s.emptyBody,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsx("button",{type:"button",onClick:onAction,disabled:cooling,"aria-label":cooling?COOLING_A11Y_LABEL:label,style:{...s.emptyAction,...cooling?s.emptyActionDisabled:{}},"data-testid":testID?`${testID}-action`:`records-empty-${variant}-action`,children:label}):null]})}function useStyles(){let theme=useEverfurTheme();return useMemo(()=>makeStyles2(theme),[theme])}function makeStyles2(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=`1px solid ${color.brandBorder}`;return{dashboard:{display:"flex",flexDirection:"column",gap:space.lg,padding:`${space.xs}px ${space.sm}px 0`,backgroundColor:color.background},inset:{padding:`0 ${space.sm}px`},summaryCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.md+space.xs/2,borderRadius:radius.lg-space.xs,border:hairline,backgroundColor:color.surface,padding:`${space.lg+space.xs}px ${space.lg}px`},badges:{display:"flex",gap:space.md},carouselCard:{borderRadius:radius.lg-space.xs,border:hairline,backgroundColor:color.surface,padding:space.lg},dots:{display:"flex",alignItems:"center",justifyContent:"center",gap:space.xs+space.xs/2},centered:{display:"flex",justifyContent:"center"},actions:{display:"flex",flexDirection:"column",gap:space.sm+space.xs/2},actionRow:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:radius.md,border:hairline,backgroundColor:color.surface,padding:space.lg},actionLeft:{flex:1,display:"flex",alignItems:"center",gap:space.md},request:{display:"flex",flexDirection:"column",gap:space.lg+space.xs/2,padding:`${space.xs}px ${space.lg}px 0`},railRow:{display:"flex",alignItems:"flex-start",gap:space.md},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.xs/2,width:24},railBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs+space.xs/2,paddingBottom:space.lg+space.xs/2},statusCard:{display:"flex",flexDirection:"column",gap:space.sm,borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},timeline:{backgroundColor:color.background},timelineDisclaimer:{padding:`${space.xs}px ${space.lg}px ${space.md}px`},timelineRow:{display:"flex",gap:space.md,padding:`${space.md+space.xs/2}px ${space.lg}px`},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs-1},timelineTop:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.sm},timelineSeparator:{height:1,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},clinics:{display:"flex",flexDirection:"column",gap:space.md},clinicRow:{display:"flex",flexDirection:"column",gap:space.sm,borderRadius:radius.lg-space.xs/2,border:hairline,backgroundColor:color.surface,padding:`${space.md+space.xs/2}px`},shares:{display:"flex",flexDirection:"column",gap:space.md,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline},shareRow:{display:"flex",flexDirection:"column",gap:space.xs+space.xs/2},empty:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm+space.xs/2,padding:`${space.xxl}px ${space.xl}px`,textAlign:"center"},emptyGlyph:{boxSizing:"border-box",width:22,height:22,borderRadius:11,backgroundColor:color.brandSoft,border:hairline,marginBottom:space.xs},emptyTitle:{margin:0,...headingFaceCss(theme,"bold"),fontSize:type.size.subtitle,lineHeight:`${Math.round(type.size.subtitle*type.lineHeight.snug)-1}px`,color:color.brandInk},emptyBody:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:`${Math.round(type.size.bodyTight*type.lineHeight.normal)}px`,color:color.text.muted,maxWidth:320},emptyAction:{boxSizing:"border-box",marginTop:space.sm,minHeight:40,borderRadius:radius.pill,padding:`0 ${space.lg+space.xs/2}px`,backgroundColor:color.brand,color:color.onPrimary,border:0,cursor:"pointer",...faceCss(theme,"bold"),fontSize:type.size.bodyTight},emptyActionDisabled:{opacity:.5,cursor:"default"}}}var EMAIL=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function EverfurClinicPicker(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
184
- return jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,className:props.className,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(PickerBody,{...guardHostProps(props,["onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef]))})}function PickerBody({petRef:petRef,petName:petName,controller:controller,recordsController:recordsController,location:location2,onNavigate:onNavigate,onBack:onBack,style:style,className:className}){let{theme:theme,styles:styles}=useScreenStyles(),runtimeController=useEverfurRecordsClinic(),picker=useClinicPicker(controller??runtimeController,location2),records=useEverfurRecords(recordsController?{petRef:petRef,controller:recordsController}:{petRef:petRef}),keyFactory=useRef(defaultIdempotencyKeyFactory()),[starting,setStarting]=useState(false),[startError,setStartError]=useState(null),[fallbackOpen,setFallbackOpen]=useState(false),[fallbackName,setFallbackName]=useState(""),[fallbackNameDirty,setFallbackNameDirty]=useState(false),[fallbackEmail,setFallbackEmail]=useState(""),[fallbackTouched,setFallbackTouched]=useState(false),select=useCallback(clinic=>{onNavigate?.({name:"consent",clinic:clinicDraftFor(clinic,null,"",keyFactory.current())})},[onNavigate]),startUpload=()=>{starting||(setStarting(true),setStartError(null),records.createRequest(`records-upload-${Date.now().toString(36)}`).then(result=>{if(setStarting(false),!result.ok){setStartError(REQUEST_SCREEN_COPY.errors.start);return}onNavigate?.({name:"request",requestId:result.value.id})}))},displayName=fallbackNameDirty?fallbackName:picker.query,fallbackEmailValid=EMAIL.test(fallbackEmail.trim()),canContinue=displayName.trim().length>0&&fallbackEmailValid,fallbackEmailWrong=fallbackTouched&&fallbackEmail.trim().length>0&&!fallbackEmailValid,listData=picker.isSearchActive?picker.clinics:picker.recent,emptyVariant=picker.isSearchActive?picker.error?recordsEmptyVariantForError(picker.error):!picker.initialLoading&&picker.clinics.length===0?"idle":null:picker.recent.length>0||picker.recentLoading?null:"idle",block={display:"flex",flexDirection:"column",gap:theme.space.sm},resultsAnnouncement=picker.isSearchActive&&!picker.initialLoading&&!picker.error&&picker.clinics.length>0?CLINIC_PICKER_COPY.resultsCountDraft(picker.clinics.length):"",onScroll=event=>{let el=event.currentTarget;el.scrollTop+el.clientHeight>=el.scrollHeight-el.clientHeight*.6&&picker.loadMore()};/* @__PURE__ */
185
+ return jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,className:props.className,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(PickerBody,{...guardHostProps(props,["onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef]))})}function PickerBody({petRef:petRef,petName:petName,controller:controller,recordsController:recordsController,location:location2,onNavigate:onNavigate,onBack:onBack,style:style,className:className}){let{theme:theme,styles:styles}=useScreenStyles(),runtimeController=useEverfurRecordsClinic(),picker=useClinicPicker(controller??runtimeController,location2),records=useEverfurRecords(recordsController?{petRef:petRef,controller:recordsController}:{petRef:petRef}),keyFactory=useRef(defaultIdempotencyKeyFactory()),[starting,setStarting]=useState(false),[startError,setStartError]=useState(null),[fallbackOpen,setFallbackOpen]=useState(false),[fallbackName,setFallbackName]=useState(""),[fallbackNameDirty,setFallbackNameDirty]=useState(false),[fallbackEmail,setFallbackEmail]=useState(""),[fallbackTouched,setFallbackTouched]=useState(false),select=useCallback(clinic=>{onNavigate?.({name:"consent",clinic:clinicDraftFor(clinic,null,"",keyFactory.current())})},[onNavigate]),startUpload=()=>{starting||(setStarting(true),setStartError(null),records.createRequest(`records-upload-${Date.now().toString(36)}`).then(result=>{if(setStarting(false),!result.ok){setStartError(REQUEST_SCREEN_COPY.errors.start);return}onNavigate?.({name:"request",requestId:result.value.id})}))},displayName=fallbackNameDirty?fallbackName:picker.query,fallbackEmailValid=EMAIL.test(fallbackEmail.trim()),canContinue=displayName.trim().length>0&&fallbackEmailValid,fallbackEmailWrong=fallbackTouched&&fallbackEmail.trim().length>0&&!fallbackEmailValid,listData=picker.isSearchActive?picker.clinics:picker.recent,emptyVariant=picker.isSearchActive?picker.error?recordsEmptyVariantForError(picker.error):!picker.initialLoading&&picker.clinics.length===0?"idle":null:picker.recent.length>0||picker.recentLoading?null:"idle",block={display:"flex",flexDirection:"column",gap:theme.space.sm},resultsAnnouncement=picker.isSearchActive&&!picker.initialLoading&&!picker.error&&picker.clinics.length>0?CLINIC_PICKER_COPY.resultsCount(picker.clinics.length):"",onScroll=event=>{let el=event.currentTarget;el.scrollTop+el.clientHeight>=el.scrollHeight-el.clientHeight*.6&&picker.loadMore()};/* @__PURE__ */
185
186
  return jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"records-clinic-picker",children:[
186
187
  /* @__PURE__ */jsx(ScreenHeader,{title:CLINIC_PICKER_COPY.titleFor(petName),onBack:onBack,testID:"records-clinic-header"}),
187
188
  /* @__PURE__ */jsx("p",{style:styles.subLead,"data-testid":"records-clinic-lead",children:CLINIC_PICKER_COPY.leadWeb}),
@@ -254,7 +255,7 @@ return Object.freeze({petRef:pet,available:true,withheld:false,labResults:/* @__
254
255
  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__ */
255
256
  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__ */
256
257
  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 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=useMemo(()=>({}),[client,petRef,extraKey,consentEpoch]),[state,setState]=useState({scope:scope,value:null,error:null,loading:true}),generation=useRef(0),load=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]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let current=state.scope===scope?state:{value:null,error:null,loading:true},refresh=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 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 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]=useState(false),[ownerName,setOwnerName]=useState(input.ownerName),[email2,setEmail]=useState(clinic.email),[emailTouched,setEmailTouched]=useState(false),[copy,setCopy]=useState(null),[copyError,setCopyError]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),[error,setError]=useState(null),[busy,setBusy]=useState(false),[created,setCreated]=useState(null),[signatures,setSignatures]=useState([]),[reuseSignatureId,setReuseSignatureId]=useState(null),[signed,setSigned]=useState(false),locked=useRef(false),live=useRef(true),keyFactory=useRef(defaultIdempotencyKeyFactory()),attempt=useRef(null);useEffect(()=>(live.current=true,()=>{live.current=false,attempt.current=null}),[controller]),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]),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&&copy&&scope&&named&&clinicName&&(!needsEmail||validEmail)),ready=readyButSigned&&hasSignature,submit=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=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__ */
257
- return jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,className:props.className,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(ConsentBody,{...guardHostProps(props,["onCreated","onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.clinic.key]))})}function ConsentBody({petRef:petRef,petName:petName,clinic:clinic,ownerName:ownerName,onCaptureSignature:onCaptureSignature,onCreated:onCreated,controller:controller,onNavigate:onNavigate,onBack:onBack,style:style,className:className}){let{theme:theme,styles:styles}=useScreenStyles(),runtimeController=useEverfurRecordsClinic(),resolved=controller??runtimeController,depthClient=useEverfurRecordsDepthClient(),pad=useSignatureCanvas(),rise=useSectionRise(),form=useRecordsConsentForm({petRef:petRef,petName:petName,ownerName:ownerName??"",clinic:clinic,controller:resolved,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}):async()=>pad.signed?pad.capture(resolved,(new AbortController).signal):null,hostCapture:onCaptureSignature!==void 0,onCreated:request=>{onCreated?.(request),onNavigate?.({name:"dashboard"})}}),padSigned=pad.signed,formRef=useRef(form);formRef.current=form,useEffect(()=>{formRef.current.setSigned(padSigned)},[padSigned]);let busy=form.busy,block={display:"flex",flexDirection:"column",gap:theme.space.sm},ownerId="records-consent-owner-name",emailId="records-consent-clinic-email";/* @__PURE__ */
258
+ return jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,className:props.className,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(ConsentBody,{...guardHostProps(props,["onCreated","onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.clinic.key]))})}function ConsentBody({petRef:petRef,petName:petName,clinic:clinic,ownerName:ownerName,onCaptureSignature:onCaptureSignature,onCreated:onCreated,controller:controller,onNavigate:onNavigate,onBack:onBack,style:style,className:className}){let directSendNote=useRecordsSandboxTenant()?RECORDS_SANDBOX_COPY.newClinicDirectSendNote:RECORDS_CONSENT_COPY.newClinicDirectSendNote,{theme:theme,styles:styles}=useScreenStyles(),runtimeController=useEverfurRecordsClinic(),resolved=controller??runtimeController,depthClient=useEverfurRecordsDepthClient(),pad=useSignatureCanvas(),rise=useSectionRise(),form=useRecordsConsentForm({petRef:petRef,petName:petName,ownerName:ownerName??"",clinic:clinic,controller:resolved,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}):async()=>pad.signed?pad.capture(resolved,(new AbortController).signal):null,hostCapture:onCaptureSignature!==void 0,onCreated:request=>{onCreated?.(request),onNavigate?.({name:"dashboard"})}}),padSigned=pad.signed,formRef=useRef(form);formRef.current=form,useEffect(()=>{formRef.current.setSigned(padSigned)},[padSigned]);let busy=form.busy,block={display:"flex",flexDirection:"column",gap:theme.space.sm},ownerId="records-consent-owner-name",emailId="records-consent-clinic-email";/* @__PURE__ */
258
259
  return jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"records-consent-screen",children:[
259
260
  /* @__PURE__ */jsx(ScreenHeader,{title:form.title,onBack:onBack,testID:"records-consent-header"}),
260
261
  /* @__PURE__ */jsx("p",{style:styles.subLead,"data-testid":"records-consent-lead",children:RECORDS_CONSENT_COPY.leadWeb(petName)}),
@@ -276,7 +277,7 @@ return jsxs("div",{className:className,style:{...styles.root,...style},"data-tes
276
277
  /* @__PURE__ */jsx("input",{id:ownerId,style:styles.field,value:form.ownerName,placeholder:RECORDS_CONSENT_COPY.fullNamePlaceholder,maxLength:200,disabled:busy,autoComplete:"name",onChange:event=>form.setOwnerName(event.target.value),"data-testid":"records-consent-owner-name"})]}),form.needsEmail?/* @__PURE__ */jsxs("div",{style:block,"data-testid":"records-consent-email-block",children:[form.directoryClinicNoEmail?/* @__PURE__ */jsx("p",{style:styles.cautionNote,"data-testid":"records-consent-no-email-note",children:RECORDS_CONSENT_COPY.noEmailNote(petName,form.clinicName)}):null,
277
278
  /* @__PURE__ */jsx("label",{htmlFor:emailId,style:styles.fieldLabel,children:RECORDS_CONSENT_COPY.emailLabel}),
278
279
  /* @__PURE__ */jsx("input",{id:emailId,type:"email",style:styles.field,value:form.email,placeholder:RECORDS_CONSENT_COPY.emailPlaceholder,maxLength:320,disabled:busy,autoComplete:"off","aria-invalid":form.emailError?true:void 0,"aria-describedby":form.emailError?`${emailId}-error`:void 0,onChange:event=>form.setEmail(event.target.value),"data-testid":"records-consent-clinic-email"}),form.emailError?/* @__PURE__ */jsx("p",{id:`${emailId}-error`,role:"alert",style:styles.errorText,children:form.emailError}):null,
279
- /* @__PURE__ */jsx("p",{style:styles.muted,"data-testid":"records-consent-review-note",children:RECORDS_CONSENT_COPY.newClinicDirectSendNote})]}):null,onCaptureSignature?null:/* @__PURE__ */jsxs("div",{style:block,children:[form.signatures.length>0?/* @__PURE__ */jsxs("div",{style:block,children:[
280
+ /* @__PURE__ */jsx("p",{style:styles.muted,"data-testid":"records-consent-review-note",children:directSendNote})]}):null,onCaptureSignature?null:/* @__PURE__ */jsxs("div",{style:block,children:[form.signatures.length>0?/* @__PURE__ */jsxs("div",{style:block,children:[
280
281
  /* @__PURE__ */jsx("span",{style:styles.fieldLabel,children:RECORDS_CONSENT_COPY.reuseSignature}),
281
282
  /* @__PURE__ */jsx("div",{style:{display:"flex",gap:theme.space.sm,overflowX:"auto",padding:`${theme.space.xs}px 0`},children:form.signatures.map(sig=>{let selected=form.reuseSignatureId===sig.signatureId;/* @__PURE__ */
282
283
  return jsx("button",{type:"button",onClick:()=>form.pickReuseSignature(selected?null:sig.signatureId),"aria-label":selected?RECORDS_CONSENT_COPY.reuseTileSelectedA11y:RECORDS_CONSENT_COPY.reuseTileA11y,"aria-pressed":selected,style:{flexShrink:0,width:112,height:56,borderRadius:theme.radius.sm,border:selected?`2px solid ${theme.color.brandInk}`:`1px solid ${theme.color.brandBorder}`,backgroundColor:theme.color.surface,padding:0,overflow:"hidden",cursor:"pointer"},"data-testid":`records-consent-reuse-${sig.signatureId}`,children:/* @__PURE__ */jsx("img",{src:sig.previewUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"contain"}})},sig.signatureId)})}),
@@ -307,7 +308,7 @@ return jsxs("section",{"aria-label":RECORDS_COPY.records,style:styles.list,child
307
308
  /* @__PURE__ */jsx("dl",{style:styles.card,children:view.contributions.map(entity=>/* @__PURE__ */jsxs("div",{style:styles.row,children:[
308
309
  /* @__PURE__ */jsx("dt",{style:styles.rowTitle,children:entity.label}),
309
310
  /* @__PURE__ */jsx("dd",{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsx("dd",{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useDepthTheme(){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles3(theme),[theme]);return{theme:theme,styles:styles}}function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:lh(size,multiplier),color:fg}),recordCard=recordCardSlot(slots),cardText=slotText(recordCard),inCard=(size,multiplier,fg,weight="regular")=>({...text3(size,multiplier,fg,weight),...cardText}),hairline=`1px solid ${color.brandBorder}`,errorColor=theme.brightness==="dark"?color.errorRed:color.danger;return{container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT2,height:"100%",backgroundColor:color.background,color:color.text.primary,...faceCss(theme,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT2,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:space.lg,padding:space.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:24,height:24,borderRadius:radius.pill,border:`3px solid ${color.brandSofter}`,borderTopColor:color.brandInk},emptyGlyph:{boxSizing:"border-box",width:40,height:40,borderRadius:radius.lg,backgroundColor:color.brandSoft,border:hairline},alertText:text3(type.size.subtitle,type.lineHeight.snug,color.text.secondary),errorText:text3(type.size.subtitle,type.lineHeight.snug,errorColor),primaryButton:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET2,minWidth:MIN_TOUCH_TARGET2,padding:`${space.md}px ${space.xl}px`,borderRadius:radius.pill,...faceCss(theme,"bold"),fontSize:type.size.body,border:0,cursor:"pointer",backgroundColor:color.primary,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},list:{display:"flex",flexDirection:"column",gap:space.md,padding:space.lg},section:{display:"flex",flexDirection:"column",gap:space.sm},heading:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFaceCss(theme,"bold")},card:{boxSizing:"border-box",listStyle:"none",display:"flex",flexDirection:"column",gap:space.sm,margin:0,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline,...slotBoxCss(recordCard,1)},plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:space.sm},row:{display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.xs}px 0`,borderBottom:`1px solid ${color.borderHairlineGreen}`},topLine:{display:"flex",justifyContent:"space-between",gap:space.md},kindLabel:{...inCard(type.size.caption,type.lineHeight.normal,color.text.muted,"medium")},date:inCard(type.size.caption,type.lineHeight.normal,color.text.muted),rowTitle:{...inCard(type.size.body,type.lineHeight.normal,color.text.primary,"bold")},rowValue:{...inCard(type.size.body,type.lineHeight.normal,color.text.primary,"medium")},rowDetail:inCard(type.size.bodyTight,type.lineHeight.normal,color.text.muted),rowMuted:{...inCard(type.size.bodyTight,type.lineHeight.normal,color.text.muted),opacity:.7},chip:{...text3(type.size.caption,type.lineHeight.normal,color.text.primary),alignSelf:"flex-start",padding:`${space.xs}px ${space.sm}px`,borderRadius:radius.pill},chipNeutral:{backgroundColor:color.badgeBgNeutral},chipCaution:{backgroundColor:color.badgeBgCaution},chipCritical:{backgroundColor:color.badgeBgCritical},disclaimer:text3(type.size.caption,type.lineHeight.normal,color.text.muted),timelineList:{display:"flex",flexDirection:"column",paddingBottom:space.xxl},timelineBand:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary),borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,margin:`${space.xs}px ${space.lg}px ${space.md}px`,...slotCss(slots.banner)},timelineSeparated:{borderTop:`1px solid ${color.brandBorder}`,marginLeft:TIMELINE_SEPARATOR_INSET,paddingLeft:0},timelineRow:{display:"flex",gap:space.md,padding:`${space.md+space.xs/2}px ${space.lg}px`},timelineBubble:{boxSizing:"border-box",flexShrink:0,width:34,height:34,borderRadius:radius.pill,backgroundColor:color.brandSoft,border:hairline},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs-1,minWidth:0},timelineKind:{...faceCss(theme,"mono"),fontSize:type.size.micro,lineHeight:`${type.size.bodyTight}px`,letterSpacing:type.letterSpacing.eyebrow/3,textTransform:"uppercase",color:color.text.secondary},timelineTitle:{...text3(type.size.body,type.lineHeight.normal,color.text.primary,"medium")}}}function useRecordShares(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),now=opts.now??Date.now,[shares,setShares]=useState(null),[loading,setLoading]=useState(true),[error,setError]=useState(null),[lit,setLit]=useState(null),available=lit===true,[urls,setUrls]=useState({}),[creating,setCreating]=useState(false),[revokingId,setRevokingId]=useState(null),[preparingPdf,setPreparingPdf]=useState(false),[consentRequired,setConsentRequired]=useState(false),[sending,setSending]=useState(false),[featuresState,setFeaturesState]=useState(null),recordsFeatures=featuresState!==null&&featuresState.client===client?featuresState.value:RECORDS_FEATURES_PDF_ONLY,shareAudiences=recordsFeatures.shareAudiences,consentEpoch=useRecordsConsentEpoch(petRef),generation=useRef(0),live=useRef(true),load=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]);useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]),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=useRef(consentEpoch);useEffect(()=>{seenEpoch.current!==consentEpoch&&(seenEpoch.current=consentEpoch,setUrls({}),setConsentRequired(true),load())},[consentEpoch,load]);let createLink=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=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=useCallback(async shareId=>{setRevokingId(shareId);let result=await client.revokeShare(petRef,shareId);return live.current&&(setRevokingId(null),load()),result},[client,petRef,load]),pdfLink=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=useCallback(()=>{setConsentRequired(false),load()},[load]),rows=useMemo(()=>buildShareRows(shares??[],urls,now()),[shares,urls,now]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated",features=recordsFeatures.features;return 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=useMemo(()=>({}),[client,petRef,userRef]),[state,setState]=useState({scope:scope,lit:null});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 useMemo(()=>({lit:lit}),[lit])}function useRecordPdfLink(petRef){let client=useEverfurRecordsDepthClient(),available=useRecordsDepthProbe(petRef).lit===true,[preparing,setPreparing]=useState(false),[error,setError]=useState(null),live=useRef(true);useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let pdfLink=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 useMemo(()=>({preparing:preparing,available:available,error:error,pdfLink:pdfLink}),[preparing,available,error,pdfLink])}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,isDevelopment2){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment2()===!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,isDevelopment2){useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment2)},[consentVersion,consentText,isDevelopment2])}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var URL_MAX_LENGTH=2048;function fontSourceUrl(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>URL_MAX_LENGTH?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(trimmed)?trimmed:null}var loads=/* @__PURE__ */new Map,warned2=/* @__PURE__ */new Set,useBeforePaintEffect=typeof document>"u"?useEffect:useLayoutEffect;function keyOf(source){return source.cssSrc!==void 0?`css\n${source.cssSrc}`:`file\n${source.family}\n${source.src??""}\n${source.weight??"400"}\n${source.style??"normal"}`}function warnOnce(source,warn){if(!warn)return;let url=source.cssSrc??source.src??"",message=`[everfur] A font in appearance.fonts did not load: "${source.family}" from ${url}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(source.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!warned2.has(message)){warned2.add(message);try{globalThis.console?.warn?.(message)}catch{}}}function existingLink(href){let links=document.getElementsByTagName("link");for(let index=0;index<links.length;index+=1){let link=links[index];if(link.rel==="stylesheet"&&link.getAttribute("href")===href)return link}return null}function loadStylesheet(href){return existingLink(href)!==null?Promise.resolve(true):new Promise(resolve=>{let link=document.createElement("link");link.rel="stylesheet",link.href=href,link.setAttribute("data-everfur-font",""),link.addEventListener("load",()=>resolve(true)),link.addEventListener("error",()=>resolve(false)),document.head.appendChild(link)})}function loadFile(source){let fonts=document.fonts;return new FontFace(source.family,`url("${source.src}")`,{display:"swap",weight:source.weight??"400",style:source.style??"normal"}).load().then(face=>(fonts.add(face),true)).catch(()=>false)}function loadFontSource(source,warn=false){let key=keyOf(source),load=loads.get(key);if(load===void 0){load=Promise.resolve(false);try{if(typeof document<"u"){let css=source.cssSrc===void 0?null:fontSourceUrl(source.cssSrc),src=source.src===void 0?null:fontSourceUrl(source.src);css!==null?load=loadStylesheet(css):src!==null&&(load=loadFile({...source,src:src}))}}catch{load=Promise.resolve(false)}let settled=load.then(ok2=>(ok2||warnOnce(source,warn),ok2));loads.set(key,settled),load=settled}return load}function useFontSources(theme,isDevelopment2){let sources=theme.type.fontSources;useBeforePaintEffect(()=>{if(sources.length===0)return;let warn=false;try{warn=isDevelopment2()}catch{}for(let source of sources)loadFontSource(source,warn)},[sources,isDevelopment2])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads2=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads2.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face=>(fonts.add(face),!0)).catch(()=>!1)}catch{}loads2.set(key,load)}return load}var FACES=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;useEffect(()=>{for(let face of FACES){let url=fontUrls[face];url!=null&&loadBrandFont(families[face],url,namedFaces[face]?weight.regular:weight[FACE_WEIGHT[face]])}},[families,fontUrls,weight,namedFaces]),useFontSources(theme,isWebDevelopment)}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument2=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument2?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});var isDevelopment=()=>webThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment)}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."});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 pct=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:`${pct}%`;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 PDF_SIGNATURE=[37,80,68,70,45],JPEG_SIGNATURE=[255,216,255],PNG_SIGNATURE=[137,80,78,71,13,10,26,10],HEAD_BYTES=12,BMFF_BRANDS=/* @__PURE__ */Object.freeze({heic:"image/heic",heix:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif"}),RECORDS_DOCUMENT_ACCEPT="application/pdf,.pdf",PHOTO_ACCEPT=/* @__PURE__ */Object.freeze({"image/jpeg":"image/jpeg,.jpg,.jpeg","image/png":"image/png,.png","image/heic":"image/heic,.heic","image/heif":"image/heif,.heif"});function recordsDocumentAccept(types){let photos=RECORDS_PHOTO_CONTENT_TYPES.filter(type=>isAcceptedUploadType(type,types));return[RECORDS_DOCUMENT_ACCEPT,...photos.map(type=>PHOTO_ACCEPT[type])].join(",")}var NOT_A_PDF="application/octet-stream",WEB_FILE_URI="file:web-document";async function readHead(blob,length){let head=blob.slice(0,length);try{return typeof head.arrayBuffer=="function"?new Uint8Array(await head.arrayBuffer()):await new Promise(resolve=>{let reader=new FileReader;reader.onload=()=>{resolve(reader.result instanceof ArrayBuffer?new Uint8Array(reader.result):new Uint8Array)},reader.onerror=()=>resolve(new Uint8Array),reader.readAsArrayBuffer(head)})}catch{return new Uint8Array}}async function isPdfBlob(blob){if(blob.size<PDF_SIGNATURE.length)return false;let head=await readHead(blob,PDF_SIGNATURE.length);return startsWith(head,PDF_SIGNATURE)}function startsWith(head,signature,offset=0){return head.length>=offset+signature.length&&signature.every((byte2,index)=>head[offset+index]===byte2)}function photoTypeOf(head){return startsWith(head,JPEG_SIGNATURE)?"image/jpeg":startsWith(head,PNG_SIGNATURE)?"image/png":head.length>=HEAD_BYTES&&String.fromCharCode(...head.slice(4,8))==="ftyp"?BMFF_BRANDS[String.fromCharCode(...head.slice(8,12))]??null:null}async function detectedType(blob,types){if(await isPdfBlob(blob))return RECORDS_UPLOAD_CONTENT_TYPE;if(!RECORDS_PHOTO_CONTENT_TYPES.some(type=>isAcceptedUploadType(type,types)))return null;let photo=photoTypeOf(await readHead(blob,HEAD_BYTES));return photo!==null&&isAcceptedUploadType(photo,types)?photo:null}async function fileToHandle(file,types){let detected=await detectedType(file,types),rawName=file.name,name=typeof rawName=="string"?rawName:void 0;/* @__PURE__ */
310
- return Object.freeze({uri:WEB_FILE_URI,mimeType:detected??NOT_A_PDF,sizeBytes:file.size,blob:file,...name!==void 0?{name:name}:{}})}function isUploadableHandle(handle,types){let size=handle.sizeBytes;return isAcceptedUploadType(handle.mimeType,types)&&typeof size=="number"&&Number.isFinite(size)&&size>0&&size<=MAX_UPLOAD_BYTES}function pickDocument(doc=document,types){return new Promise(resolve=>{let input=doc.createElement("input");input.type="file",input.accept=recordsDocumentAccept(types),input.hidden=true;let done=()=>{input.remove()};input.addEventListener("change",()=>{let file=input.files?.[0];if(done(),file===void 0){resolve(null);return}fileToHandle(file,types).then(resolve)},{once:true}),input.addEventListener("cancel",()=>{done(),resolve(null)},{once:true}),doc.body.appendChild(input),input.click()})}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]=useState(""),[busy,setBusy]=useState(false),[error,setError]=useState(null),[confirmingRevoke,setConfirmingRevoke]=useState(false),[settled,setSettled]=useState(null),locked=useRef(false),active=useRef(false),generation=useRef(0);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&&current.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&&current.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)}function inArtifactWords(events,request,petName){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;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";function RequestTimeline({request:request,petName:petName}){let styles=useStyles2(),events=buildRequestTimeline(request,{petName:petName??null});
311
+ return Object.freeze({uri:WEB_FILE_URI,mimeType:detected??NOT_A_PDF,sizeBytes:file.size,blob:file,...name!==void 0?{name:name}:{}})}function isUploadableHandle(handle,types){let size=handle.sizeBytes;return isAcceptedUploadType(handle.mimeType,types)&&typeof size=="number"&&Number.isFinite(size)&&size>0&&size<=MAX_UPLOAD_BYTES}function pickDocument(doc=document,types){return new Promise(resolve=>{let input=doc.createElement("input");input.type="file",input.accept=recordsDocumentAccept(types),input.hidden=true;let done=()=>{input.remove()};input.addEventListener("change",()=>{let file=input.files?.[0];if(done(),file===void 0){resolve(null);return}fileToHandle(file,types).then(resolve)},{once:true}),input.addEventListener("cancel",()=>{done(),resolve(null)},{once:true}),doc.body.appendChild(input),input.click()})}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]=useState(""),[busy,setBusy]=useState(false),[error,setError]=useState(null),[confirmingRevoke,setConfirmingRevoke]=useState(false),[settled,setSettled]=useState(null),locked=useRef(false),active=useRef(false),generation=useRef(0);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&&current.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&&current.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";function RequestTimeline({request:request,petName:petName}){let styles=useStyles2(),sandbox=useRecordsSandboxTenant(),events=buildRequestTimeline(request,{petName:petName??null,sandbox:sandbox});
311
312
  /* @__PURE__ */
312
313
  return jsx("ol",{style:styles.list,"aria-label":REQUEST_SCREEN_COPY.timelineA11y,"data-testid":"records-timeline",children:events.map((event,idx)=>/* @__PURE__ */jsx(TimelineRow,{event:event,isLast:idx===events.length-1,styles:styles},event.key))})}function TimelineRow({event:event,isLast:isLast,styles:styles}){let date=event.at?formatRecordsDate(event.at):null,title={...styles.title,...event.state==="current"?styles.titleCurrent:{},...event.state==="failed"?styles.titleFailed:{},...event.state==="upcoming"?styles.titleUpcoming:{},...event.key==="ready"&&(event.state==="done"||event.state==="current")?styles.titleReady:{}};/* @__PURE__ */
313
314
  return jsxs("li",{style:styles.row,"data-testid":`records-timeline-${event.key}`,children:[
@@ -415,7 +416,8 @@ return jsxs("div",{style:{...cardBlock,borderColor:styles.chipTones[meta.tone].c
415
416
  /* @__PURE__ */jsx("p",{style:styles.rowMuted,children:[candidate.docId?record.documents[candidate.docId]?.title??RECORD_SCREEN_COPY.uploadedDocument: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__ */jsxs("section",{style:styles.section,"data-testid":"record-section-completeness",children:[
416
417
  /* @__PURE__ */jsx(SectionHeader,{title:RECORD_SCREEN_COPY.whatsOnFile}),
417
418
  /* @__PURE__ */jsxs("div",{style:styles.card,children:[
418
- /* @__PURE__ */jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:theme.space.sm,padding:`${theme.space.md}px 0`},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__ */jsx("span",{"aria-label":`${label}: ${present?RECORD_SCREEN_COPY.onFile:RECORD_SCREEN_COPY.noneOnFile}`,style:{...styles.chip,...present?styles.chipTones.positive:{backgroundColor:theme.color.badgeBgNeutral,color:theme.color.text.muted},fontSize:theme.type.size.caption},children:label},label))}),
419
+ /* @__PURE__ */jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:theme.space.sm,padding:`${theme.space.md}px 0`},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])=>
420
+ /* @__PURE__ */jsx("span",{"aria-label":`${label}: ${present?RECORD_SCREEN_COPY.onFile:RECORD_SCREEN_COPY.noneOnFile}`,style:{...styles.chip,...present?{...styles.chipTones.positive,...slotRadius(theme.slots.chip)}:{backgroundColor:theme.color.badgeBgNeutral,color:theme.color.text.muted,...slotCss(theme.slots.chip)},fontSize:theme.type.size.caption},children:label},label))}),
419
421
  /* @__PURE__ */jsxs("div",{style:{display:"flex",alignItems:"center",gap:theme.space.sm,paddingBottom:theme.space.md},children:[
420
422
  /* @__PURE__ */jsx("span",{style:{...styles.rowDetail,flex:1,marginTop:0},children:RECORD_SCREEN_COPY.documentsOnFile(depth.completeness.documentsIngested)}),depth.completeness.documentsInReview>0?/* @__PURE__ */jsx(Chip,{label:RECORD_SCREEN_COPY.inReviewChip(depth.completeness.documentsInReview),tone:"warning"}):null,heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)>0?/* @__PURE__ */jsx("span",{"aria-label":RECORD_SCREEN_COPY.beingVerifiedA11y(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),children:/* @__PURE__ */jsx(Chip,{label:RECORD_SCREEN_COPY.beingVerified(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),depth.completeness.earliestRecordAt||depth.completeness.latestRecordAt?/* @__PURE__ */jsx("p",{style:{...styles.rowDetail,paddingBottom:theme.space.md},children:RECORD_SCREEN_COPY.dateRange(depth.completeness.earliestRecordAt,depth.completeness.latestRecordAt)}):null,Object.entries(depth.completeness.entitiesPendingReview).filter(([,count])=>count>0).length>0?/* @__PURE__ */jsxs("p",{style:{...styles.rowMuted,paddingBottom:theme.space.md},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__ */jsxs("section",{style:styles.section,"data-testid":"record-section-documents",children:[
421
423
  /* @__PURE__ */jsx(SectionHeader,{title:RECORD_SCREEN_COPY.documents,count:documents.length}),