@everfur/sdk 0.18.2 → 0.19.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 +124 -0
- package/README.md +6 -5
- package/dist/{Chat.d-BkLu9G00.d.ts → Chat.d-BHovj6Ku.d.ts} +1 -1
- package/dist/{Chat.d-B7iUVGmB.d.cts → Chat.d-BO-XtVYe.d.cts} +1 -1
- package/dist/{DepthViews.d-BiS-GTEf.d.cts → DepthViews.d-BwIkdmWZ.d.cts} +1 -1
- package/dist/{DepthViews.d-C-zs_BnZ.d.cts → DepthViews.d-Bx85LeiP.d.cts} +1 -1
- package/dist/{DepthViews.d-hXV6Ef0y.d.ts → DepthViews.d-CBUunxP1.d.ts} +1 -1
- package/dist/{DepthViews.d-C0DVqywN.d.ts → DepthViews.d-DKoZgF8l.d.ts} +1 -1
- package/dist/{IntakeMedia.d-4a89XrP7.d.ts → IntakeMedia.d-B_ZVDxh3.d.ts} +1 -1
- package/dist/{IntakeMedia.d-JJCUvQu7.d.cts → IntakeMedia.d-CnGzpllr.d.cts} +1 -1
- package/dist/{IntakeMedia.d-DGxrhgIW.d.ts → IntakeMedia.d-DNUAks9E.d.ts} +1 -1
- package/dist/{IntakeMedia.d-DUPR4lVM.d.cts → IntakeMedia.d-Dqc5V_YH.d.cts} +1 -1
- package/dist/{RecordsPage.d-BG_RDR1V.d.ts → RecordsPage.d-CsvBhU0f.d.ts} +1 -1
- package/dist/{RecordsPage.d-5rHMTDyY.d.cts → RecordsPage.d-DRFp2LXH.d.cts} +1 -1
- package/dist/animations/index.cjs +1 -94
- package/dist/animations/index.d.cts +3 -3
- package/dist/animations/index.d.ts +3 -3
- package/dist/animations/index.js +1 -94
- package/dist/{attachments.d-_mgNU-ur.d.ts → attachments.d-DOZjCdkb.d.ts} +2 -2
- package/dist/{attachments.d-DFbXLAYK.d.cts → attachments.d-DWUsHPf9.d.cts} +2 -2
- package/dist/{bookingCopy.d-RU8lNYJ4.d.ts → bookingCopy.d-BlMWlvgv.d.ts} +10 -3
- package/dist/{bookingCopy.d-0K1trjxx.d.cts → bookingCopy.d-tvO7y6MK.d.cts} +10 -3
- package/dist/{casesRepository.d-D2SQFL27.d.ts → casesRepository.d-C7qbrOL-.d.ts} +1 -1
- package/dist/{casesRepository.d-D7vIZ9oX.d.cts → casesRepository.d-sSo6oakf.d.cts} +1 -1
- package/dist/chat/index.cjs +29 -119
- package/dist/chat/index.d.cts +11 -10
- package/dist/chat/index.d.ts +11 -10
- package/dist/chat/index.js +30 -120
- package/dist/chat/lite/index.cjs +29 -119
- package/dist/chat/lite/index.d.cts +11 -10
- package/dist/chat/lite/index.d.ts +11 -10
- package/dist/chat/lite/index.js +30 -120
- package/dist/{attachments.d-D7f7OfPE.d.ts → chatHandoffToken.d-C4tEyuCT.d.ts} +33 -9
- package/dist/{attachments.d-HmRqizDG.d.cts → chatHandoffToken.d-D6GUoBvs.d.cts} +33 -9
- package/dist/{ports.d-RKc2C07X.d.ts → chatTypes.d-BI4vidgu.d.ts} +41 -52
- package/dist/{ports.d-CB9YZT2L.d.cts → chatTypes.d-CSyw9em_.d.cts} +41 -52
- package/dist/client/index.cjs +2 -95
- package/dist/client/index.d.cts +7 -7
- package/dist/client/index.d.ts +7 -7
- package/dist/client/index.js +2 -95
- package/dist/{clinicBatch.d-BN1jfVGo.d.cts → clinicBatch.d-BxA_uGBb.d.cts} +2 -2
- package/dist/{clinicBatch.d-BhaCdstU.d.ts → clinicBatch.d-T5oSAhY-.d.ts} +2 -2
- package/dist/{config.d-D_k_rNZZ.d.ts → config.d-N5Xzy53V.d.ts} +1 -1
- package/dist/{config.d-BFTqU7ft.d.cts → config.d-jCmrhM4a.d.cts} +1 -1
- package/dist/consent/index.cjs +1 -94
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/consent/index.js +1 -94
- package/dist/{context.d-B4LODPF1.d.ts → context.d-BJEpEERH.d.ts} +7 -6
- package/dist/{context.d-D2fhrjAM.d.cts → context.d-l4HkFJI8.d.cts} +7 -6
- package/dist/{copy.d-Bn9eIgkW.d.ts → copy.d-hFRaovog.d.ts} +2 -2
- package/dist/{copy.d-DjYhMxxS.d.cts → copy.d-hS49oJ4w.d.cts} +2 -2
- package/dist/core/index.cjs +6 -99
- package/dist/core/index.d.cts +14 -13
- package/dist/core/index.d.ts +14 -13
- package/dist/core/index.js +6 -99
- package/dist/{depth.d-CsKZkLNi.d.cts → depth.d-BYwddMNU.d.cts} +2 -2
- package/dist/{depth.d-DlaIV8TV.d.ts → depth.d-C99_xup2.d.ts} +2 -2
- package/dist/{entitlementRepository.d-CpIRpfzy.d.cts → entitlementRepository.d-CiU_QIPL.d.cts} +2 -2
- package/dist/{entitlementRepository.d-C5d_6QMi.d.ts → entitlementRepository.d-qZAlET7C.d.ts} +2 -2
- package/dist/{focus.d-DOlAaNIU.d.ts → focus.d-CG6KhDBK.d.ts} +2 -2
- package/dist/{focus.d-DdBbwzjP.d.cts → focus.d-RJMXplJc.d.cts} +2 -2
- package/dist/health-plan/index.cjs +1 -94
- package/dist/health-plan/index.d.cts +9 -9
- package/dist/health-plan/index.d.ts +9 -9
- package/dist/health-plan/index.js +1 -94
- package/dist/{idempotency.d-CmQc1OUv.d.ts → idempotency.d-D-ZWpO9p.d.ts} +1 -1
- package/dist/{idempotency.d-P4O5lNBq.d.cts → idempotency.d-DJyOZDPb.d.cts} +1 -1
- package/dist/{identity.d-BmbAwQYx.d.cts → identity.d-CA7mW59I.d.cts} +1 -1
- package/dist/{identity.d-BZXPu9Hi.d.ts → identity.d-DIOnFzXL.d.ts} +1 -1
- package/dist/index.cjs +30 -120
- package/dist/index.d.cts +14 -13
- package/dist/index.d.ts +14 -13
- package/dist/index.js +31 -121
- package/dist/{introEvents.d-Bqw2Hcpt.d.cts → introEvents.d-7wNDMhEF.d.cts} +1 -1
- package/dist/{introEvents.d-Cy8yxOoe.d.ts → introEvents.d-BjqfFgE1.d.ts} +1 -1
- package/dist/notifications/inbox/index.cjs +44 -0
- package/dist/notifications/inbox/index.d.cts +50 -0
- package/dist/notifications/inbox/index.d.ts +50 -0
- package/dist/notifications/inbox/index.js +44 -0
- package/dist/notifications/index.cjs +18 -98
- package/dist/notifications/index.d.cts +12 -6
- package/dist/notifications/index.d.ts +12 -6
- package/dist/notifications/index.js +18 -98
- package/dist/{optInView.d-wGSNOB86.d.ts → optInView.d-B5v4cDDW.d.ts} +2 -2
- package/dist/{optInView.d-DXj2w4KU.d.cts → optInView.d-BQhHPleh.d.cts} +2 -2
- package/dist/parse.d-DYsx1Q2V.d.cts +168 -0
- package/dist/parse.d-Do0sdAgm.d.ts +168 -0
- package/dist/{pets.d-CP13kAFa.d.cts → pets.d-DRqMaP8A.d.cts} +1 -1
- package/dist/{pets.d-tqGZP3Co.d.ts → pets.d-DVrOb-Bj.d.ts} +1 -1
- package/dist/{petsRepository.d-CLyzuoo4.d.ts → petsRepository.d-CpYWRWFq.d.ts} +1 -1
- package/dist/{petsRepository.d-CyerzD5G.d.cts → petsRepository.d-tZADfKA1.d.cts} +1 -1
- package/dist/photo/index.cjs +1 -94
- package/dist/photo/index.js +1 -94
- package/dist/records/depth/index.cjs +1 -94
- package/dist/records/depth/index.d.cts +9 -9
- package/dist/records/depth/index.d.ts +9 -9
- package/dist/records/depth/index.js +1 -94
- package/dist/records/index.cjs +2 -95
- package/dist/records/index.d.cts +10 -10
- package/dist/records/index.d.ts +10 -10
- package/dist/records/index.js +2 -95
- package/dist/{requestFunnel.d-BPWf5SQf.d.ts → requestFunnel.d-B8OVGh0p.d.ts} +2 -2
- package/dist/{requestFunnel.d-DocT7FXR.d.cts → requestFunnel.d-C4abgvt9.d.cts} +2 -2
- package/dist/{parse.d-MQST1RP3.d.ts → route.d-BAZqGLfl.d.ts} +90 -53
- package/dist/{parse.d-C9_UMXfA.d.cts → route.d-CTf8h9vS.d.cts} +90 -53
- package/dist/{runtimeTypes.d-CkwEMpy8.d.cts → runtimeTypes.d-DbaQKGLv.d.cts} +39 -5
- package/dist/{runtimeTypes.d-D4Cjjf_C.d.ts → runtimeTypes.d-DrIz5e6L.d.ts} +39 -5
- package/dist/{screenProps.d-DNTTp7hU.d.ts → screenProps.d-BP8LAZWn.d.ts} +1 -1
- package/dist/{screenProps.d-Byla6nJL.d.cts → screenProps.d-Di3wYGCn.d.cts} +1 -1
- package/dist/server/events/index.cjs +2 -95
- package/dist/server/events/index.d.cts +122 -4
- package/dist/server/events/index.d.ts +122 -4
- package/dist/server/events/index.js +2 -95
- package/dist/server/index.cjs +2 -95
- package/dist/server/index.d.cts +3 -3
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +2 -95
- package/dist/shop/index.d.cts +3 -3
- package/dist/shop/index.d.ts +3 -3
- package/dist/tabs/index.cjs +3 -96
- package/dist/tabs/index.d.cts +6 -6
- package/dist/tabs/index.d.ts +6 -6
- package/dist/tabs/index.js +3 -96
- package/dist/televet/booking/index.cjs +11 -103
- package/dist/televet/booking/index.d.cts +13 -11
- package/dist/televet/booking/index.d.ts +13 -11
- package/dist/televet/booking/index.js +11 -103
- package/dist/televet/index.cjs +1 -94
- package/dist/televet/index.d.cts +3 -3
- package/dist/televet/index.d.ts +3 -3
- package/dist/televet/index.js +1 -94
- package/dist/{televetGlobal.d-CC-DrqkQ.d.ts → televetGlobal.d-B0_jbCtC.d.ts} +7 -0
- package/dist/{televetGlobal.d-CKwDCbmN.d.cts → televetGlobal.d-BWYJR391.d.cts} +7 -0
- package/dist/testing/index.cjs +1 -94
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -94
- package/dist/testing/rn/index.cjs +1 -94
- package/dist/testing/rn/index.d.cts +8 -7
- package/dist/testing/rn/index.d.ts +8 -7
- package/dist/testing/rn/index.js +1 -94
- package/dist/testing/web/index.cjs +1 -94
- package/dist/testing/web/index.d.cts +8 -7
- package/dist/testing/web/index.d.ts +8 -7
- package/dist/testing/web/index.js +1 -94
- package/dist/texting/index.cjs +1 -94
- package/dist/texting/index.d.cts +5 -5
- package/dist/texting/index.d.ts +5 -5
- package/dist/texting/index.js +1 -94
- package/dist/{threadOptions.d-jgk_sHrj.d.ts → threadOptions.d-Cwmyu8pc.d.ts} +2 -2
- package/dist/{threadOptions.d-CIrevUL8.d.cts → threadOptions.d-REwBuXAY.d.cts} +2 -2
- package/dist/{timelineRows.d-BST14weg.d.ts → timelineRows.d-CTlGQTB0.d.ts} +1 -1
- package/dist/{timelineRows.d-BEjiHpkP.d.cts → timelineRows.d-CongJG58.d.cts} +1 -1
- package/dist/unreadStore.d-gCsleb6l.d.ts +74 -0
- package/dist/unreadStore.d-w5x6lEpR.d.cts +74 -0
- package/dist/{useHealthPlanSubscription.d-C9kh4mvk.d.ts → useHealthPlanSubscription.d-BSo5kFT9.d.ts} +2 -2
- package/dist/{useHealthPlanSubscription.d-CYJi9ZNE.d.cts → useHealthPlanSubscription.d-Br7GKHTt.d.cts} +2 -2
- package/dist/useInboxUnread.d-Blxu00eY.d.ts +206 -0
- package/dist/useInboxUnread.d-pi6FNnK-.d.cts +206 -0
- package/dist/{usePresentation.d-COEh8Xa1.d.cts → usePresentation.d-C6ci1s3j.d.cts} +1 -1
- package/dist/{usePresentation.d-WA3sfMpz.d.ts → usePresentation.d-yd9Gh4GB.d.ts} +1 -1
- package/dist/{useRecordsDepth.d-DZfdRdIU.d.cts → useRecordsDepth.d-BIDVPfx7.d.cts} +1 -1
- package/dist/{useRecordsDepth.d-CAYnVYl1.d.ts → useRecordsDepth.d-C5snbNxR.d.ts} +1 -1
- package/dist/{appStateLifecycle.d-_TM06yEk.d.cts → useUnread.d-CORommFJ.d.cts} +49 -14
- package/dist/{appStateLifecycle.d-7H_2a9it.d.ts → useUnread.d-w0dKMnx7.d.ts} +49 -14
- package/dist/video/index.cjs +1 -94
- package/dist/video/index.js +1 -94
- package/dist/{view.d-D8soknYh.d.ts → view.d-CK2UN4qn.d.ts} +3 -3
- package/dist/{view.d-eM315KIZ.d.cts → view.d-DUhKppyl.d.cts} +3 -3
- package/dist/web/consent/index.cjs +1 -94
- package/dist/web/consent/index.d.cts +5 -5
- package/dist/web/consent/index.d.ts +5 -5
- package/dist/web/consent/index.js +1 -94
- package/dist/web/health-plan/index.cjs +1 -94
- package/dist/web/health-plan/index.d.cts +11 -11
- package/dist/web/health-plan/index.d.ts +11 -11
- package/dist/web/health-plan/index.js +1 -94
- package/dist/web/inbox/index.cjs +49 -0
- package/dist/web/inbox/index.d.cts +191 -0
- package/dist/web/inbox/index.d.ts +191 -0
- package/dist/web/inbox/index.js +49 -0
- package/dist/web/index.cjs +28 -118
- package/dist/web/index.d.cts +76 -36
- package/dist/web/index.d.ts +76 -36
- package/dist/web/index.js +28 -118
- package/dist/web/intro/index.cjs +3 -96
- package/dist/web/intro/index.d.cts +6 -6
- package/dist/web/intro/index.d.ts +6 -6
- package/dist/web/intro/index.js +3 -96
- package/dist/web/notifications/index.cjs +16 -96
- package/dist/web/notifications/index.d.cts +8 -3
- package/dist/web/notifications/index.d.ts +8 -3
- package/dist/web/notifications/index.js +16 -96
- package/dist/web/records/depth/index.cjs +1 -94
- package/dist/web/records/depth/index.d.cts +9 -9
- package/dist/web/records/depth/index.d.ts +9 -9
- package/dist/web/records/depth/index.js +1 -94
- package/dist/web/records/index.cjs +1 -94
- package/dist/web/records/index.d.cts +11 -11
- package/dist/web/records/index.d.ts +11 -11
- package/dist/web/records/index.js +1 -94
- package/dist/web/records-sheet/index.cjs +2 -95
- package/dist/web/records-sheet/index.js +2 -95
- package/dist/web/shop/index.d.cts +3 -3
- package/dist/web/shop/index.d.ts +3 -3
- package/dist/web/televet/booking/index.cjs +9 -102
- package/dist/web/televet/booking/index.d.cts +18 -11
- package/dist/web/televet/booking/index.d.ts +18 -11
- package/dist/web/televet/booking/index.js +9 -102
- package/dist/web/televet/index.cjs +1 -94
- package/dist/web/televet/index.d.cts +3 -3
- package/dist/web/televet/index.d.ts +3 -3
- package/dist/web/televet/index.js +1 -94
- package/dist/web/texting/index.cjs +1 -94
- package/dist/web/texting/index.d.cts +5 -5
- package/dist/web/texting/index.d.ts +5 -5
- package/dist/web/texting/index.js +1 -94
- package/notifications/inbox/package.json +8 -0
- package/package.json +29 -1
- package/web/inbox/native-blocked.cjs +12 -0
- package/web/inbox/package.json +8 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
|
|
2
|
+
import { CSSProperties, ReactNode } from 'react';
|
|
3
|
+
import { P as PetRef, U as UserRef } from '../../ids.d-B2GAAifq.js';
|
|
4
|
+
export { B as Brand, C as ConversationId, R as RecordsRequestId, _ as __brand } from '../../ids.d-B2GAAifq.js';
|
|
5
|
+
import { L as LifecyclePort } from '../../LifecyclePort.d-Cr1p33a7.js';
|
|
6
|
+
import { E as EverfurInboxOpenHandler, a as EverfurInboxCopy, U as UseEverfurInboxOptions, b as EverfurInboxState, c as UseEverfurInboxUnreadOptions, d as EverfurInboxUnread, g as EverfurInboxOpen } from '../../useInboxUnread.d-Blxu00eY.js';
|
|
7
|
+
export { e as EverfurInboxClient, f as EverfurInboxItem, h as EverfurInboxPage, i as EverfurInboxQuery, j as EverfurInboxSnapshot, k as EverfurInboxStatus, l as EverfurInboxTarget, I as InboxRuntime, m as createInboxClient, u as useEverfurInboxClient } from '../../useInboxUnread.d-Blxu00eY.js';
|
|
8
|
+
import { g as EverfurNotificationTarget } from '../../parse.d-Do0sdAgm.js';
|
|
9
|
+
export { d as EverfurNotification, f as EverfurNotificationEventType, h as EverfurNotificationTargetKind } from '../../parse.d-Do0sdAgm.js';
|
|
10
|
+
import { E as EverfurResult } from '../../EverfurResult.d-D_-254ZY.js';
|
|
11
|
+
import { E as ErrorPolicyPort } from '../../ErrorPolicyPort.d-68yrE3BE.js';
|
|
12
|
+
import { A as AuthContext } from '../../identity.d-DIOnFzXL.js';
|
|
13
|
+
export { I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-DIOnFzXL.js';
|
|
14
|
+
export { V as VetVisitIntent } from '../../visitIntent.d-D7_yVp1I.js';
|
|
15
|
+
export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config.d-N5Xzy53V.js';
|
|
16
|
+
export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode } from '../../EverfurError.d-8NHtlgzA.js';
|
|
17
|
+
|
|
18
|
+
interface EverfurInboxProps {
|
|
19
|
+
/** A tapped item, marked read. Route its target; return `false` to have the inbox show it instead. */
|
|
20
|
+
readonly onOpen?: EverfurInboxOpenHandler;
|
|
21
|
+
/** Open this item on its own at mount (the item of a tapped push you did not route). */
|
|
22
|
+
readonly initialItemId?: string | null;
|
|
23
|
+
/**
|
|
24
|
+
* Open the item of this event on its own at mount, for a tapped push that named no item (`initialItemId` wins when
|
|
25
|
+
* both are set).
|
|
26
|
+
*/
|
|
27
|
+
readonly initialEventId?: string | null;
|
|
28
|
+
/** Only this pet's items. Absent, every item of the member. */
|
|
29
|
+
readonly petRef?: PetRef | null;
|
|
30
|
+
/** Items per page, 1 to 50 (default 20). */
|
|
31
|
+
readonly pageSize?: number;
|
|
32
|
+
/** When to read again (see `useEverfurInbox`). */
|
|
33
|
+
readonly lifecycle?: LifecyclePort | null;
|
|
34
|
+
/** Any of the inbox's words, over the defaults. */
|
|
35
|
+
readonly copy?: Partial<EverfurInboxCopy>;
|
|
36
|
+
/** The level of the inbox's heading, 1 to 6 (default 2). */
|
|
37
|
+
readonly headingLevel?: number;
|
|
38
|
+
/** Merged over the root's style. */
|
|
39
|
+
readonly style?: CSSProperties;
|
|
40
|
+
}
|
|
41
|
+
/** The member's Everfur inbox. */
|
|
42
|
+
declare function EverfurInbox(props: EverfurInboxProps): ReactNode;
|
|
43
|
+
|
|
44
|
+
/** The member's inbox: read on mount, on the page coming back and on a push; every verb settles. */
|
|
45
|
+
declare function useEverfurInbox(options?: UseEverfurInboxOptions): EverfurInboxState;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The member's unread inbox count, shared with `EverfurInbox`: read on mount, on the page coming back and on a push.
|
|
49
|
+
* For one badge with the chat, add it to `useEverfurUnread().unreadCount` from "@everfur/sdk/web".
|
|
50
|
+
*/
|
|
51
|
+
declare function useEverfurInboxUnread(options?: UseEverfurInboxUnreadOptions): EverfurInboxUnread;
|
|
52
|
+
|
|
53
|
+
/** What to register: the browser's push subscription, the page a tap opens, and the member's zone and language. */
|
|
54
|
+
interface WebPushSubscriptionInput {
|
|
55
|
+
/** `PushSubscription.endpoint`. */
|
|
56
|
+
readonly endpoint: string;
|
|
57
|
+
/** `PushSubscription.toJSON().keys`. */
|
|
58
|
+
readonly keys: {
|
|
59
|
+
readonly p256dh: string;
|
|
60
|
+
readonly auth: string;
|
|
61
|
+
};
|
|
62
|
+
/** The page a tapped notification opens (https; its origin must be one of your allowed embed origins). */
|
|
63
|
+
readonly openUrl: string;
|
|
64
|
+
/** IANA zone name (`America/Chicago`), for quiet hours; null when unknown. */
|
|
65
|
+
readonly timezone: string | null;
|
|
66
|
+
/** BCP 47 tag (`en-US`); null when unknown. */
|
|
67
|
+
readonly locale: string | null;
|
|
68
|
+
}
|
|
69
|
+
interface WebPushClient {
|
|
70
|
+
/** `GET .../web-push/config`. Settles the VAPID public key (base64url); the not-found error while web push is off. */
|
|
71
|
+
config(opts?: {
|
|
72
|
+
readonly signal?: AbortSignal;
|
|
73
|
+
}): Promise<EverfurResult<{
|
|
74
|
+
readonly vapidPublicKey: string;
|
|
75
|
+
}>>;
|
|
76
|
+
/** `POST .../web-push/subscriptions`. Idempotent on the endpoint. Settles Everfur's subscription id (`wps_...`). */
|
|
77
|
+
subscribe(input: WebPushSubscriptionInput): Promise<EverfurResult<{
|
|
78
|
+
readonly subscriptionId: string;
|
|
79
|
+
}>>;
|
|
80
|
+
/** `DELETE .../web-push/subscriptions/{id}`. Settles `ok(undefined)` on 204. */
|
|
81
|
+
unsubscribe(subscriptionId: string): Promise<EverfurResult<void>>;
|
|
82
|
+
}
|
|
83
|
+
/** The part of the runtime this client needs, read at call time. Any `EverfurRuntime` satisfies it. */
|
|
84
|
+
interface WebPushRuntime {
|
|
85
|
+
readonly isDisposed: boolean;
|
|
86
|
+
readonly registry: {
|
|
87
|
+
readonly services: {
|
|
88
|
+
authFor(userRef: UserRef | null): AuthContext;
|
|
89
|
+
readonly errorPolicy: ErrorPolicyPort | undefined;
|
|
90
|
+
};
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/** The client over the runtime under your provider. Auth is read at call time. */
|
|
94
|
+
declare function createWebPushClient(runtime: WebPushRuntime): WebPushClient;
|
|
95
|
+
|
|
96
|
+
/** Where web push stands for this browser and member. */
|
|
97
|
+
type EverfurWebPushState =
|
|
98
|
+
/** This browser has no web push (no service worker, no Push API, or an insecure page). */
|
|
99
|
+
'unsupported'
|
|
100
|
+
/** Web push is not switched on for your tenant. */
|
|
101
|
+
| 'unavailable'
|
|
102
|
+
/** The member blocked notifications for your site in the browser. */
|
|
103
|
+
| 'denied'
|
|
104
|
+
/** Not asked yet: `enable` from a button shows the browser's prompt. */
|
|
105
|
+
| 'ask'
|
|
106
|
+
/** Allowed, and not subscribed (or subscribed for another member): `enable` subscribes without a prompt. */
|
|
107
|
+
| 'off' | 'on';
|
|
108
|
+
/** How an `enable` ended. `dismissed`: the member closed the browser's prompt without choosing. */
|
|
109
|
+
type EverfurWebPushOutcome = 'on' | 'denied' | 'dismissed' | 'unavailable' | 'unsupported' | 'failed';
|
|
110
|
+
interface EverfurWebPushOptions {
|
|
111
|
+
/** The one-line service worker file on your origin (see the web push guide). Default `/everfur-sw.js`. */
|
|
112
|
+
readonly serviceWorkerPath?: string;
|
|
113
|
+
/** Its scope. Default `everfur-push/` beside the file, so your own service worker is never replaced. */
|
|
114
|
+
readonly scope?: string;
|
|
115
|
+
/**
|
|
116
|
+
* The page a tapped notification opens: https, on this page's origin (the service worker's own), and one of your
|
|
117
|
+
* allowed embed origins. Default: this page. Another origin settles `enable` and `sync` as 'failed' with a console
|
|
118
|
+
* warning, because the service worker would never open it.
|
|
119
|
+
*/
|
|
120
|
+
readonly openUrl?: string;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Where web push stands: the browser's state, `checking` while it is read, `signed_out` with no member. */
|
|
124
|
+
type EverfurWebPushStatus = EverfurWebPushState | 'checking' | 'signed_out';
|
|
125
|
+
interface EverfurWebPush {
|
|
126
|
+
readonly status: EverfurWebPushStatus;
|
|
127
|
+
/** An `enable` or `disable` is running. */
|
|
128
|
+
readonly busy: boolean;
|
|
129
|
+
/** Ask (from a click), subscribe and register. Settles how it ended; never throws. */
|
|
130
|
+
enable(): Promise<EverfurWebPushOutcome>;
|
|
131
|
+
/** Unregister and unsubscribe this browser. Settles false when Everfur could not be told (try again). */
|
|
132
|
+
disable(): Promise<boolean>;
|
|
133
|
+
}
|
|
134
|
+
/** Web push for the member under your provider. */
|
|
135
|
+
declare function useEverfurWebPush(options?: EverfurWebPushOptions): EverfurWebPush;
|
|
136
|
+
|
|
137
|
+
/** A tapped notification: its ids, and the inbox item ready to route, or null when Everfur has none for it. */
|
|
138
|
+
interface EverfurNotificationOpen {
|
|
139
|
+
readonly eventId: string | null;
|
|
140
|
+
readonly itemId: string | null;
|
|
141
|
+
readonly inbox: EverfurInboxOpen | null;
|
|
142
|
+
/**
|
|
143
|
+
* The push's own target, for when `inbox` is null (a push-only message, such as an answer ready in chat, keeps no
|
|
144
|
+
* inbox item). Null when `inbox` is not, and when the push carried none. A tap that opened the page brings it on
|
|
145
|
+
* the address, which anyone can link to: treat it as deep-link input, and have the screen it opens check the
|
|
146
|
+
* member's access on your server, never trust it because it came from a notification.
|
|
147
|
+
*/
|
|
148
|
+
readonly target: EverfurNotificationTarget | null;
|
|
149
|
+
}
|
|
150
|
+
/** A tap's routing block as the push sent it (`event_type` and the wire `target`), not yet read. */
|
|
151
|
+
interface EverfurNotificationRoute {
|
|
152
|
+
readonly event_type: string;
|
|
153
|
+
readonly target: Readonly<Record<string, unknown>>;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* A tapped web push as `takeEverfurNotificationOpen()` reads it off the address: its ids and, for a push kept in no
|
|
157
|
+
* inbox, its routing block. Plain JSON, to keep across a sign-in redirect (session storage) and pass back as the
|
|
158
|
+
* hook's `eventId`.
|
|
159
|
+
*/
|
|
160
|
+
interface EverfurNotificationTap {
|
|
161
|
+
readonly eventId: string | null;
|
|
162
|
+
readonly itemId: string | null;
|
|
163
|
+
readonly route?: EverfurNotificationRoute | null;
|
|
164
|
+
}
|
|
165
|
+
interface EverfurNotificationOpenOptions {
|
|
166
|
+
/** Called once per tap. A throw is swallowed. */
|
|
167
|
+
readonly onOpen: (open: EverfurNotificationOpen) => void;
|
|
168
|
+
/**
|
|
169
|
+
* The tap you read yourself, before your router read the URL: `takeEverfurNotificationOpen()`'s tap (kept across
|
|
170
|
+
* a sign-in redirect too; it is checked again here), or `takeEverfurNotificationEventId()`'s event id. Absent, the
|
|
171
|
+
* hook takes the tap off the address on mount; `null`, the address is not read.
|
|
172
|
+
*/
|
|
173
|
+
readonly eventId?: string | EverfurNotificationTap | null;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The event id of a tapped web push in this page's address, taken out of the address bar as it is read; null when
|
|
177
|
+
* there is none (or the push named only its inbox item). Call it once, early, before your router reads the URL, and
|
|
178
|
+
* pass it to `useEverfurNotificationOpen`; the hook picks up the item and target the same tap carried. To keep a tap
|
|
179
|
+
* across a sign-in redirect, use `takeEverfurNotificationOpen()`: an id alone loses a push-only message's target.
|
|
180
|
+
*/
|
|
181
|
+
declare function takeEverfurNotificationEventId(): string | null;
|
|
182
|
+
/**
|
|
183
|
+
* The tapped web push in this page's address (its ids, and the routing block of a push kept in no inbox), taken out
|
|
184
|
+
* of the address bar as it is read; null when there is none. Call it once, early, before your router reads the URL.
|
|
185
|
+
* Pass it as the hook's `eventId`, or keep it in session storage across a sign-in redirect and pass it after sign-in.
|
|
186
|
+
*/
|
|
187
|
+
declare function takeEverfurNotificationOpen(): EverfurNotificationTap | null;
|
|
188
|
+
/** Route taps on Everfur's web push notifications to `onOpen`. Signed out, a tap waits for the member to sign in. */
|
|
189
|
+
declare function useEverfurNotificationOpen(options: EverfurNotificationOpenOptions): void;
|
|
190
|
+
|
|
191
|
+
export { AuthContext, ErrorPolicyPort, EverfurInbox, EverfurInboxCopy, EverfurInboxOpen, EverfurInboxOpenHandler, type EverfurInboxProps, EverfurInboxState, EverfurInboxUnread, type EverfurNotificationOpen, type EverfurNotificationOpenOptions, type EverfurNotificationRoute, type EverfurNotificationTap, EverfurNotificationTarget, EverfurResult, type EverfurWebPush, type EverfurWebPushOptions, type EverfurWebPushOutcome, type EverfurWebPushState, type EverfurWebPushStatus, LifecyclePort, PetRef, UseEverfurInboxOptions, UseEverfurInboxUnreadOptions, UserRef, type WebPushClient, type WebPushRuntime, type WebPushSubscriptionInput, createWebPushClient, takeEverfurNotificationEventId, takeEverfurNotificationOpen, useEverfurInbox, useEverfurInboxUnread, useEverfurNotificationOpen, useEverfurWebPush };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
|
|
2
|
+
"use client";
|
|
3
|
+
import{createContext,useMemo,useRef,useEffect,useState,useCallback,useContext,useSyncExternalStore}from"react";import{jsx,jsxs,Fragment}from"react/jsx-runtime";function ok(value,warning){/* @__PURE__ */
|
|
4
|
+
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
5
|
+
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 INBOX_COPY=/* @__PURE__ */Object.freeze({title:"Notifications",loading:"Loading notifications",emptyTitle:"You’re all caught up",emptyBody:"Updates about your pet’s care will show up here.",errorTitle:"Could not load your notifications",errorBody:"Check your connection and try again.",retry:"Try again",rowFallbackTitle:"Notification",unreadPrefix:"Unread.",timeAgoSuffix:"ago",now:"Now",more:"Show more",detailErrorTitle:"Could not load this notification",detailErrorBody:"Check your connection and try again.",notFoundTitle:"This notification is no longer available",notFoundBody:"The notification may have expired or been removed.",back:"Back to inbox"});function inboxCopyWith(copy){if(copy===void 0)return INBOX_COPY;let out={...INBOX_COPY};for(let key2 of Object.keys(INBOX_COPY)){let value=copy[key2];typeof value=="string"&&value.trim().length>0&&(out[key2]=value)}/* @__PURE__ */
|
|
6
|
+
return Object.freeze(out)}function formatInboxTime(iso,nowMs,now){let date=new Date(iso),at2=date.getTime();if(Number.isNaN(at2))return null;let diff=nowMs-at2;if(diff<6e4)return now;if(diff<36e5)return`${Math.floor(diff/6e4)}m`;if(diff<864e5)return`${Math.floor(diff/36e5)}h`;if(diff<6048e5)return`${Math.floor(diff/864e5)}d`;if(diff<5*6048e5)return`${Math.floor(diff/6048e5)}w`;let sameYear=date.getFullYear()===new Date(nowMs).getFullYear();try{return date.toLocaleDateString("en-US",{month:"short",day:"numeric",...sameYear?{}:{year:"numeric"}})}catch{return date.toISOString().slice(0,10)}}function inboxTimeTakesAgo(label){return typeof label=="string"&&/^\d+[mhdw]$/.test(label)}function inboxRowLabel(parts,copy){let time=parts.time===null?null:inboxTimeTakesAgo(parts.time)?`${parts.time} ${copy.timeAgoSuffix}`:parts.time;return[parts.unread?copy.unreadPrefix:null,parts.title,parts.body.length>0?parts.body:null,time].filter(part=>part!==null).join(" ")}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}}function inboxRows(items,nowMs,copy){return items.map(item=>{let title=item.title.trim().length>0?item.title:copy.rowFallbackTitle,time=formatInboxTime(item.createdAt,nowMs,copy.now),unread=item.readAt===null;return{id:item.id,title:title,body:item.body,time:time,unread:unread,label:inboxRowLabel({title:title,body:item.body,time:time,unread:unread},copy)}})}function detailFor(ref,res){return res.ok?{kind:"ready",item:res.value.item}:res.error.httpStatus===404?{kind:"notFound",ref:ref}:{kind:"error",ref:ref}}function wantedRef(itemId,eventId){return typeof itemId=="string"?{itemId:itemId}:typeof eventId=="string"?{eventId:eventId}:null}var refKey=ref=>"itemId"in ref?`i:${ref.itemId}`:`e:${ref.eventId}`;function useInboxView(inbox,props){let{open:open}=inbox,onOpen=useRef(props.onOpen);onOpen.current=props.onOpen;let wanted=wantedRef(props.initialItemId,props.initialEventId),[detail,setDetail]=useState(()=>wanted===null?null:{kind:"loading",ref:wanted}),turn=useRef(0),live=useRef(true);useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let show=useCallback(ref=>{let mine=++turn.current;setDetail({kind:"loading",ref:ref}),open(ref).then(res=>{live.current&&mine===turn.current&&setDetail(detailFor(ref,res))})},[open]),showRef=useRef(show);showRef.current=show;let wantedKey=wanted===null?null:refKey(wanted),shown=useRef(null),wantedNow=useRef(wanted);wantedNow.current=wanted,useEffect(()=>{if(wantedKey===null){shown.current=null;return}shown.current===wantedKey||wantedNow.current===null||(shown.current=wantedKey,showRef.current(wantedNow.current))},[wantedKey]);let openRow=useCallback(itemId=>{let handler=onOpen.current;if(handler===void 0){show({itemId:itemId});return}let mine=++turn.current;open({itemId:itemId}).then(res=>{if(!(!live.current||mine!==turn.current)){if(!res.ok){setDetail(detailFor({itemId:itemId},res));return}callHost(handler,res.value)===false&&setDetail({kind:"ready",item:res.value.item})}})},[open,show]),back=useCallback(()=>{turn.current+=1,shown.current=null,setDetail(null)},[]),retryDetail=useCallback(()=>{detail!==null&&detail.kind!=="ready"&&show(detail.ref)},[detail,show]);return useMemo(()=>({detail:detail,openRow:openRow,back:back,retryDetail:retryDetail}),[detail,openRow,back,retryDetail])}var COARSE_NOW_TICK_MS=3600*1e3;function useCoarseNow(fixed,shown=true){let[now,setNow]=useState(()=>Date.now()),first=useRef(true);return useEffect(()=>{if(first.current){first.current=false;return}shown&&setNow(Date.now())},[fixed,shown]),useEffect(()=>{if(!shown)return;let tick=setInterval(()=>setNow(Date.now()),COARSE_NOW_TICK_MS),onVisible=()=>{document.visibilityState==="visible"&&setNow(Date.now())},doc=typeof document<"u"&&typeof document.addEventListener=="function"?document:null;return doc?.addEventListener("visibilitychange",onVisible),()=>{clearInterval(tick),doc?.removeEventListener("visibilitychange",onVisible)}},[fixed,shown]),now}var VISUALLY_HIDDEN=/* @__PURE__ */Object.freeze({position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0});var FOCUS_RING_WIDTH=2,SELF_FOCUS_RING_ATTRIBUTE="data-ef-focus-ring",FOCUS_VISIBLE_ATTRIBUTE="data-ef-focus-visible",FOCUS_RING_COLOR_ATTRIBUTE="data-ef-focus-ring-color";function focusRingStyle(color){return{outline:`${FOCUS_RING_WIDTH}px solid ${color}`,outlineOffset:FOCUS_RING_WIDTH}}var keyboardDriving=false,bound=0;function onKeyDown(event){event.metaKey||event.ctrlKey||event.altKey||(keyboardDriving=true)}function onPointerDown(){keyboardDriving=false}function bindModality(){return typeof document>"u"?()=>{}:(bound===0&&(document.addEventListener("keydown",onKeyDown,true),document.addEventListener("pointerdown",onPointerDown,true),document.addEventListener("mousedown",onPointerDown,true),document.addEventListener("touchstart",onPointerDown,true)),bound+=1,()=>{bound-=1,!(bound>0)&&(document.removeEventListener("keydown",onKeyDown,true),document.removeEventListener("pointerdown",onPointerDown,true),document.removeEventListener("mousedown",onPointerDown,true),document.removeEventListener("touchstart",onPointerDown,true),keyboardDriving=false)})}var TEXT_INPUT_TYPES=/* @__PURE__ */new Set(["","text","search","email","tel","url","password","number"]);function isTextField(element){return element.tagName==="TEXTAREA"||element.isContentEditable?true:element.tagName!=="INPUT"?false:TEXT_INPUT_TYPES.has((element.getAttribute("type")??"").toLowerCase())}function useKeyboardFocusRing(root,color){useEffect(()=>{let node=root.current;if(node!==null)return bindKeyboardFocusRing(node,color)},[root,color])}function bindKeyboardFocusRing(node,color){let unbind=bindModality(),painted=/* @__PURE__ */new Map,onFocusIn=event=>{let target=event.target;if(!(target instanceof HTMLElement)||painted.has(target)||target.closest(`[${SELF_FOCUS_RING_ATTRIBUTE}="self"]`)!==null||!keyboardDriving&&!isTextField(target))return;painted.set(target,{outline:target.style.outline,outlineOffset:target.style.outlineOffset});let region=target.closest(`[${FOCUS_RING_COLOR_ATTRIBUTE}]`),ring=focusRingStyle(region?.getAttribute(FOCUS_RING_COLOR_ATTRIBUTE)||color);target.style.outline=ring.outline,target.style.outlineOffset=`${ring.outlineOffset}px`,target.setAttribute(FOCUS_VISIBLE_ATTRIBUTE,"")},onFocusOut=event=>{let target=event.target;if(!(target instanceof HTMLElement))return;let before=painted.get(target);before!==void 0&&(painted.delete(target),target.style.outline=before.outline,target.style.outlineOffset=before.outlineOffset,target.removeAttribute(FOCUS_VISIBLE_ATTRIBUTE))};return node.addEventListener("focusin",onFocusIn),node.addEventListener("focusout",onFocusOut),()=>{node.removeEventListener("focusin",onFocusIn),node.removeEventListener("focusout",onFocusOut);for(let[element,before]of painted)element.style.outline=before.outline,element.style.outlineOffset=before.outlineOffset,element.removeAttribute(FOCUS_VISIBLE_ATTRIBUTE);painted.clear(),unbind()}}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);createContext(NESTED_HEADING_LEVEL_DEFAULT);var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key2 of Object.keys(value))deepFreeze(value[key2])}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)}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function headingFaceCss(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type,base=faceCss(theme,fallback);return headingFamily===null&&headingWeight===null?base:headingFamily!==null?{fontFamily:cssFontFamily(headingFamily),fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]}:theme.type.namedFaces[fallback]||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}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=1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function slotBoxCss(slot,borderWidth){let box=slotBox(slot),out={};return box.backgroundColor!==void 0&&(out.backgroundColor=box.backgroundColor),box.borderColor!==void 0&&(out.border=`${box.borderWidth??1}px solid ${box.borderColor}`),box.borderRadius!==void 0&&(out.borderRadius=box.borderRadius),out}function slotCss(slot,borderWidth){return{...slotBoxCss(slot),...slotText(slot)}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});var RETRYABILITY_ROWS=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze(RETRYABILITY_ROWS.map(row=>/* @__PURE__ */Object.freeze(row)));/* @__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",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable"}),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 key2=wireCode.trim().toUpperCase();if(key2.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key2);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 bounded2=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded2,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,key2,value){Object.defineProperty(target,key2,{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 errorFrame(fields){/* @__PURE__ */
|
|
7
|
+
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[key2,value]of Object.entries(headers)){let lower=key2.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key2]=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,base=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({...base,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(
|
|
8
|
+
/* @__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__ */
|
|
9
|
+
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key2,value]of Object.entries(req.headers??{}))key2.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key2]=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 at2=findResetsAt(error.raw);if(at2!==null){let delta=at2-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 noop2=()=>{};if(!caller)return{signal:deadline,dispose:noop2};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop2};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})})}var INTENT_BY_VISIT_EVENT=/* @__PURE__ */Object.freeze({"visit.booked":"visit","visit.reminder":"join","visit.rescheduled":"visit","visit.followup_sent":"messages","visit.message_received":"messages","visit.completed":"summary","visit.ended":"visit","visit.cancelled":null,"visit.no_show":null});function vetVisitIntentForEvent(eventType){return Object.prototype.hasOwnProperty.call(INTENT_BY_VISIT_EVENT,eventType)?INTENT_BY_VISIT_EVENT[eventType]:"visit"}var EVERFUR_NOTIFICATION_VERSION=1,EVERFUR_NOTIFICATION_TARGET_KINDS=/* @__PURE__ */Object.freeze(["record_request","pet","visit","case","chat","records","vaccine","medication","labs","order","health_plan","tip","walk","weather","pack","mood","card","membership","support","offer","inbox"]),TOP_KEYS=["v","event_id","event_type","target"],EVENT_TYPE=/^[a-z][a-z0-9_]{0,39}(\.[a-z0-9_]{1,40}){1,4}$/,WIRE_KEY=/^[a-z][a-z0-9_]{0,39}$/,UNKNOWN_FIELDS_MAX=16,INBOX_ITEM_ID=/^inb_[A-Za-z0-9_-]{1,64}$/,VISIT_PUSH_INTENTS=/* @__PURE__ */new Set(["visit","join","summary","messages","prep","waiting","notes"]),HOSTED_INTENT=/* @__PURE__ */Object.freeze({visit:"visit",join:"join",summary:"summary",messages:"messages",prep:"visit",waiting:"join",notes:"summary"}),MEDICATION_INTENTS=/* @__PURE__ */new Set(["check","refill","dose"]),ORDER_INTENTS=/* @__PURE__ */new Set(["status","prescription"]),MAX_VALUE_LENGTH=128,MAX_ENCODED_LENGTH=4096,EVENT_ID=/^evt_[A-Za-z0-9]{1,64}$/,UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,CONTROL_CHAR=/[\0-]/;function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function keysOf(value){return Object.keys(value)}function decodeBlock(raw){if(isRecord2(raw))return raw;if(typeof raw!="string"||raw.length===0||raw.length>MAX_ENCODED_LENGTH)return null;let decoded=JSON.parse(raw);return isRecord2(decoded)?decoded:null}function at(root,path){let current=root;for(let key2 of path){if(!isRecord2(current))return;current=current[key2]}return current}var DATA_PATHS=[[],["data"],["request","content","data"],["notification","request","content","data"]];function locateBlock(payload){if(!isRecord2(payload))return null;for(let path of DATA_PATHS){let map=at(payload,path);if(isRecord2(map)&&"everfur"in map)return map.everfur}return TOP_KEYS.every(key2=>key2 in payload)?payload:null}function opaqueString(value){return typeof value!="string"||value.length===0||value.length>MAX_VALUE_LENGTH||CONTROL_CHAR.test(value)||value.includes("://")||value.toLowerCase().startsWith("everfur")?null:value}function own(target,key2){return Object.prototype.hasOwnProperty.call(target,key2)?target[key2]:void 0}function optional(target,key2){let raw=own(target,key2);if(raw==null)return{ok:true,value:null};let value=opaqueString(raw);return value===null?{ok:false}:{ok:true,value:value}}function required(target,key2){return opaqueString(own(target,key2))}function oneOf(target,key2,allowed){let field=optional(target,key2);if(field.ok)return field.value!==null&&allowed.has(field.value)?field.value:null}function unknownTarget(raw,kind){let fields={},count2=0;for(let key2 of keysOf(raw)){let value=raw[key2];if(!(key2==="kind"||!WIRE_KEY.test(key2)||typeof value!="string")){if(opaqueString(value)===null||(count2+=1,count2>UNKNOWN_FIELDS_MAX))return null;fields[key2]=value}}/* @__PURE__ */
|
|
10
|
+
return Object.freeze({kind:"unknown",wireKind:kind,fields:/* @__PURE__ */Object.freeze(fields)})}function visitIntents(raw,eventType){let named=oneOf(raw,"intent",VISIT_PUSH_INTENTS);if(named===void 0)return null;if(named===null)return{intent:vetVisitIntentForEvent(eventType)};let pushIntent=named;return{intent:HOSTED_INTENT[pushIntent],pushIntent:pushIntent}}function conversationOf(target){let conversation=optional(target,"conversation_id");if(conversation.ok&&!(conversation.value!==null&&!UUID.test(conversation.value)))return conversation.value}function parseTarget(raw,eventType){if(!isRecord2(raw))return null;let kind=own(raw,"kind");if(typeof kind!="string"||!WIRE_KEY.test(kind))return null;if(!EVERFUR_NOTIFICATION_TARGET_KINDS.includes(kind))return unknownTarget(raw,kind);let pet=optional(raw,"pet_ref");if(!pet.ok)return null;let petRef=pet.value;switch(kind){case"record_request":{let requestId=required(raw,"request_id");return requestId===null?null:/* @__PURE__ */Object.freeze({kind:"record_request",requestId:requestId,petRef:petRef})}case"pet":return petRef===null?null:/* @__PURE__ */Object.freeze({kind:"pet",petRef:petRef});case"visit":{let visitRef=required(raw,"visit_ref"),intents=visitIntents(raw,eventType);return visitRef===null||intents===null?null:/* @__PURE__ */Object.freeze({kind:"visit",visitRef:visitRef,petRef:petRef,...intents})}case"case":{let caseRef=required(raw,"case_ref");if(caseRef===null)return null;let conversationId=conversationOf(raw);return conversationId===void 0?null:/* @__PURE__ */Object.freeze({kind:"case",caseRef:caseRef,conversationId:conversationId,petRef:petRef})}case"chat":{if(petRef===null)return null;let conversationId=conversationOf(raw);return conversationId===void 0?null:/* @__PURE__ */Object.freeze({kind:"chat",petRef:petRef,conversationId:conversationId})}case"records":case"vaccine":case"mood":return petRef===null?null:/* @__PURE__ */Object.freeze({kind:kind,petRef:petRef});case"medication":{let medicationRef=optional(raw,"medication_ref"),intent=oneOf(raw,"intent",MEDICATION_INTENTS);return petRef===null||!medicationRef.ok||intent===void 0?null:/* @__PURE__ */Object.freeze({kind:kind,petRef:petRef,medicationRef:medicationRef.value,intent:intent})}case"labs":{let resultRef=optional(raw,"result_ref");return petRef===null||!resultRef.ok?null:/* @__PURE__ */Object.freeze({kind:kind,petRef:petRef,resultRef:resultRef.value})}case"order":{let orderRef=required(raw,"order_ref"),intent=oneOf(raw,"intent",ORDER_INTENTS);return orderRef===null||intent===void 0?null:/* @__PURE__ */Object.freeze({kind:kind,orderRef:orderRef,intent:intent})}case"health_plan":case"walk":/* @__PURE__ */
|
|
11
|
+
return Object.freeze({kind:kind,petRef:petRef});case"tip":{let topic=required(raw,"topic");return topic===null?null:/* @__PURE__ */Object.freeze({kind:kind,topic:topic,petRef:petRef})}case"weather":case"pack":case"membership":case"support":/* @__PURE__ */
|
|
12
|
+
return Object.freeze({kind:kind});case"card":{let cardRef=required(raw,"card_ref");return cardRef===null?null:/* @__PURE__ */Object.freeze({kind:kind,cardRef:cardRef})}case"offer":{let offerRef=required(raw,"offer_ref");return offerRef===null?null:/* @__PURE__ */Object.freeze({kind:kind,offerRef:offerRef})}case"inbox":{let item=optional(raw,"item_id");return!item.ok||item.value!==null&&!INBOX_ITEM_ID.test(item.value)?null:/* @__PURE__ */Object.freeze({kind:kind,itemId:item.value})}default:return null}}function parseBlock(block){if(own(block,"v")!==EVERFUR_NOTIFICATION_VERSION)return null;let eventId=own(block,"event_id");if(typeof eventId!="string"||!EVENT_ID.test(eventId))return null;let eventType=own(block,"event_type");if(typeof eventType!="string"||!EVENT_TYPE.test(eventType))return null;let target=parseTarget(own(block,"target"),eventType);if(target===null)return null;let inboxItemId=own(block,"inbox_item_id"),item=typeof inboxItemId=="string"&&INBOX_ITEM_ID.test(inboxItemId)?{inboxItemId:inboxItemId}:{};/* @__PURE__ */
|
|
13
|
+
return Object.freeze({eventId:eventId,eventType:eventType,target:target,...item})}function parseEverfurNotification(payload){try{let block=decodeBlock(locateBlock(payload));return block===null?null:parseBlock(block)}catch{return null}}var ITEM_ID=/^inb_[A-Za-z0-9_-]{1,64}$/,EVENT_ID2=/^evt_[A-Za-z0-9]{1,64}$/,TARGET_KEY=/^[a-z][a-z0-9_]{0,39}$/,TARGET_KEYS_MAX=16,TARGET_VALUE_MAX=128,PAGE_LIMIT_MAX=50,CURSOR_MAX=512,PET_REF_MAX=128,READ_IDS_MAX=100,TITLE_MAX=500,BODY_MAX=4e3,CONTROL_CHAR2=/[\u0000-\u001f\u007f]/;function invalid(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed(call){return makeEverfurError("internalError",{retryable:false,wireMessage:`${call}: the response was not the documented shape`})}function disposed(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isInboxItemId(value){return typeof value=="string"&&ITEM_ID.test(value)}function isNotificationEventId(value){return typeof value=="string"&&EVENT_ID2.test(value)}function opaque(value){return value.length>0&&value.length<=TARGET_VALUE_MAX&&!CONTROL_CHAR2.test(value)&&!value.includes("://")&&!value.toLowerCase().startsWith("everfur")}function readTarget(raw){if(!isRecord3(raw))return null;let kind=raw.kind;if(typeof kind!="string"||!TARGET_KEY.test(kind))return null;let out={},count2=0;for(let key2 of Object.keys(raw)){let value=raw[key2];if(!(!TARGET_KEY.test(key2)||value!==null&&typeof value!="string")){if(typeof value=="string"&&!opaque(value)||(count2+=1,count2>TARGET_KEYS_MAX))return null;out[key2]=value}}/* @__PURE__ */
|
|
14
|
+
return Object.freeze(out)}function str(value){return typeof value=="string"&&value.length>0?value:null}function nullableStr(value){return value==null?null:typeof value=="string"&&value.length>0?value:void 0}function parseInboxItem(raw){if(!isRecord3(raw))return null;let id=raw.id,typeKey=str(raw.type_key),title=raw.title,body=raw.body,createdAt=str(raw.created_at),eventType=nullableStr(raw.event_type),petRef=nullableStr(raw.pet_ref),readAt=nullableStr(raw.read_at),eventIdRaw=nullableStr(raw.event_id);if(!isInboxItemId(id)||typeKey===null||createdAt===null||typeof title!="string"||title.length>TITLE_MAX||typeof body!="string"||body.length>BODY_MAX||eventType===void 0||petRef===void 0||readAt===void 0||eventIdRaw===void 0)return null;let eventId=eventIdRaw!==null&&isNotificationEventId(eventIdRaw)?eventIdRaw:null;/* @__PURE__ */
|
|
15
|
+
return Object.freeze({id:id,typeKey:typeKey,eventType:eventType,eventId:eventId,title:title,body:body,petRef:petRef,target:readTarget(raw.target),createdAt:createdAt,readAt:readAt})}function count(value){return typeof value=="number"&&Number.isInteger(value)&&value>=0?value:null}function parsePage(raw){if(!isRecord3(raw)||!Array.isArray(raw.items))return null;let unread=count(raw.unread_count),cursor=nullableStr(raw.next_cursor);if(unread===null||cursor===void 0)return null;let items=[];for(let row of raw.items){let item=parseInboxItem(row);item!==null&&items.push(item)}/* @__PURE__ */
|
|
16
|
+
return Object.freeze({items:/* @__PURE__ */Object.freeze(items),nextCursor:cursor,unreadCount:unread})}function parseCount(raw){return isRecord3(raw)?count(raw.unread_count):null}function notificationForInboxItem(item){if(item.eventId===null||item.eventType===null||item.target===null)return null;let target={};for(let[key2,value]of Object.entries(item.target))value!==null&&(target[key2]=value);return parseEverfurNotification({v:1,event_id:item.eventId,event_type:item.eventType,target:target})}function inboxOpenFor(item){/* @__PURE__ */
|
|
17
|
+
return Object.freeze({item:item,notification:notificationForInboxItem(item)})}function queryString(query){let pairs=[],{limit:limit,cursor:cursor,petRef:petRef,eventId:eventId}=query??{};if(limit!==void 0){if(!Number.isInteger(limit)||limit<1||limit>PAGE_LIMIT_MAX)return invalid(`limit must be an integer from 1 to ${PAGE_LIMIT_MAX}`);pairs.push(`limit=${limit}`)}if(cursor!==void 0){if(typeof cursor!="string"||cursor.length===0||cursor.length>CURSOR_MAX)return invalid("cursor must be the nextCursor of an earlier page");pairs.push(`cursor=${encodeURIComponent(cursor)}`)}if(petRef!==void 0){if(typeof petRef!="string"||petRef.length===0||petRef.length>PET_REF_MAX)return invalid(`petRef must be 1..${PET_REF_MAX} characters`);pairs.push(`pet_ref=${encodeURIComponent(petRef)}`)}if(eventId!==void 0){if(!isNotificationEventId(eventId))return invalid("eventId must be an Everfur event id (evt_...)");pairs.push(`event_id=${eventId}`)}return pairs.length===0?"":`?${pairs.join("&")}`}function createInboxClient(runtime){let over=()=>{let{services:services}=runtime.registry;return createInboxClientOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed(verb)));return{listPage:(query,opts)=>runtime.isDisposed?gone("listPage"):over().listPage(query,opts),getItem:(itemId,opts)=>runtime.isDisposed?gone("getItem"):over().getItem(itemId,opts),markRead:itemIds=>runtime.isDisposed?gone("markRead"):over().markRead(itemIds),markAllRead:()=>runtime.isDisposed?gone("markAllRead"):over().markAllRead(),unreadCount:opts=>runtime.isDisposed?gone("unreadCount"):over().unreadCount(opts)}}function createInboxClientOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),withSignal=(req,signal)=>signal?{...req,signal:signal}:req,read=async(call,body)=>{let res=await funnel.send(call,{method:"POST",path:"/widget/v1/inbox/read",body:body});if(!res.ok)return res;let unread=parseCount(res.value);return unread===null?err(malformed(call)):ok(unread)};return{async listPage(query,opts){let qs=queryString(query);if(typeof qs!="string")return err(qs);let res=await funnel.send("inbox.list",withSignal({method:"GET",path:`/widget/v1/inbox${qs}`},opts?.signal));if(!res.ok)return res;let page=parsePage(res.value);return page===null?err(malformed("inbox.list")):ok(page)},async getItem(itemId,opts){if(!isInboxItemId(itemId))return err(invalid("itemId must be an inbox item id (inb_...)"));let res=await funnel.send("inbox.get",withSignal({method:"GET",path:`/widget/v1/inbox/${itemId}`},opts?.signal));if(!res.ok)return res;let item=parseInboxItem(res.value);return item===null?err(malformed("inbox.get")):ok(item)},markRead(itemIds){return!Array.isArray(itemIds)||itemIds.length===0||itemIds.length>READ_IDS_MAX||!itemIds.every(isInboxItemId)?Promise.resolve(err(invalid(`markRead needs 1..${READ_IDS_MAX} inbox item ids`))):read("inbox.markRead",{ids:[...new Set(itemIds)]})},markAllRead(){return read("inbox.markAllRead",{all:true})},async unreadCount(opts){let res=await funnel.send("inbox.unreadCount",withSignal({method:"GET",path:"/widget/v1/inbox/unread-count"},opts?.signal));if(!res.ok)return res;let unread=parseCount(res.value);return unread===null?err(malformed("inbox.unreadCount")):ok(unread)}}}var INBOX_PAGE_SIZE=20,INITIAL=/* @__PURE__ */Object.freeze({status:"idle",items:/* @__PURE__ */Object.freeze([]),unreadCount:null,hasMore:false,refreshing:false,loadingMore:false,error:null});function isOff(error){return error.httpStatus===404}function notFound(){return makeEverfurError("resourceNotFound",{retryable:false,httpStatus:404,wireMessage:"no inbox item matched"})}function mergeHead(head,current){let seen=new Set(head.map(item=>item.id));/* @__PURE__ */
|
|
18
|
+
return Object.freeze([...head,...current.filter(item=>!seen.has(item.id))])}function createInboxController(deps){let{client:client}=deps,pageSize=deps.pageSize??INBOX_PAGE_SIZE,petRef=deps.petRef??null,snapshot=INITIAL,cursor=null,pages=0,disposed3=false,firstRead=null,refreshing=null,loadingMore=null,generation=0,listeners=/* @__PURE__ */new Set,set=patch=>{if(!disposed3){snapshot=/* @__PURE__ */Object.freeze({...snapshot,...patch});for(let listener of[...listeners])try{listener()}catch{}}},unread=count2=>{set({unreadCount:count2});try{deps.onUnreadCount?.(count2)}catch{}},query=after=>({limit:pageSize,...after===null?{}:{cursor:after},...petRef===null?{}:{petRef:petRef}}),landHead=(page,merge)=>{let items=merge?mergeHead(page.items,snapshot.items):page.items;(!merge||pages<=1)&&(generation+=1,cursor=page.nextCursor,pages=1),set({status:"ready",items:items,hasMore:cursor!==null,error:null}),unread(page.unreadCount)},readHead=async merge=>{let res=await client.listPage(query(null));if(!disposed3){if(res.ok){landHead(res.value,merge);return}if(isOff(res.error)){cursor=null,set({status:"off",items:INITIAL.items,hasMore:false,unreadCount:null,error:null});return}snapshot.status==="ready"?set({error:res.error}):set({status:"error",error:res.error})}},markItems=async ids=>{let before=snapshot.items,marked=ids===null?null:new Set(ids),now=/* @__PURE__ */(new Date).toISOString();set({items:/* @__PURE__ */Object.freeze(before.map(item=>item.readAt===null&&(marked===null||marked.has(item.id))?/* @__PURE__ */Object.freeze({...item,readAt:now}):item))});let res=ids===null?await client.markAllRead():await client.markRead(ids);if(disposed3)return res.ok?ok(void 0):err(res.error);if(!res.ok){let restore=new Map(before.map(item=>[item.id,item]));return set({items:/* @__PURE__ */Object.freeze(snapshot.items.map(item=>item.readAt===now?restore.get(item.id)??item:item))}),err(res.error)}return unread(res.value),ok(void 0)},load=()=>firstRead!==null||disposed3?firstRead??Promise.resolve():(set({status:"loading",error:null}),firstRead=readHead(false),firstRead);return{subscribe(listener){return listeners.add(listener),()=>listeners.delete(listener)},getSnapshot:()=>snapshot,load:load,refresh(){return disposed3?Promise.resolve():firstRead===null?load():(refreshing!==null||(snapshot.status==="error"||snapshot.status==="idle"?set({status:"loading",error:null}):set({refreshing:true}),refreshing=readHead(snapshot.status==="ready").finally(()=>{refreshing=null,set({refreshing:false})})),refreshing)},loadMore(){if(disposed3||loadingMore!==null||cursor===null||snapshot.status!=="ready")return loadingMore??Promise.resolve();let at2=generation,after=cursor;return set({loadingMore:true}),loadingMore=client.listPage(query(after)).then(res=>{if(disposed3||at2!==generation)return;if(!res.ok){set({error:res.error});return}cursor=res.value.nextCursor,pages+=1;let seen=new Set(snapshot.items.map(item=>item.id));set({items:/* @__PURE__ */Object.freeze([...snapshot.items,...res.value.items.filter(item=>!seen.has(item.id))]),hasMore:cursor!==null,error:null}),unread(res.value.unreadCount)}).finally(()=>{loadingMore=null,set({loadingMore:false})}),loadingMore},markRead:itemId=>markItems([itemId]),markAllRead:()=>markItems(null),async open(ref){let{itemId:itemId,eventId:eventId}=ref,item=itemId===void 0?null:snapshot.items.find(row=>row.id===itemId)??null;if(item===null&&eventId!==void 0&&(item=snapshot.items.find(row=>row.eventId===eventId)??null),item===null&&itemId!==void 0){let res=await client.getItem(itemId);if(!res.ok&&eventId===void 0)return err(res.error);res.ok&&(item=res.value)}if(item===null&&eventId!==void 0){let res=await client.listPage({eventId:eventId,limit:1});if(!res.ok)return err(res.error);item=res.value.items[0]??null}return item===null?err(notFound()):(item.readAt===null&&markItems([item.id]),ok(inboxOpenFor(item)))},dispose(){disposed3=true,listeners.clear()}}}var SLOT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#InboxUnread@v1");function slots(){let host=globalThis,stored=host[SLOT_SYMBOL];if(stored instanceof WeakMap)return stored;let made=/* @__PURE__ */new WeakMap;return host[SLOT_SYMBOL]=made,made}function createStore(runtime){let value=null,inFlight=null,listeners=/* @__PURE__ */new Set,set=next=>{if(next!==value){value=next;for(let listener of[...listeners])try{listener()}catch{}}};return{get:()=>value,subscribe(listener){return listeners.add(listener),()=>listeners.delete(listener)},refresh(){if(inFlight!==null)return inFlight;if(runtime.isDisposed)return Promise.resolve();let{services:services}=runtime.registry;return inFlight=createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}).send("inbox.unreadCount",{method:"GET",path:"/widget/v1/inbox/unread-count"}).then(res=>{if(res.ok){let raw=res.value?.unread_count;typeof raw=="number"&&Number.isInteger(raw)&&raw>=0&&set(raw)}else res.error.httpStatus===404&&set(null)}).catch(()=>{}).finally(()=>{inFlight=null}),inFlight},report(count2){Number.isInteger(count2)&&count2>=0&&set(count2)}}}function inboxUnreadStoreFor(runtime,scope){let all=slots(),hit=all.get(runtime);if(hit!==void 0&&hit.key===scope)return hit.store;let store=createStore(runtime);return all.set(runtime,{key:scope,store:store}),store}function inboxUnreadScope(userRef,scopeEpoch){return`${userRef??""}\0${scopeEpoch}`}function isCoalesced(trigger,conversationId,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId=state.activeConversationId===null||state.activeConversationId.length===0?null:state.activeConversationId;return conversationId===null&&state.refreshesBlankThread!==true?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId}}function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),probeOffline=()=>lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,isOffline=probeOffline(),run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId,isTurnInFlight:isTurnInFlight,refresh:refresh,refreshesBlankThread:refreshesBlankThread}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId,isTurnInFlight:isTurnInFlight,refreshesBlankThread:refreshesBlankThread===true,isOffline:probeOffline(),lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}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}var INBOX_REFRESH_KEY="everfur-inbox",SIGNED_OUT=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>SIGNED_OUT_SNAPSHOT,load:()=>Promise.resolve(),refresh:()=>Promise.resolve(),loadMore:()=>Promise.resolve(),markRead:()=>Promise.resolve(err(noUser())),markAllRead:()=>Promise.resolve(err(noUser())),open:()=>Promise.resolve(err(noUser())),dispose:()=>{}}),SIGNED_OUT_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",items:/* @__PURE__ */Object.freeze([]),unreadCount:null,hasMore:false,refreshing:false,loadingMore:false,error:null});function noUser(){return makeEverfurError("sessionRequired",{retryable:false,wireMessage:"the inbox needs a signed-in user on the provider"})}function useEverfurInboxClient(){let{runtime:runtime}=useEverfurContext();return useMemo(()=>createInboxClient(runtime),[runtime])}function useInboxState(options,lifecycle){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=useEverfurInboxClient(),petRef=options.petRef??null,{pageSize:pageSize}=options,unread=useMemo(()=>inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),[runtime,userRef,scopeEpoch]),controller=useScopedController(()=>userRef===null?SIGNED_OUT:createInboxController({client:client,petRef:petRef,...pageSize===void 0?{}:{pageSize:pageSize},onUnreadCount:count2=>unread.report(count2)}),[client,userRef,scopeEpoch,petRef,pageSize,unread]),snapshot=useSyncExternalStore(controller.subscribe,controller.getSnapshot,controller.getSnapshot),unreadCount=useSyncExternalStore(unread.subscribe,unread.get,unread.get);useEffect(()=>{controller.load()},[controller]);let refresh=useCallback(()=>controller.refresh(),[controller]),open=useCallback(ref=>controller.open(ref),[controller]);return useChatLifecycle(lifecycle,{conversationId:userRef===null?null:INBOX_REFRESH_KEY,isTurnInFlight:false,refresh:refresh}),useMemo(()=>({...snapshot,unreadCount:userRef===null?null:unreadCount??snapshot.unreadCount,refresh:refresh,loadMore:()=>controller.loadMore(),markRead:itemId=>controller.markRead(itemId),markAllRead:()=>controller.markAllRead(),open:open}),[snapshot,unreadCount,userRef,refresh,open,controller])}var FRAGMENT_KEYS=["efn","efi","eft"];var NOTIFICATION_MESSAGE_TYPE="everfur:notification",PUSH_RECEIVED_MESSAGE_TYPE="everfur:push_received",EVENT_ID3=/^evt_[A-Za-z0-9]{1,64}$/,ITEM_ID2=/^inb_[A-Za-z0-9_-]{1,64}$/;function isRecord4(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function notificationRouteOf(eventType,target){return typeof eventType=="string"&&eventType.length>0&&eventType.length<=200&&isRecord4(target)?{event_type:eventType,target:target}:null}function fragmentValue(url,key2){let hash=url.indexOf("#");if(hash<0)return null;for(let pair of url.slice(hash+1).split("&"))if(pair.startsWith(`${key2}=`))return pair.slice(key2.length+1);return null}function routeFromFragment(value){if(value===null||value.length>1024)return null;try{let decoded=JSON.parse(decodeURIComponent(value));return isRecord4(decoded)?notificationRouteOf(decoded.event_type,decoded.target):null}catch{return null}}function notificationOpenFromUrl(url){if(typeof url!="string")return null;let eventId=notificationEventIdFromUrl(url),item=fragmentValue(url,"efi"),itemId=item!==null&&ITEM_ID2.test(item)?item:null;return eventId===null&&itemId===null?null:{eventId:eventId,itemId:itemId,route:item===null?routeFromFragment(fragmentValue(url,"eft")):null}}function notificationOpenOf(value){if(!isRecord4(value))return null;let eventId=typeof value.eventId=="string"&&EVENT_ID3.test(value.eventId)?value.eventId:null,itemId=typeof value.itemId=="string"&&ITEM_ID2.test(value.itemId)?value.itemId:null;if(eventId===null&&itemId===null)return null;let route=value.route;return{eventId:eventId,itemId:itemId,route:itemId===null&&isRecord4(route)?notificationRouteOf(route.event_type,route.target):null}}function notificationEventIdFromUrl(url){if(typeof url!="string")return null;let value=fragmentValue(url,"efn");return value!==null&&EVENT_ID3.test(value)?value:null}function withoutNotificationEventId(url){let hash=url.indexOf("#");if(hash<0)return url;let kept=url.slice(hash+1).split("&").filter(pair=>!FRAGMENT_KEYS.some(key2=>pair===key2||pair.startsWith(`${key2}=`)));return kept.length===0?url.slice(0,hash):`${url.slice(0,hash)}#${kept.join("&")}`}function notificationOpenFromMessage(data){if(typeof data!="object"||data===null)return null;let message=data;if(message.type!==NOTIFICATION_MESSAGE_TYPE||typeof message.envelope!="object"||message.envelope===null)return null;let envelope=message.envelope,eventId=typeof envelope.event_id=="string"&&EVENT_ID3.test(envelope.event_id)?envelope.event_id:null,itemId=typeof envelope.inbox_item_id=="string"&&ITEM_ID2.test(envelope.inbox_item_id)?envelope.inbox_item_id:null;return eventId===null&&itemId===null?null:{eventId:eventId,itemId:itemId,route:notificationRouteOf(envelope.event_type,envelope.target)}}function takeNotificationOpenFrom(win){let href;try{if(win===void 0)return null;href=win.location.href}catch{return null}let scrubbed=withoutNotificationEventId(href);if(scrubbed===href)return null;try{win.history.replaceState(win.history.state,"",scrubbed)}catch{}return notificationOpenFromUrl(href)}var noop=()=>{};function createBrowserLifecycle(){return{onForeground(listener){if(typeof document>"u"||typeof document.addEventListener!="function")return noop;let wasHidden=document.visibilityState==="hidden",onChange=()=>{let hidden=document.visibilityState==="hidden";wasHidden&&!hidden&&listener(),wasHidden=hidden};return document.addEventListener("visibilitychange",onChange),()=>document.removeEventListener("visibilitychange",onChange)},onOnline(listener){if(typeof window>"u"||typeof window.addEventListener!="function")return noop;let onOnline=()=>listener();return window.addEventListener("online",onOnline),()=>window.removeEventListener("online",onOnline)},isOffline(){return typeof navigator<"u"&&navigator.onLine===false}}}function serviceWorkerMessages(){try{let container=globalThis.navigator?.serviceWorker;return typeof container=="object"&&container!==null&&typeof container.addEventListener=="function"?container:null}catch{return null}}function onNotificationMessage(listener,source=serviceWorkerMessages()){if(source===null)return()=>{};let onMessage=event=>{let ref=notificationOpenFromMessage(event.data);ref!==null&&listener(ref)};return source.addEventListener("message",onMessage),()=>source.removeEventListener("message",onMessage)}function onPushReceived(listener,source=serviceWorkerMessages()){if(source===null)return()=>{};let onMessage=event=>{let data=event.data;typeof data=="object"&&data!==null&&data.type===PUSH_RECEIVED_MESSAGE_TYPE&&listener()};return source.addEventListener("message",onMessage),()=>source.removeEventListener("message",onMessage)}function createInboxBrowserLifecycle(source=serviceWorkerMessages()){return{...createBrowserLifecycle(),onAnnounced:listener=>onPushReceived(listener,source)}}function useEverfurInbox(options={}){let{lifecycle:lifecycle}=options,port=useMemo(()=>lifecycle===void 0?createInboxBrowserLifecycle():lifecycle??void 0,[lifecycle]);return useInboxState(options,port)}function EverfurInbox(props){let{onOpen:onOpen,initialItemId:initialItemId,initialEventId:initialEventId,petRef:petRef,pageSize:pageSize,lifecycle:lifecycle,copy:hostCopy,headingLevel:headingLevel2,style:style}=props,theme=useEverfurTheme(),styles=useMemo(()=>makeInboxStyles(theme),[theme]),copy=useMemo(()=>inboxCopyWith(hostCopy),[hostCopy]),{userRef:userRef}=useEverfurContext(),inbox=useEverfurInbox({...petRef===void 0?{}:{petRef:petRef},...pageSize===void 0?{}:{pageSize:pageSize},...lifecycle===void 0?{}:{lifecycle:lifecycle}}),view=useInboxView(inbox,{onOpen:onOpen,initialItemId:initialItemId,initialEventId:initialEventId}),now=useCoarseNow(),rows=useMemo(()=>inboxRows(inbox.items,now,copy),[inbox.items,now,copy]),level=headingLevel(headingLevel2??DEFAULT_ROOT_HEADING_LEVEL),Heading=headingTag(level),rootRef=useRef(null);useKeyboardFocusRing(rootRef,theme.color.brandInk);let backRef=useRef(null),lastRow=useRef(null),showingDetail=view.detail!==null;useEffect(()=>{if(showingDetail){backRef.current?.focus();return}let id=lastRow.current;if(id===null)return;rootRef.current?.querySelector(`[data-everfur-inbox-row="${id}"]`)?.focus()},[showingDetail]);let openRow=id=>{lastRow.current=id,view.openRow(id)},content;return view.detail!==null?content=/* @__PURE__ */jsx(InboxDetailView,{detail:view.detail,copy:copy,styles:styles,now:now,backRef:backRef,onBack:view.back,onRetry:view.retryDetail,level:level}):userRef===null||inbox.status==="off"||inbox.status==="ready"&&rows.length===0?content=/* @__PURE__ */jsxs("div",{style:styles.state,children:[
|
|
19
|
+
/* @__PURE__ */jsx("p",{style:styles.stateTitle,children:copy.emptyTitle}),
|
|
20
|
+
/* @__PURE__ */jsx("p",{style:styles.stateBody,children:copy.emptyBody})]}):inbox.status==="error"&&rows.length===0?content=/* @__PURE__ */jsxs("div",{role:"alert",style:styles.state,children:[
|
|
21
|
+
/* @__PURE__ */jsx("p",{style:styles.stateTitle,children:copy.errorTitle}),
|
|
22
|
+
/* @__PURE__ */jsx("p",{style:styles.stateBody,children:copy.errorBody}),
|
|
23
|
+
/* @__PURE__ */jsx("button",{type:"button",onClick:()=>{inbox.refresh()},style:styles.primary,children:copy.retry})]}):rows.length===0?content=/* @__PURE__ */jsx("div",{role:"status","aria-label":copy.loading,style:styles.list,children:[0,1,2].map(key2=>/* @__PURE__ */jsxs("div",{"aria-hidden":"true",style:styles.skeletonRow,children:[
|
|
24
|
+
/* @__PURE__ */jsx("span",{style:styles.skeletonTitle}),
|
|
25
|
+
/* @__PURE__ */jsx("span",{style:styles.skeletonBody})]},key2))}):content=/* @__PURE__ */jsxs(Fragment,{children:[
|
|
26
|
+
/* @__PURE__ */jsx("ul",{"aria-label":copy.title,style:styles.list,children:rows.map(row=>/* @__PURE__ */jsx("li",{style:styles.item,children:/* @__PURE__ */jsx(InboxRowButton,{row:row,styles:styles,onPress:openRow})},row.id))}),inbox.error!==null?
|
|
27
|
+
/* @__PURE__ */jsxs("div",{role:"alert",style:styles.state,"data-everfur-inbox-error":"",children:[
|
|
28
|
+
/* @__PURE__ */jsx("p",{style:styles.stateTitle,children:copy.errorTitle}),
|
|
29
|
+
/* @__PURE__ */jsx("p",{style:styles.stateBody,children:copy.errorBody}),
|
|
30
|
+
/* @__PURE__ */jsx("button",{type:"button",onClick:()=>{inbox.refresh()},style:styles.secondary,children:copy.retry})]}):null,inbox.hasMore?/* @__PURE__ */jsx("button",{type:"button",onClick:()=>{inbox.loadMore()},disabled:inbox.loadingMore,"aria-busy":inbox.loadingMore,style:styles.secondary,children:copy.more}):null]}),/* @__PURE__ */jsxs("section",{ref:rootRef,"aria-label":copy.title,"data-everfur-inbox":"",style:{...styles.root,...style},children:[view.detail===null?/* @__PURE__ */jsx(Heading,{style:styles.heading,children:copy.title}):null,content]})}function InboxRowButton({row:row,styles:styles,onPress:onPress}){/* @__PURE__ */
|
|
31
|
+
return jsxs("button",{type:"button","aria-label":row.label,"data-everfur-inbox-row":row.id,onClick:()=>onPress(row.id),style:row.unread?styles.rowUnread:styles.row,children:[
|
|
32
|
+
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:row.unread?styles.dot:styles.dotRead}),
|
|
33
|
+
/* @__PURE__ */jsxs("span",{"aria-hidden":"true",style:styles.rowText,children:[
|
|
34
|
+
/* @__PURE__ */jsxs("span",{style:styles.rowTop,children:[
|
|
35
|
+
/* @__PURE__ */jsx("span",{style:row.unread?styles.rowTitleUnread:styles.rowTitle,children:row.title}),row.time===null?null:/* @__PURE__ */jsx("span",{style:styles.time,children:row.time})]}),row.body.length>0?/* @__PURE__ */jsx("span",{style:styles.rowBody,children:row.body}):null]})]})}function InboxDetailView(props){let{detail:detail,copy:copy,styles:styles,now:now,level:level,backRef:backRef,onBack:onBack,onRetry:onRetry}=props,Heading=headingTag(level),back=/* @__PURE__ */jsx("button",{ref:backRef,type:"button",onClick:onBack,style:styles.back,children:copy.back});return detail.kind==="loading"?/* @__PURE__ */jsxs(Fragment,{children:[back,
|
|
36
|
+
/* @__PURE__ */jsxs("div",{role:"status","aria-label":copy.loading,style:styles.state,children:[
|
|
37
|
+
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.skeletonTitle}),
|
|
38
|
+
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.skeletonBody})]})]}):detail.kind==="notFound"?/* @__PURE__ */jsxs(Fragment,{children:[back,
|
|
39
|
+
/* @__PURE__ */jsxs("div",{role:"status",style:styles.state,children:[
|
|
40
|
+
/* @__PURE__ */jsx("p",{style:styles.stateTitle,children:copy.notFoundTitle}),
|
|
41
|
+
/* @__PURE__ */jsx("p",{style:styles.stateBody,children:copy.notFoundBody})]})]}):detail.kind==="error"?/* @__PURE__ */jsxs(Fragment,{children:[back,
|
|
42
|
+
/* @__PURE__ */jsxs("div",{role:"alert",style:styles.state,children:[
|
|
43
|
+
/* @__PURE__ */jsx("p",{style:styles.stateTitle,children:copy.detailErrorTitle}),
|
|
44
|
+
/* @__PURE__ */jsx("p",{style:styles.stateBody,children:copy.detailErrorBody}),
|
|
45
|
+
/* @__PURE__ */jsx("button",{type:"button",onClick:onRetry,style:styles.primary,children:copy.retry})]})]}):/* @__PURE__ */jsxs(Fragment,{children:[back,
|
|
46
|
+
/* @__PURE__ */jsxs("article",{style:styles.detail,children:[
|
|
47
|
+
/* @__PURE__ */jsx(Heading,{style:styles.heading,children:detailTitle(detail.item,copy)}),
|
|
48
|
+
/* @__PURE__ */jsx(DetailTime,{item:detail.item,now:now,copy:copy,styles:styles}),detail.item.body.length>0?/* @__PURE__ */jsx("p",{style:styles.detailBody,children:detail.item.body}):null]})]})}function detailTitle(item,copy){return item.title.trim().length>0?item.title:copy.rowFallbackTitle}function DetailTime({item:item,now:now,copy:copy,styles:styles}){let time=formatInboxTime(item.createdAt,now,copy.now);return time===null?null:/* @__PURE__ */jsxs("p",{style:styles.time,children:[
|
|
49
|
+
/* @__PURE__ */jsx("time",{dateTime:item.createdAt,children:time}),inboxTimeTakesAgo(time)?/* @__PURE__ */jsx("span",{style:VISUALLY_HIDDEN,children:` ${copy.timeAgoSuffix}`}):null]})}function makeInboxStyles(theme){let{color:color,radius:radius,space:space,type:type,slots:slots2}=theme,lineHeight=(size,ratio)=>`${Math.round(size*ratio)}px`,button={minHeight:48,padding:`0 ${space.lg}px`,borderRadius:radius.pill,cursor:"pointer",...faceCss(theme,"bold"),fontSize:type.size.body},row={boxSizing:"border-box",display:"flex",alignItems:"flex-start",gap:space.sm,width:"100%",minHeight:48,margin:0,padding:`${space.md}px ${space.lg}px`,border:"none",borderRadius:radius.md,backgroundColor:"transparent",color:color.text.primary,textAlign:"start",cursor:"pointer",...faceCss(theme,"regular")},dot={flex:"none",width:8,height:8,marginTop:Math.round((type.size.body*type.lineHeight.normal-8)/2),borderRadius:radius.pill},title={flex:1,minWidth:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.snug),color:color.text.primary,overflowWrap:"anywhere"},bar={display:"block",height:type.size.body,borderRadius:radius.xs,backgroundColor:color.skeleton};return{root:{...SURFACE_ROOT_RESET,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.md,width:"100%",padding:space.lg,borderRadius:radius.lg,backgroundColor:color.surface,color:color.text.primary,...faceCss(theme,"regular"),...slotCss(slots2.card)},heading:{margin:0,...headingFaceCss(theme,"bold"),fontSize:type.size.heading,lineHeight:lineHeight(type.size.heading,type.lineHeight.snug),color:color.text.primary},list:{display:"flex",flexDirection:"column",gap:space.xs,margin:0,padding:0,listStyle:"none"},item:{margin:0,padding:0},row:row,rowUnread:{...row,backgroundColor:color.brandSofter},dot:{...dot,backgroundColor:color.brand},dotRead:{...dot,backgroundColor:"transparent"},rowText:{display:"flex",flexDirection:"column",gap:space.xs,flex:1,minWidth:0},rowTop:{display:"flex",alignItems:"baseline",gap:space.sm},rowTitle:{...title,...faceCss(theme,"medium")},rowTitleUnread:{...title,...faceCss(theme,"bold")},rowBody:{fontSize:type.size.bodyTight,lineHeight:lineHeight(type.size.bodyTight,type.lineHeight.normal),color:color.text.secondary,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",overflowWrap:"anywhere"},time:{flex:"none",margin:0,fontSize:type.size.caption,lineHeight:lineHeight(type.size.caption,type.lineHeight.normal),color:color.text.timestamp},state:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm,padding:`${space.xl}px ${space.lg}px`,textAlign:"center"},stateTitle:{margin:0,...faceCss(theme,"bold"),fontSize:type.size.subtitle,lineHeight:lineHeight(type.size.subtitle,type.lineHeight.snug),color:color.text.primary},stateBody:{margin:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.normal),color:color.text.secondary},primary:{...button,marginTop:space.xs,border:"none",backgroundColor:color.brand,color:color.text.onBrand,...slotCss(slots2.primaryButton)},secondary:{...button,alignSelf:"center",border:`1px solid ${color.brandBorder}`,backgroundColor:"transparent",color:color.brandInk},back:{...button,alignSelf:"flex-start",padding:`0 ${space.sm}px`,border:"none",backgroundColor:"transparent",color:color.brandInk,...slotCss(slots2.link)},detail:{display:"flex",flexDirection:"column",gap:space.sm},detailBody:{margin:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.relaxed),color:color.text.primary,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},skeletonRow:{display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.md}px ${space.lg}px`},skeletonTitle:{...bar,width:"60%"},skeletonBody:{...bar,width:"90%",height:type.size.bodyTight}}}var INBOX_UNREAD_REFRESH_KEY="everfur-inbox-unread";function useInboxUnreadState(lifecycle){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),store=useMemo(()=>userRef===null?null:inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),[runtime,userRef,scopeEpoch]),subscribe=useCallback(listener=>store===null?()=>{}:store.subscribe(listener),[store]),read=useCallback(()=>store===null?null:store.get(),[store]),unreadCount=useSyncExternalStore(subscribe,read,read),refresh=useCallback(()=>store===null?Promise.resolve():store.refresh(),[store]);return useEffect(()=>{refresh()},[refresh]),useChatLifecycle(store===null?void 0:lifecycle,{conversationId:store===null?null:INBOX_UNREAD_REFRESH_KEY,isTurnInFlight:false,refresh:refresh}),useMemo(()=>({unreadCount:unreadCount,refresh:refresh}),[unreadCount,refresh])}function useEverfurInboxUnread(options={}){let{lifecycle:lifecycle}=options,port=useMemo(()=>lifecycle===void 0?createInboxBrowserLifecycle():lifecycle??void 0,[lifecycle]);return useInboxUnreadState(port)}var BASE="/widget/v1/notifications/web-push",URL_MAX=2048,KEY_MAX=256,TIMEZONE_MAX=64,LOCALE_MAX=35,BASE64URL=/^[A-Za-z0-9_-]+={0,2}$/,SUBSCRIPTION_ID=/^wps_[A-Za-z0-9_-]{1,64}$/,LOCAL_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]);function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed2(call){return makeEverfurError("internalError",{retryable:false,wireMessage:`${call}: the response was not the documented shape`})}function disposed2(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function hintsRefused(error){return error.httpStatus===400&&error.code==="validationFailed"}function withoutHints(body){let rest={...body};return delete rest.timezone,delete rest.locale,rest}function webPushUrl(value){if(typeof value!="string"||value.length===0||value.length>URL_MAX)return null;let url;try{url=new URL(value)}catch{return null}return url.protocol==="https:"||url.protocol==="http:"&&LOCAL_HOSTS.has(url.hostname)?url.href:null}function key(value){return typeof value=="string"&&value.length>0&&value.length<=KEY_MAX&&BASE64URL.test(value)}function bounded(value,max){return typeof value=="string"&&value.length>0&&value.length<=max?value:null}function validate(input){if(typeof input!="object"||input===null)return invalid2("subscribe needs an input object");let{endpoint:endpoint,keys:keys,openUrl:openUrl,timezone:timezone,locale:locale}=input,endpointHref=webPushUrl(endpoint);if(endpointHref===null||!endpointHref.startsWith("https:"))return invalid2("endpoint must be the https endpoint of a push subscription");if(typeof keys!="object"||keys===null||!key(keys.p256dh)||!key(keys.auth))return invalid2("keys must carry the subscription p256dh and auth keys (base64url)");let open=webPushUrl(openUrl);return open===null?invalid2("openUrl must be an https URL of your page"):{body:{endpoint:endpointHref,keys:{p256dh:keys.p256dh,auth:keys.auth},open_url:open,timezone:bounded(timezone,TIMEZONE_MAX),locale:bounded(locale,LOCALE_MAX)}}}function createWebPushClient(runtime){let over=()=>{let{services:services}=runtime.registry;return createWebPushClientOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed2(verb)));return{config:opts=>runtime.isDisposed?gone("config"):over().config(opts),subscribe:input=>runtime.isDisposed?gone("subscribe"):over().subscribe(input),unsubscribe:id=>runtime.isDisposed?gone("unsubscribe"):over().unsubscribe(id)}}function createWebPushClientOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async config(opts){let res=await funnel.send("webPush.config",{method:"GET",path:`${BASE}/config`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return res;let vapid=res.value?.vapid_public_key;return key(vapid)?ok(/* @__PURE__ */Object.freeze({vapidPublicKey:vapid})):err(malformed2("webPush.config"))},async subscribe(input){let checked=validate(input);if(!("body"in checked))return err(checked);let send=body=>funnel.send("webPush.subscribe",{method:"POST",path:`${BASE}/subscriptions`,body:body}),res=await send(checked.body);if(!res.ok&&hintsRefused(res.error)&&(checked.body.timezone!==null||checked.body.locale!==null)&&(res=await send(withoutHints(checked.body))),!res.ok)return res;let id=res.value?.subscription_id;return typeof id=="string"&&SUBSCRIPTION_ID.test(id)?ok(/* @__PURE__ */Object.freeze({subscriptionId:id})):err(malformed2("webPush.subscribe"))},async unsubscribe(subscriptionId){if(typeof subscriptionId!="string"||!SUBSCRIPTION_ID.test(subscriptionId))return err(invalid2("subscriptionId must be a web push subscription id (wps_...)"));let res=await funnel.send("webPush.unsubscribe",{method:"DELETE",path:`${BASE}/subscriptions/${subscriptionId}`});return res.ok?ok(void 0):err(res.error)}}}var LOGOUT_HOOK_BUDGET_MS=3e3;function wireCodeOf2(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}var DEFAULT_SERVICE_WORKER_PATH="/everfur-sw.js",SCOPE_DIRECTORY="everfur-push/",STORE_KEY="everfur.webPush.v1";function applicationServerKeyFromBase64Url(key2){let padded=key2.replace(/=+$/,"").replace(/-/g,"+").replace(/_/g,"/"),base64=padded+"=".repeat((4-padded.length%4)%4),binary=atob(base64),bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index+=1)bytes[index]=binary.charCodeAt(index);return bytes}function ownerTag(userRef){let hash=2166136261;for(let index=0;index<userRef.length;index+=1)hash^=userRef.charCodeAt(index),hash=Math.imul(hash,16777619)>>>0;return hash.toString(16).padStart(8,"0")}function webPushScope(serviceWorkerPath,scope){if(scope!==void 0)return scope;let path=serviceWorkerPath.split("?")[0]??serviceWorkerPath;return`${path.slice(0,path.lastIndexOf("/")+1)}${SCOPE_DIRECTORY}`}function pageOnly(url){return url.split(/[?#]/)[0]??url}function localStore(){let storage=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}};return{read(){try{let raw=storage()?.getItem(STORE_KEY);if(raw==null)return null;let parsed=JSON.parse(raw),owner=parsed?.owner,subscriptionId=parsed?.subscriptionId,endpoint=parsed?.endpoint;return typeof owner!="string"||typeof subscriptionId!="string"||typeof endpoint!="string"?null:{owner:owner,subscriptionId:subscriptionId,endpoint:endpoint}}catch{return null}},write(entry){try{storage()?.setItem(STORE_KEY,JSON.stringify(entry))}catch{}},clear(){try{storage()?.removeItem(STORE_KEY)}catch{}}}}function browserWebPush(){try{let g=globalThis,container=g.navigator?.serviceWorker,notification=g.Notification;if(container===void 0||notification===void 0||g.PushManager===void 0||g.isSecureContext===!1)return null;let asRegistration=value=>typeof value=="object"&&value!==null&&"pushManager"in value?value:null;return{permission:()=>notification.permission,requestPermission:()=>notification.requestPermission(),async register(path,scope){let registration=asRegistration(await container.register(path,{scope:scope}));return registration!==null&&await waitForActive(registration),registration},async existing(scope){return asRegistration(await container.getRegistration(scope))},pageUrl:()=>g.location?.href??"",timeZone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{return null}},locale:()=>typeof g.navigator?.language=="string"&&g.navigator.language.length>0?g.navigator.language:null}}catch{return null}}function waitForActive(registration){let reg=registration,worker=reg.active?null:reg.installing??reg.waiting??null;return worker===null?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,1e4);worker.addEventListener("statechange",()=>{(worker.state==="activated"||worker.state==="redundant")&&(clearTimeout(timer),resolve())})})}var WEB_PUSH_UNAVAILABLE="web_push_unavailable",OUTCOME_BY_PERMISSION=/* @__PURE__ */Object.freeze({default:"dismissed",denied:"denied"});function createWebPushController(deps){let{client:client}=deps,browser=deps.browser===void 0?browserWebPush():deps.browser,store=deps.store??localStore(),owner=ownerTag(deps.userRef),path=deps.options?.serviceWorkerPath??DEFAULT_SERVICE_WORKER_PATH,scope=webPushScope(path,deps.options?.scope),available=null,openUrl=()=>{let page=browser?.pageUrl()??"",open=webPushUrl(deps.options?.openUrl??pageOnly(page));return open===null?null:originOf(open)===originOf(page)?open:(warnOnce(`Everfur web push: openUrl ${originOf(open)??""} is not this page's origin (${originOf(page)??"unknown"}). The service worker opens only its own origin; pass an openUrl on this origin.`),null)},notOffered=error=>error.httpStatus===404?(available=false,true):wireCodeOf2(error)!==WEB_PUSH_UNAVAILABLE?false:(error.raw?.retryable!==true&&(available=false),true),currentSubscription=async()=>{if(browser===null)return null;let registration=await browser.existing(scope).catch(()=>null);return registration===null?null:registration.pushManager.getSubscription().catch(()=>null)},dropForeign=async subscription=>{subscription!==null&&await subscription.unsubscribe().catch(()=>false),store.clear()},register=async subscription=>{let json=subscription.toJSON(),p256dh=json.keys?.p256dh,auth=json.keys?.auth,endpoint=json.endpoint??subscription.endpoint,open=openUrl();if(typeof p256dh!="string"||typeof auth!="string"||typeof endpoint!="string"||open===null||browser===null)return"failed";let res=await client.subscribe({endpoint:endpoint,keys:{p256dh:p256dh,auth:auth},openUrl:open,timezone:browser.timeZone(),locale:browser.locale()});return res.ok?(store.write({owner:owner,subscriptionId:res.value.subscriptionId,endpoint:endpoint}),"ok"):notOffered(res.error)?"unavailable":"failed"},probe=async()=>{if(available!==null)return available;let res=await client.config();if(res.ok)available=true;else if(notOffered(res.error))return false;return available??true};return{async state(){try{if(browser===null)return"unsupported";let permission=browser.permission();if(permission==="denied")return"denied";if(!await probe())return"unavailable";if(permission==="default")return"ask";let subscription=await currentSubscription(),stored=store.read();return subscription!==null&&stored!==null&&stored.owner===owner&&stored.endpoint===subscription.endpoint?"on":"off"}catch{return browser===null?"unsupported":"off"}},async enable(){if(browser===null)return"unsupported";if(available===false)return"unavailable";if(openUrl()===null)return"failed";try{let permission=browser.permission()==="granted"?"granted":await browser.requestPermission();if(permission!=="granted")return OUTCOME_BY_PERMISSION[permission];let registration=await browser.register(path,scope);if(registration===null)return"failed";let config=await client.config();if(!config.ok)return notOffered(config.error)?"unavailable":"failed";available=!0;let existing=await registration.pushManager.getSubscription().catch(()=>null),stored=store.read(),subscription=existing;existing!==null&&(stored===null||stored.owner!==owner)&&(await dropForeign(existing),subscription=null),subscription??=await registration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:applicationServerKeyFromBase64Url(config.value.vapidPublicKey)});let outcome=await register(subscription);return outcome==="ok"?"on":outcome}catch{return"failed"}},async disable(){try{let subscription=await currentSubscription(),stored=store.read();if(stored!==null&&stored.owner===owner){let res=await client.unsubscribe(stored.subscriptionId);if(!res.ok&&res.error.httpStatus!==404)return!1}return subscription!==null&&await subscription.unsubscribe(),store.clear(),!0}catch{return false}},async sync(){try{if(browser===null||browser.permission()!=="granted")return"skipped";let subscription=await currentSubscription(),stored=store.read();if(subscription===null)return stored!==null&&(stored.owner===owner&&client.unsubscribe(stored.subscriptionId),store.clear()),"skipped";if(stored===null||stored.owner!==owner)return await dropForeign(subscription),"reset";let outcome=await register(subscription);return outcome==="ok"?"synced":outcome}catch{return"failed"}},async endForSignOut(signOutClient){try{let stored=store.read(),subscription=await currentSubscription();stored!==null&&stored.owner===owner&&await signOutClient.unsubscribe(stored.subscriptionId),subscription!==null&&await subscription.unsubscribe()}catch{}finally{store.clear()}}}}function originOf(url){try{return new URL(url).origin}catch{return null}}var warned=false;function warnOnce(message){if(warned)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}function useEverfurWebPush(options={}){let{runtime:runtime,userRef:userRef}=useEverfurContext(),{serviceWorkerPath:serviceWorkerPath,scope:scope,openUrl:openUrl}=options,settings=useMemo(()=>({...serviceWorkerPath===void 0?{}:{serviceWorkerPath:serviceWorkerPath},...scope===void 0?{}:{scope:scope},...openUrl===void 0?{}:{openUrl:openUrl}}),[serviceWorkerPath,scope,openUrl]),controller=useMemo(()=>userRef===null?null:createWebPushController({client:createWebPushClient(runtime),userRef:userRef,options:settings}),[runtime,userRef,settings]),[status,setStatus]=useState(controller===null?"signed_out":"checking"),[busy,setBusy]=useState(false),current=useRef(controller);current.current=controller,useEffect(()=>{if(controller===null){setStatus("signed_out");return}let live=true;return setStatus("checking"),(async()=>{await controller.sync();let next=await controller.state();live&&setStatus(next)})(),()=>{live=false}},[controller]),useEffect(()=>runtime.onBeforeLogout(async({userRef:leaving,auth:auth})=>{let funnel=createRequestFunnel({auth:auth,maxAttempts:1,unaryTimeoutMs:LOGOUT_HOOK_BUDGET_MS,...runtime.registry.services.errorPolicy?{errorPolicy:runtime.registry.services.errorPolicy}:{}});await createWebPushController({client:createWebPushClient(runtime),userRef:leaving,options:settings}).endForSignOut(createWebPushClientOver({auth:auth,funnel:funnel}))}),[runtime,settings]);let enable=useCallback(()=>{let mine=current.current;return mine===null?Promise.resolve("failed"):(setBusy(true),mine.enable().then(async outcome=>{let next=await mine.state();return current.current===mine&&(setStatus(next),setBusy(false)),outcome}))},[]),disable=useCallback(async()=>{let mine=current.current;if(mine===null)return false;setBusy(true);let done=await mine.disable(),next=await mine.state();return current.current===mine&&(setStatus(next),setBusy(false)),done},[]);return useMemo(()=>({status:status,busy:busy,enable:enable,disable:disable}),[status,busy,enable,disable])}function tapTarget(ref){return ref.route==null||ref.eventId===null?null:parseEverfurNotification({v:1,event_id:ref.eventId,event_type:ref.route.event_type,target:ref.route.target})?.target??null}var addressTap=null,ADDRESS_TAPS=/* @__PURE__ */new WeakSet;function takeAddressTap(){let taken=takeNotificationOpenFrom(typeof window>"u"?void 0:window);return taken!==null&&(addressTap=taken,ADDRESS_TAPS.add(taken)),taken}function takeEverfurNotificationEventId(){return takeAddressTap()?.eventId??null}function takeEverfurNotificationOpen(){return takeAddressTap()}function firstTap(given){if(given===void 0)return takeAddressTap()??addressTap;if(given===null||typeof given=="string")return addressTap!==null&&addressTap.eventId===given?addressTap:given===null?null:{eventId:given,itemId:null};let tap=notificationOpenOf(given);return tap!==null&&addressTap!==null&&addressTap.eventId===tap.eventId&&addressTap.itemId===tap.itemId?addressTap:tap}function useEverfurNotificationOpen(options){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=useEverfurInboxClient(),onOpen=useRef(options.onOpen);onOpen.current=options.onOpen;let pending=useRef(null);if(pending.current===null){let first=firstTap(options.eventId);pending.current=first===null?[]:[first]}let queue=pending,flush=useRef(()=>{});useEffect(()=>onNotificationMessage(ref=>{queue.current.push(ref),flush.current()}),[]),useEffect(()=>{if(userRef===null)return;let live=true,started=/* @__PURE__ */new Set,unread=inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),controller=createInboxController({client:client,onUnreadCount:count2=>unread.report(count2)}),run=()=>{for(let ref of queue.current)started.has(ref)||(started.add(ref),controller.open({...ref.itemId===null?{}:{itemId:ref.itemId},...ref.eventId===null?{}:{eventId:ref.eventId}}).then(res=>{let at2=queue.current.indexOf(ref);if(!live||at2<0)return;if(queue.current.splice(at2,1),ref===addressTap)addressTap=null;else if(ADDRESS_TAPS.has(ref))return;let inbox=res.ok?res.value:null;callHost(onOpen.current,{eventId:ref.eventId,itemId:ref.itemId,inbox:inbox,target:inbox===null?tapTarget(ref):null})}))};return flush.current=run,run(),()=>{live=false,flush.current=()=>{},controller.dispose()}},[client,userRef,runtime,scopeEpoch])}export{EverfurInbox,createInboxClient,createWebPushClient,takeEverfurNotificationEventId,takeEverfurNotificationOpen,useEverfurInbox,useEverfurInboxClient,useEverfurInboxUnread,useEverfurNotificationOpen,useEverfurWebPush};
|