@everfur/sdk 0.15.1 → 0.16.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 +122 -0
- package/dist/{DepthViews.d-BuEWI6Ln.d.ts → DepthViews.d-A7S-XYiI.d.ts} +1 -1
- package/dist/{DepthViews.d--1daZblh.d.cts → DepthViews.d-C4TIZDfz.d.cts} +1 -1
- package/dist/{DepthViews.d-CKTnEeUo.d.ts → DepthViews.d-CNjaHLAS.d.ts} +1 -1
- package/dist/{DepthViews.d-PuBGdAYk.d.cts → DepthViews.d-DapfRz1S.d.cts} +1 -1
- package/dist/{RecordsPage.d-CBB8sfoY.d.ts → RecordsPage.d-6WMbieaV.d.ts} +1 -1
- package/dist/{RecordsPage.d-Dq5gpQG0.d.cts → RecordsPage.d-B2gLf8RH.d.cts} +1 -1
- package/dist/animations/index.d.cts +5 -5
- package/dist/animations/index.d.ts +5 -5
- package/dist/{Chat.d-BlsnQwCQ.d.ts → appStateLifecycle.d-B7L427MF.d.ts} +64 -141
- package/dist/{Chat.d-BO5iJsR2.d.cts → appStateLifecycle.d-CWedOJq4.d.cts} +64 -141
- package/dist/{attachments.d-DRHsJkni.d.cts → attachments.d-BARh-PrJ.d.cts} +24 -6
- package/dist/{attachments.d-DFP9yvz9.d.ts → attachments.d-CB0R1_vK.d.ts} +24 -6
- package/dist/{attachments.d-C2nkIyDB.d.ts → attachments.d-CPgp4_W-.d.ts} +2 -2
- package/dist/{attachments.d-DRUC35Ti.d.cts → attachments.d-DeoaCEMD.d.cts} +2 -2
- package/dist/{bookingCopy.d-CFL-1Be2.d.ts → bookingCopy.d-BakTjvWw.d.ts} +2 -2
- package/dist/{bookingCopy.d-bF_QknDC.d.cts → bookingCopy.d-CVmpuk9C.d.cts} +2 -2
- package/dist/{casesRepository.d-C__BnffJ.d.ts → casesRepository.d-CuokarTU.d.ts} +1 -1
- package/dist/{casesRepository.d-BMOnT1fg.d.cts → casesRepository.d-DKRLtYb8.d.cts} +1 -1
- package/dist/chat/index.cjs +227 -213
- package/dist/chat/index.d.cts +11 -9
- package/dist/chat/index.d.ts +11 -9
- package/dist/chat/index.js +228 -214
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +6 -6
- package/dist/client/index.d.ts +6 -6
- package/dist/client/index.js +1 -1
- package/dist/{clinicBatch.d-D68RYvc3.d.ts → clinicBatch.d-BP_Rpvcy.d.ts} +2 -2
- package/dist/{clinicBatch.d-C5deJ4xY.d.cts → clinicBatch.d-BTDdhMQ2.d.cts} +2 -2
- package/dist/{config.d-BQgrIDdu.d.cts → config.d-84fNJFv9.d.cts} +1 -1
- package/dist/{config.d-XSMThgVj.d.ts → config.d-B4-Mrwq2.d.ts} +1 -1
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/{context.d-Ba8YyJpk.d.cts → context.d-87MMrNm6.d.cts} +5 -5
- package/dist/{context.d-xoh5vmxS.d.ts → context.d-rNGMZH8T.d.ts} +5 -5
- package/dist/{copy.d-Cq-s-UUv.d.cts → copy.d-CJOLhJac.d.cts} +2 -2
- package/dist/{copy.d-HV9fU5kh.d.ts → copy.d-DbwWriBp.d.ts} +2 -2
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.d.cts +13 -13
- package/dist/core/index.d.ts +13 -13
- package/dist/core/index.js +1 -1
- package/dist/{depth.d-DYnkz8Re.d.cts → depth.d-CXpPxNSK.d.cts} +2 -2
- package/dist/{depth.d-D7kKiYl7.d.ts → depth.d-Dca1T_RH.d.ts} +2 -2
- package/dist/{entitlementRepository.d-DmnUZLl_.d.ts → entitlementRepository.d-BBRYTUlp.d.ts} +2 -2
- package/dist/{entitlementRepository.d-B_kEPLhz.d.cts → entitlementRepository.d-DBhzBQjZ.d.cts} +2 -2
- package/dist/{focus.d-BHm_QtQ9.d.cts → focus.d-BQnOVAql.d.cts} +3 -3
- package/dist/{focus.d-CjL6Cj0m.d.ts → focus.d-BZ2sEpbU.d.ts} +3 -3
- package/dist/health-plan/index.cjs +134 -131
- package/dist/health-plan/index.d.cts +77 -24
- package/dist/health-plan/index.d.ts +77 -24
- package/dist/health-plan/index.js +134 -131
- package/dist/{idempotency.d-BSRK8od4.d.cts → idempotency.d-9wNNohIA.d.cts} +1 -1
- package/dist/{idempotency.d-CFc4CCc9.d.ts → idempotency.d-BdB17veP.d.ts} +1 -1
- package/dist/{identity.d-Be2Es9Td.d.ts → identity.d-DxNvhj3a.d.ts} +1 -1
- package/dist/{identity.d-HbwYQ4-z.d.cts → identity.d-nRZBzkG2.d.cts} +1 -1
- package/dist/index.cjs +232 -218
- package/dist/index.d.cts +14 -12
- package/dist/index.d.ts +14 -12
- package/dist/index.js +233 -219
- package/dist/{introEvents.d-Dr34KIaD.d.cts → introEvents.d-CQeiUeLn.d.cts} +1 -1
- package/dist/{introEvents.d-DflJ6J9H.d.ts → introEvents.d-bkIxpIKr.d.ts} +1 -1
- package/dist/notifications/index.d.cts +4 -4
- package/dist/notifications/index.d.ts +4 -4
- package/dist/{optInView.d-D23o1gtT.d.cts → optInView.d-BbVUUeoG.d.cts} +2 -2
- package/dist/{optInView.d-3mbj1mR6.d.ts → optInView.d-DVJcB4Gp.d.ts} +2 -2
- package/dist/{parse.d-BERabxHw.d.ts → parse.d-CGeJrcAC.d.ts} +1 -1
- package/dist/{parse.d-4lUXdmvY.d.cts → parse.d-Dk0BasyK.d.cts} +1 -1
- package/dist/{pets.d-D_ayuqjp.d.ts → pets.d-DBopbeRe.d.ts} +1 -1
- package/dist/{pets.d-CHU0UbXt.d.cts → pets.d-DVptPgi0.d.cts} +1 -1
- package/dist/{petsRepository.d-DUaAWoTv.d.ts → petsRepository.d-BtuooSOW.d.ts} +1 -1
- package/dist/{petsRepository.d-Bwfe8yuR.d.cts → petsRepository.d-Daef7u0o.d.cts} +1 -1
- package/dist/{ports.d-DzEJMVRs.d.ts → ports.d-BxCVSbSi.d.ts} +4 -4
- package/dist/{ports.d-ClbPRUtx.d.cts → ports.d-CAT70bVD.d.cts} +4 -4
- package/dist/records/depth/index.cjs +1 -1
- 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 -1
- package/dist/records/index.cjs +242 -200
- package/dist/records/index.d.cts +169 -73
- package/dist/records/index.d.ts +169 -73
- package/dist/records/index.js +243 -201
- package/dist/{requestFunnel.d-YabU6G-Z.d.ts → requestFunnel.d-Cxt0JqYx.d.ts} +2 -2
- package/dist/{requestFunnel.d-JoqddYSx.d.cts → requestFunnel.d-mEu6B-n8.d.cts} +2 -2
- package/dist/{runtimeTypes.d-DQTBJAbk.d.ts → runtimeTypes.d-Bkcj_XQy.d.ts} +4 -4
- package/dist/{runtimeTypes.d-Cv38YuzP.d.cts → runtimeTypes.d-D_qHJROH.d.cts} +4 -4
- package/dist/{screenProps.d-C-AuHoyF.d.cts → screenProps.d-CR1lrpzR.d.cts} +2 -2
- package/dist/{screenProps.d-BuJLzFkN.d.ts → screenProps.d-D9n-ancr.d.ts} +2 -2
- package/dist/server/events/index.cjs +1 -1
- package/dist/server/events/index.d.cts +2 -2
- package/dist/server/events/index.d.ts +2 -2
- package/dist/server/events/index.js +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +3 -3
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +1 -1
- package/dist/shop/index.cjs +16 -16
- package/dist/shop/index.d.cts +12 -3
- package/dist/shop/index.d.ts +12 -3
- package/dist/shop/index.js +16 -16
- package/dist/tabs/index.cjs +4 -4
- package/dist/tabs/index.d.cts +34 -15
- package/dist/tabs/index.d.ts +34 -15
- package/dist/tabs/index.js +5 -5
- package/dist/{tabsModel.d-BfIQg6yS.d.ts → tabsModel.d-B7QMug1u.d.cts} +1 -17
- package/dist/{tabsModel.d-BfIQg6yS.d.cts → tabsModel.d-B7QMug1u.d.ts} +1 -17
- package/dist/televet/booking/index.d.cts +6 -6
- package/dist/televet/booking/index.d.ts +6 -6
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/rn/index.cjs +1 -1
- package/dist/testing/rn/index.d.cts +7 -7
- package/dist/testing/rn/index.d.ts +7 -7
- package/dist/testing/rn/index.js +1 -1
- package/dist/testing/web/index.d.cts +7 -7
- package/dist/testing/web/index.d.ts +7 -7
- package/dist/texting/index.cjs +21 -16
- package/dist/texting/index.d.cts +5 -5
- package/dist/texting/index.d.ts +5 -5
- package/dist/texting/index.js +22 -17
- package/dist/threadOptions.d-6hfQS1x7.d.cts +55 -0
- package/dist/threadOptions.d-6hfQS1x7.d.ts +55 -0
- package/dist/threadOptions.d-BEG-LZrC.d.cts +147 -0
- package/dist/threadOptions.d-BerQM1Ql.d.ts +147 -0
- package/dist/{threadOptions.d-8x_1evAr.d.ts → threadOptions.d-BgBvSIw8.d.ts} +6 -40
- package/dist/{threadOptions.d-DBrmOwmb.d.cts → threadOptions.d-P9v7I7va.d.cts} +6 -40
- package/dist/{timelineRows.d-B6lLC8Ud.d.cts → timelineRows.d-C04lp_Vj.d.cts} +1 -1
- package/dist/{timelineRows.d-Brlkti-G.d.ts → timelineRows.d-_7JemrY-.d.ts} +1 -1
- package/dist/{planSignals.d-CON9gTvJ.d.ts → useHealthPlanSubscription.d-CUbHE6eK.d.ts} +81 -3
- package/dist/{planSignals.d-Dha2CMDF.d.cts → useHealthPlanSubscription.d-OhLZpn-n.d.cts} +81 -3
- package/dist/{usePresentation.d-Bne14SlX.d.ts → usePresentation.d-CBtBx38t.d.ts} +40 -40
- package/dist/{usePresentation.d-BcdCIuEU.d.cts → usePresentation.d-YkJeq9mf.d.cts} +40 -40
- package/dist/{useRecordsDepth.d-DAa169VY.d.cts → useRecordsDepth.d-FTImzp6T.d.cts} +1 -1
- package/dist/{useRecordsDepth.d-Cd6J03o5.d.ts → useRecordsDepth.d-_rqDIvoq.d.ts} +1 -1
- package/dist/{view.d-3d5_O7Xk.d.cts → view.d-Dd6AfMvG.d.cts} +3 -3
- package/dist/{view.d-DkGM8GNA.d.ts → view.d-gmYinlac.d.ts} +3 -3
- package/dist/web/consent/index.d.cts +5 -5
- package/dist/web/consent/index.d.ts +5 -5
- package/dist/web/health-plan/index.cjs +1 -1
- package/dist/web/health-plan/index.d.cts +15 -69
- package/dist/web/health-plan/index.d.ts +15 -69
- package/dist/web/health-plan/index.js +1 -1
- package/dist/web/index.cjs +5 -5
- package/dist/web/index.d.cts +26 -43
- package/dist/web/index.d.ts +26 -43
- package/dist/web/index.js +5 -5
- package/dist/web/intro/index.d.cts +6 -6
- package/dist/web/intro/index.d.ts +6 -6
- package/dist/web/notifications/index.d.cts +3 -3
- package/dist/web/notifications/index.d.ts +3 -3
- package/dist/web/records/depth/index.d.cts +9 -9
- package/dist/web/records/depth/index.d.ts +9 -9
- package/dist/web/records/index.d.cts +11 -11
- package/dist/web/records/index.d.ts +11 -11
- package/dist/web/records-sheet/index.cjs +10 -10
- package/dist/web/records-sheet/index.js +10 -10
- package/dist/web/shop/index.cjs +11 -11
- package/dist/web/shop/index.d.cts +3 -3
- package/dist/web/shop/index.d.ts +3 -3
- package/dist/web/shop/index.js +11 -11
- package/dist/web/televet/booking/index.d.cts +6 -6
- package/dist/web/televet/booking/index.d.ts +6 -6
- package/dist/web/texting/index.d.cts +5 -5
- package/dist/web/texting/index.d.ts +5 -5
- package/package.json +6 -2
package/dist/web/index.d.cts
CHANGED
|
@@ -1,44 +1,45 @@
|
|
|
1
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
2
|
import { ReactNode, CSSProperties } from 'react';
|
|
3
|
-
import { E as EverfurProviderProps } from '../context.d-
|
|
4
|
-
export { a as EverfurConfig, b as EverfurHandle, c as EverfurUser, U as UseEverfurPetProfileState, u as useCapability, d as useEverfur, e as useEverfurPetProfile, f as useEverfurTheme } from '../context.d-
|
|
3
|
+
import { E as EverfurProviderProps } from '../context.d-87MMrNm6.cjs';
|
|
4
|
+
export { a as EverfurConfig, b as EverfurHandle, c as EverfurUser, U as UseEverfurPetProfileState, u as useCapability, d as useEverfur, e as useEverfurPetProfile, f as useEverfurTheme } from '../context.d-87MMrNm6.cjs';
|
|
5
5
|
import { C as CapabilityName, a as CapabilityDecision } from '../resolve.d-CoQWUy1Y.cjs';
|
|
6
6
|
export { b as CapabilityDisabled, D as DisabledLevel } from '../resolve.d-CoQWUy1Y.cjs';
|
|
7
|
-
import { U as UrgencyDisplayLevel, E as EverfurChatDraftStore } from '../attachments.d-
|
|
8
|
-
export { C as ChatFeedbackReason, a as ChatFeedbackReasonOption,
|
|
7
|
+
import { U as UrgencyDisplayLevel, E as EverfurChatDraftStore, b as ChatFollowUpPolicy } from '../attachments.d-BARh-PrJ.cjs';
|
|
8
|
+
export { C as ChatFeedbackReason, a as ChatFeedbackReasonOption, c as ChatSentiment, d as UseChatAttachmentsOptions, e as UseChatAttachmentsState, f as UseEverfurChatState, g as UseEverfurPetsState, u as useChatAttachments, h as useEverfurChat, i as useEverfurPets } from '../attachments.d-BARh-PrJ.cjs';
|
|
9
9
|
import { P as PetRef, C as ConversationId } from '../ids.d-B2GAAifq.cjs';
|
|
10
10
|
export { B as Brand, a as ClientId, b as ResponseId, U as UserRef, _ as __brand, c as conversationId, p as petRef, u as userRef } from '../ids.d-B2GAAifq.cjs';
|
|
11
|
-
import { a as ChatCheckinTarget } from '../ports.d-
|
|
12
|
-
export { C as ChatCheckin, b as ChatConversation, c as ChatConversationListOptions, d as ChatConversationPage, e as ChatFeedbackReceipt, f as ChatFeedbackType, g as ChatHistoryOptions, i as ChatMessage, h as ChatMessagePage, j as ChatMessageRole, k as ChatMessageSender, l as ChatStatus, m as Citation, P as PresignedPolicy, S as SendOptions, U as UploadPort } from '../ports.d-
|
|
11
|
+
import { a as ChatCheckinTarget } from '../ports.d-CAT70bVD.cjs';
|
|
12
|
+
export { C as ChatCheckin, b as ChatConversation, c as ChatConversationListOptions, d as ChatConversationPage, e as ChatFeedbackReceipt, f as ChatFeedbackType, g as ChatHistoryOptions, i as ChatMessage, h as ChatMessagePage, j as ChatMessageRole, k as ChatMessageSender, l as ChatStatus, m as Citation, P as PresignedPolicy, S as SendOptions, U as UploadPort } from '../ports.d-CAT70bVD.cjs';
|
|
13
13
|
import { i as EverfurPresentationInput } from '../presentation.d-vy8kTGfR.cjs';
|
|
14
14
|
export { D as DEFAULT_PRESENTATION, E as EverfurChatAnswerStyle, a as EverfurChatComposerPlaceholder, b as EverfurChatComposerStyle, c as EverfurChatHistoryBarSetting, d as EverfurChatHistoryStyle, e as EverfurChatSendButtonSetting, f as EverfurChatTopCardSetting, g as EverfurHealthPlanLayout, h as EverfurPresentation, l as EverfurPresentationField, j as EverfurSafetyDisclaimerPlacement, p as parsePresentation, r as resolvePresentation } from '../presentation.d-vy8kTGfR.cjs';
|
|
15
|
-
import { P as PetProfileInput } from '../petsRepository.d-
|
|
16
|
-
export { a as PetProfilePatch, R as RegisteredPet, W as WidgetPet, b as WidgetPetProfile } from '../petsRepository.d-
|
|
15
|
+
import { P as PetProfileInput } from '../petsRepository.d-Daef7u0o.cjs';
|
|
16
|
+
export { a as PetProfilePatch, R as RegisteredPet, W as WidgetPet, b as WidgetPetProfile } from '../petsRepository.d-Daef7u0o.cjs';
|
|
17
17
|
import { L as LifecyclePort } from '../LifecyclePort.d-Cr1p33a7.cjs';
|
|
18
18
|
import { E as EverfurStarterPrompt } from '../quickPrompts.d-NM_81Jc1.cjs';
|
|
19
|
-
import { h as
|
|
20
|
-
export {
|
|
21
|
-
|
|
22
|
-
export {
|
|
19
|
+
import { h as EverfurChatEmptyState, i as EverfurChatHistoryBar, j as EverfurChatOpeningCard, k as EverfurChatAnswerCards, E as EverfurChatTopCard, l as EverfurChatHistorySheet, b as EverfurHealthPlanProps } from '../threadOptions.d-P9v7I7va.cjs';
|
|
20
|
+
export { m as EverfurChatAnswerCard, n as EverfurChatAnswerContext, o as EverfurChatFollowUpAction } from '../threadOptions.d-P9v7I7va.cjs';
|
|
21
|
+
import { a as EverfurChatEmptyHeaderContext } from '../threadOptions.d-6hfQS1x7.cjs';
|
|
22
|
+
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-84fNJFv9.cjs';
|
|
23
|
+
export { C as CheckinAnswer, a as CheckinOutcome, W as WatchCase } from '../casesRepository.d-DKRLtYb8.cjs';
|
|
23
24
|
export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode, c as categoryFor, i as isRetryableCode, u as userFacingError } from '../EverfurError.d-8NHtlgzA.cjs';
|
|
24
|
-
export { A as AttachmentError, a as AttachmentErrorCode, b as AttachmentOutcome, c as AttachmentQueue, d as AttachmentState, e as AttachmentStatus } from '../attachments.d-
|
|
25
|
+
export { A as AttachmentError, a as AttachmentErrorCode, b as AttachmentOutcome, c as AttachmentQueue, d as AttachmentState, e as AttachmentStatus } from '../attachments.d-DeoaCEMD.cjs';
|
|
25
26
|
import { U as UploadTransport, F as FileHandle } from '../ports.d-BX4f4UsB.cjs';
|
|
26
27
|
export { b as FilePort, a as UploadPolicyWire } from '../ports.d-BX4f4UsB.cjs';
|
|
27
28
|
import { C as CaptureRecordsSignature } from '../clinicRequestProps.d-1dCtouGA.cjs';
|
|
28
|
-
import { E as EverfurRecordsPageProps } from '../RecordsPage.d-
|
|
29
|
-
import { E as EverfurIntroCopy, a as EverfurIntroBlank, b as EverfurRecordsRequested, d as EverfurRecordsLanded } from '../introEvents.d-
|
|
30
|
-
import {
|
|
31
|
-
export { b as EVERFUR_TABS_COPY } from '../tabsModel.d-
|
|
29
|
+
import { E as EverfurRecordsPageProps } from '../RecordsPage.d-B2gLf8RH.cjs';
|
|
30
|
+
import { E as EverfurIntroCopy, a as EverfurIntroBlank, b as EverfurRecordsRequested, d as EverfurRecordsLanded } from '../introEvents.d-CQeiUeLn.cjs';
|
|
31
|
+
import { E as EverfurTabId, a as EverfurTabsCopy } from '../tabsModel.d-B7QMug1u.cjs';
|
|
32
|
+
export { b as EVERFUR_TABS_COPY } from '../tabsModel.d-B7QMug1u.cjs';
|
|
32
33
|
export { E as EVERFUR_RECORDS_LANDED_EVENT, a as EVERFUR_RECORDS_REQUESTED_EVENT } from '../introEvents.d-dS3fJCH1.cjs';
|
|
33
|
-
export { L as useEverfurPresentation } from '../usePresentation.d-
|
|
34
|
+
export { L as useEverfurPresentation } from '../usePresentation.d-YkJeq9mf.cjs';
|
|
34
35
|
import { K as KvPort } from '../cacheEpoch.d-DknKn3S0.cjs';
|
|
35
36
|
export { I as ImageCachePort } from '../cacheEpoch.d-DknKn3S0.cjs';
|
|
36
|
-
export { E as EverfurClientEvent, a as EverfurEventHandler, L as LogLevel, b as LogRecord, c as LogSink, P as PrepareOptions, d as PrepareResult, e as PrepareStatus, S as SecureStorePort } from '../runtimeTypes.d-
|
|
37
|
+
export { E as EverfurClientEvent, a as EverfurEventHandler, L as LogLevel, b as LogRecord, c as LogSink, P as PrepareOptions, d as PrepareResult, e as PrepareStatus, S as SecureStorePort } from '../runtimeTypes.d-D_qHJROH.cjs';
|
|
37
38
|
export { T as TelemetryPort } from '../TelemetryPort.d-BDNr00hu.cjs';
|
|
38
39
|
export { E as ErrorPolicyPort } from '../ErrorPolicyPort.d-DirW9hgO.cjs';
|
|
39
40
|
export { C as CameraPort, a as CaptureOptions, M as MediaSource } from '../CameraPort.d-Cv31Pz7g.cjs';
|
|
40
41
|
export { a as EverfurConfigError, E as EverfurResult, b as EverfurThrownError, i as isErr, c as isOk, u as unwrap } from '../EverfurResult.d-BFH-3s6E.cjs';
|
|
41
|
-
export { M as MintedToken, T as TokenProvider } from '../identity.d-
|
|
42
|
+
export { M as MintedToken, T as TokenProvider } from '../identity.d-nRZBzkG2.cjs';
|
|
42
43
|
export { E as EverfurFaceStyle, a as EverfurThemeAdjustment, f as face, h as headingFace, p as previewTheme, t as themeAdjustments } from '../typeStyle.d-DmlwyJq-.cjs';
|
|
43
44
|
import { E as EverfurThemeInput } from '../branding.d-Bbc6p1XY.cjs';
|
|
44
45
|
export { A as APPEARANCE_PRESETS, a as APPEARANCE_PRESET_NAMES, b as APPEARANCE_SIZE_RANGES, c as EverfurAppearance, d as EverfurAppearanceFont, e as EverfurAppearancePreset, f as EverfurAppearanceRules, g as EverfurAppearanceVariables, h as EverfurThemeFontFaceKey, i as EverfurThemeFontUrlsInput, j as EverfurThemeFontsInput, k as EverfurThemeSlotInput, l as EverfurThemeSlotsInput, m as expandAppearance } from '../branding.d-Bbc6p1XY.cjs';
|
|
@@ -46,35 +47,17 @@ import { d as EverfurFontWeight, m as EverfurTheme, a as EverfurFontFaceKey } fr
|
|
|
46
47
|
export { E as EverfurColorTokens, b as EverfurFontFamilies, c as EverfurFontSource, e as EverfurLetterSpacingTokens, f as EverfurLineHeightTokens, g as EverfurMotionDurationTokens, h as EverfurMotionTokens, i as EverfurRadiusTokens, j as EverfurSpaceTokens, k as EverfurSpringToken, l as EverfurTextColorTokens, n as EverfurThemeMeta, o as EverfurThemeSlot, p as EverfurThemeSlotKey, q as EverfurThemeSlotName, r as EverfurThemeSlots, s as EverfurTypeSizeTokens, t as EverfurTypeTokens, u as EverfurWeightTokens, T as THEME_SLOT_KEYS, v as THEME_SLOT_KEYS_BY_SLOT, w as THEME_SLOT_NAMES, x as themeSlotKeysFor } from '../tokens.d-BUVqme2D.cjs';
|
|
47
48
|
export { b as PetActivityLevel, c as PetAllergy, d as PetAllergySeverity, e as PetBirthDatePrecision, f as PetCondition, a as PetHealthProfile, P as PetHealthProfileInput, g as PetIndoorOutdoor, h as PetMedication, i as PetSex } from '../profile.d-CSs1wlXT.cjs';
|
|
48
49
|
export { C as CanonicalPetSpecies, c as canonicalPetSpecies } from '../species.d-BXAIMh7I.cjs';
|
|
49
|
-
import '../requestFunnel.d-
|
|
50
|
-
import '../focus.d-
|
|
50
|
+
import '../requestFunnel.d-mEu6B-n8.cjs';
|
|
51
|
+
import '../focus.d-BQnOVAql.cjs';
|
|
51
52
|
import '../clinicModels.d-BXgKZqDb.cjs';
|
|
52
53
|
import '../models.d-BSqvbTE1.cjs';
|
|
53
54
|
import '../useRecords.d-BYNX01El.cjs';
|
|
54
55
|
import '../features.d-DrQxTw3-.cjs';
|
|
55
|
-
import '../screenProps.d-
|
|
56
|
-
import '../clinicBatch.d-
|
|
56
|
+
import '../screenProps.d-CR1lrpzR.cjs';
|
|
57
|
+
import '../clinicBatch.d-BTDdhMQ2.cjs';
|
|
57
58
|
import '../recordsAsk.d-C5CGSi3j.cjs';
|
|
58
59
|
import '../sheetSeam.d-BBuEIVsa.cjs';
|
|
59
60
|
|
|
60
|
-
/**
|
|
61
|
-
* A host's rule for the follow-ups under a reply (`EverfurChat`'s `followUpPolicy`, opt-in). Without one the
|
|
62
|
-
* surface draws `visibleFollowUps` exactly as before.
|
|
63
|
-
*/
|
|
64
|
-
interface ChatFollowUpPolicy {
|
|
65
|
-
/** How many to draw, 1 to 5. With `fill` the surface draws exactly this many whenever it can. Default 3. */
|
|
66
|
-
readonly count?: number;
|
|
67
|
-
/** Drop a backend prompt this matches (a visit or booking follow-up a host does not offer). */
|
|
68
|
-
readonly exclude?: RegExp | ((prompt: string) => boolean);
|
|
69
|
-
/**
|
|
70
|
-
* The host's own prompts that top the list up to `count` after the backend's (in order, de-duplicated, the
|
|
71
|
-
* `exclude` rule applied too). A function receives the member's last question, so the top-ups can follow it.
|
|
72
|
-
*/
|
|
73
|
-
readonly fill?: readonly string[] | ((lastQuestion: string | null) => readonly string[]);
|
|
74
|
-
/** A visible label over the follow-ups ("Follow-up questions"). Absent, the list keeps only its accessible name. */
|
|
75
|
-
readonly label?: string;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
61
|
/**
|
|
79
62
|
* Wrap the tree ONCE, high. Mounting constructs the runtime (transport, identity, registry,
|
|
80
63
|
* entitlement repository, pollers) exactly once and starts fail-closed: a bad manifest/entitlement
|
|
@@ -510,4 +493,4 @@ declare function headingFaceCss(theme: EverfurTheme, fallback?: EverfurFontFaceK
|
|
|
510
493
|
*/
|
|
511
494
|
declare function createLocalStorageKv(): KvPort;
|
|
512
495
|
|
|
513
|
-
export { CapabilityDecision, CapabilityGate, type CapabilityGateProps, CapabilityName, ChatCheckinTarget,
|
|
496
|
+
export { CapabilityDecision, CapabilityGate, type CapabilityGateProps, CapabilityName, ChatCheckinTarget, ChatFollowUpPolicy, ConversationId, EverfurChat, EverfurChatAnswerCards, EverfurChatDraftStore, EverfurChatEmptyHeaderContext, EverfurChatEmptyState, EverfurChatHistoryBar, EverfurChatHistorySheet, EverfurChatOpeningCard, type EverfurChatProps, EverfurChatTopCard, type EverfurFaceCss, EverfurFontFaceKey, EverfurFontWeight, EverfurPoweredBy, type EverfurPoweredByProps, EverfurPresentationInput, EverfurProvider, EverfurProviderProps, EverfurRecordsLanded, EverfurRecordsRequested, EverfurStarterPrompt, EverfurTabId, EverfurTabs, type EverfurTabsChatProps, type EverfurTabsClassNames, EverfurTabsCopy, type EverfurTabsHandle, type EverfurTabsIntro, type EverfurTabsOpened, type EverfurTabsPlanProps, type EverfurTabsProps, type EverfurTabsRecordsProps, EverfurTheme, EverfurThemeInput, EverfurThemeProvider, type EverfurThemeProviderProps, FileHandle, KvPort, LifecyclePort, PetProfileInput, PetRef, UploadTransport, UrgencyDisplayLevel, type WebAttachmentTransportOptions, createBrowserLifecycle, createLocalStorageKv, createWebAttachmentTransport, faceCss, fileToAttachmentHandle, headingFaceCss, useEverfurTabs, useHostPoweredBy };
|
package/dist/web/index.d.ts
CHANGED
|
@@ -1,44 +1,45 @@
|
|
|
1
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
2
|
import { ReactNode, CSSProperties } from 'react';
|
|
3
|
-
import { E as EverfurProviderProps } from '../context.d-
|
|
4
|
-
export { a as EverfurConfig, b as EverfurHandle, c as EverfurUser, U as UseEverfurPetProfileState, u as useCapability, d as useEverfur, e as useEverfurPetProfile, f as useEverfurTheme } from '../context.d-
|
|
3
|
+
import { E as EverfurProviderProps } from '../context.d-rNGMZH8T.js';
|
|
4
|
+
export { a as EverfurConfig, b as EverfurHandle, c as EverfurUser, U as UseEverfurPetProfileState, u as useCapability, d as useEverfur, e as useEverfurPetProfile, f as useEverfurTheme } from '../context.d-rNGMZH8T.js';
|
|
5
5
|
import { C as CapabilityName, a as CapabilityDecision } from '../resolve.d-CoQWUy1Y.js';
|
|
6
6
|
export { b as CapabilityDisabled, D as DisabledLevel } from '../resolve.d-CoQWUy1Y.js';
|
|
7
|
-
import { U as UrgencyDisplayLevel, E as EverfurChatDraftStore } from '../attachments.d-
|
|
8
|
-
export { C as ChatFeedbackReason, a as ChatFeedbackReasonOption,
|
|
7
|
+
import { U as UrgencyDisplayLevel, E as EverfurChatDraftStore, b as ChatFollowUpPolicy } from '../attachments.d-CB0R1_vK.js';
|
|
8
|
+
export { C as ChatFeedbackReason, a as ChatFeedbackReasonOption, c as ChatSentiment, d as UseChatAttachmentsOptions, e as UseChatAttachmentsState, f as UseEverfurChatState, g as UseEverfurPetsState, u as useChatAttachments, h as useEverfurChat, i as useEverfurPets } from '../attachments.d-CB0R1_vK.js';
|
|
9
9
|
import { P as PetRef, C as ConversationId } from '../ids.d-B2GAAifq.js';
|
|
10
10
|
export { B as Brand, a as ClientId, b as ResponseId, U as UserRef, _ as __brand, c as conversationId, p as petRef, u as userRef } from '../ids.d-B2GAAifq.js';
|
|
11
|
-
import { a as ChatCheckinTarget } from '../ports.d-
|
|
12
|
-
export { C as ChatCheckin, b as ChatConversation, c as ChatConversationListOptions, d as ChatConversationPage, e as ChatFeedbackReceipt, f as ChatFeedbackType, g as ChatHistoryOptions, i as ChatMessage, h as ChatMessagePage, j as ChatMessageRole, k as ChatMessageSender, l as ChatStatus, m as Citation, P as PresignedPolicy, S as SendOptions, U as UploadPort } from '../ports.d-
|
|
11
|
+
import { a as ChatCheckinTarget } from '../ports.d-BxCVSbSi.js';
|
|
12
|
+
export { C as ChatCheckin, b as ChatConversation, c as ChatConversationListOptions, d as ChatConversationPage, e as ChatFeedbackReceipt, f as ChatFeedbackType, g as ChatHistoryOptions, i as ChatMessage, h as ChatMessagePage, j as ChatMessageRole, k as ChatMessageSender, l as ChatStatus, m as Citation, P as PresignedPolicy, S as SendOptions, U as UploadPort } from '../ports.d-BxCVSbSi.js';
|
|
13
13
|
import { i as EverfurPresentationInput } from '../presentation.d-vy8kTGfR.js';
|
|
14
14
|
export { D as DEFAULT_PRESENTATION, E as EverfurChatAnswerStyle, a as EverfurChatComposerPlaceholder, b as EverfurChatComposerStyle, c as EverfurChatHistoryBarSetting, d as EverfurChatHistoryStyle, e as EverfurChatSendButtonSetting, f as EverfurChatTopCardSetting, g as EverfurHealthPlanLayout, h as EverfurPresentation, l as EverfurPresentationField, j as EverfurSafetyDisclaimerPlacement, p as parsePresentation, r as resolvePresentation } from '../presentation.d-vy8kTGfR.js';
|
|
15
|
-
import { P as PetProfileInput } from '../petsRepository.d-
|
|
16
|
-
export { a as PetProfilePatch, R as RegisteredPet, W as WidgetPet, b as WidgetPetProfile } from '../petsRepository.d-
|
|
15
|
+
import { P as PetProfileInput } from '../petsRepository.d-BtuooSOW.js';
|
|
16
|
+
export { a as PetProfilePatch, R as RegisteredPet, W as WidgetPet, b as WidgetPetProfile } from '../petsRepository.d-BtuooSOW.js';
|
|
17
17
|
import { L as LifecyclePort } from '../LifecyclePort.d-Cr1p33a7.js';
|
|
18
18
|
import { E as EverfurStarterPrompt } from '../quickPrompts.d-NM_81Jc1.js';
|
|
19
|
-
import { h as
|
|
20
|
-
export {
|
|
21
|
-
|
|
22
|
-
export {
|
|
19
|
+
import { h as EverfurChatEmptyState, i as EverfurChatHistoryBar, j as EverfurChatOpeningCard, k as EverfurChatAnswerCards, E as EverfurChatTopCard, l as EverfurChatHistorySheet, b as EverfurHealthPlanProps } from '../threadOptions.d-BgBvSIw8.js';
|
|
20
|
+
export { m as EverfurChatAnswerCard, n as EverfurChatAnswerContext, o as EverfurChatFollowUpAction } from '../threadOptions.d-BgBvSIw8.js';
|
|
21
|
+
import { a as EverfurChatEmptyHeaderContext } from '../threadOptions.d-6hfQS1x7.js';
|
|
22
|
+
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-B4-Mrwq2.js';
|
|
23
|
+
export { C as CheckinAnswer, a as CheckinOutcome, W as WatchCase } from '../casesRepository.d-CuokarTU.js';
|
|
23
24
|
export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode, c as categoryFor, i as isRetryableCode, u as userFacingError } from '../EverfurError.d-8NHtlgzA.js';
|
|
24
|
-
export { A as AttachmentError, a as AttachmentErrorCode, b as AttachmentOutcome, c as AttachmentQueue, d as AttachmentState, e as AttachmentStatus } from '../attachments.d-
|
|
25
|
+
export { A as AttachmentError, a as AttachmentErrorCode, b as AttachmentOutcome, c as AttachmentQueue, d as AttachmentState, e as AttachmentStatus } from '../attachments.d-CPgp4_W-.js';
|
|
25
26
|
import { U as UploadTransport, F as FileHandle } from '../ports.d-BX4f4UsB.js';
|
|
26
27
|
export { b as FilePort, a as UploadPolicyWire } from '../ports.d-BX4f4UsB.js';
|
|
27
28
|
import { C as CaptureRecordsSignature } from '../clinicRequestProps.d-CjsMg_OD.js';
|
|
28
|
-
import { E as EverfurRecordsPageProps } from '../RecordsPage.d-
|
|
29
|
-
import { E as EverfurIntroCopy, a as EverfurIntroBlank, b as EverfurRecordsRequested, d as EverfurRecordsLanded } from '../introEvents.d-
|
|
30
|
-
import {
|
|
31
|
-
export { b as EVERFUR_TABS_COPY } from '../tabsModel.d-
|
|
29
|
+
import { E as EverfurRecordsPageProps } from '../RecordsPage.d-6WMbieaV.js';
|
|
30
|
+
import { E as EverfurIntroCopy, a as EverfurIntroBlank, b as EverfurRecordsRequested, d as EverfurRecordsLanded } from '../introEvents.d-bkIxpIKr.js';
|
|
31
|
+
import { E as EverfurTabId, a as EverfurTabsCopy } from '../tabsModel.d-B7QMug1u.js';
|
|
32
|
+
export { b as EVERFUR_TABS_COPY } from '../tabsModel.d-B7QMug1u.js';
|
|
32
33
|
export { E as EVERFUR_RECORDS_LANDED_EVENT, a as EVERFUR_RECORDS_REQUESTED_EVENT } from '../introEvents.d-dS3fJCH1.js';
|
|
33
|
-
export { L as useEverfurPresentation } from '../usePresentation.d-
|
|
34
|
+
export { L as useEverfurPresentation } from '../usePresentation.d-CBtBx38t.js';
|
|
34
35
|
import { K as KvPort } from '../cacheEpoch.d-DknKn3S0.js';
|
|
35
36
|
export { I as ImageCachePort } from '../cacheEpoch.d-DknKn3S0.js';
|
|
36
|
-
export { E as EverfurClientEvent, a as EverfurEventHandler, L as LogLevel, b as LogRecord, c as LogSink, P as PrepareOptions, d as PrepareResult, e as PrepareStatus, S as SecureStorePort } from '../runtimeTypes.d-
|
|
37
|
+
export { E as EverfurClientEvent, a as EverfurEventHandler, L as LogLevel, b as LogRecord, c as LogSink, P as PrepareOptions, d as PrepareResult, e as PrepareStatus, S as SecureStorePort } from '../runtimeTypes.d-Bkcj_XQy.js';
|
|
37
38
|
export { T as TelemetryPort } from '../TelemetryPort.d-BDNr00hu.js';
|
|
38
39
|
export { E as ErrorPolicyPort } from '../ErrorPolicyPort.d-68yrE3BE.js';
|
|
39
40
|
export { C as CameraPort, a as CaptureOptions, M as MediaSource } from '../CameraPort.d-Cv31Pz7g.js';
|
|
40
41
|
export { a as EverfurConfigError, E as EverfurResult, b as EverfurThrownError, i as isErr, c as isOk, u as unwrap } from '../EverfurResult.d-D_-254ZY.js';
|
|
41
|
-
export { M as MintedToken, T as TokenProvider } from '../identity.d-
|
|
42
|
+
export { M as MintedToken, T as TokenProvider } from '../identity.d-DxNvhj3a.js';
|
|
42
43
|
export { E as EverfurFaceStyle, a as EverfurThemeAdjustment, f as face, h as headingFace, p as previewTheme, t as themeAdjustments } from '../typeStyle.d-B3Kdtjie.js';
|
|
43
44
|
import { E as EverfurThemeInput } from '../branding.d-y6c0UwhE.js';
|
|
44
45
|
export { A as APPEARANCE_PRESETS, a as APPEARANCE_PRESET_NAMES, b as APPEARANCE_SIZE_RANGES, c as EverfurAppearance, d as EverfurAppearanceFont, e as EverfurAppearancePreset, f as EverfurAppearanceRules, g as EverfurAppearanceVariables, h as EverfurThemeFontFaceKey, i as EverfurThemeFontUrlsInput, j as EverfurThemeFontsInput, k as EverfurThemeSlotInput, l as EverfurThemeSlotsInput, m as expandAppearance } from '../branding.d-y6c0UwhE.js';
|
|
@@ -46,35 +47,17 @@ import { d as EverfurFontWeight, m as EverfurTheme, a as EverfurFontFaceKey } fr
|
|
|
46
47
|
export { E as EverfurColorTokens, b as EverfurFontFamilies, c as EverfurFontSource, e as EverfurLetterSpacingTokens, f as EverfurLineHeightTokens, g as EverfurMotionDurationTokens, h as EverfurMotionTokens, i as EverfurRadiusTokens, j as EverfurSpaceTokens, k as EverfurSpringToken, l as EverfurTextColorTokens, n as EverfurThemeMeta, o as EverfurThemeSlot, p as EverfurThemeSlotKey, q as EverfurThemeSlotName, r as EverfurThemeSlots, s as EverfurTypeSizeTokens, t as EverfurTypeTokens, u as EverfurWeightTokens, T as THEME_SLOT_KEYS, v as THEME_SLOT_KEYS_BY_SLOT, w as THEME_SLOT_NAMES, x as themeSlotKeysFor } from '../tokens.d-BUVqme2D.js';
|
|
47
48
|
export { b as PetActivityLevel, c as PetAllergy, d as PetAllergySeverity, e as PetBirthDatePrecision, f as PetCondition, a as PetHealthProfile, P as PetHealthProfileInput, g as PetIndoorOutdoor, h as PetMedication, i as PetSex } from '../profile.d-CSs1wlXT.js';
|
|
48
49
|
export { C as CanonicalPetSpecies, c as canonicalPetSpecies } from '../species.d-BXAIMh7I.js';
|
|
49
|
-
import '../requestFunnel.d-
|
|
50
|
-
import '../focus.d-
|
|
50
|
+
import '../requestFunnel.d-Cxt0JqYx.js';
|
|
51
|
+
import '../focus.d-BZ2sEpbU.js';
|
|
51
52
|
import '../clinicModels.d-CaS64-P-.js';
|
|
52
53
|
import '../models.d-DOwnr8fi.js';
|
|
53
54
|
import '../useRecords.d-DWk61a4c.js';
|
|
54
55
|
import '../features.d-DrQxTw3-.js';
|
|
55
|
-
import '../screenProps.d-
|
|
56
|
-
import '../clinicBatch.d-
|
|
56
|
+
import '../screenProps.d-D9n-ancr.js';
|
|
57
|
+
import '../clinicBatch.d-BP_Rpvcy.js';
|
|
57
58
|
import '../recordsAsk.d-C5CGSi3j.js';
|
|
58
59
|
import '../sheetSeam.d-B09jf4YC.js';
|
|
59
60
|
|
|
60
|
-
/**
|
|
61
|
-
* A host's rule for the follow-ups under a reply (`EverfurChat`'s `followUpPolicy`, opt-in). Without one the
|
|
62
|
-
* surface draws `visibleFollowUps` exactly as before.
|
|
63
|
-
*/
|
|
64
|
-
interface ChatFollowUpPolicy {
|
|
65
|
-
/** How many to draw, 1 to 5. With `fill` the surface draws exactly this many whenever it can. Default 3. */
|
|
66
|
-
readonly count?: number;
|
|
67
|
-
/** Drop a backend prompt this matches (a visit or booking follow-up a host does not offer). */
|
|
68
|
-
readonly exclude?: RegExp | ((prompt: string) => boolean);
|
|
69
|
-
/**
|
|
70
|
-
* The host's own prompts that top the list up to `count` after the backend's (in order, de-duplicated, the
|
|
71
|
-
* `exclude` rule applied too). A function receives the member's last question, so the top-ups can follow it.
|
|
72
|
-
*/
|
|
73
|
-
readonly fill?: readonly string[] | ((lastQuestion: string | null) => readonly string[]);
|
|
74
|
-
/** A visible label over the follow-ups ("Follow-up questions"). Absent, the list keeps only its accessible name. */
|
|
75
|
-
readonly label?: string;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
61
|
/**
|
|
79
62
|
* Wrap the tree ONCE, high. Mounting constructs the runtime (transport, identity, registry,
|
|
80
63
|
* entitlement repository, pollers) exactly once and starts fail-closed: a bad manifest/entitlement
|
|
@@ -510,4 +493,4 @@ declare function headingFaceCss(theme: EverfurTheme, fallback?: EverfurFontFaceK
|
|
|
510
493
|
*/
|
|
511
494
|
declare function createLocalStorageKv(): KvPort;
|
|
512
495
|
|
|
513
|
-
export { CapabilityDecision, CapabilityGate, type CapabilityGateProps, CapabilityName, ChatCheckinTarget,
|
|
496
|
+
export { CapabilityDecision, CapabilityGate, type CapabilityGateProps, CapabilityName, ChatCheckinTarget, ChatFollowUpPolicy, ConversationId, EverfurChat, EverfurChatAnswerCards, EverfurChatDraftStore, EverfurChatEmptyHeaderContext, EverfurChatEmptyState, EverfurChatHistoryBar, EverfurChatHistorySheet, EverfurChatOpeningCard, type EverfurChatProps, EverfurChatTopCard, type EverfurFaceCss, EverfurFontFaceKey, EverfurFontWeight, EverfurPoweredBy, type EverfurPoweredByProps, EverfurPresentationInput, EverfurProvider, EverfurProviderProps, EverfurRecordsLanded, EverfurRecordsRequested, EverfurStarterPrompt, EverfurTabId, EverfurTabs, type EverfurTabsChatProps, type EverfurTabsClassNames, EverfurTabsCopy, type EverfurTabsHandle, type EverfurTabsIntro, type EverfurTabsOpened, type EverfurTabsPlanProps, type EverfurTabsProps, type EverfurTabsRecordsProps, EverfurTheme, EverfurThemeInput, EverfurThemeProvider, type EverfurThemeProviderProps, FileHandle, KvPort, LifecyclePort, PetProfileInput, PetRef, UploadTransport, UrgencyDisplayLevel, type WebAttachmentTransportOptions, createBrowserLifecycle, createLocalStorageKv, createWebAttachmentTransport, faceCss, fileToAttachmentHandle, headingFaceCss, useEverfurTabs, useHostPoweredBy };
|
package/dist/web/index.js
CHANGED
|
@@ -103,7 +103,7 @@ return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversati
|
|
|
103
103
|
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:fields.serverRequestId??null})}function analysisStartedFrame(requestId,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
104
104
|
return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
|
|
105
105
|
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:fields.resultId,analysisType:fields.analysisType,modelVersion:fields.modelVersion,confidence:fields.confidence,detections:/* @__PURE__ */Object.freeze([...fields.detections]),interpretation:fields.interpretation,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function unknownFrame(raw,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
106
|
-
return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function 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 createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */z.record(/* @__PURE__ */z.string(),/* @__PURE__ */z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=new TextDecoder("utf-8"),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var SDK_VERSION="0.15.1",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
106
|
+
return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function 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 createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */z.record(/* @__PURE__ */z.string(),/* @__PURE__ */z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=new TextDecoder("utf-8"),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var SDK_VERSION="0.16.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
107
107
|
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function checkPublishableKey(raw){let publishableKey=typeof raw=="string"?raw.trim():"";return publishableKey.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(publishableKey)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}function tryResolveClientConfig(config,options){let keyFailure=checkPublishableKey(config?.publishableKey);if(keyFailure!==null)/* @__PURE__ */
|
|
108
108
|
return Object.freeze({ok:false,failure:keyFailure});let publishableKey=config.publishableKey.trim(),baseUrl=tryResolveApiBaseUrl(config.apiBaseUrl);if(!baseUrl.ok)return baseUrl;let contractVersion=config.contractVersion?.trim()||DEFAULT_CONTRACT_VERSION;/* @__PURE__ */
|
|
109
109
|
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:publishableKey,apiBaseUrl:baseUrl.value,contractVersion:contractVersion,sdkVersion:SDK_VERSION,platform:options?.platform??SDK_PLATFORM,debug:config.debug===true})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host2){return host2.length===0||host2.includes("@")?false:host2.startsWith("[")&&host2.endsWith("]")?true:!host2.includes(":")}function canEchoOrigin(rawTrimmed,host2){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host2)}function safeOrigin(scheme,host2){return`${scheme}://${host2}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host2=hostOf(match[2]);if(host2.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host2)?`: ${safeOrigin(scheme,host2)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host2)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
|
|
@@ -268,7 +268,7 @@ return jsx("div",{className:cls.wrap,hidden:!state3.open,children:/* @__PURE__ *
|
|
|
268
268
|
/* @__PURE__ */jsx("button",{className:cls.ask,type:"button",onClick:()=>ask(question.prompt),style:inline("ask",{minHeight:36,border:"none",background:"transparent",padding:0,color:v3.link,...bold,fontWeight:700,fontSize:14.5,textDecoration:"underline",textDecorationThickness:"1.5px",textUnderlineOffset:3,cursor:"pointer"}),children:question.label}):null]}):null]})]})})}function TopCardPill({card:card,state:state3}){let{theme:theme}=useChatTheme(),v3=v3Palette(theme),cls=card.classNames??{};return card.closeLabel===void 0?null:/* @__PURE__ */jsxs("button",{ref:state3.pillRef,className:cls.pill,type:"button","aria-controls":state3.id,"aria-expanded":state3.open,hidden:state3.open,onClick:()=>state3.show(true),style:cls.pill?void 0:{display:state3.open?"none":"inline-flex",alignItems:"center",gap:7,marginLeft:"auto",minHeight:36,padding:"0 14px",border:"none",borderRadius:999,background:v3.riskBg,color:v3.riskInk,...faceCss(theme,"bold"),fontWeight:800,fontSize:15,cursor:"pointer"},children:[
|
|
269
269
|
/* @__PURE__ */jsx("i",{"aria-hidden":"true",style:cls.pill?void 0:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:v3.riskDot}}),card.pill??card.kicker]})}var REF_MAX2=128;var ICONS=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),TONES=/* @__PURE__ */new Set(["y","c","g","r"]),TRACK_STATES=/* @__PURE__ */new Set(["done","now","next"]),obj=value=>value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null,str4=(value,max=1e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null,kindOf=value=>typeof value=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(value)?value:null,iconOf=value=>typeof value=="string"&&ICONS.has(value)?value:null;function imageOf(value){let s=str4(value,2048);return s===null||/\s/.test(s)?null:/^https:\/\/[^/]/i.test(s)||/^\/(?![/\\])/.test(s)?s:null}var idOf=value=>typeof value=="number"&&Number.isInteger(value)?String(value):str4(value,REF_MAX2);function weightOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:null}function clean(fields){/* @__PURE__ */
|
|
270
270
|
return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str4(v,len),max);function focusOf(value){let o=obj(value),kicker=str4(o?.kicker,120),title=str4(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote2=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let label=str4(obj(r)?.label,60);return label===null?null:clean({label:label,kind:kindOf(obj(r)?.kind)})},6),risk:str4(risk?.lead,300)===null?null:clean({lead:str4(risk?.lead,300),body:str4(risk?.body),kind:kindOf(risk?.kind)}),odds:str4(odds?.label,120)===null||str4(odds?.from,20)===null||str4(odds?.to,20)===null?null:clean({label:str4(odds?.label,120),tag:str4(odds?.tag,40),from:str4(odds?.from,20),to:str4(odds?.to,20),toLabel:str4(odds?.toLabel,120)}),quote:str4(quote2?.text)===null?null:clean({kicker:str4(quote2?.kicker,120),tag:str4(quote2?.tag,40),text:str4(quote2?.text)}),jump:str4(jump?.title,300)===null||str4(jump?.go,60)===null?null:clean({title:str4(jump?.title,300),go:str4(jump?.go,60)})})}function routineOf(value){let o=obj(value),title=str4(o?.title,300),steps=listOf(o?.steps,r=>{let s=obj(r),t=str4(s?.title,300),tone=s?.tone;return t===null?null:clean({title:t,body:str4(s?.body),source:str4(s?.source,200),tone:typeof tone=="string"&&TONES.has(tone)?tone:null,icon:iconOf(s?.icon),fromVet:s?.fromVet===true?true:null})});return title===null||steps===null?null:clean({title:title,label:str4(o?.label,60),steps:steps})}function pickOf(value){let o=obj(value),title=str4(o?.title,300);if(o===null||title===null)return null;let rating=obj(o.rating),reviews=obj(o.reviews),why=obj(o.why),score=obj(why?.score),dose=obj(o.dose),ingredients=obj(o.ingredients),reviewItems=listOf(reviews?.items,r=>{let v=obj(r),stars=v?.stars,text3=str4(v?.text),by=str4(v?.by,80);return typeof stars!="number"||!Number.isFinite(stars)||stars<1||stars>5||text3===null||by===null?null:clean({stars:Math.round(stars),text:text3,by:by})},5),whyRows=listOf(why?.rows,r=>{let v=obj(r),chip=str4(v?.chip,40),t=str4(v?.title,300);return chip===null||t===null?null:clean({chip:chip,kind:kindOf(v?.kind),title:t,body:str4(v?.body)})}),stats=listOf(dose?.stats,r=>{let v=obj(r),val=str4(v?.value,40),label=str4(v?.label,120),kind=v?.kind;return val===null||label===null?null:clean({value:val,label:label,kind:kind==="weight"||kind==="dose"||kind==="days"?kind:null})},6),ingredientItems=words(ingredients?.items,12,80);return clean({title:title,none:o.none===true?true:null,hidden:o.none===true&&o.hidden===true?true:null,productId:idOf(o.productId),partnerSku:str4(o.partnerSku,200),rating:str4(rating?.value,20)===null?null:clean({value:str4(rating?.value,20),label:str4(rating?.label,120)}),line:str4(o.line),reviews:str4(reviews?.label,200)===null||reviewItems===null?null:clean({label:str4(reviews?.label,200),items:reviewItems}),checkoutLine:str4(o.checkoutLine,300),why:str4(why?.title,200)===null||whyRows===null?null:clean({title:str4(why?.title,200),rows:whyRows,score:str4(score?.text,200)===null||str4(score?.value,20)===null?null:clean({text:str4(score?.text,200),value:str4(score?.value,20)})}),dose:str4(dose?.title,200)===null||stats===null?null:clean({title:str4(dose?.title,200),stats:stats,note:str4(dose?.note)}),doseLabel:str4(o.doseLabel,120),ingredients:ingredientItems===null?null:clean({label:str4(ingredients?.label,200),items:ingredientItems}),proof:str4(o.proof,300),trust:listOf(o.trust,r=>{let v=obj(r),icon2=iconOf(v?.icon),label=str4(v?.label,120);return icon2===null||label===null?null:clean({icon:icon2,label:label})},6),more:str4(o.more,120),fine:str4(o.fine),checkin:str4(o.checkin,200)})}function signsOf(value){let o=obj(value),title=str4(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),t=str4(v?.title,300),body=str4(v?.body);return t===null||body===null?null:clean({title:t,body:body,urgent:v?.urgent===true?true:null,callVet:v?.callVet===true?true:null})});return title===null||items===null?null:clean({title:title,items:items})}function checkupOf(value){let o=obj(value),title=str4(o?.title,200),questions=words(o?.questions,12,300),add=str4(o?.add,80),added=str4(o?.added,80);return title===null||questions===null||add===null||added===null?null:clean({title:title,questions:questions,add:add,added:added})}function extrasOf(value){let o=obj(value),title=str4(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),key=str4(v?.key,REF_MAX2),t=str4(v?.title,300),action=str4(v?.action,80),productId=idOf(v?.productId),added=str4(v?.added,80)??(productId!==null?action:null);return key===null||t===null||action===null||added===null?null:clean({key:key,productId:productId,title:t,body:str4(v?.body),price:str4(v?.price,40),was:str4(v?.was,40),tag:str4(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added,owned:v?.owned===true?true:null})},6);return title===null||items===null?null:clean({title:title,items:items})}function waitOf(value){let o=obj(value),kicker=str4(o?.kicker,120),title=str4(o?.title,120);return o===null||kicker===null||title===null?null:clean({kicker:kicker,title:title,icon:iconOf(o.icon),track:listOf(o.track,r=>{let v=obj(r),t=str4(v?.title,120),state3=v?.state;return t===null?null:clean({title:t,detail:str4(v?.detail,120),state:typeof state3=="string"&&TRACK_STATES.has(state3)?state3:null,tag:str4(v?.tag,40)})},6),heading:str4(o.heading,200),rows:listOf(o.rows,r=>{let v=obj(r),icon2=iconOf(v?.icon),label=str4(v?.label,120);if(icon2===null||label===null)return null;if(v?.fromVet===true)return clean({icon:icon2,label:label,text:"",fromVet:true});let text3=str4(v?.text,300);return text3===null?null:clean({icon:icon2,label:label,text:text3})},6),note:str4(o.note,300),action:str4(o.action,80)})}function healthPlanFocusDesignFromWire(raw){let o=obj(raw),title=str4(o?.title,300),pick5=pickOf(o?.pick);if(o===null||title===null||pick5===null)return null;let byline=obj(o.byline);return clean({eyebrow:str4(o.eyebrow,120),title:title,subtitle:str4(o.subtitle,300),subtitleNoRecords:str4(o.subtitleNoRecords,300),headImageUrl:imageOf(o.headImageUrl),byline:str4(byline?.name,120)===null?null:clean({name:str4(byline?.name,120),role:str4(byline?.role,120),imageUrl:imageOf(byline?.imageUrl),shortName:str4(byline?.shortName,60)}),focus:focusOf(o.focus),routine:routineOf(o.routine),pick:pick5,signs:signsOf(o.signs),checkup:checkupOf(o.checkup),extras:extrasOf(o.extras),wait:waitOf(o.wait),fine:str4(o.fine),checkoutRows:listOf(o.checkoutRows,r=>{let v=obj(r),icon2=iconOf(v?.icon),label=str4(v?.label,60),val=str4(v?.value,200);return icon2===null||label===null||val===null?null:clean({icon:icon2,label:label,value:val})},6)})}function healthPlanPageFromWire(raw,petRef2){let o=obj(raw);if(o===null||!("page"in o))return null;let pet=obj(o.pet),sex=pet?.sex;/* @__PURE__ */
|
|
271
|
-
return Object.freeze({petRef:str4(o.pet_ref,REF_MAX2)??petRef2,pet:/* @__PURE__ */Object.freeze({name:str4(pet?.name,120),species:str4(pet?.species,60),sex:sex==="female"||sex==="male"?sex:null,breed:str4(pet?.breed,120),weightKg:weightOf(pet?.weight_kg),weightLb:weightOf(pet?.weight_lb)}),checkout:o.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(o.page),vetReviewed:o.vet_reviewed===true,trackingTextsEnabled:o.tracking_texts_enabled===true})}function invalid4(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed4(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the expected shape`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX2;function base(petRef2){return`/widget/v1/pets/${encodeURIComponent(petRef2)}/plan`}async function readPage(funnel,petRef2,opts){if(!validRef(petRef2))return err(invalid4("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.page.read",{method:"GET",path:`${base(petRef2)}/page`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let page=healthPlanPageFromWire(res.value,petRef2);return page===null?err(malformed4("healthPlan.page.read")):ok(page)}var readers=/* @__PURE__ */new WeakMap;function createHealthPlanPageReader(runtime){let known=readers.get(runtime);if(known!==void 0)return known;let reader=makeHealthPlanPageReader(runtime);return readers.set(runtime,reader),reader}function makeHealthPlanPageReader(runtime){return{getPage:(petRef2,opts)=>{if(runtime.isDisposed)return Promise.resolve(err(disposed("getPage")));let{services:services}=runtime.registry,funnel=withPlainNotFound(createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}));return readPage(funnel,petRef2,opts)}}}var HEALTH_PLAN_STALE_MS=6e4;function useHealthPlanRevalidation({lifecycle:lifecycle,refreshKey:refreshKey,readyAt:readyAt,revalidate:revalidate,refresh:refresh,now:now=Date.now}){let latest=useRef({readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now});latest.current={readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now},useEffect(()=>{if(lifecycle==null)return;let stop=callHost(()=>lifecycle.onForeground(()=>{let{readyAt:at,revalidate:run,now:clock}=latest.current;at!==null&&clock()-at>=HEALTH_PLAN_STALE_MS&&run()}));return()=>{typeof stop=="function"&&callHost(stop)}},[lifecycle]);let seenKey=useRef(refreshKey);useEffect(()=>{Object.is(seenKey.current,refreshKey)||(seenKey.current=refreshKey,latest.current.refresh())},[refreshKey])}var HEALTH_PLAN_PAGE_SHARE_MS=HEALTH_PLAN_STALE_MS,SHARED_READS_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function sharedReads(){let host2=globalThis,stored3=host2[SHARED_READS_SYMBOL];if(stored3 instanceof WeakMap)return stored3;let made=/* @__PURE__ */new WeakMap;return host2[SHARED_READS_SYMBOL]=made,made}function readShared(reader,runtime,userRef2,petRef2,fresh4){let all=sharedReads(),reads=all.get(runtime);reads===void 0&&(reads=/* @__PURE__ */new Map,all.set(runtime,reads));let map=reads,key=`${userRef2}\0${petRef2}`,hit=map.get(key);if(!fresh4&&hit!==void 0&&(hit.at===null||Date.now()-hit.at<HEALTH_PLAN_PAGE_SHARE_MS))return hit.promise;let entry={at:null,promise:reader.getPage(petRef2).then(res=>(map.get(key)===entry&&(res.ok||isNotFoundError(res.error)?entry.at=Date.now():map.delete(key)),res))};return map.set(key,entry),entry.promise}function useHealthPlanPage(options){let{userRef:userRef2,runtime:runtime}=useEverfurContext(),own=useMemo(()=>createHealthPlanPageReader(runtime),[runtime]),hostRepository=options.repository,repository=hostRepository??own,getPage=useCallback((pet,fresh4)=>hostRepository!==void 0||userRef2==null?repository.getPage(pet):readShared(own,runtime,userRef2,pet,fresh4),[hostRepository,repository,own,runtime,userRef2]),{petRef:petRef2}=options,enabled=options.enabled!==false&&userRef2!=null&&petRef2!==null,[state3,setState]=useState({phase:"idle",petRef:null,page:null,error:null}),epoch=useRef(0),quiet=useRef(0),read=useCallback(async fresh4=>{let mine=++epoch.current;if(!enabled||petRef2===null){setState(prev=>prev.phase==="idle"&&prev.petRef===null?prev:{phase:"idle",petRef:null,page:null,error:null});return}setState(prev=>({phase:"loading",petRef:petRef2,page:prev.petRef===petRef2?prev.page:null,error:null}));let res=await getPage(petRef2,fresh4);mine===epoch.current&&(res.ok?setState({phase:"ready",petRef:petRef2,page:res.value,error:null,readyAt:Date.now()}):isNotFoundError(res.error)?setState({phase:"ready",petRef:petRef2,page:null,error:null,missing:true,readyAt:Date.now()}):setState({phase:"failed",petRef:petRef2,page:null,error:res.error}))},[enabled,petRef2,getPage]),load=useCallback(()=>read(true),[read]),ready=state3.phase==="ready"&&state3.petRef===petRef2,revalidate=useCallback(async()=>{if(!enabled||petRef2===null||!ready)return;let mine=epoch.current,seq=++quiet.current,res=await getPage(petRef2,true);mine!==epoch.current||seq!==quiet.current||!res.ok||setState(prev=>prev.phase==="ready"&&prev.petRef===petRef2?{phase:"ready",petRef:petRef2,page:res.value,error:null,readyAt:Date.now()}:prev)},[enabled,petRef2,ready,getPage]);useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?state3.readyAt??null:null,revalidate:()=>{revalidate()},refresh:()=>{ready?revalidate():load()}}),useEffect(()=>(read(false),()=>{epoch.current+=1}),[read]);let stale=enabled&&state3.petRef!==petRef2;return useMemo(()=>({phase:stale?"loading":state3.phase,page:stale?null:state3.page,error:stale?null:state3.error,missing:!stale&&state3.missing===true,refresh:load}),[stale,state3,load])}var CLOSE_FALLBACK="Close",HEALTH_PLAN_TOP_CARD_COPY=/* @__PURE__ */Object.freeze({action:who=>who.possessive===null?null:`See ${who.possessive} Health Plan`,ask:"What does it mean?",askPrompt:(focus,ask)=>focus.risk?.lead?`${focus.risk.lead} ${ask}`:`${focus.title}: ${ask}`,close:who=>who.possessive===null?null:`Close ${who.possessive} focus`});function healthPlanPossessive(pet){let sex=typeof pet.sex=="string"?pet.sex.trim().toLowerCase():null;if(sex==="female")return"her";if(sex==="male")return"his";let name=typeof pet.name=="string"?pet.name.trim():"";return name!==""?`${name}'s`:null}function healthPlanTopCard(page,options){let focus=page?.page?.focus;if(page===null||focus===void 0||focus.title.trim()===""||focus.kicker.trim()==="")return;let copy={...HEALTH_PLAN_TOP_CARD_COPY,...options.copy},who={pet:page.pet,possessive:healthPlanPossessive(page.pet)},badge=focus.sources?.find(source=>source.label.trim()!=="")?.label,onOpenPlan=options.onOpenPlan,action=onOpenPlan===void 0?null:copy.action(who),close=copy.close(who),ask=copy.ask.trim();return{kicker:focus.kicker,...badge===void 0?{}:{badge:badge},title:focus.title,...focus.risk?.lead?{lead:focus.risk.lead}:{},...focus.risk?.body?{body:focus.risk.body}:{},...action===null||action.trim()===""||onOpenPlan===void 0?{}:{action:{label:action,onPress:onOpenPlan}},...ask===""?{}:{ask:{label:ask,prompt:copy.askPrompt(focus,ask)}},closeLabel:close===null||close.trim()===""?CLOSE_FALLBACK:close,pill:focus.kicker,...options.renderIcon===void 0?{}:{renderIcon:options.renderIcon},...options.classNames===void 0?{}:{classNames:options.classNames}}}var placed=0,listeners2=/* @__PURE__ */new Set,notify=()=>listeners2.forEach(listener=>listener()),subscribe=listener=>(listeners2.add(listener),()=>listeners2.delete(listener)),snapshot=()=>placed>0,serverSnapshot=()=>false;function useHostPoweredBy(){return useSyncExternalStore(subscribe,snapshot,serverSnapshot)}function EverfurPoweredBy({children:children,className:className,style:style}){let hidden=useEverfurTheme().meta.hidePoweredBy;return useEffect(()=>{if(!hidden)return placed+=1,notify(),()=>{placed-=1,notify()}},[hidden]),hidden?null:/* @__PURE__ */jsx("span",{...className===void 0?{}:{className:className},...style===void 0?{}:{style:style},children:children??CHAT_COPY.poweredBy})}function readOn(ink,grounds2,target){return pushToContrast(ink,grounds2,poleForGrounds(grounds2),target)}function themedUrgencyTier(tier,theme){if(tier.level==="emergency")return tier;let caution=tier.level==="schedule_soon",branded=brandedStatus(theme),statusSet=caution?branded.warning:branded.info,painted=isEverfurLightLook(theme)&&!statusSet?tier:tokenPaint(tier,theme,caution);return withBannerSlot(painted,theme.slots.banner)}function tokenPaint(tier,theme,caution){let c=theme.color,fill2=flattenOnto(caution?c.badgeBgCaution:c.badgeBgInfo,c.surface)??c.surface,edgeFrom=caution?c.cautionAccent:c.infoEdge,borderColor=readOn(flattenOnto(edgeFrom,c.surface)??edgeFrom,[c.surface,c.chatGround],SLOT_MIN_BORDER_CONTRAST),textColor=readOn(caution?c.warningStrong:c.info,[fill2,c.surface],SLOT_MIN_CONTRAST);/* @__PURE__ */
|
|
271
|
+
return Object.freeze({petRef:str4(o.pet_ref,REF_MAX2)??petRef2,pet:/* @__PURE__ */Object.freeze({name:str4(pet?.name,120),species:str4(pet?.species,60),sex:sex==="female"||sex==="male"?sex:null,breed:str4(pet?.breed,120),weightKg:weightOf(pet?.weight_kg),weightLb:weightOf(pet?.weight_lb)}),checkout:o.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(o.page),vetReviewed:o.vet_reviewed===true,trackingTextsEnabled:o.tracking_texts_enabled===true})}function invalid4(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed4(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the expected shape`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX2;function base(petRef2){return`/widget/v1/pets/${encodeURIComponent(petRef2)}/plan`}async function readPage(funnel,petRef2,opts){if(!validRef(petRef2))return err(invalid4("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.page.read",{method:"GET",path:`${base(petRef2)}/page`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let page=healthPlanPageFromWire(res.value,petRef2);return page===null?err(malformed4("healthPlan.page.read")):ok(page)}var readers=/* @__PURE__ */new WeakMap;function createHealthPlanPageReader(runtime){let known=readers.get(runtime);if(known!==void 0)return known;let reader=makeHealthPlanPageReader(runtime);return readers.set(runtime,reader),reader}function makeHealthPlanPageReader(runtime){return{getPage:(petRef2,opts)=>{if(runtime.isDisposed)return Promise.resolve(err(disposed("getPage")));let{services:services}=runtime.registry,funnel=withPlainNotFound(createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}));return readPage(funnel,petRef2,opts)}}}var HEALTH_PLAN_STALE_MS=6e4;function useHealthPlanRevalidation({lifecycle:lifecycle,refreshKey:refreshKey,readyAt:readyAt,revalidate:revalidate,refresh:refresh,now:now=Date.now}){let latest=useRef({readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now});latest.current={readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now},useEffect(()=>{if(lifecycle==null)return;let stop=callHost(()=>lifecycle.onForeground(()=>{let{readyAt:at,revalidate:run,now:clock}=latest.current;at!==null&&clock()-at>=HEALTH_PLAN_STALE_MS&&run()}));return()=>{typeof stop=="function"&&callHost(stop)}},[lifecycle]);let seenKey=useRef(refreshKey);useEffect(()=>{Object.is(seenKey.current,refreshKey)||(seenKey.current=refreshKey,latest.current.refresh())},[refreshKey])}var HEALTH_PLAN_PAGE_SHARE_MS=HEALTH_PLAN_STALE_MS,SHARED_READS_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function sharedReads(){let host2=globalThis,stored3=host2[SHARED_READS_SYMBOL];if(stored3 instanceof WeakMap)return stored3;let made=/* @__PURE__ */new WeakMap;return host2[SHARED_READS_SYMBOL]=made,made}function readShared(reader,runtime,userRef2,petRef2,fresh4){let all=sharedReads(),reads=all.get(runtime);reads===void 0&&(reads=/* @__PURE__ */new Map,all.set(runtime,reads));let map=reads,key=`${userRef2}\0${petRef2}`,hit=map.get(key);if(!fresh4&&hit!==void 0&&(hit.at===null||Date.now()-hit.at<HEALTH_PLAN_PAGE_SHARE_MS))return hit.promise;let entry={at:null,promise:reader.getPage(petRef2).then(res=>(map.get(key)===entry&&(res.ok||isNotFoundError(res.error)?entry.at=Date.now():map.delete(key)),res))};return map.set(key,entry),entry.promise}function useHealthPlanPage(options){let{userRef:userRef2,runtime:runtime}=useEverfurContext(),own=useMemo(()=>createHealthPlanPageReader(runtime),[runtime]),hostRepository=options.repository,repository=hostRepository??own,getPage=useCallback((pet,fresh4)=>hostRepository!==void 0||userRef2==null?repository.getPage(pet):readShared(own,runtime,userRef2,pet,fresh4),[hostRepository,repository,own,runtime,userRef2]),{petRef:petRef2}=options,enabled=options.enabled!==false&&userRef2!=null&&petRef2!==null,[state3,setState]=useState({phase:"idle",petRef:null,page:null,error:null}),epoch=useRef(0),quiet=useRef(0),read=useCallback(async fresh4=>{let mine=++epoch.current;if(!enabled||petRef2===null){setState(prev=>prev.phase==="idle"&&prev.petRef===null?prev:{phase:"idle",petRef:null,page:null,error:null});return}setState(prev=>({phase:"loading",petRef:petRef2,page:prev.petRef===petRef2?prev.page:null,error:null}));let res=await getPage(petRef2,fresh4);mine===epoch.current&&(res.ok?setState({phase:"ready",petRef:petRef2,page:res.value,error:null,readyAt:Date.now()}):isNotFoundError(res.error)?setState({phase:"ready",petRef:petRef2,page:null,error:null,missing:true,readyAt:Date.now()}):setState({phase:"failed",petRef:petRef2,page:null,error:res.error}))},[enabled,petRef2,getPage]),load=useCallback(()=>read(true),[read]),ready=state3.phase==="ready"&&state3.petRef===petRef2,revalidate=useCallback(async()=>{if(!enabled||petRef2===null||!ready)return;let mine=epoch.current,seq=++quiet.current,res=await getPage(petRef2,true);mine!==epoch.current||seq!==quiet.current||!res.ok||setState(prev=>prev.phase==="ready"&&prev.petRef===petRef2?{phase:"ready",petRef:petRef2,page:res.value,error:null,readyAt:Date.now()}:prev)},[enabled,petRef2,ready,getPage]);useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?state3.readyAt??null:null,revalidate:()=>{revalidate()},refresh:()=>{ready?revalidate():load()}}),useEffect(()=>(read(false),()=>{epoch.current+=1}),[read]);let stale=enabled&&state3.petRef!==petRef2;return useMemo(()=>({phase:stale?"loading":state3.phase,page:stale?null:state3.page,error:stale?null:state3.error,missing:!stale&&state3.missing===true,refresh:load}),[stale,state3,load])}var CLOSE_FALLBACK="Close",HEALTH_PLAN_TOP_CARD_COPY=/* @__PURE__ */Object.freeze({action:who=>who.possessive===null?null:`See ${who.possessive} Health Plan`,ask:"What does it mean?",askPrompt:(focus,ask)=>focus.risk?.lead?`${focus.risk.lead} ${ask}`:`${focus.title}: ${ask}`,close:who=>who.possessive===null?null:`Close ${who.possessive} focus`});function healthPlanPossessive(pet){let sex=typeof pet.sex=="string"?pet.sex.trim().toLowerCase():null;if(sex==="female")return"her";if(sex==="male")return"his";let name=typeof pet.name=="string"?pet.name.trim():"";return name!==""?`${name}'s`:null}function healthPlanTopCard(page,options={}){let focus=page?.page?.focus;if(page===null||focus===void 0||focus.title.trim()===""||focus.kicker.trim()==="")return;let copy={...HEALTH_PLAN_TOP_CARD_COPY,...options.copy},who={pet:page.pet,possessive:healthPlanPossessive(page.pet)},badge=focus.sources?.find(source=>source.label.trim()!=="")?.label,onOpenPlan=options.onOpenPlan,action=onOpenPlan===void 0?null:copy.action(who),close=copy.close(who),ask=copy.ask.trim();return{kicker:focus.kicker,...badge===void 0?{}:{badge:badge},title:focus.title,...focus.risk?.lead?{lead:focus.risk.lead}:{},...focus.risk?.body?{body:focus.risk.body}:{},...action===null||action.trim()===""||onOpenPlan===void 0?{}:{action:{label:action,onPress:onOpenPlan}},...ask===""?{}:{ask:{label:ask,prompt:copy.askPrompt(focus,ask)}},closeLabel:close===null||close.trim()===""?CLOSE_FALLBACK:close,pill:focus.kicker,...options.renderIcon===void 0?{}:{renderIcon:options.renderIcon}}}function healthPlanTopCard2(page,options){let card=healthPlanTopCard(page,options);if(card!==void 0)return{...card,...options.classNames===void 0?{}:{classNames:options.classNames}}}var placed=0,listeners2=/* @__PURE__ */new Set,notify=()=>listeners2.forEach(listener=>listener()),subscribe=listener=>(listeners2.add(listener),()=>listeners2.delete(listener)),snapshot=()=>placed>0,serverSnapshot=()=>false;function useHostPoweredBy(){return useSyncExternalStore(subscribe,snapshot,serverSnapshot)}function EverfurPoweredBy({children:children,className:className,style:style}){let hidden=useEverfurTheme().meta.hidePoweredBy;return useEffect(()=>{if(!hidden)return placed+=1,notify(),()=>{placed-=1,notify()}},[hidden]),hidden?null:/* @__PURE__ */jsx("span",{...className===void 0?{}:{className:className},...style===void 0?{}:{style:style},children:children??CHAT_COPY.poweredBy})}function readOn(ink,grounds2,target){return pushToContrast(ink,grounds2,poleForGrounds(grounds2),target)}function themedUrgencyTier(tier,theme){if(tier.level==="emergency")return tier;let caution=tier.level==="schedule_soon",branded=brandedStatus(theme),statusSet=caution?branded.warning:branded.info,painted=isEverfurLightLook(theme)&&!statusSet?tier:tokenPaint(tier,theme,caution);return withBannerSlot(painted,theme.slots.banner)}function tokenPaint(tier,theme,caution){let c=theme.color,fill2=flattenOnto(caution?c.badgeBgCaution:c.badgeBgInfo,c.surface)??c.surface,edgeFrom=caution?c.cautionAccent:c.infoEdge,borderColor=readOn(flattenOnto(edgeFrom,c.surface)??edgeFrom,[c.surface,c.chatGround],SLOT_MIN_BORDER_CONTRAST),textColor=readOn(caution?c.warningStrong:c.info,[fill2,c.surface],SLOT_MIN_CONTRAST);/* @__PURE__ */
|
|
272
272
|
return Object.freeze({...tier,borderColor:borderColor,backgroundColor:fill2,textColor:textColor,reasonColor:readOn(c.text.primary,[fill2],SLOT_MIN_CONTRAST),pillColor:c.surface})}function withBannerSlot(tier,slot){if(slot===void 0)return tier;let next={...tier};return slot.backgroundColor!==void 0&&(next.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(next.borderColor=slot.borderColor),slot.textColor!==void 0&&(next.textColor=slot.textColor,next.reasonColor=slot.textColor),/* @__PURE__ */Object.freeze(next)}var MIN_TOUCH_TARGET7=44,DISMISS_SIZE=22,DISMISS_GLYPH_SIZE=14,INFO_GLYPH_SIZE=20,PIN_GLYPH_SIZE=16,ALERT_GLYPH_SIZE=20,BANNER_BORDER=1.5,ACTION_EDGE=1.5;function UrgencyBanner({surface:surface,vetEntry:vetEntry,renderVetAction:renderVetAction,onFindVet:onFindVet}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles7(theme),[theme]),motion=useChatMotion(),banner=usePresence(surface.showBanner,motion.bannerOutMs),icon2=usePresence(surface.showCompactIcon,motion.iconOutMs);/* @__PURE__ */
|
|
273
273
|
return jsxs(Fragment,{children:[banner.present&&surface.tier!==null&&surface.source!==null?/* @__PURE__ */jsx(Banner,{surface:surface,exiting:banner.exiting,styles:styles,erLine:surface.tier.level==="emergency"&&onFindVet===void 0,action:surface.showVetAction?/* @__PURE__ */jsx(VetAction,{tier:themedUrgencyTier(surface.tier,theme),styles:styles,vetEntry:vetEntry,renderVetAction:renderVetAction,onFindVet:onFindVet}):null},surface.signature??"banner"):null,icon2.present?/* @__PURE__ */jsx(CompactIcon,{exiting:icon2.exiting,onExpand:surface.expand,styles:styles}):null]})}function Banner({surface:surface,exiting:exiting,styles:styles,erLine:erLine,action:action}){let ref=useRef(null),motion=useChatMotion(),theme=useEverfurTheme();useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:motion.bannerInMs,fromOpacity:0});return()=>animation?.cancel()},[motion.bannerInMs]),useEffect(()=>{exiting&&animateExit(ref.current,motion.bannerOutMs)},[exiting,motion.bannerOutMs]);let source=surface.source;if(surface.tier===null||source===null)return null;let tier=themedUrgencyTier(surface.tier,theme),urgent=tier.level==="emergency"||tier.level==="schedule_soon",paint=tierPaint(tier,theme);/* @__PURE__ */
|
|
274
274
|
return jsxs("div",{ref:ref,role:urgent?"alert":"status","aria-hidden":exiting?true:void 0,style:{...styles.banner,borderColor:paint.edge,backgroundColor:paint.fill,...bannerRadius(tier,theme)},children:[
|
|
@@ -380,19 +380,19 @@ return jsxs("div",{"data-everfur-texting-ask":stage,style:{...styles.row,...styl
|
|
|
380
380
|
/* @__PURE__ */jsxs("div",{style:{...styles.bubble,...styles.bubbleAssistant},children:[showName?null:/* @__PURE__ */jsx("span",{style:VISUALLY_HIDDEN,children:`${CHAT_COPY.senderAssistant}: `}),
|
|
381
381
|
/* @__PURE__ */jsx("p",{style:styles.bubbleTextAssistant,children:text3})]}),stage==="offered"?/* @__PURE__ */jsxs("ul",{style:styles.followUps,children:[
|
|
382
382
|
/* @__PURE__ */jsx("li",{style:{display:"flex",maxWidth:"100%"},children:/* @__PURE__ */jsx("button",{type:"button",onClick:onAccept,style:styles.followUpRow,children:accept})}),
|
|
383
|
-
/* @__PURE__ */jsx("li",{style:{display:"flex",maxWidth:"100%"},children:/* @__PURE__ */jsx("button",{type:"button",onClick:onDismiss,style:styles.followUpRow,children:dismiss})})]}):null]})}function useChatDraft(send,conversationId2,seed){let[state3,setState]=useState({send:send,conversationId:conversationId2,text:seed??"",seeded:seed??null}),belongs=state3.send===send&&(state3.conversationId===null||state3.conversationId===conversationId2);useEffect(()=>{setState(previous=>{let kept=previous.send===send&&(previous.conversationId===null||previous.conversationId===conversationId2),text3=kept?previous.text:"",seeded=kept?previous.seeded:null,fresh4=seed!=null&&seed!==seeded&&text3.length===0;return{send:send,conversationId:conversationId2,text:fresh4?seed:text3,seeded:fresh4?seed:seeded}})},[send,conversationId2,seed]);let setDraft=useCallback(text3=>setState(previous=>({send:send,conversationId:conversationId2,text:text3,seeded:previous.seeded})),[send,conversationId2]);return[belongs?state3.text:"",setDraft]}function usePersistedDraft(store,conversationId2,draft,setDraft){let latest=useRef({draft:draft,setDraft:setDraft});latest.current={draft:draft,setDraft:setDraft};let asked=useRef(null),[settled,setSettled]=useState(null);useEffect(()=>{if(store===void 0)return;let key=`${conversationId2??""}`;if(asked.current===key)return;asked.current=key;let live=true;return(async()=>{let outcome=await callHostAsync(()=>store.read(conversationId2));if(!live)return;let stored3=outcome.ok&&typeof outcome.value=="string"?outcome.value:"";stored3.length>0&&latest.current.draft.length===0&&latest.current.setDraft(stored3),setSettled(key)})(),()=>{live=false}},[store,conversationId2]),useEffect(()=>{store===void 0||settled!==`${conversationId2??""}`||callHost(()=>store.write(conversationId2,draft))},[store,conversationId2,draft,settled])}var
|
|
383
|
+
/* @__PURE__ */jsx("li",{style:{display:"flex",maxWidth:"100%"},children:/* @__PURE__ */jsx("button",{type:"button",onClick:onDismiss,style:styles.followUpRow,children:dismiss})})]}):null]})}function useChatDraft(send,conversationId2,seed){let[state3,setState]=useState({send:send,conversationId:conversationId2,text:seed??"",seeded:seed??null}),belongs=state3.send===send&&(state3.conversationId===null||state3.conversationId===conversationId2);useEffect(()=>{setState(previous=>{let kept=previous.send===send&&(previous.conversationId===null||previous.conversationId===conversationId2),text3=kept?previous.text:"",seeded=kept?previous.seeded:null,fresh4=seed!=null&&seed!==seeded&&text3.length===0;return{send:send,conversationId:conversationId2,text:fresh4?seed:text3,seeded:fresh4?seed:seeded}})},[send,conversationId2,seed]);let setDraft=useCallback(text3=>setState(previous=>({send:send,conversationId:conversationId2,text:text3,seeded:previous.seeded})),[send,conversationId2]);return[belongs?state3.text:"",setDraft]}function usePersistedDraft(store,conversationId2,draft,setDraft,paused=false){let latest=useRef({draft:draft,setDraft:setDraft});latest.current={draft:draft,setDraft:setDraft};let asked=useRef(null),[settled,setSettled]=useState(null);useEffect(()=>{if(store===void 0)return;let key=`${conversationId2??""}`;if(asked.current===key)return;asked.current=key;let live=true;return(async()=>{let outcome=await callHostAsync(()=>store.read(conversationId2));if(!live)return;let stored3=outcome.ok&&typeof outcome.value=="string"?outcome.value:"";stored3.length>0&&latest.current.draft.length===0&&latest.current.setDraft(stored3),setSettled(key)})(),()=>{live=false}},[store,conversationId2]),useEffect(()=>{store===void 0||paused||settled!==`${conversationId2??""}`||callHost(()=>store.write(conversationId2,draft))},[store,conversationId2,draft,settled,paused])}var DICTATION_ERROR_VISIBLE_MS=6e3;function composeDictatedText(base2,transcript,maxLength){let spoken=transcript.trim();if(!spoken)return base2;let separator=base2===""||/\s$/.test(base2)?"":" ",text3=`${base2}${separator}${spoken}`;return typeof maxLength=="number"&&maxLength>0?text3.slice(0,maxLength):text3}function formatDictationElapsed(elapsedMs){let totalSeconds=Math.max(0,Math.floor(elapsedMs/1e3)),minutes=Math.floor(totalSeconds/60),seconds=totalSeconds%60;return`${minutes}:${seconds.toString().padStart(2,"0")}`}function dictationErrorMessage(kind){switch(kind){case"permissionDenied":return CHAT_COPY.micBlocked;case"noSpeech":return CHAT_COPY.noSpeech;case"unavailable":return CHAT_COPY.dictationUnavailable}}function trackDictationEvent(telemetry,name,properties){if(telemetry)try{telemetry.track(name,{...properties})}catch{}}var MIN_TOUCH_TARGET14=44,MIC_GLYPH_SIZE=18,STOP_GLYPH_SIZE2=14,PULSE_INSET=6,PULSE_LOOP_MS=1200,DISABLED_OPACITY2=.4;function DictationButton({active:active,listening:listening,elapsedMs:elapsedMs,disabled:disabled=false,onToggle:onToggle}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles15(theme),[theme]);/* @__PURE__ */
|
|
384
384
|
return jsxs("span",{style:styles.wrap,children:[listening?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.timer,children:formatDictationElapsed(elapsedMs)}):null,
|
|
385
385
|
/* @__PURE__ */jsx("button",{type:"button",disabled:disabled,onClick:()=>onToggle(),"aria-label":active?CHAT_COPY.stopDictation:CHAT_COPY.dictate,"aria-pressed":active,style:{...styles.button,...disabled?styles.buttonDisabled:null},children:active?/* @__PURE__ */jsxs(Fragment,{children:[
|
|
386
386
|
/* @__PURE__ */jsx(Pulse,{style:styles.pulse}),
|
|
387
387
|
/* @__PURE__ */jsx(Glyph,{name:"square",size:STOP_GLYPH_SIZE2,color:theme.color.brandInk,fill:theme.color.brandInk,style:{position:"relative"}})]}):/* @__PURE__ */jsx(Glyph,{name:"mic",size:MIC_GLYPH_SIZE,color:theme.color.brandInk})}),
|
|
388
|
-
/* @__PURE__ */jsx("span",{role:"status","aria-live":"polite",style:VISUALLY_HIDDEN,children:listening?CHAT_COPY.listening:""})]})}function Pulse({style:style}){let ref=useRef(null),motion=useChatMotion();return useEffect(()=>{let node=ref.current;if(motion.reduced||!canAnimate(node))return;let animation=node.animate([{opacity:1},{opacity:.4},{opacity:1}],{duration:PULSE_LOOP_MS,iterations:1/0,easing:"ease-in-out"});return()=>animation.cancel()},[motion.reduced]),/* @__PURE__ */jsx("span",{ref:ref,"aria-hidden":"true",style:style})}function makeStyles15(theme){let c=theme.color,r=theme.radius,t=theme.type;return{wrap:{display:"inline-flex",flexShrink:0,alignItems:"center",gap:theme.space.xs},timer:{...faceCss(theme,"mono"),fontSize:t.tierSizes.compact.micro,lineHeight:`${t.tierSizes.compact.micro+2}px`,fontVariantNumeric:"tabular-nums",color:c.text.muted},button:{position:"relative",boxSizing:"border-box",width:MIN_TOUCH_TARGET14,height:MIN_TOUCH_TARGET14,minWidth:MIN_TOUCH_TARGET14,minHeight:MIN_TOUCH_TARGET14,margin:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:c.brandInk},buttonDisabled:{opacity:DISABLED_OPACITY2,cursor:"not-allowed"},pulse:{position:"absolute",top:PULSE_INSET,right:PULSE_INSET,bottom:PULSE_INSET,left:PULSE_INSET,borderRadius:r.pill,backgroundColor:c.brandSofter}}}function getRecognitionConstructor(env){if(!env)return null;let ctor=env.SpeechRecognition??env.webkitSpeechRecognition;return typeof ctor=="function"?ctor:null}function resolveDictationLang(language){return typeof language=="string"&&language.toLowerCase().startsWith("en")?language:"en-US"}async function probeDictationCapability(env,lang){let ctor=getRecognitionConstructor(env);if(!ctor)return"none";if(typeof ctor.available!="function")return"browser";try{let status=await ctor.available({langs:[lang],processLocally:!0});return status==="available"?"on_device":status==="downloadable"?"downloadable":"browser"}catch{return"browser"}}function joinRecognitionResults(results){let pieces=[];for(let index=0;index<results.length;index+=1){let piece=results[index]?.[0]?.transcript?.trim();if(!piece)continue;let previous=pieces[pieces.length-1];previous&&piece.toLowerCase().startsWith(previous.toLowerCase())?pieces[pieces.length-1]=piece:pieces.push(piece)}return pieces.join(" ")}function composeDictatedText(base2,transcript,maxLength){let spoken=transcript.trim();if(!spoken)return base2;let separator=base2===""||/\s$/.test(base2)?"":" ",text3=`${base2}${separator}${spoken}`;return typeof maxLength=="number"&&maxLength>0?text3.slice(0,maxLength):text3}function mapDictationError(code){return code==="not-allowed"||code==="service-not-allowed"?"permissionDenied":code==="no-speech"?"noSpeech":"unavailable"}var ON_DEVICE_FALLBACK_CODES=/* @__PURE__ */new Set(["language-not-supported","service-not-allowed"]),defaultTimers3={setTimeout:(run,ms)=>globalThis.setTimeout(run,ms),clearTimeout:handle=>globalThis.clearTimeout(handle)};function startDictation(options){let{env:env,capability:capability,lang:lang,callbacks:callbacks}=options,timers=options.timers??defaultTimers3,maxDurationMs=options.maxDurationMs??6e4,ctor=getRecognitionConstructor(env),mode=capability==="on_device"?"on_device":"browser",usePhrases=mode==="on_device"&&(options.phrases?.length??0)>0&&typeof env.SpeechRecognitionPhrase=="function",fellBack=false,retriedWithoutPhrases=false,pendingRelaunch=false,recognition=null,generation=0,started=false,finished=false,stopRequested=false,stoppedByOwner=false,heardAnything=false,transcript="",lastError=null,timer=null,finish=()=>{if(finished)return;finished=true,generation+=1,timer!==null&&timers.clearTimeout(timer),timer=null;let error=lastError;error===null&&!stoppedByOwner&&transcript.trim()===""&&(error="noSpeech"),callbacks.onEnd?.({mode:mode,transcript:transcript,error:error})},launch=()=>{if(!ctor){lastError="unavailable",finish();return}generation+=1;let token=generation,live=()=>token===generation&&!finished,next=new ctor;if(recognition=next,next.lang=lang,next.continuous=true,next.interimResults=true,mode==="on_device")try{next.processLocally=!0}catch{mode="browser"}if(mode==="on_device"&&usePhrases)try{let Phrase=env.SpeechRecognitionPhrase;next.phrases=(options.phrases??[]).map(phrase=>new Phrase(phrase))}catch{usePhrases=false,retriedWithoutPhrases=true}next.onstart=()=>{!live()||started||(started=true,callbacks.onStart?.(mode))},next.onresult=event=>{live()&&(heardAnything=true,transcript=joinRecognitionResults(event.results),callbacks.onTranscript?.(transcript))},next.onerror=event=>{if(!live())return;let code=event?.error??"";if(!(code==="aborted"&&stopRequested)){if(code==="phrases-not-supported"&&!retriedWithoutPhrases&&!heardAnything&&!stopRequested){usePhrases=false,retriedWithoutPhrases=true,pendingRelaunch=true;return}if(mode==="on_device"&&!fellBack&&!heardAnything&&!stopRequested&&ON_DEVICE_FALLBACK_CODES.has(code)){mode="browser",usePhrases=false,fellBack=true,pendingRelaunch=true;return}code==="no-speech"&&transcript.trim()!==""||(lastError=mapDictationError(code))}},next.onend=()=>{if(live()){if(pendingRelaunch&&!stopRequested){pendingRelaunch=false,launch();return}finish()}};try{next.start()}catch{if(mode==="on_device"&&!fellBack){mode="browser",usePhrases=false,fellBack=true,launch();return}lastError="unavailable",finish()}};if(capability==="downloadable"&&ctor&&typeof ctor.install=="function")try{Promise.resolve(ctor.install({langs:[lang],processLocally:!0})).catch(()=>{})}catch{}let stopListening=()=>{if(!(finished||stopRequested)){stopRequested=true,pendingRelaunch=false,timer!==null&&timers.clearTimeout(timer),timer=null;try{recognition?.stop()}catch{finish()}}};timer=timers.setTimeout(()=>{timer=null,stopListening()},maxDurationMs);let session={get mode(){return mode},stop(){finished||stopRequested||(stoppedByOwner=true,stopListening())},cancel(){if(finished)return;stopRequested=true,stoppedByOwner=true,pendingRelaunch=false;let current=recognition;finish();try{current?.abort()}catch{}}};return launch(),session}var DICTATION_ERROR_VISIBLE_MS=6e3;function trackDictationEvent(telemetry,name,properties){if(telemetry)try{telemetry.track(name,{...properties})}catch{}}function browserEnv(){return typeof window>"u"?null:window}function useDictation({enabled:enabled,input:input,setInput:setInput,phrases:phrases,maxLength:maxLength,telemetry:telemetry,env:env}){let[capability,setCapability]=useState("none"),[status,setStatus]=useState("idle"),[error,setError]=useState(null),[elapsedMs,setElapsedMs]=useState(0),sessionRef=useRef(null),startedAtRef=useRef(null),inputRef=useRef(input);inputRef.current=input;let setInputRef=useRef(setInput);setInputRef.current=setInput;let telemetryRef=useRef(telemetry);telemetryRef.current=telemetry;let[probeCount,setProbeCount]=useState(0),resolveEnv=useCallback(()=>env??browserEnv(),[env]);useEffect(()=>{if(!enabled){setCapability("none");return}let target=resolveEnv();if(!target)return;let live=true;return probeDictationCapability(target,resolveDictationLang(target.navigator?.language)).then(next=>{live&&setCapability(next)}),()=>{live=false}},[enabled,resolveEnv,probeCount]);let start=useCallback(()=>{let target=resolveEnv();if(!target||capability==="none")return;setError(null),setElapsedMs(0),startedAtRef.current=null,setStatus("starting");let base2=inputRef.current,probedAs=capability,ended=false,session=startDictation({env:target,capability:capability,lang:resolveDictationLang(target.navigator?.language),...phrases!==void 0?{phrases:phrases}:{},callbacks:{onStart:mode=>{startedAtRef.current=Date.now(),setStatus("listening"),trackDictationEvent(telemetryRef.current,"chat_dictation_started",{mode:mode})},onTranscript:transcript=>{setInputRef.current(composeDictatedText(base2,transcript,maxLength))},onEnd:({mode:mode,transcript:transcript,error:endError})=>{ended=true,sessionRef.current=null;let startedAt=startedAtRef.current;startedAtRef.current=null,endError?(setError(endError),setStatus("error"),trackDictationEvent(telemetryRef.current,"chat_dictation_failed",{mode:mode,error:endError})):(setStatus("idle"),trackDictationEvent(telemetryRef.current,"chat_dictation_completed",{mode:mode,duration_ms:startedAt===null?0:Date.now()-startedAt,char_count:transcript.trim().length})),probedAs==="downloadable"&&setProbeCount(count2=>count2+1)}}});ended||(sessionRef.current=session)},[capability,maxLength,phrases,resolveEnv]),stop=useCallback(()=>{sessionRef.current?.stop()},[]),cancel=useCallback(()=>{sessionRef.current?.cancel()},[]),active=status==="starting"||status==="listening",toggle=useCallback(()=>{if(sessionRef.current){sessionRef.current.stop();return}start()},[start]);return useEffect(()=>{if(status!=="listening")return;let tick=()=>{let startedAt=startedAtRef.current;startedAt!==null&&setElapsedMs(Date.now()-startedAt)};tick();let handle=setInterval(tick,1e3);return()=>clearInterval(handle)},[status]),useEffect(()=>{if(!active||typeof document>"u")return;let onVisibility=()=>{document.visibilityState==="hidden"&&sessionRef.current?.stop()};return document.addEventListener("visibilitychange",onVisibility),()=>document.removeEventListener("visibilitychange",onVisibility)},[active]),useEffect(()=>{if(!active||typeof document>"u")return;let onKey=event=>{event.key==="Escape"&&sessionRef.current?.stop()};return document.addEventListener("keydown",onKey),()=>document.removeEventListener("keydown",onKey)},[active]),useEffect(()=>{if(status!=="error")return;let handle=setTimeout(()=>{setError(null),setStatus("idle")},DICTATION_ERROR_VISIBLE_MS);return()=>clearTimeout(handle)},[status]),useEffect(()=>()=>{sessionRef.current?.cancel()},[]),{supported:enabled&&capability!=="none",status:status,active:active,error:error,elapsedMs:elapsedMs,toggle:toggle,stop:stop,cancel:cancel}}var DICTATION_VOCABULARY=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function buildDictationPhrases(pet={}){let seen=/* @__PURE__ */new Set,phrases=[];for(let candidate of[pet.name,pet.breed,...DICTATION_VOCABULARY]){let phrase=(candidate??"").trim();if(!phrase)continue;let key=phrase.toLowerCase();if(!seen.has(key)&&(seen.add(key),phrases.push(phrase),phrases.length>=100))break}return phrases}function composerPlaceholder(branded,mood,petName,petPlaceholder=false){let named=typeof petName=="string"&&petName.trim()!=="";return petPlaceholder&&named&&mood!=="urgent"?forPet(CHAT_COPY.placeholder,petName):branded!==null?branded:mood==="urgent"?CHAT_COPY.placeholderUrgentWeb:mood==="followUp"?CHAT_COPY.placeholderFollowUpWeb:forPet(CHAT_COPY.placeholder,petName)}var COMPACT_HEIGHT=52,COMPACT_DISC_SIZE=40,COMPACT_ATTACH_GLYPH=22,COMPACT_SEND_GLYPH=20,COMPACT_PILL={alignItems:"center",gap:6,minHeight:COMPACT_HEIGHT,paddingTop:0,paddingBottom:0,paddingLeft:8,paddingRight:6,borderRadius:COMPACT_HEIGHT/2},COMPACT_BLOCK_TOP=6,COMPACT_BLOCK_FOOT=10,COMPACT_BLOCK={width:"calc(100% - 28px)",paddingTop:COMPACT_BLOCK_TOP,paddingBottom:COMPACT_BLOCK_FOOT},COMPACT_ATTACH={marginLeft:-3,marginRight:-3},COMPACT_SEND={marginLeft:-2,marginRight:-2},COMPACT_DISC={width:COMPACT_DISC_SIZE,height:COMPACT_DISC_SIZE,borderRadius:COMPACT_DISC_SIZE/2};function Composer({send:send,draftScope:draftScope,stop:stop,isStreaming:isStreaming,inputRef:inputRef,conversationId:conversationId2,seed:seed,draftStore:draftStore,attachments:attachments,onPreview:onPreview,dictation:dictation,pet:pet,telemetry:telemetry,mood:mood="ask",compact:compact=false,petPlaceholder:petPlaceholder=false,dimEmptySend:dimEmptySend=false,children:children}){let{theme:theme,styles:styles}=useChatTheme(),[draft,setDraft]=useChatDraft(draftScope,conversationId2,seed);usePersistedDraft(draftStore,conversationId2===null?null:String(conversationId2),draft,setDraft);let[focused,setFocused]=useState(false),placeholder=composerPlaceholder(theme.meta.placeholder,mood,pet?.name,petPlaceholder),phrases=useMemo(()=>buildDictationPhrases({name:pet?.name??null,breed:pet?.breed??null}),[pet?.name,pet?.breed]),voice=useDictation({enabled:dictation,input:draft,setInput:setDraft,phrases:phrases,maxLength:MESSAGE_MAX_CHARS,telemetry:telemetry}),cancelDictation=voice.cancel,dictating=voice.active,fileInput=useRef(null),liveUrls=useRef(/* @__PURE__ */new Set),sentUrls=useRef(/* @__PURE__ */new Set);useEffect(()=>()=>{for(let url of liveUrls.current)revokeObjectUrl(url);for(let url of sentUrls.current)revokeObjectUrl(url)},[]);let onPick=useCallback(event=>{if(attachments===null)return;let files=Array.from(event.target.files??[]);if(event.target.value="",files.length===0)return;attachments.dismissRejected();let handles=files.map(fileToAttachmentHandle),outcomes=attachments.add(handles);handles.forEach((handle,index)=>{outcomes[index]?.ok===true?liveUrls.current.add(handle.uri):revokeObjectUrl(handle.uri)})},[attachments]),onRemove=useCallback(id=>{if(attachments===null)return;let row=attachments.attachments.find(entry=>entry.id===id);attachments.remove(id),row!==void 0&&liveUrls.current.delete(row.previewUri)&&revokeObjectUrl(row.previewUri)},[attachments]),uploading=attachments!==null&&attachments.uploading,uploadFailed=attachments!==null&&attachments.failed,uploadBlocked=uploading||uploadFailed,isOverLimit=useMemo(()=>[...draft].length>MESSAGE_MAX_CHARS,[draft]),onSend=useCallback(()=>{if(draft.trim().length===0||[...draft].length>MESSAGE_MAX_CHARS||uploadBlocked)return;dictating&&cancelDictation();let images=attachments===null?NO_IMAGES:attachments.attachments.flatMap(row=>row.status==="uploaded"?[{uri:row.previewUri,filename:row.filename}]:[]);for(let image of images)liveUrls.current.delete(image.uri),sentUrls.current.add(image.uri);send(draft,images),setDraft("")},[draft,send,uploadBlocked,dictating,cancelDictation,attachments,setDraft]),onStop=useCallback(()=>{stop()},[stop]),onKeyDown2=useCallback(event=>{event.key!=="Enter"||event.shiftKey||event.altKey||event.ctrlKey||event.metaKey||event.nativeEvent.isComposing||(event.preventDefault(),onSend())},[onSend]),onChange=useCallback(event=>{dictating&&cancelDictation(),setDraft(event.target.value)},[dictating,cancelDictation,setDraft]);useLayoutEffect(()=>{let node=inputRef.current;node!==null&&(node.style.height="auto",node.style.height=`${Math.min(node.scrollHeight,INPUT_MAX_HEIGHT)}px`)},[draft,inputRef]);let sendBlocked=isOverLimit||uploadBlocked||draft.trim().length===0,sendDimmed=isOverLimit||uploadBlocked||dimEmptySend&&draft.trim().length===0,attachFull=attachments!==null&&attachments.attachments.length>=attachments.maxPerMessage,onPillPress=useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),inputRef.current?.focus())},[inputRef]),sendInk=sendGlyphInk(theme);/* @__PURE__ */
|
|
388
|
+
/* @__PURE__ */jsx("span",{role:"status","aria-live":"polite",style:VISUALLY_HIDDEN,children:listening?CHAT_COPY.listening:""})]})}function Pulse({style:style}){let ref=useRef(null),motion=useChatMotion();return useEffect(()=>{let node=ref.current;if(motion.reduced||!canAnimate(node))return;let animation=node.animate([{opacity:1},{opacity:.4},{opacity:1}],{duration:PULSE_LOOP_MS,iterations:1/0,easing:"ease-in-out"});return()=>animation.cancel()},[motion.reduced]),/* @__PURE__ */jsx("span",{ref:ref,"aria-hidden":"true",style:style})}function makeStyles15(theme){let c=theme.color,r=theme.radius,t=theme.type;return{wrap:{display:"inline-flex",flexShrink:0,alignItems:"center",gap:theme.space.xs},timer:{...faceCss(theme,"mono"),fontSize:t.tierSizes.compact.micro,lineHeight:`${t.tierSizes.compact.micro+2}px`,fontVariantNumeric:"tabular-nums",color:c.text.muted},button:{position:"relative",boxSizing:"border-box",width:MIN_TOUCH_TARGET14,height:MIN_TOUCH_TARGET14,minWidth:MIN_TOUCH_TARGET14,minHeight:MIN_TOUCH_TARGET14,margin:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:c.brandInk},buttonDisabled:{opacity:DISABLED_OPACITY2,cursor:"not-allowed"},pulse:{position:"absolute",top:PULSE_INSET,right:PULSE_INSET,bottom:PULSE_INSET,left:PULSE_INSET,borderRadius:r.pill,backgroundColor:c.brandSofter}}}var DICTATION_MAX_DURATION_MS=6e4;function getRecognitionConstructor(env){if(!env)return null;let ctor=env.SpeechRecognition??env.webkitSpeechRecognition;return typeof ctor=="function"?ctor:null}function resolveDictationLang(language){return typeof language=="string"&&language.toLowerCase().startsWith("en")?language:"en-US"}async function probeDictationCapability(env,lang){let ctor=getRecognitionConstructor(env);if(!ctor)return"none";if(typeof ctor.available!="function")return"browser";try{let status=await ctor.available({langs:[lang],processLocally:!0});return status==="available"?"on_device":status==="downloadable"?"downloadable":"browser"}catch{return"browser"}}function joinRecognitionResults(results){let pieces=[];for(let index=0;index<results.length;index+=1){let piece=results[index]?.[0]?.transcript?.trim();if(!piece)continue;let previous=pieces[pieces.length-1];previous&&piece.toLowerCase().startsWith(previous.toLowerCase())?pieces[pieces.length-1]=piece:pieces.push(piece)}return pieces.join(" ")}function mapDictationError(code){return code==="not-allowed"||code==="service-not-allowed"?"permissionDenied":code==="no-speech"?"noSpeech":"unavailable"}var ON_DEVICE_FALLBACK_CODES=/* @__PURE__ */new Set(["language-not-supported","service-not-allowed"]),defaultTimers3={setTimeout:(run,ms)=>globalThis.setTimeout(run,ms),clearTimeout:handle=>globalThis.clearTimeout(handle)};function startDictation(options){let{env:env,capability:capability,lang:lang,callbacks:callbacks}=options,timers=options.timers??defaultTimers3,maxDurationMs=options.maxDurationMs??DICTATION_MAX_DURATION_MS,ctor=getRecognitionConstructor(env),mode=capability==="on_device"?"on_device":"browser",usePhrases=mode==="on_device"&&(options.phrases?.length??0)>0&&typeof env.SpeechRecognitionPhrase=="function",fellBack=false,retriedWithoutPhrases=false,pendingRelaunch=false,recognition=null,generation=0,started=false,finished=false,stopRequested=false,stoppedByOwner=false,heardAnything=false,transcript="",lastError=null,timer=null,finish=()=>{if(finished)return;finished=true,generation+=1,timer!==null&&timers.clearTimeout(timer),timer=null;let error=lastError;error===null&&!stoppedByOwner&&transcript.trim()===""&&(error="noSpeech"),callbacks.onEnd?.({mode:mode,transcript:transcript,error:error})},launch=()=>{if(!ctor){lastError="unavailable",finish();return}generation+=1;let token=generation,live=()=>token===generation&&!finished,next=new ctor;if(recognition=next,next.lang=lang,next.continuous=true,next.interimResults=true,mode==="on_device")try{next.processLocally=!0}catch{mode="browser"}if(mode==="on_device"&&usePhrases)try{let Phrase=env.SpeechRecognitionPhrase;next.phrases=(options.phrases??[]).map(phrase=>new Phrase(phrase))}catch{usePhrases=false,retriedWithoutPhrases=true}next.onstart=()=>{!live()||started||(started=true,callbacks.onStart?.(mode))},next.onresult=event=>{live()&&(heardAnything=true,transcript=joinRecognitionResults(event.results),callbacks.onTranscript?.(transcript))},next.onerror=event=>{if(!live())return;let code=event?.error??"";if(!(code==="aborted"&&stopRequested)){if(code==="phrases-not-supported"&&!retriedWithoutPhrases&&!heardAnything&&!stopRequested){usePhrases=false,retriedWithoutPhrases=true,pendingRelaunch=true;return}if(mode==="on_device"&&!fellBack&&!heardAnything&&!stopRequested&&ON_DEVICE_FALLBACK_CODES.has(code)){mode="browser",usePhrases=false,fellBack=true,pendingRelaunch=true;return}code==="no-speech"&&transcript.trim()!==""||(lastError=mapDictationError(code))}},next.onend=()=>{if(live()){if(pendingRelaunch&&!stopRequested){pendingRelaunch=false,launch();return}finish()}};try{next.start()}catch{if(mode==="on_device"&&!fellBack){mode="browser",usePhrases=false,fellBack=true,launch();return}lastError="unavailable",finish()}};if(capability==="downloadable"&&ctor&&typeof ctor.install=="function")try{Promise.resolve(ctor.install({langs:[lang],processLocally:!0})).catch(()=>{})}catch{}let stopListening=()=>{if(!(finished||stopRequested)){stopRequested=true,pendingRelaunch=false,timer!==null&&timers.clearTimeout(timer),timer=null;try{recognition?.stop()}catch{finish()}}};timer=timers.setTimeout(()=>{timer=null,stopListening()},maxDurationMs);let session={get mode(){return mode},stop(){finished||stopRequested||(stoppedByOwner=true,stopListening())},cancel(){if(finished)return;stopRequested=true,stoppedByOwner=true,pendingRelaunch=false;let current=recognition;finish();try{current?.abort()}catch{}}};return launch(),session}function browserEnv(){return typeof window>"u"?null:window}function useDictation({enabled:enabled,input:input,setInput:setInput,phrases:phrases,maxLength:maxLength,telemetry:telemetry,env:env}){let[capability,setCapability]=useState("none"),[status,setStatus]=useState("idle"),[error,setError]=useState(null),[elapsedMs,setElapsedMs]=useState(0),sessionRef=useRef(null),startedAtRef=useRef(null),inputRef=useRef(input);inputRef.current=input;let setInputRef=useRef(setInput);setInputRef.current=setInput;let telemetryRef=useRef(telemetry);telemetryRef.current=telemetry;let[probeCount,setProbeCount]=useState(0),resolveEnv=useCallback(()=>env??browserEnv(),[env]);useEffect(()=>{if(!enabled){setCapability("none");return}let target=resolveEnv();if(!target)return;let live=true;return probeDictationCapability(target,resolveDictationLang(target.navigator?.language)).then(next=>{live&&setCapability(next)}),()=>{live=false}},[enabled,resolveEnv,probeCount]);let start=useCallback(()=>{let target=resolveEnv();if(!target||capability==="none")return;setError(null),setElapsedMs(0),startedAtRef.current=null,setStatus("starting");let base2=inputRef.current,probedAs=capability,ended=false,session=startDictation({env:target,capability:capability,lang:resolveDictationLang(target.navigator?.language),...phrases!==void 0?{phrases:phrases}:{},callbacks:{onStart:mode=>{startedAtRef.current=Date.now(),setStatus("listening"),trackDictationEvent(telemetryRef.current,"chat_dictation_started",{mode:mode})},onTranscript:transcript=>{setInputRef.current(composeDictatedText(base2,transcript,maxLength))},onEnd:({mode:mode,transcript:transcript,error:endError})=>{ended=true,sessionRef.current=null;let startedAt=startedAtRef.current;startedAtRef.current=null,endError?(setError(endError),setStatus("error"),trackDictationEvent(telemetryRef.current,"chat_dictation_failed",{mode:mode,error:endError})):(setStatus("idle"),trackDictationEvent(telemetryRef.current,"chat_dictation_completed",{mode:mode,duration_ms:startedAt===null?0:Date.now()-startedAt,char_count:transcript.trim().length})),probedAs==="downloadable"&&setProbeCount(count2=>count2+1)}}});ended||(sessionRef.current=session)},[capability,maxLength,phrases,resolveEnv]),stop=useCallback(()=>{sessionRef.current?.stop()},[]),cancel=useCallback(()=>{sessionRef.current?.cancel()},[]),active=status==="starting"||status==="listening",toggle=useCallback(()=>{if(sessionRef.current){sessionRef.current.stop();return}start()},[start]);return useEffect(()=>{if(status!=="listening")return;let tick=()=>{let startedAt=startedAtRef.current;startedAt!==null&&setElapsedMs(Date.now()-startedAt)};tick();let handle=setInterval(tick,1e3);return()=>clearInterval(handle)},[status]),useEffect(()=>{if(!active||typeof document>"u")return;let onVisibility=()=>{document.visibilityState==="hidden"&&sessionRef.current?.stop()};return document.addEventListener("visibilitychange",onVisibility),()=>document.removeEventListener("visibilitychange",onVisibility)},[active]),useEffect(()=>{if(!active||typeof document>"u")return;let onKey=event=>{event.key==="Escape"&&sessionRef.current?.stop()};return document.addEventListener("keydown",onKey),()=>document.removeEventListener("keydown",onKey)},[active]),useEffect(()=>{if(status!=="error")return;let handle=setTimeout(()=>{setError(null),setStatus("idle")},DICTATION_ERROR_VISIBLE_MS);return()=>clearTimeout(handle)},[status]),useEffect(()=>()=>{sessionRef.current?.cancel()},[]),{supported:enabled&&capability!=="none",status:status,active:active,error:error,elapsedMs:elapsedMs,toggle:toggle,stop:stop,cancel:cancel}}var DICTATION_VOCABULARY=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function buildDictationPhrases(pet={}){let seen=/* @__PURE__ */new Set,phrases=[];for(let candidate of[pet.name,pet.breed,...DICTATION_VOCABULARY]){let phrase=(candidate??"").trim();if(!phrase)continue;let key=phrase.toLowerCase();if(!seen.has(key)&&(seen.add(key),phrases.push(phrase),phrases.length>=100))break}return phrases}function composerPlaceholder(branded,mood,petName,petPlaceholder=false){let named=typeof petName=="string"&&petName.trim()!=="";return petPlaceholder&&named&&mood!=="urgent"?forPet(CHAT_COPY.placeholder,petName):branded!==null?branded:mood==="urgent"?CHAT_COPY.placeholderUrgentWeb:mood==="followUp"?CHAT_COPY.placeholderFollowUpWeb:forPet(CHAT_COPY.placeholder,petName)}var COMPACT_HEIGHT=52,COMPACT_DISC_SIZE=40,COMPACT_ATTACH_GLYPH=22,COMPACT_SEND_GLYPH=20,COMPACT_PILL={alignItems:"center",gap:6,minHeight:COMPACT_HEIGHT,paddingTop:0,paddingBottom:0,paddingLeft:8,paddingRight:6,borderRadius:COMPACT_HEIGHT/2},COMPACT_BLOCK_TOP=6,COMPACT_BLOCK_FOOT=10,COMPACT_BLOCK={width:"calc(100% - 28px)",paddingTop:COMPACT_BLOCK_TOP,paddingBottom:COMPACT_BLOCK_FOOT},COMPACT_ATTACH={marginLeft:-3,marginRight:-3},COMPACT_SEND={marginLeft:-2,marginRight:-2},COMPACT_DISC={width:COMPACT_DISC_SIZE,height:COMPACT_DISC_SIZE,borderRadius:COMPACT_DISC_SIZE/2};function Composer({send:send,draftScope:draftScope,stop:stop,isStreaming:isStreaming,inputRef:inputRef,conversationId:conversationId2,seed:seed,draftStore:draftStore,attachments:attachments,onPreview:onPreview,dictation:dictation,pet:pet,telemetry:telemetry,mood:mood="ask",compact:compact=false,petPlaceholder:petPlaceholder=false,dimEmptySend:dimEmptySend=false,children:children}){let{theme:theme,styles:styles}=useChatTheme(),[draft,setDraft]=useChatDraft(draftScope,conversationId2,seed);usePersistedDraft(draftStore,conversationId2===null?null:String(conversationId2),draft,setDraft);let[focused,setFocused]=useState(false),placeholder=composerPlaceholder(theme.meta.placeholder,mood,pet?.name,petPlaceholder),phrases=useMemo(()=>buildDictationPhrases({name:pet?.name??null,breed:pet?.breed??null}),[pet?.name,pet?.breed]),voice=useDictation({enabled:dictation,input:draft,setInput:setDraft,phrases:phrases,maxLength:MESSAGE_MAX_CHARS,telemetry:telemetry}),cancelDictation=voice.cancel,dictating=voice.active,fileInput=useRef(null),liveUrls=useRef(/* @__PURE__ */new Set),sentUrls=useRef(/* @__PURE__ */new Set);useEffect(()=>()=>{for(let url of liveUrls.current)revokeObjectUrl(url);for(let url of sentUrls.current)revokeObjectUrl(url)},[]);let onPick=useCallback(event=>{if(attachments===null)return;let files=Array.from(event.target.files??[]);if(event.target.value="",files.length===0)return;attachments.dismissRejected();let handles=files.map(fileToAttachmentHandle),outcomes=attachments.add(handles);handles.forEach((handle,index)=>{outcomes[index]?.ok===true?liveUrls.current.add(handle.uri):revokeObjectUrl(handle.uri)})},[attachments]),onRemove=useCallback(id=>{if(attachments===null)return;let row=attachments.attachments.find(entry=>entry.id===id);attachments.remove(id),row!==void 0&&liveUrls.current.delete(row.previewUri)&&revokeObjectUrl(row.previewUri)},[attachments]),uploading=attachments!==null&&attachments.uploading,uploadFailed=attachments!==null&&attachments.failed,uploadBlocked=uploading||uploadFailed,isOverLimit=useMemo(()=>[...draft].length>MESSAGE_MAX_CHARS,[draft]),onSend=useCallback(()=>{if(draft.trim().length===0||[...draft].length>MESSAGE_MAX_CHARS||uploadBlocked)return;dictating&&cancelDictation();let images=attachments===null?NO_IMAGES:attachments.attachments.flatMap(row=>row.status==="uploaded"?[{uri:row.previewUri,filename:row.filename}]:[]);for(let image of images)liveUrls.current.delete(image.uri),sentUrls.current.add(image.uri);send(draft,images),setDraft("")},[draft,send,uploadBlocked,dictating,cancelDictation,attachments,setDraft]),onStop=useCallback(()=>{stop()},[stop]),onKeyDown2=useCallback(event=>{event.key!=="Enter"||event.shiftKey||event.altKey||event.ctrlKey||event.metaKey||event.nativeEvent.isComposing||(event.preventDefault(),onSend())},[onSend]),onChange=useCallback(event=>{dictating&&cancelDictation(),setDraft(event.target.value)},[dictating,cancelDictation,setDraft]);useLayoutEffect(()=>{let node=inputRef.current;node!==null&&(node.style.height="auto",node.style.height=`${Math.min(node.scrollHeight,INPUT_MAX_HEIGHT)}px`)},[draft,inputRef]);let sendBlocked=isOverLimit||uploadBlocked||draft.trim().length===0,sendDimmed=isOverLimit||uploadBlocked||dimEmptySend&&draft.trim().length===0,attachFull=attachments!==null&&attachments.attachments.length>=attachments.maxPerMessage,onPillPress=useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),inputRef.current?.focus())},[inputRef]),sendInk=sendGlyphInk(theme);/* @__PURE__ */
|
|
389
389
|
return jsxs("div",{style:compact?{...styles.composerBlock,...COMPACT_BLOCK}:styles.composerBlock,children:[uploadFailed?/* @__PURE__ */jsx("p",{role:"alert",style:styles.composerError,children:CHAT_COPY.attachmentsFailedBlocked}):null,attachments!==null&&attachments.rejected!==null?/* @__PURE__ */jsx("p",{role:"alert",style:styles.composerError,children:attachmentErrorMessage(attachments.rejected)}):null,voice.supported&&voice.error!==null?/* @__PURE__ */jsx("p",{role:"alert",style:styles.composerError,children:dictationErrorMessage(voice.error)}):null,attachments!==null?/* @__PURE__ */jsx(AttachmentTray,{attachments:attachments.attachments,onRetry:attachments.retry,onRemove:onRemove,onPreview:onPreview}):null,
|
|
390
390
|
/* @__PURE__ */jsxs("div",{style:{...styles.composer,...attachments!==null?{paddingLeft:theme.space.sm}:null,...compact?COMPACT_PILL:null,...focused?styles.composerFocused:null},onMouseDown:onPillPress,children:[attachments!==null?/* @__PURE__ */jsxs(Fragment,{children:[
|
|
391
391
|
/* @__PURE__ */jsx("input",{ref:fileInput,type:"file",accept:ATTACHMENT_ACCEPT,multiple:attachments.maxPerMessage>1,onChange:onPick,tabIndex:-1,"aria-hidden":"true",style:VISUALLY_HIDDEN}),
|
|
392
392
|
/* @__PURE__ */jsx("button",{type:"button",onClick:()=>fileInput.current?.click(),"aria-label":attachControlLabel(attachments.attachments.length,attachments.maxPerMessage),"aria-disabled":attachFull,style:{...styles.iconControl,...compact?COMPACT_ATTACH:null,...attachFull?styles.actionButtonDisabled:null},children:/* @__PURE__ */jsx(Glyph,{name:"upload",size:compact?COMPACT_ATTACH_GLYPH:ATTACH_GLYPH_SIZE,color:theme.color.brandInk})})]}):null,
|
|
393
393
|
/* @__PURE__ */jsxs("div",{style:styles.inputWrap,children:[draft.length===0?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.placeholder,children:placeholder}):null,
|
|
394
394
|
/* @__PURE__ */jsx("textarea",{ref:inputRef,rows:1,value:draft,onChange:onChange,onKeyDown:onKeyDown2,onFocus:()=>setFocused(true),onBlur:()=>setFocused(false),"data-ef-focus-ring":"self","aria-label":CHAT_COPY.composerLabel,"aria-description":placeholder,style:styles.input})]}),voice.supported?/* @__PURE__ */jsx(DictationButton,{active:voice.active,listening:voice.status==="listening",elapsedMs:voice.elapsedMs,onToggle:voice.toggle}):null,isStreaming?/* @__PURE__ */jsx("button",{type:"button",onClick:onStop,"aria-label":CHAT_COPY.stop,style:{...styles.actionButton,...compact?COMPACT_SEND:null},children:/* @__PURE__ */jsx("span",{"data-everfur-send-disc":"",style:{...styles.sendDisc,...compact?COMPACT_DISC:null},children:/* @__PURE__ */jsx(Glyph,{name:"square",size:STOP_GLYPH_SIZE,color:sendInk,fill:sendInk})})}):/* @__PURE__ */jsx("button",{type:"button",onClick:onSend,"aria-label":CHAT_COPY.send,"aria-disabled":sendBlocked,style:{...styles.actionButton,...compact?COMPACT_SEND:null,...sendDimmed?styles.actionButtonDisabled:null},children:/* @__PURE__ */jsx("span",{"data-everfur-send-disc":"",style:{...styles.sendDisc,...compact?COMPACT_DISC:null},children:compact?/* @__PURE__ */jsx(Glyph,{name:"arrowUp",size:COMPACT_SEND_GLYPH,color:sendInk,strokeWidth:2.3}):/* @__PURE__ */jsx(Glyph,{name:"send",size:SEND_GLYPH_SIZE,color:sendInk})})})]}),children]})}var WEB_ATTACHMENT_TRANSPORT=createWebAttachmentTransport(),NO_IMAGES2=/* @__PURE__ */Object.freeze([]),TELEVET_HOST_SCOPE=/* @__PURE__ */Object.freeze({display:"contents"});function EverfurChat(props){let{style:style,className:className,renderPending:renderPending}=props;/* @__PURE__ */
|
|
395
|
-
return jsx(CapabilityGate,{capability:"chat",style:style,className:className,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsx(CitationLinksScope,{onOpenUrl:props.onOpenUrl,children:/* @__PURE__ */jsx(ChatLayoutScope,{headingLevel:props.headingLevel,children:/* @__PURE__ */jsx(ChatBody,{...props})})})})}function ChatBody(props){let{petRef:petRef2,conversationId:conversationId2,style:style,className:className,renderPending:renderPending,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer}=props,maxPerMessage=props.attachments===false?void 0:props.attachments?.maxPerMessage,{presentation:hostPresentation,dictation:dictation,attachments:attachmentsProp,topCard:hostTopCard}=props,{presentation:presentation,isLocked:isLocked2}=useEverfurPresentationState(definedPresentation({...hostPresentation,chatComposerMic:hostPresentation?.chatComposerMic??(dictation===void 0?void 0:dictation!==false),chatComposerUpload:hostPresentation?.chatComposerUpload??(attachmentsProp===void 0?void 0:attachmentsProp!==false)})),attachmentsEnabled=presentation.chatComposerUpload,dictationEnabled=presentation.chatComposerMic,answerFooter=presentation.safetyDisclaimerPlacement==="answer_footer",sheet=presentation.chatHistoryStyle==="sheet",topCardState=useTopCardState(),{activePet:activePet}=useEverfurContext(),planPetRef=petRef2??activePet??null,planEnabled=useCapabilityEnabled("healthPlan"),wantsPlan=presentation.chatTopCard==="focus"&&hostTopCard===void 0&&planEnabled,planPage=useHealthPlanPage({petRef:planPetRef,enabled:wantsPlan}),onOpenHealthPlan=props.onOpenHealthPlan,openPlan=useMemo(()=>onOpenHealthPlan===void 0?void 0:()=>{callHost(onOpenHealthPlan,planPetRef)},[onOpenHealthPlan,planPetRef]),planCard=useMemo(()=>wantsPlan&&planPage.phase==="ready"?
|
|
395
|
+
return jsx(CapabilityGate,{capability:"chat",style:style,className:className,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsx(CitationLinksScope,{onOpenUrl:props.onOpenUrl,children:/* @__PURE__ */jsx(ChatLayoutScope,{headingLevel:props.headingLevel,children:/* @__PURE__ */jsx(ChatBody,{...props})})})})}function ChatBody(props){let{petRef:petRef2,conversationId:conversationId2,style:style,className:className,renderPending:renderPending,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer}=props,maxPerMessage=props.attachments===false?void 0:props.attachments?.maxPerMessage,{presentation:hostPresentation,dictation:dictation,attachments:attachmentsProp,topCard:hostTopCard}=props,{presentation:presentation,isLocked:isLocked2}=useEverfurPresentationState(definedPresentation({...hostPresentation,chatComposerMic:hostPresentation?.chatComposerMic??(dictation===void 0?void 0:dictation!==false),chatComposerUpload:hostPresentation?.chatComposerUpload??(attachmentsProp===void 0?void 0:attachmentsProp!==false)})),attachmentsEnabled=presentation.chatComposerUpload,dictationEnabled=presentation.chatComposerMic,answerFooter=presentation.safetyDisclaimerPlacement==="answer_footer",sheet=presentation.chatHistoryStyle==="sheet",topCardState=useTopCardState(),{activePet:activePet}=useEverfurContext(),planPetRef=petRef2??activePet??null,planEnabled=useCapabilityEnabled("healthPlan"),wantsPlan=presentation.chatTopCard==="focus"&&hostTopCard===void 0&&planEnabled,planPage=useHealthPlanPage({petRef:planPetRef,enabled:wantsPlan}),onOpenHealthPlan=props.onOpenHealthPlan,openPlan=useMemo(()=>onOpenHealthPlan===void 0?void 0:()=>{callHost(onOpenHealthPlan,planPetRef)},[onOpenHealthPlan,planPetRef]),planCard=useMemo(()=>wantsPlan&&planPage.phase==="ready"?healthPlanTopCard2(planPage.page,{onOpenPlan:openPlan}):void 0,[wantsPlan,planPage.phase,planPage.page,openPlan]),topCard=hostTopCard??planCard,showTopCard=topCard!==void 0&&presentation.chatTopCard==="focus",{theme:theme,styles:styles}=useChatTheme(),hostPoweredBy=useHostPoweredBy(),{starterPrompts:starterPrompts,renderEmptyHeader:renderEmptyHeader,emptyState:emptyState,initialAskCard:initialAskCard,answerCards:answerCards}=props,countLocked=isLocked2("chatFollowUpCount"),followUpPolicy=useMemo(()=>followUpPolicyFor(props.followUpPolicy,presentation,countLocked),[props.followUpPolicy,presentation,countLocked]),askPrompt=useMemo(()=>sanitizeSeedPrompt(initialAsk),[initialAsk]),historyBar=useMemo(()=>{let bar=props.historyBar;return bar===void 0||!showTopCard||topCard===void 0?bar:{...bar,extra:/* @__PURE__ */jsxs(Fragment,{children:[bar.extra??null,
|
|
396
396
|
/* @__PURE__ */jsx(TopCardPill,{card:topCard,state:topCardState})]})}},[props.historyBar,showTopCard,topCard,topCardState]),chatOpts=useMemo(()=>buildChatOpts(petRef2,conversationId2),[petRef2,conversationId2]),chat=useEverfurChat(chatOpts),view=selectView2(chat),pets=useEverfurPets(),headerPet=useMemo(()=>headerPetOf(pets.pets,chat.petRef),[pets.pets,chat.petRef]),disclaimerClass=answerCards?.classNames?.disclaimer,footnoteInThread=answerFooter&&(view==="populated"||view==="empty"),barInThread=presentation.chatHistoryBar==="scroll"&&(view==="populated"||view==="empty"),footnote=/* @__PURE__ */jsx("p",{role:"note","data-everfur-footnote":"",className:footnoteInThread?disclaimerClass:void 0,style:footnoteInThread&&disclaimerClass?void 0:styles.footnote,children:forPet(CHAT_COPY.footnoteWeb,headerPet?.name)}),history=useHistoryPanel(chat),historyTrigger=useRef(null),threadEmpty=chat.messages.length===0,unread=(chat.hasUnreadThreads??false)||(chat.unreadCount??0)>0||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0),historyBarNode=useMemo(()=>historyBar===void 0?null:/* @__PURE__ */jsx(HistoryBar,{bar:historyBar,history:history,triggerRef:historyTrigger,empty:threadEmpty,unread:unread}),[historyBar,history,threadEmpty,unread]),textingAsk=useChatTextingAsk(presentation.chatTextingAsk,chat,presentation.chatTextingAsk&&props.textingEntry!==false,props.header===false),onTopCardAsk=useCallback(prompt=>{chat.send(prompt)},[chat.send]),emptyOptions=useMemo(()=>({...starterPrompts!==void 0?{starterPrompts:starterPrompts}:{},...renderEmptyHeader!==void 0?{renderEmptyHeader:renderEmptyHeader}:{},...emptyState!==void 0?{emptyState:emptyState}:{},...followUpPolicy!==void 0?{followUpPolicy:followUpPolicy}:{},...initialAskCard!==void 0&&askPrompt!==null?{openingCard:{card:initialAskCard,prompt:askPrompt}}:{},...presentation.chatAnswerStyle==="cards"?{answerStyle:"cards",answerCards:answerCards}:{},...footnoteInThread?{answerFooter:footnote}:{},...showTopCard&&topCard!==void 0?{topCard:/* @__PURE__ */jsx(TopCard,{card:topCard,state:topCardState,ask:onTopCardAsk})}:{},...barInThread&&historyBarNode!==null?{threadTop:historyBarNode}:{},...textingAsk.line!==null?{threadAside:textingAsk.line,...textingAsk.stage!==null?{threadAsideKey:textingAsk.stage}:{}}:{}}),[starterPrompts,renderEmptyHeader,emptyState,followUpPolicy,initialAskCard,askPrompt,presentation.chatAnswerStyle,answerCards,footnoteInThread,headerPet?.name,disclaimerClass,showTopCard,topCard,topCardState,onTopCardAsk,barInThread,historyBarNode,textingAsk.line,textingAsk.stage]),inputRef=useRef(null),context=useEverfurContext(),announcement=useReplyAnnouncement(chat,headerPet?.name??null),addPet=useMemo(()=>onAddPet===void 0?null:()=>{callHost(onAddPet)},[onAddPet]),onSelectPet=useCallback(next=>{context.handle.setActivePet(next),callHost(onPetChange,next)},[context.handle,onPetChange]),barShown=historyBar!==void 0,historyLoad=history.load,historyOpen=history.open;useEffect(()=>{barShown&&!historyOpen&&historyLoad()},[barShown,historyOpen,chat.conversationId,historyLoad]);let layout=useChatLayout();useCheckinTarget(chat.openCheckin,checkinTarget),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk,initialAskKey);let seed=useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]),lifecyclePort=useMemo(()=>lifecycle===void 0?createBrowserLifecycle():lifecycle??void 0,[lifecycle]);useChatLifecycle(lifecyclePort,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refresh:chat.refreshActiveThread});let urgency=useUrgencySurface(useMemo(()=>latestUrgencySource(chat.messages),[chat.messages])),vetOptions=useMemo(()=>chatVetVisitOptions(chat.petRef,vetReturnTo===void 0&&vetUsState===void 0&&vetPrefer===void 0?void 0:{returnTo:vetReturnTo,usState:vetUsState,prefer:vetPrefer}),[chat.petRef,vetReturnTo,vetUsState,vetPrefer]),vetVisit=useVetVisit(vetOptions),openVetVisit=vetVisit.open,vetEntry=useMemo(()=>({available:vetVisit.available,open:()=>{openVetVisit()}}),[vetVisit.available,openVetVisit]),checkinFindVet=useMemo(()=>vetEntry.available?vetEntry.open:onFindVet!==void 0?()=>{callHost(onFindVet,"emergency")}:null,[vetEntry,onFindVet]),vetPrep=useMemo(()=>onVetPrep!==void 0?()=>{callHost(onVetPrep,chat.petRef)}:vetEntry.available?vetEntry.open:null,[onVetPrep,chat.petRef,vetEntry]),attachments=useChatAttachments({transport:WEB_ATTACHMENT_TRANSPORT,...maxPerMessage!==void 0?{maxPerMessage:maxPerMessage}:{}}),sentImages=useSentImages(chat.messages),[lightbox,setLightbox]=useState(null),lightboxTrigger=useRef(null),onPreview=useCallback((image,trigger)=>{lightboxTrigger.current=trigger,setLightbox(image)},[]),closeLightbox=useCallback(()=>setLightbox(null),[]),onSelectPrompt=useCallback(prompt=>{chat.send(prompt),inputRef.current?.focus()},[chat.send]),onSend=useCallback((text3,images)=>{sentImages.record(text3,images),attachments.s3Keys.length>0?chat.send(text3,{imageS3Keys:attachments.s3Keys}):chat.send(text3),attachments.clear()},[chat.send,attachments,sentImages]),telemetry=context.runtime.registry?.services?.telemetry??null,rootRef=useRef(null);return useKeyboardFocusRing(rootRef,theme.color.brandInk),useMeasuredLayout(rootRef),/* @__PURE__ */jsxs("div",{ref:rootRef,className:className,style:{...styles.container,...style},children:[props.header===false?null:/* @__PURE__ */jsx(ChatHeader,{pets:pets.pets,activePet:headerPet,unread:unread,onOpenHistory:history.open?history.close:history.show,historyTriggerRef:historyTrigger,onSelectPet:onSelectPet,onAddPet:addPet,rail:layout.rail,historyOpen:history.open,onNewChat:history.newConversation,vetEntry:vetEntry.available?vetEntry.open:null,textingEntry:textingAsk.headerEntry}),pet!==void 0?/* @__PURE__ */jsx(PetSetupNotice,{petRef:petRef2??null,pet:pet,onRegistered:pets.refresh}):null,
|
|
397
397
|
/* @__PURE__ */jsxs("div",{style:styles.split,children:[
|
|
398
398
|
/* @__PURE__ */jsxs("div",{style:styles.main,children:[props.header===false?textingAsk.headerEntry:null,barInThread?null:historyBarNode,!presentation.chatGeneralBanner&&urgency.tier?.level==="general"?null:/* @__PURE__ */jsx(UrgencyBanner,{surface:urgency,vetEntry:vetEntry,renderVetAction:renderVetAction,onFindVet:onFindVet}),
|