@everfur/sdk 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +174 -0
- package/README.md +2 -1
- package/dist/{Chat-BOG0SXKV.d.cts → Chat.d-DUNTfzqC.d.ts} +170 -8
- package/dist/{Chat-CIolBgjJ.d.ts → Chat.d-Dts8u_1a.d.cts} +170 -8
- package/dist/{DepthViews-BR6VQ3Ta.d.cts → DepthViews.d-BIp599lz.d.cts} +1 -1
- package/dist/{DepthViews-280t3BcQ.d.ts → DepthViews.d-BMU2jFPw.d.cts} +1 -1
- package/dist/{DepthViews-DlBuFsgN.d.ts → DepthViews.d-Ce2Zhnrb.d.ts} +1 -1
- package/dist/{DepthViews-BTbF_DJY.d.cts → DepthViews.d-CubkMPbU.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-10s3HJCt.d.cts → ErrorPolicyPort.d-68yrE3BE.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-C3nNSS_j.d.ts → ErrorPolicyPort.d-DirW9hgO.d.cts} +1 -1
- package/dist/{EverfurError-DeBqRpQV.d.cts → EverfurError.d-8NHtlgzA.d.cts} +11 -1
- package/dist/{EverfurError-DeBqRpQV.d.ts → EverfurError.d-8NHtlgzA.d.ts} +11 -1
- package/dist/{EverfurResult-ClPTS0P2.d.ts → EverfurResult.d-BFH-3s6E.d.cts} +1 -1
- package/dist/{EverfurResult-COlXj1wq.d.cts → EverfurResult.d-D_-254ZY.d.ts} +1 -1
- package/dist/{IntakeMedia-BH0fYDT2.d.cts → IntakeMedia.d-4a89XrP7.d.ts} +1 -1
- package/dist/{IntakeMedia-B-_vA9ZB.d.cts → IntakeMedia.d-DGxrhgIW.d.ts} +1 -1
- package/dist/{IntakeMedia-CIoTXAWs.d.ts → IntakeMedia.d-DUPR4lVM.d.cts} +1 -1
- package/dist/{IntakeMedia-Bavl7E4Z.d.ts → IntakeMedia.d-JJCUvQu7.d.cts} +1 -1
- package/dist/LifecyclePort.d-Cr1p33a7.d.cts +23 -0
- package/dist/LifecyclePort.d-Cr1p33a7.d.ts +23 -0
- package/dist/{PhotoController-vzY5bfY_.d.ts → PhotoController.d-BzCJOE7e.d.cts} +2 -2
- package/dist/{PhotoController-3l7MT9jA.d.cts → PhotoController.d-D0XiUUOl.d.ts} +2 -2
- package/dist/animations/index.cjs +5 -1
- package/dist/animations/index.d.cts +24 -24
- package/dist/animations/index.d.ts +24 -24
- package/dist/animations/index.js +5 -1
- package/dist/{attachments-CGxvnYu4.d.ts → attachments.d-Bp2qbHxn.d.cts} +22 -26
- package/dist/{attachments-CWNj1ZkM.d.ts → attachments.d-D1yhJjcZ.d.ts} +4 -4
- package/dist/{attachments-waXcJWCp.d.cts → attachments.d-DisnvB9R.d.cts} +4 -4
- package/dist/{attachments-B6h4cJU-.d.cts → attachments.d-Djy9z_0Z.d.ts} +22 -26
- package/dist/{bookingCopy-CjPKeg75.d.ts → bookingCopy.d-BJF6gd1A.d.ts} +24 -9
- package/dist/{bookingCopy-8aEU6ZmR.d.cts → bookingCopy.d-BlBmhAJc.d.cts} +24 -9
- package/dist/{branding-DJf4h12Q.d.ts → branding.d-DI8S400y.d.cts} +9 -2
- package/dist/{branding-BCfwLj0h.d.cts → branding.d-OIGLbQeM.d.ts} +9 -2
- package/dist/{callRoom-BhIdadyV.d.cts → callRoom.d-B1DoYdJe.d.cts} +1 -1
- package/dist/{callRoom-B92eH_ij.d.ts → callRoom.d-Dqm1rUqT.d.ts} +1 -1
- package/dist/{casesRepository-CGdhvzTu.d.cts → casesRepository.d-CT2LTicS.d.cts} +3 -3
- package/dist/{casesRepository-ZG9Sg0e4.d.ts → casesRepository.d-UsWOz9bv.d.ts} +3 -3
- package/dist/chat/index.cjs +132 -57
- package/dist/chat/index.d.cts +18 -16
- package/dist/chat/index.d.ts +18 -16
- package/dist/chat/index.js +133 -58
- package/dist/client/index.cjs +15 -10
- package/dist/client/index.d.cts +19 -18
- package/dist/client/index.d.ts +19 -18
- package/dist/client/index.js +15 -10
- package/dist/{config-B0p6Lygh.d.cts → config.d-BR3DT9ho.d.cts} +3 -3
- package/dist/{config-DmFAZJOx.d.ts → config.d-Dy6igYlH.d.ts} +3 -3
- package/dist/consent/index.cjs +5 -1
- package/dist/consent/index.d.cts +10 -10
- package/dist/consent/index.d.ts +10 -10
- package/dist/consent/index.js +5 -1
- package/dist/{context-BNreNLtL.d.ts → context.d-Cwks0p3C.d.cts} +15 -15
- package/dist/{context-BgS2a57J.d.cts → context.d-QcCgguzA.d.ts} +15 -15
- package/dist/{copy-DLJriGQS.d.ts → copy.d-CiMn2IIt.d.ts} +6 -6
- package/dist/{copy-lWp-Lkv5.d.cts → copy.d-DLJTyRfT.d.cts} +6 -6
- package/dist/core/index.cjs +17 -13
- package/dist/core/index.d.cts +33 -29
- package/dist/core/index.d.ts +33 -29
- package/dist/core/index.js +17 -13
- package/dist/{depth-BYb3RXoA.d.cts → depth.d-CjPGVPDL.d.cts} +9 -115
- package/dist/{depth-COz-sSG5.d.ts → depth.d-OSALbYM7.d.ts} +9 -115
- package/dist/{entitlementRepository-D-Lse67w.d.cts → entitlementRepository.d-CVQa1DA1.d.cts} +10 -5
- package/dist/{entitlementRepository-CrTOP_-o.d.ts → entitlementRepository.d-Cf3LbTwD.d.ts} +10 -5
- package/dist/features.d-fNsGcg0R.d.cts +108 -0
- package/dist/features.d-fNsGcg0R.d.ts +108 -0
- package/dist/focus.d-DMg2ngHI.d.ts +1178 -0
- package/dist/focus.d-az9cqUz3.d.cts +1178 -0
- package/dist/health-plan/index.cjs +370 -0
- package/dist/health-plan/index.d.cts +251 -0
- package/dist/health-plan/index.d.ts +251 -0
- package/dist/health-plan/index.js +370 -0
- package/dist/idempotency.d-D461_DPD.d.cts +910 -0
- package/dist/idempotency.d-WpXx9zQo.d.ts +910 -0
- package/dist/{identity-Cw07BKZp.d.ts → identity.d-60LeJt_s.d.cts} +3 -3
- package/dist/{identity-DFVGYn1o.d.cts → identity.d-DzTijonw.d.ts} +3 -3
- package/dist/index.cjs +141 -66
- package/dist/index.d.cts +31 -29
- package/dist/index.d.ts +31 -29
- package/dist/index.js +142 -67
- package/dist/{models-A4A5S7AG.d.cts → models.d-BagXhafD.d.ts} +8 -3
- package/dist/{models-CnXY5LuO.d.ts → models.d-BnLm3VAA.d.cts} +8 -3
- package/dist/notifications/index.cjs +5 -1
- package/dist/notifications/index.d.cts +9 -9
- package/dist/notifications/index.d.ts +9 -9
- package/dist/notifications/index.js +5 -1
- package/dist/optInView.d-CEyHR6PK.d.cts +325 -0
- package/dist/optInView.d-acKpV8V2.d.ts +325 -0
- package/dist/parse.d-C8CXyS58.d.ts +210 -0
- package/dist/parse.d-tEzufgJX.d.cts +210 -0
- package/dist/{pets-BYALZTSu.d.ts → pets.d-C_53_fzo.d.ts} +3 -3
- package/dist/{pets-CcyPQS-H.d.cts → pets.d-NbJvP_kh.d.cts} +3 -3
- package/dist/{petsRepository-B_Q1gFkE.d.cts → petsRepository.d-BuGHymNx.d.ts} +4 -4
- package/dist/{petsRepository-518QkPxH.d.ts → petsRepository.d-lp1BHRqM.d.cts} +4 -4
- package/dist/photo/index.cjs +6 -2
- package/dist/photo/index.d.cts +9 -9
- package/dist/photo/index.d.ts +9 -9
- package/dist/photo/index.js +6 -2
- package/dist/{ports-BN6RHF9W.d.ts → ports.d-BX4f4UsB.d.cts} +14 -1
- package/dist/{ports-BN6RHF9W.d.cts → ports.d-BX4f4UsB.d.ts} +14 -1
- package/dist/{ports-RuNJmBA-.d.cts → ports.d-CEROoqnA.d.cts} +16 -10
- package/dist/{ports-DmQeMArX.d.ts → ports.d-COIyN624.d.ts} +16 -10
- package/dist/presentation.d-DMbdad7G.d.cts +90 -0
- package/dist/presentation.d-DMbdad7G.d.ts +90 -0
- package/dist/records/depth/index.cjs +11 -7
- package/dist/records/depth/index.d.cts +14 -12
- package/dist/records/depth/index.d.ts +14 -12
- package/dist/records/depth/index.js +11 -7
- package/dist/records/index.cjs +225 -62
- package/dist/records/index.d.cts +159 -20
- package/dist/records/index.d.ts +159 -20
- package/dist/records/index.js +225 -62
- package/dist/recordsAsk.d-C5CGSi3j.d.cts +14 -0
- package/dist/recordsAsk.d-C5CGSi3j.d.ts +14 -0
- package/dist/{requestFunnel-B9fdXMi5.d.ts → requestFunnel.d-CXUMPw1K.d.ts} +5 -5
- package/dist/{requestFunnel-BBjNNwc9.d.cts → requestFunnel.d-DWQQpjFR.d.cts} +5 -5
- package/dist/{resolve-D4Ywz5OS.d.ts → resolve.d-jI8FmBj3.d.cts} +3 -3
- package/dist/{resolve-D4Ywz5OS.d.cts → resolve.d-jI8FmBj3.d.ts} +3 -3
- package/dist/{runtimeTypes-CstDBX8w.d.cts → runtimeTypes.d-4yFNNuYR.d.ts} +20 -13
- package/dist/{runtimeTypes-N_K4BVZB.d.ts → runtimeTypes.d-D6N_fhxx.d.cts} +20 -13
- package/dist/server/events/index.cjs +7 -3
- package/dist/server/events/index.d.cts +51 -9
- package/dist/server/events/index.d.ts +51 -9
- package/dist/server/events/index.js +7 -3
- package/dist/server/index.cjs +12 -6
- package/dist/server/index.d.cts +152 -8
- package/dist/server/index.d.ts +152 -8
- package/dist/server/index.js +12 -6
- package/dist/sheetCopy.d-CAhLOxjc.d.cts +4 -0
- package/dist/sheetCopy.d-CAhLOxjc.d.ts +4 -0
- package/dist/sheetSeam.d-Cviqk89n.d.ts +45 -0
- package/dist/sheetSeam.d-DCS3LW8g.d.cts +45 -0
- package/dist/shop/index.cjs +262 -0
- package/dist/shop/index.d.cts +193 -0
- package/dist/shop/index.d.ts +193 -0
- package/dist/shop/index.js +262 -0
- package/dist/televet/booking/index.cjs +16 -12
- package/dist/televet/booking/index.d.cts +36 -22
- package/dist/televet/booking/index.d.ts +36 -22
- package/dist/televet/booking/index.js +16 -12
- package/dist/televet/call/index.d.cts +5 -5
- package/dist/televet/call/index.d.ts +5 -5
- package/dist/televet/index.cjs +7 -3
- package/dist/televet/index.d.cts +12 -12
- package/dist/televet/index.d.ts +12 -12
- package/dist/televet/index.js +7 -3
- package/dist/{televetGlobal-C5dTUACe.d.cts → televetGlobal.d-CC-DrqkQ.d.ts} +7 -2
- package/dist/{televetGlobal-CnjrfhT4.d.ts → televetGlobal.d-CKwDCbmN.d.cts} +7 -2
- package/dist/testing/index.cjs +7 -3
- package/dist/testing/index.d.cts +3 -3
- package/dist/testing/index.d.ts +3 -3
- package/dist/testing/index.js +7 -3
- package/dist/testing/rn/index.cjs +5 -1
- package/dist/testing/rn/index.d.cts +23 -22
- package/dist/testing/rn/index.d.ts +23 -22
- package/dist/testing/rn/index.js +5 -1
- package/dist/testing/web/index.cjs +5 -1
- package/dist/testing/web/index.d.cts +23 -22
- package/dist/testing/web/index.d.ts +23 -22
- package/dist/testing/web/index.js +5 -1
- package/dist/texting/index.cjs +158 -0
- package/dist/texting/index.d.cts +36 -0
- package/dist/texting/index.d.ts +36 -0
- package/dist/texting/index.js +158 -0
- package/dist/threadOptions.d-B1pTMmDF.d.cts +260 -0
- package/dist/threadOptions.d-B1pTMmDF.d.ts +260 -0
- package/dist/{timelineRows-7yjHyh8i.d.ts → timelineRows.d-BNxgzYRW.d.cts} +1 -1
- package/dist/{timelineRows-WvnL-Lds.d.cts → timelineRows.d-CU5GvvLk.d.ts} +1 -1
- package/dist/{tokens-DLj8OnLH.d.cts → tokens.d-DarDaV39.d.cts} +10 -2
- package/dist/{tokens-DLj8OnLH.d.ts → tokens.d-DarDaV39.d.ts} +10 -2
- package/dist/{typeStyle-BxVyF71R.d.ts → typeStyle.d-Bl8pzbBy.d.cts} +2 -2
- package/dist/{typeStyle-DJedEu14.d.cts → typeStyle.d-C1HBRAI3.d.ts} +2 -2
- package/dist/{uploadTransport-BM_pnEWj.d.cts → uploadTransport.d-CWL7CdWP.d.cts} +1 -1
- package/dist/{uploadTransport-C6kGP1Kd.d.ts → uploadTransport.d-EGoUl7gX.d.ts} +1 -1
- package/dist/usePresentation.d-D6qsFzBz.d.cts +9 -0
- package/dist/usePresentation.d-DuGQe_Do.d.ts +9 -0
- package/dist/useRecords.d-Cb-36SF5.d.cts +121 -0
- package/dist/useRecords.d-aQTzQZoV.d.ts +121 -0
- package/dist/{useRecordsDepth-Bp6L4M5P.d.ts → useRecordsDepth.d-DFcCfiXm.d.ts} +8 -20
- package/dist/{useRecordsDepth-DPdAK_81.d.cts → useRecordsDepth.d-sAq2Qkhr.d.cts} +8 -20
- package/dist/{useVetVisit-DmWa7lt1.d.ts → useVetVisit.d-BtdwhmgD.d.cts} +15 -4
- package/dist/{useVetVisit-PtBjNwZr.d.cts → useVetVisit.d-DoYQimyt.d.ts} +15 -4
- package/dist/video/index.cjs +6 -2
- package/dist/video/index.d.cts +7 -7
- package/dist/video/index.d.ts +7 -7
- package/dist/video/index.js +6 -2
- package/dist/{view-C6go2uUt.d.ts → view.d-C-SNpDJX.d.ts} +10 -122
- package/dist/{view-CiF_HVFQ.d.cts → view.d-Dps5C8-s.d.cts} +10 -122
- package/dist/web/consent/index.cjs +5 -1
- package/dist/web/consent/index.d.cts +10 -10
- package/dist/web/consent/index.d.ts +10 -10
- package/dist/web/consent/index.js +5 -1
- package/dist/web/health-plan/index.cjs +414 -0
- package/dist/web/health-plan/index.d.cts +335 -0
- package/dist/web/health-plan/index.d.ts +335 -0
- package/dist/web/health-plan/index.js +414 -0
- package/dist/web/index.cjs +150 -82
- package/dist/web/index.d.cts +152 -38
- package/dist/web/index.d.ts +152 -38
- package/dist/web/index.js +150 -82
- package/dist/web/notifications/index.cjs +16 -3
- package/dist/web/notifications/index.d.cts +39 -209
- package/dist/web/notifications/index.d.ts +39 -209
- package/dist/web/notifications/index.js +16 -3
- package/dist/web/records/depth/index.cjs +11 -7
- package/dist/web/records/depth/index.d.cts +14 -12
- package/dist/web/records/depth/index.d.ts +14 -12
- package/dist/web/records/depth/index.js +11 -7
- package/dist/web/records/index.cjs +95 -68
- package/dist/web/records/index.d.cts +66 -21
- package/dist/web/records/index.d.ts +66 -21
- package/dist/web/records/index.js +95 -68
- package/dist/web/records/upload/index.d.cts +2 -2
- package/dist/web/records/upload/index.d.ts +2 -2
- package/dist/web/records-sheet/index.cjs +278 -0
- package/dist/web/records-sheet/index.d.cts +102 -0
- package/dist/web/records-sheet/index.d.ts +102 -0
- package/dist/web/records-sheet/index.js +278 -0
- package/dist/web/shop/index.cjs +301 -0
- package/dist/web/shop/index.d.cts +42 -0
- package/dist/web/shop/index.d.ts +42 -0
- package/dist/web/shop/index.js +301 -0
- package/dist/web/televet/booking/index.cjs +16 -12
- package/dist/web/televet/booking/index.d.cts +37 -23
- package/dist/web/televet/booking/index.d.ts +37 -23
- package/dist/web/televet/booking/index.js +16 -12
- package/dist/web/televet/call/index.d.cts +4 -4
- package/dist/web/televet/call/index.d.ts +4 -4
- package/dist/web/televet/index.cjs +7 -3
- package/dist/web/televet/index.d.cts +12 -12
- package/dist/web/televet/index.d.ts +12 -12
- package/dist/web/televet/index.js +7 -3
- package/dist/web/texting/index.cjs +157 -0
- package/dist/web/texting/index.d.cts +36 -0
- package/dist/web/texting/index.d.ts +36 -0
- package/dist/web/texting/index.js +157 -0
- package/health-plan/package.json +8 -0
- package/package.json +106 -4
- package/shop/package.json +8 -0
- package/texting/package.json +8 -0
- package/web/health-plan/native-blocked.cjs +12 -0
- package/web/health-plan/package.json +8 -0
- package/web/records-sheet/native-blocked.cjs +12 -0
- package/web/records-sheet/package.json +8 -0
- package/web/shop/native-blocked.cjs +12 -0
- package/web/shop/package.json +8 -0
- package/web/texting/native-blocked.cjs +12 -0
- package/web/texting/package.json +8 -0
- /package/dist/{CameraPort-Cv31Pz7g.d.cts → CameraPort.d-Cv31Pz7g.d.cts} +0 -0
- /package/dist/{CameraPort-Cv31Pz7g.d.ts → CameraPort.d-Cv31Pz7g.d.ts} +0 -0
- /package/dist/{TelemetryPort-BDNr00hu.d.cts → TelemetryPort.d-BDNr00hu.d.cts} +0 -0
- /package/dist/{TelemetryPort-BDNr00hu.d.ts → TelemetryPort.d-BDNr00hu.d.ts} +0 -0
- /package/dist/{cacheEpoch-DknKn3S0.d.cts → cacheEpoch.d-DknKn3S0.d.cts} +0 -0
- /package/dist/{cacheEpoch-DknKn3S0.d.ts → cacheEpoch.d-DknKn3S0.d.ts} +0 -0
- /package/dist/{callCopy-Bw6oZT54.d.cts → callCopy.d-Bw6oZT54.d.cts} +0 -0
- /package/dist/{callCopy-Bw6oZT54.d.ts → callCopy.d-Bw6oZT54.d.ts} +0 -0
- /package/dist/{ids-B2GAAifq.d.cts → ids.d-B2GAAifq.d.cts} +0 -0
- /package/dist/{ids-B2GAAifq.d.ts → ids.d-B2GAAifq.d.ts} +0 -0
- /package/dist/{optionalModule-DbJmsq5f.d.cts → optionalModule.d-DbJmsq5f.d.cts} +0 -0
- /package/dist/{optionalModule-DbJmsq5f.d.ts → optionalModule.d-DbJmsq5f.d.ts} +0 -0
- /package/dist/{profile-CSs1wlXT.d.cts → profile.d-CSs1wlXT.d.cts} +0 -0
- /package/dist/{profile-CSs1wlXT.d.ts → profile.d-CSs1wlXT.d.ts} +0 -0
- /package/dist/{projection-CeIUsbSk.d.cts → projection.d-CeIUsbSk.d.cts} +0 -0
- /package/dist/{projection-CeIUsbSk.d.ts → projection.d-CeIUsbSk.d.ts} +0 -0
- /package/dist/{species-BXAIMh7I.d.cts → species.d-BXAIMh7I.d.cts} +0 -0
- /package/dist/{species-BXAIMh7I.d.ts → species.d-BXAIMh7I.d.ts} +0 -0
- /package/dist/{visitIntent-D7_yVp1I.d.cts → visitIntent.d-D7_yVp1I.d.cts} +0 -0
- /package/dist/{visitIntent-D7_yVp1I.d.ts → visitIntent.d-D7_yVp1I.d.ts} +0 -0
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import{createContext,forwardRef,createElement,useState,useMemo,useContext,useEffect,useSyncExternalStore,useCallback,useRef,Fragment as Fragment$1,Component}from"react";import{TextInput,View,Pressable,StyleSheet,useWindowDimensions,ScrollView,Modal,Image,Text as Text$1,Linking,AppState,ActivityIndicator}from"react-native";import{jsxs,jsx,Fragment}from"react/jsx-runtime";var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base3=face(theme,fallback);return base3.fontWeight===void 0||headingWeight===null?base3:{fontFamily:base3.fontFamily,fontWeight:headingWeight}}var HEALTH_PLAN_COPY=/* @__PURE__ */Object.freeze({loading:"Loading",retry:"Try again",signedOut:"Sign in required",addToCart:"Add to cart",added:"Added",remove:"Remove",checkout:"Checkout",subtotal:"Subtotal",sample:"Sample",cartEmpty:"Your cart is empty.",choosePet:"Choose a pet",emptyTitle:"",emptyBody:"",emptyAsk:""}),COPY_ASKS=/* @__PURE__ */Object.freeze({emptyTitle:true,emptyBody:true,emptyAsk:true}),HEALTH_PLAN_REASON_LABELS=/* @__PURE__ */Object.freeze({dna:"",records:"Records",inside:"Inside",profile:""}),HEALTH_PLAN_TEMPLATES=/* @__PURE__ */Object.freeze({planTitle:petName=>`${petName}'s care plan`,cartLabel:brand=>`${brand} cart`}),HEALTH_PLAN_COPY_PLACEHOLDERS=/* @__PURE__ */Object.freeze([...Object.keys(HEALTH_PLAN_COPY).filter(key=>COPY_ASKS[key]===true&&HEALTH_PLAN_COPY[key]==="").map(key=>`HEALTH_PLAN_COPY.${key}`),...["profile"].filter(kind=>HEALTH_PLAN_REASON_LABELS[kind]==="").map(kind=>`HEALTH_PLAN_REASON_LABELS.${kind}`)]);var HEALTH_PLAN_LAYOUT_DEFAULTS=/* @__PURE__ */Object.freeze({imageVariant:"wide",reasonVariant:"pills",cartBarVisibility:"whenItems",cartBarPlacement:"sticky",addButtonSize:"full",addedVariant:"link",categoryVariant:"text",showCategory:false,cardShadow:false,cardBorder:true});function healthPlanWrites(plan,setInPlan){return{setInPlan:setInPlan,addAll:async()=>{let missing=(plan?.items??[]).filter(item=>!item.inPlan);return(await Promise.all(missing.map(item=>setInPlan(item.productId,true)))).every(Boolean)}}}function showHealthPlanCartBar(visibility,count){return(visibility??HEALTH_PLAN_LAYOUT_DEFAULTS.cartBarVisibility)==="always"||count>0}var HEALTH_PLAN_CARD_OPTION_KEYS=/* @__PURE__ */Object.freeze(["showCategory","cardShadow","cardBorder","addButtonSize","addButtonFontSize","addedVariant","categoryVariant","cardPadding","itemTitleSize","itemTitleWeight","priceSize","priceWeight","reasonTextSize","reasonLabelWidth","reasonGap"]);function pickHealthPlanCardOptions(props){let out={};for(let key of HEALTH_PLAN_CARD_OPTION_KEYS)props[key]!==void 0&&(out[key]=props[key]);return out}function healthPlanAddButtonHeight(size){let height=typeof size=="number"&&Number.isFinite(size)&&size>0?size:size==="compact"?32:44;return{height:height,hit:Math.max(44,height)}}function parseHealthPlanShadow(css){if(css.length>200||css.includes(",")&&!/rgba?\(|hsla?\(/i.test(css))return null;let color=/(rgba?\([^)]*\)|hsla?\([^)]*\)|#[0-9a-f]{3,8}\b|[a-z]+)\s*$/i.exec(css.trim())?.[1]??null;if(color===null)return null;let lengths=css.trim().slice(0,css.trim().length-color.length).trim().split(/\s+/).filter(Boolean);if(lengths.length<2||lengths.length>4)return null;let px=lengths.map(part=>part==="0"?0:/^-?\d*\.?\d+px$/.test(part)?Number(part.slice(0,-2)):Number.NaN);return px.some(n=>!Number.isFinite(n))?null:{color:color,offsetX:px[0]??0,offsetY:px[1]??0,blur:Math.max(0,px[2]??0)}}function healthPlanLength(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function healthPlanTitleOffset(titleGap,sectionGap){let gap=healthPlanLength(titleGap);return gap===null?0:gap-sectionGap}function isHealthPlanSessionRequired(error){return error!==null&&(error.reasonCode==="session_required"||error.code==="sessionRequired")}var DockContext=createContext(null);function HealthPlanCartScope({children:children}){let[dock,setDock]=useState(null),store=useMemo(()=>({dock:dock,publish:setDock}),[dock]);return createElement(DockContext.Provider,{value:store},children)}function useHealthPlanCartDock(){return useContext(DockContext)?.dock??null}function usePublishHealthPlanCart(enabled,cart,busy,petRef,plan,setInPlan){let publish=useContext(DockContext)?.publish,latest=useRef(setInPlan);useEffect(()=>{latest.current=setInPlan},[setInPlan]);let writes=useMemo(()=>healthPlanWrites(plan,(productId,inPlan)=>latest.current(productId,inPlan)),[plan]);useEffect(()=>{if(!(publish===void 0||!enabled))return publish(/* @__PURE__ */Object.freeze({cart:cart,busy:busy,petRef:petRef,plan:plan,...writes})),()=>publish(null)},[publish,enabled,cart,busy,petRef,plan,writes])}var noopTelemetry=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});function ok(value,warning){/* @__PURE__ */
|
|
2
|
+
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
3
|
+
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 EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var HEALTH_PLAN_EVENTS=/* @__PURE__ */Object.freeze({opened:"health_plan.opened",productClicked:"health_plan.product_clicked",checkoutStarted:"health_plan.checkout_started"});function useHealthPlanTelemetry(){return useContext(EverfurContext)?.runtime.registry.services.telemetry??noopTelemetry}var PlanPetContext=createContext(null);function HealthPlanPetScope({petRef:petRef,children:children}){return createElement(PlanPetContext.Provider,{value:petRef},children)}function useHealthPlanBarPet(dockPet){let page=useContext(PlanPetContext),ctx=useContext(EverfurContext);return page??dockPet??ctx?.activePet??null}function useHealthPlanOpened(drawn,petRef,plan){let telemetry=useHealthPlanTelemetry(),sent=useRef(null);useEffect(()=>{if(!drawn||petRef===null||sent.current===petRef)return;sent.current=petRef;let items=plan?.items??[];telemetry.track(HEALTH_PLAN_EVENTS.opened,{petRef:petRef,itemsCount:items.length,inPlanCount:items.filter(item=>item.inPlan).length})},[drawn,petRef,plan,telemetry])}function trackProductClicked(telemetry,petRef,productId,inPlan){telemetry.track(HEALTH_PLAN_EVENTS.productClicked,{petRef:petRef,productId:productId,inPlan:inPlan})}function trackCheckoutStarted(telemetry,petRef,cart){telemetry.track(HEALTH_PLAN_EVENTS.checkoutStarted,{petRef:petRef,itemsCount:cart.count,subtotal:cart.subtotal,currency:cart.currency})}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
4
|
+
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
5
|
+
/* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
6
|
+
/* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
7
|
+
/* @__PURE__ */Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
8
|
+
/* @__PURE__ */Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
9
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
10
|
+
/* @__PURE__ */Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
11
|
+
/* @__PURE__ */Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
12
|
+
/* @__PURE__ */Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),
|
|
13
|
+
/* @__PURE__ */Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),
|
|
14
|
+
/* @__PURE__ */Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),
|
|
15
|
+
/* @__PURE__ */Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
16
|
+
/* @__PURE__ */Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
17
|
+
/* @__PURE__ */Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
18
|
+
/* @__PURE__ */Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),
|
|
19
|
+
/* @__PURE__ */Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
20
|
+
/* @__PURE__ */Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
21
|
+
/* @__PURE__ */Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
22
|
+
/* @__PURE__ */Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
23
|
+
/* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
24
|
+
/* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
|
|
25
|
+
/* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
26
|
+
/* @__PURE__ */Object.freeze({wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
27
|
+
/* @__PURE__ */Object.freeze({wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
28
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
29
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
30
|
+
/* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
31
|
+
/* @__PURE__ */Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
32
|
+
/* @__PURE__ */Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
33
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
34
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
35
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
36
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
37
|
+
/* @__PURE__ */Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
38
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
39
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
40
|
+
/* @__PURE__ */Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
41
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
42
|
+
/* @__PURE__ */Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
43
|
+
/* @__PURE__ */Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
44
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
45
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),
|
|
46
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
47
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
48
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
49
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
50
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
51
|
+
/* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
52
|
+
/* @__PURE__ */Object.freeze({wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
53
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
54
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
55
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
|
|
56
|
+
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
57
|
+
/* @__PURE__ */Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),
|
|
58
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
59
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
60
|
+
/* @__PURE__ */Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
61
|
+
/* @__PURE__ */Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),
|
|
62
|
+
/* @__PURE__ */Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
63
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
64
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
65
|
+
/* @__PURE__ */Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
66
|
+
/* @__PURE__ */Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
67
|
+
/* @__PURE__ */Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
68
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
69
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
70
|
+
/* @__PURE__ */Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
71
|
+
/* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
72
|
+
/* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
73
|
+
/* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
74
|
+
/* @__PURE__ */Object.freeze({wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
75
|
+
/* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
|
|
76
|
+
/* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
|
|
77
|
+
/* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
78
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
79
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
80
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
81
|
+
/* @__PURE__ */Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
82
|
+
/* @__PURE__ */Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
83
|
+
/* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
84
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
|
|
85
|
+
/* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
86
|
+
/* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
87
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
88
|
+
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
89
|
+
/* @__PURE__ */Object.freeze({wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
90
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
91
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
92
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
93
|
+
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
94
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
95
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
96
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
|
|
97
|
+
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base3=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base3,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
98
|
+
/* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
|
|
99
|
+
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var HEALTH_PLAN_REASON_KINDS=/* @__PURE__ */Object.freeze(["dna","records","inside","profile"]),REF_MAX=128;function invalid(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function malformed(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response carried no plan`})}var str=(value,max=4e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null;function httpsUrl(value){let s=str(value,2048);return s===null?null:/^https:\/\/[^\s]+$/i.test(s)?s:null}function priceOf(value){let n=typeof value=="number"?value:typeof value=="string"&&/^\d+(\.\d+)?$/.test(value.trim())?Number(value):Number.NaN;return Number.isFinite(n)&&n>=0?n:null}function currencyOf(value){return typeof value=="string"&&/^[A-Za-z]{3}$/.test(value)?value.toUpperCase():null}function reasonsOf(value){if(!Array.isArray(value))/* @__PURE__ */return Object.freeze([]);let out=[];for(let raw of value){if(raw===null||typeof raw!="object")continue;let o=raw,text2=str(o.text,1e3);if(text2===null)continue;let kind=typeof o.kind=="string"&&HEALTH_PLAN_REASON_KINDS.includes(o.kind)?o.kind:"profile";out.push(/* @__PURE__ */Object.freeze({kind:kind,text:text2}))}/* @__PURE__ */
|
|
100
|
+
return Object.freeze(out)}function itemOf(raw){if(raw===null||typeof raw!="object")return null;let o=raw,rawId=o.product_id,productId=typeof rawId=="number"&&Number.isInteger(rawId)?String(rawId):str(rawId,REF_MAX),title=str(o.title,300);return productId===null||title===null?null:/* @__PURE__ */Object.freeze({productId:productId,partnerSku:str(o.partner_sku,200),title:title,description:str(o.description),category:str(o.category,60),price:priceOf(o.price),currency:currencyOf(o.currency),imageUrl:httpsUrl(o.image_url),url:httpsUrl(o.url),reasons:reasonsOf(o.reasons),inPlan:o.in_plan===true,sample:o.sample===true})}function healthPlanFromWire(raw,petRef){if(raw===null||typeof raw!="object")return null;let o=raw;if(!Array.isArray(o.items))return null;let items=[],seen=/* @__PURE__ */new Set;for(let row of o.items){let item=itemOf(row);item===null||seen.has(item.productId)||(seen.add(item.productId),items.push(item))}/* @__PURE__ */
|
|
101
|
+
return Object.freeze({petRef:str(o.pet_ref,REF_MAX)??petRef,headline:str(o.headline,300),items:/* @__PURE__ */Object.freeze(items),updatedAt:str(o.updated_at,64),...o.tracking_texts_enabled===true?{trackingTextsEnabled:true}:{}})}function validRef(value){return typeof value=="string"&&value.length>0&&value.length<=REF_MAX}function planPath(petRef){return`/widget/v1/pets/${encodeURIComponent(petRef)}/plan`}function createHealthPlanRepository(runtime){let over=()=>{let{services:services}=runtime.registry;return createHealthPlanRepositoryOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})};return{read:(petRef,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("read"))):over().read(petRef,opts),addItem:(petRef,id)=>runtime.isDisposed?Promise.resolve(err(disposed("addItem"))):over().addItem(petRef,id),removeItem:(petRef,id)=>runtime.isDisposed?Promise.resolve(err(disposed("removeItem"))):over().removeItem(petRef,id)}}function createHealthPlanRepositoryOver(deps){let funnel=withPlainNotFound(deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}})),write=async(method,petRef,productId)=>{if(!validRef(petRef))return err(invalid("petRef must be 1..128 characters"));if(!validRef(productId))return err(invalid("productId must be 1..128 characters"));let call=method==="PUT"?"healthPlan.item.add":"healthPlan.item.remove",res=await funnel.send(call,{method:method,path:`${planPath(petRef)}/items/${encodeURIComponent(productId)}`});return res.ok?res.value===null||res.value===void 0||res.value===""?ok(null):ok(healthPlanFromWire(res.value,petRef)):err(res.error)};return{async read(petRef,opts){if(!validRef(petRef))return err(invalid("petRef must be 1..128 characters"));let req={method:"GET",path:planPath(petRef),...opts?.signal?{signal:opts.signal}:{}},res=await funnel.send("healthPlan.read",req);if(!res.ok)return err(res.error);let plan=healthPlanFromWire(res.value,petRef);return plan===null?err(malformed("healthPlan.read")):ok(plan)},addItem:(petRef,productId)=>write("PUT",petRef,productId),removeItem:(petRef,productId)=>write("DELETE",petRef,productId)}}var IDLE=/* @__PURE__ */Object.freeze({phase:"idle",petRef:null,plan:null,pending:/* @__PURE__ */Object.freeze([]),itemErrors:/* @__PURE__ */Object.freeze({}),error:null});function withItem(plan,productId,inPlan){let items=plan.items.map(item=>item.productId===productId?/* @__PURE__ */Object.freeze({...item,inPlan:inPlan}):item);/* @__PURE__ */
|
|
102
|
+
return Object.freeze({...plan,items:/* @__PURE__ */Object.freeze(items)})}var HealthPlanController=class{constructor(repository){this.repository=repository;this.snapshot=IDLE;this.listeners=/* @__PURE__ */new Set;this.generation=0;this.writes=0;this.revalidations=0;this.refreshAfterWrites=false;this.disposed=false;this.subscribe=listener=>(this.listeners.add(listener),()=>{this.listeners.delete(listener)});this.getSnapshot=()=>this.snapshot}set(next){if(!this.disposed){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...next});for(let listener of this.listeners)listener()}}async load(petRef){let gen=++this.generation;if(this.refreshAfterWrites=false,petRef===null){this.set({...IDLE});return}let samePet=this.snapshot.petRef===petRef;this.set({phase:"loading",petRef:petRef,plan:samePet?this.snapshot.plan:null,pending:/* @__PURE__ */Object.freeze([]),itemErrors:samePet?this.snapshot.itemErrors:/* @__PURE__ */Object.freeze({}),error:null});let result=await this.repository.read(petRef);if(gen===this.generation){if(!result.ok){this.set({phase:"failed",error:result.error});return}this.set({phase:"ready",plan:result.value,error:null,itemErrors:/* @__PURE__ */Object.freeze({})})}}async revalidate(){let{phase:phase,petRef:petRef,pending:pending}=this.snapshot;if(phase!=="ready"||petRef===null||pending.length>0)return;let gen=this.generation,writes=this.writes,seq=++this.revalidations,result=await this.repository.read(petRef);gen!==this.generation||writes!==this.writes||seq!==this.revalidations||this.snapshot.pending.length>0||this.snapshot.petRef!==petRef||result.ok&&this.set({plan:result.value,itemErrors:/* @__PURE__ */Object.freeze({})})}async refresh(){let{phase:phase,petRef:petRef,pending:pending}=this.snapshot;if(!(petRef===null||phase==="idle")){if(phase!=="ready")return this.load(petRef);if(pending.length>0){this.refreshAfterWrites=true;return}return this.revalidate()}}settleWrite(){!this.refreshAfterWrites||this.snapshot.pending.length>0||(this.refreshAfterWrites=false,this.revalidate())}async setInPlan(productId,inPlan){let{plan:plan,petRef:petRef,pending:pending}=this.snapshot;if(this.snapshot.phase!=="ready"||plan===null||petRef===null||pending.includes(productId))return false;let before=plan.items.find(item=>item.productId===productId);if(before===void 0||before.inPlan===inPlan)return false;this.writes+=1;let gen=this.generation,otherErrors=Object.fromEntries(Object.entries(this.snapshot.itemErrors).filter(([id])=>id!==productId));this.set({plan:withItem(plan,productId,inPlan),pending:/* @__PURE__ */Object.freeze([...pending,productId]),itemErrors:/* @__PURE__ */Object.freeze(otherErrors)});let result=inPlan?await this.repository.addItem(petRef,productId):await this.repository.removeItem(petRef,productId);if(gen!==this.generation)return result.ok;let current=this.snapshot.plan??plan,stillPending=/* @__PURE__ */Object.freeze(this.snapshot.pending.filter(id=>id!==productId));if(!result.ok)return this.set({plan:withItem(current,productId,before.inPlan),pending:stillPending,itemErrors:/* @__PURE__ */Object.freeze({...this.snapshot.itemErrors,[productId]:result.error})}),this.settleWrite(),false;let next=result.value??current;for(let id of stillPending){let mine=current.items.find(item=>item.productId===id);mine!==void 0&&(next=withItem(next,id,mine.inPlan))}return this.set({plan:next,pending:stillPending}),this.settleWrite(),true}dispose(){this.generation+=1,this.disposed=true,this.listeners.clear()}};function useScopedController(create,deps){let[controller,setController]=useState(create),adopted=useRef(false);return useEffect(()=>{let current=controller;return adopted.current&&(current=create(),setController(current)),adopted.current=true,()=>current.dispose()},deps),controller}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}var HEALTH_PLAN_STALE_MS=6e4;function useHealthPlanRevalidation({lifecycle:lifecycle,refreshKey:refreshKey,readyAt:readyAt,revalidate:revalidate,refresh:refresh,now:now=Date.now}){let latest=useRef({readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now});latest.current={readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now},useEffect(()=>{if(lifecycle==null)return;let stop=callHost(()=>lifecycle.onForeground(()=>{let{readyAt:at,revalidate:run,now:clock}=latest.current;at!==null&&clock()-at>=HEALTH_PLAN_STALE_MS&&run()}));return()=>{typeof stop=="function"&&callHost(stop)}},[lifecycle]);let seenKey=useRef(refreshKey);useEffect(()=>{Object.is(seenKey.current,refreshKey)||(seenKey.current=refreshKey,latest.current.refresh())},[refreshKey])}function healthPlanCart(plan){let items=/* @__PURE__ */Object.freeze((plan?.items??[]).filter(item=>item.inPlan));if(items.length===0)/* @__PURE__ */return Object.freeze({items:items,count:0,subtotal:null,currency:null});let currencies=new Set(items.map(item=>item.currency));if(!items.every(item=>item.price!==null)||currencies.size!==1)/* @__PURE__ */return Object.freeze({items:items,count:items.length,subtotal:null,currency:null});let cents=items.reduce((sum,item)=>sum+Math.round(item.price*100),0);/* @__PURE__ */
|
|
103
|
+
return Object.freeze({items:items,count:items.length,subtotal:cents/100,currency:items[0]?.currency??null})}function formatHealthPlanPrice(amount,currency,locale,format){if(amount===null||currency===null||!Number.isFinite(amount))return null;let whole=format?.dropZeroCents===true&&Number.isInteger(amount);try{return new Intl.NumberFormat(locale,{style:"currency",currency:currency,...whole?{minimumFractionDigits:0,maximumFractionDigits:0}:{}}).format(amount)}catch{return`${currency} ${whole?String(amount):amount.toFixed(2)}`}}function formatHealthPlanPriceWith(amount,currency,format){return formatHealthPlanPrice(amount,currency,format?.locale,format)}function useEverfurHealthPlanRepository(){let{runtime:runtime}=useEverfurContext();return useMemo(()=>createHealthPlanRepository(runtime),[runtime])}function useEverfurHealthPlan(options){let{userRef:userRef,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useEverfurHealthPlanRepository(),petRef=options?.petRef??activePet??null,controller=useScopedController(()=>new HealthPlanController(repository),[repository,userRef,scopeEpoch]);useEffect(()=>{controller.load(userRef===null?null:petRef)},[controller,userRef,petRef]);let snapshot=useSyncExternalStore(controller.subscribe,controller.getSnapshot,controller.getSnapshot),cart=useMemo(()=>healthPlanCart(snapshot.plan),[snapshot.plan]),[readyAt,setReadyAt]=useState(null);useEffect(()=>{setReadyAt(snapshot.phase==="ready"&&snapshot.plan!==null?Date.now():null)},[snapshot.phase,snapshot.plan]),useHealthPlanRevalidation({lifecycle:options?.lifecycle,refreshKey:options?.refreshKey,readyAt:readyAt,revalidate:()=>{controller.revalidate()},refresh:()=>{controller.refresh()}});let status;return userRef===null?status="signedOut":petRef===null?status="noPet":snapshot.petRef!==petRef||snapshot.phase==="idle"||snapshot.phase==="loading"?status="loading":snapshot.phase==="failed"?status=isNotFoundError(snapshot.error)?"empty":"failed":status=(snapshot.plan?.items.length??0)===0?"empty":"ready",useMemo(()=>({status:status,petRef:petRef,plan:snapshot.petRef===petRef?snapshot.plan:null,cart:cart,pending:snapshot.pending,itemErrors:snapshot.itemErrors,error:status==="empty"?null:snapshot.error,setInPlan:(productId,inPlan)=>controller.setInPlan(productId,inPlan),refresh:()=>controller.load(userRef===null?null:petRef)}),[status,petRef,snapshot,cart,controller,userRef])}var REF_MAX2=128,DATE=/^\d{4}-\d{2}-\d{2}$/,STEPS=/* @__PURE__ */new Set(["first_box_ships","checkin","refill_reminder","next_box_ships"]);function isHealthPlanSubscriptionUnavailable(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}var str2=(value,max=300)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null;function money(value){let n=typeof value=="number"?value:typeof value=="string"&&/^\d+(\.\d+)?$/.test(value.trim())?Number(value):Number.NaN;return Number.isFinite(n)&&n>=0?n:null}function int(value){return typeof value=="number"&&Number.isInteger(value)&&value>0?value:null}function idOf(value){return typeof value=="number"&&Number.isInteger(value)?String(value):str2(value,REF_MAX2)}function currencyOf2(value){return typeof value=="string"&&/^[A-Za-z]{3}$/.test(value)?value.toUpperCase():null}function dateOf(value){return typeof value=="string"&&DATE.test(value)?value:null}function intervalsOf(value){return Array.isArray(value)?/* @__PURE__ */Object.freeze(value.map(int).filter(n=>n!==null)):/* @__PURE__ */Object.freeze([])}function renewalOf(value){if(value===null||typeof value!="object")return null;let o=value,amount=money(o.amount),currency=currencyOf2(o.currency),intervalDays=int(o.interval_days);return amount===null||currency===null||intervalDays===null?null:/* @__PURE__ */Object.freeze({amount:amount,currency:currency,intervalDays:intervalDays})}function timelineOf(value){if(!Array.isArray(value))/* @__PURE__ */return Object.freeze([]);let out=[];for(let raw of value){if(raw===null||typeof raw!="object")continue;let o=raw,on=dateOf(o.on);typeof o.step!="string"||!STEPS.has(o.step)||on===null||out.push(/* @__PURE__ */Object.freeze({step:o.step,on:on}))}/* @__PURE__ */
|
|
104
|
+
return Object.freeze(out)}function healthPlanSubscriptionFromWire(raw){if(raw===null||typeof raw!="object")return null;let o=raw,subscriptionId=idOf(o.subscription_id),productId=idOf(o.product_id),status=o.status==="active"||o.status==="cancelled"?o.status:null,intervalDays=int(o.interval_days),currency=currencyOf2(o.currency),boxPrice=money(o.box_price);if(subscriptionId===null||productId===null||status===null||intervalDays===null||currency===null||boxPrice===null)return null;let options=intervalsOf(o.interval_options);/* @__PURE__ */
|
|
105
|
+
return Object.freeze({subscriptionId:subscriptionId,productId:productId,title:str2(o.title),status:status,intervalDays:intervalDays,intervalOptions:options.length>0?options:/* @__PURE__ */Object.freeze([intervalDays]),currency:currency,boxPrice:boxPrice,firstBoxPrice:money(o.first_box_price)??boxPrice,offerApplied:o.offer_applied===true,nextBoxDate:status==="active"?dateOf(o.next_box_date):null,renewal:renewalOf(o.renewal),timeline:status==="active"?timelineOf(o.timeline):/* @__PURE__ */Object.freeze([])})}function healthPlanOneBoxOrderFromWire(raw){if(raw===null||typeof raw!="object")return null;let o=raw,orderId=idOf(o.order_id),productId=idOf(o.product_id),currency=currencyOf2(o.currency),price=money(o.price);if(orderId===null||productId===null||currency===null||price===null)return null;let quantity=int(o.quantity),qty=quantity!==null&&quantity<=QUANTITY_MAX?quantity:1;/* @__PURE__ */
|
|
106
|
+
return Object.freeze({orderId:orderId,productId:productId,title:str2(o.title),currency:currency,boxPrice:money(o.box_price)??price,price:price,discountPercent:int(o.discount_percent)??0,shipsOn:dateOf(o.ships_on),createdAt:instantOf(o.created_at),quantity:qty,total:money(o.total)??Math.round(price*qty*100)/100,...trackingOf(o.tracking)})}var QUANTITY_MAX=10,TRACKING_STATUSES=/* @__PURE__ */new Set(["ordered","shipped","delivered"]),UNSAFE_TEXT=/[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069]/;function trackingText(value,max){if(typeof value!="string"||UNSAFE_TEXT.test(value))return null;let v=value.trim();return v.length>0&&v.length<=max?v:null}function trackingUrlOf(value){if(typeof value!="string"||value.length>2048||UNSAFE_TEXT.test(value)||/[\s@]/.test(value)||!/^https:\/\/[^/]/i.test(value))return null;try{return new URL(value).protocol==="https:"?value:null}catch{return null}}function healthPlanOrderTrackingFromWire(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let o=raw,status=typeof o.status=="string"&&TRACKING_STATUSES.has(o.status)?o.status:"ordered";/* @__PURE__ */
|
|
107
|
+
return Object.freeze({status:status,orderNumber:trackingText(o.order_number,64),carrier:trackingText(o.carrier,64),trackingNumber:trackingText(o.tracking_number,128),trackingUrl:trackingUrlOf(o.tracking_url),shippedAt:instantOf(o.shipped_at),estimatedDelivery:dateOf(o.estimated_delivery),updatedAt:instantOf(o.updated_at)})}function trackingOf(raw){let t=healthPlanOrderTrackingFromWire(raw);return t===null?{}:{tracking:t}}function healthPlanOneBoxOrderPageFromWire(raw){let rows=raw!==null&&typeof raw=="object"?raw.orders:null;if(!Array.isArray(rows))return null;let cursor=raw.next_cursor;/* @__PURE__ */
|
|
108
|
+
return Object.freeze({orders:/* @__PURE__ */Object.freeze(rows.map(healthPlanOneBoxOrderFromWire).filter(x=>x!==null)),nextCursor:typeof cursor=="string"&&cursor.length>0&&cursor.length<=REF_MAX2?cursor:null})}function instantOf(value){return typeof value!="string"||value.length>40||!/^\d{4}-\d{2}-\d{2}T/.test(value)||Number.isNaN(Date.parse(value))?null:value}function oneBoxOf(value,boxPrice){if(value===null||typeof value!="object")return null;let o=value,price=money(o.price);return price===null||price>boxPrice?null:/* @__PURE__ */Object.freeze({price:price,discountPercent:int(o.discount_percent)??0})}function healthPlanSubscriptionQuoteFromWire(raw){if(raw===null||typeof raw!="object")return null;let o=raw,productId=idOf(o.product_id),currency=currencyOf2(o.currency),boxPrice=money(o.box_price),options=intervalsOf(o.interval_options);if(productId===null||currency===null||boxPrice===null||options.length===0)return null;let offerApplies=o.offer_applies===true,def=int(o.default_interval_days),s=o.supply,supply=null;if(s!==null&&typeof s=="object"){let so=s,unitsPerBox=int(so.units_per_box),unitsPerDay=money(so.units_per_day),supplyDays=int(so.supply_days);unitsPerBox!==null&&unitsPerDay!==null&&supplyDays!==null&&(supply=/* @__PURE__ */Object.freeze({unitsPerBox:unitsPerBox,unitLabel:str2(so.unit_label,30),unitsPerDay:unitsPerDay,supplyDays:supplyDays,doseBasis:so.dose_basis==="weight"?"weight":"assumed"}))}let pct=int(o.first_box_discount_percent)??0;/* @__PURE__ */
|
|
109
|
+
return Object.freeze({productId:productId,currency:currency,boxPrice:boxPrice,firstBoxPrice:offerApplies?money(o.first_box_price)??boxPrice:boxPrice,firstBoxDiscountPercent:offerApplies?pct:0,offerApplies:offerApplies,oneBox:oneBoxOf(o.one_box,boxPrice),intervalOptions:options,defaultIntervalDays:def!==null&&options.includes(def)?def:options[0],supply:supply,firstBoxShipsOn:dateOf(o.first_box_ships_on),subscription:healthPlanSubscriptionFromWire(o.subscription)})}function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed2(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response carried no subscription`})}function disposed2(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef2=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX2;function base(petRef){return`/widget/v1/pets/${encodeURIComponent(petRef)}/plan/subscriptions`}function createHealthPlanSubscriptionRepositoryOver(deps){let funnel=withPlainNotFound(deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}})),one=async(call,petRef,method,suffix,body)=>{if(!validRef2(petRef))return err(invalid2("petRef must be 1..128 characters"));let res=await funnel.send(call,{method:method,path:`${base(petRef)}${suffix}`,...body===void 0?{}:{body:body}});if(!res.ok)return err(res.error);let sub=healthPlanSubscriptionFromWire(res.value);return sub===null?err(malformed2(call)):ok(sub)},idSuffix=(id,tail="")=>validRef2(id)?`/${encodeURIComponent(id)}${tail}`:null;return{async quote(petRef,productId){if(!validRef2(petRef))return err(invalid2("petRef must be 1..128 characters"));if(!validRef2(productId))return err(invalid2("productId must be 1..128 characters"));let res=await funnel.send("healthPlan.subscription.quote",{method:"GET",path:`${base(petRef)}/quote`,query:{product_id:productId}});if(!res.ok)return err(res.error);let quote=healthPlanSubscriptionQuoteFromWire(res.value);return quote===null?err(malformed2("healthPlan.subscription.quote")):ok(quote)},async list(petRef){if(!validRef2(petRef))return err(invalid2("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.subscription.list",{method:"GET",path:base(petRef)});if(!res.ok)return err(res.error);let rows=res.value!==null&&typeof res.value=="object"?res.value.subscriptions:null;return Array.isArray(rows)?ok(/* @__PURE__ */Object.freeze(rows.map(healthPlanSubscriptionFromWire).filter(s=>s!==null))):err(malformed2("healthPlan.subscription.list"))},create(petRef,productId,intervalDays){return validRef2(productId)?one("healthPlan.subscription.create",petRef,"POST","",{product_id:productId,...intervalDays===void 0?{}:{interval_days:intervalDays}}):Promise.resolve(err(invalid2("productId must be 1..128 characters")))},changeInterval(petRef,id,intervalDays){let s=idSuffix(id);return s===null?Promise.resolve(err(invalid2("subscriptionId must be 1..128 characters"))):one("healthPlan.subscription.interval",petRef,"PATCH",s,{interval_days:intervalDays})},skip(petRef,id){let s=idSuffix(id,"/skip");return s===null?Promise.resolve(err(invalid2("subscriptionId must be 1..128 characters"))):one("healthPlan.subscription.skip",petRef,"POST",s,{})},cancel(petRef,id){let s=idSuffix(id,"/cancel");return s===null?Promise.resolve(err(invalid2("subscriptionId must be 1..128 characters"))):one("healthPlan.subscription.cancel",petRef,"POST",s,{})},restart(petRef,id,intervalDays){let s=idSuffix(id,"/restart");return s===null?Promise.resolve(err(invalid2("subscriptionId must be 1..128 characters"))):one("healthPlan.subscription.restart",petRef,"POST",s,intervalDays===void 0?{}:{interval_days:intervalDays})},async buyOneBox(petRef,productId,tapKey){if(!validRef2(petRef))return err(invalid2("petRef must be 1..128 characters"));if(!validRef2(productId))return err(invalid2("productId must be 1..128 characters"));let res=await funnel.send("healthPlan.subscription.oneBox",{method:"POST",path:`${base(petRef)}/one-box`,body:{product_id:productId}},{idempotent:true,...tapKey===void 0?{}:{idempotencyKey:`hp-one-box:${tapKey}`}});if(!res.ok)return err(res.error);let order=healthPlanOneBoxOrderFromWire(res.value);return order===null?err(malformed2("healthPlan.subscription.oneBox")):ok(order)},async listOneBoxOrders(petRef){if(!validRef2(petRef))return err(invalid2("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.subscription.oneBoxList",{method:"GET",path:`${base(petRef)}/one-box`});if(!res.ok)return err(res.error);let page=healthPlanOneBoxOrderPageFromWire(res.value);return page===null?err(malformed2("healthPlan.subscription.oneBoxList")):ok(page.orders)},async listOneBoxOrderPage(petRef,opts){if(!validRef2(petRef))return err(invalid2("petRef must be 1..128 characters"));let limit=opts?.limit;if(limit!==void 0&&!(Number.isInteger(limit)&&limit>=1&&limit<=50))return err(invalid2("limit must be a whole number 1..50"));if(opts?.cursor!==void 0&&!validRef2(opts.cursor))return err(invalid2("cursor must be 1..128 characters"));let query={...limit!==void 0?{limit:String(limit)}:{},...opts?.cursor!==void 0?{cursor:opts.cursor}:{}},res=await funnel.send("healthPlan.subscription.oneBoxList",{method:"GET",path:`${base(petRef)}/one-box`,query:query});if(!res.ok)return err(res.error);let page=healthPlanOneBoxOrderPageFromWire(res.value);return page===null?err(malformed2("healthPlan.subscription.oneBoxList")):ok(page)}}}function createHealthPlanSubscriptionRepository(runtime){let over=()=>{let{services:services}=runtime.registry;return createHealthPlanSubscriptionRepositoryOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},guard=(verb,f)=>(...a)=>runtime.isDisposed?Promise.resolve(err(disposed2(verb))):f(over(),...a);return{quote:guard("quote",(r,p,id)=>r.quote(p,id)),list:guard("list",(r,p)=>r.list(p)),create:guard("create",(r,p,id,n)=>r.create(p,id,n)),changeInterval:guard("changeInterval",(r,p,id,n)=>r.changeInterval(p,id,n)),skip:guard("skip",(r,p,id)=>r.skip(p,id)),cancel:guard("cancel",(r,p,id)=>r.cancel(p,id)),restart:guard("restart",(r,p,id,n)=>r.restart(p,id,n)),buyOneBox:guard("buyOneBox",(r,p,id,k)=>r.buyOneBox(p,id,k)),listOneBoxOrders:guard("listOneBoxOrders",(r,p)=>r.listOneBoxOrders(p)),listOneBoxOrderPage:guard("listOneBoxOrderPage",(r,p,o)=>r.listOneBoxOrderPage(p,o))}}var REFUSALS=/* @__PURE__ */new Set(["cart_disabled","cart_has_subscription","cart_currency_mixed","sample_product","partner_endpoint_missing","checkout_pending","already_subscribed"]);function healthPlanCheckoutRefusal(error){if(error==null||error.httpStatus!==409)return null;let raw=obj(error.raw);for(let candidate of[error.reasonCode,error.wireMessage,raw?.detail,raw?.message,raw?.reason_code])if(typeof candidate=="string"&&REFUSALS.has(candidate.trim()))return candidate.trim();return null}var REF_MAX3=128,CART_MAX=10,ICONS=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame"]),obj=value=>value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null,str3=(value,max=1e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null,kindOf=value=>typeof value=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(value)?value:null,iconOf=value=>typeof value=="string"&&ICONS.has(value)?value:null;function imageOf(value){let s=str3(value,2048);return s===null||/\s/.test(s)?null:/^https:\/\/[^/]/i.test(s)||/^\/(?![/\\])/.test(s)?s:null}var idOf2=value=>typeof value=="number"&&Number.isInteger(value)?String(value):str3(value,REF_MAX3);function weightOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:null}function clean(fields){/* @__PURE__ */
|
|
110
|
+
return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str3(v,len),max);function focusOf(value){let o=obj(value),kicker=str3(o?.kicker,120),title=str3(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let label=str3(obj(r)?.label,60);return label===null?null:clean({label:label,kind:kindOf(obj(r)?.kind)})},6),risk:str3(risk?.lead,300)===null?null:clean({lead:str3(risk?.lead,300),body:str3(risk?.body),kind:kindOf(risk?.kind)}),odds:str3(odds?.label,120)===null||str3(odds?.from,20)===null||str3(odds?.to,20)===null?null:clean({label:str3(odds?.label,120),tag:str3(odds?.tag,40),from:str3(odds?.from,20),to:str3(odds?.to,20),toLabel:str3(odds?.toLabel,120)}),quote:str3(quote?.kicker,120)===null||str3(quote?.text)===null?null:clean({kicker:str3(quote?.kicker,120),tag:str3(quote?.tag,40),text:str3(quote?.text)}),jump:str3(jump?.title,300)===null||str3(jump?.go,60)===null?null:clean({title:str3(jump?.title,300),go:str3(jump?.go,60)})})}function routineOf(value){let o=obj(value),title=str3(o?.title,300),steps=listOf(o?.steps,r=>{let s=obj(r),t=str3(s?.title,300);return t===null?null:clean({title:t,body:str3(s?.body),source:str3(s?.source,200)})});return title===null||steps===null?null:clean({title:title,label:str3(o?.label,60),steps:steps})}function pickOf(value){let o=obj(value),title=str3(o?.title,300);if(o===null||title===null)return null;let rating=obj(o.rating),reviews=obj(o.reviews),why=obj(o.why),score=obj(why?.score),dose=obj(o.dose),ingredients=obj(o.ingredients),reviewItems=listOf(reviews?.items,r=>{let v=obj(r),stars=v?.stars,text2=str3(v?.text),by=str3(v?.by,80);return typeof stars!="number"||!Number.isFinite(stars)||stars<1||stars>5||text2===null||by===null?null:clean({stars:Math.round(stars),text:text2,by:by})},5),whyRows=listOf(why?.rows,r=>{let v=obj(r),chip=str3(v?.chip,40),t=str3(v?.title,300);return chip===null||t===null?null:clean({chip:chip,kind:kindOf(v?.kind),title:t,body:str3(v?.body)})}),stats=listOf(dose?.stats,r=>{let v=obj(r),val=str3(v?.value,40),label=str3(v?.label,120);return val===null||label===null?null:clean({value:val,label:label})},6),ingredientItems=words(ingredients?.items,12,80);return clean({title:title,productId:idOf2(o.productId),partnerSku:str3(o.partnerSku,200),rating:str3(rating?.value,20)===null?null:clean({value:str3(rating?.value,20),label:str3(rating?.label,120)}),line:str3(o.line),reviews:str3(reviews?.label,200)===null||reviewItems===null?null:clean({label:str3(reviews?.label,200),items:reviewItems}),checkoutLine:str3(o.checkoutLine,300),why:str3(why?.title,200)===null||whyRows===null?null:clean({title:str3(why?.title,200),rows:whyRows,score:str3(score?.text,200)===null||str3(score?.value,20)===null?null:clean({text:str3(score?.text,200),value:str3(score?.value,20)})}),dose:str3(dose?.title,200)===null||stats===null?null:clean({title:str3(dose?.title,200),stats:stats,note:str3(dose?.note)}),ingredients:ingredientItems===null?null:clean({label:str3(ingredients?.label,200),items:ingredientItems}),proof:str3(o.proof,300),trust:listOf(o.trust,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str3(v?.label,120);return icon===null||label===null?null:clean({icon:icon,label:label})},6),more:str3(o.more,120),fine:str3(o.fine),checkin:str3(o.checkin,200)})}function signsOf(value){let o=obj(value),title=str3(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),t=str3(v?.title,300),body=str3(v?.body);return t===null||body===null?null:clean({title:t,body:body,urgent:v?.urgent===true?true:null})});return title===null||items===null?null:clean({title:title,items:items})}function checkupOf(value){let o=obj(value),title=str3(o?.title,200),questions=words(o?.questions,12,300),add=str3(o?.add,80),added=str3(o?.added,80);return title===null||questions===null||add===null||added===null?null:clean({title:title,questions:questions,add:add,added:added})}function extrasOf(value){let o=obj(value),title=str3(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),key=str3(v?.key,REF_MAX3),t=str3(v?.title,300),action=str3(v?.action,80),added=str3(v?.added,80);return key===null||t===null||action===null||added===null?null:clean({key:key,title:t,body:str3(v?.body),price:str3(v?.price,40),was:str3(v?.was,40),tag:str3(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added})},6);return title===null||items===null?null:clean({title:title,items:items})}function healthPlanFocusDesignFromWire(raw){let o=obj(raw),title=str3(o?.title,300),pick2=pickOf(o?.pick);if(o===null||title===null||pick2===null)return null;let byline=obj(o.byline);return clean({eyebrow:str3(o.eyebrow,120),title:title,subtitle:str3(o.subtitle,300),headImageUrl:imageOf(o.headImageUrl),byline:str3(byline?.name,120)===null?null:clean({name:str3(byline?.name,120),role:str3(byline?.role,120),imageUrl:imageOf(byline?.imageUrl)}),focus:focusOf(o.focus),routine:routineOf(o.routine),pick:pick2,signs:signsOf(o.signs),checkup:checkupOf(o.checkup),extras:extrasOf(o.extras),fine:str3(o.fine),checkoutRows:listOf(o.checkoutRows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str3(v?.label,60),val=str3(v?.value,200);return icon===null||label===null||val===null?null:clean({icon:icon,label:label,value:val})},6)})}function healthPlanPageFromWire(raw,petRef){let o=obj(raw);if(o===null||!("page"in o))return null;let pet=obj(o.pet),sex=pet?.sex;/* @__PURE__ */
|
|
111
|
+
return Object.freeze({petRef:str3(o.pet_ref,REF_MAX3)??petRef,pet:/* @__PURE__ */Object.freeze({name:str3(pet?.name,120),species:str3(pet?.species,60),sex:sex==="female"||sex==="male"?sex:null,breed:str3(pet?.breed,120),weightKg:weightOf(pet?.weight_kg),weightLb:weightOf(pet?.weight_lb)}),checkout:o.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(o.page),vetReviewed:o.vet_reviewed===true,trackingTextsEnabled:o.tracking_texts_enabled===true})}function healthPlanCheckoutSessionFromWire(raw){let o=obj(raw),checkoutId=idOf2(o?.checkout_id),url=str3(o?.url,4096);return checkoutId===null||url===null||!/^https:\/\/[^\s/][^\s]*$/i.test(url)?null:/* @__PURE__ */Object.freeze({checkoutId:checkoutId,url:url})}var STATUSES=/* @__PURE__ */new Set(["pending","paid","expired","failed"]);function healthPlanCheckoutStateFromWire(raw){let o=obj(raw),status=o?.status,purchase=o?.purchase;if(typeof status!="string"||!STATUSES.has(status)||purchase!=="one_box"&&purchase!=="subscription")return null;let order=healthPlanOneBoxOrderFromWire(o?.order),list=Array.isArray(o?.orders)?(o?.orders).map(healthPlanOneBoxOrderFromWire).filter(x=>x!==null):[];/* @__PURE__ */
|
|
112
|
+
return Object.freeze({status:status,purchase:purchase,order:order??list[0]??null,orders:/* @__PURE__ */Object.freeze(list.length>0?list:order===null?[]:[order]),subscription:healthPlanSubscriptionFromWire(o?.subscription)})}function invalid3(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed3(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the expected shape`})}function disposed3(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef3=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX3,absoluteUrl=value=>typeof value=="string"&&value.length<=2048&&/^https?:\/\/[^\s/][^\s]*$/i.test(value);function base2(petRef){return`/widget/v1/pets/${encodeURIComponent(petRef)}/plan`}async function readPage(funnel,petRef,opts){if(!validRef3(petRef))return err(invalid3("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.page.read",{method:"GET",path:`${base2(petRef)}/page`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let page=healthPlanPageFromWire(res.value,petRef);return page===null?err(malformed3("healthPlan.page.read")):ok(page)}var readers=/* @__PURE__ */new WeakMap;function createHealthPlanPageReader(runtime){let known=readers.get(runtime);if(known!==void 0)return known;let reader=makeHealthPlanPageReader(runtime);return readers.set(runtime,reader),reader}function makeHealthPlanPageReader(runtime){return{getPage:(petRef,opts)=>{if(runtime.isDisposed)return Promise.resolve(err(disposed3("getPage")));let{services:services}=runtime.registry,funnel=withPlainNotFound(createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}));return readPage(funnel,petRef,opts)}}}function createHealthPlanPageRepositoryOver(deps){let funnel=withPlainNotFound(deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}));return{getPage:(petRef,opts)=>readPage(funnel,petRef,opts),async startCheckout(petRef,body,idempotencyKey){if(!validRef3(petRef))return err(invalid3("petRef must be 1..128 characters"));if(!validRef3(body.productId))return err(invalid3("productId must be 1..128 characters"));if(body.purchase!=="one_box"&&body.purchase!=="subscription")return err(invalid3("purchase must be one_box or subscription"));if(body.intervalDays!==void 0&&(!Number.isInteger(body.intervalDays)||body.intervalDays<=0))return err(invalid3("intervalDays must be a positive whole number"));if(!absoluteUrl(body.successUrl)||!absoluteUrl(body.cancelUrl))return err(invalid3("successUrl and cancelUrl must be absolute http(s) URLs"));let res=await funnel.send("healthPlan.checkout.start",{method:"POST",path:`${base2(petRef)}/checkout`,body:{product_id:body.productId,purchase:body.purchase,...body.purchase==="subscription"&&body.intervalDays!==void 0?{interval_days:body.intervalDays}:{},success_url:body.successUrl,cancel_url:body.cancelUrl}},{idempotent:true,idempotencyKey:`hp-checkout:${idempotencyKey}`});if(!res.ok)return err(res.error);let session=healthPlanCheckoutSessionFromWire(res.value);return session===null?err(malformed3("healthPlan.checkout.start")):ok(session)},async startCartCheckout(petRef,body,idempotencyKey){if(!validRef3(petRef))return err(invalid3("petRef must be 1..128 characters"));let items=body.items;if(!Array.isArray(items)||items.length<1||items.length>CART_MAX)return err(invalid3("items must hold 1..10 lines"));let seen=/* @__PURE__ */new Set;for(let it of items){if(!validRef3(it.productId)||seen.has(it.productId))return err(invalid3("each item needs a productId, once per cart"));if(seen.add(it.productId),it.purchase!=="one_box"&&it.purchase!=="subscription")return err(invalid3("purchase must be one_box or subscription"));let q=it.quantity??1;if(!Number.isInteger(q)||q<1||q>CART_MAX)return err(invalid3("quantity must be a whole number 1..10"));if(it.purchase==="subscription"&&q!==1)return err(invalid3("a subscription line is quantity 1"));if(it.intervalDays!==void 0&&(!Number.isInteger(it.intervalDays)||it.intervalDays<=0))return err(invalid3("intervalDays must be a positive whole number"))}if(!absoluteUrl(body.successUrl)||!absoluteUrl(body.cancelUrl))return err(invalid3("successUrl and cancelUrl must be absolute http(s) URLs"));let res=await funnel.send("healthPlan.checkout.start",{method:"POST",path:`${base2(petRef)}/checkout`,body:{items:items.map(it=>({product_id:it.productId,purchase:it.purchase,...it.purchase==="subscription"&&it.intervalDays!==void 0?{interval_days:it.intervalDays}:{},quantity:it.quantity??1})),success_url:body.successUrl,cancel_url:body.cancelUrl}},{idempotent:true,idempotencyKey:`hp-checkout:${idempotencyKey}`});if(!res.ok)return err(res.error);let session=healthPlanCheckoutSessionFromWire(res.value);return session===null?err(malformed3("healthPlan.checkout.start")):ok(session)},async getCheckout(petRef,checkoutId){if(!validRef3(petRef))return err(invalid3("petRef must be 1..128 characters"));if(!validRef3(checkoutId))return err(invalid3("checkoutId must be 1..128 characters"));let res=await funnel.send("healthPlan.checkout.read",{method:"GET",path:`${base2(petRef)}/checkout/${encodeURIComponent(checkoutId)}`});if(!res.ok)return err(res.error);let state=healthPlanCheckoutStateFromWire(res.value);return state===null?err(malformed3("healthPlan.checkout.read")):ok(state)}}}function createHealthPlanPageRepository(runtime){let over=()=>{let{services:services}=runtime.registry;return createHealthPlanPageRepositoryOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})};return{getPage:(petRef,opts)=>runtime.isDisposed?Promise.resolve(err(disposed3("getPage"))):over().getPage(petRef,opts),startCheckout:(petRef,body,key)=>runtime.isDisposed?Promise.resolve(err(disposed3("startCheckout"))):over().startCheckout(petRef,body,key),startCartCheckout:(petRef,body,key)=>runtime.isDisposed?Promise.resolve(err(disposed3("startCartCheckout"))):over().startCartCheckout?.(petRef,body,key)??Promise.resolve(err(disposed3("startCartCheckout"))),getCheckout:(petRef,id)=>runtime.isDisposed?Promise.resolve(err(disposed3("getCheckout"))):over().getCheckout(petRef,id)}}var HEALTH_PLAN_PAGE_SHARE_MS=5e3,sharedReads=/* @__PURE__ */new WeakMap;function readShared(reader,userRef,petRef,fresh){let reads=sharedReads.get(reader);reads===void 0&&(reads=/* @__PURE__ */new Map,sharedReads.set(reader,reads));let map=reads,key=`${userRef}\0${petRef}`,hit=map.get(key);if(!fresh&&hit!==void 0&&(hit.at===null||Date.now()-hit.at<HEALTH_PLAN_PAGE_SHARE_MS))return hit.promise;let entry={at:null,promise:reader.getPage(petRef).then(res=>(map.get(key)===entry&&(res.ok||isNotFoundError(res.error)?entry.at=Date.now():map.delete(key)),res))};return map.set(key,entry),entry.promise}function useHealthPlanPageRepository(){let{runtime:runtime}=useEverfurContext();return useMemo(()=>createHealthPlanPageRepository(runtime),[runtime])}function useHealthPlanPage(options){let{userRef:userRef,runtime:runtime}=useEverfurContext(),own=useMemo(()=>createHealthPlanPageReader(runtime),[runtime]),hostRepository=options.repository,repository=hostRepository??own,getPage=useCallback((pet,fresh)=>hostRepository!==void 0||userRef==null?repository.getPage(pet):readShared(own,userRef,pet,fresh),[hostRepository,repository,own,userRef]),{petRef:petRef}=options,enabled=options.enabled!==false&&userRef!=null&&petRef!==null,[state,setState]=useState({phase:"idle",petRef:null,page:null,error:null}),epoch=useRef(0),quiet=useRef(0),read=useCallback(async fresh=>{let mine=++epoch.current;if(!enabled||petRef===null){setState(prev=>prev.phase==="idle"&&prev.petRef===null?prev:{phase:"idle",petRef:null,page:null,error:null});return}setState(prev=>({phase:"loading",petRef:petRef,page:prev.petRef===petRef?prev.page:null,error:null}));let res=await getPage(petRef,fresh);mine===epoch.current&&(res.ok?setState({phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}):isNotFoundError(res.error)?setState({phase:"ready",petRef:petRef,page:null,error:null,missing:true,readyAt:Date.now()}):setState({phase:"failed",petRef:petRef,page:null,error:res.error}))},[enabled,petRef,getPage]),load=useCallback(()=>read(true),[read]),ready=state.phase==="ready"&&state.petRef===petRef,revalidate=useCallback(async()=>{if(!enabled||petRef===null||!ready)return;let mine=epoch.current,seq=++quiet.current,res=await getPage(petRef,true);mine!==epoch.current||seq!==quiet.current||!res.ok||setState(prev=>prev.phase==="ready"&&prev.petRef===petRef?{phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}:prev)},[enabled,petRef,ready,getPage]);useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?state.readyAt??null:null,revalidate:()=>{revalidate()},refresh:()=>{ready?revalidate():load()}}),useEffect(()=>(read(false),()=>{epoch.current+=1}),[read]);let stale=enabled&&state.petRef!==petRef;return useMemo(()=>({phase:stale?"loading":state.phase,page:stale?null:state.page,error:stale?null:state.error,missing:!stale&&state.missing===true,refresh:load}),[stale,state,load])}var DEFAULT_PRESENTATION=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark"}),PRESENTATION_WIRE_NAMES=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button"}),FIELDS=Object.keys(PRESENTATION_WIRE_NAMES),PRESENTATION_LOCK="presentation",PRESENTATION_LOCK_PREFIX="presentation.";var ENUMS={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},BOOLS=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner"]);function parseField(field,value){if(value==null)return;let allowed=ENUMS[field];return allowed!==void 0?typeof value=="string"&&allowed.includes(value)?value:void 0:BOOLS.has(field)?typeof value=="boolean"?value:void 0:typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=3?value:void 0}function parsePresentation(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let source=raw,out={};for(let field of FIELDS){let wire=PRESENTATION_WIRE_NAMES[field],value=Object.prototype.hasOwnProperty.call(source,wire)?source[wire]:source[field],parsed=parseField(field,value);parsed!==void 0&&(out[field]=parsed)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function isPresentationFieldLocked(field,locked){if(locked==null)return false;let one=`${PRESENTATION_LOCK_PREFIX}${PRESENTATION_WIRE_NAMES[field]}`;for(let name of locked)if(name===PRESENTATION_LOCK||name===one)return true;return false}function resolvePresentation(input){let server=parsePresentation(input?.server??null)??{},client=parsePresentation(input?.client??null)??{},locked=input?.locked?[...input.locked]:null,out={};for(let field of FIELDS){let fromServer=server[field],fromClient=isPresentationFieldLocked(field,locked)?void 0:client[field];out[field]=fromClient??fromServer??DEFAULT_PRESENTATION[field]}/* @__PURE__ */
|
|
113
|
+
return Object.freeze(out)}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentation(client){return useEverfurPresentationState(client).presentation}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf(client);return useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX4=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX4,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str4=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str4(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str4(o.ref),name:name,dose:str4(o.dose),frequency:str4(o.frequency),startDate:str4(o.start_date),endDate:str4(o.end_date),notes:str4(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
|
|
114
|
+
return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str4(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str4(o.food_brand),foodType:str4(o.food_type),microchipId:str4(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str4(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str4(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str4(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str4(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str4(row.ref),conditionName:conditionName,diagnosedDate:str4(row.diagnosed_date),notes:str4(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid4(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid4(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid4(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid4(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid4("pet_ref must be a string");if(petRef.trim().length===0)return invalid4("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid4("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid4("profile must be an object");let checks=[checkString("pet_ref",petRef,PET_REF_MAX)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid4(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid4("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid4("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str5=v=>typeof v=="string"?v:null,num=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
|
|
115
|
+
return Object.freeze({petRef:str5(o.pet_ref)??petRef,name:str5(o.name),species:str5(o.species),breed:str5(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef=str5(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str5(o.pet_id),petRef:petRef,name:str5(o.name),species:str5(o.species),breed:str5(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str5(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
|
|
116
|
+
return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid5=validate(petRef,profile);if(invalid5!==null)return err(invalid5);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base3={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base3,signal:opts.signal}:base3);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"};deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap2=type.scaleCaps[tier];return cap2>0?cap2:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap2=tierMultiplier(type,tier);return createElement(Text$1,cap2===void 0?props:{maxFontSizeMultiplier:cap2,...props})}forwardRef(function(props,ref){return createElement(TextInput,{...props,...ref===null?{}:{ref:ref}})});var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
|
|
117
|
+
return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
|
|
118
|
+
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base3={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base3.disabled=d.disabled),/* @__PURE__ */Object.freeze(base3)}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}=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})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
119
|
+
return jsx(View,{style:[styles.offstate,style],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${capability}`,children:/* @__PURE__ */jsx(View,{style:styles.skeletonBar})})}function OffState({decision:decision,style:style}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
|
|
120
|
+
return jsx(View,{style:[styles.offstate,style],accessible:true,accessibilityRole:"text",accessibilityLabel:message,children:message.length>0?/* @__PURE__ */jsx(Text,{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return StyleSheet.create({offstate:{minHeight:MIN_OFFSTATE_HEIGHT,justifyContent:"center",paddingHorizontal:space.lg,paddingVertical:space.md,backgroundColor:color.surfaceCream,borderRadius:radius.md,borderWidth:StyleSheet.hairlineWidth,borderColor:color.brandBorder},offstateText:{...face(theme,"regular"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.normal),color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}})}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 HealthPlanCartBar(props){let{cart:cart,onCheckout:onCheckout,busy:busy=false,priceFormat:priceFormat,style:style}=guardHostProps(props,["onCheckout"]),theme=useEverfurTheme(),styles=useMemo(()=>makeStyles2(theme),[theme]),subtotal=formatHealthPlanPriceWith(cart.subtotal,cart.currency,priceFormat),disabled=cart.count===0||busy,telemetry=useHealthPlanTelemetry(),petRef=useHealthPlanBarPet(useHealthPlanCartDock()?.petRef);/* @__PURE__ */
|
|
121
|
+
return jsxs(View,{style:[styles.bar,style],accessibilityLabel:HEALTH_PLAN_TEMPLATES.cartLabel(theme.meta.displayName),children:[
|
|
122
|
+
/* @__PURE__ */jsxs(View,{style:styles.copy,children:[
|
|
123
|
+
/* @__PURE__ */jsxs(View,{style:styles.labelRow,children:[
|
|
124
|
+
/* @__PURE__ */jsx(Text,{style:styles.label,children:HEALTH_PLAN_TEMPLATES.cartLabel(theme.meta.displayName)}),cart.count>0?/* @__PURE__ */jsx(View,{style:styles.count,accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(Text,{tier:"badge",style:styles.countLabel,children:String(cart.count)})}):null]}),cart.count===0?/* @__PURE__ */jsx(Text,{style:styles.line,children:HEALTH_PLAN_COPY.cartEmpty}):subtotal===null?null:/* @__PURE__ */jsxs(Text,{style:styles.line,children:[HEALTH_PLAN_COPY.subtotal," ",subtotal]})]}),onCheckout===void 0?null:/* @__PURE__ */jsx(Pressable,{onPress:()=>{trackCheckoutStarted(telemetry,petRef,cart),onCheckout(cart.items)},disabled:disabled,accessibilityRole:"button",accessibilityLabel:HEALTH_PLAN_COPY.checkout,accessibilityState:{disabled:disabled,busy:busy},style:[styles.checkout,disabled?styles.dimmed:null],testID:"health-plan-checkout",children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles.checkoutLabel,children:HEALTH_PLAN_COPY.checkout})})]})}function makeStyles2(theme){let{color:color,radius:radius,space:space,type:type,slots:slots}=theme,ink=slots.cartBar?.textColor??color.text.onBrand,fill=slots.cartBar?.backgroundColor??color.brandInk,text2=(size,tint,weight)=>({...face(theme,weight),fontSize:size,lineHeight:Math.round(size*type.lineHeight.snug),color:tint});return StyleSheet.create({bar:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.md,paddingHorizontal:space.lg,paddingVertical:space.md,borderRadius:radius.lg,backgroundColor:color.brand,...slotBox(slots.cartBar)},copy:{flex:1,gap:2},labelRow:{flexDirection:"row",alignItems:"center",gap:space.sm},label:text2(type.size.body,ink,"bold"),count:{minWidth:22,height:22,paddingHorizontal:space.xs,borderRadius:radius.pill,alignItems:"center",justifyContent:"center",backgroundColor:ink},countLabel:text2(type.size.caption,fill,"bold"),line:text2(type.size.caption,ink,"regular"),checkout:{minHeight:44,paddingHorizontal:space.lg,borderRadius:radius.pill,alignItems:"center",justifyContent:"center",backgroundColor:ink},checkoutLabel:text2(type.size.body,fill,"bold"),dimmed:{opacity:.5}})}function healthPlanPetWords(name,sex){let n=name?.trim()??"",named=n===""?"your pet":n,Named=n===""?"Your pet":n;return{name:named,Name:Named,poss:"her",Poss:"Her",obj:"her"}}var cartRenewal=p=>p===null?"":`${p.productName} renews every ${p.intervalDays} days at ${p.box??""} until you cancel; skip or cancel anytime in the app.`,HEALTH_PLAN_NO_SHIP_DAY_COPY=/* @__PURE__ */Object.freeze({onceFine:"",cartFine:cartRenewal,startedWhat:()=>""});function healthPlanFocusCopyFor(pet){let w=healthPlanPetWords(pet.name),nameOf=p=>p.petName?.trim()||w.name,NameOf=p=>p.petName?.trim()||w.Name,copy=/* @__PURE__ */Object.freeze({jumpKicker:(p,subscribed)=>subscribed?`In ${w.poss} plan, every ${p.intervalDays} days`:p.offer?`${p.discountPercent}% off ${w.poss} first box`:p.intervalDays>0?`Ships every ${p.intervalDays} days`:copy.onceLine(p),optionsLabel:"How to buy",subscribe:"Subscribe",bestValue:"Best value",subscribeLine:p=>p.offer?`First box, then ${p.box??""}`:`${p.box??""} every ${p.intervalDays} days`,priceLine:p=>p.offer?`${p.discountPercent}% off the first box. Ships every ${p.intervalDays} days.`:p.intervalDays>0?`Ships every ${p.intervalDays} days.`:copy.onceOffer(p),once:"One box",onceLine:p=>p.onceDiscountPercent>0?`${p.onceDiscountPercent}% off, ships once`:"Ships once",buyOnce:p=>`Buy one box, ${p.once??p.box??""}`,subscribed:"Subscribed",subscribedLine:(p,next)=>next===null?`Every ${p.intervalDays} days`:`Every ${p.intervalDays} days · next box ${next}`,manage:"Manage",checkoutKicker:"Checkout",checkoutTitle:p=>`Checkout: ${p.productName}`,checkoutOffer:p=>`${p.discountPercent}% off your first box.`,shipsEvery:"Ships every",days:n=>`${n} days`,buyOnceOption:"Buy once",checkoutGo:(_p,subscribe,today)=>`${subscribe?"Subscribe":"Buy now"} · ${today} today`,renews:p=>`Renews every ${p.intervalDays} days at ${p.box??""} until you cancel; skip or cancel anytime in the app.`,onceFine:"One box, ships tomorrow.",onceOffer:p=>p.onceDiscountPercent>0?`${p.onceDiscountPercent}% off, ships once.`:"Ships once.",checkoutNote:"",close:"Close",startedTitle:p=>`${NameOf(p)}'s plan has started.`,orderedTitle:()=>"Order placed.",startedWhat:p=>`${p.productName} ships tomorrow.`,startedNote:"",startedSteps:"What happens next",tomorrow:"Tomorrow",firstBoxShips:`${w.Poss} first box ships.`,trackingComesByText:"Tracking comes by text.",checkin:q=>q===null?"A 2-week check-in by text.":`A 2-week check-in by text: ${q}`,refill:`A text 3 days before ${w.poss} next box. Reply SKIP to skip it.`,nextBoxShips:p=>`${w.Poss} next box ships, ${p.box??""}.`,startedDone:`Back to ${w.poss} plan`,manageKicker:"Your subscription",manageTitle:p=>`Manage ${p.productName}`,skip:"Skip the next box",cancel:"Cancel subscription",skipped:(_p,next)=>next===null?"Skipped.":`Skipped. ${w.Poss} next box ships ${next}.`,cancelled:p=>`${p.productName} is cancelled. Restart it from ${w.poss} plan anytime.`,orders:"Orders",startedHeader:"Subscribed",placedHeader:"Order placed",cartCheckoutTitle:"Checkout",orderNote:"",cartLabel:n=>n>0?`Cart, ${n} item${n>1?"s":""}`:"Cart, empty",addToCart:price=>`Add to cart · ${price}`,viewCart:"View cart",addedToCart:(p,subscription)=>`${p.productName} is in your cart${subscription?", as a subscription":""}.`,removedFromCart:name=>`${name} is out of your cart.`,cartTitle:"Cart",cartEmptyTitle:"Your cart is empty",cartEmptyBody:p=>`${NameOf(p)}'s plan pick lands here when you add it.`,seeOrders:`See ${w.poss} orders`,quantityLabel:name=>`How many: ${name}`,fewer:"One fewer",more:"One more",remove:"Remove",cartSubLine:p=>p.offer?`First box ${p.discountPercent}% off, then ${p.box??""} every ${p.intervalDays} days`:`Every ${p.intervalDays} days`,cartOnceLine:(p,subscribed)=>subscribed?`An extra box. ${w.Poss} plan keeps shipping.`:p.onceDiscountPercent>0?`One box, ${p.onceDiscountPercent}% off`:"One box",cartModeLabel:name=>`How to buy ${name}`,cartModeSubscribe:p=>p.offer?`Subscribe, ${p.discountPercent}% off the first box`:"Subscribe",cartModeOnce:p=>p.onceDiscountPercent>0?`One box, ${p.onceDiscountPercent}% off`:"One box",subtotal:"Subtotal",shipping:"Shipping",shippingValue:"",shippingTag:"",total:"Total",dueToday:"Due today",thenRenews:p=>`Then ${p.productName}`,renewsEvery:p=>`${p.box??""} every ${p.intervalDays} days`,checkoutCart:total=>`Checkout · ${total}`,cartOneAtATime:"",cartSubscriptionApart:"",cartItemSubscription:p=>`Subscription, every ${p.intervalDays} days`,cartItemQuantity:n=>`Qty ${n}`,placeOrder:(total,subscribe)=>`${subscribe?"Place order and subscribe":"Place order"} · ${total}`,cartFine:p=>`${p===null?"":`${cartRenewal(p)} `}Ships tomorrow.`,placedSteps:"What's coming",placedShips:"It ships.",placedArrives:"It arrives at home.",viewOrder:"View order",herSubscription:`${w.Poss} subscription`,nextBox:day=>`Next box ${day}`,everyDays:n=>`Every ${n} days`,ordersHeading:afterSubscription=>afterSubscription?"Orders":`${w.Poss} orders`,ordersFine:"",ordersEmptyTitle:"No orders yet",ordersEmptyBody:p=>`The boxes from ${nameOf(p)}'s plan show up here.`,moreOrders:"",orderSteps:["Ordered","Shipped","Out for delivery","Delivered"],subscriptionBox:"Subscription box",orderTitle:n=>n===null?"Order":`Order ${n}`,arrivesBy:day=>`Arrives by ${day}`,deliveredOn:day=>`Delivered ${day}`,expected:day=>`Expected ${day}`,tracking:"Tracking",trackingByText:"The tracking number comes by text when it ships.",trackOn:carrier=>`Track on ${carrier}`,trackLink:"",inThisOrder:"In this order",orderItemLine:(n,box2)=>`Qty ${n}${box2?" · subscription box":""}`,paidWith:"Paid with",buyAgain:"Buy again",orderHelp:"Get help with this order",addWeightTitle:`Add ${w.poss} weight to size ${w.poss} dose`,addWeightBody:`From a home scale or ${w.poss} last vet visit.`,connectRecordsTitle:`Connect ${w.poss} vet records`,connectRecordsBody:`${w.Poss} weight, visits and labs make ${w.poss} plan sharper.`,weightKicker:`${w.Poss} weight`,weightTitle:p=>`Add ${nameOf(p)}'s weight`,weightBody:`From a home scale or ${w.poss} last vet visit. ${w.Poss} plan uses it to size ${w.poss} dose.`,weightField:`${w.Poss} weight`,weightUnit:"lb",weightUnitKg:"kg",weightErrorKg:"Enter your pet’s weight",weightError:`Enter ${w.poss} weight in pounds, like 14.1.`,weightSave:`Save ${w.poss} weight`,weightSaved:lb=>`Saved: ${lb} lb. ${w.Poss} dose is sized for ${w.obj}.`,weightSavedKg:kg=>`Saved: ${kg} kg. ${w.Poss} dose is sized for ${w.obj}.`,checkoutFailed:"That didn't go through. Please try again."});return copy}var HEALTH_PLAN_FOCUS_COPY=healthPlanFocusCopyFor({});function formatHealthPlanDay(iso,locale){if(iso===null||!/^\d{4}-\d{2}-\d{2}$/.test(iso))return null;let d=/* @__PURE__ */new Date(`${iso}T00:00:00Z`);if(Number.isNaN(d.getTime()))return null;try{return new Intl.DateTimeFormat(locale??"en-US",{month:"short",day:"numeric",timeZone:"UTC"}).format(d)}catch{return iso}}function useHealthPlanSubscriptionRepository(){let{runtime:runtime}=useEverfurContext();return useMemo(()=>createHealthPlanSubscriptionRepository(runtime),[runtime])}function useHealthPlanSubscription(options){let{userRef:userRef}=useEverfurContext(),own=useHealthPlanSubscriptionRepository(),repository=options.repository??own,enabled=options.enabled!==false&&userRef!==null&&options.petRef!==null&&options.productId!==null,{petRef:petRef,productId:productId}=options,[phase,setPhase]=useState("idle"),[quote,setQuote]=useState(null),[subscription,setSubscription]=useState(null),[busy,setBusy]=useState(false),[error,setError]=useState(null),[readyAt,setReadyAt]=useState(null),epoch=useRef(0),writes=useRef(0),quiet=useRef(0),busyRef=useRef(false),refreshAfterWrite=useRef(false),revalidateRef=useRef(()=>Promise.resolve()),load=useCallback(async()=>{let mine=++epoch.current;if(refreshAfterWrite.current=false,setReadyAt(null),!enabled||petRef===null||productId===null){setPhase("idle"),setQuote(null),setSubscription(null);return}setPhase("loading");let res=await repository.quote(petRef,productId);if(mine===epoch.current){if(!res.ok){setQuote(null),setSubscription(null),setError(res.error),setPhase(isHealthPlanSubscriptionUnavailable(res.error)?"unavailable":"failed");return}setError(null),setQuote(res.value),setSubscription(res.value.subscription),setPhase("ready"),setReadyAt(Date.now())}},[enabled,petRef,productId,repository]),ready=enabled&&phase==="ready",revalidate=useCallback(async()=>{if(!ready||busyRef.current||petRef===null||productId===null)return;let mine=epoch.current,wrote=writes.current,seq=++quiet.current,res=await repository.quote(petRef,productId);mine!==epoch.current||wrote!==writes.current||seq!==quiet.current||busyRef.current||!res.ok||(setQuote(res.value),setSubscription(res.value.subscription),setReadyAt(Date.now()))},[ready,petRef,productId,repository]);revalidateRef.current=revalidate;let refreshOnKey=()=>{if(!ready){load();return}if(busyRef.current){refreshAfterWrite.current=true;return}revalidate()};useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?readyAt:null,revalidate:()=>{revalidate()},refresh:refreshOnKey});let settleWrite=useCallback(()=>{refreshAfterWrite.current&&(refreshAfterWrite.current=false,revalidateRef.current())},[]);useEffect(()=>(load(),()=>{epoch.current+=1}),[load]);let write=useCallback(async run=>{let mine=epoch.current;writes.current+=1,busyRef.current=true,setBusy(true);let res=await run();return busyRef.current=false,mine!==epoch.current?res:(setBusy(false),res.ok?(setError(null),setSubscription(res.value),settleWrite(),res):(setError(res.error),isHealthPlanSubscriptionUnavailable(res.error)?setPhase("unavailable"):settleWrite(),res))},[settleWrite]),buy=useCallback(async tapKey=>{let mine=epoch.current;writes.current+=1,busyRef.current=true,setBusy(true);let res=await repository.buyOneBox(petRef,productId,tapKey);return busyRef.current=false,mine!==epoch.current?res:(setBusy(false),res.ok?(setError(null),load(),res):(setError(res.error),isHealthPlanSubscriptionUnavailable(res.error)?setPhase("unavailable"):settleWrite(),res))},[repository,petRef,productId,load,settleWrite]);return useMemo(()=>{let p=petRef,sid=subscription?.subscriptionId??"",none=()=>Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"the subscription quote is not ready"})));return{phase:phase,quote:quote,subscription:subscription,busy:busy,error:error,subscribe:n=>ready&&productId!==null?write(()=>repository.create(p,productId,n)):none(),changeInterval:n=>ready&&sid!==""?write(()=>repository.changeInterval(p,sid,n)):none(),skip:()=>ready&&sid!==""?write(()=>repository.skip(p,sid)):none(),cancel:()=>ready&&sid!==""?write(()=>repository.cancel(p,sid)):none(),restart:n=>ready&&sid!==""?write(()=>repository.restart(p,sid,n)):none(),buyOneBox:k=>ready&&productId!==null?buy(k):none(),refresh:load}},[phase,quote,subscription,busy,error,ready,petRef,productId,repository,write,buy,load])}var HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function Cross({size:size,color:color,strokeWidth:strokeWidth,rotate:rotate}){let w=stroke(size,strokeWidth),length=size*.78;/* @__PURE__ */
|
|
125
|
+
return jsxs(View,{style:[box(size),{transform:[{rotate:rotate}]}],...HIDDEN,children:[
|
|
126
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",width:length,height:w,borderRadius:w,backgroundColor:color}}),
|
|
127
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",width:w,height:length,borderRadius:w,backgroundColor:color}})]})}function PlusGlyph(props){/* @__PURE__ */
|
|
128
|
+
return jsx(Cross,{...props,rotate:"0deg"})}function CloseGlyph(props){/* @__PURE__ */
|
|
129
|
+
return jsx(Cross,{...props,rotate:"45deg"})}function CheckGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
|
|
130
|
+
return jsx(View,{style:box(size),...HIDDEN,children:/* @__PURE__ */jsx(View,{style:{width:size*.36,height:size*.66,marginTop:-size*.14,borderBottomWidth:w,borderRightWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})})}var CHEVRON_POSE={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:size,color:color,strokeWidth:strokeWidth,direction:direction}){let w=stroke(size,strokeWidth),side=size*.46,pose=CHEVRON_POSE[direction];/* @__PURE__ */
|
|
131
|
+
return jsx(View,{style:box(size),...HIDDEN,children:/* @__PURE__ */jsx(View,{style:{width:side,height:side,borderRightWidth:w,borderBottomWidth:w,borderColor:color,marginTop:side*pose.marginTop,marginLeft:side*pose.marginLeft,transform:[{rotate:pose.rotate}]}})})}function FocusIcon({name:name,size:size=18,color:color}){let glyph;switch(name){case"check":glyph=/* @__PURE__ */jsx(CheckGlyph,{size:size,color:color});break;case"plus":glyph=/* @__PURE__ */jsx(PlusGlyph,{size:size,color:color});break;case"x":glyph=/* @__PURE__ */jsx(CloseGlyph,{size:size,color:color});break;case"chev":case"arrow":glyph=/* @__PURE__ */jsx(ChevronGlyph,{size:size,color:color,direction:"right"});break;case"minus":glyph=/* @__PURE__ */jsx(View,{style:{width:size,height:size,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */jsx(View,{style:{width:Math.round(size*.6),height:2,borderRadius:1,backgroundColor:color}})});break;case"cart":{let w=Math.max(1.5,Math.round(size*1.8/24*2)/2),at=n=>Math.round(size*n);glyph=/* @__PURE__ */jsxs(View,{style:{width:size,height:size},children:[
|
|
132
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",left:at(.1),top:at(.17),width:at(.17),height:w,borderRadius:w,backgroundColor:color}}),
|
|
133
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",left:at(.25),top:at(.17),width:w,height:at(.2),borderRadius:w,backgroundColor:color}}),
|
|
134
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",left:at(.25),top:at(.3),width:at(.63),height:at(.36),borderWidth:w,borderColor:color,borderRadius:at(.06),borderTopLeftRadius:0}}),
|
|
135
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",left:at(.33),top:at(.74),width:at(.16),height:at(.16),borderWidth:w,borderColor:color,borderRadius:size}}),
|
|
136
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",left:at(.66),top:at(.74),width:at(.16),height:at(.16),borderWidth:w,borderColor:color,borderRadius:size}})]});break}case"box":{let w=Math.max(1.5,Math.round(size*1.7/24*2)/2),at=n=>Math.round(size*n);glyph=/* @__PURE__ */jsxs(View,{style:{width:size,height:size},children:[
|
|
137
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",left:at(.16),top:at(.2),width:at(.68),height:at(.62),borderWidth:w,borderColor:color,borderRadius:at(.08)}}),
|
|
138
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",left:at(.16),top:at(.4),width:at(.68),height:w,backgroundColor:color}}),
|
|
139
|
+
/* @__PURE__ */jsx(View,{style:{position:"absolute",left:at(.5)-w/2,top:at(.2),width:w,height:at(.2),backgroundColor:color}})]});break}case"alert":glyph=/* @__PURE__ */jsx(View,{style:{width:size,height:size,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */jsx(View,{style:{width:Math.round(size*.5),height:Math.round(size*.5),borderRadius:size,backgroundColor:color}})});break;default:glyph=/* @__PURE__ */jsx(View,{style:{width:size,height:size,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */jsx(View,{style:{width:Math.round(size*.55),height:Math.round(size*.55),borderRadius:4,borderWidth:2,borderColor:color}})})}/* @__PURE__ */
|
|
140
|
+
return jsx(View,{accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:`health-plan-icon-${name}`,children:glyph})}function healthPlanPossessive(pet){if(pet.sex==="female")return"her";if(pet.sex==="male")return"his";let name=pet.name?.trim();return name?`${name}'s`:null}var HEALTH_PLAN_FOCUS_RN_COPY=/* @__PURE__ */Object.freeze({...HEALTH_PLAN_FOCUS_COPY,firstBoxShips:"Her first box ships.",placedShips:"It ships.",trackingByText:"",moreOrders:"Load more",checkoutFailed:"That didn't go through. Please try again.",weightErrorKg:"",weightSavedKg:()=>"",back:"Back"}),cap=s=>s===""?s:`${s.charAt(0).toUpperCase()}${s.slice(1)}`;function healthPlanPetCopy(pet){let name=pet.name?.trim()??"",her=healthPlanPossessive(pet)??"your pet's",Her=cap(her),them=pet.sex==="female"?"her":pet.sex==="male"?"him":name!==""?name:"your pet",base3=HEALTH_PLAN_FOCUS_COPY;return{jumpKicker:(p,subscribed)=>subscribed?`In ${her} plan, every ${p.intervalDays} days`:p.offer?`${p.discountPercent}% off ${her} first box`:base3.jumpKicker(p,false),firstBoxShips:pet.trackingTexts===true?`${Her} first box ships. Tracking comes by text.`:`${Her} first box ships.`,placedShips:pet.trackingTexts===true?base3.placedShips:HEALTH_PLAN_FOCUS_RN_COPY.placedShips,trackingByText:pet.trackingTexts===true?base3.trackingByText:"",refill:`A text 3 days before ${her} next box. Reply SKIP to skip it.`,nextBoxShips:p=>`${Her} next box ships, ${p.box??""}.`,startedDone:`Back to ${her} plan`,skipped:(_p,next)=>next===null?"Skipped.":`Skipped. ${Her} next box ships ${next}.`,cancelled:p=>`${p.productName} is cancelled. Restart it from ${her} plan anytime.`,seeOrders:`See ${her} orders`,cartOnceLine:(p,subscribed)=>subscribed?`An extra box. ${Her} plan keeps shipping.`:base3.cartOnceLine(p,false),herSubscription:`${Her} subscription`,ordersHeading:afterSubscription=>afterSubscription?"Orders":`${Her} orders`,addWeightTitle:`Add ${her} weight to size ${her} dose`,addWeightBody:`From a home scale or ${her} last vet visit.`,connectRecordsTitle:`Connect ${her} vet records`,connectRecordsBody:`${Her} weight, visits and labs make ${her} plan sharper.`,weightKicker:`${Her} weight`,weightBody:`From a home scale or ${her} last vet visit. ${Her} plan uses it to size ${her} dose.`,weightField:`${Her} weight`,weightError:`Enter ${her} weight in pounds, like 14.1.`,weightSave:`Save ${her} weight`,weightSaved:lb=>`Saved: ${lb} lb. ${Her} dose is sized for ${them}.`}}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 int2=Math.trunc(n)>>>0,a=int2>>>24&255;return{r:int2>>>16&255,g:int2>>>8&255,b:int2&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 rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds){let worst=ink=>grounds.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}var PUSH_STEP=.05;function pushToContrast(color,grounds,pole,target){let first=grounds[0];if(first===void 0)return pole;let reads=candidate=>grounds.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix(from.r,to.r),mix(from.g,to.g),mix(from.b,to.b));if(reads(candidate))return candidate}return pole}var RAPH_V3_LIGHT=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),cache=/* @__PURE__ */new WeakMap;function v3Palette(theme){let hit=cache.get(theme);if(hit!==void 0)return hit;let c=theme.color,dark=theme.brightness==="dark",neutrals=dark?{dark:dark,ink:c.text.primary,ink2:c.text.secondary,ink3:c.text.muted,paper:c.background,card:c.surface,line:c.borderRingCream,tile:c.surfaceSubtle,shadow:c.shadow,riskBg:c.badgeBgCritical,riskInk:c.danger,riskDot:c.danger,clearBg:c.badgeBgPositive,clearInk:c.success,clearDot:c.success,watchDot:c.warningStrong}:{dark:dark,...RAPH_V3_LIGHT},textOn=(ink,grounds)=>pushToContrast(ink,grounds,poleForGrounds(grounds),V3_TEXT_CONTRAST),labelOn=(ink,fill)=>contrastRatio(ink,fill)>=V3_TEXT_CONTRAST?ink:legibleOn(fill,V3_TEXT_CONTRAST),badgeGrounds=[neutrals.card,neutrals.paper].map(under=>flattenOnto(c.brandSoft,under)??under),brand={primary:c.primary,onPrimary:labelOn(c.onPrimary,c.primary),accent:c.accent,onAccent:labelOn(c.onAccent,c.accent),link:textOn(c.linkInk,[neutrals.card,neutrals.paper,neutrals.tile]),badge:c.brandSoft,onBadge:textOn(c.brandInk,badgeGrounds)},palette=/* @__PURE__ */Object.freeze({...neutrals,...brand});return cache.set(theme,palette),palette}var V3_TEXT_CONTRAST=4.5;function focusPalette(theme){let c=theme.color;if(theme.brightness==="dark")return{ink:c.text.primary,ink2:c.text.secondary,ink3:c.text.muted,paper:c.surfaceSubtle,tile:c.badgeBgNeutral,line:c.brandBorder,card:c.surface,teal:c.brandInk,cyan:c.brandSofter,yellow:c.accent,riskDot:c.errorRed,riskBg:c.badgeBgCritical,riskInk:c.text.primary,clearDot:c.success,clearBg:c.badgeBgPositive,clearInk:c.text.primary,star:c.accent,button:c.primary,onButton:c.onPrimary,jump:c.surfaceSubtle,onJump:c.text.primary,jumpSmall:c.accent,tints:{y:c.badgeBgCaution,c:c.brandSofter,g:c.badgeBgPositive,r:c.badgeBgCritical},scrim:"rgba(0,0,0,0.6)"};let v=v3Palette(theme);return{ink:v.ink,ink2:v.ink2,ink3:v.ink3,paper:v.paper,tile:v.tile,line:v.line,card:v.card,teal:c.brandInk,cyan:c.brandSofter,yellow:v.accent,riskDot:v.riskDot,riskBg:v.riskBg,riskInk:v.riskInk,clearDot:v.clearDot,clearBg:v.clearBg,clearInk:v.clearInk,star:v.watchDot,button:v.primary,onButton:v.onPrimary,jump:v.ink,onJump:v.card,jumpSmall:v.accent,tints:{y:"#FFE7A1",c:"#C8F4F8",g:"#DDEFC4",r:"#FFD8D6"},scrim:"rgba(38,37,35,0.45)"}}function makeFocusStyles(theme){let P=focusPalette(theme),{space:space}=theme,t=(size,ink,weight="regular",ratio=1.35)=>({...face(theme,weight),fontSize:size,lineHeight:Math.round(size*ratio),color:ink}),card={marginTop:14,padding:16,borderRadius:22,backgroundColor:P.card,shadowColor:"#262523",shadowOpacity:theme.brightness==="dark"?0:.06,shadowRadius:3,shadowOffset:{width:0,height:1},elevation:theme.brightness==="dark"?0:1};return{...StyleSheet.create({root:{gap:0,paddingHorizontal:space.lg,paddingBottom:space.xl},shrink:{flexShrink:1,minWidth:0},row:{flexDirection:"row",alignItems:"center",gap:space.sm},rowTop:{flexDirection:"row",alignItems:"flex-start",gap:space.sm},tools:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm,paddingTop:space.md},toolsEnd:{flexDirection:"row",alignItems:"center",gap:space.sm},toolButton:{minHeight:44,minWidth:44,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.xs,paddingHorizontal:space.sm,borderRadius:999,backgroundColor:P.tile},toolLabel:t(14,P.ink,"bold"),cartCount:{minWidth:18,height:18,borderRadius:9,paddingHorizontal:4,alignItems:"center",justifyContent:"center",backgroundColor:P.button},cartCountText:t(11,P.onButton,"bold",1.2),head:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.md,paddingTop:space.md},eyebrow:{...t(10.5,P.ink3,"mono"),textTransform:"uppercase",letterSpacing:.9},title:{...t(29,P.ink,"bold",1.06),...headingFace(theme,"bold")},subtitle:{...t(15,P.ink2),marginTop:6},headImage:{width:56,height:56,borderRadius:28,backgroundColor:P.paper},by:{flexDirection:"row",alignItems:"center",gap:space.sm,marginTop:space.md},byImage:{width:40,height:40,borderRadius:20,backgroundColor:P.paper},card:card,need:card,kickerRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:space.xs},mini:{...t(10.5,P.ink3,"mono"),textTransform:"uppercase",letterSpacing:.9},source:{height:24,paddingHorizontal:10,borderRadius:12,justifyContent:"center",backgroundColor:P.tile},sourceText:t(12,P.ink2,"medium",1.2),h3:{...t(19,P.ink,"bold",1.2),marginTop:space.sm},sectionTitle:{...t(19,P.ink,"bold",1.2),flexShrink:1},sectionHead:{flexDirection:"row",alignItems:"center",gap:space.sm,marginTop:14},n:{width:24,height:24,borderRadius:12,alignItems:"center",justifyContent:"center",backgroundColor:P.ink},nText:t(12.5,theme.brightness==="dark"?theme.color.surface:"#FFFFFF","bold",1.2),risk:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,marginTop:space.sm},dot:{width:8,height:8,borderRadius:4,marginTop:7,backgroundColor:P.riskDot},dotClear:{backgroundColor:P.clearDot},riskText:{...t(15,P.ink2,"regular",1.45),flexShrink:1},bold:face(theme,"bold"),odds:{marginTop:space.md,padding:space.md,borderRadius:14,backgroundColor:P.tints.y},oddsRow:{flexDirection:"row",alignItems:"center",flexWrap:"wrap",gap:space.sm,marginTop:space.xs},oddsFrom:{...t(28,P.ink3,"regular",1.1),...headingFace(theme,"regular"),textDecorationLine:"line-through"},oddsTo:{...t(28,P.ink,"bold",1.1),...headingFace(theme,"bold")},tag:{alignSelf:"flex-start",paddingHorizontal:8,paddingVertical:2,borderRadius:999,backgroundColor:P.ink},tagText:t(11,theme.brightness==="dark"?theme.color.surface:"#FFFFFF","bold",1.2),quote:{marginTop:space.md,padding:space.md,borderRadius:14,backgroundColor:P.paper,gap:space.xs},quoteText:{...t(14.5,P.ink,"regular",1.4),...headingFace(theme,"regular")},jump:{flexDirection:"row",alignItems:"center",gap:space.sm,marginTop:space.md,padding:space.md,borderRadius:14,backgroundColor:P.jump},jumpImage:{width:44,height:44,borderRadius:22,backgroundColor:P.paper},jumpSmall:t(13,P.jumpSmall,"medium",1.3),jumpStrong:t(15,P.onJump,"bold",1.3),jumpGo:t(13,P.onJump,"bold",1.3),tips:{gap:space.sm,paddingRight:space.lg},tip:{borderRadius:18,padding:space.lg,gap:space.xs,backgroundColor:P.tints.y},tipN:{...t(30,P.ink,"bold",1.1),...headingFace(theme,"bold")},tipStrong:t(17,P.ink,"bold",1.3),tipSmall:t(14.5,P.ink2,"regular",1.4),tipEm:{...t(10.5,P.teal,"mono"),textTransform:"uppercase",letterSpacing:.6},pickTop:{flexDirection:"row",alignItems:"flex-start",gap:space.md},pickImage:{width:76,height:76,borderRadius:14,backgroundColor:P.paper},h4:t(17,P.ink,"bold",1.3),stars:{...t(13.5,P.star,"bold",1.3)},starsLabel:t(13.5,P.ink3,"regular",1.3),line:t(14,P.ink2,"regular",1.4),reviews:{gap:space.sm,paddingRight:space.lg,marginTop:space.md},review:{borderRadius:16,padding:space.md,gap:space.xs,backgroundColor:P.paper},reviewText:t(14,P.ink,"regular",1.4),small:t(13,P.ink3,"regular",1.35),smallInk:t(13,P.ink2,"regular",1.35),why:{marginTop:space.md,padding:space.md,borderRadius:16,borderWidth:1.5,borderColor:P.ink,gap:space.sm},whyRow:{flexDirection:"row",alignItems:"flex-start",gap:space.sm},chip:{height:22,paddingHorizontal:8,borderRadius:11,justifyContent:"center",backgroundColor:P.tile},chipText:{...t(10.5,P.ink2,"mono",1.2),textTransform:"uppercase"},score:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm,paddingTop:space.sm,borderTopWidth:1,borderTopColor:P.line},scoreValue:{...t(21,P.ink,"mono",1.2)},dose:{marginTop:space.md,padding:space.md,borderRadius:16,backgroundColor:P.cyan,gap:space.sm},stats:{flexDirection:"row",gap:space.sm},stat:{flex:1,minWidth:0,padding:space.sm,borderRadius:12,backgroundColor:P.card,gap:2},statValue:t(21,P.ink,"mono",1.2),pills:{flexDirection:"row",flexWrap:"wrap",gap:space.xs,marginTop:space.md},pill:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,backgroundColor:P.tile},opts:{gap:space.sm,marginTop:space.md},opt:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm,padding:14,borderRadius:16,borderWidth:1.5,borderColor:"#DEDCD7"},optOn:{borderWidth:2.5,borderColor:P.ink},optTag:{alignSelf:"flex-start",paddingHorizontal:8,paddingVertical:2,borderRadius:999,backgroundColor:P.riskInk,marginBottom:4},optTagText:t(12,"#FFFFFF","bold",1.2),price:{alignItems:"flex-end",gap:2,flexShrink:0,maxWidth:"45%"},priceText:t(17,P.ink,"bold",1.2),strike:{...t(13,P.ink3,"regular",1.2),textDecorationLine:"line-through"},button:{minHeight:52,borderRadius:999,alignItems:"center",justifyContent:"center",paddingHorizontal:space.lg,backgroundColor:P.button,marginTop:space.md},buttonText:{...t(17,P.onButton,"bold",1.2),textAlign:"center"},buttonGhost:{minHeight:48,borderRadius:999,alignItems:"center",justifyContent:"center",paddingHorizontal:space.lg,borderWidth:2,borderColor:P.ink,marginTop:space.sm},buttonGhostText:{...t(15,P.ink,"bold",1.2),textAlign:"center"},disabled:{opacity:.5},trust:{flexDirection:"row",gap:space.sm,marginTop:space.md},trustItem:{flex:1,minWidth:0,alignItems:"center",gap:4},trustText:{...t(12.5,P.ink2,"regular",1.3),textAlign:"center"},on:{flexDirection:"row",alignItems:"center",gap:space.sm,marginTop:space.md,padding:space.md,borderRadius:16,backgroundColor:P.clearBg},link:{minHeight:44,justifyContent:"center",alignSelf:"flex-start"},linkText:{...t(15,P.teal,"bold",1.3),textDecorationLine:"underline"},fine:{...t(13,P.ink3,"regular",1.4),marginTop:space.sm},sign:{marginTop:space.sm,padding:space.md,borderRadius:16,borderWidth:1.5,borderColor:"#DEDCD7",gap:4},signUrgent:{backgroundColor:P.riskBg,borderColor:P.riskBg},signUrgentTitle:{color:P.riskInk},questions:{gap:space.xs,marginTop:space.sm},question:{...t(15,P.ink,"regular",1.4),flexShrink:1},add:{minHeight:48,borderRadius:24,borderWidth:2,borderColor:P.ink,alignItems:"center",justifyContent:"center",paddingHorizontal:space.lg,marginTop:space.md},addOn:{backgroundColor:P.clearBg,borderColor:P.clearInk},addText:t(15,P.ink,"bold",1.2),addOnText:{color:P.clearInk},askRow:{flexDirection:"row",alignItems:"center",gap:space.sm,marginTop:space.md,padding:space.md,borderRadius:16,backgroundColor:P.paper,minHeight:56},askIcon:{width:36,height:36,borderRadius:18,alignItems:"center",justifyContent:"center",backgroundColor:P.cyan},extra:{flexDirection:"row",alignItems:"center",gap:space.sm,marginTop:space.sm,padding:space.md,borderRadius:16,backgroundColor:P.card},extraGo:{minHeight:44,borderRadius:22,borderWidth:2,borderColor:P.ink,alignItems:"center",justifyContent:"center",paddingHorizontal:space.md},iconTile:{width:64,height:64,borderRadius:14,alignItems:"center",justifyContent:"center",backgroundColor:P.tile},pageFine:{...t(13,P.ink3,"regular",1.4),marginTop:space.lg},toast:{marginTop:space.sm,padding:space.md,borderRadius:14,backgroundColor:P.ink},toastText:t(14,theme.brightness==="dark"?theme.color.surface:"#FFFFFF","medium",1.35),notice:{marginTop:space.sm,padding:space.md,borderRadius:14,backgroundColor:P.riskBg},noticeText:t(14,P.riskInk,"medium",1.35),scrim:{flex:1,justifyContent:"flex-end",backgroundColor:P.scrim},sheet:{maxHeight:"92%",paddingHorizontal:space.lg,paddingTop:space.sm,paddingBottom:space.xl,borderTopLeftRadius:22,borderTopRightRadius:22,backgroundColor:P.card},sheetGrab:{alignSelf:"center",width:40,height:4,borderRadius:2,backgroundColor:P.line,marginBottom:space.sm},sheetTop:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},close:{width:44,height:44,alignItems:"center",justifyContent:"center"},screen:{paddingHorizontal:space.lg,paddingBottom:space.xl,gap:space.sm},back:{flexDirection:"row",alignItems:"center",gap:space.xs,minHeight:44,alignSelf:"flex-start"},done:{alignItems:"center",gap:space.sm,paddingTop:space.xl},doneCheck:{width:56,height:56,borderRadius:28,alignItems:"center",justifyContent:"center",backgroundColor:P.clearBg},doneTitle:{...t(29,P.ink,"bold",1.1),...headingFace(theme,"bold"),textAlign:"center"},doneWhen:{...t(15,P.ink2,"regular",1.4),textAlign:"center"},next:{alignSelf:"stretch",gap:space.sm,marginTop:space.md},nextRow:{flexDirection:"row",alignItems:"center",gap:space.sm},nextIcon:{width:36,height:36,borderRadius:18,alignItems:"center",justifyContent:"center",backgroundColor:P.tile},shopCard:{padding:space.md,borderRadius:16,backgroundColor:P.card,borderWidth:1,borderColor:P.line,gap:space.sm},shopItem:{flexDirection:"row",alignItems:"flex-start",gap:space.md},shopImage:{width:64,height:64,borderRadius:14,backgroundColor:P.paper,alignItems:"center",justifyContent:"center"},stepper:{flexDirection:"row",alignItems:"center",gap:space.xs,borderRadius:999,borderWidth:1.5,borderColor:P.line},stepperButton:{width:44,height:44,alignItems:"center",justifyContent:"center"},modeRow:{flexDirection:"row",gap:space.xs,marginTop:space.xs},modeButton:{flex:1,minWidth:0,minHeight:44,padding:space.sm,borderRadius:12,borderWidth:1.5,borderColor:"#DEDCD7"},chips:{flexDirection:"row",flexWrap:"wrap",gap:space.xs,marginTop:space.xs},chipButton:{minHeight:44,paddingHorizontal:space.md,borderRadius:22,borderWidth:1.5,borderColor:"#DEDCD7",justifyContent:"center"},summary:{gap:space.xs,paddingVertical:space.sm},summaryRow:{flexDirection:"row",justifyContent:"space-between",gap:space.sm},summaryTotal:t(17,P.ink,"bold",1.3),empty:{alignItems:"center",gap:space.sm,paddingTop:space.xl},emptyTile:{width:64,height:64,borderRadius:18,alignItems:"center",justifyContent:"center",backgroundColor:P.tile},order:{flexDirection:"row",alignItems:"center",gap:space.sm,padding:space.md,borderRadius:16,backgroundColor:P.card,borderWidth:1,borderColor:P.line,minHeight:56},orderPill:{alignSelf:"flex-start",paddingHorizontal:8,paddingVertical:2,borderRadius:999,backgroundColor:P.tile},orderPillDone:{backgroundColor:P.clearBg},track:{gap:space.sm},trackRow:{flexDirection:"row",alignItems:"flex-start",gap:space.sm},trackDot:{width:20,height:20,borderRadius:10,alignItems:"center",justifyContent:"center",borderWidth:2,borderColor:P.line,backgroundColor:P.card},trackDotDone:{borderColor:P.clearDot,backgroundColor:P.clearDot},input:{...t(21,P.ink,"mono",1.2),flex:1,minHeight:48,paddingHorizontal:space.md,borderRadius:12,borderWidth:1.5,borderColor:P.line,backgroundColor:P.card}}),palette:P}}var LB_PER_KG=2.20462262,ORDER_STEPS=["ordered","shipped","out_for_delivery","delivered"],TRACK_STEP={ordered:0,shipped:1,delivered:3};function hostOrderView(o){let step=Math.max(0,ORDER_STEPS.indexOf(o.status));return{key:o.key,number:o.number??null,step:step,dates:o.dates??[],everfur:false,steps:step===2?[0,1,2,3]:[0,1,3],productId:null,items:o.items.map(x=>({title:x.title,quantity:x.quantity,price:x.price,imageUrl:x.imageUrl??null,icon:x.icon??null})),total:Math.round(o.items.reduce((n,x)=>n+x.price,0)*100)/100,currency:o.currency,subscriptionBox:o.subscriptionBox===true,carrier:o.carrier??null,trackingNumber:o.trackingNumber??null,trackingTag:o.trackingTag??null,trackingUrl:o.trackingUrl??null}}function everfurOrderView(o,items){let it=items.find(x=>x.productId===o.productId),t=o.tracking,quantity=o.quantity??1,total=o.total??Math.round(o.price*quantity*100)/100,step=t===void 0?0:TRACK_STEP[t.status];return{key:o.orderId,number:t?.orderNumber??null,step:step,dates:t===void 0?[o.createdAt??null]:[o.createdAt??null,t.shippedAt,null,step===3?null:t.estimatedDelivery],steps:t===void 0?[0]:[0,1,3],everfur:true,productId:o.productId,items:[{title:o.title??it?.title??"",quantity:quantity,price:total,imageUrl:it?.imageUrl??null,icon:null}],total:total,currency:o.currency,subscriptionBox:false,carrier:t?.carrier??null,trackingNumber:t?.trackingNumber??null,trackingTag:null,trackingUrl:t?.trackingUrl??null}}function formatShopDay(iso,locale,now=/* @__PURE__ */new Date){if(iso==null)return null;let dateOnly=/^\d{4}-\d{2}-\d{2}$/.test(iso),d=new Date(dateOnly?`${iso}T00:00:00Z`:iso);if(Number.isNaN(d.getTime()))return null;let tz=dateOnly?"UTC":void 0,year=Number(new Intl.DateTimeFormat("en-US",{year:"numeric",...tz?{timeZone:tz}:{}}).format(d));try{return new Intl.DateTimeFormat(locale??"en-US",year!==now.getFullYear()?{month:"short",day:"numeric",year:"numeric",...tz?{timeZone:tz}:{}}:{weekday:"short",month:"short",day:"numeric",...tz?{timeZone:tz}:{}}).format(d)}catch{return iso}}function andList(names){return names.length<=1?names[0]??"":`${names.slice(0,-1).join(", ")} and ${names[names.length-1]??""}`}async function readOrders(repo,petRef,cursor){if(repo.listOneBoxOrderPage!==void 0)return repo.listOneBoxOrderPage(petRef,{limit:20,...cursor===null?{}:{cursor:cursor}});if(cursor!==null||repo.listOneBoxOrders===void 0)return{ok:true,value:{orders:[],nextCursor:null}};let res=await repo.listOneBoxOrders(petRef);return res.ok?{ok:true,value:{orders:res.value,nextCursor:null}}:res}function invalidCursor(error){if(error.httpStatus!==422)return false;let raw=error.raw!==null&&typeof error.raw=="object"?error.raw:null;return[error.reasonCode,error.wireMessage,raw?.detail,raw?.message].some(x=>x==="invalid_cursor")}var CHECKOUT_PARAM="everfur_checkout",CHECKOUT_CANCEL_PARAM="everfur_checkout_cancel",STRIPE_SESSION_ID="{CHECKOUT_SESSION_ID}",CHECKOUT_POLL_MS=2e3,CHECKOUT_POLL_TRIES=30;function validReturnUrl(url){return typeof url!="string"?false:/^https:\/\/[^/?#\s]+[^\s]*$/i.test(url.trim())}var PARAM_RE=new RegExp(`([?&])(?:${CHECKOUT_PARAM}|${CHECKOUT_CANCEL_PARAM})=[^&#]*&?`,"g");function checkoutReturnUrl(base3,name,value){let hashAt=base3.indexOf("#"),hash=hashAt===-1?"":base3.slice(hashAt),head=hashAt===-1?base3:base3.slice(0,hashAt);head=head.replace(PARAM_RE,"$1").replace(/[?&]$/,"");let sep=head.includes("?")?"&":"?";return`${head}${sep}${name}=${value}${hash}`}function readCheckoutReturn(url,base3){let strip=u=>u.split(/[?#]/)[0]?.replace(/\/+$/,"").toLowerCase()??"";if(strip(url)!==strip(base3))return null;let query=url.split("#")[0]?.split("?")[1]??"",params=/* @__PURE__ */new Map;for(let pair of query.split("&")){if(pair==="")continue;let at=pair.indexOf("="),key=at===-1?pair:pair.slice(0,at),value=at===-1?"":pair.slice(at+1);try{value=decodeURIComponent(value)}catch{}params.set(key,value)}if(params.has(CHECKOUT_CANCEL_PARAM))return{kind:"cancel"};let id=params.get(CHECKOUT_PARAM);return id===void 0?null:{kind:"return",sessionId:id===""||id===STRIPE_SESSION_ID?null:id}}function mintTapKey(){let c=globalThis.crypto;return c?.randomUUID?c.randomUUID():`tap-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}var checkouts=/* @__PURE__ */new Map,carts=/* @__PURE__ */new Map;function rememberCheckout(petRef,checkoutId){checkouts.set(petRef,checkoutId)}function recallCheckout(petRef){return checkouts.get(petRef)??null}function forgetCheckout(petRef){checkouts.delete(petRef)}function readCart(petRef){return carts.get(petRef)??[]}function writeCart(petRef,lines){lines.length===0?carts.delete(petRef):carts.set(petRef,lines)}var thumb=(k,src,fallback="box")=>src?/* @__PURE__ */jsx(Image,{source:{uri:src},style:k.S.shopImage,accessibilityIgnoresInvertColors:true}):/* @__PURE__ */jsx(View,{style:k.S.shopImage,children:k.icon(fallback)});function shopButton(k,label,onPress,opts={}){let{S:S}=k,disabled=opts.disabled===true;/* @__PURE__ */
|
|
141
|
+
return jsx(Pressable,{onPress:disabled?void 0:onPress,disabled:disabled,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{disabled:disabled},style:[opts.ghost?S.buttonGhost:S.button,disabled?S.disabled:null],...opts.testID?{testID:opts.testID}:{},children:/* @__PURE__ */jsx(Text,{tier:"control",style:opts.ghost?S.buttonGhostText:S.buttonText,children:label})})}function shopLink(k,label,onPress,testID){/* @__PURE__ */
|
|
142
|
+
return jsx(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label,style:k.S.link,...testID?{testID:testID}:{},children:/* @__PURE__ */jsx(Text,{tier:"control",style:k.S.linkText,children:label})})}function shopRows(k,rows){return rows.length===0?null:/* @__PURE__ */jsx(View,{style:k.S.summary,testID:"health-plan-checkout-rows",children:rows.map(r=>/* @__PURE__ */jsxs(View,{style:k.S.summaryRow,children:[
|
|
143
|
+
/* @__PURE__ */jsxs(View,{style:[k.S.row,k.S.shrink],children:[k.icon(r.icon),
|
|
144
|
+
/* @__PURE__ */jsx(Text,{style:[k.S.smallInk,k.S.shrink],children:r.label})]}),
|
|
145
|
+
/* @__PURE__ */jsx(Text,{style:[k.S.smallInk,k.S.bold],children:r.value})]},r.label))})}function shopSummary(k,total,opts={}){let{S:S,copy:copy}=k,renew=opts.renew??null;/* @__PURE__ */
|
|
146
|
+
return jsxs(View,{style:S.summary,children:[
|
|
147
|
+
/* @__PURE__ */jsxs(View,{style:S.summaryRow,children:[
|
|
148
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,children:copy.subtotal}),
|
|
149
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,children:total})]}),copy.shippingValue===""?null:/* @__PURE__ */jsxs(View,{style:S.summaryRow,children:[
|
|
150
|
+
/* @__PURE__ */jsxs(Text,{style:S.smallInk,children:[copy.shipping,opts.tag&©.shippingTag!==""?` ${copy.shippingTag}`:""]}),
|
|
151
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,children:copy.shippingValue})]}),
|
|
152
|
+
/* @__PURE__ */jsxs(View,{style:S.summaryRow,children:[
|
|
153
|
+
/* @__PURE__ */jsx(Text,{style:S.summaryTotal,children:renew===null?copy.total:copy.dueToday}),
|
|
154
|
+
/* @__PURE__ */jsx(Text,{style:S.summaryTotal,children:total})]}),renew===null?null:/* @__PURE__ */jsxs(View,{style:S.summaryRow,children:[
|
|
155
|
+
/* @__PURE__ */jsx(Text,{style:[S.small,S.shrink],children:copy.thenRenews(renew)}),
|
|
156
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:copy.renewsEvery(renew)})]})]})}function shopTrack(k,steps,label){let{S:S}=k;/* @__PURE__ */
|
|
157
|
+
return jsx(View,{style:S.track,accessibilityLabel:label,testID:"health-plan-track",children:steps.map(s=>/* @__PURE__ */jsxs(View,{style:S.trackRow,children:[
|
|
158
|
+
/* @__PURE__ */jsx(View,{style:[S.trackDot,s.state==="done"?S.trackDotDone:null],children:s.state==="done"?k.icon("check",S.palette.card):null}),
|
|
159
|
+
/* @__PURE__ */jsxs(View,{style:S.shrink,children:[
|
|
160
|
+
/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.bold],children:s.title}),s.detail?/* @__PURE__ */jsxs(Text,{style:S.small,children:[s.detail,s.tag?` ${s.tag}`:""]}):null]})]},s.title))})}function shopAskRow(k,iconName,title,body,onPress,testID){let{S:S}=k;return title===""?null:/* @__PURE__ */jsxs(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:title,style:S.askRow,testID:testID,children:[
|
|
161
|
+
/* @__PURE__ */jsx(View,{style:S.askIcon,children:k.icon(iconName)}),
|
|
162
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
163
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:title}),body===""?null:/* @__PURE__ */jsx(Text,{style:S.small,children:body})]}),k.icon("chev")]})}function shopWait(k,w,onAction){let{S:S}=k;/* @__PURE__ */
|
|
164
|
+
return jsxs(View,{style:S.card,testID:"health-plan-wait",children:[
|
|
165
|
+
/* @__PURE__ */jsxs(View,{style:S.rowTop,children:[
|
|
166
|
+
/* @__PURE__ */jsx(View,{style:S.askIcon,children:k.icon(w.icon??"kit")}),
|
|
167
|
+
/* @__PURE__ */jsxs(View,{style:S.shrink,children:[
|
|
168
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:w.kicker}),
|
|
169
|
+
/* @__PURE__ */jsx(Text,{style:S.h3,accessibilityRole:"header",children:w.title})]})]}),w.track&&w.track.length>0?/* @__PURE__ */jsx(View,{style:{marginTop:12},children:shopTrack(k,w.track,w.kicker)}):null,w.heading?/* @__PURE__ */jsx(Text,{style:[S.mini,{marginTop:12}],children:w.heading}):null,w.rows&&w.rows.length>0?/* @__PURE__ */jsx(View,{style:S.next,children:w.rows.map(r=>/* @__PURE__ */jsxs(View,{style:S.nextRow,children:[
|
|
170
|
+
/* @__PURE__ */jsx(View,{style:S.nextIcon,children:k.icon(r.icon)}),
|
|
171
|
+
/* @__PURE__ */jsxs(View,{style:S.shrink,children:[
|
|
172
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:r.label}),
|
|
173
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,children:r.text})]})]},r.label))}):null,w.note?/* @__PURE__ */jsx(Text,{style:[S.smallInk,{marginTop:12}],children:w.note}):null,w.action&&onAction?shopButton(k,w.action,onAction):null]})}function shopCartBody(k,lines,subtotal,renew,petPrices,h){let{S:S,copy:copy}=k;return lines.length===0?/* @__PURE__ */jsxs(View,{style:S.empty,testID:"health-plan-cart-empty",children:[
|
|
174
|
+
/* @__PURE__ */jsx(View,{style:S.emptyTile,children:k.icon("cart")}),
|
|
175
|
+
/* @__PURE__ */jsx(Text,{style:S.doneTitle,accessibilityRole:"header",children:copy.cartEmptyTitle}),
|
|
176
|
+
/* @__PURE__ */jsx(Text,{style:S.doneWhen,children:copy.cartEmptyBody(petPrices)}),shopLink(k,copy.seeOrders,h.onOrders,"health-plan-cart-orders")]}):/* @__PURE__ */jsxs(View,{style:{gap:12},testID:"health-plan-cart",children:[
|
|
177
|
+
/* @__PURE__ */jsx(View,{style:S.shopCard,children:lines.map(x=>/* @__PURE__ */jsxs(View,{style:S.shopItem,testID:`health-plan-cart-line-${x.key}`,children:[thumb(k,x.imageUrl),
|
|
178
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1,gap:4}],children:[
|
|
179
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:x.name}),
|
|
180
|
+
/* @__PURE__ */jsxs(View,{style:[S.row,{flexWrap:"wrap"}],children:[x.price===null?null:/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.bold],children:x.price}),x.was===null?null:/* @__PURE__ */jsx(Text,{style:S.strike,children:x.was})]}),x.note===null?null:/* @__PURE__ */jsx(Text,{style:S.small,children:x.note}),x.modes===null?null:/* @__PURE__ */jsx(View,{style:S.modeRow,accessibilityRole:"radiogroup",accessibilityLabel:x.modes.label,children:["sub","once"].map(m=>{let mode=m==="sub"?x.modes?.sub:x.modes?.once,on=m==="sub"?x.subscription:!x.subscription;return mode===void 0?null:/* @__PURE__ */jsxs(Pressable,{onPress:()=>h.onMode(x.key,m),accessibilityRole:"radio",accessibilityLabel:mode.label,accessibilityState:{checked:on},style:[S.modeButton,on?S.optOn:null],children:[
|
|
181
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:mode.label}),mode.price===null?null:/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.bold],children:mode.price})]},m)})}),x.every===null?null:/* @__PURE__ */jsx(View,{style:S.chips,accessibilityRole:"radiogroup",accessibilityLabel:copy.shipsEvery,children:x.every.options.map(d=>{let on=x.every?.selected===d;/* @__PURE__ */
|
|
182
|
+
return jsx(Pressable,{onPress:()=>h.onEvery(x.key,d),accessibilityRole:"radio",accessibilityState:{checked:on},accessibilityLabel:copy.days(d),style:[S.chipButton,on?S.optOn:null],children:/* @__PURE__ */jsx(Text,{style:S.smallInk,children:copy.days(d)})},d)})}),
|
|
183
|
+
/* @__PURE__ */jsxs(View,{style:[S.row,{justifyContent:"space-between",flexWrap:"wrap"}],children:[x.subscription?/* @__PURE__ */jsx(View,{}):/* @__PURE__ */jsxs(View,{style:S.stepper,accessibilityLabel:copy.quantityLabel(x.name),children:[
|
|
184
|
+
/* @__PURE__ */jsx(Pressable,{onPress:x.quantity<=1?void 0:()=>h.onQuantity(x.key,-1),disabled:x.quantity<=1,accessibilityRole:"button",accessibilityLabel:copy.fewer,accessibilityState:{disabled:x.quantity<=1},style:[S.stepperButton,x.quantity<=1?S.disabled:null],testID:`health-plan-fewer-${x.key}`,children:k.icon("minus")}),
|
|
185
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,accessibilityLiveRegion:"polite",children:String(x.quantity)}),
|
|
186
|
+
/* @__PURE__ */jsx(Pressable,{onPress:x.quantity>=x.maxQuantity?void 0:()=>h.onQuantity(x.key,1),disabled:x.quantity>=x.maxQuantity,accessibilityRole:"button",accessibilityLabel:copy.more,accessibilityState:{disabled:x.quantity>=x.maxQuantity},style:[S.stepperButton,x.quantity>=x.maxQuantity?S.disabled:null],testID:`health-plan-more-${x.key}`,children:k.icon("plus")})]}),shopLink(k,copy.remove,()=>h.onRemove(x.key),`health-plan-remove-${x.key}`)]})]})]},x.key))}),shopSummary(k,subtotal,{tag:true,renew:renew}),shopLink(k,copy.seeOrders,h.onOrders,"health-plan-cart-orders")]})}function shopCartCheckout(k,lines,lineTotal,rows,subtotal,renew,go,fine){let{S:S,copy:copy}=k;/* @__PURE__ */
|
|
187
|
+
return jsxs(View,{style:{gap:12},testID:"health-plan-cart-checkout-sheet",children:[
|
|
188
|
+
/* @__PURE__ */jsx(Text,{style:S.h3,accessibilityRole:"header",children:copy.cartCheckoutTitle}),lines.map(x=>/* @__PURE__ */jsxs(View,{style:S.shopItem,children:[thumb(k,x.imageUrl),
|
|
189
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
190
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:x.name}),
|
|
191
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:x.subscription?copy.cartItemSubscription(x.lp):copy.cartItemQuantity(x.quantity)})]}),
|
|
192
|
+
/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.bold],children:lineTotal(x)??""})]},x.key)),shopRows(k,rows),shopSummary(k,subtotal,{renew:renew}),shopButton(k,go.label,go.onPress,{disabled:go.disabled,testID:"health-plan-place-order"}),fine===""?null:/* @__PURE__ */jsx(Text,{style:S.fine,children:fine})]})}function orderRow(k,o,fmt,day,onOpen){let{S:S,copy:copy}=k,done=o.step===3,last=o.dates[3]??null,lastDay=day(last),when=done?lastDay===null?null:copy.deliveredOn(lastDay):lastDay===null?null:copy.arrivesBy(lastDay),total=fmt(o.total,o.currency),what=andList(o.items.map(x=>x.title));/* @__PURE__ */
|
|
193
|
+
return jsxs(Pressable,{onPress:()=>onOpen(o.key),accessibilityRole:"button",accessibilityLabel:what,style:S.order,testID:`health-plan-order-${o.key}`,children:[
|
|
194
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1,gap:4}],children:[
|
|
195
|
+
/* @__PURE__ */jsxs(View,{style:[S.row,{flexWrap:"wrap"}],children:[
|
|
196
|
+
/* @__PURE__ */jsx(View,{style:[S.orderPill,done?S.orderPillDone:null],children:/* @__PURE__ */jsx(Text,{style:S.small,children:copy.orderSteps[o.step]??""})}),o.subscriptionBox?/* @__PURE__ */jsx(View,{style:S.orderPill,children:/* @__PURE__ */jsx(Text,{style:S.small,children:copy.subscriptionBox})}):null,o.number===null?null:/* @__PURE__ */jsx(Text,{style:S.small,children:o.number})]}),
|
|
197
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:what}),
|
|
198
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:[when,total].filter(x=>x!==null).join(" · ")})]}),k.icon("chev")]},o.key)}function shopOrdersBody(k,a){let{S:S,copy:copy}=k,s=a.subscription;return!a.loaded&&s===null?/* @__PURE__ */jsx(View,{testID:"health-plan-orders-loading"}):a.loaded&&a.orders.length===0&&s===null?/* @__PURE__ */jsxs(View,{style:S.empty,testID:"health-plan-orders-empty",children:[
|
|
199
|
+
/* @__PURE__ */jsx(View,{style:S.emptyTile,children:k.icon("box")}),
|
|
200
|
+
/* @__PURE__ */jsx(Text,{style:S.doneTitle,accessibilityRole:"header",children:copy.ordersEmptyTitle}),
|
|
201
|
+
/* @__PURE__ */jsx(Text,{style:S.doneWhen,children:copy.ordersEmptyBody(a.petPrices)}),shopButton(k,copy.startedDone,a.onBack)]}):/* @__PURE__ */jsxs(View,{style:{gap:8},testID:"health-plan-orders",children:[s===null?null:/* @__PURE__ */jsxs(Fragment,{children:[
|
|
202
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:copy.herSubscription}),
|
|
203
|
+
/* @__PURE__ */jsxs(View,{style:[S.shopCard,S.shopItem],children:[thumb(k,s.imageUrl),
|
|
204
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
205
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:s.name}),s.next===null?null:/* @__PURE__ */jsx(Text,{style:S.small,children:copy.nextBox(s.next)}),
|
|
206
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:copy.everyDays(s.every)})]}),shopLink(k,copy.manage,s.onManage,"health-plan-orders-manage")]})]}),a.orders.length>0?/* @__PURE__ */jsxs(Fragment,{children:[
|
|
207
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:copy.ordersHeading(s!==null)}),a.orders.map(o=>orderRow(k,o,a.fmt,a.day,a.onOpen)),a.more&©.moreOrders!==""?shopButton(k,copy.moreOrders,a.more.onMore,{ghost:true,disabled:a.more.loading,testID:"health-plan-orders-more"}):null,copy.ordersFine===""?null:/* @__PURE__ */jsx(Text,{style:S.fine,children:copy.ordersFine})]}):null]})}function shopOrderBody(k,a){let{S:S,copy:copy}=k,o=a.order,done=o.step===3,last=o.dates[3]??null,lastDay=a.day(last),sub2=done?lastDay===null?null:copy.deliveredOn(lastDay):lastDay===null?null:copy.arrivesBy(lastDay),steps=o.steps.flatMap(i=>{let title=copy.orderSteps[i];if(title===void 0)return[];let d=a.day(o.dates[i]??null);return[i<=o.step?{title:title,state:"done",...d===null?{}:{detail:d}}:{title:title,state:"next",...d===null?{}:{detail:copy.expected(d)}}]}),httpsLink=o.trackingUrl!==null&&/^https:\/\//i.test(o.trackingUrl)?o.trackingUrl:null,linkLabel=httpsLink===null?"":o.carrier!==null?copy.trackOn(o.carrier):copy.trackLink,total=a.fmt(o.total,o.currency)??"",fine=[copy.ordersFine,o.everfur?copy.orderNote:""].filter(x=>x!=="").join(" ");/* @__PURE__ */
|
|
208
|
+
return jsxs(View,{style:{gap:12},testID:"health-plan-order",children:[
|
|
209
|
+
/* @__PURE__ */jsx(Text,{style:S.doneTitle,accessibilityRole:"header",children:done?copy.orderSteps[3]:copy.orderSteps[0]}),sub2===null?null:/* @__PURE__ */jsx(Text,{style:S.doneWhen,children:sub2}),
|
|
210
|
+
/* @__PURE__ */jsx(View,{style:S.shopCard,children:shopTrack(k,steps,copy.tracking)}),o.carrier===null&&o.trackingNumber===null?null:/* @__PURE__ */jsxs(View,{style:[S.shopCard,S.shopItem],testID:"health-plan-carrier",children:[
|
|
211
|
+
/* @__PURE__ */jsx(View,{style:S.nextIcon,children:k.icon("truck")}),
|
|
212
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[o.carrier===null?null:/* @__PURE__ */jsx(Text,{style:S.h4,children:o.carrier}),o.trackingNumber===null?null:/* @__PURE__ */jsxs(Text,{style:S.small,selectable:true,children:[o.trackingNumber,o.trackingTag===null?"":` ${o.trackingTag}`]}),o.trackingNumber===null&©.trackingByText!==""?/* @__PURE__ */jsx(Text,{style:S.small,children:copy.trackingByText}):null]}),httpsLink===null||linkLabel===""||o.trackingNumber===null?null:shopLink(k,linkLabel,()=>{Linking.openURL(httpsLink).catch(()=>{})},"health-plan-track-link")]}),
|
|
213
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:copy.inThisOrder}),
|
|
214
|
+
/* @__PURE__ */jsx(View,{style:S.shopCard,children:o.items.map(x=>/* @__PURE__ */jsxs(View,{style:S.shopItem,children:[x.imageUrl?thumb(k,x.imageUrl):/* @__PURE__ */jsx(View,{style:S.shopImage,children:k.icon(x.icon??"box")}),
|
|
215
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
216
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:x.title}),
|
|
217
|
+
/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.bold],children:a.fmt(x.price,o.currency)??""}),
|
|
218
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:copy.orderItemLine(x.quantity,o.subscriptionBox)})]})]},x.title))}),shopSummary(k,total),shopRows(k,a.rows),a.onBuyAgain===null?null:shopButton(k,copy.buyAgain,a.onBuyAgain,{ghost:true,testID:"health-plan-buy-again"}),a.onHelp===null?null:shopLink(k,copy.orderHelp,a.onHelp),fine===""?null:/* @__PURE__ */jsx(Text,{style:S.fine,children:fine})]})}var initialRead=/* @__PURE__ */new Set;function useCheckoutReturn(options){let{enabled:enabled,petRef:petRef,pages:pages,returnUrl:returnUrl,lifecycle:lifecycle}=options,handlers=useRef(options);handlers.current=options,useEffect(()=>{if(!enabled||returnUrl===null)return;let live=true,polling=false,timer=null,poll=async(checkoutId,tries)=>{let res=await pages.getCheckout(petRef,checkoutId);if(live){if(res.ok&&res.value.status==="paid"){polling=false,forgetCheckout(petRef),handlers.current.onPaid(res.value);return}if(res.ok&&(res.value.status==="failed"||res.value.status==="expired")){polling=false,forgetCheckout(petRef),handlers.current.onFailed();return}if(!res.ok&&!res.error.retryable){polling=false,forgetCheckout(petRef),handlers.current.onError(res.error);return}if(tries<=1){polling=false,forgetCheckout(petRef),handlers.current.onTimeout();return}timer=setTimeout(()=>{poll(checkoutId,tries-1)},CHECKOUT_POLL_MS)}},start=checkoutId=>{polling||(polling=true,poll(checkoutId,CHECKOUT_POLL_TRIES))},onUrl=url=>{let back=readCheckoutReturn(url,returnUrl);if(back===null)return;if(back.kind==="cancel"){forgetCheckout(petRef),handlers.current.onCancel();return}let id=recallCheckout(petRef)??back.sessionId;id!==null&&start(id)},resume=()=>{let id=recallCheckout(petRef);id!==null&&start(id)},sub=Linking.addEventListener("url",event=>onUrl(event.url));Linking.getInitialURL().then(url=>{!live||url===null||url===void 0||initialRead.has(url)||readCheckoutReturn(url,returnUrl)!==null&&(initialRead.add(url),onUrl(url))}).catch(()=>{});let offForeground;if(lifecycle)offForeground=lifecycle.onForeground(resume);else{let app=AppState.addEventListener("change",next=>{next==="active"&&resume()});offForeground=()=>app.remove()}return()=>{live=false,timer!==null&&clearTimeout(timer),sub.remove(),offForeground()}},[enabled,petRef,pages,returnUrl,lifecycle])}function recordsEmptyReader(auth,errorPolicy){let funnel=withPlainNotFound(createRequestFunnel({auth:auth,...errorPolicy?{errorPolicy:errorPolicy}:{}}));return{getRecord:petRef=>funnel.send("records.getRecord",{method:"GET",path:`/widget/v1/records/pets/${encodeURIComponent(petRef)}/record`})}}var PAY_WITH="Pay with",KG_MIN=.5,KG_MAX=90.7,isDogSpecies=s=>s!=null&&/^(dog|canine)$/i.test(s.trim());function HealthPlanFocus(props){let{design:design,item:item,petRef:petRef,locale:locale}=props,petName=props.petName?.trim()?props.petName.trim():null,theme=useEverfurTheme(),S=useMemo(()=>makeFocusStyles(theme),[theme]),P=S.palette,telemetry=useHealthPlanTelemetry(),{runtime:runtime,userRef:userRef}=useEverfurContext(),window=useWindowDimensions(),sex=props.petSex??null,trackingTexts=props.trackingTexts===true,copy=useMemo(()=>({...HEALTH_PLAN_FOCUS_RN_COPY,...healthPlanPetCopy({name:petName,sex:sex,trackingTexts:trackingTexts}),...design.copy,...props.fromBackend===true?HEALTH_PLAN_NO_SHIP_DAY_COPY:{},...props.copy}),[petName,sex,trackingTexts,design.copy,props.copy,props.fromBackend]),sub=useHealthPlanSubscription({petRef:petRef,productId:item.productId,enabled:props.subscriptions!==false,...props.subscriptionRepository?{repository:props.subscriptionRepository}:{},...props.lifecycle!==void 0?{lifecycle:props.lifecycle}:{},...props.refreshKey!==void 0?{refreshKey:props.refreshKey}:{}}),renderIcon=props.renderIcon,icon=useCallback((name,color,size)=>(renderIcon?callHost(renderIcon,name):void 0)??/* @__PURE__ */jsx(FocusIcon,{name:name,color:color??P.ink,...size===void 0?{}:{size:size}}),[renderIcon,P.ink]),kit={S:S,icon:icon,copy:copy},[mode,setMode]=useState("sub"),[added,setAdded]=useState(false),[extras,setExtras]=useState(()=>/* @__PURE__ */new Set),[sheet,setSheet]=useState(null),[started,setStarted]=useState(null),tapKey=useRef(null),[toast,setToast]=useState(null),toastTimer=useRef(null);useEffect(()=>()=>{toastTimer.current!==null&&clearTimeout(toastTimer.current)},[]);let say=line=>{line!==""&&(setToast(line),toastTimer.current!==null&&clearTimeout(toastTimer.current),toastTimer.current=setTimeout(()=>setToast(null),2600))},returnUrl=validReturnUrl(props.checkoutReturnUrl)?props.checkoutReturnUrl.trim():null,everfur=props.checkout==="everfur_stripe"&&returnUrl!==null,ownPages=useHealthPlanPageRepository(),pages=props.pageRepository??ownPages,checkoutTap=useRef(null),[redirecting,setRedirecting]=useState(false),shop=props.shop??everfur,[cart,setCartState]=useState(()=>shop?readCart(petRef):[]),setCart=useCallback(f2=>{setCartState(prev=>{let next=f2(prev);return writeCart(petRef,next),next})},[petRef]),[screens,setScreens]=useState([]),[cartNotice,setCartNotice]=useState(null),ownSubs=useHealthPlanSubscriptionRepository(),subsRepo=props.subscriptionRepository??ownSubs,[everfurOrders,setEverfurOrders]=useState({loaded:false,orders:[],next:null,loading:false}),[cartOff,setCartOff]=useState(false),[weightSaved,setWeightSaved]=useState(false),[recent,setRecent]=useState([]),others=props.others??[],planItems=[item,...others],seen=/* @__PURE__ */new Set,allOrders=[...[...recent,...everfurOrders.orders].filter(o=>seen.has(o.orderId)?false:(seen.add(o.orderId),true)).map(o=>everfurOrderView(o,planItems)),...(props.shopOrders??[]).map(hostOrderView)],push=useCallback(screen=>{setSheet(null),setScreens(prev=>[...prev.filter(x=>x.kind!==screen.kind),screen])},[]),top=screens.length>0?screens[screens.length-1]:void 0,overlay=sheet!==null?sheet.kind:started!==null?"started":top!==void 0?top.kind:null,under=started!==null?"started":top!==void 0?top.kind:null,closeOverlays=useCallback(()=>{setSheet(null),setStarted(null),setScreens([]),setCartNotice(null)},[]),back=useCallback(()=>{sheet!==null?setSheet(null):started!==null?setStarted(null):setScreens(prev=>prev.slice(0,-1))},[sheet,started]),orderNumber=key=>allOrders.find(o=>o.key===key)?.number??null,title=(o=>{switch(o){case"started":return started?.kind==="once"?copy.placedHeader:copy.startedHeader;case"cart":return copy.cartTitle;case"placed":return copy.placedHeader;case"orders":return copy.orders;case"order":return copy.orderTitle(top?.kind==="order"?orderNumber(top.key):null);default:return}})(under),full=under==="started"||under==="cart"||under==="placed",onOverlayChange=props.onOverlayChange;useEffect(()=>{onOverlayChange!==void 0&&callHost(onOverlayChange,overlay,{close:closeOverlays,back:back,...title===void 0?{}:{title:title},...full?{full:full}:{}})},[overlay,onOverlayChange,closeOverlays,back,title,full]);let quote=sub.phase==="ready"?sub.quote:null,subscription=sub.subscription,active=subscription?.status==="active",canSubscribe=quote!==null,offer=canSubscribe&"e.offerApplies&&subscription===null,every=active?subscription.intervalDays:canSubscribe?quote.defaultIntervalDays:0,fmt=(n2,currency2)=>formatHealthPlanPriceWith(n2,currency2,{dropZeroCents:false,...props.priceFormat,...locale?{locale:locale}:{}}),currency=quote?.currency??item.currency,boxPrice=quote?.boxPrice??item.price,oneBox=quote?.oneBox??null,prices=(days,productName=item.title)=>({petName:petName,productName:productName,first:fmt(offer&"e?quote.firstBoxPrice:boxPrice,currency),box:fmt(boxPrice,currency),once:fmt(oneBox?.price??boxPrice,currency),onceDiscountPercent:oneBox?.discountPercent??0,intervalDays:days,discountPercent:offer&"e?quote.firstBoxDiscountPercent:0,offer:offer}),pr=prices(every),priced=pr.box!==null,buyMode=canSubscribe?mode:"once",day=iso=>formatHealthPlanDay(iso,locale),nextBoxDay=s=>day(s.timeline.find(step=>step.step==="next_box_ships")?.on??s.nextBoxDate),buyOnce=(target=item)=>{props.onBuy?callHost(props.onBuy,target):props.onCheckout&&callHost(props.onCheckout,[target])},partnerBuys=props.onBuy!==void 0||props.onCheckout!==void 0,settle=res=>res.ok?(props.onSubscriptionChange&&callHost(props.onSubscriptionChange,res.value),res.value):(say(res.error.displayMessage),null),leave=url=>{props.navigate?callHost(props.navigate,url):Linking.openURL(url).catch(()=>{})},returnUrls=()=>returnUrl===null?null:{successUrl:checkoutReturnUrl(returnUrl,CHECKOUT_PARAM,STRIPE_SESSION_ID),cancelUrl:checkoutReturnUrl(returnUrl,CHECKOUT_CANCEL_PARAM,"1")},redirect=async(purchase,intervalDays,target=item)=>{let urls=returnUrls();if(urls===null||redirecting)return;let sig=`${target.productId}:${purchase}:${intervalDays??""}`;checkoutTap.current?.sig!==sig&&(checkoutTap.current={sig:sig,key:mintTapKey()}),setRedirecting(true);let res=await pages.startCheckout(petRef,{productId:target.productId,purchase:purchase,...intervalDays===null?{}:{intervalDays:intervalDays},...urls},checkoutTap.current.key);if(setRedirecting(false),!res.ok){say(res.error.displayMessage);return}rememberCheckout(petRef,res.value.checkoutId),leave(res.value.url)},itemOf2=productId=>planItems.find(x=>x.productId===productId),inCart=productId=>cart.find(x=>x.productId===productId),isPick=productId=>productId===item.productId,lineSub=x=>isPick(x.productId)&&canSubscribe&&!active&&x.mode==="sub",unitOf=x=>isPick(x.productId)?lineSub(x)?offer&"e?quote.firstBoxPrice:boxPrice:oneBox?.price??boxPrice:itemOf2(x.productId)?.price??null,lines=cart.filter(x=>itemOf2(x.productId)!==void 0),lineCount=lines.reduce((n2,x)=>n2+x.qty,0),cartTotal=Math.round(lines.reduce((n2,x)=>n2+(unitOf(x)??0)*x.qty,0)*100)/100,subLine=lines.find(lineSub)??null,cartOn=everfur&&!cartOff&&pages.startCartCheckout!==void 0,lineView=x=>{let it=itemOf2(x.productId)??item,subbed=lineSub(x),pick2=isPick(x.productId),lp=pick2?prices(x.every,it.title):{...prices(0,it.title),offer:false};return{key:x.productId,name:it.title,imageUrl:it.imageUrl??null,quantity:x.qty,subscription:subbed,price:fmt(unitOf(x),pick2?currency:it.currency),was:pick2?subbed?offer?lp.box:null:oneBox!==null&&boxPrice!==null&&oneBox.price<boxPrice?lp.box:null:null,note:pick2?subbed?copy.cartSubLine(lp):copy.cartOnceLine(lp,active):null,modes:pick2&&canSubscribe&&!active?{label:copy.cartModeLabel(it.title),sub:{label:copy.cartModeSubscribe(lp),price:lp.first},once:{label:copy.cartModeOnce(lp),price:lp.once}}:null,every:subbed&"e!==null?{options:quote.intervalOptions,selected:x.every}:null,maxQuantity:cartOn&&!subbed?5:1,lp:lp}},views=lines.map(lineView),renewPrices=subLine===null?null:prices(subLine.every),addToCart=(target,m)=>{if(inCart(target.productId)){push({kind:"cart"});return}let subbing=isPick(target.productId)&&canSubscribe&&!active&&m==="sub";setCart(prev=>[...prev,{productId:target.productId,mode:subbing?"sub":"once",every:quote?.defaultIntervalDays??0,qty:1}]),say(copy.addedToCart(isPick(target.productId)?pr:{...prices(0,target.title),offer:false},subbing))},editLine=(productId,f2)=>setCart(prev=>prev.flatMap(x=>x.productId!==productId?[x]:f2(x)??[])),apart=cartOn&&subLine!==null&&lines.length>1,batch=apart?lines.filter(x=>!lineSub(x)):lines,batchTotal=Math.round(batch.reduce((n2,x)=>n2+(unitOf(x)??0)*x.qty,0)*100)/100,batchSub=batch.find(lineSub)??null,batchRenew=batchSub===null?null:prices(batchSub.every),cartReady=lines.length>0&&lines.every(x=>unitOf(x)!==null)&&(lines.length===1&&(lines[0]?.qty??0)===1?true:cartOn?batch.length>0&&batch.length<=10:!everfur&&props.onCheckout!==void 0&&lines.every(x=>!lineSub(x))),redirectCart=async batchLines=>{let urls=returnUrls();if(urls===null||redirecting||pages.startCartCheckout===void 0)return;let sig=`cart:${batchLines.map(x=>`${x.productId}:${x.qty}:${lineSub(x)?x.every:""}`).join("|")}`;checkoutTap.current?.sig!==sig&&(checkoutTap.current={sig:sig,key:mintTapKey()}),setRedirecting(true);let res=await pages.startCartCheckout(petRef,{items:batchLines.map(x=>{let subbing=lineSub(x);return{productId:x.productId,purchase:subbing?"subscription":"one_box",...subbing?{intervalDays:x.every}:{},quantity:subbing?1:x.qty}}),...urls},checkoutTap.current.key);if(setRedirecting(false),!res.ok){let why=healthPlanCheckoutRefusal(res.error);if(why==="cart_disabled"){setCartOff(true),setSheet(null),say(copy.cartOneAtATime===""?res.error.displayMessage:copy.cartOneAtATime);return}if(why==="cart_has_subscription"){setSheet(null),say(copy.cartSubscriptionApart===""?res.error.displayMessage:copy.cartSubscriptionApart);return}say(res.error.displayMessage);return}rememberCheckout(petRef,res.value.checkoutId),leave(res.value.url)},placeCart=async()=>{if(!cartReady)return;if(setCartNotice(null),everfur&&cartOn&&!(batch.length===1&&(batch[0]?.qty??0)===1)){batch.map(x=>itemOf2(x.productId)).filter(x=>x!==void 0);trackCheckoutStarted(telemetry,petRef,{count:batch.reduce((n2,x)=>n2+x.qty,0),subtotal:batchTotal,currency:currency}),await redirectCart(batch);return}let only=batch.length===1?batch[0]:lines.length===1?lines[0]:void 0;if(only===void 0){props.onCheckout&&callHost(props.onCheckout,lines.map(x=>itemOf2(x.productId)).filter(x=>x!==void 0));return}let target=itemOf2(only.productId)??item,subbing=lineSub(only);if(trackCheckoutStarted(telemetry,petRef,{count:1,subtotal:unitOf(only),currency:isPick(only.productId)?currency:target.currency}),everfur){await redirect(subbing?"subscription":"one_box",subbing?only.every:null,target);return}if(subbing){let s=settle(await sub.subscribe(only.every));if(s===null)return;bought([s.productId]),setSheet(null),setScreens([]),setStarted({kind:"sub",sub:s});return}if(!isPick(only.productId)||oneBox===null){setSheet(null),buyOnce(target);return}tapKey.current===null&&(tapKey.current=mintTapKey());let res=await sub.buyOneBox(tapKey.current);if(!res.ok){say(res.error.displayMessage);return}tapKey.current=null,props.onOneBoxOrder&&callHost(props.onOneBoxOrder,res.value),bought([res.value.productId]),placed([res.value])},ordersOpen=screens.some(x=>x.kind==="orders"||x.kind==="order"),ordersLive=useRef(false),loadingMore=useRef(false),sayRef=useRef(say);sayRef.current=say,useEffect(()=>{if(!shop||!ordersOpen)return;let live=true;return ordersLive.current=true,readOrders(subsRepo,petRef,null).then(res=>{live&&(res.ok?setEverfurOrders({loaded:true,orders:res.value.orders,next:res.value.nextCursor,loading:false}):(setEverfurOrders(prev=>({...prev,loaded:true,loading:false})),sayRef.current(res.error.displayMessage)))}),()=>{live=false,ordersLive.current=false}},[shop,ordersOpen,petRef,subsRepo]);let moreOrders=()=>{let cursor=everfurOrders.next;cursor===null||loadingMore.current||(loadingMore.current=true,setEverfurOrders(prev=>({...prev,loading:true})),readOrders(subsRepo,petRef,cursor).then(async res=>{let again=!res.ok&&invalidCursor(res.error)?await readOrders(subsRepo,petRef,null):null;if(loadingMore.current=false,!!ordersLive.current){if(again!==null){again.ok?setEverfurOrders({loaded:true,orders:again.value.orders,next:again.value.nextCursor,loading:false}):(setEverfurOrders(prev=>({...prev,next:null,loading:false})),sayRef.current(again.error.displayMessage));return}if(res.ok){let page=res.value;setEverfurOrders(prev=>({loaded:true,orders:[...prev.orders,...page.orders.filter(o=>!prev.orders.some(x=>x.orderId===o.orderId))],next:page.nextCursor,loading:false}))}else setEverfurOrders(prev=>({...prev,loading:false})),sayRef.current(res.error.displayMessage)}}))},species=props.species??null,isDog=isDogSpecies(species),otherSpecies=species!==null&&species.trim()!==""&&!isDog,askWeight=!(props.weightKnown!==false||weightSaved)&&isDog,kg=props.weightUnit==="kg",[weightInput,setWeightInput]=useState(""),[weightError,setWeightError]=useState(""),[savingWeight,setSavingWeight]=useState(false),saveWeight=async()=>{let n2=Math.round(Number.parseFloat(weightInput.replace(",","."))*10)/10;if(!(kg?n2>=KG_MIN&&n2<=KG_MAX:n2>=1&&n2<=200)){setWeightError(kg?copy.weightErrorKg:copy.weightError);return}let weightKg=kg?Math.round(n2*100)/100:Math.round(n2/LB_PER_KG*100)/100,lb=kg?Math.round(n2*LB_PER_KG*10)/10:n2;setSavingWeight(true);let res=props.onSaveWeight?await props.onSaveWeight(weightKg,lb):await runtime.updatePet(petRef,{weightKg:weightKg});if(setSavingWeight(false),!res.ok){setWeightError(res.error.displayMessage);return}setWeightError(""),setWeightSaved(true),setSheet(null),say(kg?copy.weightSavedKg(String(n2)):copy.weightSaved(String(lb))),props.onWeightSaved&&callHost(props.onWeightSaved,weightKg)},recordsReader=props.recordsRepository,[recordsEmpty,setRecordsEmpty]=useState(null),probeRecords=props.recordsMissing===void 0&&props.onConnectRecords!==void 0;useEffect(()=>{if(!probeRecords)return;let live=true;return(recordsReader??recordsEmptyReader(runtime.registry.services.authFor(userRef),runtime.registry.services.errorPolicy)).getRecord(petRef).then(res=>{live&&setRecordsEmpty(res.ok?res.value.withheld!==true&&res.value.is_empty===true:null)}).catch(()=>{}),()=>{live=false}},[probeRecords,recordsReader,runtime,userRef,petRef]);let recordsMissing=props.recordsMissing??recordsEmpty===true,placed=orders=>{let first=orders[0];if(first!==void 0){if(!shop){setStarted({kind:"once",order:first});return}setRecent(prev=>[...orders,...prev.filter(o=>!orders.some(x=>x.orderId===o.orderId))]),setSheet(null),setScreens([{kind:"placed",orders:orders}])}},bought=productIds=>{let gone=new Set(productIds.filter(x=>x!==null));gone.size>0&&setCart(prev=>prev.filter(x=>!gone.has(x.productId)))};useCheckoutReturn({enabled:everfur,petRef:petRef,pages:pages,returnUrl:returnUrl,lifecycle:props.lifecycle??null,onPaid:state=>{let run=state.subscription,orders=state.orders??(state.order===null?[]:[state.order]);if(setCartNotice(null),run!==null)props.onSubscriptionChange&&callHost(props.onSubscriptionChange,run),setSheet(null),setScreens([]),setStarted({kind:"sub",sub:run});else if(orders.length>0){for(let o of orders)props.onOneBoxOrder&&callHost(props.onOneBoxOrder,o);placed(orders)}bought([run?.productId??null,...orders.map(o=>o.productId)]),sub.refresh()},onFailed:()=>{setSheet(null),setStarted(null),setScreens([{kind:"cart"}]),setCartNotice(copy.checkoutFailed)},onCancel:()=>{setRedirecting(false)},onTimeout:()=>{setSheet(null),setStarted(null),setScreens([{kind:"orders"}])},onError:error=>say(error.displayMessage)});let img=(src,style)=>src?/* @__PURE__ */jsx(Image,{source:{uri:src},style:style,accessibilityIgnoresInvertColors:true}):null,tag=label=>label===void 0||label===""?null:/* @__PURE__ */jsx(View,{style:S.tag,children:/* @__PURE__ */jsx(Text,{style:S.tagText,children:label})}),sec=1,n=k=>/* @__PURE__ */jsx(View,{style:S.n,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */jsx(Text,{style:S.nText,children:String(k)})}),sectionHead=label=>/* @__PURE__ */jsxs(View,{style:S.sectionHead,children:[n(sec++),
|
|
219
|
+
/* @__PURE__ */jsx(Text,{style:S.sectionTitle,accessibilityRole:"header",children:label})]}),toastNode=toast===null?null:/* @__PURE__ */jsx(View,{style:S.toast,accessibilityLiveRegion:"polite",accessibilityRole:"alert",testID:"health-plan-toast",children:/* @__PURE__ */jsx(Text,{style:S.toastText,children:toast})}),f=design.focus,pk=design.pick,waitNode=props.renderWait?callHost(props.renderWait)??null:null,waiting=waitNode!==null||design.wait!==void 0,rows=props.checkoutRows??(props.fromBackend?[]:design.checkoutRows??[]),trust=props.trust??(props.fromBackend?[]:pk.trust??[]),byline=design.byline!==void 0&&(props.fromBackend!==true||props.vetReviewed===true)?design.byline:void 0,tipWidth=Math.max(200,Math.round((window.width-32)*.78)),checkupBody=as=>{let c=design.checkup;return c===void 0?null:/* @__PURE__ */jsxs(Fragment,{children:[as==="kicker"?/* @__PURE__ */jsx(Text,{style:[S.mini,{marginTop:14}],accessibilityRole:"header",children:c.title}):sectionHead(c.title),
|
|
220
|
+
/* @__PURE__ */jsx(View,{style:S.questions,children:c.questions.map((q,i)=>/* @__PURE__ */jsxs(View,{style:S.rowTop,children:[
|
|
221
|
+
/* @__PURE__ */jsx(Text,{style:S.question,children:`${i+1}.`}),
|
|
222
|
+
/* @__PURE__ */jsx(Text,{style:S.question,children:q})]},q))}),c.add===""?null:/* @__PURE__ */jsx(Pressable,{onPress:()=>{let next=!added;setAdded(next),props.onAddToVisit&&callHost(props.onAddToVisit,next,c.questions)},accessibilityRole:"button",accessibilityState:{selected:added},accessibilityLabel:added?c.added:c.add,style:[S.add,added?S.addOn:null],testID:"health-plan-add-to-visit",children:/* @__PURE__ */jsx(Text,{tier:"control",style:[S.addText,added?S.addOnText:null],children:added?c.added:c.add})})]})},connectRow=recordsMissing&&props.onConnectRecords?shopAskRow(kit,"file",copy.connectRecordsTitle,copy.connectRecordsBody,()=>props.onConnectRecords&&callHost(props.onConnectRecords),"health-plan-connect-records"):null,pickInCart=shop&&inCart(item.productId)!==void 0,showBuy=priced&&(everfur||canSubscribe||partnerBuys),tools=shop?/* @__PURE__ */jsxs(View,{style:S.tools,children:[design.eyebrow?/* @__PURE__ */jsx(Text,{style:[S.eyebrow,S.shrink],children:design.eyebrow}):/* @__PURE__ */jsx(View,{}),
|
|
223
|
+
/* @__PURE__ */jsxs(View,{style:S.toolsEnd,children:[
|
|
224
|
+
/* @__PURE__ */jsxs(Pressable,{onPress:()=>push({kind:"orders"}),accessibilityRole:"button",accessibilityLabel:copy.orders,style:S.toolButton,testID:"health-plan-orders-button",children:[icon("box",void 0,21),
|
|
225
|
+
/* @__PURE__ */jsx(Text,{tier:"control",style:S.toolLabel,children:copy.orders})]}),
|
|
226
|
+
/* @__PURE__ */jsxs(Pressable,{onPress:()=>push({kind:"cart"}),accessibilityRole:"button",accessibilityLabel:copy.cartLabel(lineCount),style:S.toolButton,testID:"health-plan-cart-button",children:[icon("cart",void 0,26),lineCount===0?null:/* @__PURE__ */jsx(View,{style:S.cartCount,children:/* @__PURE__ */jsx(Text,{tier:"badge",style:S.cartCountText,children:String(lineCount)})})]})]})]}):null,pageNode=/* @__PURE__ */jsxs(View,{style:[S.root,props.style],testID:"health-plan-focus",children:[tools,toastNode,
|
|
227
|
+
/* @__PURE__ */jsxs(View,{style:S.head,children:[
|
|
228
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[design.eyebrow&&!shop?/* @__PURE__ */jsx(Text,{style:S.eyebrow,children:design.eyebrow}):null,
|
|
229
|
+
/* @__PURE__ */jsx(Text,{style:S.title,accessibilityRole:"header",testID:"health-plan-focus-title",children:design.title}),design.subtitle?/* @__PURE__ */jsx(Text,{style:S.subtitle,children:design.subtitle}):null]}),img(design.headImageUrl,S.headImage)]}),waitNode!==null?/* @__PURE__ */jsx(View,{style:{marginTop:14},children:waitNode}):design.wait?shopWait(kit,design.wait,props.onWaitAction):null,byline&&!waiting?/* @__PURE__ */jsxs(View,{style:S.by,testID:"health-plan-byline",children:[img(byline.imageUrl,S.byImage),
|
|
230
|
+
/* @__PURE__ */jsxs(View,{style:S.shrink,children:[
|
|
231
|
+
/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.bold],children:byline.name}),byline.role?/* @__PURE__ */jsx(Text,{style:S.small,children:byline.role}):null]}),icon("shield",P.teal)]}):null,f&&!waiting?/* @__PURE__ */jsxs(View,{style:S.need,accessibilityLabel:f.title,testID:"health-plan-focus-card",children:[
|
|
232
|
+
/* @__PURE__ */jsxs(View,{style:S.kickerRow,children:[
|
|
233
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:f.kicker}),(f.sources??[]).map(s=>/* @__PURE__ */jsx(View,{style:S.source,children:/* @__PURE__ */jsx(Text,{style:S.sourceText,children:s.label})},s.label))]}),
|
|
234
|
+
/* @__PURE__ */jsx(Text,{style:S.h3,accessibilityRole:"header",children:f.title}),f.risk?/* @__PURE__ */jsxs(View,{style:S.risk,children:[
|
|
235
|
+
/* @__PURE__ */jsx(View,{style:[S.dot,f.risk.kind==="clear"||f.risk.kind==="ok"?S.dotClear:null]}),
|
|
236
|
+
/* @__PURE__ */jsxs(Text,{style:S.riskText,children:[
|
|
237
|
+
/* @__PURE__ */jsx(Text,{style:S.bold,children:f.risk.lead}),f.risk.body?` ${f.risk.body}`:""]})]}):null,f.odds?/* @__PURE__ */jsxs(View,{style:S.odds,children:[
|
|
238
|
+
/* @__PURE__ */jsxs(View,{style:S.kickerRow,children:[
|
|
239
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:f.odds.label}),tag(f.odds.tag)]}),
|
|
240
|
+
/* @__PURE__ */jsxs(View,{style:S.oddsRow,children:[
|
|
241
|
+
/* @__PURE__ */jsx(Text,{style:S.oddsFrom,children:f.odds.from}),icon("arrow"),
|
|
242
|
+
/* @__PURE__ */jsx(Text,{style:S.oddsTo,children:f.odds.to}),f.odds.toLabel?/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.shrink],children:f.odds.toLabel}):null]})]}):null,f.quote?/* @__PURE__ */jsxs(View,{style:S.quote,children:[
|
|
243
|
+
/* @__PURE__ */jsxs(View,{style:S.kickerRow,children:[
|
|
244
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:f.quote.kicker}),tag(f.quote.tag)]}),
|
|
245
|
+
/* @__PURE__ */jsx(Text,{style:S.quoteText,children:f.quote.text})]}):null,f.jump?/* @__PURE__ */jsxs(Pressable,{onPress:props.onJump?()=>props.onJump&&callHost(props.onJump):void 0,disabled:props.onJump===void 0,accessibilityRole:props.onJump?"button":"text",style:S.jump,testID:"health-plan-jump",children:[img(item.imageUrl,S.jumpImage),
|
|
246
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[pr.box===null&&!canSubscribe?null:/* @__PURE__ */jsx(Text,{style:S.jumpSmall,children:copy.jumpKicker(pr,active)}),
|
|
247
|
+
/* @__PURE__ */jsx(Text,{style:S.jumpStrong,children:f.jump.title})]}),props.onJump?/* @__PURE__ */jsx(Text,{style:S.jumpGo,children:f.jump.go}):null]}):null]}):null,design.routine&&!waiting?/* @__PURE__ */jsxs(View,{testID:"health-plan-routine",children:[sectionHead(design.routine.title),design.routine.label?/* @__PURE__ */jsx(Text,{style:S.small,children:design.routine.label}):null,
|
|
248
|
+
/* @__PURE__ */jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:[S.tips,{marginTop:12}],children:design.routine.steps.map((s,i)=>/* @__PURE__ */jsxs(View,{style:[S.tip,{width:tipWidth,backgroundColor:P.tints[s.tone??"y"]}],children:[
|
|
249
|
+
/* @__PURE__ */jsxs(View,{style:S.row,children:[
|
|
250
|
+
/* @__PURE__ */jsx(Text,{style:S.tipN,accessibilityElementsHidden:true,importantForAccessibility:"no",children:String(i+1)}),s.icon?icon(s.icon):null]}),
|
|
251
|
+
/* @__PURE__ */jsx(Text,{style:S.tipStrong,children:s.title}),s.body?/* @__PURE__ */jsx(Text,{style:S.tipSmall,children:s.body}):null,s.source?/* @__PURE__ */jsx(Text,{style:S.tipEm,children:s.source}):null]},s.title))})]}):null,waiting?null:/* @__PURE__ */jsxs(View,{testID:"health-plan-pick",children:[sectionHead(pk.title),
|
|
252
|
+
/* @__PURE__ */jsxs(View,{style:S.card,children:[
|
|
253
|
+
/* @__PURE__ */jsxs(View,{style:S.pickTop,children:[item.imageUrl?img(item.imageUrl,S.pickImage):/* @__PURE__ */jsx(View,{style:S.pickImage}),
|
|
254
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1,gap:2}],children:[
|
|
255
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,testID:"health-plan-pick-title",children:item.title}),pk.rating?/* @__PURE__ */jsxs(Text,{style:S.stars,accessibilityLabel:[pk.rating.value,pk.rating.label].filter(Boolean).join(" "),children:[`★ ${pk.rating.value}`,pk.rating.label?/* @__PURE__ */jsx(Text,{style:S.starsLabel,children:` ${pk.rating.label}`}):null]}):null,pk.line??item.description?/* @__PURE__ */jsx(Text,{style:S.line,children:pk.line??item.description}):null]})]}),pk.reviews&&pk.reviews.items.length>0?/* @__PURE__ */jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:S.reviews,accessibilityLabel:pk.reviews.label,testID:"health-plan-reviews",children:pk.reviews.items.map(r=>{let stars=Math.max(1,Math.min(5,Math.round(r.stars)));/* @__PURE__ */
|
|
256
|
+
return jsxs(View,{style:[S.review,{width:tipWidth}],children:[
|
|
257
|
+
/* @__PURE__ */jsx(Text,{style:S.stars,accessibilityLabel:`${stars} out of 5 stars`,children:"★".repeat(stars)}),
|
|
258
|
+
/* @__PURE__ */jsx(Text,{style:S.reviewText,children:`“${r.text}”`}),
|
|
259
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:r.by})]},`${r.by}${r.text}`)})}):null,pk.why&&pk.why.rows.length>0?/* @__PURE__ */jsxs(View,{style:S.why,testID:"health-plan-why",children:[
|
|
260
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:pk.why.title}),pk.why.rows.map(r=>/* @__PURE__ */jsxs(View,{style:S.whyRow,children:[
|
|
261
|
+
/* @__PURE__ */jsx(View,{style:S.chip,children:/* @__PURE__ */jsx(Text,{style:S.chipText,children:r.chip})}),
|
|
262
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
263
|
+
/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.bold],children:r.title}),r.body?/* @__PURE__ */jsx(Text,{style:S.small,children:r.body}):null]})]},r.title)),pk.why.score&&pk.why.rows.length>=2?/* @__PURE__ */jsxs(View,{style:S.score,testID:"health-plan-why-score",children:[
|
|
264
|
+
/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.shrink],children:pk.why.score.text}),
|
|
265
|
+
/* @__PURE__ */jsx(Text,{style:S.scoreValue,accessibilityElementsHidden:true,importantForAccessibility:"no",children:pk.why.score.value})]}):null]}):null,otherSpecies?null:askWeight?shopAskRow(kit,"pulse",copy.addWeightTitle,copy.addWeightBody,()=>{setWeightError(""),setSheet({kind:"weight"})},"health-plan-add-weight"):pk.dose?/* @__PURE__ */jsxs(View,{style:S.dose,testID:"health-plan-dose",children:[
|
|
266
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:pk.dose.title}),
|
|
267
|
+
/* @__PURE__ */jsx(View,{style:S.stats,children:pk.dose.stats.map(s=>/* @__PURE__ */jsxs(View,{style:S.stat,children:[
|
|
268
|
+
/* @__PURE__ */jsx(Text,{style:S.statValue,children:s.value}),
|
|
269
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:s.label})]},`${s.value}${s.label}`))}),pk.dose.note?/* @__PURE__ */jsx(Text,{style:S.small,children:pk.dose.note}):null]}):null,pk.ingredients&&pk.ingredients.items.length>0?/* @__PURE__ */jsx(View,{style:S.pills,accessibilityLabel:pk.ingredients.label??pk.ingredients.items.join(", "),children:pk.ingredients.items.map(x=>/* @__PURE__ */jsx(View,{style:S.pill,children:/* @__PURE__ */jsx(Text,{style:S.smallInk,children:x})},x))}):null,canSubscribe&&priced?/* @__PURE__ */jsxs(View,{style:S.opts,accessibilityRole:"radiogroup",accessibilityLabel:copy.optionsLabel,testID:"health-plan-options",children:[
|
|
270
|
+
/* @__PURE__ */jsxs(Pressable,{onPress:()=>setMode("sub"),accessibilityRole:"radio",accessibilityState:{checked:buyMode==="sub"},accessibilityLabel:copy.subscribe,style:[S.opt,buyMode==="sub"?S.optOn:null],testID:"health-plan-opt-sub",children:[
|
|
271
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[offer?/* @__PURE__ */jsx(View,{style:S.optTag,children:/* @__PURE__ */jsx(Text,{style:S.optTagText,children:copy.bestValue})}):null,
|
|
272
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:copy.subscribe}),
|
|
273
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:copy.subscribeLine(pr)})]}),
|
|
274
|
+
/* @__PURE__ */jsxs(View,{style:S.price,children:[
|
|
275
|
+
/* @__PURE__ */jsx(Text,{style:S.priceText,children:offer?pr.first:pr.box}),offer?/* @__PURE__ */jsx(Text,{style:S.strike,children:pr.box}):null,
|
|
276
|
+
/* @__PURE__ */jsx(Text,{style:[S.small,{textAlign:"right"}],children:copy.priceLine(pr)})]})]}),
|
|
277
|
+
/* @__PURE__ */jsxs(Pressable,{onPress:()=>setMode("once"),accessibilityRole:"radio",accessibilityState:{checked:buyMode==="once"},accessibilityLabel:copy.once,style:[S.opt,buyMode==="once"?S.optOn:null],testID:"health-plan-opt-once",children:[
|
|
278
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
279
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:copy.once}),
|
|
280
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:copy.onceLine(pr)})]}),
|
|
281
|
+
/* @__PURE__ */jsx(View,{style:S.price,children:/* @__PURE__ */jsx(Text,{style:S.priceText,children:pr.once})})]})]}):null,showBuy?shop?shopButton(kit,pickInCart?copy.viewCart:copy.addToCart((buyMode==="sub"?pr.first:pr.once)??""),()=>addToCart(item,buyMode),{disabled:sub.phase==="loading"&&props.subscriptions!==false,testID:"health-plan-buy"}):shopButton(kit,buyMode==="sub"?copy.subscribe:copy.buyOnce(pr),press,{disabled:sub.phase==="loading"&&props.subscriptions!==false||redirecting,testID:"health-plan-buy"}):null,pk.proof&&!active?/* @__PURE__ */jsx(Text,{style:S.fine,children:pk.proof}):null,trust.length>0?/* @__PURE__ */jsx(View,{style:S.trust,testID:"health-plan-trust",children:trust.map(t=>/* @__PURE__ */jsxs(View,{style:S.trustItem,children:[icon(t.icon),
|
|
282
|
+
/* @__PURE__ */jsx(Text,{style:S.trustText,children:t.label})]},t.label))}):null,active&&subscription!==null?/* @__PURE__ */jsxs(View,{style:S.on,testID:"health-plan-subscribed",children:[icon("check",P.clearInk),
|
|
283
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
284
|
+
/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.bold],children:copy.subscribed}),
|
|
285
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:copy.subscribedLine(pr,nextBoxDay(subscription))})]}),shopLink(kit,copy.manage,()=>setSheet({kind:"manage"}),"health-plan-manage")]}):null,pk.more&&props.onMore?shopLink(kit,pk.more,()=>props.onMore&&callHost(props.onMore,item)):null,pk.fine?/* @__PURE__ */jsx(Text,{style:S.fine,children:pk.fine}):null]})]}),others.length>0&&!waiting?/* @__PURE__ */jsx(View,{testID:"health-plan-others",children:others.map(o=>{let once=fmt(o.price,o.currency),op={petName:petName,productName:o.title,first:once,box:once,once:once,onceDiscountPercent:0,intervalDays:0,discountPercent:0,offer:false},buyable=once!==null&&(shop||everfur||partnerBuys);/* @__PURE__ */
|
|
286
|
+
return jsxs(View,{style:S.card,testID:`health-plan-other-${o.productId}`,children:[
|
|
287
|
+
/* @__PURE__ */jsxs(View,{style:S.pickTop,children:[o.imageUrl?img(o.imageUrl,S.pickImage):/* @__PURE__ */jsx(View,{style:S.pickImage}),
|
|
288
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1,gap:2}],children:[props.showCategory===true&&o.category!==null?/* @__PURE__ */jsx(Text,{style:S.mini,children:o.category}):null,
|
|
289
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:o.title}),o.sample?tag(HEALTH_PLAN_COPY.sample):null,o.description?/* @__PURE__ */jsx(Text,{style:S.line,children:o.description}):null]})]}),buyable?shop?shopButton(kit,inCart(o.productId)?copy.viewCart:copy.addToCart(once),()=>addToCart(o,"once"),{testID:`health-plan-other-buy-${o.productId}`}):shopButton(kit,copy.buyOnce(op),()=>pressOther(o),{disabled:redirecting,testID:`health-plan-other-buy-${o.productId}`}):null]},o.productId)})}):null,waiting?null:design.signs?/* @__PURE__ */jsxs(View,{testID:"health-plan-signs",children:[sectionHead(design.signs.title),design.signs.items.map(s=>/* @__PURE__ */jsxs(View,{style:[S.sign,s.urgent?S.signUrgent:null],children:[
|
|
290
|
+
/* @__PURE__ */jsxs(View,{style:S.row,children:[s.urgent?icon("alert",P.riskInk):null,
|
|
291
|
+
/* @__PURE__ */jsx(Text,{style:[S.h4,S.shrink,s.urgent?S.signUrgentTitle:null],children:s.title})]}),
|
|
292
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,children:s.body})]},s.title)),checkupBody("kicker"),connectRow]}):design.checkup?/* @__PURE__ */jsxs(View,{testID:"health-plan-checkup",children:[checkupBody("section"),connectRow]}):connectRow,!waiting&&design.extras&&design.extras.items.length>0?/* @__PURE__ */jsxs(View,{testID:"health-plan-extras",children:[
|
|
293
|
+
/* @__PURE__ */jsx(Text,{style:[S.sectionTitle,{marginTop:14}],accessibilityRole:"header",children:design.extras.title}),design.extras.items.map(x=>{let product=shop&&x.productId!==void 0?itemOf2(x.productId):void 0;if(product===void 0&&props.onExtra===void 0)return null;let on=product!==void 0?inCart(product.productId)!==void 0:extras.has(x.key);/* @__PURE__ */
|
|
294
|
+
return jsxs(View,{style:S.extra,children:[x.imageUrl?img(x.imageUrl,S.iconTile):x.icon?/* @__PURE__ */jsx(View,{style:S.iconTile,children:icon(x.icon)}):null,
|
|
295
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
296
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:x.title}),x.body?/* @__PURE__ */jsx(Text,{style:S.small,children:x.body}):null,x.price?/* @__PURE__ */jsxs(View,{style:[S.row,{flexWrap:"wrap"}],children:[
|
|
297
|
+
/* @__PURE__ */jsx(Text,{style:[S.smallInk,S.bold],children:x.price}),x.was?/* @__PURE__ */jsx(Text,{style:S.strike,children:x.was}):null,tag(x.tag)]}):null]}),
|
|
298
|
+
/* @__PURE__ */jsx(Pressable,{onPress:()=>{if(product!==void 0){addToCart(product,"once");return}let next=!on;setExtras(prev=>{let out=new Set(prev);return next?out.add(x.key):out.delete(x.key),out}),props.onExtra&&callHost(props.onExtra,x.key,next)},accessibilityRole:"button",accessibilityState:{selected:on},accessibilityLabel:product!==void 0&&on?copy.viewCart:on?x.added:x.action,style:[S.extraGo,on?S.addOn:null],children:/* @__PURE__ */jsx(Text,{tier:"control",style:[S.addText,on?S.addOnText:null],children:product!==void 0&&on?copy.viewCart:on?x.added:x.action})})]},x.key)})]}):null,design.fine?/* @__PURE__ */jsx(Text,{style:S.pageFine,children:design.fine}):null]});function press(){if(trackCheckoutStarted(telemetry,petRef,{count:1,subtotal:item.price,currency:item.price===null?null:item.currency}),!canSubscribe){everfur?redirect("one_box",null):buyOnce();return}tapKey.current=null,setSheet({kind:"checkout",mode:buyMode,every:quote.defaultIntervalDays})}function pressOther(target){trackCheckoutStarted(telemetry,petRef,{count:1,subtotal:target.price,currency:target.price===null?null:target.currency}),everfur?redirect("one_box",null,target):buyOnce(target)}let close=()=>setSheet(null),productBlock=line=>/* @__PURE__ */jsxs(View,{style:S.pickTop,children:[item.imageUrl?img(item.imageUrl,S.shopImage):/* @__PURE__ */jsx(View,{style:S.shopImage}),
|
|
299
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
300
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:item.title}),line===""?null:/* @__PURE__ */jsx(Text,{style:S.small,children:line})]})]}),intervals=(selected,pick2)=>/* @__PURE__ */jsx(View,{style:S.chips,accessibilityRole:"radiogroup",accessibilityLabel:copy.shipsEvery,children:(quote?.intervalOptions??subscription?.intervalOptions??[]).map(d=>/* @__PURE__ */jsx(Pressable,{onPress:sub.busy?void 0:()=>pick2(d),disabled:sub.busy,accessibilityRole:"radio",accessibilityState:{checked:selected===d,disabled:sub.busy},accessibilityLabel:copy.days(d),style:[S.chipButton,selected===d?S.optOn:null],testID:`health-plan-every-${d}`,children:/* @__PURE__ */jsx(Text,{style:S.smallInk,children:copy.days(d)})},d))}),sheetBody=null,kicker="";if(sheet?.kind==="checkout"&"e!==null){kicker=copy.checkoutKicker;let isSub=sheet.mode==="sub",cp=prices(sheet.every),today=isSub?cp.first:cp.once,coFine=[isSub?copy.renews(cp):copy.onceFine,copy.checkoutNote].filter(x=>x!=="").join(" ");sheetBody=/* @__PURE__ */jsxs(View,{style:{gap:12},testID:"health-plan-checkout-sheet",children:[
|
|
301
|
+
/* @__PURE__ */jsx(Text,{style:S.h3,accessibilityRole:"header",children:copy.checkoutTitle(cp)}),productBlock(pk.checkoutLine??pk.line??item.description??""),
|
|
302
|
+
/* @__PURE__ */jsxs(View,{style:S.opts,accessibilityRole:"radiogroup",accessibilityLabel:copy.optionsLabel,children:[
|
|
303
|
+
/* @__PURE__ */jsxs(Pressable,{onPress:()=>setSheet({...sheet,mode:"sub"}),accessibilityRole:"radio",accessibilityState:{checked:isSub},accessibilityLabel:copy.subscribe,style:[S.opt,{flexDirection:"column"},isSub?S.optOn:null],children:[
|
|
304
|
+
/* @__PURE__ */jsxs(View,{style:[S.row,{justifyContent:"space-between",alignSelf:"stretch"}],children:[
|
|
305
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:copy.subscribe}),
|
|
306
|
+
/* @__PURE__ */jsxs(View,{style:S.row,children:[
|
|
307
|
+
/* @__PURE__ */jsx(Text,{style:S.priceText,children:cp.first}),offer?/* @__PURE__ */jsx(Text,{style:S.strike,children:cp.box}):null]})]}),offer?/* @__PURE__ */jsx(Text,{style:S.small,children:copy.checkoutOffer(cp)}):null]}),isSub?/* @__PURE__ */jsxs(View,{children:[
|
|
308
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:copy.shipsEvery}),intervals(sheet.every,d=>setSheet({...sheet,every:d}))]}):null,
|
|
309
|
+
/* @__PURE__ */jsxs(Pressable,{onPress:()=>setSheet({...sheet,mode:"once"}),accessibilityRole:"radio",accessibilityState:{checked:!isSub},accessibilityLabel:copy.buyOnceOption,style:[S.opt,{flexDirection:"column"},isSub?null:S.optOn],children:[
|
|
310
|
+
/* @__PURE__ */jsxs(View,{style:[S.row,{justifyContent:"space-between",alignSelf:"stretch"}],children:[
|
|
311
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:copy.buyOnceOption}),
|
|
312
|
+
/* @__PURE__ */jsxs(View,{style:S.row,children:[
|
|
313
|
+
/* @__PURE__ */jsx(Text,{style:S.priceText,children:cp.once}),cp.onceDiscountPercent>0?/* @__PURE__ */jsx(Text,{style:S.strike,children:cp.box}):null]})]}),oneBox!==null?/* @__PURE__ */jsx(Text,{style:S.small,children:copy.onceOffer(cp)}):null]})]}),shopRows(kit,rows),shopButton(kit,copy.checkoutGo(cp,isSub,today??""),()=>{(async()=>{if(everfur){await redirect(isSub?"subscription":"one_box",isSub?sheet.every:null);return}if(!isSub){if(oneBox===null){close(),buyOnce();return}tapKey.current===null&&(tapKey.current=mintTapKey());let res=await sub.buyOneBox(tapKey.current);if(!res.ok){say(res.error.displayMessage);return}tapKey.current=null,props.onOneBoxOrder&&callHost(props.onOneBoxOrder,res.value),setSheet(null),placed([res.value]);return}let s=settle(await sub.subscribe(sheet.every));s!==null&&(setSheet(null),setStarted({kind:"sub",sub:s}))})()},{disabled:sub.busy||redirecting,testID:"health-plan-checkout-go"}),coFine===""?null:/* @__PURE__ */jsx(Text,{style:S.fine,children:coFine})]})}else if(sheet?.kind==="manage"&&subscription!==null&&active){kicker=copy.manageKicker;let mp=prices(subscription.intervalDays);sheetBody=/* @__PURE__ */jsxs(View,{style:{gap:12},testID:"health-plan-manage-sheet",children:[
|
|
314
|
+
/* @__PURE__ */jsx(Text,{style:S.h3,accessibilityRole:"header",children:copy.manageTitle(mp)}),productBlock(copy.subscribedLine(mp,nextBoxDay(subscription))),
|
|
315
|
+
/* @__PURE__ */jsxs(View,{children:[
|
|
316
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:copy.shipsEvery}),intervals(subscription.intervalDays,d=>{d!==subscription.intervalDays&&sub.changeInterval(d).then(settle)})]}),shopButton(kit,copy.skip,()=>{sub.skip().then(res=>{let s=settle(res);s!==null&&say(copy.skipped(prices(s.intervalDays),nextBoxDay(s)))})},{ghost:true,disabled:sub.busy,testID:"health-plan-skip"}),shopLink(kit,copy.cancel,()=>{sub.cancel().then(res=>{settle(res)!==null&&(setSheet(null),setMode("sub"),say(copy.cancelled(mp)))})},"health-plan-cancel")]})}else if(sheet?.kind==="cartCheckout"&&batch.length>0){kicker=copy.checkoutKicker;let total=fmt(batchTotal,currency)??"";sheetBody=shopCartCheckout(kit,batch.map(lineView),x=>{let line=lines.find(l=>l.productId===x.key),unit=line===void 0?null:unitOf(line);return unit===null||line===void 0?null:fmt(Math.round(unit*line.qty*100)/100,isPick(line.productId)?currency:itemOf2(line.productId)?.currency??currency)},rows,total,batchRenew,{label:copy.placeOrder(total,batchSub!==null),disabled:!cartReady||sub.busy||redirecting,onPress:()=>{placeCart()}},[copy.cartFine(batchRenew),apart?copy.cartSubscriptionApart:"",copy.checkoutNote].filter(x=>x!=="").join(" "))}else sheet?.kind==="weight"&&(kicker=copy.weightKicker,sheetBody=/* @__PURE__ */jsxs(View,{style:{gap:12},testID:"health-plan-weight-sheet",children:[
|
|
317
|
+
/* @__PURE__ */jsx(Text,{style:S.h3,accessibilityRole:"header",children:copy.weightTitle(pr)}),
|
|
318
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,children:copy.weightBody}),
|
|
319
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:copy.weightField}),
|
|
320
|
+
/* @__PURE__ */jsxs(View,{style:S.row,children:[
|
|
321
|
+
/* @__PURE__ */jsx(TextInput,{value:weightInput,onChangeText:setWeightInput,keyboardType:"decimal-pad",placeholder:"0.0",accessibilityLabel:copy.weightField,onSubmitEditing:()=>{saveWeight()},style:S.input,testID:"health-plan-weight-input"}),
|
|
322
|
+
/* @__PURE__ */jsx(Text,{style:S.h4,children:kg?"kg":copy.weightUnit})]}),weightError===""?null:/* @__PURE__ */jsx(Text,{style:S.noticeText,accessibilityLiveRegion:"polite",testID:"health-plan-weight-error",children:weightError}),shopButton(kit,copy.weightSave,()=>{saveWeight()},{disabled:savingWeight,testID:"health-plan-weight-save"})]}));let sheetNode=sheetBody===null?null:/* @__PURE__ */jsx(Modal,{visible:true,transparent:true,animationType:"slide",onRequestClose:close,testID:"health-plan-sheet",children:/* @__PURE__ */jsxs(View,{style:S.scrim,children:[
|
|
323
|
+
/* @__PURE__ */jsx(Pressable,{style:{flex:1},onPress:close,accessibilityRole:"button",accessibilityLabel:copy.close}),
|
|
324
|
+
/* @__PURE__ */jsxs(View,{style:S.sheet,accessibilityViewIsModal:true,children:[
|
|
325
|
+
/* @__PURE__ */jsx(View,{style:S.sheetGrab}),
|
|
326
|
+
/* @__PURE__ */jsxs(View,{style:S.sheetTop,children:[
|
|
327
|
+
/* @__PURE__ */jsx(Text,{style:S.mini,children:kicker}),
|
|
328
|
+
/* @__PURE__ */jsx(Pressable,{onPress:close,accessibilityRole:"button",accessibilityLabel:copy.close,style:S.close,testID:"health-plan-sheet-close",children:icon("x")})]}),
|
|
329
|
+
/* @__PURE__ */jsx(ScrollView,{keyboardShouldPersistTaps:"handled",children:sheetBody})]})]})}),backRow=onOverlayChange===void 0?/* @__PURE__ */jsxs(Pressable,{onPress:back,accessibilityRole:"button",accessibilityLabel:copy.back,style:S.back,testID:"health-plan-back",children:[
|
|
330
|
+
/* @__PURE__ */jsx(View,{style:{transform:[{scaleX:-1}]},children:icon("chev")}),
|
|
331
|
+
/* @__PURE__ */jsx(Text,{tier:"control",style:S.toolLabel,children:copy.back})]}):null,screenNode=null;if(started!==null){let run=started.kind==="sub"?started.sub:null,boughtId=started.kind==="sub"?started.sub.productId:started.order.productId,boughtItem=planItems.find(x=>x.productId===boughtId)??item,sp=prices(run?.intervalDays??every,boughtItem.title),label=(step,first)=>step.step==="first_box_ships"&&first?copy.tomorrow:day(step.on)??step.on,steps=run===null?[{icon:"truck",when:copy.tomorrow,what:copy.firstBoxShips}]:run.timeline.map((step,i)=>{switch(step.step){case"first_box_ships":return{icon:"truck",when:label(step,i===0),what:copy.firstBoxShips};case"checkin":return{icon:"chat",when:label(step,false),what:copy.checkin(pk.checkin??null)};case"refill_reminder":return{icon:"repeat",when:label(step,false),what:copy.refill};default:return{icon:"calendar",when:label(step,false),what:copy.nextBoxShips(sp)}}}),doneTitle=run===null?copy.orderedTitle(sp):copy.startedTitle(sp);screenNode=/* @__PURE__ */jsxs(View,{style:S.screen,testID:"health-plan-started",children:[backRow,
|
|
332
|
+
/* @__PURE__ */jsxs(View,{style:S.done,children:[
|
|
333
|
+
/* @__PURE__ */jsx(View,{style:S.doneCheck,children:icon("check",P.clearInk)}),
|
|
334
|
+
/* @__PURE__ */jsx(Text,{style:S.doneTitle,accessibilityRole:"header",children:doneTitle}),copy.startedWhat(sp).trim()===""?null:/* @__PURE__ */jsx(Text,{style:S.doneWhen,children:copy.startedWhat(sp)}),copy.startedNote?/* @__PURE__ */jsx(Text,{style:S.small,children:copy.startedNote}):null,
|
|
335
|
+
/* @__PURE__ */jsx(View,{style:S.next,accessibilityLabel:copy.startedSteps,children:steps.map(r=>/* @__PURE__ */jsxs(View,{style:S.nextRow,children:[
|
|
336
|
+
/* @__PURE__ */jsx(View,{style:S.nextIcon,children:icon(r.icon)}),
|
|
337
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
338
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:r.when}),
|
|
339
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,children:r.what})]})]},`${r.icon}${r.when}`))})]}),shopButton(kit,copy.startedDone,()=>setStarted(null),{testID:"health-plan-started-done"})]})}else if(top!==void 0){let shopDay=iso=>formatShopDay(iso,locale),money2=(amount,cur)=>fmt(amount,cur),toOrders=()=>push({kind:"orders"}),body=null,foot=null;if(top.kind==="cart")body=shopCartBody(kit,views,fmt(cartTotal,currency)??"",renewPrices,pr,{onQuantity:(key,by)=>editLine(key,x=>({...x,qty:Math.max(1,Math.min(cartOn&&!lineSub(x)?5:1,x.qty+by))})),onRemove:key=>{editLine(key,()=>null),say(copy.removedFromCart(itemOf2(key)?.title??""))},onMode:(key,m)=>editLine(key,x=>({...x,mode:m,qty:1})),onEvery:(key,d)=>editLine(key,x=>({...x,every:d})),onOrders:toOrders}),foot=views.length===0?shopButton(kit,copy.startedDone,closeOverlays):/* @__PURE__ */jsxs(Fragment,{children:[shopButton(kit,copy.checkoutCart(fmt(cartTotal,currency)??""),()=>setSheet({kind:"cartCheckout"}),{disabled:!cartReady,testID:"health-plan-cart-checkout"}),!cartReady&©.cartOneAtATime!==""?/* @__PURE__ */jsx(Text,{style:S.fine,children:copy.cartOneAtATime}):null]});else if(top.kind==="orders"||top.kind==="order"){let subCard=subscription!==null&&active?{name:subscription.title??item.title,imageUrl:item.imageUrl??null,next:nextBoxDay(subscription),every:subscription.intervalDays,onManage:()=>setSheet({kind:"manage"})}:null;if(top.kind==="orders")body=shopOrdersBody(kit,{subscription:subCard,orders:allOrders,loaded:everfurOrders.loaded,fmt:money2,day:shopDay,onOpen:key=>push({kind:"order",key:key}),onBack:closeOverlays,petPrices:pr,more:everfurOrders.next===null?null:{onMore:moreOrders,loading:everfurOrders.loading}});else{let order=allOrders.find(o=>o.key===top.key),again=order?.everfur===true&&order.productId!==null?itemOf2(order.productId):void 0;body=order===void 0?null:shopOrderBody(kit,{order:order,fmt:money2,day:shopDay,rows:rows.map(r=>r.label===PAY_WITH?{...r,label:copy.paidWith}:r),onBuyAgain:again===void 0?null:()=>addToCart(again,"once"),onHelp:props.onOrderHelp?()=>props.onOrderHelp&&callHost(props.onOrderHelp,order.key):null})}}else{let placedOrders=top.orders,first=placedOrders[0],op=prices(every,first?.title??(first?itemOf2(first.productId)?.title:void 0)??item.title),one=xs=>{let known=[...new Set(xs.filter(x=>x!=null))];return known.length===1?known[0]??null:null},placedNo=one(placedOrders.map(o=>o.tracking?.orderNumber)),arrives=placedOrders.length>0&&placedOrders.every(o=>o.tracking?.estimatedDelivery)?one(placedOrders.map(o=>o.tracking?.estimatedDelivery)):null,arrivesDay=day(arrives),placedCurrency=one(placedOrders.map(o=>o.currency)),placedTotal=placedCurrency===null?null:fmt(Math.round(placedOrders.reduce((sum,o)=>sum+(o.total??o.price),0)*100)/100,placedCurrency);body=/* @__PURE__ */jsxs(View,{style:S.done,testID:"health-plan-placed",children:[
|
|
340
|
+
/* @__PURE__ */jsx(View,{style:S.doneCheck,children:icon("check",P.clearInk)}),
|
|
341
|
+
/* @__PURE__ */jsx(Text,{style:S.doneTitle,accessibilityRole:"header",children:copy.orderedTitle(op)}),arrivesDay===null?null:/* @__PURE__ */jsx(Text,{style:S.doneWhen,children:copy.arrivesBy(arrivesDay)}),placedNo===null?null:/* @__PURE__ */jsx(Text,{style:S.small,children:copy.orderTitle(placedNo)}),
|
|
342
|
+
/* @__PURE__ */jsxs(View,{style:S.next,accessibilityLabel:copy.placedSteps,children:[placedOrders.map(o=>{let it=itemOf2(o.productId);/* @__PURE__ */
|
|
343
|
+
return jsxs(View,{style:S.nextRow,children:[
|
|
344
|
+
/* @__PURE__ */jsx(View,{style:S.nextIcon,children:icon("box")}),
|
|
345
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
346
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:copy.cartItemQuantity(o.quantity??1)}),
|
|
347
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,children:o.title??it?.title??""})]})]},o.orderId)}),
|
|
348
|
+
/* @__PURE__ */jsxs(View,{style:S.nextRow,children:[
|
|
349
|
+
/* @__PURE__ */jsx(View,{style:S.nextIcon,children:icon("truck")}),
|
|
350
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
351
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:copy.tomorrow}),
|
|
352
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,children:copy.placedShips})]})]}),arrivesDay===null?null:/* @__PURE__ */jsxs(View,{style:S.nextRow,children:[
|
|
353
|
+
/* @__PURE__ */jsx(View,{style:S.nextIcon,children:icon("calendar")}),
|
|
354
|
+
/* @__PURE__ */jsxs(View,{style:[S.shrink,{flex:1}],children:[
|
|
355
|
+
/* @__PURE__ */jsx(Text,{style:S.small,children:arrivesDay}),
|
|
356
|
+
/* @__PURE__ */jsx(Text,{style:S.smallInk,children:copy.placedArrives})]})]})]}),placedOrders.length>1&&placedTotal!==null?/* @__PURE__ */jsx(View,{style:{alignSelf:"stretch"},children:shopSummary(kit,placedTotal)}):null,copy.startedNote?/* @__PURE__ */jsx(Text,{style:S.fine,children:copy.startedNote}):null]}),foot=/* @__PURE__ */jsxs(Fragment,{children:[shopButton(kit,placedOrders.length===1?copy.viewOrder:copy.seeOrders,()=>setScreens(placedOrders.length===1&&first!==void 0?[{kind:"order",key:first.orderId}]:[{kind:"orders"}]),{testID:"health-plan-placed-view"}),shopButton(kit,copy.startedDone,closeOverlays,{ghost:true})]})}screenNode=/* @__PURE__ */jsxs(View,{style:S.screen,testID:`health-plan-screen-${top.kind}`,children:[backRow,onOverlayChange===void 0&&title!==void 0?/* @__PURE__ */jsx(Text,{style:S.h3,accessibilityRole:"header",children:title}):null,toastNode,top.kind==="cart"&&cartNotice!==null&&cartNotice!==""?/* @__PURE__ */jsx(View,{style:S.notice,accessibilityLiveRegion:"polite",testID:"health-plan-cart-notice",children:/* @__PURE__ */jsx(Text,{style:S.noticeText,children:cartNotice})}):null,body,foot]})}/* @__PURE__ */
|
|
357
|
+
return jsxs(Fragment,{children:[screenNode??pageNode,sheetNode]})}function HealthPlanItemCard(props){let{item:item,onToggle:onToggle,pending:pending=false,error:error=null,imageVariant:imageVariant=HEALTH_PLAN_LAYOUT_DEFAULTS.imageVariant,reasonVariant:reasonVariant=HEALTH_PLAN_LAYOUT_DEFAULTS.reasonVariant,priceFormat:priceFormat,renderFooter:renderFooter,showCategory:showCategory=HEALTH_PLAN_LAYOUT_DEFAULTS.showCategory,cardShadow:cardShadow=HEALTH_PLAN_LAYOUT_DEFAULTS.cardShadow,cardBorder:cardBorder=HEALTH_PLAN_LAYOUT_DEFAULTS.cardBorder,addButtonSize:addButtonSize=HEALTH_PLAN_LAYOUT_DEFAULTS.addButtonSize,addButtonFontSize:addButtonFontSize,addedVariant:addedVariant=HEALTH_PLAN_LAYOUT_DEFAULTS.addedVariant,categoryVariant:categoryVariant=HEALTH_PLAN_LAYOUT_DEFAULTS.categoryVariant,cardPadding:cardPadding,itemTitleSize:itemTitleSize,itemTitleWeight:itemTitleWeight,priceSize:priceSize,priceWeight:priceWeight,reasonTextSize:reasonTextSize,reasonLabelWidth:reasonLabelWidth,reasonGap:reasonGap,style:style}=guardHostProps(props,["onToggle"]),theme=useEverfurTheme(),styles=useMemo(()=>makeStyles3(theme),[theme]),sized=(size,weight)=>{let px=healthPlanLength(size),fontSize=px===null||px===0?null:{fontSize:px,lineHeight:Math.round(px*theme.type.lineHeight.snug)};return fontSize===null&&weight===void 0?null:{...fontSize,...weight===void 0?null:{fontWeight:String(weight)}}},titleSized=sized(itemTitleSize,itemTitleWeight),priceSized=sized(priceSize,priceWeight),reasonSized=sized(reasonTextSize),labelWidth=healthPlanLength(reasonLabelWidth),labelGap=healthPlanLength(reasonGap),padding=healthPlanLength(cardPadding),shadow=useMemo(()=>cardShadowStyle(cardShadow,styles.cardShadow,theme),[cardShadow,styles,theme]),price=formatHealthPlanPriceWith(item.price,item.currency,priceFormat),thumbnail=imageVariant==="thumbnail",rows=reasonVariant==="rows",priceNode=price===null?null:/* @__PURE__ */jsx(Text,{style:[styles.price,priceSized],children:price}),category=showCategory&&item.category!==null?/* @__PURE__ */jsx(Text,{...categoryVariant==="label"?{tier:"compact"}:{},style:categoryVariant==="label"?styles.categoryLabel:styles.category,testID:`health-plan-category-${item.productId}`,children:item.category}):null,full=addButtonSize==="full",{height:height,hit:hit}=healthPlanAddButtonHeight(addButtonSize),slop=(hit-height)/2,fontPx=healthPlanLength(addButtonFontSize),pillStyle=full?styles.add:[styles.addCompact,{minHeight:height,paddingHorizontal:height>=40?theme.space.lg:theme.space.md}],pillLabel=pressed=>[full||height>=40?styles.addLabel:styles.addCompactLabel,pressed?styles.addPressedLabel:null,fontPx===null||fontPx===0?null:{fontSize:fontPx,lineHeight:Math.round(fontPx*theme.type.lineHeight.snug)}],hitSlop=slop>0?{top:slop,bottom:slop,left:0,right:0}:void 0,title=/* @__PURE__ */jsx(Text,{style:[thumbnail?styles.thumbTitle:styles.title,titleSized],accessibilityRole:"header",children:item.title}),sample=item.sample?/* @__PURE__ */jsx(View,{style:styles.sample,children:/* @__PURE__ */jsx(Text,{tier:"badge",style:styles.sampleLabel,children:HEALTH_PLAN_COPY.sample})}):null,description=item.description===null?null:/* @__PURE__ */jsx(Text,{style:styles.body,children:item.description}),control=item.inPlan&&addedVariant==="pressed"?
|
|
358
|
+
/* @__PURE__ */jsx(Pressable,{onPress:()=>onToggle?.(false),disabled:pending,accessibilityRole:"button",accessibilityLabel:HEALTH_PLAN_COPY.added,accessibilityState:{disabled:pending,busy:pending,selected:true},style:[pillStyle,styles.addPressed,pending?styles.dimmed:null],...hitSlop?{hitSlop:hitSlop}:{},testID:`health-plan-added-${item.productId}`,children:/* @__PURE__ */jsx(Text,{tier:"control",style:pillLabel(true),children:HEALTH_PLAN_COPY.added})}):item.inPlan?/* @__PURE__ */jsxs(View,{style:styles.row,children:[
|
|
359
|
+
/* @__PURE__ */jsx(Text,{style:styles.added,children:HEALTH_PLAN_COPY.added}),
|
|
360
|
+
/* @__PURE__ */jsx(Pressable,{onPress:()=>onToggle?.(false),disabled:pending,accessibilityRole:"button",accessibilityLabel:HEALTH_PLAN_COPY.remove,accessibilityState:{disabled:pending,busy:pending},style:styles.remove,testID:`health-plan-remove-${item.productId}`,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles.removeLabel,children:HEALTH_PLAN_COPY.remove})})]}):/* @__PURE__ */jsx(Pressable,{onPress:()=>onToggle?.(true),disabled:pending,accessibilityRole:"button",accessibilityLabel:HEALTH_PLAN_COPY.addToCart,accessibilityState:{disabled:pending,busy:pending,...addedVariant==="pressed"?{selected:false}:{}},style:[pillStyle,pending?styles.dimmed:null],...hitSlop?{hitSlop:hitSlop}:{},testID:`health-plan-add-${item.productId}`,children:/* @__PURE__ */jsx(Text,{tier:"control",style:pillLabel(false),children:HEALTH_PLAN_COPY.addToCart})});/* @__PURE__ */
|
|
361
|
+
return jsxs(View,{style:[styles.card,shadow,cardBorder?null:styles.cardNoBorder,padding===null?null:{padding:padding},style],accessibilityState:{busy:pending},testID:`health-plan-item-${item.productId}`,children:[thumbnail?/* @__PURE__ */jsxs(View,{style:styles.thumbHead,testID:`health-plan-thumb-head-${item.productId}`,children:[item.imageUrl===null?null:/* @__PURE__ */jsx(Image,{source:{uri:item.imageUrl},style:styles.thumb,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),
|
|
362
|
+
/* @__PURE__ */jsxs(View,{style:styles.thumbCopy,children:[category,title,sample,description]})]}):/* @__PURE__ */jsxs(Fragment,{children:[item.imageUrl===null?null:/* @__PURE__ */jsx(Image,{source:{uri:item.imageUrl},style:styles.image,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),category,
|
|
363
|
+
/* @__PURE__ */jsxs(View,{style:styles.head,children:[title,priceNode]}),sample,description]}),item.reasons.map((reason,index)=>/* @__PURE__ */jsxs(View,{style:[rows?styles.reasonRow:styles.reason,labelGap===null?null:{gap:labelGap}],testID:`health-plan-reason-${rows?"row":"pill"}`,children:[
|
|
364
|
+
/* @__PURE__ */jsx(Text,{tier:"compact",style:[rows?styles.reasonRowKind:styles.reasonKind,rows&&labelWidth!==null?{width:labelWidth}:null],children:HEALTH_PLAN_REASON_LABELS[reason.kind]}),
|
|
365
|
+
/* @__PURE__ */jsx(Text,{style:[rows?styles.reasonRowText:styles.reasonText,reasonSized],children:reason.text})]},`${reason.kind}-${index}`)),renderFooter===void 0?null:/* @__PURE__ */jsx(HostRender,{resetKey:item,render:()=>renderFooter(item),fallback:null}),thumbnail?/* @__PURE__ */jsxs(View,{style:styles.actionRow,children:[priceNode,control]}):control,error===null?null:/* @__PURE__ */jsx(Text,{style:styles.error,accessibilityLiveRegion:"polite",children:error.displayMessage})]})}var THUMB_SIZE=64,COMPACT_HEIGHT=32,REASON_LABEL_WIDTH=72;function cardShadowStyle(shadow,soft,theme){if(shadow===true)return soft;if(shadow===void 0||shadow===false)return null;let spec=typeof shadow=="string"?parseHealthPlanShadow(shadow):shadow;if(spec===null)return null;let rgba=toRgba(spec.color);if(rgba===null)return null;let blur=Math.max(0,spec.blur);return{shadowColor:`rgb(${rgba.r}, ${rgba.g}, ${rgba.b})`,shadowOffset:{width:spec.offsetX??0,height:spec.offsetY},shadowRadius:blur/2,shadowOpacity:Math.min(1,Math.max(0,rgba.a*(spec.opacity??1))),elevation:Math.max(0,Math.min(theme.space.lg,Math.round(blur/2)))}}function makeStyles3(theme){let{color:color,radius:radius,space:space,type:type,slots:slots}=theme,text2=(size,ink,weight)=>({...face(theme,weight),fontSize:size,lineHeight:Math.round(size*type.lineHeight.snug),color:ink}),cardInk=slots.planCard?.textColor??slots.card?.textColor,reasonLabelInk=slots.planReasonLabel?.textColor??slots.chip?.textColor??color.brandInk;return StyleSheet.create({card:{gap:space.sm,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,...slotBox(slots.card,1),...slotBox(slots.planCard,1)},cardShadow:{shadowColor:color.shadow,shadowOffset:{width:0,height:space.xs},shadowRadius:space.md,shadowOpacity:.08,elevation:space.xs},cardNoBorder:{borderWidth:0},category:text2(type.size.caption,cardInk??color.text.secondary,"regular"),categoryLabel:{...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:Math.round(type.size.micro*type.lineHeight.snug),letterSpacing:type.letterSpacing.monoWide,textTransform:"uppercase",color:reasonLabelInk},image:{width:"100%",aspectRatio:4/3,borderRadius:radius.md,backgroundColor:color.surfaceSubtle},thumbHead:{flexDirection:"row",alignItems:"flex-start",gap:space.md},thumb:{width:THUMB_SIZE,height:THUMB_SIZE,borderRadius:radius.md,backgroundColor:color.surfaceSubtle},thumbCopy:{flex:1,gap:space.xs},thumbTitle:text2(type.size.body,cardInk??color.text.primary,"bold"),actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},reasonRow:{flexDirection:"row",alignItems:"flex-start",gap:space.lg},reasonRowKind:{width:REASON_LABEL_WIDTH,paddingTop:2,...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:Math.round(type.size.micro*type.lineHeight.snug),letterSpacing:type.letterSpacing.monoWide,textTransform:"uppercase",color:reasonLabelInk},reasonRowText:{flex:1,...text2(type.size.caption,cardInk??color.text.secondary,"regular")},head:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.sm},title:{flex:1,...text2(type.size.body,cardInk??color.text.primary,"bold")},price:text2(type.size.body,cardInk??color.text.primary,"bold"),sample:{alignSelf:"flex-start",paddingHorizontal:space.sm,paddingVertical:2,borderRadius:radius.pill,backgroundColor:color.badgeBgNeutral},sampleLabel:text2(type.size.caption,color.text.secondary,"bold"),body:text2(type.size.caption,cardInk??color.text.secondary,"regular"),reason:{flexDirection:"row",alignItems:"baseline",gap:space.sm,paddingHorizontal:space.sm,paddingVertical:space.xs,borderRadius:radius.md,backgroundColor:color.brandSofter,...slotBox(slots.chip,1)},reasonKind:{...text2(type.size.caption,color.brandInk,"bold"),textTransform:"uppercase",letterSpacing:.4,...slotText(slots.chip)},reasonText:{flex:1,...text2(type.size.caption,color.text.secondary,"regular"),...slotText(slots.chip)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},added:text2(type.size.caption,color.brandInk,"bold"),add:{minHeight:44,paddingHorizontal:space.lg,borderRadius:radius.pill,alignItems:"center",justifyContent:"center",backgroundColor:color.brand,...slotBox(slots.primaryButton)},addLabel:{...text2(type.size.body,color.text.onBrand,"bold"),...slotText(slots.primaryButton)},addCompact:{minHeight:COMPACT_HEIGHT,alignSelf:"flex-start",paddingHorizontal:space.md,borderRadius:radius.pill,alignItems:"center",justifyContent:"center",backgroundColor:color.brand,...slotBox(slots.primaryButton)},addCompactLabel:{...text2(type.size.caption,color.text.onBrand,"bold"),...slotText(slots.primaryButton)},addPressed:{backgroundColor:color.brandInk,borderWidth:0},addPressedLabel:{color:readableOn(color.brandInk)},remove:{minHeight:44,justifyContent:"center"},removeLabel:{...text2(type.size.caption,color.linkInk,"bold"),...slotText(slots.link)},dimmed:{opacity:.5},error:text2(type.size.caption,color.errorRed,"regular")})}function EverfurHealthPlan(props){let guarded=guardHostProps(props,["onCheckout"]),theme=useEverfurTheme(),styles=useMemo(()=>makeStyles4(theme),[theme]),{lifecycle:lifecycle,refreshKey:refreshKey,presentation:presentation,focus:focus,onAvailabilityChange:onAvailabilityChange,...bodyProps}=guarded,layout=useEverfurPresentation(presentation?.healthPlanLayout===void 0?void 0:{healthPlanLayout:presentation.healthPlanLayout}).healthPlanLayout,plan=useEverfurHealthPlan({...guarded.petRef===void 0?{}:{petRef:guarded.petRef},...lifecycle===void 0?{}:{lifecycle:lifecycle},...refreshKey===void 0?{}:{refreshKey:refreshKey}});return plan.status==="signedOut"?/* @__PURE__ */jsx(View,{style:[styles.page,guarded.style],children:/* @__PURE__ */jsx(Text,{style:styles.body,children:HEALTH_PLAN_COPY.signedOut})}):/* @__PURE__ */jsx(CapabilityGate,{capability:"healthPlan",...guarded.renderDisabled?{renderDisabled:guarded.renderDisabled}:{},style:guarded.style,children:/* @__PURE__ */jsx(PlanBody,{...bodyProps,plan:plan,styles:styles,focusLayout:layout==="focus_plan",...focus===void 0?{}:{focus:focus},...onAvailabilityChange===void 0?{}:{onAvailabilityChange:onAvailabilityChange},...lifecycle===void 0?{}:{lifecycle:lifecycle},...refreshKey===void 0?{}:{refreshKey:refreshKey}})})}function useAvailability(available,onChange){useEffect(()=>{available===null||onChange===void 0||callHost(onChange,available)},[available,onChange])}function Refused({error:error,retry:retry,renderNotice:renderNotice,styles:styles,style:style}){let signIn=isHealthPlanSessionRequired(error),line=signIn?HEALTH_PLAN_COPY.signedOut:error?.displayMessage??"";/* @__PURE__ */
|
|
366
|
+
return jsx(View,{style:style,children:/* @__PURE__ */jsxs(View,{style:styles.notice,accessibilityLiveRegion:"polite",children:[error===null?null:/* @__PURE__ */jsx(HostRender,{resetKey:error,render:()=>renderNotice?renderNotice(error):/* @__PURE__ */jsx(Text,{style:styles.noticeText,children:line}),fallback:/* @__PURE__ */jsx(Text,{style:styles.noticeText,children:line})}),signIn?null:/* @__PURE__ */jsx(Pressable,{onPress:retry,accessibilityRole:"button",accessibilityLabel:HEALTH_PLAN_COPY.retry,style:styles.retry,testID:"health-plan-retry",children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles.retryLabel,children:HEALTH_PLAN_COPY.retry})})]})})}function Loading({styles:styles,style:style}){let theme=useEverfurTheme();/* @__PURE__ */
|
|
367
|
+
return jsx(View,{style:[styles.page,style],accessible:true,accessibilityRole:"progressbar",accessibilityLabel:HEALTH_PLAN_COPY.loading,children:/* @__PURE__ */jsx(ActivityIndicator,{color:theme.color.brandInk})})}function FocusBody({plan:plan,focus:focus,styles:styles,style:style,petName:petName,petSpecies:petSpecies,onCheckout:onCheckout,renderNotice:renderNotice,priceFormat:priceFormat,showCategory:showCategory,lifecycle:lifecycle,refreshKey:refreshKey,onAvailable:onAvailable,list:list}){let fromBackend=focus.design===void 0,page=useHealthPlanPage({petRef:plan.petRef,enabled:fromBackend,...focus.pageRepository?{repository:focus.pageRepository}:{},...lifecycle===void 0?{}:{lifecycle:lifecycle},...refreshKey===void 0?{}:{refreshKey:refreshKey}}),design=focus.design,checkout,weightKnown=focus.weightKnown,name=petName,sex=focus.petSex??null,species=petSpecies,vetReviewed=false,pageTexts=false,state="ready";fromBackend&&(page.phase==="failed"?state=isHealthPlanSessionRequired(page.error)?"failed":"list":page.missing?state="list":page.page===null?state="loading":page.page.page===null?state="list":(design=page.page.page,checkout=page.page.checkout,weightKnown??=page.page.pet.weightKg!==null,name=page.page.pet.name??petName,sex=page.page.pet.sex??sex,species=page.page.pet.species??petSpecies,vetReviewed=page.page.vetReviewed===true,pageTexts=page.page.trackingTextsEnabled===true));let items=plan.plan?.items??[],pick2=design?.pick,picked=pick2===void 0?void 0:items.find(item=>pick2.productId!==void 0&&item.productId===pick2.productId)??items.find(item=>pick2.partnerSku!==void 0&&item.partnerSku===pick2.partnerSku)??items[0];if(state==="ready"&&(design===void 0||picked===void 0||plan.petRef===null)&&(state="hidden"),useEffect(()=>{onAvailable(state==="ready"||state==="list"?true:state==="hidden"?false:null)},[state,onAvailable]),state==="list")return list;if(state==="failed")/* @__PURE__ */return jsx(Refused,{error:page.error,retry:()=>{page.refresh()},renderNotice:renderNotice,styles:styles,style:[styles.page,style]});if(state==="loading")/* @__PURE__ */return jsx(Loading,{styles:styles,style:style});if(state==="hidden"||design===void 0||picked===void 0||plan.petRef===null)return null;let onWeightSaved=focus.onWeightSaved,pageRefresh=page.refresh;/* @__PURE__ */
|
|
368
|
+
return jsx(HealthPlanFocus,{...focus,design:design,...checkout?{checkout:checkout}:{},...weightKnown===void 0?{}:{weightKnown:weightKnown},...fromBackend?{onWeightSaved:kg=>{onWeightSaved&&callHost(onWeightSaved,kg),pageRefresh()}}:{},item:picked,others:items.filter(item=>item!==picked),...showCategory!==void 0?{showCategory:showCategory}:{},...lifecycle===void 0?{}:{lifecycle:lifecycle},...refreshKey===void 0?{}:{refreshKey:refreshKey},petRef:plan.petRef,petName:name,petSex:sex,species:species,fromBackend:fromBackend,vetReviewed:vetReviewed,trackingTexts:pageTexts||plan.plan?.trackingTextsEnabled===true,...onCheckout?{onCheckout:onCheckout}:{},...priceFormat?{priceFormat:priceFormat}:{},style:style},plan.petRef)}function PlanBody({plan:plan,styles:styles,onCheckout:onCheckout,renderNotice:renderNotice,style:style,imageVariant:imageVariant,reasonVariant:reasonVariant,cartBarVisibility:cartBarVisibility,priceFormat:priceFormat,renderHeader:renderHeader,renderItemFooter:renderItemFooter,renderFooter:renderFooter,titleSize:titleSize,titleGap:titleGap,sectionGap:sectionGap,cartBarPlacement:cartBarPlacement,titleLineHeight:titleLineHeight,renderBetweenItems:renderBetweenItems,focusLayout:focusLayout,focus:focus,onAvailabilityChange:onAvailabilityChange,lifecycle:lifecycle,refreshKey:refreshKey,...cardProps}){let theme=useEverfurTheme(),{pets:pets}=useEverfurPets(),pet=pets.find(p=>p.petRef===plan.petRef),petName=pet?.name??null,[focusAvailable,setFocusAvailable]=useState(null);useAvailability(plan.status==="empty"?false:plan.status==="ready"?focusLayout?focusAvailable:true:null,onAvailabilityChange);let title=plan.plan?.headline??(petName===null?null:HEALTH_PLAN_TEMPLATES.planTitle(petName)),docked=cartBarPlacement==="none";usePublishHealthPlanCart(docked&&plan.status==="ready",plan.cart,plan.pending.length>0,plan.petRef,plan.plan,plan.setInPlan);let telemetry=useHealthPlanTelemetry();useHealthPlanOpened(plan.status==="ready"||plan.status==="empty",plan.petRef,plan.plan);let gap=healthPlanLength(sectionGap),pageStyle=gap===null?styles.page:[styles.page,{gap:gap}],size=healthPlanLength(titleSize),ratio=healthPlanLength(titleLineHeight),titleStyle=[styles.title,size===null||size===0?null:{fontSize:size,lineHeight:Math.round(size*theme.type.lineHeight.snug)},ratio===null||ratio===0?null:{lineHeight:Math.round((size===null||size===0?theme.type.size.heading:size)*ratio)},{marginBottom:healthPlanTitleOffset(titleGap,gap??theme.space.lg)}],heading=title===null?null:/* @__PURE__ */jsx(Text,{style:titleStyle,accessibilityRole:"header",children:title}),writes=useMemo(()=>healthPlanWrites(plan.plan,plan.setInPlan),[plan.plan,plan.setInPlan]),context={petRef:plan.petRef,plan:plan.plan,cart:plan.cart,...writes},cardOptions=pickHealthPlanCardOptions(cardProps),between=(index,item)=>renderBetweenItems===void 0||index===0?null:/* @__PURE__ */jsx(HostRender,{resetKey:item,render:()=>renderBetweenItems(index,item),fallback:null}),header=renderHeader===void 0?null:/* @__PURE__ */jsx(HostRender,{resetKey:plan.plan,render:()=>renderHeader(context),fallback:null});if(plan.status==="noPet")/* @__PURE__ */
|
|
369
|
+
return jsx(View,{style:[pageStyle,style],children:/* @__PURE__ */jsx(Text,{style:styles.body,children:HEALTH_PLAN_COPY.choosePet})});if(plan.status==="loading")/* @__PURE__ */return jsx(Loading,{styles:styles,style:[gap===null?null:{gap:gap},style]});if(plan.status==="failed")/* @__PURE__ */return jsx(Refused,{error:plan.error,retry:()=>{plan.refresh()},renderNotice:renderNotice,styles:styles,style:[pageStyle,style]});if(plan.status==="empty")return null;let items=plan.plan?.items??[],list=/* @__PURE__ */jsxs(View,{style:[pageStyle,style],children:[heading,header,items.map((item,index)=>/* @__PURE__ */jsxs(Fragment$1,{children:[between(index,item),
|
|
370
|
+
/* @__PURE__ */jsx(HealthPlanItemCard,{item:item,pending:plan.pending.includes(item.productId),error:plan.itemErrors[item.productId]??null,onToggle:inPlan=>{trackProductClicked(telemetry,plan.petRef,item.productId,inPlan),plan.setInPlan(item.productId,inPlan)},...imageVariant?{imageVariant:imageVariant}:{},...reasonVariant?{reasonVariant:reasonVariant}:{},...priceFormat?{priceFormat:priceFormat}:{},...renderItemFooter?{renderFooter:renderItemFooter}:{},...cardOptions})]},item.productId)),renderFooter===void 0?null:/* @__PURE__ */jsx(HostRender,{resetKey:plan.plan,render:()=>renderFooter(context),fallback:null}),!docked&&showHealthPlanCartBar(cartBarVisibility,plan.cart.count)?/* @__PURE__ */jsx(HealthPlanPetScope,{petRef:plan.petRef,children:/* @__PURE__ */jsx(HealthPlanCartBar,{cart:plan.cart,busy:plan.pending.length>0,...onCheckout?{onCheckout:onCheckout}:{},...priceFormat?{priceFormat:priceFormat}:{}})}):null]});return focusLayout?/* @__PURE__ */jsx(FocusBody,{plan:plan,focus:focus??{},styles:styles,style:style,petName:petName,petSpecies:pet?.species??null,onCheckout:onCheckout,renderNotice:renderNotice,priceFormat:priceFormat,showCategory:cardOptions.showCategory,lifecycle:lifecycle,refreshKey:refreshKey,onAvailable:setFocusAvailable,list:list}):list}function makeStyles4(theme){let{color:color,space:space,type:type}=theme,text2=(size,ink,weight)=>({...face(theme,weight),fontSize:size,lineHeight:Math.round(size*type.lineHeight.snug),color:ink});return StyleSheet.create({page:{gap:space.lg,padding:space.lg},title:{...text2(type.size.heading,color.text.primary,"bold"),...headingFace(theme,"bold")},subtitle:text2(type.size.body,color.text.primary,"bold"),body:text2(type.size.body,color.text.secondary,"regular"),notice:{gap:space.xs},noticeText:text2(type.size.caption,color.errorRed,"regular"),retry:{minHeight:44,justifyContent:"center",alignSelf:"flex-start"},retryLabel:text2(type.size.caption,color.linkInk,"bold")})}export{EverfurHealthPlan,HEALTH_PLAN_COPY,HEALTH_PLAN_COPY_PLACEHOLDERS,HEALTH_PLAN_FOCUS_COPY,HEALTH_PLAN_FOCUS_RN_COPY,HEALTH_PLAN_LAYOUT_DEFAULTS,HEALTH_PLAN_REASON_KINDS,HEALTH_PLAN_REASON_LABELS,HEALTH_PLAN_TEMPLATES,HealthPlanCartBar,HealthPlanCartScope,HealthPlanController,HealthPlanFocus,HealthPlanItemCard,createHealthPlanPageRepository,createHealthPlanPageRepositoryOver,createHealthPlanRepository,createHealthPlanRepositoryOver,formatHealthPlanDay,formatHealthPlanPrice,formatHealthPlanPriceWith,healthPlanCart,healthPlanCheckoutRefusal,healthPlanCheckoutSessionFromWire,healthPlanCheckoutStateFromWire,healthPlanFocusDesignFromWire,healthPlanFromWire,healthPlanPageFromWire,healthPlanPetCopy,healthPlanPossessive,isHealthPlanSessionRequired,showHealthPlanCartBar,useEverfurHealthPlan,useEverfurHealthPlanRepository,useEverfurPresentation,useHealthPlanCartDock,useHealthPlanPage,useHealthPlanPageRepository};
|