@everfur/sdk 0.13.0 → 0.14.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 +126 -0
- package/README.md +11 -10
- package/dist/{Chat.d-Dts8u_1a.d.cts → Chat.d-aycmX1CA.d.cts} +12 -4
- package/dist/{Chat.d-DUNTfzqC.d.ts → Chat.d-puminpyi.d.ts} +12 -4
- package/dist/{DepthViews.d-CubkMPbU.d.ts → DepthViews.d-BdvFZgPs.d.cts} +1 -1
- package/dist/{DepthViews.d-Ce2Zhnrb.d.ts → DepthViews.d-DIvxzLDf.d.ts} +1 -1
- package/dist/{DepthViews.d-BMU2jFPw.d.cts → DepthViews.d-Dy0Zl-s-.d.ts} +1 -1
- package/dist/{DepthViews.d-BIp599lz.d.cts → DepthViews.d-wLNkzk9f.d.cts} +1 -1
- package/dist/RecordsPage.d-9Ank15PT.d.ts +93 -0
- package/dist/RecordsPage.d-DMKU0IKc.d.cts +93 -0
- package/dist/animations/index.d.cts +5 -5
- package/dist/animations/index.d.ts +5 -5
- package/dist/{attachments.d-D1yhJjcZ.d.ts → attachments.d--sIsfk6e.d.ts} +2 -2
- package/dist/{attachments.d-Bp2qbHxn.d.cts → attachments.d-DNUCiyy5.d.cts} +6 -24
- package/dist/{attachments.d-DisnvB9R.d.cts → attachments.d-ZEpTUeWN.d.cts} +2 -2
- package/dist/{attachments.d-Djy9z_0Z.d.ts → attachments.d-rp3xs-Q3.d.ts} +6 -24
- package/dist/{bookingCopy.d-BJF6gd1A.d.ts → bookingCopy.d-D0uIIFAJ.d.ts} +2 -2
- package/dist/{bookingCopy.d-BlBmhAJc.d.cts → bookingCopy.d-DUrmVcLs.d.cts} +2 -2
- package/dist/{branding.d-DI8S400y.d.cts → branding.d-CTXTUg_8.d.cts} +1 -1
- package/dist/{branding.d-OIGLbQeM.d.ts → branding.d-DxJSoFce.d.ts} +1 -1
- package/dist/{casesRepository.d-CT2LTicS.d.cts → casesRepository.d-DCnix2pT.d.cts} +1 -1
- package/dist/{casesRepository.d-UsWOz9bv.d.ts → casesRepository.d-DbirgbyH.d.ts} +1 -1
- package/dist/chat/index.cjs +43 -41
- package/dist/chat/index.d.cts +26 -13
- package/dist/chat/index.d.ts +26 -13
- package/dist/chat/index.js +43 -41
- package/dist/client/index.cjs +2 -2
- package/dist/client/index.d.cts +10 -10
- package/dist/client/index.d.ts +10 -10
- package/dist/client/index.js +2 -2
- package/dist/clinicBatch.d-Ccmrngcu.d.cts +71 -0
- package/dist/clinicBatch.d-D9Ci7IpP.d.ts +71 -0
- package/dist/clinicModels.d-BXgKZqDb.d.cts +68 -0
- package/dist/clinicModels.d-CaS64-P-.d.ts +68 -0
- package/dist/clinicRequestProps.d-1dCtouGA.d.cts +65 -0
- package/dist/clinicRequestProps.d-CjsMg_OD.d.ts +65 -0
- package/dist/{config.d-BR3DT9ho.d.cts → config.d-DJ4mvf_w.d.cts} +1 -1
- package/dist/{config.d-Dy6igYlH.d.ts → config.d-MX7IKP2f.d.ts} +1 -1
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/{context.d-QcCgguzA.d.ts → context.d-BdnBe8Oe.d.ts} +7 -7
- package/dist/{context.d-Cwks0p3C.d.cts → context.d-C6MJsMpN.d.cts} +7 -7
- package/dist/{copy.d-CiMn2IIt.d.ts → copy.d-BIfQOoDB.d.ts} +2 -2
- package/dist/{copy.d-DLJTyRfT.d.cts → copy.d-C_u7shha.d.cts} +2 -2
- package/dist/core/index.cjs +3 -3
- package/dist/core/index.d.cts +20 -18
- package/dist/core/index.d.ts +20 -18
- package/dist/core/index.js +3 -3
- package/dist/{depth.d-OSALbYM7.d.ts → depth.d-COFxYWLU.d.ts} +6 -133
- package/dist/{depth.d-CjPGVPDL.d.cts → depth.d-D2e5WZuE.d.cts} +6 -133
- package/dist/{entitlementRepository.d-CVQa1DA1.d.cts → entitlementRepository.d-BP15dFbe.d.cts} +4 -4
- package/dist/{entitlementRepository.d-Cf3LbTwD.d.ts → entitlementRepository.d-DLuxnGi5.d.ts} +4 -4
- package/dist/{features.d-fNsGcg0R.d.ts → features.d-DrQxTw3-.d.cts} +1 -1
- package/dist/{features.d-fNsGcg0R.d.cts → features.d-DrQxTw3-.d.ts} +1 -1
- package/dist/{focus.d-DMg2ngHI.d.ts → focus.d-C0Tr0oVJ.d.ts} +109 -348
- package/dist/{focus.d-az9cqUz3.d.cts → focus.d-jQWp0hdK.d.cts} +109 -348
- package/dist/health-plan/index.cjs +165 -151
- package/dist/health-plan/index.d.cts +53 -11
- package/dist/health-plan/index.d.ts +53 -11
- package/dist/health-plan/index.js +169 -155
- package/dist/{idempotency.d-D461_DPD.d.cts → idempotency.d-DXb1BN2A.d.ts} +151 -6
- package/dist/{idempotency.d-WpXx9zQo.d.ts → idempotency.d-HF6fyRt2.d.cts} +151 -6
- package/dist/{identity.d-DzTijonw.d.ts → identity.d-BePPZ7Uv.d.ts} +1 -1
- package/dist/{identity.d-60LeJt_s.d.cts → identity.d-CJfnWOdH.d.cts} +1 -1
- package/dist/index.cjs +46 -44
- package/dist/index.d.cts +19 -18
- package/dist/index.d.ts +19 -18
- package/dist/index.js +46 -44
- package/dist/introEvents.d-BkGDT_kG.d.cts +175 -0
- package/dist/introEvents.d-DHlMvmC7.d.ts +175 -0
- package/dist/introEvents.d-dS3fJCH1.d.cts +5 -0
- package/dist/introEvents.d-dS3fJCH1.d.ts +5 -0
- package/dist/{models.d-BnLm3VAA.d.cts → models.d-BSqvbTE1.d.cts} +8 -1
- package/dist/{models.d-BagXhafD.d.ts → models.d-DOwnr8fi.d.ts} +8 -1
- package/dist/notifications/index.d.cts +4 -4
- package/dist/notifications/index.d.ts +4 -4
- package/dist/{optInView.d-CEyHR6PK.d.cts → optInView.d-0iI5JoAf.d.cts} +119 -3
- package/dist/{optInView.d-acKpV8V2.d.ts → optInView.d-s-w4aGN3.d.ts} +119 -3
- package/dist/{parse.d-C8CXyS58.d.ts → parse.d-COt1qVA6.d.ts} +1 -1
- package/dist/{parse.d-tEzufgJX.d.cts → parse.d-EmsgOUMQ.d.cts} +1 -1
- package/dist/{pets.d-C_53_fzo.d.ts → pets.d-BFT_b53y.d.ts} +1 -1
- package/dist/{pets.d-NbJvP_kh.d.cts → pets.d-nNAVnw7f.d.cts} +1 -1
- package/dist/{petsRepository.d-lp1BHRqM.d.cts → petsRepository.d-B2TpRE7r.d.cts} +1 -1
- package/dist/{petsRepository.d-BuGHymNx.d.ts → petsRepository.d-RGwSZcYl.d.ts} +1 -1
- package/dist/planSignals.d-BDbp2e-k.d.cts +126 -0
- package/dist/planSignals.d-DSnxKoWe.d.ts +126 -0
- package/dist/{ports.d-COIyN624.d.ts → ports.d-D2n4HRUy.d.ts} +4 -4
- package/dist/{ports.d-CEROoqnA.d.cts → ports.d-DBA_gsq5.d.cts} +4 -4
- package/dist/{presentation.d-DMbdad7G.d.cts → presentation.d-vy8kTGfR.d.cts} +6 -0
- package/dist/{presentation.d-DMbdad7G.d.ts → presentation.d-vy8kTGfR.d.ts} +6 -0
- package/dist/quickPrompts.d-NM_81Jc1.d.cts +19 -0
- package/dist/quickPrompts.d-NM_81Jc1.d.ts +19 -0
- package/dist/records/depth/index.d.cts +13 -9
- package/dist/records/depth/index.d.ts +13 -9
- package/dist/records/index.cjs +252 -138
- package/dist/records/index.d.cts +88 -23
- package/dist/records/index.d.ts +88 -23
- package/dist/records/index.js +253 -139
- package/dist/{requestFunnel.d-CXUMPw1K.d.ts → requestFunnel.d-D9edIEjZ.d.ts} +2 -2
- package/dist/{requestFunnel.d-DWQQpjFR.d.cts → requestFunnel.d-RZex94XX.d.cts} +2 -2
- package/dist/{resolve.d-jI8FmBj3.d.cts → resolve.d-CoQWUy1Y.d.cts} +1 -1
- package/dist/{resolve.d-jI8FmBj3.d.ts → resolve.d-CoQWUy1Y.d.ts} +1 -1
- package/dist/{runtimeTypes.d-4yFNNuYR.d.ts → runtimeTypes.d-BYq38b17.d.ts} +6 -6
- package/dist/{runtimeTypes.d-D6N_fhxx.d.cts → runtimeTypes.d-LkwZaF7z.d.cts} +6 -6
- package/dist/{useRecordsDepth.d-DFcCfiXm.d.ts → screenProps.d-BVzRzowC.d.ts} +5 -91
- package/dist/{useRecordsDepth.d-sAq2Qkhr.d.cts → screenProps.d-CQ0qZJkr.d.cts} +5 -91
- 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/{sheetSeam.d-Cviqk89n.d.ts → sheetSeam.d-B09jf4YC.d.ts} +8 -4
- package/dist/{sheetSeam.d-DCS3LW8g.d.cts → sheetSeam.d-BBuEIVsa.d.cts} +8 -4
- package/dist/shop/index.cjs +224 -58
- package/dist/shop/index.d.cts +23 -5
- package/dist/shop/index.d.ts +23 -5
- package/dist/shop/index.js +225 -59
- package/dist/tabs/index.cjs +195 -0
- package/dist/tabs/index.d.cts +174 -0
- package/dist/tabs/index.d.ts +174 -0
- package/dist/tabs/index.js +195 -0
- package/dist/tabsModel.d-BfIQg6yS.d.cts +31 -0
- package/dist/tabsModel.d-BfIQg6yS.d.ts +31 -0
- package/dist/televet/booking/index.d.cts +6 -6
- package/dist/televet/booking/index.d.ts +6 -6
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/rn/index.cjs +1 -1
- package/dist/testing/rn/index.d.cts +11 -11
- package/dist/testing/rn/index.d.ts +11 -11
- package/dist/testing/rn/index.js +1 -1
- package/dist/testing/web/index.d.cts +12 -12
- package/dist/testing/web/index.d.ts +12 -12
- package/dist/texting/index.cjs +40 -5
- package/dist/texting/index.d.cts +40 -7
- package/dist/texting/index.d.ts +40 -7
- package/dist/texting/index.js +40 -5
- package/dist/threadOptions.d-9r4Csa7k.d.cts +458 -0
- package/dist/threadOptions.d-B6GA09aM.d.ts +458 -0
- package/dist/{timelineRows.d-CU5GvvLk.d.ts → timelineRows.d-Bes8ip2v.d.ts} +1 -1
- package/dist/{timelineRows.d-BNxgzYRW.d.cts → timelineRows.d-BvM2A7_G.d.cts} +1 -1
- package/dist/{typeStyle.d-C1HBRAI3.d.ts → typeStyle.d-Co5KF0up.d.ts} +1 -1
- package/dist/{typeStyle.d-Bl8pzbBy.d.cts → typeStyle.d-xIZj02Ru.d.cts} +1 -1
- package/dist/useIntroSeen.d-CTWFUthO.d.cts +35 -0
- package/dist/useIntroSeen.d-CTWFUthO.d.ts +35 -0
- package/dist/usePresentation.d-BGz32Vlm.d.ts +285 -0
- package/dist/usePresentation.d-DYTF_ZGf.d.cts +285 -0
- package/dist/{useRecords.d-Cb-36SF5.d.cts → useRecords.d-BYNX01El.d.cts} +2 -2
- package/dist/{useRecords.d-aQTzQZoV.d.ts → useRecords.d-DWk61a4c.d.ts} +2 -2
- package/dist/useRecordsDepth.d--LLA_4ga.d.cts +32 -0
- package/dist/useRecordsDepth.d-BQRL0Hez.d.ts +32 -0
- package/dist/{view.d-Dps5C8-s.d.cts → view.d-0yBjLTV3.d.cts} +6 -4
- package/dist/{view.d-C-SNpDJX.d.ts → view.d-DqbCADFa.d.ts} +6 -4
- 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 +50 -43
- package/dist/web/health-plan/index.d.cts +46 -192
- package/dist/web/health-plan/index.d.ts +46 -192
- package/dist/web/health-plan/index.js +65 -58
- package/dist/web/index.cjs +61 -45
- package/dist/web/index.d.cts +165 -25
- package/dist/web/index.d.ts +165 -25
- package/dist/web/index.js +62 -46
- package/dist/web/intro/index.cjs +167 -0
- package/dist/web/intro/index.d.cts +79 -0
- package/dist/web/intro/index.d.ts +79 -0
- package/dist/web/intro/index.js +167 -0
- 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 +13 -9
- package/dist/web/records/depth/index.d.ts +13 -9
- package/dist/web/records/index.cjs +7 -7
- package/dist/web/records/index.d.cts +21 -82
- package/dist/web/records/index.d.ts +21 -82
- package/dist/web/records/index.js +7 -7
- package/dist/web/records-sheet/index.cjs +181 -127
- package/dist/web/records-sheet/index.d.cts +18 -16
- package/dist/web/records-sheet/index.d.ts +18 -16
- package/dist/web/records-sheet/index.js +181 -127
- package/dist/web/shop/index.cjs +191 -76
- package/dist/web/shop/index.d.cts +21 -4
- package/dist/web/shop/index.d.ts +21 -4
- package/dist/web/shop/index.js +191 -76
- 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.cjs +36 -5
- package/dist/web/texting/index.d.cts +40 -7
- package/dist/web/texting/index.d.ts +40 -7
- package/dist/web/texting/index.js +36 -5
- package/package.json +35 -4
- package/tabs/package.json +8 -0
- package/web/intro/native-blocked.cjs +12 -0
- package/web/intro/package.json +8 -0
- package/dist/threadOptions.d-B1pTMmDF.d.cts +0 -260
- package/dist/threadOptions.d-B1pTMmDF.d.ts +0 -260
- package/dist/usePresentation.d-D6qsFzBz.d.cts +0 -9
- package/dist/usePresentation.d-DuGQe_Do.d.ts +0 -9
package/dist/web/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{createContext,useContext,createElement,useSyncExternalStore,useMemo,useState,useRef,useEffect,useCallback,useReducer,
|
|
2
|
+
import{createContext,useContext,createElement,useSyncExternalStore,useMemo,useState,useRef,useEffect,useCallback,useLayoutEffect,Suspense,useReducer,useId,Fragment as Fragment$1,lazy,Component}from"react";import{z}from"zod";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import{createPortal}from"react-dom";function ok(value,warning){/* @__PURE__ */
|
|
3
3
|
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
4
4
|
return Object.freeze({ok:false,error:error})}function isOk(r){return r.ok}function isErr(r){return!r.ok}var EverfurThrownError=class _EverfurThrownError extends Error{constructor(error){super(`${error.code}: ${error.displayMessage}`),this.name="EverfurThrownError",this.error=error,this.code=error.code,this.category=error.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(r){if(r.ok)return r.value;throw new EverfurThrownError(r.error)}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var noopTelemetry=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
5
5
|
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
@@ -102,11 +102,11 @@ return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversati
|
|
|
102
102
|
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__ */
|
|
103
103
|
return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
|
|
104
104
|
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__ */
|
|
105
|
-
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.13.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
105
|
+
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.14.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
106
106
|
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__ */
|
|
107
107
|
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__ */
|
|
108
|
-
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(
|
|
109
|
-
return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var UNARY_TIMEOUT_MS=3e4,REQUEST_ID_HEADER="x-request-id";async function*fetchByteSource(body){if(!body)return;let reader=body.getReader();try{for(;;){let{done:done,value:value}=await reader.read();if(done)break;value&&value.length>0&&(yield value)}}finally{await(reader.cancel?.())}}function eventSourceByteSource(es){let enc=new TextEncoder,queue=createByteQueue(),cleaned=false,onMessage=ev=>{let block="";ev.lastEventId&&(block+=`id: ${ev.lastEventId}\n`);let data=ev.data??"";for(let line of data.split(`\n`))block+=`data: ${line}\n`;block+=`\n`,queue.push(enc.encode(block))},onDone=()=>{cleanup(),queue.end()},onError=ev=>{let status=typeof ev.xhrStatus=="number"?ev.xhrStatus:0;if(status>=400){let wireCode=statusToWireCode(status),retryable=isAutoRetryable(fromWire(wireCode));queue.push(enc.encode(`data: ${JSON.stringify({type:"error",code:wireCode,retryable:retryable})}\n\n`))}cleanup(),queue.end()};es.addEventListener("message",onMessage),es.addEventListener("done",onDone),es.addEventListener("error",onError);function cleanup(){if(!cleaned){cleaned=true,es.removeEventListener("message",onMessage),es.removeEventListener("done",onDone),es.removeEventListener("error",onError);try{es.close()}catch{}}}return sourceWithCleanup(queue.source,cleanup)}async function*sourceWithCleanup(source,cleanup){try{yield*source}finally{cleanup()}}function createByteQueue(){let buffer=[],done=false,wake=null,signal=()=>{if(wake){let fn=wake;wake=null,fn()}};async function*gen(){for(;;){let next=buffer.shift();if(next!==void 0){yield next;continue}if(done)return;await new Promise(resolve=>{wake=resolve})}}return{source:gen(),push:u=>{buffer.push(u),signal()},end:()=>{done=true,signal()}}}async function requestJson(req,deps){let fetchImpl=deps.fetchImpl??getGlobalFetch(),url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"application/json",req.body!==void 0&&req.multipart===void 0),deadline2=timeoutSignal(UNARY_TIMEOUT_MS),signal=mergeAbortSignals(deadline2.signal,req.signal),res;try{res=await fetchImpl(url,buildInit({...req,signal:signal},headers))}catch(cause){return err(networkError(cause))}finally{deadline2.cancel()}let bodyJson=await safeJson(res);return res.ok?ok(bodyJson):err(errorFromResponse(res.status,withRetryAfter(res,bodyJson),requestIdOf(res)))}function createHttpTransport(deps){return{request:req=>requestJson(req,deps),stream:(req,signal)=>streamFrames(withSignal(req,signal),deps)}}async function*streamFrames(req,deps){let url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"text/event-stream",req.body!==void 0&&req.multipart===void 0);if(deps.eventSourceFactory){let es=deps.eventSourceFactory(url,buildEventSourceInit(req,headers));yield*parseSse(eventSourceByteSource(es),()=>eventSourceRequestId(es));return}let fetchImpl=deps.fetchImpl??getGlobalFetch(),res;try{res=await fetchImpl(url,buildInit(req,headers))}catch(cause){yield syntheticErrorFrame("",true,describeCause(cause));return}let requestId=requestIdOf(res);if(!res.ok){let body=await safeJson(res),wireCode=extractWireCode(body)??statusToWireCode(res.status),retryable=extractRetryable(body)||isAutoRetryable(fromWire(wireCode));yield syntheticErrorFrame(wireCode,retryable,extractWireMessage(body),requestId);return}if(res.body){yield*parseSse(fetchByteSource(res.body),requestId);return}yield*parseSse(fetchByteSource(null),requestId)}function buildEventSourceInit(req,headers){return{method:req.method,headers:headers,pollingInterval:0,...req.body!==void 0?{body:JSON.stringify(req.body)}:{}}}function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function eventSourceRequestId(es){if(typeof es.getResponseHeader!="function")return null;let value;try{value=es.getResponseHeader(REQUEST_ID_HEADER)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function statusToWireCode(status){return status===401?"AUTH_EXPIRED":status===403?"ACCESS_DENIED":status===404?"NOT_FOUND":status===409?"IDEMPOTENCY_CONFLICT":status===421?"MISDIRECTED_REQUEST":status===429?"RATE_LIMITED":status===400||status===422?"INVALID_REQUEST":status===503||status>=500?"INTERNAL_ERROR":""}function syntheticErrorFrame(code,retryable,wireMessage,serverRequestId=null){return errorFrame({code:code,retryable:retryable,wireMessage:wireMessage,synthesized:true,lastEventId:null,serverRequestId:serverRequestId})}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function buildUrl(base2,path,query){let rel=path.startsWith("/")?path:`/${path}`,url=`${base2}${rel}`;if(query){let qs=Object.entries(query).filter(entry=>entry[1]!==void 0).map(([k,v])=>`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");qs&&(url+=`?${qs}`)}return url}function mergeHeaders(config,reqHeaders,accept,hasJsonBody){let headers={...buildBaseHeaders(config),accept:accept};return hasJsonBody&&(headers["content-type"]="application/json"),reqHeaders&&Object.assign(headers,reqHeaders),headers}function buildInit(req,headers){let init={method:req.method,headers:headers};return req.multipart!==void 0?init.body=req.multipart:req.body!==void 0&&(init.body=JSON.stringify(req.body)),req.signal&&(init.signal=req.signal),init}function withSignal(req,signal){return req.signal?req:{...req,signal:signal}}function timeoutSignal(ms){let ctrl=new AbortController,handle=setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>clearTimeout(handle)}}function mergeAbortSignals(deadline2,caller){if(!caller)return deadline2;let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return deadline2.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),ctrl.signal}async function safeJson(res){try{return await res.json()}catch{return null}}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?foldDailyQuotaWireCode(code,body):null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base2=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline2=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline2.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline2.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
108
|
+
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__ */
|
|
109
|
+
return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host2=hostname.toLowerCase();return host2==="localhost"||host2==="127.0.0.1"||host2==="[::1]"||host2==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var UNARY_TIMEOUT_MS=3e4,REQUEST_ID_HEADER="x-request-id";async function*fetchByteSource(body){if(!body)return;let reader=body.getReader();try{for(;;){let{done:done,value:value}=await reader.read();if(done)break;value&&value.length>0&&(yield value)}}finally{await(reader.cancel?.())}}function eventSourceByteSource(es){let enc=new TextEncoder,queue=createByteQueue(),cleaned=false,onMessage=ev=>{let block="";ev.lastEventId&&(block+=`id: ${ev.lastEventId}\n`);let data=ev.data??"";for(let line of data.split(`\n`))block+=`data: ${line}\n`;block+=`\n`,queue.push(enc.encode(block))},onDone=()=>{cleanup(),queue.end()},onError=ev=>{let status=typeof ev.xhrStatus=="number"?ev.xhrStatus:0;if(status>=400){let wireCode=statusToWireCode(status),retryable=isAutoRetryable(fromWire(wireCode));queue.push(enc.encode(`data: ${JSON.stringify({type:"error",code:wireCode,retryable:retryable})}\n\n`))}cleanup(),queue.end()};es.addEventListener("message",onMessage),es.addEventListener("done",onDone),es.addEventListener("error",onError);function cleanup(){if(!cleaned){cleaned=true,es.removeEventListener("message",onMessage),es.removeEventListener("done",onDone),es.removeEventListener("error",onError);try{es.close()}catch{}}}return sourceWithCleanup(queue.source,cleanup)}async function*sourceWithCleanup(source,cleanup){try{yield*source}finally{cleanup()}}function createByteQueue(){let buffer=[],done=false,wake=null,signal=()=>{if(wake){let fn=wake;wake=null,fn()}};async function*gen(){for(;;){let next=buffer.shift();if(next!==void 0){yield next;continue}if(done)return;await new Promise(resolve=>{wake=resolve})}}return{source:gen(),push:u=>{buffer.push(u),signal()},end:()=>{done=true,signal()}}}async function requestJson(req,deps){let fetchImpl=deps.fetchImpl??getGlobalFetch(),url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"application/json",req.body!==void 0&&req.multipart===void 0),deadline2=timeoutSignal(UNARY_TIMEOUT_MS),signal=mergeAbortSignals(deadline2.signal,req.signal),res;try{res=await fetchImpl(url,buildInit({...req,signal:signal},headers))}catch(cause){return err(networkError(cause))}finally{deadline2.cancel()}let bodyJson=await safeJson(res);return res.ok?ok(bodyJson):err(errorFromResponse(res.status,withRetryAfter(res,bodyJson),requestIdOf(res)))}function createHttpTransport(deps){return{request:req=>requestJson(req,deps),stream:(req,signal)=>streamFrames(withSignal(req,signal),deps)}}async function*streamFrames(req,deps){let url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"text/event-stream",req.body!==void 0&&req.multipart===void 0);if(deps.eventSourceFactory){let es=deps.eventSourceFactory(url,buildEventSourceInit(req,headers));yield*parseSse(eventSourceByteSource(es),()=>eventSourceRequestId(es));return}let fetchImpl=deps.fetchImpl??getGlobalFetch(),res;try{res=await fetchImpl(url,buildInit(req,headers))}catch(cause){yield syntheticErrorFrame("",true,describeCause(cause));return}let requestId=requestIdOf(res);if(!res.ok){let body=await safeJson(res),wireCode=extractWireCode(body)??statusToWireCode(res.status),retryable=extractRetryable(body)||isAutoRetryable(fromWire(wireCode));yield syntheticErrorFrame(wireCode,retryable,extractWireMessage(body),requestId);return}if(res.body){yield*parseSse(fetchByteSource(res.body),requestId);return}yield*parseSse(fetchByteSource(null),requestId)}function buildEventSourceInit(req,headers){return{method:req.method,headers:headers,pollingInterval:0,...req.body!==void 0?{body:JSON.stringify(req.body)}:{}}}function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function eventSourceRequestId(es){if(typeof es.getResponseHeader!="function")return null;let value;try{value=es.getResponseHeader(REQUEST_ID_HEADER)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function statusToWireCode(status){return status===401?"AUTH_EXPIRED":status===403?"ACCESS_DENIED":status===404?"NOT_FOUND":status===409?"IDEMPOTENCY_CONFLICT":status===421?"MISDIRECTED_REQUEST":status===429?"RATE_LIMITED":status===400||status===422?"INVALID_REQUEST":status===503||status>=500?"INTERNAL_ERROR":""}function syntheticErrorFrame(code,retryable,wireMessage,serverRequestId=null){return errorFrame({code:code,retryable:retryable,wireMessage:wireMessage,synthesized:true,lastEventId:null,serverRequestId:serverRequestId})}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function buildUrl(base2,path,query){let rel=path.startsWith("/")?path:`/${path}`,url=`${base2}${rel}`;if(query){let qs=Object.entries(query).filter(entry=>entry[1]!==void 0).map(([k,v])=>`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");qs&&(url+=`?${qs}`)}return url}function mergeHeaders(config,reqHeaders,accept,hasJsonBody){let headers={...buildBaseHeaders(config),accept:accept};return hasJsonBody&&(headers["content-type"]="application/json"),reqHeaders&&Object.assign(headers,reqHeaders),headers}function buildInit(req,headers){let init={method:req.method,headers:headers};return req.multipart!==void 0?init.body=req.multipart:req.body!==void 0&&(init.body=JSON.stringify(req.body)),req.signal&&(init.signal=req.signal),init}function withSignal(req,signal){return req.signal?req:{...req,signal:signal}}function timeoutSignal(ms){let ctrl=new AbortController,handle=setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>clearTimeout(handle)}}function mergeAbortSignals(deadline2,caller){if(!caller)return deadline2;let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return deadline2.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),ctrl.signal}async function safeJson(res){try{return await res.json()}catch{return null}}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?foldDailyQuotaWireCode(code,body):null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base2=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline2=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline2.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline2.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
110
110
|
/* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null})}}/* @__PURE__ */
|
|
111
111
|
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline2,caller){let noop2=()=>{};if(!caller)return{signal:deadline2,dispose:noop2};let ctrl=new AbortController;if(deadline2.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop2};let onAbort=()=>ctrl.abort();return deadline2.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline2.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var CHECKIN_ANSWERS=/* @__PURE__ */Object.freeze(["better","same","worse"]),CASE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function invalid(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function malformed(){return err(makeEverfurError("internalError",{retryable:false}))}function petPath(petRef2){return typeof petRef2!="string"||petRef2.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):hasLoneSurrogate(petRef2)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(petRef2)}/cases`}var str=v=>typeof v=="string"?v:null,count=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function caseFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,caseId=str(o.case_id),status=str(o.status);if(caseId===null||status===null)return null;let last=str(o.last_response);/* @__PURE__ */
|
|
112
112
|
return Object.freeze({caseId:caseId,status:status,bodyLocation:str(o.body_location),lastResponse:last!==null&&CHECKIN_ANSWERS.includes(last)?last:null,checkInDueAt:str(o.check_in_due_at),openedAt:str(o.opened_at),resolvedAt:str(o.resolved_at),resolutionText:str(o.resolution_text),checkinAskCount:count(o.checkin_ask_count),checkinAnswerCount:count(o.checkin_answer_count)})}function createCasesRepositoryOver(funnel){return{async list(petRef2,opts){let path=petPath(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("cases.list",{method:"GET",path:path,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let rows=typeof res.value=="object"&&res.value!==null?res.value.cases:null;if(!Array.isArray(rows))return malformed();let cases=rows.map(caseFromWire);return cases.every(c=>c!==null)?ok(/* @__PURE__ */Object.freeze(cases)):malformed()},async checkin(petRef2,caseId,answer,opts){let path=petPath(petRef2);if(typeof path!="string")return err(path);if(typeof caseId!="string"||!CASE_ID_PATTERN.test(caseId))return invalid("case_id must be a UUID");if(!CHECKIN_ANSWERS.includes(answer))return invalid("response must be one of better, same, worse");let res=await funnel.send("cases.checkin",{method:"POST",path:`${path}/${caseId}/checkin`,body:{response:answer},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let o=typeof res.value=="object"&&res.value!==null?res.value:{},watchCase=caseFromWire(o.case);return watchCase===null?malformed():ok(/* @__PURE__ */Object.freeze({case:watchCase,ctaDeepLink:str(o.cta_deep_link)}))}}}var unavailableUpload=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var defaultTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function delayAbortable2(ms,signal,timers){return new Promise(resolve=>{if(signal.aborted){resolve();return}let holder={handle:void 0},done=()=>{timers.clearTimeout(holder.handle),signal.removeEventListener("abort",done),resolve()};holder.handle=timers.setTimeout(done,ms),signal.addEventListener("abort",done,{once:true})})}function mergeSignals2(a,b){if(!b)return a;let ctrl=new AbortController;if(a.aborted||b.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return a.addEventListener("abort",onAbort,{once:true}),b.addEventListener("abort",onAbort,{once:true}),ctrl.signal}var MediaStore=class{constructor(initial){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...initial})}subscribe(listener){return this.listeners.add(listener),()=>{this.listeners.delete(listener)}}getSnapshot(){return this.snapshot}patch(partial){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...partial});for(let listener of this.listeners)listener()}beginOperation(external){this.inFlight?.abort();let ctrl=new AbortController;this.inFlight=ctrl;let epoch=this.epoch;return{signal:external?mergeSignals2(ctrl.signal,external):ctrl.signal,epoch:epoch,settle:()=>{this.inFlight===ctrl&&(this.inFlight=null)}}}alive(epoch){return epoch===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear()}};function makeUser(id,text3,createdAt){/* @__PURE__ */
|
|
@@ -117,24 +117,24 @@ return Object.freeze({status:s.status,messages:/* @__PURE__ */Object.freeze([...
|
|
|
117
117
|
return Object.freeze(out)}function flattenPrompts(categories){let seen=/* @__PURE__ */new Set,out=[];for(let category of categories)for(let prompt of category.prompts){let trimmed=prompt.trim();trimmed.length===0||seen.has(trimmed)||(seen.add(trimmed),out.push(trimmed))}return out}function isPlainObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asStr(v){return typeof v=="string"?v:null}function asPromptTextList(v){if(!Array.isArray(v))return[];let out=[];for(let entry of v)if(typeof entry=="string")out.push(entry);else if(isPlainObject2(entry)){let text3=asStr(entry.text)??asStr(entry.prompt)??asStr(entry.title);text3!==null&&out.push(text3)}return out}function defaultIdFactory(){let counter=0;return()=>`m-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function defaultIdempotencyFactory(){let counter=0;return()=>`chat-send-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}var defaultTimers2={setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()};async function*withWatchdog(source,budget,signal,timers){let it=source[Symbol.asyncIterator](),overall=deadline(budget.overallMs,timers),idle=deadline(budget.idleMs,timers),abort=abortPromise(signal);try{for(;;){if(signal.aborted)return;let nextTagged=it.next().then(value=>({tag:"next",value:value}),()=>({tag:"streamError"})),outcome=await Promise.race([nextTagged,idle.promise.then(()=>({tag:"idle"})),overall.promise.then(()=>({tag:"overall"})),abort.then(()=>({tag:"abort"}))]);if(outcome.tag==="abort")return;if(outcome.tag==="streamError"){if(signal.aborted)return;yield synthStreamErrorFrame();return}if(outcome.tag==="idle"||outcome.tag==="overall"){yield synthTimeoutFrame();return}let result=outcome.value;if(result.done||(idle.reset(budget.idleMs),yield result.value,result.value.terminal))return}}finally{idle.cancel(),overall.cancel(),Promise.resolve(it.return?.(void 0)).catch(()=>{})}}function synthTimeoutFrame(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function synthStreamErrorFrame(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function deadline(ms,timers){let resolveFn=()=>{},promise=new Promise(resolve=>{resolveFn=resolve}),handle=timers.setTimeout(()=>resolveFn(),ms);return{promise:promise,reset(next){timers.clearTimeout(handle),handle=timers.setTimeout(()=>resolveFn(),next)},cancel(){timers.clearTimeout(handle)}}}function abortPromise(signal){return new Promise(resolve=>{if(signal.aborted){resolve();return}signal.addEventListener("abort",()=>resolve(),{once:true})})}var MAX_USER_REF_LEN=128,MAX_PET_REF_LEN=128,CONTROL_CHAR=/[\u0000-\u001F\u007F]/,UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_PET_REF_LEN)throw new EverfurConfigError("invalid-argument",`petRef must be 1..${MAX_PET_REF_LEN} characters`);if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","petRef must be printable (no control characters)");return v}function userRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_USER_REF_LEN)throw new EverfurConfigError("invalid-argument",`userRef must be 1..${MAX_USER_REF_LEN} characters`);if(v.includes("@"))throw new EverfurConfigError("invalid-argument","userRef must not contain '@'");if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","userRef must be printable (no control characters)");return v}function conversationId(raw){if(!UUID_RE.test(raw))throw new EverfurConfigError("invalid-argument","conversationId must be a UUID");return raw}var CHECKIN_KIND="checkin",DUE_DAY_PATTERN=/^\d{4}-\d{2}-\d{2}$/,CHECKIN_ANSWERABLE_STATUS="watching";function isCheckinSettled(checkin){return checkin.status!=null&&checkin.status!==CHECKIN_ANSWERABLE_STATUS}function isLiveAskAnswered(counts){let{askCount:askCount,answerCount:answerCount}=counts;return typeof askCount!="number"||!Number.isFinite(askCount)||typeof answerCount!="number"||!Number.isFinite(answerCount)||askCount<=0?true:answerCount>=askCount}function parseCheckinOrigin(ref){if(typeof ref!="string")return null;let parts=ref.split(":");if(parts.length!==3)return null;let[kind,caseId,dueDay]=parts;return kind!==CHECKIN_KIND||caseId===void 0||dueDay===void 0||!CASE_ID_PATTERN.test(caseId)||!DUE_DAY_PATTERN.test(dueDay)?null:{caseId:caseId,dueDay:dueDay}}function parseCheckinOriginRef(ref){return parseCheckinOrigin(ref)?.caseId??null}function historyQuery(opts,max){if(opts?.limit!==void 0&&(!Number.isInteger(opts.limit)||opts.limit<1||opts.limit>max))return err(makeEverfurError("validationFailed"));let query=[];for(let[key,value]of[["cursor",opts?.cursor],["pet_ref",opts?.petRef]])if(value!==void 0){if(typeof value!="string"||value.length===0||hasLoneSurrogate(value))return err(makeEverfurError("validationFailed"));query.push(`${key}=${encodeURIComponent(value)}`)}return opts?.limit!==void 0&&query.push(`limit=${opts.limit}`),ok(query.length?`?${query.join("&")}`:"")}function validConversationId(id){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)}function object(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null}function cursor(value){return value==null||typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}function mapConversationPage(value){let page=object(value);if(!page||!Array.isArray(page.conversations)||!cursor(page.next_cursor))return malformed2();let conversations=[];for(let raw of page.conversations){let row=object(raw);if(!row||typeof row.conversation_id!="string"||!validConversationId(row.conversation_id)||!(row.title==null||typeof row.title=="string")||typeof row.created_at!="string"||typeof row.updated_at!="string")return malformed2();let unread=row.unread_message_count;if(!(unread==null||Number.isInteger(unread)&&unread>=0))return malformed2();let preview=typeof row.preview=="string"?row.preview.replace(/\s+/g," ").trim().slice(0,140):"";conversations.push(/* @__PURE__ */Object.freeze({id:row.conversation_id,title:row.title??null,createdAt:row.created_at,updatedAt:row.updated_at,unreadCount:unread??null,...preview.length>0?{preview:preview}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(conversations),nextCursor:page.next_cursor??null}))}function mapMessagePage(value){let page=object(value);if(!page||!Array.isArray(page.messages)||!cursor(page.next_cursor))return malformed2();let messages=[],seen=/* @__PURE__ */new Set;for(let raw of page.messages){let row=object(raw);if(!row||typeof row.message_id!="string"||!validConversationId(row.message_id)||typeof row.role!="string"||typeof row.content!="string"||typeof row.created_at!="string")return malformed2();if(row.role!=="user"&&row.role!=="assistant"&&row.role!=="vet"||seen.has(row.message_id))continue;if(seen.add(row.message_id),row.role==="vet"){messages.push(vetMessage(row,row.message_id,row.content,row.created_at));continue}let origin=typeof row.proactive_origin_ref=="string"?row.proactive_origin_ref:null,caseId=row.role==="assistant"?parseCheckinOriginRef(origin):null;messages.push(/* @__PURE__ */Object.freeze({id:row.message_id,role:row.role,text:row.content,createdAt:row.created_at,...row.role==="assistant"?{responseId:row.message_id}:{},...row.urgency_level!==void 0?{urgencyLevel:normalizeUrgency(row.urgency_level)}:{},...Array.isArray(row.citations)?{citations:historyCitations(row.citations)}:{},...origin!==null?{proactiveOriginRef:origin}:{},...caseId!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:caseId,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(messages),nextCursor:page.next_cursor??null}))}function vetMessage(row,id,text3,createdAt){let sender=object(row.sender),displayName=trimmedText(sender?.display_name)??trimmedText(row.sender_display_name),specialty=trimmedText(sender?.specialty);/* @__PURE__ */
|
|
118
118
|
return Object.freeze({id:id,role:"vet",text:text3,createdAt:createdAt,sender:/* @__PURE__ */Object.freeze({displayName:displayName,specialty:specialty})})}function trimmedText(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length>0&&!hasLoneSurrogate(trimmed)?trimmed:null}function normalizeUrgency(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}function historyCitations(values){let keys=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
|
|
119
119
|
return Object.freeze(values.flatMap(value=>{let row=object(value);if(!row||typeof row.source_name!="string"||typeof row.authority_tier!="string")return[];let citation={};for(let key of keys){let item=row[key];(typeof item=="string"||item===null)&&(citation[key]=item)}return[/* @__PURE__ */Object.freeze(citation)]}))}var CHAT_FEEDBACK_TYPES=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),FEEDBACK_NOTES_MAX_CHARS=4e3;var MESSAGE_MAX_CHARS=4e3;function validateImageKeys(keys){return keys===void 0?null:!Array.isArray(keys)||keys.length>5?{reason:"too_many_images",error:makeError("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:keys.some(key=>typeof key!="string"||key.trim().length===0)?{reason:"bad_image_key",error:makeError("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function validateMessageText(text3){let raw=typeof text3=="string"?text3:"";if(raw.trim().length===0)return{reason:"empty",error:makeError("validationFailed",false,"message is empty or whitespace-only")};let codePoints=[...raw].length;return codePoints>MESSAGE_MAX_CHARS?{reason:"too_long",error:makeError("validationFailed",false,`message is ${codePoints} characters; the server accepts at most ${MESSAGE_MAX_CHARS}`)}:null}function urgencyTier(value){return value==="emergency"||value==="schedule_soon"||value==="home_care"?value:null}async function*singleFrameStream(frame){yield frame}async function*emptyStream(){}var DEFAULT_IDLE_MS=6e4,DEFAULT_OVERALL_MS=18e4,DELTA_FLUSH_MS=24,DELTA_FLUSH_CHARS=512,SEND_IS_SERVER_DEDUPED=false;function createChatController(deps){return new ChatControllerImpl(deps)}var ChatControllerImpl=class extends MediaStore{constructor(deps){super(freezeSnapshot({status:"idle",messages:[],conversationId:deps.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingDelta="";this.flushHandle=null;this.auth=deps.auth,this.funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),this.petRef=deps.petRef??null,this.cases=createCasesRepositoryOver(this.funnel),this.telemetry=deps.telemetry??noopTelemetry,this.onConversationStarted=deps.onConversationStarted,this.errorPolicy=deps.errorPolicy??defaultErrorPolicy,this.timers=deps.timers??defaultTimers2,this.rng=deps.rng??Math.random,this.newId=deps.newId??defaultIdFactory(),this.makeIdempotencyKey=deps.makeIdempotencyKey??defaultIdempotencyFactory(),this.budget={idleMs:deps.budget?.idleMs??DEFAULT_IDLE_MS,overallMs:deps.budget?.overallMs??DEFAULT_OVERALL_MS}}patch(partial){if(partial.messages!==void 0){let frozen=/* @__PURE__ */Object.freeze([...partial.messages]);super.patch({...partial,messages:frozen});return}super.patch(partial)}send(text3,opts,handlers){let options=opts??{};if(this.disposed||this.snapshot.isBootstrapping){let error=makeError(this.disposed?"accessDenied":"internalError",!this.disposed);return handlers?(handlers.onError(error),()=>{}):singleFrameStream(synthErrorFrame(error))}let invalid5=validateMessageText(text3)??validateImageKeys(options.imageS3Keys);if(invalid5!==null)return this.telemetry.track("chat.send.rejected",{reason:invalid5.reason}),this.patch({status:"error",isStreaming:false,error:invalid5.error}),handlers?(handlers.onError(invalid5.error),()=>{}):singleFrameStream(synthErrorFrame(invalid5.error));if(handlers)return this.driveWithHandlers(text3,options,handlers);let turn=this.beginTurn(text3,options);return this.runTurn(turn,options.signal)}askEverfur(prompt,opts){if(this.disposed)return singleFrameStream(synthErrorFrame(makeError("accessDenied",false)));let invalid5=validateMessageText(prompt);return invalid5!==null?(this.telemetry.track("chat.send.rejected",{reason:invalid5.reason}),singleFrameStream(synthErrorFrame(invalid5.error))):(this.resetThread(),this.send(prompt,opts??{}))}retryLast(){let turn=this.lastTurn;if(turn===null){let id=this.snapshot.conversationId;return id!==null&&this.snapshot.status==="error"?this.retryHistory(id):emptyStream()}turn.assistantMessageId=null,turn.sawDelta=false,turn.conversationIdOverride=null,this.discardPendingDelta();let messages=this.snapshot.messages.some(m=>m.id===turn.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,makeUser(turn.userMessageId,turn.text,this.stamp())];return this.patch({error:null,stopped:false,messages:messages}),this.runTurn(turn,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let stopped=this.snapshot.messages.some(m=>m.role==="user"&&m.pending===true),messages=stopped?this.snapshot.messages.map(m=>m.pending===true?stripPending(m):m):this.snapshot.messages;(this.snapshot.status==="streaming"||stopped)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...stopped?{messages:messages,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot()}resetThread(prompts=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=prompts,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:prompts,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false})}newConversation(){this.disposed||this.resetThread(this.scopePrompts)}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let teardown of this.handlerTeardowns)teardown();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(id){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==id&&this.patch({conversationId:id}))}adoptPrompts(categories){if(this.disposed)return;let prompts=/* @__PURE__ */Object.freeze(flattenPrompts(categories));this.bootstrapPrompts=prompts,this.scopePrompts=prompts,this.replyPrompts===null&&(prompts.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:prompts}))}async listConversations(opts){return this.listConversationsWith(opts)}async listConversationsWith(opts,funnelOpts){let query=historyQuery(opts,100);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${query.value}`},opts?.signal,funnelOpts);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let page=mapConversationPage(result.value);if(page.ok){for(let conversation of page.value.conversations)conversation.unreadCount!==null&&this.unreadByConversation.set(conversation.id,conversation.unreadCount);let active=this.snapshot.conversationId,count2=active===null?void 0:this.unreadByConversation.get(active);count2!==void 0&&count2!==this.snapshot.unreadCount&&this.patch({unreadCount:count2}),this.reflectUnreadDot()}return page}reflectUnreadDot(){let unread=false;for(let count2 of this.unreadByConversation.values())if(count2>0){unread=true;break}unread!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:unread})}async openCheckin(target){if(this.disposed)return err(makeError("accessDenied",false));let named=target?.conversationId??null;if(named!==null){let opened2=await this.resumeConversation(named);return opened2.ok?ok(named):err(opened2.error)}let petRef2=target?.petRef??this.petRef,listed=await this.listConversations({...petRef2===null?{}:{petRef:petRef2},limit:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];if(head===void 0)return ok(null);let opened=await this.resumeConversation(head.id);return opened.ok?ok(head.id):err(opened.error)}async markRead(opts){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null)return ok(void 0);let epoch=this.epoch,result=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${id}/read`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?(this.unreadByConversation.set(id,0),this.snapshot.conversationId===id&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),ok(void 0)):err(result.error)}async submitFeedback(responseId,feedbackType,notes,opts){if(this.disposed)return err(makeError("accessDenied",false));if(typeof responseId!="string"||responseId.trim().length===0||hasLoneSurrogate(responseId))return err(makeError("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!CHAT_FEEDBACK_TYPES.includes(feedbackType))return err(makeError("validationFailed",false,`feedback_type must be one of ${CHAT_FEEDBACK_TYPES.join(", ")}`));let note=typeof notes=="string"?notes.trim():"";if([...note].length>FEEDBACK_NOTES_MAX_CHARS)return err(makeError("validationFailed",false,`notes is over ${FEEDBACK_NOTES_MAX_CHARS} characters`));let body={feedback_type:feedbackType};note.length>0&&(body.notes=note);let epoch=this.epoch,result=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(responseId)}/feedback`,body:body},opts?.signal);if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let feedbackId=result.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof feedbackId=="string"?feedbackId:""}))}async answerCheckin(caseId,answer,opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??this.petRef;if(petRef2===null)return err(makeError("validationFailed",false,"a check-in needs the pet the case belongs to"));let epoch=this.epoch,result=await this.cases.checkin(petRef2,caseId,answer,opts?.signal?{signal:opts.signal}:{});if(!this.alive(epoch)||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return result;let openedAt=result.value.case.openedAt,checkin=/* @__PURE__ */Object.freeze({caseId:caseId,answer:answer,resolutionText:result.value.case.resolutionText,status:result.value.case.status??null,...openedAt!==null?{openedAt:openedAt}:{}}),carries=m=>m.checkin?.caseId===caseId;return this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,checkin:checkin}):m)}),result}async getMessages(id,opts){if(!validConversationId(id))return err(makeError("validationFailed",false));let query=historyQuery(opts,200);if(!query.ok)return query;let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let result=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${id}/messages${query.value}`},opts?.signal);return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):result.ok?mapMessagePage(result.value):result}async resumeConversation(id){if(this.disposed)return err(makeError("accessDenied",false));if(!validConversationId(id))return err(makeError("validationFailed",false));this.resetThread();let generation=this.historyGeneration;this.patch({conversationId:id,isBootstrapping:true,isLoadingHistory:true});let result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return this.patch({status:"error",error:result.error,isBootstrapping:false,isLoadingHistory:false}),result;let unread=this.unreadByConversation.get(id)??null;return this.patch({messages:result.value.messages,historyCursor:result.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:unread}),this.stampCheckinStatuses(generation),unread!==null&&unread>0&&this.markRead(),ok(void 0)}async stampCheckinStatuses(generation){let petRef2=this.petRef;if(petRef2===null||!this.snapshot.messages.some(m=>m.checkin!==void 0&&m.checkin.status===null))return;let result=await this.cases.list(petRef2);if(!result.ok||generation!==this.historyGeneration||this.disposed)return;let open=new Set(result.value.filter(row=>row.status===CHECKIN_ANSWERABLE_STATUS).map(row=>row.caseId)),byCase=new Map(result.value.map(row=>[row.caseId,row])),changed=false,messages=this.snapshot.messages.map(message=>{let checkin=message.checkin;if(checkin===void 0||checkin.status!==null)return message;changed=true;let row=byCase.get(checkin.caseId),openedAt=checkin.openedAt??row?.openedAt??null,watching=open.has(checkin.caseId),answerOnRecord=row!==void 0&&(!watching||isLiveAskAnswered({askCount:row.checkinAskCount,answerCount:row.checkinAnswerCount}))?row.lastResponse:null;/* @__PURE__ */
|
|
120
|
-
return Object.freeze({...message,checkin:/* @__PURE__ */Object.freeze({...checkin,status:watching?CHECKIN_ANSWERABLE_STATUS:row?.status??"resolved",answer:checkin.answer??answerOnRecord,resolutionText:checkin.resolutionText??row?.resolutionText??null,...openedAt!==null?{openedAt:openedAt}:{}})})});changed&&this.patch({messages:messages})}async refreshActiveThread(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null||this.snapshot.isStreaming)return ok(void 0);let generation=this.historyGeneration,result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let existing=new Set(this.snapshot.messages.map(message=>message.id)),arrived=result.value.messages.filter(message=>!existing.has(message.id));return arrived.length>0&&this.patch({messages:[...this.snapshot.messages,...arrived]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId,cursor2=this.snapshot.historyCursor;if(!id||!cursor2||this.snapshot.isLoadingHistory)return ok(void 0);let generation=this.historyGeneration;this.patch({isLoadingHistory:true});let result=await this.getMessages(id,{cursor:cursor2});if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(this.patch({isLoadingHistory:false}),!result.ok)return result;let existing=new Set(this.snapshot.messages.map(message=>message.id)),older=result.value.messages.filter(message=>!existing.has(message.id));return this.patch({messages:[...older,...this.snapshot.messages],historyCursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}),ok(void 0)}async*retryHistory(id){let result=await this.resumeConversation(id);result.ok||(yield synthErrorFrame(result.error))}async primeConversation(opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.primeBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async primeBounded(petRef2){let head=await this.headThreadWithUnread(petRef2);return head.ok?head.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(head.value)).ok?ok(head.value):ok(this.snapshot.conversationId):head.error.code==="accessDenied"||head.error.httpStatus===403?ok(null):err(head.error)}async headThreadWithUnread(petRef2){let listed=await this.listConversationsWith({...petRef2===null?{}:{petRef:petRef2},limit:1},{maxAttempts:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];return head===void 0||head.unreadCount===null||head.unreadCount<=0?ok(null):ok(head.id)}async createConversation(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending={petRef:petRef2,settled:this.createConversationBounded(petRef2)};this.unadoptedCreate=pending;let result=await pending.settled;return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending&&(this.unadoptedCreate=null),result)}async createConversationBounded(petRef2,signal){let req={method:"POST",path:"/widget/v1/conversations",body:petRef2?{pet_ref:petRef2}:{}},res=await this.authedUnary("chat.createConversation",req,signal,{maxAttempts:1});if(!res.ok)return err(res.error);let raw=res.value?.conversation_id??res.value?.id;return typeof raw!="string"||raw.length===0?err(makeError("internalError",true)):ok(raw)}async getPrompts(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null;if(petRef2!==null&&hasLoneSurrogate(petRef2))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let query=petRef2!==null?`?pet_ref=${encodeURIComponent(petRef2)}`:"",res=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${query}`});return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):res.ok?ok(parsePromptCategories(res.value)):err(res.error)}async authedUnary(call,req,external,opts){return this.funnel.send(call,external?{...req,signal:external}:req,opts)}driveWithHandlers(text3,opts,handlers){let cancel=new AbortController,signal=mergeSignals2(cancel.signal,opts.signal),turn=this.beginTurn(text3,opts),iterable=this.runTurn(turn,signal),torn=false,teardown=()=>{torn||(torn=true,cancel.abort(),this.handlerTeardowns.delete(teardown))};return this.handlerTeardowns.add(teardown),(async()=>{for await(let frame of iterable){if(torn)break;handlers.onFrame(frame),frame.kind==="done"&&handlers.onDone(this.lastResponseIdValue)}!torn&&this.snapshot.status==="error"&&this.snapshot.error!==null&&handlers.onError(this.snapshot.error),this.handlerTeardowns.delete(teardown)})(),teardown}beginTurn(text3,opts){let turn={epoch:this.epoch,text:text3,petRef:opts.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...opts.imageS3Keys??[]]),idempotencyKey:opts.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:opts.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,makeUser(turn.userMessageId,text3,this.stamp())]}),turn}async*runTurn(turn,external){let op=this.beginOperation(external);turn.epoch=op.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=turn;let retries=0,recreated=false,refreshedOnce=false;try{for(;;){if(op.signal.aborted||!this.alive(op.epoch))return;let needsConversation=turn.conversationIdOverride===null&&this.snapshot.conversationId===null,pending=needsConversation?this.unadoptedCreate:null;if(pending!==null&&(turn.petRef===null||turn.petRef===pending.petRef)){let primed=await pending.settled;if(op.signal.aborted||!this.alive(op.epoch))return;primed.ok&&primed.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(primed.value),this.reportConversationStarted(primed.value))}if(needsConversation&&this.snapshot.conversationId===null){let created=await this.createConversationBounded(turn.petRef,op.signal);if(op.signal.aborted||!this.alive(op.epoch))return;if(!created.ok){yield*this.emitTerminal(turn,created.error,synthErrorFrame(created.error));return}this.adoptConversation(created.value),this.reportConversationStarted(created.value)}let convId=turn.conversationIdOverride??this.snapshot.conversationId;if(convId===null){let e=makeError("internalError",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}this.clearAssistantInProgress(turn);let attemptCtrl=new AbortController,attemptSignal=mergeSignals2(op.signal,attemptCtrl.signal),terminalError=null;try{let authedReq;try{authedReq=await this.funnel.authorize(this.buildSendRequest(turn,convId))}catch{this.reportSessionRejected();let e=this.authRejected();yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}if(op.signal.aborted||!this.alive(op.epoch))return;let source=this.funnel.stream("chat.send",authedReq,attemptSignal);for await(let frame of withWatchdog(source,this.budget,attemptSignal,this.timers)){if(!this.alive(op.epoch))return;if(frame.kind==="error"&&frame.terminal){terminalError=frame;break}if(this.applyFrame(frame,turn),yield frame,frame.terminal){op.settle();return}}}finally{attemptCtrl.abort()}if(op.signal.aborted||!this.alive(op.epoch))return;if(terminalError===null){if(this.snapshot.status==="complete")return;let e=makeError("streamIncomplete",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}let code=fromWire(terminalError.code);if(code==="authExpired"&&this.auth.mode==="personalized"&&!refreshedOnce){refreshedOnce=!0,this.telemetry.track("chat.auth.refresh",{});let refreshed=await this.tryForceRefresh();if(op.signal.aborted||!this.alive(op.epoch))return;if(!refreshed){this.reportSessionRejected();let e=this.authRejected(terminalError);yield*this.emitTerminal(turn,e,terminalError);return}this.patch({reconnecting:!0});continue}if(code==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let e=this.authRejected(terminalError);yield*this.emitTerminal(turn,e,terminalError);return}if(code==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}if(canRecreateOnNotFound(code)&&!recreated){recreated=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),turn.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let framedRetry=terminalError.retryable&&shouldRetry(code,!0);if(SEND_IS_SERVER_DEDUPED&&framedRetry&&retries+1<this.errorPolicy.maxAttempts(code));yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}}finally{op.settle()}}*emitTerminal(turn,error,frame){this.applyError(turn,error),yield frame}applyFrame(frame,turn){switch(frame.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(frame.delta,turn);return;case"done":this.applyDone(frame,turn);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(frame)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(text3,turn){if(turn.assistantMessageId===null){let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true;let cleared=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"streaming",isStreaming:true,messages:[...cleared,makeAssistant(assistantId,text3,this.stamp())]});return}if(this.pendingDelta+=text3,this.pendingDelta.length>=DELTA_FLUSH_CHARS){this.flushPendingDelta(turn);return}this.scheduleDeltaFlush(turn)}scheduleDeltaFlush(turn){if(this.flushHandle!==null)return;let scheduledEpoch=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(scheduledEpoch)){this.pendingDelta="";return}this.flushPendingDelta(turn)},DELTA_FLUSH_MS)}flushPendingDelta(turn){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let chunk=this.pendingDelta;this.pendingDelta="";let assistantId=turn.assistantMessageId;if(assistantId===null)return;let messages=this.snapshot.messages.map(m=>m.id===assistantId?appendText(m,chunk):m);this.patch({messages:messages})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(done,turn){this.flushPendingDelta(turn),this.lastResponseIdValue=done.messageId?done.messageId:null;let nextConv=done.conversationId?done.conversationId:this.snapshot.conversationId,messages;if(turn.assistantMessageId!==null)messages=this.snapshot.messages.map(m=>m.id===turn.assistantMessageId?finalizeAssistant(m,done):m);else{let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true,messages=[...this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m),finalizeAssistant(makeAssistant(assistantId,"",this.stamp()),done)]}let followUps=flattenPrompts([{category:"",prompts:done.followUpQuestions}]);this.replyPrompts=followUps.length>0?/* @__PURE__ */Object.freeze(followUps):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:nextConv,messages:messages,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!done.urgencyProvided&&nextConv!==null&&this.classifyTurn(nextConv,this.lastResponseIdValue)}async classifyTurn(conversationId2,responseId){if(responseId===null||this.disposed)return;let messageId=String(responseId);if(this.classifiedMessageIds.has(messageId))return;this.classifiedMessageIds.add(messageId);let epoch=this.epoch,generation=this.historyGeneration,result=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${conversationId2}/classify`});if(!result.ok||!this.alive(epoch)||this.disposed||generation!==this.historyGeneration||this.snapshot.conversationId!==conversationId2)return;let level=urgencyTier(result.value?.urgency),reason=typeof result.value?.reason=="string"?result.value.reason:null,carries=m=>m.responseId===responseId;this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,urgencyLevel:level,urgencyReason:reason,urgencyProvided:true}):m)})}applyError(turn,error){this.flushPendingDelta(turn);let messages=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"error",isStreaming:false,error:error,messages:messages,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(error)}catch{}}clearAssistantInProgress(turn){if(this.discardPendingDelta(),turn.assistantMessageId===null)return;let assistantId=turn.assistantMessageId;turn.assistantMessageId=null,turn.sawDelta=false;let messages=this.snapshot.messages.filter(m=>m.id!==assistantId);messages.length!==this.snapshot.messages.length&&this.patch({messages:messages})}buildSendRequest(turn,convId){let body={message:turn.text};return turn.imageS3Keys.length>0&&(body.image_s3_keys=turn.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${convId}/messages`,body:body,headers:{"Idempotency-Key":turn.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(id){try{this.onConversationStarted?.(id)}catch{}}authRejected(refusal){return refusal===void 0?makeError("authRejected",false):makeEverfurError("authRejected",{retryable:false,...refusal.code?{wireCode:refusal.code}:{},...refusal.serverRequestId?{requestId:refusal.serverRequestId}:{}})}};async function bootstrapChat(input,deps){let{controller:controller}=deps,petRef2=input.petRef??null,resume=input.resumeConversationId??null,candidateConversationIds=[],sawForbidden=false,sawUnauthorized=false,sawConversationInitFailure=false,authBlock=null,initFailure=null,conversationPromise=resume?controller.resumeConversation(resume).then(result=>result.ok?ok(resume):err(result.error)):controller.primeConversation(petRef2?{petRef:petRef2}:void 0),promptsPromise=controller.getPrompts(petRef2!==null?{petRef:petRef2}:void 0),[conversationRes,initialPromptsRes]=await Promise.all([conversationPromise,promptsPromise]),conversationId2=null;if(conversationRes.ok)conversationId2=conversationRes.value,conversationRes.value!==null&&candidateConversationIds.push(conversationRes.value),conversationRes.value!==null&&controller.getSnapshot().conversationId===null&&controller.adoptConversation(conversationRes.value);else{let e=conversationRes.error;initFailure=e,isUnauthorized(e)?(sawUnauthorized=true,authBlock=e):(isForbidden(e)&&(sawForbidden=true),sawConversationInitFailure=true)}let suggestedPrompts=[];initialPromptsRes.ok?suggestedPrompts=initialPromptsRes.value:recordAuthSignals(initialPromptsRes.error);function recordAuthSignals(e){isUnauthorized(e)?(sawUnauthorized=true,authBlock===null&&(authBlock=e)):isForbidden(e)&&(sawForbidden=true)}let error=authBlock!==null?authBlock.displayMessage:null;/* @__PURE__ */
|
|
120
|
+
return Object.freeze({...message,checkin:/* @__PURE__ */Object.freeze({...checkin,status:watching?CHECKIN_ANSWERABLE_STATUS:row?.status??"resolved",answer:checkin.answer??answerOnRecord,resolutionText:checkin.resolutionText??row?.resolutionText??null,...openedAt!==null?{openedAt:openedAt}:{}})})});changed&&this.patch({messages:messages})}async refreshActiveThread(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId;if(id===null||this.snapshot.isStreaming)return ok(void 0);let generation=this.historyGeneration,result=await this.getMessages(id);if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(!result.ok)return err(result.error);let existing=new Set(this.snapshot.messages.map(message=>message.id)),arrived=result.value.messages.filter(message=>!existing.has(message.id));return arrived.length>0&&this.patch({messages:[...this.snapshot.messages,...arrived]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(makeError("accessDenied",false));let id=this.snapshot.conversationId,cursor2=this.snapshot.historyCursor;if(!id||!cursor2||this.snapshot.isLoadingHistory)return ok(void 0);let generation=this.historyGeneration;this.patch({isLoadingHistory:true});let result=await this.getMessages(id,{cursor:cursor2});if(generation!==this.historyGeneration||this.disposed)return err(makeError("accessDenied",false));if(this.patch({isLoadingHistory:false}),!result.ok)return result;let existing=new Set(this.snapshot.messages.map(message=>message.id)),older=result.value.messages.filter(message=>!existing.has(message.id));return this.patch({messages:[...older,...this.snapshot.messages],historyCursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}),ok(void 0)}async*retryHistory(id){let result=await this.resumeConversation(id);result.ok||(yield synthErrorFrame(result.error))}async primeConversation(opts){if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending2={petRef:petRef2,settled:this.primeBounded(petRef2)};this.unadoptedCreate=pending2;let result=await pending2.settled;return this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending2&&(this.unadoptedCreate=null),result)}async primeBounded(petRef2){let head=await this.headThreadWithUnread(petRef2);return head.ok?head.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(head.value)).ok?ok(head.value):ok(this.snapshot.conversationId):head.error.code==="accessDenied"||head.error.httpStatus===403?ok(null):err(head.error)}async headThreadWithUnread(petRef2){let listed=await this.listConversationsWith({...petRef2===null?{}:{petRef:petRef2},limit:1},{maxAttempts:1});if(!listed.ok)return err(listed.error);let head=listed.value.conversations[0];return head===void 0||head.unreadCount===null||head.unreadCount<=0?ok(null):ok(head.id)}async createConversation(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null,pending2={petRef:petRef2,settled:this.createConversationBounded(petRef2)};this.unadoptedCreate=pending2;let result=await pending2.settled;return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):(!result.ok&&this.unadoptedCreate===pending2&&(this.unadoptedCreate=null),result)}async createConversationBounded(petRef2,signal){let req={method:"POST",path:"/widget/v1/conversations",body:petRef2?{pet_ref:petRef2}:{}},res=await this.authedUnary("chat.createConversation",req,signal,{maxAttempts:1});if(!res.ok)return err(res.error);let raw=res.value?.conversation_id??res.value?.id;return typeof raw!="string"||raw.length===0?err(makeError("internalError",true)):ok(raw)}async getPrompts(opts){let epoch=this.epoch;if(this.disposed)return err(makeError("accessDenied",false));let petRef2=opts?.petRef??null;if(petRef2!==null&&hasLoneSurrogate(petRef2))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let query=petRef2!==null?`?pet_ref=${encodeURIComponent(petRef2)}`:"",res=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${query}`});return!this.alive(epoch)||this.disposed?err(makeError("accessDenied",false)):res.ok?ok(parsePromptCategories(res.value)):err(res.error)}async authedUnary(call,req,external,opts){return this.funnel.send(call,external?{...req,signal:external}:req,opts)}driveWithHandlers(text3,opts,handlers){let cancel=new AbortController,signal=mergeSignals2(cancel.signal,opts.signal),turn=this.beginTurn(text3,opts),iterable=this.runTurn(turn,signal),torn=false,teardown=()=>{torn||(torn=true,cancel.abort(),this.handlerTeardowns.delete(teardown))};return this.handlerTeardowns.add(teardown),(async()=>{for await(let frame of iterable){if(torn)break;handlers.onFrame(frame),frame.kind==="done"&&handlers.onDone(this.lastResponseIdValue)}!torn&&this.snapshot.status==="error"&&this.snapshot.error!==null&&handlers.onError(this.snapshot.error),this.handlerTeardowns.delete(teardown)})(),teardown}beginTurn(text3,opts){let turn={epoch:this.epoch,text:text3,petRef:opts.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...opts.imageS3Keys??[]]),idempotencyKey:opts.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:opts.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,makeUser(turn.userMessageId,text3,this.stamp())]}),turn}async*runTurn(turn,external){let op=this.beginOperation(external);turn.epoch=op.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=turn;let retries=0,recreated=false,refreshedOnce=false;try{for(;;){if(op.signal.aborted||!this.alive(op.epoch))return;let needsConversation=turn.conversationIdOverride===null&&this.snapshot.conversationId===null,pending2=needsConversation?this.unadoptedCreate:null;if(pending2!==null&&(turn.petRef===null||turn.petRef===pending2.petRef)){let primed=await pending2.settled;if(op.signal.aborted||!this.alive(op.epoch))return;primed.ok&&primed.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(primed.value),this.reportConversationStarted(primed.value))}if(needsConversation&&this.snapshot.conversationId===null){let created=await this.createConversationBounded(turn.petRef,op.signal);if(op.signal.aborted||!this.alive(op.epoch))return;if(!created.ok){yield*this.emitTerminal(turn,created.error,synthErrorFrame(created.error));return}this.adoptConversation(created.value),this.reportConversationStarted(created.value)}let convId=turn.conversationIdOverride??this.snapshot.conversationId;if(convId===null){let e=makeError("internalError",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}this.clearAssistantInProgress(turn);let attemptCtrl=new AbortController,attemptSignal=mergeSignals2(op.signal,attemptCtrl.signal),terminalError=null;try{let authedReq;try{authedReq=await this.funnel.authorize(this.buildSendRequest(turn,convId))}catch{this.reportSessionRejected();let e=this.authRejected();yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}if(op.signal.aborted||!this.alive(op.epoch))return;let source=this.funnel.stream("chat.send",authedReq,attemptSignal);for await(let frame of withWatchdog(source,this.budget,attemptSignal,this.timers)){if(!this.alive(op.epoch))return;if(frame.kind==="error"&&frame.terminal){terminalError=frame;break}if(this.applyFrame(frame,turn),yield frame,frame.terminal){op.settle();return}}}finally{attemptCtrl.abort()}if(op.signal.aborted||!this.alive(op.epoch))return;if(terminalError===null){if(this.snapshot.status==="complete")return;let e=makeError("streamIncomplete",!0);yield*this.emitTerminal(turn,e,synthErrorFrame(e));return}let code=fromWire(terminalError.code);if(code==="authExpired"&&this.auth.mode==="personalized"&&!refreshedOnce){refreshedOnce=!0,this.telemetry.track("chat.auth.refresh",{});let refreshed=await this.tryForceRefresh();if(op.signal.aborted||!this.alive(op.epoch))return;if(!refreshed){this.reportSessionRejected();let e=this.authRejected(terminalError);yield*this.emitTerminal(turn,e,terminalError);return}this.patch({reconnecting:!0});continue}if(code==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let e=this.authRejected(terminalError);yield*this.emitTerminal(turn,e,terminalError);return}if(code==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}if(canRecreateOnNotFound(code)&&!recreated){recreated=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),turn.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let framedRetry=terminalError.retryable&&shouldRetry(code,!0);if(SEND_IS_SERVER_DEDUPED&&framedRetry&&retries+1<this.errorPolicy.maxAttempts(code));yield*this.emitTerminal(turn,errorFromFrame(terminalError),terminalError);return}}finally{op.settle()}}*emitTerminal(turn,error,frame){this.applyError(turn,error),yield frame}applyFrame(frame,turn){switch(frame.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(frame.delta,turn);return;case"done":this.applyDone(frame,turn);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(frame)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(text3,turn){if(turn.assistantMessageId===null){let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true;let cleared=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"streaming",isStreaming:true,messages:[...cleared,makeAssistant(assistantId,text3,this.stamp())]});return}if(this.pendingDelta+=text3,this.pendingDelta.length>=DELTA_FLUSH_CHARS){this.flushPendingDelta(turn);return}this.scheduleDeltaFlush(turn)}scheduleDeltaFlush(turn){if(this.flushHandle!==null)return;let scheduledEpoch=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(scheduledEpoch)){this.pendingDelta="";return}this.flushPendingDelta(turn)},DELTA_FLUSH_MS)}flushPendingDelta(turn){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let chunk=this.pendingDelta;this.pendingDelta="";let assistantId=turn.assistantMessageId;if(assistantId===null)return;let messages=this.snapshot.messages.map(m=>m.id===assistantId?appendText(m,chunk):m);this.patch({messages:messages})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(done,turn){this.flushPendingDelta(turn),this.lastResponseIdValue=done.messageId?done.messageId:null;let nextConv=done.conversationId?done.conversationId:this.snapshot.conversationId,messages;if(turn.assistantMessageId!==null)messages=this.snapshot.messages.map(m=>m.id===turn.assistantMessageId?finalizeAssistant(m,done):m);else{let assistantId=this.newId();turn.assistantMessageId=assistantId,turn.sawDelta=true,messages=[...this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m),finalizeAssistant(makeAssistant(assistantId,"",this.stamp()),done)]}let followUps=flattenPrompts([{category:"",prompts:done.followUpQuestions}]);this.replyPrompts=followUps.length>0?/* @__PURE__ */Object.freeze(followUps):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:nextConv,messages:messages,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!done.urgencyProvided&&nextConv!==null&&this.classifyTurn(nextConv,this.lastResponseIdValue)}async classifyTurn(conversationId2,responseId){if(responseId===null||this.disposed)return;let messageId=String(responseId);if(this.classifiedMessageIds.has(messageId))return;this.classifiedMessageIds.add(messageId);let epoch=this.epoch,generation=this.historyGeneration,result=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${conversationId2}/classify`});if(!result.ok||!this.alive(epoch)||this.disposed||generation!==this.historyGeneration||this.snapshot.conversationId!==conversationId2)return;let level=urgencyTier(result.value?.urgency),reason=typeof result.value?.reason=="string"?result.value.reason:null,carries=m=>m.responseId===responseId;this.snapshot.messages.some(carries)&&this.patch({messages:this.snapshot.messages.map(m=>carries(m)?/* @__PURE__ */Object.freeze({...m,urgencyLevel:level,urgencyReason:reason,urgencyProvided:true}):m)})}applyError(turn,error){this.flushPendingDelta(turn);let messages=this.snapshot.messages.map(m=>m.id===turn.userMessageId&&m.pending===true?stripPending(m):m);this.patch({status:"error",isStreaming:false,error:error,messages:messages,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(error)}catch{}}clearAssistantInProgress(turn){if(this.discardPendingDelta(),turn.assistantMessageId===null)return;let assistantId=turn.assistantMessageId;turn.assistantMessageId=null,turn.sawDelta=false;let messages=this.snapshot.messages.filter(m=>m.id!==assistantId);messages.length!==this.snapshot.messages.length&&this.patch({messages:messages})}buildSendRequest(turn,convId){let body={message:turn.text};return turn.imageS3Keys.length>0&&(body.image_s3_keys=turn.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${convId}/messages`,body:body,headers:{"Idempotency-Key":turn.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(id){try{this.onConversationStarted?.(id)}catch{}}authRejected(refusal){return refusal===void 0?makeError("authRejected",false):makeEverfurError("authRejected",{retryable:false,...refusal.code?{wireCode:refusal.code}:{},...refusal.serverRequestId?{requestId:refusal.serverRequestId}:{}})}};async function bootstrapChat(input,deps){let{controller:controller}=deps,petRef2=input.petRef??null,resume=input.resumeConversationId??null,candidateConversationIds=[],sawForbidden=false,sawUnauthorized=false,sawConversationInitFailure=false,authBlock=null,initFailure=null,conversationPromise=resume?controller.resumeConversation(resume).then(result=>result.ok?ok(resume):err(result.error)):controller.primeConversation(petRef2?{petRef:petRef2}:void 0),promptsPromise=controller.getPrompts(petRef2!==null?{petRef:petRef2}:void 0),[conversationRes,initialPromptsRes]=await Promise.all([conversationPromise,promptsPromise]),conversationId2=null;if(conversationRes.ok)conversationId2=conversationRes.value,conversationRes.value!==null&&candidateConversationIds.push(conversationRes.value),conversationRes.value!==null&&controller.getSnapshot().conversationId===null&&controller.adoptConversation(conversationRes.value);else{let e=conversationRes.error;initFailure=e,isUnauthorized(e)?(sawUnauthorized=true,authBlock=e):(isForbidden(e)&&(sawForbidden=true),sawConversationInitFailure=true)}let suggestedPrompts=[];initialPromptsRes.ok?suggestedPrompts=initialPromptsRes.value:recordAuthSignals(initialPromptsRes.error);function recordAuthSignals(e){isUnauthorized(e)?(sawUnauthorized=true,authBlock===null&&(authBlock=e)):isForbidden(e)&&(sawForbidden=true)}let error=authBlock!==null?authBlock.displayMessage:null;/* @__PURE__ */
|
|
121
121
|
return Object.freeze({conversationId:conversationId2,petRef:petRef2,suggestedPrompts:suggestedPrompts,error:error,warning:error===null&&conversationId2===null&&sawConversationInitFailure?CONVERSATION_NOT_PRIMED_WARNING:null,cause:authBlock??initFailure,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...candidateConversationIds]),sawForbidden:sawForbidden,sawUnauthorized:sawUnauthorized,sawConversationInitFailure:sawConversationInitFailure})})}var CONVERSATION_NOT_PRIMED_WARNING="Chat is ready. Your first message will start the conversation.";function isUnauthorized(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function isForbidden(e){return e.httpStatus===403||e.code==="accessDenied"}var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var ATTACHMENT_MIME_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]),ATTACHMENT_ACCEPT="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",MAX_ATTACHMENT_BYTES=10*1024*1024,MAX_ATTACHMENTS_PER_MESSAGE=5,MAX_FILENAME_LENGTH=120,ATTACHMENT_INITIATE_PATH="/widget/v1/uploads/initiate";function isAttachmentMime(mime){return typeof mime=="string"&&ATTACHMENT_MIME_TYPES.includes(mime.trim().toLowerCase())}function sanitizeFilename(input){if(!input)return"attachment";let stripped=input.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!stripped)return"attachment";if(stripped.length<=MAX_FILENAME_LENGTH)return stripped;let dotIndex=stripped.lastIndexOf(".");if(dotIndex===-1||dotIndex===stripped.length-1)return stripped.slice(0,MAX_FILENAME_LENGTH);let extension=stripped.slice(dotIndex);return extension.length>=MAX_FILENAME_LENGTH?stripped.slice(0,MAX_FILENAME_LENGTH):`${stripped.slice(0,dotIndex).slice(0,MAX_FILENAME_LENGTH-extension.length)}${extension}`}function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}var ok2=value=>/* @__PURE__ */Object.freeze({ok:true,value:value}),err2=error=>/* @__PURE__ */Object.freeze({ok:false,error:error});function failure(code,retryable,filename,extra){/* @__PURE__ */
|
|
122
122
|
return Object.freeze({code:code,retryable:retryable,filename:filename,...extra??{}})}function attachmentSize(file){if(typeof file.sizeBytes=="number"&&Number.isFinite(file.sizeBytes)&&file.sizeBytes>=0)return file.sizeBytes;let blob=file.blob;return blob!==void 0&&typeof blob.size=="number"&&Number.isFinite(blob.size)?blob.size:null}function validateAttachment(file){let filename=sanitizeFilename(file.name),contentType=typeof file.mimeType=="string"?file.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(contentType))return err2(failure("unsupported_type",false,filename));let sizeBytes=attachmentSize(file);return sizeBytes===null?err2(failure("unknown",false,filename)):sizeBytes>MAX_ATTACHMENT_BYTES?err2(failure("too_large",false,filename,{sizeBytes:sizeBytes})):ok2(/* @__PURE__ */Object.freeze({file:file,filename:filename,contentType:contentType,sizeBytes:sizeBytes}))}function parsePolicy(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,str5=v=>typeof v=="string"&&v.length>0?v:null,num2=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadId=str5(o.upload_id),uploadUrl=str5(o.upload_url),s3Key=str5(o.s3_key);if(uploadId===null||uploadUrl===null||s3Key===null)return null;let fields={},rawFields=o.upload_fields;if(typeof rawFields=="object"&&rawFields!==null)for(let[key,value]of Object.entries(rawFields))typeof value=="string"&&(fields[key]=value);/* @__PURE__ */
|
|
123
|
-
return Object.freeze({upload_id:uploadId,upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num2(o.expires_in_seconds)??0,max_content_length:num2(o.max_content_length)??MAX_ATTACHMENT_BYTES,s3_key:s3Key,purpose:str5(o.purpose)})}function initiateFailure(error,filename){let status=error.httpStatus;switch(error.code){case"quotaExceeded":return failure("quota_exceeded",false,filename,{cause:error});case"rateLimited":return failure("rate_limited",true,filename,{cause:error});case"idempotencyConflict":case"idempotencyInFlight":return failure("idempotency_conflict",true,filename,{cause:error});case"validationFailed":return failure("unsupported_type",false,filename,{cause:error});case"serviceUnavailable":case"streamTimeout":return failure("network",true,filename,{cause:error});default:return status===429?failure("rate_limited",true,filename,{cause:error}):status===503?failure("network",true,filename,{cause:error}):status===void 0?failure("network",true,filename,{cause:error}):failure("server",error.retryable,filename,{httpStatus:status,cause:error})}}async function initiateAttachmentUpload(funnel,attachment,opts){let res=await funnel.send("chat.attachments.initiate",{method:"POST",path:ATTACHMENT_INITIATE_PATH,body:{filename:attachment.filename,content_type:attachment.contentType,file_size:attachment.sizeBytes},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err2(initiateFailure(res.error,attachment.filename));let policy=parsePolicy(res.value);return policy===null?err2(failure("server",false,attachment.filename)):ok2(policy)}async function uploadAttachmentBytes(transport,policy,attachment,opts){let cancelled=()=>opts?.signal?.aborted===true;if(cancelled())return err2(failure("cancelled",true,attachment.filename));try{return await transport.postMultipart(policy,attachment.file,{...opts?.signal?{signal:opts.signal}:{},...opts?.onProgress?{onProgress:opts.onProgress}:{}}),ok2(void 0)}catch{return cancelled()?err2(failure("cancelled",true,attachment.filename)):err2(failure("server",true,attachment.filename))}}var ATTACHMENT_QUEUE_CONCURRENCY=2,ATTACHMENT_MAX_ATTEMPTS=3,ATTACHMENT_BACKOFF_MS=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),idCounter=0;function defaultNewId(){return idCounter+=1,`attachment-${idCounter}`}function createAttachmentQueue(deps){let concurrency=Math.max(1,deps.concurrency??ATTACHMENT_QUEUE_CONCURRENCY),maxAttempts=Math.max(1,deps.maxAttempts??ATTACHMENT_MAX_ATTEMPTS),backoff=deps.backoffMs??ATTACHMENT_BACKOFF_MS,maxPerMessage=Math.max(1,deps.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE),timers=deps.timers??defaultTimers,newId=deps.newId??defaultNewId,available=isUploadTransportAvailable(deps.transport),rows=/* @__PURE__ */new Map,order=[],pending=[],inFlight3=/* @__PURE__ */new Set,listeners3=/* @__PURE__ */new Set,snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed2=false,publish2=()=>{snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(order.flatMap(id=>{let row=rows.get(id);return row===void 0?[]:[row.state]}))});for(let listener of listeners3)listener()},patch=(row,partial)=>{row.state=/* @__PURE__ */Object.freeze({...row.state,...partial}),publish2()},pump=()=>{for(;!disposed2&&inFlight3.size<concurrency&&pending.length>0;){let id=pending.shift(),row=rows.get(id);row!==void 0&&(inFlight3.add(id),run(row).finally(()=>{inFlight3.delete(id),pump()}))}},run=async row=>{let{attachment:attachment}=row;for(;row.attempts<maxAttempts;){if(disposed2||row.controller.signal.aborted)return;row.attempts+=1;let signal=row.controller.signal;patch(row,{status:"uploading",error:null,progress:0});let initiated=await initiateAttachmentUpload(deps.funnel,attachment,{signal:signal});if(disposed2||signal.aborted)return;let outcome;if(!initiated.ok)outcome=err2(initiated.error);else{let staged=await uploadAttachmentBytes(deps.transport,initiated.value,attachment,{signal:signal,onProgress:fraction=>{!signal.aborted&&row.state.status==="uploading"&&patch(row,{progress:clamp(fraction)})}});if(disposed2||signal.aborted)return;outcome=staged.ok?ok2(initiated.value.s3_key):err2(staged.error)}if(outcome.ok){patch(row,{status:"uploaded",s3Key:outcome.value,error:null,progress:1});return}let error=outcome.error,again=error.retryable&&row.attempts<maxAttempts;if(patch(row,{status:again?"uploading":"failed",error:error,progress:0}),!again)return;let wait=backoff[Math.min(row.attempts-1,backoff.length-1)]??0;await delayAbortable2(wait,signal,timers)}},enqueue=row=>{pending.push(row.state.id),pump()},queue={available:available,subscribe(listener){return listeners3.add(listener),()=>{listeners3.delete(listener)}},getSnapshot:()=>snapshot2,get uploading(){return snapshot2.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot2.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[])},add(file){let validated=validateAttachment(file);if(!validated.ok)return validated;if(disposed2||order.length>=maxPerMessage)return err2(failure("too_many",false,validated.value.filename));let id=newId(),row={attachment:validated.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:id,filename:validated.value.filename,previewUri:file.uri,contentType:validated.value.contentType,sizeBytes:validated.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return rows.set(id,row),order.push(id),publish2(),enqueue(row),ok2(row.state)},retry(id){let row=rows.get(id);row===void 0||disposed2||row.state.status!=="failed"||(row.controller=new AbortController,row.attempts=0,patch(row,{status:"uploading",error:null,progress:0,s3Key:null}),enqueue(row))},remove(id){let row=rows.get(id);if(row===void 0)return;row.controller.abort(),rows.delete(id);let at=order.indexOf(id);at>=0&&order.splice(at,1);let queued=pending.indexOf(id);queued>=0&&pending.splice(queued,1),publish2()},clear(){for(let id of[...order])queue.remove(id)},dispose(){disposed2=true;for(let row of rows.values())row.controller.abort();rows.clear(),order.length=0,pending.length=0,listeners3.clear(),snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return queue}function clamp(value){return Number.isNaN(value)||value<0?0:value>1?1:value}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str2=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str2(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(o.ref),name:name,dose:str2(o.dose),frequency:str2(o.frequency),startDate:str2(o.start_date),endDate:str2(o.end_date),notes:str2(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
|
|
123
|
+
return Object.freeze({upload_id:uploadId,upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num2(o.expires_in_seconds)??0,max_content_length:num2(o.max_content_length)??MAX_ATTACHMENT_BYTES,s3_key:s3Key,purpose:str5(o.purpose)})}function initiateFailure(error,filename){let status=error.httpStatus;switch(error.code){case"quotaExceeded":return failure("quota_exceeded",false,filename,{cause:error});case"rateLimited":return failure("rate_limited",true,filename,{cause:error});case"idempotencyConflict":case"idempotencyInFlight":return failure("idempotency_conflict",true,filename,{cause:error});case"validationFailed":return failure("unsupported_type",false,filename,{cause:error});case"serviceUnavailable":case"streamTimeout":return failure("network",true,filename,{cause:error});default:return status===429?failure("rate_limited",true,filename,{cause:error}):status===503?failure("network",true,filename,{cause:error}):status===void 0?failure("network",true,filename,{cause:error}):failure("server",error.retryable,filename,{httpStatus:status,cause:error})}}async function initiateAttachmentUpload(funnel,attachment,opts){let res=await funnel.send("chat.attachments.initiate",{method:"POST",path:ATTACHMENT_INITIATE_PATH,body:{filename:attachment.filename,content_type:attachment.contentType,file_size:attachment.sizeBytes},...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err2(initiateFailure(res.error,attachment.filename));let policy=parsePolicy(res.value);return policy===null?err2(failure("server",false,attachment.filename)):ok2(policy)}async function uploadAttachmentBytes(transport,policy,attachment,opts){let cancelled=()=>opts?.signal?.aborted===true;if(cancelled())return err2(failure("cancelled",true,attachment.filename));try{return await transport.postMultipart(policy,attachment.file,{...opts?.signal?{signal:opts.signal}:{},...opts?.onProgress?{onProgress:opts.onProgress}:{}}),ok2(void 0)}catch{return cancelled()?err2(failure("cancelled",true,attachment.filename)):err2(failure("server",true,attachment.filename))}}var ATTACHMENT_QUEUE_CONCURRENCY=2,ATTACHMENT_MAX_ATTEMPTS=3,ATTACHMENT_BACKOFF_MS=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),idCounter=0;function defaultNewId(){return idCounter+=1,`attachment-${idCounter}`}function createAttachmentQueue(deps){let concurrency=Math.max(1,deps.concurrency??ATTACHMENT_QUEUE_CONCURRENCY),maxAttempts=Math.max(1,deps.maxAttempts??ATTACHMENT_MAX_ATTEMPTS),backoff=deps.backoffMs??ATTACHMENT_BACKOFF_MS,maxPerMessage=Math.max(1,deps.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE),timers=deps.timers??defaultTimers,newId=deps.newId??defaultNewId,available=isUploadTransportAvailable(deps.transport),rows=/* @__PURE__ */new Map,order=[],pending2=[],inFlight3=/* @__PURE__ */new Set,listeners3=/* @__PURE__ */new Set,snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),disposed3=false,publish2=()=>{snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(order.flatMap(id=>{let row=rows.get(id);return row===void 0?[]:[row.state]}))});for(let listener of listeners3)listener()},patch=(row,partial)=>{row.state=/* @__PURE__ */Object.freeze({...row.state,...partial}),publish2()},pump=()=>{for(;!disposed3&&inFlight3.size<concurrency&&pending2.length>0;){let id=pending2.shift(),row=rows.get(id);row!==void 0&&(inFlight3.add(id),run(row).finally(()=>{inFlight3.delete(id),pump()}))}},run=async row=>{let{attachment:attachment}=row;for(;row.attempts<maxAttempts;){if(disposed3||row.controller.signal.aborted)return;row.attempts+=1;let signal=row.controller.signal;patch(row,{status:"uploading",error:null,progress:0});let initiated=await initiateAttachmentUpload(deps.funnel,attachment,{signal:signal});if(disposed3||signal.aborted)return;let outcome;if(!initiated.ok)outcome=err2(initiated.error);else{let staged=await uploadAttachmentBytes(deps.transport,initiated.value,attachment,{signal:signal,onProgress:fraction=>{!signal.aborted&&row.state.status==="uploading"&&patch(row,{progress:clamp(fraction)})}});if(disposed3||signal.aborted)return;outcome=staged.ok?ok2(initiated.value.s3_key):err2(staged.error)}if(outcome.ok){patch(row,{status:"uploaded",s3Key:outcome.value,error:null,progress:1});return}let error=outcome.error,again=error.retryable&&row.attempts<maxAttempts;if(patch(row,{status:again?"uploading":"failed",error:error,progress:0}),!again)return;let wait=backoff[Math.min(row.attempts-1,backoff.length-1)]??0;await delayAbortable2(wait,signal,timers)}},enqueue=row=>{pending2.push(row.state.id),pump()},queue={available:available,subscribe(listener){return listeners3.add(listener),()=>{listeners3.delete(listener)}},getSnapshot:()=>snapshot2,get uploading(){return snapshot2.attachments.some(row=>row.status==="uploading")},get s3Keys(){return snapshot2.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[])},add(file){let validated=validateAttachment(file);if(!validated.ok)return validated;if(disposed3||order.length>=maxPerMessage)return err2(failure("too_many",false,validated.value.filename));let id=newId(),row={attachment:validated.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:id,filename:validated.value.filename,previewUri:file.uri,contentType:validated.value.contentType,sizeBytes:validated.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return rows.set(id,row),order.push(id),publish2(),enqueue(row),ok2(row.state)},retry(id){let row=rows.get(id);row===void 0||disposed3||row.state.status!=="failed"||(row.controller=new AbortController,row.attempts=0,patch(row,{status:"uploading",error:null,progress:0,s3Key:null}),enqueue(row))},remove(id){let row=rows.get(id);if(row===void 0)return;row.controller.abort(),rows.delete(id);let at=order.indexOf(id);at>=0&&order.splice(at,1);let queued=pending2.indexOf(id);queued>=0&&pending2.splice(queued,1),publish2()},clear(){for(let id of[...order])queue.remove(id)},dispose(){disposed3=true;for(let row of rows.values())row.controller.abort();rows.clear(),order.length=0,pending2.length=0,listeners3.clear(),snapshot2=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return queue}function clamp(value){return Number.isNaN(value)||value<0?0:value>1?1:value}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str2=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str2(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(o.ref),name:name,dose:str2(o.dose),frequency:str2(o.frequency),startDate:str2(o.start_date),endDate:str2(o.end_date),notes:str2(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
|
|
124
124
|
return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str2(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str2(o.food_brand),foodType:str2(o.food_type),microchipId:str2(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str2(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str2(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str2(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str2(row.ref),conditionName:conditionName,diagnosedDate:str2(row.diagnosed_date),notes:str2(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid2(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid2(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid2(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef2,profile){if(typeof petRef2!="string")return invalid2("pet_ref must be a string");if(petRef2.trim().length===0)return invalid2("pet_ref must not be blank");if(hasLoneSurrogate(petRef2))return invalid2("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid2("profile must be an object");let checks=[checkString("pet_ref",petRef2,PET_REF_MAX)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid2(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid2("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid2("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str3=v=>typeof v=="string"?v:null,num=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef2){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
|
|
125
125
|
return Object.freeze({petRef:str3(o.pet_ref)??petRef2,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef2=str3(o.pet_ref);return petRef2===null||petRef2.length===0?null:/* @__PURE__ */Object.freeze({petId:str3(o.pet_id),petRef:petRef2,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str3(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
|
|
126
126
|
return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal2=(req,signal)=>signal?{...req,signal:signal}:req,petPath2=petRef2=>validate(petRef2,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef2)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal2({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef2,profile,opts){let invalid5=validate(petRef2,profile);if(invalid5!==null)return err(invalid5);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base2={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef2)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base2,signal:opts.signal}:base2);return res.ok?ok(fromWire2(res.value,petRef2)):err(res.error)},async updatePet(petRef2,patch,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal2({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef2)):err(res.error)},async getPetProfile(petRef2,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal2({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef2,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal2({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal2({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(name){return REQUIRES[name]}function deniedDecisionsFor(level,reason){let disabled=/* @__PURE__ */Object.freeze({reason:reason,level:level,recoverable:false}),rows=[],seen=/* @__PURE__ */new Set;for(let name of Object.keys(REQUIRES))for(let resource of REQUIRES[name])seen.has(resource)||(seen.add(resource),rows.push(/* @__PURE__ */Object.freeze({resource:resource,granted:false,disabled:disabled}))/* @__PURE__ */);return Object.freeze(rows)}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
|
|
127
127
|
return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
|
|
128
|
-
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base2={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base2.disabled=d.disabled),/* @__PURE__ */Object.freeze(base2)}function deliverClientEvent(handler,event){if(typeof handler=="function")try{let result=handler(event);result!==null&&typeof result=="object"&&typeof result.then=="function"&&result.then(void 0,reportHandlerFailure)}catch(error){reportHandlerFailure(error)}}function reportHandlerFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] onEvent threw; the SDK ignored it.",error)}catch{}}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function setPetRegistrationTenant(runtime,tenant){tenants.set(runtime,tenant)}function petRegistrationKey(runtime,auth,petRef2,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef2}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function notifyPetsChanged(runtime){let set=listeners.get(runtime);if(set!==void 0)for(let listener of[...set])try{listener()}catch{}}var inFlight2=/* @__PURE__ */new Map;function sharedTokenProvider(scope,getToken){return()=>{let pending=inFlight2.get(scope);if(pending!==void 0)return pending;let mint;try{mint=Promise.resolve(getToken())}catch(error){mint=Promise.reject(error)}let settled=mint.finally(()=>{inFlight2.get(scope)===settled&&inFlight2.delete(scope)});return inFlight2.set(scope,settled),settled}}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel2){return channel2<=.03928?channel2/12.92:Math.pow((channel2+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}function rgbToHsl(r,g,b){let rn=r/255,gn=g/255,bn=b/255,mx=Math.max(rn,gn,bn),mn=Math.min(rn,gn,bn),l=(mx+mn)/2;if(mx===mn)return{h:0,s:0,l:l};let d=mx-mn,s=d/(1-Math.abs(2*l-1)),h;return mx===rn?(h=(gn-bn)/d*60,h<0&&(h=h+360)):mx===gn?h=((bn-rn)/d+2)*60:h=((rn-gn)/d+4)*60,{h:h,s:s,l:l}}function hslToRgb(hsl){let{h:h,s:s,l:l}=hsl,c=(1-Math.abs(2*l-1))*s,hp=h/60,x=c*(1-Math.abs(hp%2-1)),m=l-c/2,sector=Math.floor(hp)%6,rgb1=[[c,x,0],[x,c,0],[0,c,x],[0,x,c],[x,0,c],[c,0,x]],[r1,g1,b1]=rgb1[sector];return{r:channel(r1+m),g:channel(g1+m),b:channel(b1+m)}}function channel(v){return Math.min(255,Math.max(0,Math.floor(v*255+.5)))}var THEME_SLOT_NAMES=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog","cartBar","planCard","planReasonLabel"]),THEME_SLOT_KEYS=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),THEME_SLOT_KEYS_BY_SLOT=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"])});function themeSlotKeysFor(name){return THEME_SLOT_KEYS_BY_SLOT[name]??THEME_SLOT_KEYS}var SLOT_MIN_CONTRAST=4.5,EMPTY=/* @__PURE__ */Object.freeze({});function isSlotName(value){return THEME_SLOT_NAMES.includes(value)}function parseRadius(value){let text3=typeof value=="string"&&value.length<=16?value.trim().replace(/ ?px$/i,""):null,n=typeof value=="number"?value:text3!==null&&text3.length>0?Number(text3):Number.NaN;return Number.isFinite(n)?Math.max(0,n):null}function parseThemeSlots(json){if(json===null||typeof json!="object"||Array.isArray(json))return null;let out={},any=false;for(let[name,raw]of Object.entries(json)){if(!isSlotName(name)||raw===null||typeof raw!="object")continue;let parsed=parseSlot(raw);if(parsed===null)continue;let slot=restrictSlotKeys(name,parsed);slot!==null&&(out[name]=slot,any=true)}return any?/* @__PURE__ */Object.freeze(out):null}function restrictSlotKeys(name,slot){let allowed=THEME_SLOT_KEYS_BY_SLOT[name];if(allowed===void 0)return slot;let out={};for(let key of allowed)slot[key]!==void 0&&(out[key]=slot[key]);return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function pick2(raw,snake,camel){return raw[snake]!==void 0?raw[snake]:raw[camel]}function parseSlot(raw){let slot={},backgroundColor=parseColor(pick2(raw,"background_color","backgroundColor"));backgroundColor!==null&&(slot.backgroundColor=backgroundColor);let borderColor=parseColor(pick2(raw,"border_color","borderColor"));borderColor!==null&&(slot.borderColor=borderColor);let borderRadius=parseRadius(pick2(raw,"border_radius","borderRadius"));borderRadius!==null&&(slot.borderRadius=borderRadius);let textColor=parseColor(pick2(raw,"text_color","textColor"));return textColor!==null&&(slot.textColor=textColor),Object.keys(slot).length===0?null:/* @__PURE__ */Object.freeze(slot)}function mergeThemeSlots(base2,over){return over===null||Object.keys(over).length===0?base2??EMPTY:base2===null||Object.keys(base2).length===0?over:/* @__PURE__ */Object.freeze({...base2,...over})}function isOpaque(color){let rgba=toRgba(color);return rgba!==null&&rgba.a>=1}var SLOT_MIN_BORDER_CONTRAST=3,DECORATIVE_EDGE_SLOTS=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function sameColor(a,b){let left=parseColor(a);return left!==null&&left===parseColor(b)}function boundaryFor(fill,surrounds,seats=[]){if(surrounds.length===0)return null;let shown=surrounds.map(ground=>flattenOnto(fill,ground)??fill);if(surrounds.every((ground,index)=>contrastRatio(shown[index],ground)>=SLOT_MIN_BORDER_CONTRAST))return null;let against=[...surrounds,...shown,...seats];return pushToContrast(shown[0],against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST)}function seatsOf(background,defaults){return background===void 0?defaults:defaults.length===0?[background]:defaults.map(ground=>flattenOnto(background,ground)??ground)}function someInkReads(seats,target){let pole=poleForGrounds(seats);return seats.every(seat=>contrastRatio(pole,seat)>=target)}function collapseUnsatisfiableFill(background,defaults){let ground=defaults[0];return ground===void 0?null:flattenOnto(background,ground)}function inkFor(seats){let pick5=legibleOn(seats[0],SLOT_MIN_CONTRAST);return seats.every(seat=>contrastRatio(pick5,seat)>=SLOT_MIN_CONTRAST)?pick5:poleForGrounds(seats)}function edgeShowsTheControl(name,edge,fill,around,melts){return DECORATIVE_EDGE_SLOTS.has(name)?false:melts?true:fill!==void 0&&sameColor(edge,fill)?false:!(around!==void 0&&fill!==void 0&&isOpaque(fill))}function guardSlotContrast(slots,grounds2,surrounds){let changed=false,out={};for(let name of THEME_SLOT_NAMES){let slot=slots[name];if(slot===void 0)continue;let bg=slot.backgroundColor,defaults=grounds2?.[name]??[],seats=seatsOf(bg,defaults),next={...slot},fixed=false;if(bg!==void 0&&seats.length>1&&!someInkReads(seats,SLOT_MIN_CONTRAST)){let opaque=collapseUnsatisfiableFill(bg,defaults);opaque!==null&&(next.backgroundColor=opaque,seats=[opaque],fixed=true)}let around=surrounds?.[name],fill=next.backgroundColor,melts=around!==void 0&&fill!==void 0&&isOpaque(fill)&&boundaryFor(fill,around,seats)!==null;if(seats.length>0){let ink=slot.textColor;if(bg!==void 0)(ink===void 0||seats.some(seat=>contrastRatio(ink,seat)<SLOT_MIN_CONTRAST))&&(next.textColor=inkFor(seats),fixed=true);else if(ink!==void 0){let legible=pushToContrast(ink,seats,poleForGrounds(seats),SLOT_MIN_CONTRAST);legible!==ink&&(next.textColor=legible,fixed=true)}if(slot.borderColor!==void 0&&edgeShowsTheControl(name,slot.borderColor,fill,around,melts)){let against=melts?[...seats,...around??[]]:seats,edge=pushToContrast(slot.borderColor,against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST);edge!==slot.borderColor&&(next.borderColor=edge,fixed=true)}}if(melts&&fill!==void 0&&around!==void 0&&next.borderColor===void 0){let edge=boundaryFor(fill,around,seats);edge!==null&&(next.borderColor=edge,fixed=true)}out[name]=fixed?/* @__PURE__ */Object.freeze(next):slot,changed=changed||fixed}return changed?/* @__PURE__ */Object.freeze(out):slots}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});function textGrounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function controlGrounds(c){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill]}function brandReadsOnControls(c){return controlGrounds(c).every(ground=>contrastRatio(c.brand,ground)>=SLOT_MIN_BORDER_CONTRAST)}function linkGrounds(c){return[c.chatGround,c.surface,c.surfaceCream]}function statusGrounds(c,wash2){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill,...washGrounds(c,wash2)]}function washGrounds(c,wash2){return[flattenOnto(wash2,c.surface)??c.surface,flattenOnto(wash2,c.surfaceCream)??c.surfaceCream]}function composerGrounds(c){return[c.composerFill,c.chatGround]}var AUTHORED_AS_IS=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function onCompiledGrounds(c,compiled){let own=new Set(textGrounds(compiled));return textGrounds(c).every(ground=>own.has(ground))}function guardInks(theme){let c=theme.color,compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,other=(theme.brightness==="dark"?EVERFUR_LIGHT:EVERFUR_DARK).color,grounds2=textGrounds(c),flipped=poleForGrounds(grounds2)!==poleForGrounds(textGrounds(compiled)),keepCompiled=onCompiledGrounds(c,compiled),dangerIsCompiled=c.danger===compiled.danger&&c.badgeBgCritical===compiled.badgeBgCritical,ink=(name,value,authored,twin,on,target)=>{let untouched=value===authored&&(name!=="errorRed"||dangerIsCompiled);return untouched&&keepCompiled&&AUTHORED_AS_IS.has(name)?value:pushToContrast(untouched&&flipped?twin:value,on,poleForGrounds(on),target)},text3=(key,on,target)=>ink(`text.${key}`,c.text[key],compiled.text[key],other.text[key],on,target),token=(key,value,on,target)=>ink(key,value,compiled[key],other[key],on,target),tint=key=>flipped&&c[key]===compiled[key]?other[key]:c[key],primary=c.primary,onPrimary=legibleOn(primary,SLOT_MIN_CONTRAST),danger=token("danger",c.danger,[...grounds2,...washGrounds(c,c.badgeBgCritical)],SLOT_MIN_CONTRAST),guarded={...c,onPrimary:onPrimary,onAccent:legibleOn(c.accent,SLOT_MIN_CONTRAST),onDanger:contrastRatio(onPrimary,danger)>=SLOT_MIN_CONTRAST?onPrimary:legibleOn(danger,SLOT_MIN_CONTRAST),brandSoft:tint("brandSoft"),brandSofter:tint("brandSofter"),brandBorder:tint("brandBorder"),borderHairlineGreen:tint("borderHairlineGreen"),brandInk:token("brandInk",c.brandInk,grounds2,SLOT_MIN_CONTRAST),linkInk:token("linkInk",theme.slots.link?.textColor??c.accent,linkGrounds(c),SLOT_MIN_CONTRAST),text:{...c.text,primary:text3("primary",grounds2,SLOT_MIN_CONTRAST),secondary:text3("secondary",grounds2,SLOT_MIN_CONTRAST),muted:text3("muted",grounds2,SLOT_MIN_CONTRAST),metaCool:text3("metaCool",grounds2,SLOT_MIN_CONTRAST),timestamp:text3("timestamp",grounds2,SLOT_MIN_CONTRAST),placeholder:text3("placeholder",controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},danger:danger,errorRed:token("errorRed",c.errorRed,statusGrounds(c,c.badgeBgCritical),SLOT_MIN_CONTRAST),warningStrong:token("warningStrong",c.warningStrong,statusGrounds(c,c.badgeBgCaution),SLOT_MIN_CONTRAST),composerBorder:token("composerBorder",c.composerBorder,composerGrounds(c),SLOT_MIN_BORDER_CONTRAST),brandBorderStrong:token("brandBorderStrong",c.brandBorderStrong,controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},accented={...guarded,...accentFamily(guarded,compiled,keepCompiled)};return{...accented,...statusInks(c,accented,compiled)}}function statusInks(merged,g,compiled){let out={},push=(value,on,target)=>pushToContrast(value,on,poleForGrounds(on),target);if((!same(merged.success,compiled.success)||!same(merged.badgeBgPositive,compiled.badgeBgPositive))&&(out.success=push(merged.success,statusGrounds(g,merged.badgeBgPositive),SLOT_MIN_CONTRAST)),(!same(merged.cautionAccent,compiled.cautionAccent)||!same(merged.badgeBgCaution,compiled.badgeBgCaution))&&(out.cautionAccent=push(merged.cautionAccent,statusGrounds(g,merged.badgeBgCaution),SLOT_MIN_CONTRAST)),isPartnerInfo(merged,compiled)){out.info=push(merged.info,statusGrounds(g,merged.badgeBgInfo),SLOT_MIN_CONTRAST);let edgeGrounds=[g.surface,g.chatGround,...washGrounds(g,merged.badgeBgInfo)];out.infoEdge=push(merged.infoEdge,edgeGrounds,SLOT_MIN_BORDER_CONTRAST)}else out.info=g.brandInk,out.badgeBgInfo=g.brandSoft,out.infoEdge=g.structureEdge;return out}function isPartnerInfo(c,compiled){return!same(c.info,compiled.info)||!same(c.badgeBgInfo,compiled.badgeBgInfo)}var HIGHLIGHT_LIGHT_TINT=.24,HIGHLIGHT_DARK_TINT=.3;function same(a,b){return parseColor(a)===parseColor(b)}function partnerHue(c,compiled){return same(c.accent,compiled.accent)?same(c.brand,compiled.brand)?null:c.brand:c.accent}function tintOver(hue,surface,tint){let wash2=withAlpha(hue,tint);return(wash2===null?null:flattenOnto(wash2,surface))??surface}function accentFamily(c,compiled,keepCompiled){let hue=partnerHue(c,compiled),controls=controlGrounds(c),controlPole=poleForGrounds(controls),darkGround=poleForGrounds([c.surface])===WHITE,everfurMarks=hue===null&&keepCompiled,highlight;everfurMarks?highlight=compiled.highlight:hue===null?highlight=darkGround?tintOver(EVERFUR_LIGHT.color.highlight,c.surface,HIGHLIGHT_DARK_TINT):EVERFUR_LIGHT.color.highlight:highlight=tintOver(hue,c.surface,darkGround?HIGHLIGHT_DARK_TINT:HIGHLIGHT_LIGHT_TINT);let onHighlight=everfurMarks?compiled.onHighlight:pushToContrast(c.text.primary,[highlight],poleForGrounds([highlight]),SLOT_MIN_CONTRAST),mark=hue===null?compiled.mark:pushToContrast(hue,controls,controlPole,SLOT_MIN_BORDER_CONTRAST),toward=brandReadsOnControls(c)?c.brand:controlPole,edge=(value,authored,compiledEdge)=>keepCompiled&&same(value,authored)?compiledEdge:pushToContrast(value,controls,toward,SLOT_MIN_BORDER_CONTRAST),primaryGrounds=[c.chatGround,c.composerFill,c.surface,c.surfaceCream],primaryEdge=primaryGrounds.every(ground=>contrastRatio(c.primary,ground)>=SLOT_MIN_BORDER_CONTRAST)?c.primary:pushToContrast(c.primary,primaryGrounds,poleForGrounds(primaryGrounds),SLOT_MIN_BORDER_CONTRAST);return{highlight:highlight,onHighlight:onHighlight,mark:mark,controlEdge:edge(c.brandBorder,compiled.brandBorder,compiled.controlEdge),structureEdge:edge(c.borderHairlineGreen,compiled.borderHairlineGreen,compiled.structureEdge),primaryEdge:primaryEdge}}var same2=(a,b)=>a!==void 0&&b!==void 0&&parseColor(a)===parseColor(b);function diffThemeAdjustments(merged,resolved){let compiled=(merged.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,m=merged.color,r=resolved.color,out=[],add=(field,role,requested,painted)=>{out.push(/* @__PURE__ */Object.freeze({field:field,role:role,requested:requested,painted:painted}))},own=(value,compiledValue)=>!same2(value,compiledValue);own(m.text.primary,compiled.text.primary)&&!same2(r.text.primary,m.text.primary)&&add("text_color","body text",m.text.primary,r.text.primary),own(m.brand,compiled.brand)&&(same2(r.brandInk,m.brand)||add("primary_color","brand text and icons",m.brand,r.brandInk),same2(r.primaryEdge,m.primary)||add("primary_color","edge of a filled control",m.primary,r.primaryEdge),!same2(r.controlEdge,m.brandBorder)&&!brandReadsOnControls({...r,brand:m.brand})&&add("primary_color","control outline",m.brand,r.controlEdge)),own(m.accent,compiled.accent)&&merged.slots.link?.textColor===void 0&&!same2(r.linkInk,m.accent)&&add("accent_color","link text",m.accent,r.linkInk),own(m.danger,compiled.danger)&&!same2(r.danger,m.danger)&&add("danger_color","error text",m.danger,r.danger),own(m.success,compiled.success)&&!same2(r.success,m.success)&&add("success_color","positive status",m.success,r.success),own(m.warningStrong,compiled.warningStrong)&&!same2(r.warningStrong,m.warningStrong)&&add("warning_color","caution text",m.warningStrong,r.warningStrong),own(m.cautionAccent,compiled.cautionAccent)&&!same2(r.cautionAccent,m.cautionAccent)&&add("warning_color","caution accent",m.cautionAccent,r.cautionAccent),(own(m.info,compiled.info)||own(m.badgeBgInfo,compiled.badgeBgInfo))&&(same2(r.info,m.info)||add("info_color","information text",m.info,r.info),same2(r.infoEdge,m.infoEdge)||add("info_color","information outline",m.infoEdge,r.infoEdge));for(let name of THEME_SLOT_NAMES){let before=merged.slots[name],after=resolved.slots[name];before===void 0||after===void 0||before===after||(after.backgroundColor!==void 0&&!same2(after.backgroundColor,before.backgroundColor)&&add(`slots.${name}.background_color`,"fill",before.backgroundColor??null,after.backgroundColor),before.textColor!==void 0&&after.textColor!==void 0&&!same2(after.textColor,before.textColor)&&add(`slots.${name}.text_color`,"text",before.textColor??null,after.textColor),after.borderColor!==void 0&&!same2(after.borderColor,before.borderColor)&&add(`slots.${name}.border_color`,"outline",before.borderColor??null,after.borderColor))}/* @__PURE__ */
|
|
129
|
-
return Object.freeze(out)}var warned=/* @__PURE__ */new Set;function warnThemeAdjustments(adjustments){if(adjustments.length===0)return;let message=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${adjustments.map(a=>` ${a.field} (${a.role}): ${a.requested??"not set"} -> ${a.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(warned.has(message))return;warned.add(message);let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}var DARK_VARIANT_GROUND="#23272C",DARK_VARIANT_TARGET_RATIO=4.5,DARK_VARIANT_LIGHTNESS_FLOOR=.6,DARK_VARIANT_LIGHTNESS_CEILING=.9,DARK_VARIANT_LIGHTNESS_STEP=.02,WHITE_INK="#FFFFFF",NEAR_BLACK_INK="#111111";function readsOnDark(candidate){return contrastRatio(candidate,DARK_VARIANT_GROUND)>=DARK_VARIANT_TARGET_RATIO&&Math.max(contrastRatio(candidate,WHITE_INK),contrastRatio(candidate,NEAR_BLACK_INK))>=DARK_VARIANT_TARGET_RATIO}function deriveDarkVariant(color){let rgba=toRgba(color);if(rgba===null)return null;let{h:h,s:s,l:l}=rgbToHsl(rgba.r,rgba.g,rgba.b),lDark=Math.min(Math.max(l,DARK_VARIANT_LIGHTNESS_FLOOR),DARK_VARIANT_LIGHTNESS_CEILING);for(let i=0;;i+=1){let li=lDark+i*DARK_VARIANT_LIGHTNESS_STEP;if(li>DARK_VARIANT_LIGHTNESS_CEILING)break;let rgb=hslToRgb({h:h,s:s,l:li}),candidate=rgbToHex(rgb.r,rgb.g,rgb.b);if(readsOnDark(candidate))return candidate}let ceiling=hslToRgb({h:h,s:s,l:DARK_VARIANT_LIGHTNESS_CEILING});return rgbToHex(ceiling.r,ceiling.g,ceiling.b)}var HIGH_CONTRAST_TARGET_RATIO=7,PUSH_STEP2=.05,BLACK2="#000000",WHITE2="#FFFFFF";function pushContrast(color,ground,pole,target){let flat=flattenOnto(color,ground);if(flat===null)return pole;if(contrastRatio(flat,ground)>=target)return flat;let from=toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP2;step+=1){let t=step*PUSH_STEP2,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(contrastRatio(candidate,ground)>=target)return candidate}return pole}function hardestGround(color,dark){let grounds2=textGrounds(color),pick5=grounds2[0],pickLum=luminanceOf(pick5);for(let ground of grounds2){let lum=luminanceOf(ground);(dark?lum>pickLum:lum<pickLum)&&(pick5=ground,pickLum=lum)}return pick5}function luminanceOf(color){let rgba=toRgba(color);return rgba===null?0:relativeLuminance(rgba)}function solid(wash2,surface){return flattenOnto(wash2,surface)??parseColor(wash2)??surface}function deriveHighContrast(theme){let c=theme.color,lightInk=poleForGrounds(textGrounds(c))===WHITE2,pole=lightInk?WHITE2:BLACK2,ground=hardestGround(c,lightInk),text3=color2=>pushContrast(color2,ground,pole,HIGH_CONTRAST_TARGET_RATIO),color={...c,brandSoft:solid(c.brandSoft,c.surface),brandSofter:solid(c.brandSofter,c.surface),brandBorder:text3(c.brandBorder),borderHairlineGreen:text3(c.borderHairlineGreen),brandBorderStrong:text3(c.brandBorderStrong),controlEdge:text3(c.controlEdge),structureEdge:text3(c.structureEdge),brandInk:text3(c.brandInk),linkInk:text3(c.linkInk),borderRingCream:text3(c.borderRingCream),composerBorder:text3(c.composerBorder),text:{primary:text3(c.text.primary),secondary:text3(c.text.secondary),muted:text3(c.text.muted),placeholder:text3(c.text.placeholder),onBrand:c.text.onBrand,metaCool:text3(c.text.metaCool),timestamp:text3(c.text.timestamp)},badgeBgPositive:solid(c.badgeBgPositive,c.surface),badgeBgCaution:solid(c.badgeBgCaution,c.surface),badgeBgCritical:solid(c.badgeBgCritical,c.surface),badgeBgNeutral:solid(c.badgeBgNeutral,c.surface),checkupCardLowRiskBg:solid(c.checkupCardLowRiskBg,c.surface),checkupCardConcernBg:solid(c.checkupCardConcernBg,c.surface),info:text3(c.info),infoEdge:text3(c.infoEdge),badgeBgInfo:solid(c.badgeBgInfo,c.surface)};return deepFreeze({...theme,highContrast:true,color:color})}var BACKGROUND_STEPS=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),CREAM_STEP=BACKGROUND_STEPS.cream,SUBTLE_STEP=BACKGROUND_STEPS.subtle,RING_STEP=BACKGROUND_STEPS.ring,MIN_DERIVED_TYPE_SIZE=10;function mix(color,toward,t){let from=toRgba(color),to=toRgba(toward);if(from===null||to===null)return null;let at=(a,b)=>Math.round(a+(b-a)*t);return rgbToHex(at(from.r,to.r),at(from.g,to.g),at(from.b,to.b))}function surfaceFamily(background){if(background===null)return{};let pole=poleForGrounds([background]),cream=mix(background,pole,CREAM_STEP),subtle=mix(background,pole,SUBTLE_STEP),ring=mix(background,pole,RING_STEP);return cream===null||subtle===null||ring===null?{}:{surface:background,background:background,chatGround:background,bubbleAssistant:background,surfaceCream:cream,composerFill:cream,surfaceSubtle:subtle,skeleton:subtle,borderRingCream:ring}}function dangerFamily(danger){if(danger===null)return{};let rgba=toRgba(danger);return rgba===null?{}:{danger:danger,errorRed:danger,badgeBgCritical:`rgba(${rgba.r},${rgba.g},${rgba.b},0.12)`}}function typeSizesFor(base2,current,compiled){if(base2===null)return current;let factor=base2/compiled.type.size.body;if(factor===1)return compiled.type.size;let out={};for(let[key,value]of Object.entries(compiled.type.size))out[key]=Math.max(MIN_DERIVED_TYPE_SIZE,Math.round(value*factor*10)/10);return out}function spaceFor(unit,current,compiled){if(unit===null)return current;let factor=unit/compiled.space.xs,s=n=>Math.round(n*factor),c=compiled.space;return{xs:s(c.xs),sm:s(c.sm),md:s(c.md),lg:s(c.lg),xl:s(c.xl),xxl:s(c.xxl)}}function radiiFor(base2,compiled){let factor=base2/compiled.radius.md,s=n=>Math.round(n*factor),r=compiled.radius;return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var STATUS_WASH=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function wash(color,alpha){let rgba=toRgba(color);return rgba===null?null:`rgba(${rgba.r},${rgba.g},${rgba.b},${alpha})`}function successFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.success.dark:STATUS_WASH.success.light),card=wash(color,dark?STATUS_WASH.successCard.dark:STATUS_WASH.successCard.light);return badge===null||card===null?{}:{success:color,badgeBgPositive:badge,checkupCardLowRiskBg:card}}function warningFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.warning.dark:STATUS_WASH.warning.light);return badge===null?{}:{warningStrong:color,cautionAccent:color,badgeBgCaution:badge}}function infoFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.info.dark:STATUS_WASH.info.light);return badge===null?{}:{info:color,infoEdge:color,badgeBgInfo:badge}}function lineHeightsFor(lineHeight,current,compiled){if(lineHeight===null)return current;let c=compiled.type.lineHeight,factor=lineHeight/c.normal;if(factor===1)return c;let s=n=>Math.round(n*factor*100)/100;return{tight:s(c.tight),snug:s(c.snug),normal:s(c.normal),relaxed:s(c.relaxed)}}function slotGrounds(c){return{composerInput:[c.composerFill],sendButton:[c.composerFill],userBubble:[c.bubbleUser],assistantBubble:[c.chatGround,c.surfaceCream],vetBubble:[c.bubbleVet],recordCard:[c.surface],vetVisitButton:[c.primary],primaryButton:[c.brand],link:linkGrounds(c),header:[c.surface,c.background,c.chatGround],banner:[flattenOnto(c.badgeBgInfo,c.surface)??c.surface,flattenOnto(c.badgeBgCaution,c.surface)??c.surface,c.surface],chip:[c.chatGround,c.surface,c.background,c.surfaceCream],card:[c.surface],input:[c.surface,c.composerFill,c.surfaceCream,c.surfaceSubtle],tab:[c.surface,c.background],bookingStep:[c.surface,c.background],dialog:[c.surface],cartBar:[c.brand],planCard:[c.surface],planReasonLabel:[c.surface]}}function slotSurrounds(c){return{userBubble:[c.chatGround],assistantBubble:[c.chatGround],vetBubble:[c.chatGround],sendButton:[c.composerFill],vetVisitButton:[c.surfaceCream,c.surface,c.chatGround],primaryButton:[c.surface,c.surfaceCream]}}var APPEARANCE_PRESET_NAMES=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),APPEARANCE_PRESETS=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),APPEARANCE_SIZE_RANGES=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function isRecord2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isPreset(value){return typeof value=="string"&&APPEARANCE_PRESET_NAMES.includes(value.trim().toLowerCase())}function present(vars,key){let value=vars[key];return value??void 0}var PX_MAX_LENGTH=16;function parsePx(value){if(typeof value=="number")return Number.isFinite(value)?value:void 0;if(typeof value!="string"||value.length>PX_MAX_LENGTH)return;let match=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(value.trim());return match===null?void 0:Number(match[1])}var COLOR_VARIABLES=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],STATUS_VARIABLES=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],PASSTHROUGH_VARIABLES=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],STRING_VARIABLES=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],SIZE_VARIABLES=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(appearance){if(!isRecord2(appearance))return null;let preset=isPreset(appearance.theme)?APPEARANCE_PRESETS[appearance.theme.trim().toLowerCase()]:{},own=isRecord2(appearance.variables)?appearance.variables:{},vars={...preset};for(let[key,value]of Object.entries(own))value!=null&&(vars[key]=value);let out={},scheme=present(vars,"colorScheme"),schemeName=typeof scheme=="string"?scheme.trim().toLowerCase():null;(schemeName==="light"||schemeName==="dark"||schemeName==="auto")&&(out.color_scheme=schemeName);let suffix=schemeName==="dark"?"_dark":"";for(let[variable,field]of COLOR_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}for(let[variable,field]of STATUS_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}for(let[variable,field]of STRING_VARIABLES){let value=present(vars,variable);typeof value=="string"&&value.trim().length>0&&(out[field]=value.trim())}for(let[variable,field]of SIZE_VARIABLES){let px=parsePx(present(vars,variable));px!==void 0&&(out[field]=px)}for(let[variable,field]of PASSTHROUGH_VARIABLES){let value=present(vars,variable);(typeof value=="number"||typeof value=="string")&&(out[field]=value)}let fonts=appearance.fonts;Array.isArray(fonts)&&fonts.length>0&&(out.font_sources=fonts);let rules=appearance.rules;if(isRecord2(rules)){let slots={};for(let name of THEME_SLOT_NAMES){let paint=rules[name];isRecord2(paint)&&(slots[name]=paint)}Object.keys(slots).length>0&&(out.slots=slots)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var DEFAULT_PRESENTATION=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark"}),PRESENTATION_WIRE_NAMES=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button"}),FIELDS=Object.keys(PRESENTATION_WIRE_NAMES),PRESENTATION_LOCK="presentation",PRESENTATION_LOCK_PREFIX="presentation.";function isPresentationLockName(name){if(name===PRESENTATION_LOCK)return true;if(!name.startsWith(PRESENTATION_LOCK_PREFIX))return false;let field=name.slice(PRESENTATION_LOCK_PREFIX.length);return Object.values(PRESENTATION_WIRE_NAMES).includes(field)}var ENUMS={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},BOOLS=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner"]);function parseField(field,value){if(value==null)return;let allowed=ENUMS[field];return allowed!==void 0?typeof value=="string"&&allowed.includes(value)?value:void 0:BOOLS.has(field)?typeof value=="boolean"?value:void 0:typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=3?value:void 0}function parsePresentation(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let source=raw,out={};for(let field of FIELDS){let wire=PRESENTATION_WIRE_NAMES[field],value=Object.prototype.hasOwnProperty.call(source,wire)?source[wire]:source[field],parsed=parseField(field,value);parsed!==void 0&&(out[field]=parsed)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function isPresentationFieldLocked(field,locked){if(locked==null)return false;let one=`${PRESENTATION_LOCK_PREFIX}${PRESENTATION_WIRE_NAMES[field]}`;for(let name of locked)if(name===PRESENTATION_LOCK||name===one)return true;return false}function resolvePresentation(input){let server=parsePresentation(input?.server??null)??{},client=parsePresentation(input?.client??null)??{},locked=input?.locked?[...input.locked]:null,out={};for(let field of FIELDS){let fromServer=server[field],fromClient=isPresentationFieldLocked(field,locked)?void 0:client[field];out[field]=fromClient??fromServer??DEFAULT_PRESENTATION[field]}/* @__PURE__ */
|
|
128
|
+
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base2={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base2.disabled=d.disabled),/* @__PURE__ */Object.freeze(base2)}function deliverClientEvent(handler,event){if(typeof handler=="function")try{let result=handler(event);result!==null&&typeof result=="object"&&typeof result.then=="function"&&result.then(void 0,reportHandlerFailure)}catch(error){reportHandlerFailure(error)}}function reportHandlerFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] onEvent threw; the SDK ignored it.",error)}catch{}}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function setPetRegistrationTenant(runtime,tenant){tenants.set(runtime,tenant)}function petRegistrationKey(runtime,auth,petRef2,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef2}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending2=inFlight.get(key);if(pending2!==void 0)return pending2;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function notifyPetsChanged(runtime){let set=listeners.get(runtime);if(set!==void 0)for(let listener of[...set])try{listener()}catch{}}var inFlight2=/* @__PURE__ */new Map;function sharedTokenProvider(scope,getToken){return()=>{let pending2=inFlight2.get(scope);if(pending2!==void 0)return pending2;let mint;try{mint=Promise.resolve(getToken())}catch(error){mint=Promise.reject(error)}let settled=mint.finally(()=>{inFlight2.get(scope)===settled&&inFlight2.delete(scope)});return inFlight2.set(scope,settled),settled}}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel2){return channel2<=.03928?channel2/12.92:Math.pow((channel2+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix3=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix3(fg.r,bg.r),g:mix3(fg.g,bg.g),b:mix3(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix3=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix3(from.r,to.r),mix3(from.g,to.g),mix3(from.b,to.b));if(reads(candidate))return candidate}return pole}function rgbToHsl(r,g,b){let rn=r/255,gn=g/255,bn=b/255,mx=Math.max(rn,gn,bn),mn=Math.min(rn,gn,bn),l=(mx+mn)/2;if(mx===mn)return{h:0,s:0,l:l};let d=mx-mn,s=d/(1-Math.abs(2*l-1)),h;return mx===rn?(h=(gn-bn)/d*60,h<0&&(h=h+360)):mx===gn?h=((bn-rn)/d+2)*60:h=((rn-gn)/d+4)*60,{h:h,s:s,l:l}}function hslToRgb(hsl){let{h:h,s:s,l:l}=hsl,c=(1-Math.abs(2*l-1))*s,hp=h/60,x=c*(1-Math.abs(hp%2-1)),m=l-c/2,sector=Math.floor(hp)%6,rgb1=[[c,x,0],[x,c,0],[0,c,x],[0,x,c],[x,0,c],[c,0,x]],[r1,g1,b1]=rgb1[sector];return{r:channel(r1+m),g:channel(g1+m),b:channel(b1+m)}}function channel(v){return Math.min(255,Math.max(0,Math.floor(v*255+.5)))}var THEME_SLOT_NAMES=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog","cartBar","planCard","planReasonLabel"]),THEME_SLOT_KEYS=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),THEME_SLOT_KEYS_BY_SLOT=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"])});function themeSlotKeysFor(name){return THEME_SLOT_KEYS_BY_SLOT[name]??THEME_SLOT_KEYS}var SLOT_MIN_CONTRAST=4.5,EMPTY=/* @__PURE__ */Object.freeze({});function isSlotName(value){return THEME_SLOT_NAMES.includes(value)}function parseRadius(value){let text3=typeof value=="string"&&value.length<=16?value.trim().replace(/ ?px$/i,""):null,n=typeof value=="number"?value:text3!==null&&text3.length>0?Number(text3):Number.NaN;return Number.isFinite(n)?Math.max(0,n):null}function parseThemeSlots(json){if(json===null||typeof json!="object"||Array.isArray(json))return null;let out={},any=false;for(let[name,raw]of Object.entries(json)){if(!isSlotName(name)||raw===null||typeof raw!="object")continue;let parsed=parseSlot(raw);if(parsed===null)continue;let slot=restrictSlotKeys(name,parsed);slot!==null&&(out[name]=slot,any=true)}return any?/* @__PURE__ */Object.freeze(out):null}function restrictSlotKeys(name,slot){let allowed=THEME_SLOT_KEYS_BY_SLOT[name];if(allowed===void 0)return slot;let out={};for(let key of allowed)slot[key]!==void 0&&(out[key]=slot[key]);return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function pick2(raw,snake,camel2){return raw[snake]!==void 0?raw[snake]:raw[camel2]}function parseSlot(raw){let slot={},backgroundColor=parseColor(pick2(raw,"background_color","backgroundColor"));backgroundColor!==null&&(slot.backgroundColor=backgroundColor);let borderColor=parseColor(pick2(raw,"border_color","borderColor"));borderColor!==null&&(slot.borderColor=borderColor);let borderRadius=parseRadius(pick2(raw,"border_radius","borderRadius"));borderRadius!==null&&(slot.borderRadius=borderRadius);let textColor=parseColor(pick2(raw,"text_color","textColor"));return textColor!==null&&(slot.textColor=textColor),Object.keys(slot).length===0?null:/* @__PURE__ */Object.freeze(slot)}function mergeThemeSlots(base2,over){return over===null||Object.keys(over).length===0?base2??EMPTY:base2===null||Object.keys(base2).length===0?over:/* @__PURE__ */Object.freeze({...base2,...over})}function isOpaque(color){let rgba=toRgba(color);return rgba!==null&&rgba.a>=1}var SLOT_MIN_BORDER_CONTRAST=3,DECORATIVE_EDGE_SLOTS=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function sameColor(a,b){let left=parseColor(a);return left!==null&&left===parseColor(b)}function boundaryFor(fill2,surrounds,seats=[]){if(surrounds.length===0)return null;let shown=surrounds.map(ground=>flattenOnto(fill2,ground)??fill2);if(surrounds.every((ground,index)=>contrastRatio(shown[index],ground)>=SLOT_MIN_BORDER_CONTRAST))return null;let against=[...surrounds,...shown,...seats];return pushToContrast(shown[0],against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST)}function seatsOf(background,defaults){return background===void 0?defaults:defaults.length===0?[background]:defaults.map(ground=>flattenOnto(background,ground)??ground)}function someInkReads(seats,target){let pole=poleForGrounds(seats);return seats.every(seat=>contrastRatio(pole,seat)>=target)}function collapseUnsatisfiableFill(background,defaults){let ground=defaults[0];return ground===void 0?null:flattenOnto(background,ground)}function inkFor(seats){let pick5=legibleOn(seats[0],SLOT_MIN_CONTRAST);return seats.every(seat=>contrastRatio(pick5,seat)>=SLOT_MIN_CONTRAST)?pick5:poleForGrounds(seats)}function edgeShowsTheControl(name,edge,fill2,around,melts){return DECORATIVE_EDGE_SLOTS.has(name)?false:melts?true:fill2!==void 0&&sameColor(edge,fill2)?false:!(around!==void 0&&fill2!==void 0&&isOpaque(fill2))}function guardSlotContrast(slots,grounds2,surrounds){let changed=false,out={};for(let name of THEME_SLOT_NAMES){let slot=slots[name];if(slot===void 0)continue;let bg=slot.backgroundColor,defaults=grounds2?.[name]??[],seats=seatsOf(bg,defaults),next={...slot},fixed=false;if(bg!==void 0&&seats.length>1&&!someInkReads(seats,SLOT_MIN_CONTRAST)){let opaque=collapseUnsatisfiableFill(bg,defaults);opaque!==null&&(next.backgroundColor=opaque,seats=[opaque],fixed=true)}let around=surrounds?.[name],fill2=next.backgroundColor,melts=around!==void 0&&fill2!==void 0&&isOpaque(fill2)&&boundaryFor(fill2,around,seats)!==null;if(seats.length>0){let ink=slot.textColor;if(bg!==void 0)(ink===void 0||seats.some(seat=>contrastRatio(ink,seat)<SLOT_MIN_CONTRAST))&&(next.textColor=inkFor(seats),fixed=true);else if(ink!==void 0){let legible=pushToContrast(ink,seats,poleForGrounds(seats),SLOT_MIN_CONTRAST);legible!==ink&&(next.textColor=legible,fixed=true)}if(slot.borderColor!==void 0&&edgeShowsTheControl(name,slot.borderColor,fill2,around,melts)){let against=melts?[...seats,...around??[]]:seats,edge=pushToContrast(slot.borderColor,against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST);edge!==slot.borderColor&&(next.borderColor=edge,fixed=true)}}if(melts&&fill2!==void 0&&around!==void 0&&next.borderColor===void 0){let edge=boundaryFor(fill2,around,seats);edge!==null&&(next.borderColor=edge,fixed=true)}out[name]=fixed?/* @__PURE__ */Object.freeze(next):slot,changed=changed||fixed}return changed?/* @__PURE__ */Object.freeze(out):slots}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});function textGrounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function controlGrounds(c){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill]}function brandReadsOnControls(c){return controlGrounds(c).every(ground=>contrastRatio(c.brand,ground)>=SLOT_MIN_BORDER_CONTRAST)}function linkGrounds(c){return[c.chatGround,c.surface,c.surfaceCream]}function statusGrounds(c,wash2){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill,...washGrounds(c,wash2)]}function washGrounds(c,wash2){return[flattenOnto(wash2,c.surface)??c.surface,flattenOnto(wash2,c.surfaceCream)??c.surfaceCream]}function composerGrounds(c){return[c.composerFill,c.chatGround]}var AUTHORED_AS_IS=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function onCompiledGrounds(c,compiled){let own=new Set(textGrounds(compiled));return textGrounds(c).every(ground=>own.has(ground))}function guardInks(theme){let c=theme.color,compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,other=(theme.brightness==="dark"?EVERFUR_LIGHT:EVERFUR_DARK).color,grounds2=textGrounds(c),flipped=poleForGrounds(grounds2)!==poleForGrounds(textGrounds(compiled)),keepCompiled=onCompiledGrounds(c,compiled),dangerIsCompiled=c.danger===compiled.danger&&c.badgeBgCritical===compiled.badgeBgCritical,ink=(name,value,authored,twin,on,target)=>{let untouched=value===authored&&(name!=="errorRed"||dangerIsCompiled);return untouched&&keepCompiled&&AUTHORED_AS_IS.has(name)?value:pushToContrast(untouched&&flipped?twin:value,on,poleForGrounds(on),target)},text3=(key,on,target)=>ink(`text.${key}`,c.text[key],compiled.text[key],other.text[key],on,target),token=(key,value,on,target)=>ink(key,value,compiled[key],other[key],on,target),tint=key=>flipped&&c[key]===compiled[key]?other[key]:c[key],primary=c.primary,onPrimary=legibleOn(primary,SLOT_MIN_CONTRAST),danger=token("danger",c.danger,[...grounds2,...washGrounds(c,c.badgeBgCritical)],SLOT_MIN_CONTRAST),guarded={...c,onPrimary:onPrimary,onAccent:legibleOn(c.accent,SLOT_MIN_CONTRAST),onDanger:contrastRatio(onPrimary,danger)>=SLOT_MIN_CONTRAST?onPrimary:legibleOn(danger,SLOT_MIN_CONTRAST),brandSoft:tint("brandSoft"),brandSofter:tint("brandSofter"),brandBorder:tint("brandBorder"),borderHairlineGreen:tint("borderHairlineGreen"),brandInk:token("brandInk",c.brandInk,grounds2,SLOT_MIN_CONTRAST),linkInk:token("linkInk",theme.slots.link?.textColor??c.accent,linkGrounds(c),SLOT_MIN_CONTRAST),text:{...c.text,primary:text3("primary",grounds2,SLOT_MIN_CONTRAST),secondary:text3("secondary",grounds2,SLOT_MIN_CONTRAST),muted:text3("muted",grounds2,SLOT_MIN_CONTRAST),metaCool:text3("metaCool",grounds2,SLOT_MIN_CONTRAST),timestamp:text3("timestamp",grounds2,SLOT_MIN_CONTRAST),placeholder:text3("placeholder",controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},danger:danger,errorRed:token("errorRed",c.errorRed,statusGrounds(c,c.badgeBgCritical),SLOT_MIN_CONTRAST),warningStrong:token("warningStrong",c.warningStrong,statusGrounds(c,c.badgeBgCaution),SLOT_MIN_CONTRAST),composerBorder:token("composerBorder",c.composerBorder,composerGrounds(c),SLOT_MIN_BORDER_CONTRAST),brandBorderStrong:token("brandBorderStrong",c.brandBorderStrong,controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},accented={...guarded,...accentFamily(guarded,compiled,keepCompiled)};return{...accented,...statusInks(c,accented,compiled)}}function statusInks(merged,g,compiled){let out={},push=(value,on,target)=>pushToContrast(value,on,poleForGrounds(on),target);if((!same(merged.success,compiled.success)||!same(merged.badgeBgPositive,compiled.badgeBgPositive))&&(out.success=push(merged.success,statusGrounds(g,merged.badgeBgPositive),SLOT_MIN_CONTRAST)),(!same(merged.cautionAccent,compiled.cautionAccent)||!same(merged.badgeBgCaution,compiled.badgeBgCaution))&&(out.cautionAccent=push(merged.cautionAccent,statusGrounds(g,merged.badgeBgCaution),SLOT_MIN_CONTRAST)),isPartnerInfo(merged,compiled)){out.info=push(merged.info,statusGrounds(g,merged.badgeBgInfo),SLOT_MIN_CONTRAST);let edgeGrounds=[g.surface,g.chatGround,...washGrounds(g,merged.badgeBgInfo)];out.infoEdge=push(merged.infoEdge,edgeGrounds,SLOT_MIN_BORDER_CONTRAST)}else out.info=g.brandInk,out.badgeBgInfo=g.brandSoft,out.infoEdge=g.structureEdge;return out}function isPartnerInfo(c,compiled){return!same(c.info,compiled.info)||!same(c.badgeBgInfo,compiled.badgeBgInfo)}var HIGHLIGHT_LIGHT_TINT=.24,HIGHLIGHT_DARK_TINT=.3;function same(a,b){return parseColor(a)===parseColor(b)}function partnerHue(c,compiled){return same(c.accent,compiled.accent)?same(c.brand,compiled.brand)?null:c.brand:c.accent}function tintOver(hue,surface,tint){let wash2=withAlpha(hue,tint);return(wash2===null?null:flattenOnto(wash2,surface))??surface}function accentFamily(c,compiled,keepCompiled){let hue=partnerHue(c,compiled),controls=controlGrounds(c),controlPole=poleForGrounds(controls),darkGround=poleForGrounds([c.surface])===WHITE,everfurMarks=hue===null&&keepCompiled,highlight;everfurMarks?highlight=compiled.highlight:hue===null?highlight=darkGround?tintOver(EVERFUR_LIGHT.color.highlight,c.surface,HIGHLIGHT_DARK_TINT):EVERFUR_LIGHT.color.highlight:highlight=tintOver(hue,c.surface,darkGround?HIGHLIGHT_DARK_TINT:HIGHLIGHT_LIGHT_TINT);let onHighlight=everfurMarks?compiled.onHighlight:pushToContrast(c.text.primary,[highlight],poleForGrounds([highlight]),SLOT_MIN_CONTRAST),mark=hue===null?compiled.mark:pushToContrast(hue,controls,controlPole,SLOT_MIN_BORDER_CONTRAST),toward=brandReadsOnControls(c)?c.brand:controlPole,edge=(value,authored,compiledEdge)=>keepCompiled&&same(value,authored)?compiledEdge:pushToContrast(value,controls,toward,SLOT_MIN_BORDER_CONTRAST),primaryGrounds=[c.chatGround,c.composerFill,c.surface,c.surfaceCream],primaryEdge=primaryGrounds.every(ground=>contrastRatio(c.primary,ground)>=SLOT_MIN_BORDER_CONTRAST)?c.primary:pushToContrast(c.primary,primaryGrounds,poleForGrounds(primaryGrounds),SLOT_MIN_BORDER_CONTRAST);return{highlight:highlight,onHighlight:onHighlight,mark:mark,controlEdge:edge(c.brandBorder,compiled.brandBorder,compiled.controlEdge),structureEdge:edge(c.borderHairlineGreen,compiled.borderHairlineGreen,compiled.structureEdge),primaryEdge:primaryEdge}}var same2=(a,b)=>a!==void 0&&b!==void 0&&parseColor(a)===parseColor(b);function diffThemeAdjustments(merged,resolved){let compiled=(merged.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,m=merged.color,r=resolved.color,out=[],add=(field,role,requested,painted)=>{out.push(/* @__PURE__ */Object.freeze({field:field,role:role,requested:requested,painted:painted}))},own=(value,compiledValue)=>!same2(value,compiledValue);own(m.text.primary,compiled.text.primary)&&!same2(r.text.primary,m.text.primary)&&add("text_color","body text",m.text.primary,r.text.primary),own(m.brand,compiled.brand)&&(same2(r.brandInk,m.brand)||add("primary_color","brand text and icons",m.brand,r.brandInk),same2(r.primaryEdge,m.primary)||add("primary_color","edge of a filled control",m.primary,r.primaryEdge),!same2(r.controlEdge,m.brandBorder)&&!brandReadsOnControls({...r,brand:m.brand})&&add("primary_color","control outline",m.brand,r.controlEdge)),own(m.accent,compiled.accent)&&merged.slots.link?.textColor===void 0&&!same2(r.linkInk,m.accent)&&add("accent_color","link text",m.accent,r.linkInk),own(m.danger,compiled.danger)&&!same2(r.danger,m.danger)&&add("danger_color","error text",m.danger,r.danger),own(m.success,compiled.success)&&!same2(r.success,m.success)&&add("success_color","positive status",m.success,r.success),own(m.warningStrong,compiled.warningStrong)&&!same2(r.warningStrong,m.warningStrong)&&add("warning_color","caution text",m.warningStrong,r.warningStrong),own(m.cautionAccent,compiled.cautionAccent)&&!same2(r.cautionAccent,m.cautionAccent)&&add("warning_color","caution accent",m.cautionAccent,r.cautionAccent),(own(m.info,compiled.info)||own(m.badgeBgInfo,compiled.badgeBgInfo))&&(same2(r.info,m.info)||add("info_color","information text",m.info,r.info),same2(r.infoEdge,m.infoEdge)||add("info_color","information outline",m.infoEdge,r.infoEdge));for(let name of THEME_SLOT_NAMES){let before=merged.slots[name],after=resolved.slots[name];before===void 0||after===void 0||before===after||(after.backgroundColor!==void 0&&!same2(after.backgroundColor,before.backgroundColor)&&add(`slots.${name}.background_color`,"fill",before.backgroundColor??null,after.backgroundColor),before.textColor!==void 0&&after.textColor!==void 0&&!same2(after.textColor,before.textColor)&&add(`slots.${name}.text_color`,"text",before.textColor??null,after.textColor),after.borderColor!==void 0&&!same2(after.borderColor,before.borderColor)&&add(`slots.${name}.border_color`,"outline",before.borderColor??null,after.borderColor))}/* @__PURE__ */
|
|
129
|
+
return Object.freeze(out)}var warned=/* @__PURE__ */new Set;function warnThemeAdjustments(adjustments){if(adjustments.length===0)return;let message=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${adjustments.map(a=>` ${a.field} (${a.role}): ${a.requested??"not set"} -> ${a.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(warned.has(message))return;warned.add(message);let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}var DARK_VARIANT_GROUND="#23272C",DARK_VARIANT_TARGET_RATIO=4.5,DARK_VARIANT_LIGHTNESS_FLOOR=.6,DARK_VARIANT_LIGHTNESS_CEILING=.9,DARK_VARIANT_LIGHTNESS_STEP=.02,WHITE_INK="#FFFFFF",NEAR_BLACK_INK="#111111";function readsOnDark(candidate){return contrastRatio(candidate,DARK_VARIANT_GROUND)>=DARK_VARIANT_TARGET_RATIO&&Math.max(contrastRatio(candidate,WHITE_INK),contrastRatio(candidate,NEAR_BLACK_INK))>=DARK_VARIANT_TARGET_RATIO}function deriveDarkVariant(color){let rgba=toRgba(color);if(rgba===null)return null;let{h:h,s:s,l:l}=rgbToHsl(rgba.r,rgba.g,rgba.b),lDark=Math.min(Math.max(l,DARK_VARIANT_LIGHTNESS_FLOOR),DARK_VARIANT_LIGHTNESS_CEILING);for(let i=0;;i+=1){let li=lDark+i*DARK_VARIANT_LIGHTNESS_STEP;if(li>DARK_VARIANT_LIGHTNESS_CEILING)break;let rgb=hslToRgb({h:h,s:s,l:li}),candidate=rgbToHex(rgb.r,rgb.g,rgb.b);if(readsOnDark(candidate))return candidate}let ceiling=hslToRgb({h:h,s:s,l:DARK_VARIANT_LIGHTNESS_CEILING});return rgbToHex(ceiling.r,ceiling.g,ceiling.b)}var HIGH_CONTRAST_TARGET_RATIO=7,PUSH_STEP2=.05,BLACK2="#000000",WHITE2="#FFFFFF";function pushContrast(color,ground,pole,target){let flat=flattenOnto(color,ground);if(flat===null)return pole;if(contrastRatio(flat,ground)>=target)return flat;let from=toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP2;step+=1){let t=step*PUSH_STEP2,mix3=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix3(from.r,to.r),mix3(from.g,to.g),mix3(from.b,to.b));if(contrastRatio(candidate,ground)>=target)return candidate}return pole}function hardestGround(color,dark){let grounds2=textGrounds(color),pick5=grounds2[0],pickLum=luminanceOf(pick5);for(let ground of grounds2){let lum=luminanceOf(ground);(dark?lum>pickLum:lum<pickLum)&&(pick5=ground,pickLum=lum)}return pick5}function luminanceOf(color){let rgba=toRgba(color);return rgba===null?0:relativeLuminance(rgba)}function solid(wash2,surface){return flattenOnto(wash2,surface)??parseColor(wash2)??surface}function deriveHighContrast(theme){let c=theme.color,lightInk=poleForGrounds(textGrounds(c))===WHITE2,pole=lightInk?WHITE2:BLACK2,ground=hardestGround(c,lightInk),text3=color2=>pushContrast(color2,ground,pole,HIGH_CONTRAST_TARGET_RATIO),color={...c,brandSoft:solid(c.brandSoft,c.surface),brandSofter:solid(c.brandSofter,c.surface),brandBorder:text3(c.brandBorder),borderHairlineGreen:text3(c.borderHairlineGreen),brandBorderStrong:text3(c.brandBorderStrong),controlEdge:text3(c.controlEdge),structureEdge:text3(c.structureEdge),brandInk:text3(c.brandInk),linkInk:text3(c.linkInk),borderRingCream:text3(c.borderRingCream),composerBorder:text3(c.composerBorder),text:{primary:text3(c.text.primary),secondary:text3(c.text.secondary),muted:text3(c.text.muted),placeholder:text3(c.text.placeholder),onBrand:c.text.onBrand,metaCool:text3(c.text.metaCool),timestamp:text3(c.text.timestamp)},badgeBgPositive:solid(c.badgeBgPositive,c.surface),badgeBgCaution:solid(c.badgeBgCaution,c.surface),badgeBgCritical:solid(c.badgeBgCritical,c.surface),badgeBgNeutral:solid(c.badgeBgNeutral,c.surface),checkupCardLowRiskBg:solid(c.checkupCardLowRiskBg,c.surface),checkupCardConcernBg:solid(c.checkupCardConcernBg,c.surface),info:text3(c.info),infoEdge:text3(c.infoEdge),badgeBgInfo:solid(c.badgeBgInfo,c.surface)};return deepFreeze({...theme,highContrast:true,color:color})}var BACKGROUND_STEPS=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),CREAM_STEP=BACKGROUND_STEPS.cream,SUBTLE_STEP=BACKGROUND_STEPS.subtle,RING_STEP=BACKGROUND_STEPS.ring,MIN_DERIVED_TYPE_SIZE=10;function mix(color,toward,t){let from=toRgba(color),to=toRgba(toward);if(from===null||to===null)return null;let at=(a,b)=>Math.round(a+(b-a)*t);return rgbToHex(at(from.r,to.r),at(from.g,to.g),at(from.b,to.b))}function surfaceFamily(background){if(background===null)return{};let pole=poleForGrounds([background]),cream=mix(background,pole,CREAM_STEP),subtle=mix(background,pole,SUBTLE_STEP),ring=mix(background,pole,RING_STEP);return cream===null||subtle===null||ring===null?{}:{surface:background,background:background,chatGround:background,bubbleAssistant:background,surfaceCream:cream,composerFill:cream,surfaceSubtle:subtle,skeleton:subtle,borderRingCream:ring}}function dangerFamily(danger){if(danger===null)return{};let rgba=toRgba(danger);return rgba===null?{}:{danger:danger,errorRed:danger,badgeBgCritical:`rgba(${rgba.r},${rgba.g},${rgba.b},0.12)`}}function typeSizesFor(base2,current,compiled){if(base2===null)return current;let factor=base2/compiled.type.size.body;if(factor===1)return compiled.type.size;let out={};for(let[key,value]of Object.entries(compiled.type.size))out[key]=Math.max(MIN_DERIVED_TYPE_SIZE,Math.round(value*factor*10)/10);return out}function spaceFor(unit,current,compiled){if(unit===null)return current;let factor=unit/compiled.space.xs,s=n=>Math.round(n*factor),c=compiled.space;return{xs:s(c.xs),sm:s(c.sm),md:s(c.md),lg:s(c.lg),xl:s(c.xl),xxl:s(c.xxl)}}function radiiFor(base2,compiled){let factor=base2/compiled.radius.md,s=n=>Math.round(n*factor),r=compiled.radius;return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var STATUS_WASH=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function wash(color,alpha){let rgba=toRgba(color);return rgba===null?null:`rgba(${rgba.r},${rgba.g},${rgba.b},${alpha})`}function successFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.success.dark:STATUS_WASH.success.light),card=wash(color,dark?STATUS_WASH.successCard.dark:STATUS_WASH.successCard.light);return badge===null||card===null?{}:{success:color,badgeBgPositive:badge,checkupCardLowRiskBg:card}}function warningFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.warning.dark:STATUS_WASH.warning.light);return badge===null?{}:{warningStrong:color,cautionAccent:color,badgeBgCaution:badge}}function infoFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.info.dark:STATUS_WASH.info.light);return badge===null?{}:{info:color,infoEdge:color,badgeBgInfo:badge}}function lineHeightsFor(lineHeight,current,compiled){if(lineHeight===null)return current;let c=compiled.type.lineHeight,factor=lineHeight/c.normal;if(factor===1)return c;let s=n=>Math.round(n*factor*100)/100;return{tight:s(c.tight),snug:s(c.snug),normal:s(c.normal),relaxed:s(c.relaxed)}}function slotGrounds(c){return{composerInput:[c.composerFill],sendButton:[c.composerFill],userBubble:[c.bubbleUser],assistantBubble:[c.chatGround,c.surfaceCream],vetBubble:[c.bubbleVet],recordCard:[c.surface],vetVisitButton:[c.primary],primaryButton:[c.brand],link:linkGrounds(c),header:[c.surface,c.background,c.chatGround],banner:[flattenOnto(c.badgeBgInfo,c.surface)??c.surface,flattenOnto(c.badgeBgCaution,c.surface)??c.surface,c.surface],chip:[c.chatGround,c.surface,c.background,c.surfaceCream],card:[c.surface],input:[c.surface,c.composerFill,c.surfaceCream,c.surfaceSubtle],tab:[c.surface,c.background],bookingStep:[c.surface,c.background],dialog:[c.surface],cartBar:[c.brand],planCard:[c.surface],planReasonLabel:[c.surface]}}function slotSurrounds(c){return{userBubble:[c.chatGround],assistantBubble:[c.chatGround],vetBubble:[c.chatGround],sendButton:[c.composerFill],vetVisitButton:[c.surfaceCream,c.surface,c.chatGround],primaryButton:[c.surface,c.surfaceCream]}}var APPEARANCE_PRESET_NAMES=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),APPEARANCE_PRESETS=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),APPEARANCE_SIZE_RANGES=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function isRecord2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isPreset(value){return typeof value=="string"&&APPEARANCE_PRESET_NAMES.includes(value.trim().toLowerCase())}function present(vars,key){let value=vars[key];return value??void 0}var PX_MAX_LENGTH=16;function parsePx(value){if(typeof value=="number")return Number.isFinite(value)?value:void 0;if(typeof value!="string"||value.length>PX_MAX_LENGTH)return;let match=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(value.trim());return match===null?void 0:Number(match[1])}var COLOR_VARIABLES=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],STATUS_VARIABLES=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],PASSTHROUGH_VARIABLES=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],STRING_VARIABLES=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],SIZE_VARIABLES=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(appearance){if(!isRecord2(appearance))return null;let preset=isPreset(appearance.theme)?APPEARANCE_PRESETS[appearance.theme.trim().toLowerCase()]:{},own=isRecord2(appearance.variables)?appearance.variables:{},vars={...preset};for(let[key,value]of Object.entries(own))value!=null&&(vars[key]=value);let out={},scheme=present(vars,"colorScheme"),schemeName=typeof scheme=="string"?scheme.trim().toLowerCase():null;(schemeName==="light"||schemeName==="dark"||schemeName==="auto")&&(out.color_scheme=schemeName);let suffix=schemeName==="dark"?"_dark":"";for(let[variable,field]of COLOR_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}for(let[variable,field]of STATUS_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}for(let[variable,field]of STRING_VARIABLES){let value=present(vars,variable);typeof value=="string"&&value.trim().length>0&&(out[field]=value.trim())}for(let[variable,field]of SIZE_VARIABLES){let px=parsePx(present(vars,variable));px!==void 0&&(out[field]=px)}for(let[variable,field]of PASSTHROUGH_VARIABLES){let value=present(vars,variable);(typeof value=="number"||typeof value=="string")&&(out[field]=value)}let fonts=appearance.fonts;Array.isArray(fonts)&&fonts.length>0&&(out.font_sources=fonts);let rules=appearance.rules;if(isRecord2(rules)){let slots={};for(let name of THEME_SLOT_NAMES){let paint=rules[name];isRecord2(paint)&&(slots[name]=paint)}Object.keys(slots).length>0&&(out.slots=slots)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var DEFAULT_PRESENTATION=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true}),PRESENTATION_WIRE_NAMES=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask"}),FIELDS=Object.keys(PRESENTATION_WIRE_NAMES),PRESENTATION_LOCK="presentation",PRESENTATION_LOCK_PREFIX="presentation.";function isPresentationLockName(name){if(name===PRESENTATION_LOCK)return true;if(!name.startsWith(PRESENTATION_LOCK_PREFIX))return false;let field=name.slice(PRESENTATION_LOCK_PREFIX.length);return Object.values(PRESENTATION_WIRE_NAMES).includes(field)}var ENUMS={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},BOOLS=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk"]);function parseField(field,value){if(value==null)return;let allowed=ENUMS[field];return allowed!==void 0?typeof value=="string"&&allowed.includes(value)?value:void 0:BOOLS.has(field)?typeof value=="boolean"?value:void 0:typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=3?value:void 0}function parsePresentation(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let source=raw,out={};for(let field of FIELDS){let wire=PRESENTATION_WIRE_NAMES[field],value=Object.prototype.hasOwnProperty.call(source,wire)?source[wire]:source[field],parsed=parseField(field,value);parsed!==void 0&&(out[field]=parsed)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function isPresentationFieldLocked(field,locked){if(locked==null)return false;let one=`${PRESENTATION_LOCK_PREFIX}${PRESENTATION_WIRE_NAMES[field]}`;for(let name of locked)if(name===PRESENTATION_LOCK||name===one)return true;return false}function resolvePresentation(input){let server=parsePresentation(input?.server??null)??{},client=parsePresentation(input?.client??null)??{},locked=input?.locked?[...input.locked]:null,out={};for(let field of FIELDS){let fromServer=server[field],fromClient=isPresentationFieldLocked(field,locked)?void 0:client[field];out[field]=fromClient??fromServer??DEFAULT_PRESENTATION[field]}/* @__PURE__ */
|
|
130
130
|
return Object.freeze(out)}var LINE_HEIGHT_RANGE=/* @__PURE__ */Object.freeze({min:1,max:2}),FAMILY_MAX_LENGTH=100,URL_MAX_LENGTH=2048,WEIGHTS=["100","200","300","400","500","600","700","800","900"];function finiteNumber(value){if(typeof value=="number")return Number.isFinite(value)?value:null;if(typeof value!="string"||value.trim().length===0||value.length>16)return null;let n=Number(value.trim());return Number.isFinite(n)?n:null}function parseFontWeight(value){let n=finiteNumber(value);if(n===null)return null;let name=String(n);return WEIGHTS.includes(name)?name:null}function parseLineHeight(value){let n=finiteNumber(value);return n===null?null:Math.min(LINE_HEIGHT_RANGE.max,Math.max(LINE_HEIGHT_RANGE.min,n))}function fontSourceUrl(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>URL_MAX_LENGTH?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(trimmed)?trimmed:null}function familyName(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>FAMILY_MAX_LENGTH||/[\u0000-\u001F\u007F]/.test(trimmed)?null:trimmed}function isRecord3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function pick3(raw,...keys){for(let key of keys)if(raw[key]!==void 0&&raw[key]!==null)return raw[key]}function parseFontSource(raw){if(!isRecord3(raw))return null;let family=familyName(raw.family);if(family===null)return null;let srcRaw=pick3(raw,"src"),cssRaw=pick3(raw,"cssSrc","css_src");if(srcRaw===void 0==(cssRaw===void 0))return null;if(cssRaw!==void 0){let cssSrc=fontSourceUrl(cssRaw);return cssSrc===null?null:/* @__PURE__ */Object.freeze({family:family,cssSrc:cssSrc})}let src=fontSourceUrl(srcRaw);if(src===null)return null;let out={family:family,src:src},weight=parseFontWeight(raw.weight);weight!==null&&(out.weight=weight);let style=typeof raw.style=="string"?raw.style.trim().toLowerCase():null;return(style==="normal"||style==="italic")&&(out.style=style),/* @__PURE__ */Object.freeze(out)}function parseFontSources(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(out.length>=4)break;let source=parseFontSource(entry);source!==null&&out.push(source)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var LOCKABLE_THEME_FIELDS=/* @__PURE__ */Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit","success_color","success_color_dark","warning_color","warning_color_dark","info_color","info_color_dark","heading_font_family","font_weight_body","font_weight_heading","line_height","assistant_avatar_url","font_sources"]),SLOT_LOCK_PREFIX="slots.",THEME_SCHEMA_VERSIONS=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(b){return Object.keys(b).every(key=>key==="schemaVersion"||(b[key]??null)===null)}function isKnownBrandingSchema(b){let version=b?.schemaVersion??null;return version===null||THEME_SCHEMA_VERSIONS.includes(version)}function lockedFieldsOf(b){/* @__PURE__ */
|
|
131
131
|
return new Set(["hide_powered_by",...b?.lockedFields??[]])}function isThemeLockName(name){return name==="hide_powered_by"||LOCKABLE_THEME_FIELDS.includes(name)||isPresentationLockName(name)?true:name.startsWith(SLOT_LOCK_PREFIX)&&THEME_SLOT_NAMES.includes(name.slice(SLOT_LOCK_PREFIX.length))}function parseClientBranding(json){if(json===null||typeof json!="object")return null;let raw=json,flat=parseFlat(raw),expanded=expandAppearance(pick4(raw,"appearance")),branding=expanded===null?flat:overlayFlat(parseFlat(expanded),flat);return isEmptyBranding(branding)?null:/* @__PURE__ */Object.freeze(branding)}function overlayFlat(base2,over){let out={...base2};for(let[key,value]of Object.entries(over))value!=null&&(out[key]=value);let slots=mergeThemeSlots(base2.slots??null,over.slots??null);return out.slots=Object.keys(slots).length===0?null:slots,out}function parseFlat(raw){return{displayName:parseNonEmptyString(pick4(raw,"display_name","displayName")),logoUrl:parseNonEmptyString(pick4(raw,"logo_url","logoUrl")),primaryColor:parseColor(pick4(raw,"primary_color","primaryColor")),accentColor:parseColor(pick4(raw,"accent_color","accentColor")),brightness:parseBrightness(pick4(raw,"brightness","color_scheme","colorScheme")),fontFamily:parseNonEmptyString(pick4(raw,"font_family","fontFamily")),fontUrl:parseNonEmptyString(pick4(raw,"font_url","fontUrl")),fonts:parseFaceMap(pick4(raw,"fonts")),fontUrls:parseFaceMap(pick4(raw,"font_urls","fontUrls")),placeholder:parseNonEmptyString(pick4(raw,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:parseBool(pick4(raw,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(pick4(raw,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(pick4(raw,"accent_color_dark","accentColorDark")),surfaceStyle:parseEnum(pick4(raw,"surface_style","surfaceStyle"),SURFACE_STYLES),radiusScale:parseEnum(pick4(raw,"radius_scale","radiusScale"),RADIUS_SCALES),logoUrlDark:parseNonEmptyString(pick4(raw,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(pick4(raw,"slots")),accessibilityMaxFontScale:parseMaxFontScale(pick4(raw,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:parseLockedFields(pick4(raw,"locked_fields","lockedFields")),presentation:parsePresentation(pick4(raw,"presentation")),schemaVersion:parseSchemaVersion(pick4(raw,"schema_version","schemaVersion")),backgroundColor:parseColor(pick4(raw,"background_color","backgroundColor")),backgroundColorDark:parseColor(pick4(raw,"background_color_dark","backgroundColorDark")),textColor:parseColor(pick4(raw,"text_color","textColor")),textColorDark:parseColor(pick4(raw,"text_color_dark","textColorDark")),dangerColor:parseColor(pick4(raw,"danger_color","dangerColor")),dangerColorDark:parseColor(pick4(raw,"danger_color_dark","dangerColorDark")),fontSizeBase:parseClamped(pick4(raw,"font_size_base","fontSizeBase"),APPEARANCE_SIZE_RANGES.fontSizeBase),borderRadius:parseClamped(pick4(raw,"border_radius","borderRadius"),APPEARANCE_SIZE_RANGES.borderRadius),spacingUnit:parseClamped(pick4(raw,"spacing_unit","spacingUnit"),APPEARANCE_SIZE_RANGES.spacingUnit),successColor:parseColor(pick4(raw,"success_color","successColor")),successColorDark:parseColor(pick4(raw,"success_color_dark","successColorDark")),warningColor:parseColor(pick4(raw,"warning_color","warningColor")),warningColorDark:parseColor(pick4(raw,"warning_color_dark","warningColorDark")),infoColor:parseColor(pick4(raw,"info_color","infoColor")),infoColorDark:parseColor(pick4(raw,"info_color_dark","infoColorDark")),headingFontFamily:parseNonEmptyString(pick4(raw,"heading_font_family","headingFontFamily")),fontWeightBody:parseFontWeight(pick4(raw,"font_weight_body","fontWeightBody")),fontWeightHeading:parseFontWeight(pick4(raw,"font_weight_heading","fontWeightHeading")),lineHeight:parseLineHeight(pick4(raw,"line_height","lineHeight")),fontSources:parseFontSources(pick4(raw,"font_sources","fontSources")),assistantAvatarUrl:parseNonEmptyString(pick4(raw,"assistant_avatar_url","assistantAvatarUrl"))}}function parseClamped(value,range){let n=parseNumber(typeof value=="string"?value.trim().replace(/px$/i,""):value);return n===null?null:Math.min(range.max,Math.max(range.min,n))}function parseBool(value){if(typeof value=="boolean")return value;if(typeof value=="string"){let lower=value.trim().toLowerCase();if(lower==="true")return true;if(lower==="false")return false}return null}function pick4(raw,...keys){for(let key of keys)if(Object.prototype.hasOwnProperty.call(raw,key)){let value=raw[key];if(value!==void 0)return value}}function parseNonEmptyString(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}var FONT_FACE_KEYS=["regular","medium","bold","mono","monoMedium","monoBold"];function parseFaceMap(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;let raw=value,out={};for(let key of FONT_FACE_KEYS){let entry=parseNonEmptyString(pick4(raw,key));entry!==null&&(out[key]=entry)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var SURFACE_STYLES=["white","cream","subtle"],RADIUS_SCALES=["sharp","default","round"];function parseEnum(value,allowed){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return allowed.includes(lower)?lower:null}function parseBrightness(value){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return lower==="light"||lower==="dark"||lower==="auto"?lower:null}function parseNumber(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):Number.NaN;return Number.isFinite(n)&&(typeof value!="string"||value.trim().length>0)?n:null}var MAX_FONT_SCALE_FLOOR=1,MAX_FONT_SCALE_CEILING=3.1;function parseMaxFontScale(value){let n=parseNumber(value);return n===null?null:n<=0?0:Math.min(MAX_FONT_SCALE_CEILING,Math.max(MAX_FONT_SCALE_FLOOR,n))}function parseSchemaVersion(value){if(value==null)return null;let n=parseNumber(value);return n!==null&&Number.isInteger(n)&&n>=1?n:0}function toWireName(name){let trimmed=name.trim();return trimmed.startsWith(SLOT_LOCK_PREFIX)?trimmed:trimmed.startsWith(PRESENTATION_LOCK_PREFIX)?PRESENTATION_LOCK_PREFIX+trimmed.slice(PRESENTATION_LOCK_PREFIX.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():trimmed.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function parseLockedFields(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(typeof entry!="string")continue;let name=toWireName(entry);isThemeLockName(name)&&!out.includes(name)&&out.push(name)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}function hardenHttpsUrl(url){if(url===null)return null;let trimmed=url.trim();return trimmed.length===0?null:/^https:\/\/\S+$/i.test(trimmed)?trimmed:null}var BRAND_ASSET_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/brand\/[0-9a-f]{16}\.(png|jpg|webp)$/;function hardenBrandAssetUrl(url){let https=hardenHttpsUrl(url);return https!==null&&BRAND_ASSET_URL.test(https)?https:null}function withServerBranding(base2,b){if(b===null||isEmptyBranding(b))return base2;let palette=(b.brightness==="light"||b.brightness==="dark")&&b.brightness!==base2.brightness?b.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT:base2,compiled=palette.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,dark=palette.brightness==="dark",primaryIn=dark?b.primaryColorDark??darkVariantOf(b.primaryColor):b.primaryColor,accentIn=dark?b.accentColorDark??darkVariantOf(b.accentColor):b.accentColor,primaryRaw=primaryIn??palette.color.primary,accent=accentIn??palette.color.accent,keepsCompiled=primaryIn!==null&&isCompiledPrimary(b,primaryRaw,compiled,dark),primary=keepsCompiled?compiled.color.primary:primaryRaw,pr=primaryIn!==null&&!keepsCompiled?toRgba(primary):null,lift=c=>Math.round(c+(255-c)*.4),brandFamily=pr!==null?{brand:primary,bubbleUser:primary,brandInk:primary,text:{...palette.color.text,secondary:primary},brandSoft:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.10)`,brandSofter:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.15)`,brandBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.20)`,borderHairlineGreen:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.28)`,brandBorderStrong:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.55)`,composerBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.75)`,accentEdge:`rgb(${lift(pr.r)}, ${lift(pr.g)}, ${lift(pr.b)})`}:keepsCompiled?compiledBrandFamily(compiled,palette.color.text):{},background=(dark?b.backgroundColorDark:b.backgroundColor)??null,grounds2=surfaceFamily(background),groundFamily={...palette.color,...grounds2},bodyInk=(dark?b.textColorDark:b.textColor)??null,status=(light,darkTwin)=>(dark?darkTwin??darkVariantOf(light??null):light)??null,next={brightness:palette.brightness,highContrast:palette.highContrast,meta:{displayName:b.displayName??palette.meta.displayName,logoUrl:(dark?b.logoUrlDark??b.logoUrl:b.logoUrl)??palette.meta.logoUrl,placeholder:b.placeholder??palette.meta.placeholder,hidePoweredBy:b.hidePoweredBy??palette.meta.hidePoweredBy,assistantAvatarUrl:b.assistantAvatarUrl??palette.meta.assistantAvatarUrl},color:{...palette.color,...brandFamily,...grounds2,...dangerFamily(status(b.dangerColor,b.dangerColorDark)),...successFamily(status(b.successColor,b.successColorDark),dark),...warningFamily(status(b.warningColor,b.warningColorDark),dark),...infoFamily(status(b.infoColor,b.infoColorDark),dark),...bodyInk!==null?{text:{...brandFamily.text??palette.color.text,primary:bodyInk}}:{},...surfaceOf(b.surfaceStyle??null,groundFamily),primary:primary,accent:accent,onPrimary:palette.color.onPrimary,onAccent:palette.color.onAccent},space:spaceFor(b.spacingUnit??null,palette.space,compiled),radius:b.borderRadius!=null?radiiFor(b.borderRadius,compiled):radiusOf(b.radiusScale??null,palette.radius,compiled),type:{...palette.type,...mergeFaces(palette.type,b),size:typeSizesFor(b.fontSizeBase??null,palette.type.size,compiled),maxScale:b.accessibilityMaxFontScale??palette.type.maxScale,lineHeight:lineHeightsFor(b.lineHeight??null,palette.type.lineHeight,compiled),weight:b.fontWeightBody==null?palette.type.weight:{...palette.type.weight,regular:b.fontWeightBody},headingFamily:b.headingFontFamily??palette.type.headingFamily,headingWeight:b.fontWeightHeading??palette.type.headingWeight,fontSources:b.fontSources??palette.type.fontSources},motion:palette.motion,slots:mergeThemeSlots(palette.slots,b.slots??null)};return deepFreeze(next)}var FACE_CHAIN={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},FACE_GROUPS=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function isMonoFace(face2){return face2==="mono"||face2==="monoMedium"||face2==="monoBold"}function mergeFaces(base2,b){let fonts=b.fonts??{},urls=b.fontUrls??{},families={...base2.families},namedFaces={...base2.namedFaces},fontUrls={...base2.fontUrls};for(let face2 of FONT_FACE_KEYS){let named=FACE_CHAIN[face2].map(key=>fonts[key]).find(name=>name!==void 0),legacy=isMonoFace(face2)?null:b.fontFamily;named!==void 0?(families[face2]=named,namedFaces[face2]=true):legacy!==null&&(families[face2]=legacy,namedFaces[face2]=false);let url=urls[face2]??(face2==="regular"?b.fontUrl:null)??null;url!==null?fontUrls[face2]=url:named!==void 0&&delete fontUrls[face2]}for(let group of FACE_GROUPS)for(let face2 of group)namedFaces[face2]&&group.some(other=>other!==face2&&families[other]===families[face2])&&(namedFaces[face2]=false);return{family:families.regular,mono:families.mono,fontUrl:fontUrls.regular??null,families:families,namedFaces:namedFaces,fontUrls:fontUrls}}function darkVariantOf(color){return color===null?null:deriveDarkVariant(color)}function surfaceOf(style,family){if(style===null)return{};let c=family;return{chatGround:style==="white"?c.surface:style==="subtle"?c.surfaceSubtle:c.surfaceCream}}function sameColor2(a,b){return a==null?false:parseColor(a)===parseColor(b)}function isCompiledPrimary(b,primary,compiled,dark){return sameColor2(primary,compiled.color.primary)?true:dark&&(b.primaryColorDark??null)===null&&sameColor2(b.primaryColor,EVERFUR_LIGHT.color.primary)}function compiledBrandFamily(compiled,text3){let c=compiled.color;return{text:{...text3,secondary:c.text.secondary},brand:c.brand,bubbleUser:c.bubbleUser,brandInk:c.brandInk,brandSoft:c.brandSoft,brandSofter:c.brandSofter,brandBorder:c.brandBorder,borderHairlineGreen:c.borderHairlineGreen,brandBorderStrong:c.brandBorderStrong,composerBorder:c.composerBorder,accentEdge:c.accentEdge}}var RADIUS_FACTOR={sharp:.5,default:1,round:1.5};function radiusOf(scale,base2,compiled){if(scale===null)return base2;let f=RADIUS_FACTOR[scale],r=compiled.radius,s=n=>Math.round(n*f);return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var DEFAULT_DISPLAY_NAME="Everfur",TEXT_SCALE_FLOOR=.5;function resolveTheme(input){return finalize(mergeLayers(input),input)}function themeAdjustments(input){let merged=mergeLayers(input);return diffThemeAdjustments(merged,finalize(merged,{...input,highContrast:false}))}function mergeLayers(input){let candidate=input?.branding??null,server=isKnownBrandingSchema(candidate)?candidate:null,client=withoutFields(input?.clientOverride??null,lockedFieldsOf(server)),device=input?.colorScheme==="dark"?"dark":"light",chosen=client?.brightness??server?.brightness??"light",withServer=withServerBranding((chosen==="auto"?device:chosen)==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,withoutBrightness(server));return withServerBranding(withServer,withoutBrightness(client))}function previewTheme(input,hints,options){return resolveTheme({...options,branding:parseClientBranding(hints),clientOverride:parseClientBranding(input)})}function wireNameOf(key){return key==="placeholder"?"chat_placeholder":toWireName(key)}var LOCK_ALIASES={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],fontSources:["font_family","heading_font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],successColorDark:["success_color"],warningColorDark:["warning_color"],infoColorDark:["info_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function isLocked(key,locked){return locked.has(wireNameOf(key))?true:(LOCK_ALIASES[key]??[]).some(name=>locked.has(name))}function withoutFields(b,locked){if(b===null)return null;let changed=false,out={...b};for(let key of Object.keys(b))(b[key]??null)!==null&&(isLocked(key,locked)||key==="lockedFields")&&(out[key]=null,changed=true);let slots=out.slots??null;if(slots!==null){let kept={},dropped=false;for(let name of THEME_SLOT_NAMES){let slot=slots[name];slot!==void 0&&(locked.has(`${SLOT_LOCK_PREFIX}${name}`)?dropped=true:kept[name]=slot)}dropped&&(out.slots=Object.keys(kept).length===0?null:/* @__PURE__ */Object.freeze(kept),changed=true)}if(!changed)return b;let stripped=/* @__PURE__ */Object.freeze(out);return isEmptyBranding(stripped)?null:stripped}function withoutBrightness(b){return b===null||b.brightness===null?b:/* @__PURE__ */Object.freeze({...b,brightness:null})}function scaledSizes(size,scale){if(scale===1)return size;let out={};for(let[key,value]of Object.entries(size))out[key]=Math.round(value*scale*10)/10;return out}function effectiveScale(textScale){return textScale===void 0||!Number.isFinite(textScale)?1:Math.max(TEXT_SCALE_FLOOR,textScale)}var SCALE_TIERS=["content","heading","control","compact","badge"];function tierCaps(maxScale){if(!(maxScale>0))return TEXT_SCALE_TIER_CAPS;let out={};for(let tier of SCALE_TIERS){let cap=TEXT_SCALE_TIER_CAPS[tier];out[tier]=cap===0?0:Math.min(cap,maxScale)}return out}function capped(scale,cap){return cap>0?Math.min(scale,cap):scale}function sizesByTier(size,scale,caps,scaleSizes){let out={};for(let tier of SCALE_TIERS)out[tier]=scaleSizes?scaledSizes(size,capped(scale,caps[tier])):size;return out}function registration(isFontRegistered,family){try{let answer=isFontRegistered(family);return answer===!0||answer===!1?answer:null}catch{return null}}function platformFaces(type,input){let isFontRegistered=input?.isFontRegistered,platformMono=input?.platformMonoFamily?.trim()||null;if(isFontRegistered===void 0&&platformMono===null)return{family:type.family,mono:type.mono,families:type.families,namedFaces:type.namedFaces,headingFamily:type.headingFamily};let headingFamily=type.headingFamily!==null&&isFontRegistered!==void 0&®istration(isFontRegistered,type.headingFamily)===false?null:type.headingFamily,families={...type.families},namedFaces={...type.namedFaces};for(let key of FONT_FACE_KEYS)!(families[key]===SYSTEM_FONT_FAMILY||families[key]===SYSTEM_MONO_FAMILY)&&isFontRegistered!==void 0&®istration(isFontRegistered,families[key])===false&&(families[key]=isMonoFace(key)?SYSTEM_MONO_FAMILY:SYSTEM_FONT_FAMILY,namedFaces[key]=false),platformMono!==null&&isMonoFace(key)&&families[key]===SYSTEM_MONO_FAMILY&&(families[key]=platformMono);return{family:families.regular,mono:families.mono,families:families,namedFaces:namedFaces,headingFamily:headingFamily}}function finalize(theme,input){let displayName=theme.meta.displayName.trim().length===0?DEFAULT_DISPLAY_NAME:theme.meta.displayName,logoUrl=hardenBrandAssetUrl(theme.meta.logoUrl),fontUrls={};for(let face2 of FONT_FACE_KEYS){let url=theme.type.fontUrls[face2];url!==void 0&&(fontUrls[face2]=hardenHttpsUrl(url))}let fontUrl=fontUrls.regular??null,motion=input?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:theme.motion.easing,reducedMotion:true}:theme.motion,maxScale=Number.isFinite(theme.type.maxScale)?theme.type.maxScale:DEFAULT_MAX_FONT_SCALE,scale=effectiveScale(input?.textScale),scaleCaps=tierCaps(maxScale),tierSizes=sizesByTier(theme.type.size,scale,scaleCaps,input?.scaleTypeSizes===true),color=guardInks(theme),finalized={brightness:theme.brightness,highContrast:false,meta:{displayName:displayName,logoUrl:logoUrl,placeholder:theme.meta.placeholder,hidePoweredBy:theme.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(theme.meta.assistantAvatarUrl)},color:color,space:theme.space,radius:theme.radius,type:{...theme.type,...platformFaces(theme.type,input),fontUrl:fontUrl,fontUrls:fontUrls,size:tierSizes.content,tierSizes:tierSizes,scale:scale,maxScale:maxScale,scaleCaps:scaleCaps},motion:motion,slots:guardSlotContrast(theme.slots,slotGrounds(color),slotSurrounds(color))};return input?.highContrast===true?deriveHighContrast(deepFreeze(finalized)):deepFreeze(finalized)}var ENTITLEMENTS_PATH="/widget/v1/entitlements",HTTP_NOT_MODIFIED=304,NOT_MODIFIED=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(auth,args={},funnel=createRequestFunnel({auth:auth})){let result=await funnel.send("entitlements.fetch",buildRequest(args));return result.ok?parseUpdated(result.value):result.error.httpStatus===HTTP_NOT_MODIFIED?NOT_MODIFIED:{kind:"failed",error:result.error}}var REGION_MAX=64;function buildRequest(args){let headers={};return isFiniteNumber(args.cachedRevision)&&(headers["if-none-match"]=`"${args.cachedRevision}"`),args.region&&args.region.length<=REGION_MAX?{method:"GET",path:ENTITLEMENTS_PATH,headers:headers,query:{region:args.region}}:{method:"GET",path:ENTITLEMENTS_PATH,headers:headers}}function parseUpdated(body){if(body===null||typeof body!="object"||!isFiniteNumber(body.revision))return malformed3();let region=typeof body.region=="string"?body.region:"",ttlSeconds=isFiniteNumber(body.ttl_seconds)?body.ttl_seconds:0;/* @__PURE__ */
|
|
132
132
|
return Object.freeze({kind:"updated",revision:body.revision,region:region,ttlSeconds:ttlSeconds,decisions:mapCapabilities(body.capabilities),branding:parseBranding(body),livemode:body.livemode!==false,...smsProfileOf(body)})}function smsProfileOf(body){let hints=body.render_hints,raw=body.sms_profile_public??(hints!==null&&typeof hints=="object"?hints.sms_profile_public:void 0);return raw!==null&&typeof raw=="object"?{smsProfilePublic:raw}:{}}function parseBranding(body){let direct=parseClientBranding(body.branding);if(direct!==null)return direct;let hints=body.render_hints;if(hints!==null&&typeof hints=="object"){let nested=parseClientBranding(hints.branding);return nested!==null?nested:parseClientBranding(hints)}return null}function mapCapabilities(capabilities){if(capabilities===null||typeof capabilities!="object")/* @__PURE__ */return Object.freeze([]);let out=[];for(let[resource,value]of Object.entries(capabilities))isEnabled(value)&&out.push(/* @__PURE__ */Object.freeze({resource:resource,granted:true}));/* @__PURE__ */
|
|
133
133
|
return Object.freeze(out)}function isEnabled(value){return typeof value=="object"&&value!==null&&value.enabled===true}function malformed3(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}var MIN_POLL_INTERVAL_SECONDS=30;function createEntitlementPoller(deps){let scheduler=deps.scheduler??defaultScheduler,resolve=deps.resolve??fetchEntitlements,floorSeconds=Math.max(1,deps.floorSeconds??MIN_POLL_INTERVAL_SECONDS),rng=deps.rng??Math.random,jitteredFloorSeconds=()=>floorSeconds+rng()*floorSeconds,started=false,stopped=false,timer=null,cachedRevision=null,lastCadenceSeconds=floorSeconds,generation=0,clearTimer=()=>{timer!==null&&(scheduler.clear(timer),timer=null)},schedule=seconds=>{stopped||!started||(lastCadenceSeconds=Math.max(floorSeconds,seconds),timer=scheduler.set(()=>{timer=null,run()},lastCadenceSeconds*1e3))},inFlight3=null,tick=async()=>{if(stopped)return null;let myGen=generation;deps.onFetch?.();let args=deps.region?{cachedRevision:cachedRevision,region:deps.region}:{cachedRevision:cachedRevision},resolution;try{resolution=await resolve(deps.authFor(),args)}catch(cause){return deps.telemetry?.track("sdk.entitlements.poll_error",{reason:describe(cause)}),!stopped&&myGen===generation&&(deps.onSettled?.(),schedule(jitteredFloorSeconds())),null}if(stopped||myGen!==generation)return null;switch(resolution.kind){case"updated":cachedRevision=resolution.revision,resolution.smsProfilePublic!==void 0?deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false,resolution.smsProfilePublic):deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false),schedule(resolution.ttlSeconds);break;case"notModified":schedule(lastCadenceSeconds);break;case"failed":deps.telemetry?.track("sdk.entitlements.poll_failed",{code:resolution.error.code}),schedule(jitteredFloorSeconds());break;default:schedule(jitteredFloorSeconds())}return deps.onSettled?.(),resolution},run=()=>{let current=tick().finally(()=>{inFlight3===current&&(inFlight3=null)});return inFlight3=current,current};return{start(){started||stopped||(started=true,run())},prime(){return stopped?Promise.resolve(null):inFlight3??run()},stop(){stopped||(stopped=true,generation++,clearTimer())},refresh(){stopped||!started||(generation++,cachedRevision=null,clearTimer(),run())}}}var defaultScheduler={set(callback,ms){let handle=setTimeout(callback,ms);return handle.unref?.(),handle},clear(handle){clearTimeout(handle)}};function describe(cause){return cause instanceof Error?cause.message:"poll failed"}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3,PER_USER_KV_KEYS=/* @__PURE__ */Object.freeze([NOTIFICATIONS_DEVICE_KV_KEY]);function startBeforeLogoutHooks(deps){let{leaving:leaving,identity:identity,hooks:hooks,telemetry:telemetry}=deps;if(leaving===null||identity===null||hooks.size===0)return null;let context=/* @__PURE__ */Object.freeze({userRef:leaving.userRef,auth:deps.graceAuth()}),runs=[...hooks].map(hook=>{try{return Promise.resolve(hook(context))}catch(cause){return Promise.reject(cause)}}),report=(reason,count2)=>{try{telemetry.track("sdk.logout.hookFailed",{reason:reason,count:count2,totalCount:runs.length})}catch{}},settled=Promise.allSettled(runs).then(outcomes=>{let failed=outcomes.filter(outcome=>outcome.status==="rejected").length;failed>0&&report("failed",failed)});return new Promise(resolve=>{let done=false,finish=()=>{done||(done=true,clearTimeout(timer),resolve())},timer=setTimeout(()=>{done||report("timeout",runs.length),finish()},LOGOUT_HOOK_BUDGET_MS);settled.then(finish,finish)})}function graceAuth(deps){let{leaving:leaving,identity:identity,transport:transport,sessionId:sessionId}=deps,token=identity.currentToken();token.catch(()=>{});let frozen={userRef:leaving.userRef,currentToken:()=>token,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:transport,identity:frozen,userRef:leaving.userRef,sessionId:sessionId}}async function sweepPerUserKv(kv,telemetry){if(PER_USER_KV_KEYS.length===0)return;let results=await Promise.allSettled(PER_USER_KV_KEYS.map(key=>kv.removeItem(key))),failedCount=results.filter(result=>result.status==="rejected").length;failedCount>0&&telemetry.track("sdk.logout.sweepPartialFailure",{failedCount:failedCount,totalCount:results.length})}function compiledDefaultDecisions(){/* @__PURE__ */
|
|
134
|
-
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function createEntitlementStore(floorDecisions=compiledDefaultDecisions){let listeners3=/* @__PURE__ */new Set,snapshot2=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit=()=>{for(let listener of listeners3)listener()};return{subscribe(listener){return listeners3.add(listener),()=>{listeners3.delete(listener)}},getSnapshot(){return snapshot2},set(next){snapshot2=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...next.decisions]),isPending:next.isPending,branding:next.branding??null,...next.livemode===false?{livemode:false}:{},...next.smsProfilePublic!==void 0&&next.smsProfilePublic!==null?{smsProfilePublic:next.smsProfilePublic}:{}}),emit()},reset(opts){snapshot2=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:opts?.keepBranding===true?snapshot2.branding??null:null,...opts?.keepBranding===true&&snapshot2.smsProfilePublic!==void 0?{smsProfilePublic:snapshot2.smsProfilePublic}:{}}),emit()},setPending(
|
|
134
|
+
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function createEntitlementStore(floorDecisions=compiledDefaultDecisions){let listeners3=/* @__PURE__ */new Set,snapshot2=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit=()=>{for(let listener of listeners3)listener()};return{subscribe(listener){return listeners3.add(listener),()=>{listeners3.delete(listener)}},getSnapshot(){return snapshot2},set(next){snapshot2=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...next.decisions]),isPending:next.isPending,branding:next.branding??null,...next.livemode===false?{livemode:false}:{},...next.smsProfilePublic!==void 0&&next.smsProfilePublic!==null?{smsProfilePublic:next.smsProfilePublic}:{}}),emit()},reset(opts){snapshot2=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:opts?.keepBranding===true?snapshot2.branding??null:null,...opts?.keepBranding===true&&snapshot2.smsProfilePublic!==void 0?{smsProfilePublic:snapshot2.smsProfilePublic}:{}}),emit()},setPending(pending2){snapshot2.isPending!==pending2&&(snapshot2=/* @__PURE__ */Object.freeze({...snapshot2,isPending:pending2}),emit())}}}var BRANDING_CACHE_KEY_PREFIX="everfur.branding.v1.";function utf8Bytes(text3){let out=[];for(let ch of text3){let cp=ch.codePointAt(0);cp<128?out.push(cp):cp<2048?out.push(192|cp>>6,128|cp&63):cp<65536?out.push(224|cp>>12,128|cp>>6&63,128|cp&63):out.push(240|cp>>18,128|cp>>12&63,128|cp>>6&63,128|cp&63)}return out}function fnv1a64Hex(text3){let hi=3421674724,lo=2216829733;for(let byte2 of utf8Bytes(text3)){lo=(lo^byte2)>>>0;let loProduct=lo*435,carry=Math.floor(loProduct/4294967296),nextLo=loProduct>>>0;hi=hi*435+carry+lo*256>>>0,lo=nextLo}return hi.toString(16).padStart(8,"0")+lo.toString(16).padStart(8,"0")}function brandingCacheKey(scope){return`${BRANDING_CACHE_KEY_PREFIX}${fnv1a64Hex(scope)}`}function serializeBranding(branding){return branding?JSON.stringify(branding):null}async function readCachedBranding(kv,scope){try{let raw=await kv.getItem(brandingCacheKey(scope));if(raw===null)return null;let parsed=parseClientBranding(JSON.parse(raw));return parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,logoUrl:hardenBrandAssetUrl(parsed.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(parsed.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(parsed.assistantAvatarUrl??null)})}catch{return null}}async function writeCachedBranding(kv,scope,serialized){try{serialized===null?await kv.removeItem(brandingCacheKey(scope)):await kv.setItem(brandingCacheKey(scope),serialized)}catch{}}function createBrandingCache(kv,scope){let lastWritten;return{restore(apply){readCachedBranding(kv,scope).then(branding=>{branding!==null&&apply(branding)})},persist(branding){let serialized=serializeBranding(branding);serialized!==lastWritten&&(lastWritten=serialized,writeCachedBranding(kv,scope,serialized))}}}function notConfiguredError(failure2){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`})}function tryResolveClient(cfg,platform){let clientCfg={publishableKey:cfg.publishableKey,...cfg.apiBaseUrl!==void 0?{apiBaseUrl:cfg.apiBaseUrl}:{},...cfg.contractVersion!==void 0?{contractVersion:cfg.contractVersion}:{},...cfg.debug!==void 0?{debug:cfg.debug}:{}};return tryResolveClientConfig(clientCfg,platform===void 0?void 0:{platform:platform})}function guardTelemetry(port){/* @__PURE__ */
|
|
135
135
|
return Object.freeze({track(event,props){try{port.track(event,props)}catch{}},trackExpectedFailure(code,props){try{port.trackExpectedFailure(code,props)}catch{}}})}var ENV_HINT=/* @__PURE__ */Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${ENV_API_BASE_URL} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function reportConfigFailure(failure2,telemetry,platform=SDK_PLATFORM){try{telemetry.trackExpectedFailure("sdk.config.invalid",{reason:failure2.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${failure2.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+ENV_HINT[platform])}function refusingTransport(failure2){/* @__PURE__ */
|
|
136
|
-
return Object.freeze({request(){return Promise.resolve(err(notConfiguredError(failure2)))},stream(_req,signal){let frame=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){signal.aborted||(yield frame)}}}})}function createInMemoryKv(){let map=/* @__PURE__ */new Map;return{async getItem(key){return map.get(key)??null},async setItem(key,value){map.set(key,value)},async removeItem(key){map.delete(key)},async keys(prefix){return[...map.keys()].filter(k=>k.startsWith(prefix))}}}var noopImageCache=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(input,opts){return new EverfurRuntimeImpl(input,opts)}var TOKEN_REFRESH_SKEW_MS=6e4,EverfurRuntimeImpl=class{constructor(input,opts){this.sessionId=newSessionId();this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let cfg=input.config;if(cfg.secureStore!==void 0&&cfg.secureStore.isAvailable===true)throw new EverfurConfigError("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.telemetry=cfg.telemetry?guardTelemetry(cfg.telemetry):noopTelemetry,this.onEvent=typeof cfg.onEvent=="function"?cfg.onEvent:void 0;let publishableKey=typeof cfg?.publishableKey=="string"?cfg.publishableKey.trim():"",failure2=checkPublishableKey(cfg?.publishableKey),transportInjected=cfg.transport!==void 0,resolvedTransport,resolvedApiBaseUrl=typeof cfg.apiBaseUrl=="string"&&cfg.apiBaseUrl.trim().length>0?cfg.apiBaseUrl.trim():null;if(failure2!==null)resolvedTransport=refusingTransport(failure2);else if(cfg.transport!==void 0)resolvedTransport=cfg.transport;else{let resolved=tryResolveClient(cfg,opts?.platform);resolved.ok?(resolvedApiBaseUrl=resolved.config.apiBaseUrl,resolvedTransport=createHttpTransport({config:resolved.config,...opts?.eventSourceFactory?{eventSourceFactory:opts.eventSourceFactory}:{}})):(failure2=resolved.failure,resolvedTransport=refusingTransport(resolved.failure))}if(this.configFailure=failure2,this.publishableKey=failure2===null?publishableKey:"",this.mintScope=`${this.publishableKey}|${resolvedApiBaseUrl??""}`,setPetRegistrationTenant(this,this.mintScope),this.transport=resolvedTransport,failure2!==null&&(reportConfigFailure(failure2,this.telemetry,opts?.platform),this.emit({type:"error",code:notConfiguredError(failure2).code,requestId:null})),this.errorPolicy=cfg.errorPolicy,this.camera=cfg.camera??unavailableCamera,this.upload=cfg.upload??unavailableUpload,this.uploadTransport=cfg.uploadTransport??unavailableUploadTransport,this.imageCache=cfg.imageCache??noopImageCache,this.kv=cfg.storage??createInMemoryKv(),this.currentUser=input.user??null,this.identity=this.buildIdentity(input.user??null),this.activePet=input.activePet,this.store=failure2===null?createEntitlementStore():createEntitlementStore(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:userRef2=>this.buildAuth(userRef2),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:resolvedApiBaseUrl},this.registry={services:this.services,acquireChat:scope=>this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat),releaseChat:controller=>this.releaseInternal(controller),peekChat:scope=>this.entries.get(`${this.epoch}|chat|${chatScopeKey(scope)}`)?.controller??null,acquire:(kind,scopeKey,create,destroy)=>this.acquireInternal(kind,scopeKey,create,destroy),release:controller=>this.releaseInternal(controller)},this.entitlements=this.store,failure2===null){this.brandingCache=createBrandingCache(this.kv,this.mintScope);let startEpoch=this.epoch;this.brandingCache.restore(branding=>{let snap=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==startEpoch||snap.branding||this.store.set({...snap,branding:branding})})}let shouldPoll=failure2===null&&(opts?.startEntitlementPolling??!transportInjected);this.poller=failure2===null?this.buildPoller(opts?.pollScheduler):null,shouldPoll&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(user){if(user===null)return null;let getToken=sharedTokenProvider(`${this.mintScope}|${user.userRef}`,user.getToken),identity=createIdentityProvider(user.userRef,getToken,expiresAtMs=>this.armTokenRefresh(identity,expiresAtMs),()=>{identity===this.identity&&this.emit({type:"session_expired",userRef:user.userRef})});return identity}armTokenRefresh(identity,expiresAtMs){if(this.clearTokenRefresh(),expiresAtMs===null||this.disposed||identity!==this.identity)return;let remaining=expiresAtMs-Date.now();if(remaining<=0)return;let delay=Math.max(remaining-TOKEN_REFRESH_SKEW_MS,remaining/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||identity!==this.identity)&&identity.currentToken({forceRefresh:true}).catch(()=>{})},delay),this.refreshTimer.unref?.()}emit(event){let handler=this.onEvent;if(handler===void 0)return;let deliver=()=>{this.disposed||deliverClientEvent(handler,event)};typeof queueMicrotask=="function"?queueMicrotask(deliver):Promise.resolve().then(deliver)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,fresh2,livemode,smsProfilePublic)=>{this.verdictLanded=true;let painted=this.store.getSnapshot().branding??null,branding=painted!==null&&fresh2!=null&&serializeBranding(painted)===serializeBranding(fresh2)?painted:fresh2;this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{},...smsProfilePublic!==void 0?{smsProfilePublic:smsProfilePublic}:{}}),this.brandingCache?.persist(branding??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...scheduler?{scheduler:scheduler}:{}})}acquireInternal(kind,scopeKey,create,destroy,warm=false){let key=`${this.epoch}|${kind}|${scopeKey}`,existing=this.entries.get(key);if(existing)return warm||(existing.warm?existing.warm=false:existing.refCount+=1),existing.controller;let controller=create();return this.entries.set(key,{controller:controller,refCount:1,warm:warm}),this.destroyers.set(controller,destroy),controller}releaseInternal(controller){for(let[key,entry]of this.entries)if(entry.controller===controller){entry.refCount-=1,entry.refCount<=0&&(this.runDestroyer(controller),this.entries.delete(key));return}}runDestroyer(controller){let destroy=this.destroyers.get(controller);this.destroyers.delete(controller),destroy&&destroy(controller)}buildChatController(scope){let controller=createChatController({auth:this.buildAuth(scope.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:scope.conversationId,petRef:scope.petRef,onConversationStarted:conversationId2=>this.emit({type:"conversation_started",conversationId:conversationId2})});return this.runBootstrap(controller,scope),controller}runBootstrap(controller,scope){let input={};scope.petRef!==null&&(input.petRef=scope.petRef),scope.conversationId!==null&&(input.resumeConversationId=scope.conversationId);let boot=bootstrapChat(input,{controller:controller});return boot.then(result=>controller.adoptPrompts(result.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(controller,boot),boot}buildAuth(scopeUserRef){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:scopeUserRef,sessionId:this.sessionId}}setUser(user){if(this.disposed)return;let nextRef=user?.userRef??null,currentRef=this.currentUser?.userRef??null;if(nextRef===currentRef){this.currentUser=user,user&&this.identity===null&&(this.identity=this.buildIdentity(user));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=user,this.identity=this.buildIdentity(user),this.rescopeAll()}async logout(){if(this.disposed)return;let wasAnonymous=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.setUser(null),this.leavingSessionId=null,wasAnonymous&&this.rescopeAll();let pending=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending!==null&&await pending,await sweepPerUserKv(this.kv,this.telemetry)}onBeforeLogout(hook){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(hook),()=>{this.beforeLogoutHooks.delete(hook)})}beforeLogoutSettlement(){let leaving=this.currentUser,identity=this.identity;return startBeforeLogoutHooks({leaving:leaving,identity:identity,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>graceAuth({leaving:leaving,identity:identity,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(pet,profile){return this.withPets("registerPet",(repo,auth)=>sharedPetRegistration(petRegistrationKey(this,auth,pet,profile),()=>profile===void 0?repo.registerPet(pet):repo.registerPet(pet,profile)))}updatePet(pet,patch){return this.withPets("updatePet",repo=>repo.updatePet(pet,patch))}deletePet(pet){return this.withPets("deletePet",repo=>repo.deletePet(pet))}eraseUserData(){return this.withPets("eraseUserData",repo=>repo.eraseUserData())}async withPets(verb,run){if(this.disposed)return err(disposedError(verb));let auth=this.buildAuth(this.currentUser?.userRef??null),result=await run(createPetsRepository(auth),auth);return result.ok&&!this.disposed&¬ifyPetsChanged(this),result}prepare(opts){let petRef2=opts?.petRef??null,key=`${this.epoch}|${this.currentUser?.userRef??""}|${petRef2??""}`,current=this.prepared;if(current!==null&¤t.key===key&&(current.result===null||current.result.status==="ready"))return current.promise;let entry={key:key,result:null,promise:this.runPrepare(petRef2).then(result=>(entry.result=result,result))};return this.prepared=entry,entry.promise}async runPrepare(petRef2){let startedAt=Date.now(),failure2=this.configFailure,refused=this.disposed?disposedError("prepare"):failure2===null?null:notConfiguredError(failure2),identity=this.identity,[session,entitlements,chat]=await Promise.all([refused?err(refused):identity===null?ok(void 0):identity.currentToken().then(()=>ok(void 0),cause=>(identity.reportRejected?.(),err(mintFailedError(cause)))),refused?err(refused):this.primeEntitlements(),petRef2===null?void 0:refused?err(refused):this.primeChat(petRef2)]),status=session.ok?entitlements.ok&&(chat?.ok??true)?"ready":"partial":"failed",durationMs=Date.now()-startedAt;try{this.telemetry.track("sdk.prepare.timing",{durationMs:durationMs,status:status})}catch{}return status==="ready"?this.emit({type:"ready"}):status==="failed"&&!session.ok&&failure2===null&&!this.disposed&&this.emit({type:"error",code:session.error.code,requestId:session.error.requestId??null}),/* @__PURE__ */Object.freeze({status:status,durationMs:durationMs,session:session,entitlements:entitlements,...chat?{chat:chat}:{}})}async primeEntitlements(){let resolution=await(this.poller?.prime());return resolution?resolution.kind==="failed"?err(resolution.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(petRef2){let scope={userRef:this.currentUser?.userRef??null,petRef:petRef2,conversationId:null},controller=this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat,true),result=await this.bootstraps.get(controller);return result?.cause&&controller.getSnapshot().conversationId===null&&(result=await this.runBootstrap(controller,scope)),result?.cause?err(result.cause):ok(void 0)}setActivePet(pet){if(this.disposed)return;let next=pet??null;next!==this.activePet&&(this.activePet=next,this.rescopeAll({keepBranding:true}))}updateEntitlements(next){this.disposed||this.configFailure===null&&this.store.set(next)}open(capability){this.telemetry.track("sdk.open",{capability:capability})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(opts){this.epoch+=1,this.disposeAllControllers(),this.store.reset(opts),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let entry of this.entries.values())this.runDestroyer(entry.controller);this.entries.clear(),this.destroyers.clear()}};function chatScopeKey(scope){return`${scope.userRef??""}|${scope.petRef??""}|${scope.conversationId??""}`}function disposeChat(controller){controller.dispose()}function disposedError(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfur(){return useEverfurContext().handle}var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot),scheme=props.seams.useColorScheme(),reducedMotion=props.seams.useReducedMotion(),textScale=props.seams.useTextScale(),highContrast=props.seams.useHighContrast(),scaleTypeSizes=props.seams.scaleTypeSizes,platformMonoFamily=props.seams.platformMonoFamily?.(),isFontRegistered=props.seams.isFontRegistered,clientKey=props.clientTheme?stableKey2(props.clientTheme):"",clientOverride=useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot2.branding??null,theme=useMemo(()=>resolveTheme({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme,reducedMotion:reducedMotion,textScale:textScale,scaleTypeSizes:scaleTypeSizes,highContrast:highContrast,...platformMonoFamily===void 0?{}:{platformMonoFamily:platformMonoFamily},...isFontRegistered===void 0?{}:{isFontRegistered:isFontRegistered}}),[serverBranding,clientOverride,scheme,reducedMotion,textScale,scaleTypeSizes,highContrast,platformMonoFamily,isFontRegistered]);props.seams.useResolvedTheme?.(theme);let isDevelopment=props.seams.isDevelopment;return useEffect(()=>{isDevelopment===void 0||!safeDevelopment(isDevelopment)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment,serverBranding,clientOverride,scheme]),createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment){try{return isDevelopment()===!0}catch{return false}}function EverfurProviderCore(props){let{config:config,user:user,activePet:activePet,theme:theme,warmUp:warmUp,children:children,seams:seams}=props,configKey=`${config?.publishableKey??""}|${config?.apiBaseUrl??""}|${config?.contractVersion??""}`,runtimeRef=useRef(null),supersededRef=useRef(null),onEventRef=useRef(config?.onEvent);onEventRef.current=config?.onEvent;let forwardEventRef=useRef(event=>{onEventRef.current?.(event)}),[renderTick,scheduleRender]=useReducer(n=>n+1,0),imperativeUserRef=useRef(null),lastPropUserRef=useRef(void 0),propUserRefKey=user?.userRef??null;lastPropUserRef.current!==propUserRefKey&&(lastPropUserRef.current!==void 0&&(imperativeUserRef.current=null),lastPropUserRef.current=propUserRefKey);let effectiveUser=imperativeUserRef.current!==null?imperativeUserRef.current.user:user??null,imperativePetRef=useRef(null),lastPropPetRef=useRef(void 0),propPetRef=activePet??null;lastPropPetRef.current!==propPetRef&&(lastPropPetRef.current!==void 0&&(imperativePetRef.current=null),lastPropPetRef.current=propPetRef);let effectivePet=imperativePetRef.current!==null?imperativePetRef.current.pet:activePet??null;(runtimeRef.current===null||runtimeRef.current.key!==configKey||runtimeRef.current.runtime.isDisposed)&&(runtimeRef.current!==null&&!runtimeRef.current.runtime.isDisposed&&(supersededRef.current=runtimeRef.current.runtime),runtimeRef.current={key:configKey,runtime:createEverfurRuntime({config:withEventForwarder(seams.withDefaults?seams.withDefaults(config):config,forwardEventRef.current),user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=useRef(null);useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]);let pendingDisposeRef=useRef(null);useEffect(()=>(pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null),()=>{pendingDisposeRef.current=runtime,deferDispose(()=>{pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null,runtime.dispose())})}),[runtime]),useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=useMemo(()=>({setUser:u=>{imperativeUserRef.current={user:u},runtime.setUser(u),scheduleRender()},setActivePet:p=>{imperativePetRef.current={pet:p},runtime.setActivePet(p),scheduleRender()},open:c=>runtime.open(c),prepare:opts=>runtime.prepare(opts),registerPet:(pet,profile)=>runtime.registerPet(pet,profile),updatePet:(pet,patch)=>runtime.updatePet(pet,patch),deletePet:pet=>runtime.deletePet(pet),eraseUserData:()=>runtime.eraseUserData(),logout:()=>{imperativeUserRef.current={user:null};let settled=runtime.logout();return scheduleRender(),settled}}),[runtime,scheduleRender]),value=useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch}),[runtime,handle,userRefKey,effectivePet,renderTick]),themed=createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}function withEventForwarder(config,forward){return typeof config!="object"||config===null?config:{...config,onEvent:forward}}function deferDispose(task){if(typeof queueMicrotask=="function"){queueMicrotask(task);return}Promise.resolve().then(task)}var NAMESPACE="everfur:";function storage(){try{if(typeof window>"u")return null;let store=window.localStorage;return store&&typeof store.getItem=="function"?store:null}catch{return null}}function createLocalStorageKv(){return{async getItem(key){try{return storage()?.getItem(NAMESPACE+key)??null}catch{return null}},async setItem(key,value){try{storage()?.setItem(NAMESPACE+key,value)}catch{}},async removeItem(key){try{storage()?.removeItem(NAMESPACE+key)}catch{}},async keys(prefix){try{let store=storage();if(store===null)return[];let out=[],wanted=NAMESPACE+prefix;for(let index=0;index<store.length;index+=1){let key=store.key(index);key!==null&&key.startsWith(wanted)&&out.push(key.slice(NAMESPACE.length))}/* @__PURE__ */
|
|
137
|
-
return Object.freeze(out)}catch{return[]}}}}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function tierScale(theme,tier){let{scale:scale,scaleCaps:scaleCaps}=theme.type,cap=scaleCaps[tier];return cap>0?Math.min(scale,cap):scale}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var loads=/* @__PURE__ */new Map,warned2=/* @__PURE__ */new Set,useBeforePaintEffect=typeof document>"u"?useEffect:useLayoutEffect;function keyOf(source){return source.cssSrc!==void 0?`css\n${source.cssSrc}`:`file\n${source.family}\n${source.src??""}\n${source.weight??"400"}\n${source.style??"normal"}`}function warnOnce(source,warn){if(!warn)return;let url=source.cssSrc??source.src??"",message=`[everfur] A font in appearance.fonts did not load: "${source.family}" from ${url}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(source.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!warned2.has(message)){warned2.add(message);try{globalThis.console?.warn?.(message)}catch{}}}function existingLink(href){let links=document.getElementsByTagName("link");for(let index=0;index<links.length;index+=1){let link=links[index];if(link.rel==="stylesheet"&&link.getAttribute("href")===href)return link}return null}function loadStylesheet(href){return existingLink(href)!==null?Promise.resolve(true):new Promise(resolve=>{let link=document.createElement("link");link.rel="stylesheet",link.href=href,link.setAttribute("data-everfur-font",""),link.addEventListener("load",()=>resolve(true)),link.addEventListener("error",()=>resolve(false)),document.head.appendChild(link)})}function loadFile(source){let fonts=document.fonts;return new FontFace(source.family,`url("${source.src}")`,{display:"swap",weight:source.weight??"400",style:source.style??"normal"}).load().then(face2=>(fonts.add(face2),true)).catch(()=>false)}function loadFontSource(source,warn=false){let key=keyOf(source),load=loads.get(key);if(load===void 0){load=Promise.resolve(false);try{if(typeof document<"u"){let css=source.cssSrc===void 0?null:fontSourceUrl(source.cssSrc),src=source.src===void 0?null:fontSourceUrl(source.src);css!==null?load=loadStylesheet(css):src!==null&&(load=loadFile({...source,src:src}))}}catch{load=Promise.resolve(false)}let settled=load.then(ok3=>(ok3||warnOnce(source,warn),ok3));loads.set(key,settled),load=settled}return load}function useFontSources(theme,isDevelopment){let sources=theme.type.fontSources;useBeforePaintEffect(()=>{if(sources.length===0)return;let warn=false;try{warn=isDevelopment()}catch{}for(let source of sources)loadFontSource(source,warn)},[sources,isDevelopment])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads2=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads2.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face2=>(fonts.add(face2),!0)).catch(()=>!1)}catch{}loads2.set(key,load)}return load}var FACES=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;useEffect(()=>{for(let face2 of FACES){let url=fontUrls[face2];url!=null&&loadBrandFont(families[face2],url,namedFaces[face2]?weight.regular:weight[FACE_WEIGHT[face2]])}},[families,fontUrls,weight,namedFaces]),useFontSources(theme,isWebDevelopment)}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument2=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument2?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});function withWebDefaults(config){return config.storage===void 0?{...config,storage:createLocalStorageKv()}:config}var webSeams=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:withWebDefaults,theme:webThemeSeams});function EverfurProvider(props){return createElement(EverfurProviderCore,{...props,seams:webSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}),[name,snapshot2])}function useCapabilityEnabled(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,subscribe2=useCallback(onChange=>store===void 0?()=>{}:store.subscribe(onChange),[store]),read=useCallback(()=>{if(store===void 0)return false;let snapshot2=store.getSnapshot();return decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}).enabled},[store,name]);return useSyncExternalStore(subscribe2,read,read)}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}function tierPx(theme,tier,points){return Math.round(points*tierScale(theme,tier)*10)/10}var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function headingFaceCss(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type,base2=faceCss(theme,fallback);return headingFamily===null&&headingWeight===null?base2:headingFamily!==null?{fontFamily:cssFontFamily(headingFamily),fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]}:theme.type.namedFaces[fallback]||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style,className:className}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
136
|
+
return Object.freeze({request(){return Promise.resolve(err(notConfiguredError(failure2)))},stream(_req,signal){let frame=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){signal.aborted||(yield frame)}}}})}var IN_MEMORY_KVS=/* @__PURE__ */new WeakSet;function createInMemoryKv(){let map=/* @__PURE__ */new Map,kv={async getItem(key){return map.get(key)??null},async setItem(key,value){map.set(key,value)},async removeItem(key){map.delete(key)},async keys(prefix){return[...map.keys()].filter(k=>k.startsWith(prefix))}};return IN_MEMORY_KVS.add(kv),kv}var noopImageCache=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(input,opts){return new EverfurRuntimeImpl(input,opts)}var TOKEN_REFRESH_SKEW_MS=6e4,EverfurRuntimeImpl=class{constructor(input,opts){this.sessionId=newSessionId();this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let cfg=input.config;if(cfg.secureStore!==void 0&&cfg.secureStore.isAvailable===true)throw new EverfurConfigError("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.telemetry=cfg.telemetry?guardTelemetry(cfg.telemetry):noopTelemetry,this.onEvent=typeof cfg.onEvent=="function"?cfg.onEvent:void 0;let publishableKey=typeof cfg?.publishableKey=="string"?cfg.publishableKey.trim():"",failure2=checkPublishableKey(cfg?.publishableKey),transportInjected=cfg.transport!==void 0,resolvedTransport,resolvedApiBaseUrl=typeof cfg.apiBaseUrl=="string"&&cfg.apiBaseUrl.trim().length>0?cfg.apiBaseUrl.trim():null;if(failure2!==null)resolvedTransport=refusingTransport(failure2);else if(cfg.transport!==void 0)resolvedTransport=cfg.transport;else{let resolved=tryResolveClient(cfg,opts?.platform);resolved.ok?(resolvedApiBaseUrl=resolved.config.apiBaseUrl,resolvedTransport=createHttpTransport({config:resolved.config,...opts?.eventSourceFactory?{eventSourceFactory:opts.eventSourceFactory}:{}})):(failure2=resolved.failure,resolvedTransport=refusingTransport(resolved.failure))}if(this.configFailure=failure2,this.publishableKey=failure2===null?publishableKey:"",this.mintScope=`${this.publishableKey}|${resolvedApiBaseUrl??""}`,setPetRegistrationTenant(this,this.mintScope),this.transport=resolvedTransport,failure2!==null&&(reportConfigFailure(failure2,this.telemetry,opts?.platform),this.emit({type:"error",code:notConfiguredError(failure2).code,requestId:null})),this.errorPolicy=cfg.errorPolicy,this.camera=cfg.camera??unavailableCamera,this.upload=cfg.upload??unavailableUpload,this.uploadTransport=cfg.uploadTransport??unavailableUploadTransport,this.imageCache=cfg.imageCache??noopImageCache,this.kv=cfg.storage??createInMemoryKv(),this.currentUser=input.user??null,this.identity=this.buildIdentity(input.user??null),this.activePet=input.activePet,this.store=failure2===null?createEntitlementStore():createEntitlementStore(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:userRef2=>this.buildAuth(userRef2),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:resolvedApiBaseUrl},this.registry={services:this.services,acquireChat:scope=>this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat),releaseChat:controller=>this.releaseInternal(controller),peekChat:scope=>this.entries.get(`${this.epoch}|chat|${chatScopeKey(scope)}`)?.controller??null,acquire:(kind,scopeKey,create,destroy)=>this.acquireInternal(kind,scopeKey,create,destroy),release:controller=>this.releaseInternal(controller)},this.entitlements=this.store,failure2===null){this.brandingCache=createBrandingCache(this.kv,this.mintScope);let startEpoch=this.epoch;this.brandingCache.restore(branding=>{let snap=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==startEpoch||snap.branding||this.store.set({...snap,branding:branding})})}let shouldPoll=failure2===null&&(opts?.startEntitlementPolling??!transportInjected);this.poller=failure2===null?this.buildPoller(opts?.pollScheduler):null,shouldPoll&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(user){if(user===null)return null;let getToken=sharedTokenProvider(`${this.mintScope}|${user.userRef}`,user.getToken),identity=createIdentityProvider(user.userRef,getToken,expiresAtMs=>this.armTokenRefresh(identity,expiresAtMs),()=>{identity===this.identity&&this.emit({type:"session_expired",userRef:user.userRef})});return identity}armTokenRefresh(identity,expiresAtMs){if(this.clearTokenRefresh(),expiresAtMs===null||this.disposed||identity!==this.identity)return;let remaining=expiresAtMs-Date.now();if(remaining<=0)return;let delay=Math.max(remaining-TOKEN_REFRESH_SKEW_MS,remaining/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||identity!==this.identity)&&identity.currentToken({forceRefresh:true}).catch(()=>{})},delay),this.refreshTimer.unref?.()}emit(event){let handler=this.onEvent;if(handler===void 0)return;let deliver=()=>{this.disposed||deliverClientEvent(handler,event)};typeof queueMicrotask=="function"?queueMicrotask(deliver):Promise.resolve().then(deliver)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,fresh4,livemode,smsProfilePublic)=>{this.verdictLanded=true;let painted=this.store.getSnapshot().branding??null,branding=painted!==null&&fresh4!=null&&serializeBranding(painted)===serializeBranding(fresh4)?painted:fresh4;this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{},...smsProfilePublic!==void 0?{smsProfilePublic:smsProfilePublic}:{}}),this.brandingCache?.persist(branding??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...scheduler?{scheduler:scheduler}:{}})}acquireInternal(kind,scopeKey,create,destroy,warm=false){let key=`${this.epoch}|${kind}|${scopeKey}`,existing=this.entries.get(key);if(existing)return warm||(existing.warm?existing.warm=false:existing.refCount+=1),existing.controller;let controller=create();return this.entries.set(key,{controller:controller,refCount:1,warm:warm}),this.destroyers.set(controller,destroy),controller}releaseInternal(controller){for(let[key,entry]of this.entries)if(entry.controller===controller){entry.refCount-=1,entry.refCount<=0&&(this.runDestroyer(controller),this.entries.delete(key));return}}runDestroyer(controller){let destroy=this.destroyers.get(controller);this.destroyers.delete(controller),destroy&&destroy(controller)}buildChatController(scope){let controller=createChatController({auth:this.buildAuth(scope.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:scope.conversationId,petRef:scope.petRef,onConversationStarted:conversationId2=>this.emit({type:"conversation_started",conversationId:conversationId2})});return this.runBootstrap(controller,scope),controller}runBootstrap(controller,scope){let input={};scope.petRef!==null&&(input.petRef=scope.petRef),scope.conversationId!==null&&(input.resumeConversationId=scope.conversationId);let boot=bootstrapChat(input,{controller:controller});return boot.then(result=>controller.adoptPrompts(result.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(controller,boot),boot}buildAuth(scopeUserRef){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:scopeUserRef,sessionId:this.sessionId}}setUser(user){if(this.disposed)return;let nextRef=user?.userRef??null,currentRef=this.currentUser?.userRef??null;if(nextRef===currentRef){this.currentUser=user,user&&this.identity===null&&(this.identity=this.buildIdentity(user));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=user,this.identity=this.buildIdentity(user),this.rescopeAll()}async logout(){if(this.disposed)return;let wasAnonymous=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.setUser(null),this.leavingSessionId=null,wasAnonymous&&this.rescopeAll();let pending2=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending2!==null&&await pending2,await sweepPerUserKv(this.kv,this.telemetry)}onBeforeLogout(hook){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(hook),()=>{this.beforeLogoutHooks.delete(hook)})}beforeLogoutSettlement(){let leaving=this.currentUser,identity=this.identity;return startBeforeLogoutHooks({leaving:leaving,identity:identity,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>graceAuth({leaving:leaving,identity:identity,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(pet,profile){return this.withPets("registerPet",(repo,auth)=>sharedPetRegistration(petRegistrationKey(this,auth,pet,profile),()=>profile===void 0?repo.registerPet(pet):repo.registerPet(pet,profile)))}updatePet(pet,patch){return this.withPets("updatePet",repo=>repo.updatePet(pet,patch))}deletePet(pet){return this.withPets("deletePet",repo=>repo.deletePet(pet))}eraseUserData(){return this.withPets("eraseUserData",repo=>repo.eraseUserData())}async withPets(verb,run){if(this.disposed)return err(disposedError(verb));let auth=this.buildAuth(this.currentUser?.userRef??null),result=await run(createPetsRepository(auth),auth);return result.ok&&!this.disposed&¬ifyPetsChanged(this),result}prepare(opts){let petRef2=opts?.petRef??null,key=`${this.epoch}|${this.currentUser?.userRef??""}|${petRef2??""}`,current=this.prepared;if(current!==null&¤t.key===key&&(current.result===null||current.result.status==="ready"))return current.promise;let entry={key:key,result:null,promise:this.runPrepare(petRef2).then(result=>(entry.result=result,result))};return this.prepared=entry,entry.promise}async runPrepare(petRef2){let startedAt=Date.now(),failure2=this.configFailure,refused=this.disposed?disposedError("prepare"):failure2===null?null:notConfiguredError(failure2),identity=this.identity,[session,entitlements,chat]=await Promise.all([refused?err(refused):identity===null?ok(void 0):identity.currentToken().then(()=>ok(void 0),cause=>(identity.reportRejected?.(),err(mintFailedError(cause)))),refused?err(refused):this.primeEntitlements(),petRef2===null?void 0:refused?err(refused):this.primeChat(petRef2)]),status=session.ok?entitlements.ok&&(chat?.ok??true)?"ready":"partial":"failed",durationMs=Date.now()-startedAt;try{this.telemetry.track("sdk.prepare.timing",{durationMs:durationMs,status:status})}catch{}return status==="ready"?this.emit({type:"ready"}):status==="failed"&&!session.ok&&failure2===null&&!this.disposed&&this.emit({type:"error",code:session.error.code,requestId:session.error.requestId??null}),/* @__PURE__ */Object.freeze({status:status,durationMs:durationMs,session:session,entitlements:entitlements,...chat?{chat:chat}:{}})}async primeEntitlements(){let resolution=await(this.poller?.prime());return resolution?resolution.kind==="failed"?err(resolution.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(petRef2){let scope={userRef:this.currentUser?.userRef??null,petRef:petRef2,conversationId:null},controller=this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat,true),result=await this.bootstraps.get(controller);return result?.cause&&controller.getSnapshot().conversationId===null&&(result=await this.runBootstrap(controller,scope)),result?.cause?err(result.cause):ok(void 0)}setActivePet(pet){if(this.disposed)return;let next=pet??null;next!==this.activePet&&(this.activePet=next,this.rescopeAll({keepBranding:true}))}updateEntitlements(next){this.disposed||this.configFailure===null&&this.store.set(next)}open(capability){this.telemetry.track("sdk.open",{capability:capability})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(opts){this.epoch+=1,this.disposeAllControllers(),this.store.reset(opts),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let entry of this.entries.values())this.runDestroyer(entry.controller);this.entries.clear(),this.destroyers.clear()}};function chatScopeKey(scope){return`${scope.userRef??""}|${scope.petRef??""}|${scope.conversationId??""}`}function disposeChat(controller){controller.dispose()}function disposedError(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfur(){return useEverfurContext().handle}var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot),scheme=props.seams.useColorScheme(),reducedMotion=props.seams.useReducedMotion(),textScale=props.seams.useTextScale(),highContrast=props.seams.useHighContrast(),scaleTypeSizes=props.seams.scaleTypeSizes,platformMonoFamily=props.seams.platformMonoFamily?.(),isFontRegistered=props.seams.isFontRegistered,clientKey=props.clientTheme?stableKey2(props.clientTheme):"",clientOverride=useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot2.branding??null,theme=useMemo(()=>resolveTheme({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme,reducedMotion:reducedMotion,textScale:textScale,scaleTypeSizes:scaleTypeSizes,highContrast:highContrast,...platformMonoFamily===void 0?{}:{platformMonoFamily:platformMonoFamily},...isFontRegistered===void 0?{}:{isFontRegistered:isFontRegistered}}),[serverBranding,clientOverride,scheme,reducedMotion,textScale,scaleTypeSizes,highContrast,platformMonoFamily,isFontRegistered]);props.seams.useResolvedTheme?.(theme);let isDevelopment=props.seams.isDevelopment;return useEffect(()=>{isDevelopment===void 0||!safeDevelopment(isDevelopment)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment,serverBranding,clientOverride,scheme]),createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment){try{return isDevelopment()===!0}catch{return false}}function EverfurProviderCore(props){let{config:config,user:user,activePet:activePet,theme:theme,warmUp:warmUp,children:children,seams:seams}=props,configKey=`${config?.publishableKey??""}|${config?.apiBaseUrl??""}|${config?.contractVersion??""}`,runtimeRef=useRef(null),supersededRef=useRef(null),onEventRef=useRef(config?.onEvent);onEventRef.current=config?.onEvent;let forwardEventRef=useRef(event=>{onEventRef.current?.(event)}),[renderTick,scheduleRender]=useReducer(n=>n+1,0),imperativeUserRef=useRef(null),lastPropUserRef=useRef(void 0),propUserRefKey=user?.userRef??null;lastPropUserRef.current!==propUserRefKey&&(lastPropUserRef.current!==void 0&&(imperativeUserRef.current=null),lastPropUserRef.current=propUserRefKey);let effectiveUser=imperativeUserRef.current!==null?imperativeUserRef.current.user:user??null,imperativePetRef=useRef(null),lastPropPetRef=useRef(void 0),propPetRef=activePet??null;lastPropPetRef.current!==propPetRef&&(lastPropPetRef.current!==void 0&&(imperativePetRef.current=null),lastPropPetRef.current=propPetRef);let effectivePet=imperativePetRef.current!==null?imperativePetRef.current.pet:activePet??null;(runtimeRef.current===null||runtimeRef.current.key!==configKey||runtimeRef.current.runtime.isDisposed)&&(runtimeRef.current!==null&&!runtimeRef.current.runtime.isDisposed&&(supersededRef.current=runtimeRef.current.runtime),runtimeRef.current={key:configKey,runtime:createEverfurRuntime({config:withEventForwarder(seams.withDefaults?seams.withDefaults(config):config,forwardEventRef.current),user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=useRef(null);useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]);let pendingDisposeRef=useRef(null);useEffect(()=>(pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null),()=>{pendingDisposeRef.current=runtime,deferDispose(()=>{pendingDisposeRef.current===runtime&&(pendingDisposeRef.current=null,runtime.dispose())})}),[runtime]),useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=useMemo(()=>({setUser:u=>{imperativeUserRef.current={user:u},runtime.setUser(u),scheduleRender()},setActivePet:p=>{imperativePetRef.current={pet:p},runtime.setActivePet(p),scheduleRender()},open:c=>runtime.open(c),prepare:opts=>runtime.prepare(opts),registerPet:(pet,profile)=>runtime.registerPet(pet,profile),updatePet:(pet,patch)=>runtime.updatePet(pet,patch),deletePet:pet=>runtime.deletePet(pet),eraseUserData:()=>runtime.eraseUserData(),logout:()=>{imperativeUserRef.current={user:null};let settled=runtime.logout();return scheduleRender(),settled}}),[runtime,scheduleRender]),value=useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch}),[runtime,handle,userRefKey,effectivePet,renderTick]),themed=createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}function withEventForwarder(config,forward){return typeof config!="object"||config===null?config:{...config,onEvent:forward}}function deferDispose(task){if(typeof queueMicrotask=="function"){queueMicrotask(task);return}Promise.resolve().then(task)}var NAMESPACE="everfur:";function storage(){try{if(typeof window>"u")return null;let store=window.localStorage;return store&&typeof store.getItem=="function"?store:null}catch{return null}}function createLocalStorageKv(){return{async getItem(key){try{return storage()?.getItem(NAMESPACE+key)??null}catch{return null}},async setItem(key,value){try{storage()?.setItem(NAMESPACE+key,value)}catch{}},async removeItem(key){try{storage()?.removeItem(NAMESPACE+key)}catch{}},async keys(prefix){try{let store=storage();if(store===null)return[];let out=[],wanted=NAMESPACE+prefix;for(let index=0;index<store.length;index+=1){let key=store.key(index);key!==null&&key.startsWith(wanted)&&out.push(key.slice(NAMESPACE.length))}/* @__PURE__ */
|
|
137
|
+
return Object.freeze(out)}catch{return[]}}}}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function tierScale(theme,tier){let{scale:scale,scaleCaps:scaleCaps}=theme.type,cap=scaleCaps[tier];return cap>0?Math.min(scale,cap):scale}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var loads=/* @__PURE__ */new Map,warned2=/* @__PURE__ */new Set,useBeforePaintEffect=typeof document>"u"?useEffect:useLayoutEffect;function keyOf(source){return source.cssSrc!==void 0?`css\n${source.cssSrc}`:`file\n${source.family}\n${source.src??""}\n${source.weight??"400"}\n${source.style??"normal"}`}function warnOnce(source,warn){if(!warn)return;let url=source.cssSrc??source.src??"",message=`[everfur] A font in appearance.fonts did not load: "${source.family}" from ${url}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(source.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!warned2.has(message)){warned2.add(message);try{globalThis.console?.warn?.(message)}catch{}}}function existingLink(href){let links=document.getElementsByTagName("link");for(let index=0;index<links.length;index+=1){let link=links[index];if(link.rel==="stylesheet"&&link.getAttribute("href")===href)return link}return null}function loadStylesheet(href){return existingLink(href)!==null?Promise.resolve(true):new Promise(resolve=>{let link=document.createElement("link");link.rel="stylesheet",link.href=href,link.setAttribute("data-everfur-font",""),link.addEventListener("load",()=>resolve(true)),link.addEventListener("error",()=>resolve(false)),document.head.appendChild(link)})}function loadFile(source){let fonts=document.fonts;return new FontFace(source.family,`url("${source.src}")`,{display:"swap",weight:source.weight??"400",style:source.style??"normal"}).load().then(face2=>(fonts.add(face2),true)).catch(()=>false)}function loadFontSource(source,warn=false){let key=keyOf(source),load=loads.get(key);if(load===void 0){load=Promise.resolve(false);try{if(typeof document<"u"){let css=source.cssSrc===void 0?null:fontSourceUrl(source.cssSrc),src=source.src===void 0?null:fontSourceUrl(source.src);css!==null?load=loadStylesheet(css):src!==null&&(load=loadFile({...source,src:src}))}}catch{load=Promise.resolve(false)}let settled=load.then(ok3=>(ok3||warnOnce(source,warn),ok3));loads.set(key,settled),load=settled}return load}function useFontSources(theme,isDevelopment){let sources=theme.type.fontSources;useBeforePaintEffect(()=>{if(sources.length===0)return;let warn=false;try{warn=isDevelopment()}catch{}for(let source of sources)loadFontSource(source,warn)},[sources,isDevelopment])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads2=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads2.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face2=>(fonts.add(face2),!0)).catch(()=>!1)}catch{}loads2.set(key,load)}return load}var FACES=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;useEffect(()=>{for(let face2 of FACES){let url=fontUrls[face2];url!=null&&loadBrandFont(families[face2],url,namedFaces[face2]?weight.regular:weight[FACE_WEIGHT[face2]])}},[families,fontUrls,weight,namedFaces]),useFontSources(theme,isWebDevelopment)}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument2=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument2?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});function withWebDefaults(config){return config.storage===void 0?{...config,storage:createLocalStorageKv()}:config}var webSeams=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:withWebDefaults,theme:webThemeSeams});function EverfurProvider(props){return createElement(EverfurProviderCore,{...props,seams:webSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot2=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}),[name,snapshot2])}function useCapabilityEnabled(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,subscribe2=useCallback(onChange=>store===void 0?()=>{}:store.subscribe(onChange),[store]),read=useCallback(()=>{if(store===void 0)return false;let snapshot2=store.getSnapshot();return decideCapability(name,snapshot2.decisions,{isPending:snapshot2.isPending}).enabled},[store,name]);return useSyncExternalStore(subscribe2,read,read)}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state3){return Object.is(props.resetKey,state3.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}function tierPx(theme,tier,points){return Math.round(points*tierScale(theme,tier)*10)/10}var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function headingFaceCss(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type,base2=faceCss(theme,fallback);return headingFamily===null&&headingWeight===null?base2:headingFamily!==null?{fontFamily:cssFontFamily(headingFamily),fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]}:theme.type.namedFaces[fallback]||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style,className:className}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
138
138
|
return jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${capability}`,className:className,style:{...styles.offstate,...style},children:/* @__PURE__ */jsx("div",{style:styles.skeletonBar})})}function OffState({decision:decision,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
|
|
139
139
|
return jsx("div",{className:className,style:{...styles.offstate,...style},children:message.length>0?/* @__PURE__ */jsx("p",{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{offstate:{...SURFACE_ROOT_RESET,boxSizing:"border-box",minHeight:MIN_OFFSTATE_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${space.md}px ${space.lg}px`,backgroundColor:color.surfaceCream,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`},offstateText:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.body,lineHeight:`${Math.round(type.size.body*type.lineHeight.normal)}px`,color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}}}var EMERGENCY_ER_LINE="Go to the nearest emergency vet now.";var CHAT_COPY=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:EMERGENCY_ER_LINE,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";var FEEDBACK_REASONS=/* @__PURE__ */Object.freeze([
|
|
140
140
|
/* @__PURE__ */Object.freeze({key:"inaccurate",label:CHAT_COPY.feedbackReasonInaccurate,feedbackType:"wrong"}),
|
|
@@ -144,10 +144,10 @@ return jsx("div",{className:className,style:{...styles.offstate,...style},childr
|
|
|
144
144
|
/* @__PURE__ */Object.freeze({key:"other",label:CHAT_COPY.feedbackReasonOther,feedbackType:"not_helpful"})]),SENTIMENT_OPTIONS=/* @__PURE__ */Object.freeze([
|
|
145
145
|
/* @__PURE__ */Object.freeze({sentiment:"up",label:CHAT_COPY.feedbackHelpful}),
|
|
146
146
|
/* @__PURE__ */Object.freeze({sentiment:"neutral",label:CHAT_COPY.feedbackNeutral}),
|
|
147
|
-
/* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}var NOT_READY=/* @__PURE__ */new WeakSet;function chatNotReadyResult(){let error=makeEverfurError("internalError",{retryable:true});return NOT_READY.add(error),err(error)}function isChatNotReadyResult(result){if(typeof result!="object"||result===null||result.ok!==false)return false;let error=result.error;return typeof error=="object"&&error!==null&&NOT_READY.has(error)}function useStalePetHold(runtime,userRef2,petRef2,scopeEpoch){let[owner,setOwner]=useState({pet:petRef2,user:userRef2}),adopt=owner.pet!==petRef2||owner.user===null&&userRef2!==null;adopt&&setOwner({pet:petRef2,user:userRef2});let current=adopt?{user:userRef2}:owner,held=petRef2!==null&¤t.user!==null&¤t.user!==userRef2;return useEffect(()=>{if(!held||userRef2===null||petRef2===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef2)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef2)&&setOwner({pet:petRef2,user:userRef2})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef2,petRef2,scopeEpoch]),held}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef2,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef2=opts?.petRef??activePet??null,conversationId2=opts?.conversationId??null,held=useStalePetHold(runtime,userRef2,petRef2,scopeEpoch),scope=useMemo(()=>({runtime:runtime,userRef:userRef2,petRef:petRef2,conversationId:conversationId2,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held]),[binding,setBinding]=useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2}),active=useRef(null);useEffect(()=>{if(held)return;let acquired=runtime.registry.acquireChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held,scope]);let subscribe2=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot2=useSyncExternalStore(subscribe2,getSnapshot,getSnapshot),send=useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef2?{petRef:petRef2}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef2]);return useMemo(()=>({status:snapshot2.status,messages:snapshot2.messages,conversationId:snapshot2.conversationId,petRef:petRef2,error:snapshot2.error,isStreaming:snapshot2.isStreaming,isBootstrapping:snapshot2.isBootstrapping,historyCursor:snapshot2.historyCursor??null,isLoadingHistory:snapshot2.isLoadingHistory??false,stopped:snapshot2.stopped??false,reconnecting:snapshot2.reconnecting??false,...history,suggestedPrompts:snapshot2.suggestedPrompts,unreadCount:snapshot2.unreadCount,hasUnreadThreads:snapshot2.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot2,petRef2,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot2=controller.getSnapshot();return snapshot2.status==="error"&&snapshot2.error!==null?err(snapshot2.error):ok(lastAssistantResponseId(snapshot2.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return chatNotReadyResult()}function attachmentErrorMessage(error){switch(error.code){case"too_large":return fillCopy(CHAT_COPY.attachmentTooLarge,{max:formatBytes(MAX_ATTACHMENT_BYTES),filename:error.filename,size:formatBytes(error.sizeBytes??0)});case"too_many":return fillCopy(CHAT_COPY.attachmentTooMany,{max:MAX_ATTACHMENTS_PER_MESSAGE});case"unsupported_type":return fillCopy(CHAT_COPY.attachmentUnsupported,{filename:error.filename});case"network":return CHAT_COPY.attachmentNetwork;case"server":return fillCopy(CHAT_COPY.attachmentServer,{status:error.httpStatus?` (${error.httpStatus})`:""});case"cancelled":return CHAT_COPY.attachmentCancelled;case"rate_limited":return CHAT_COPY.attachmentRateLimited;case"quota_exceeded":return CHAT_COPY.attachmentQuota;case"idempotency_conflict":return CHAT_COPY.attachmentConflict;case"unknown":return CHAT_COPY.attachmentUnknown}}function attachControlLabel(used,total){return fillCopy(used>=total?CHAT_COPY.attachmentsFull:CHAT_COPY.addAttachment,{used:used,total:total})}var EMPTY_SNAPSHOT=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(options={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),maxPerMessage=options.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,build=useCallback(()=>{let{services:services}=runtime.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:services.authFor(userRef2),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),transport:options.transport??services.uploadTransport,maxPerMessage:maxPerMessage})},[runtime,userRef2,scopeEpoch,maxPerMessage,options.transport]),scoped=useMemo(()=>options.queue??build(),[options.queue,build]),disposed2=useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;useEffect(()=>{if(queue!==options.queue){if(disposed2.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed2.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot2=useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=useState(null),add=useCallback(files=>{let outcomes=(Array.isArray(files)?files:[files]).map(file=>queue.add(file)),first=outcomes.find(outcome=>!outcome.ok);return first!==void 0&&!first.ok&&setRejected(first.error),outcomes},[queue,setRejected]),retry=useCallback(id=>queue.retry(id),[queue]),remove=useCallback(id=>queue.remove(id),[queue]),clear=useCallback(()=>queue.clear(),[queue]),dismissRejected=useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot2.attachments.some(row=>row.status==="uploading"),failed=snapshot2.attachments.some(row=>row.status==="failed");return useMemo(()=>({available:queue.available,attachments:snapshot2.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot2.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[]),rejected:rejected,add:add,retry:retry,remove:remove,clear:clear,dismissRejected:dismissRejected}),[queue.available,snapshot2,maxPerMessage,uploading,failed,rejected,add,retry,remove,clear,dismissRejected])}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef2,pet,onRegistered){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),register=useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef2);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef2,scopeEpoch]),bodyKey=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef2===null||bodyKey===null?null:`${String(userRef2)}|${scopeEpoch}|${petRef2}|${bodyKey}`,run=useCallback(()=>{if(petRef2===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef2,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef2,scopeKey]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return useMemo(()=>scopeKey===null?IDLE:state.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state.status,error:state.error,registered:state.registered,retry:retry},[scopeKey,state,retry])}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt,key){let clean2=sanitizeSeedPrompt(prompt),id=clean2===null?null:key!==void 0?`key:${String(key)}`:`prompt:${clean2}`,latest=useRef(askEverfur);latest.current=askEverfur;let done=useRef(null),inFlight3=useRef(null),current=useRef(id);current.current=id,useEffect(()=>{if(clean2===null||id===null||isBootstrapping||done.current===id||inFlight3.current===id)return;let ask=latest.current;if(ask===void 0)return;inFlight3.current=id;let settle=result=>{inFlight3.current===id&&(inFlight3.current=null),!isChatNotReadyResult(result)&¤t.current===id&&(done.current=id)};Promise.resolve(ask(clean2)).then(settle,()=>settle(void 0))},[clean2,id,isBootstrapping,askEverfur])}function isCoalesced(trigger,conversationId2,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId2?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId2=state.activeConversationId;return conversationId2===null||conversationId2.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId2,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId2}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),probeOffline=()=>lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,isOffline=probeOffline(),run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId2,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId2,isTurnInFlight:isTurnInFlight,isOffline:probeOffline(),lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe2=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe2(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}function targetKey(target){if(target===void 0)return null;let conversationId2=target.conversationId??"",petRef2=target.petRef??"";return conversationId2===""&&petRef2===""?null:`${String(conversationId2)}|${String(petRef2)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=useRef(null);useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count2,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count2}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state,setState]=useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=useCallback(async cursor2=>{let request=++generation.current,more=cursor2!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor2?{cursor:cursor2}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor2&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason()}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=useState(null),[expanded,setExpanded]=useState(false);useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}function selectView2(state){return state.isBootstrapping?"loading":state.status==="error"&&state.error&&state.messages.length===0?"error":state.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state,host="native"){if(state.messages.length===0)return null;let error=state.status==="error"?state.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state){let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
|
|
148
|
-
return Object.freeze(out)}var MAX_POLICY_FOLLOW_UPS=5;function excluded(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpsWithPolicy(
|
|
149
|
-
return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef2,conversationId2){let opts={};return petRef2!==void 0&&(opts.petRef=petRef2),conversationId2!==void 0&&(opts.conversationId=conversationId2),opts}function useEverfurPets(){let{runtime:runtime,userRef:userRef2,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),[
|
|
150
|
-
return jsx(EverfurTelevetDialog,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef2,options){let body={};petRef2!==void 0&&(body.pet_ref=petRef2);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef2===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef2,options){let pet;if(petRef2!=null){let length=typeof petRef2=="string"?[...petRef2].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef2}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL2=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL2.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var warned3=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned3||(warned3=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=useState(null);if(useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef2!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef2),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef2,scopeEpoch,opts.controller]),preflightController=useRef(controller);preflightController.current=controller;let scope=useMemo(()=>({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}),[runtime,userRef2,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=useState(IDLE2),inFlight3=useRef(null),scopeRef=useRef({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch};let controllerRef=useRef(controller);controllerRef.current=controller;let availableRef=useRef(available);availableRef.current=available;let start=useCallback((petRef2,visit)=>{if(inFlight3.current)return inFlight3.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef2===void 0?defaultPet:petRef2;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight3.current===tracked&&(inFlight3.current=null)});return inFlight3.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=useCallback((petRef2,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef2===void 0?defaultPet:petRef2,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null&&"consultId"in visit?{consultId:visit.consultId}:{},...visit!==null&&"visitRef"in visit?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=useCallback(petRef2=>redirect?start(petRef2,null):openInApp(petRef2,null),[redirect,start,openInApp]),openVisit=useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]),joinVisit=useCallback(consultId=>redirect?start(void 0,null):openInApp(void 0,{consultId:consultId.trim()}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit,joinVisit:joinVisit}}function closeQuietly(tab){try{tab.closed||tab.close()}catch{}}var BROWSER_OPENER=/* @__PURE__ */Object.freeze({prepare(){let tab=null;try{tab=typeof window>"u"?null:window.open("about:blank","_blank")}catch{tab=null}if(tab===null)return{ok:false,reason:"popupBlocked"};try{tab.opener=null}catch{}return{ok:true,value:{tab:tab}}},async finish({tab:tab},handoff){if(tab.closed)return"cancelled";try{return tab.location.replace(handoff.url),null}catch{return closeQuietly(tab),"popupBlocked"}},abandon({tab:tab}){closeQuietly(tab)}});function useVetVisit(opts){return useVetVisitWith(BROWSER_OPENER,opts)}var FOCUSABLE='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function isDialogElement(node){return node.tagName==="DIALOG"}function useModalDialog(open,onClose,returnFocusTo,options){let escapeAtKeyDown=options?.escapeAtKeyDown===true,dialogRef=useRef(null),wasOpen=useRef(false),opener=useRef(null),trigger=useRef(returnFocusTo);trigger.current=returnFocusTo;let restoreFocus=useCallback(()=>{if(!wasOpen.current)return;wasOpen.current=false;let target=trigger.current===void 0?opener.current:trigger.current.current;target&&target.isConnected&&target.focus(),(!target||!target.isConnected||document.activeElement===target)&&(opener.current=null)},[]);useEffect(()=>{if(!open){restoreFocus();return}let node=dialogRef.current;if(!wasOpen.current){let active=typeof document>"u"?null:document.activeElement;active!==null&&node!==null&&node.contains(active)||(opener.current=active instanceof HTMLElement?active:null)}if(wasOpen.current=true,node===null)return;if(!isDialogElement(node)){node.contains(document.activeElement)||(node.querySelector(FOCUSABLE)??node).focus();return}let dialog=node;typeof dialog.showModal=="function"?dialog.open||dialog.showModal():dialog.setAttribute("open","")},[open,restoreFocus]),useEffect(()=>restoreFocus,[restoreFocus]),useEffect(()=>{let node=dialogRef.current;if(!open||node===null||!isDialogElement(node))return;let dialog=node;if(typeof dialog.showModal!="function")return;let lastFocused=null,onFocusIn=event=>{event.target instanceof HTMLElement&&(lastFocused=event.target)},onNativeClose=()=>{if(!dialog.isConnected||dialog.open)return;let back=lastFocused;dialog.showModal(),back!==null&&back.isConnected&&dialog.contains(back)&&document.activeElement!==back&&back.focus()};return dialog.addEventListener("focusin",onFocusIn),dialog.addEventListener("close",onNativeClose),()=>{dialog.removeEventListener("focusin",onFocusIn),dialog.removeEventListener("close",onNativeClose)}},[open]);let onKeyDown2=useCallback(event=>{let node=dialogRef.current;if(node===null)return;if(event.key==="Escape"&&!isDialogElement(node)){event.preventDefault(),event.stopPropagation(),onClose();return}if(event.key==="Escape"&&escapeAtKeyDown);if(event.key!=="Tab")return;let focusable=Array.from(node.querySelectorAll(FOCUSABLE)),first=focusable[0],last=focusable[focusable.length-1];if(!first||!last){event.preventDefault();return}let active=document.activeElement;event.shiftKey&&(active===first||!node.contains(active))?(event.preventDefault(),last.focus()):!event.shiftKey&&(active===last||!node.contains(active))&&(event.preventDefault(),first.focus())},[onClose,escapeAtKeyDown]),onCancel=useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),onClose())},[onClose]);return{dialogRef:dialogRef,onKeyDown:onKeyDown2,onCancel:onCancel}}var PATHS=/* @__PURE__ */Object.freeze({check:/* @__PURE__ */jsx("polyline",{points:"20 6 9 17 4 12"}),copy:/* @__PURE__ */jsxs(Fragment,{children:[
|
|
147
|
+
/* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}var NOT_READY=/* @__PURE__ */new WeakSet;function chatNotReadyResult(){let error=makeEverfurError("internalError",{retryable:true});return NOT_READY.add(error),err(error)}function isChatNotReadyResult(result){if(typeof result!="object"||result===null||result.ok!==false)return false;let error=result.error;return typeof error=="object"&&error!==null&&NOT_READY.has(error)}function useStalePetHold(runtime,userRef2,petRef2,scopeEpoch){let[owner,setOwner]=useState({pet:petRef2,user:userRef2}),adopt=owner.pet!==petRef2||owner.user===null&&userRef2!==null;adopt&&setOwner({pet:petRef2,user:userRef2});let current=adopt?{user:userRef2}:owner,held=petRef2!==null&¤t.user!==null&¤t.user!==userRef2;return useEffect(()=>{if(!held||userRef2===null||petRef2===null)return;let live=true,repository=createPetsRepository(runtime.registry.services.authFor(userRef2)),check=async()=>{let listed=await repository.list();live&&listed.ok&&listed.value.some(pet=>pet.petRef===petRef2)&&setOwner({pet:petRef2,user:userRef2})};check();let unsubscribe=subscribePetsChanged(runtime,()=>{check()});return()=>{live=false,unsubscribe()}},[held,runtime,userRef2,petRef2,scopeEpoch]),held}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef2,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef2=opts?.petRef??activePet??null,conversationId2=opts?.conversationId??null,held=useStalePetHold(runtime,userRef2,petRef2,scopeEpoch),scope=useMemo(()=>({runtime:runtime,userRef:userRef2,petRef:petRef2,conversationId:conversationId2,scopeEpoch:scopeEpoch,held:held}),[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held]),[binding,setBinding]=useState(null),controller=held?null:binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2}),active=useRef(null);useEffect(()=>{if(held)return;let acquired=runtime.registry.acquireChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef2,petRef2,conversationId2,scopeEpoch,held,scope]);let subscribe2=useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot2=useSyncExternalStore(subscribe2,getSnapshot,getSnapshot),send=useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef2?{petRef:petRef2}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef2]);return useMemo(()=>({status:snapshot2.status,messages:snapshot2.messages,conversationId:snapshot2.conversationId,petRef:petRef2,error:snapshot2.error,isStreaming:snapshot2.isStreaming,isBootstrapping:snapshot2.isBootstrapping,historyCursor:snapshot2.historyCursor??null,isLoadingHistory:snapshot2.isLoadingHistory??false,stopped:snapshot2.stopped??false,reconnecting:snapshot2.reconnecting??false,...history,suggestedPrompts:snapshot2.suggestedPrompts,unreadCount:snapshot2.unreadCount,hasUnreadThreads:snapshot2.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot2,petRef2,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot2=controller.getSnapshot();return snapshot2.status==="error"&&snapshot2.error!==null?err(snapshot2.error):ok(lastAssistantResponseId(snapshot2.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return chatNotReadyResult()}function attachmentErrorMessage(error){switch(error.code){case"too_large":return fillCopy(CHAT_COPY.attachmentTooLarge,{max:formatBytes(MAX_ATTACHMENT_BYTES),filename:error.filename,size:formatBytes(error.sizeBytes??0)});case"too_many":return fillCopy(CHAT_COPY.attachmentTooMany,{max:MAX_ATTACHMENTS_PER_MESSAGE});case"unsupported_type":return fillCopy(CHAT_COPY.attachmentUnsupported,{filename:error.filename});case"network":return CHAT_COPY.attachmentNetwork;case"server":return fillCopy(CHAT_COPY.attachmentServer,{status:error.httpStatus?` (${error.httpStatus})`:""});case"cancelled":return CHAT_COPY.attachmentCancelled;case"rate_limited":return CHAT_COPY.attachmentRateLimited;case"quota_exceeded":return CHAT_COPY.attachmentQuota;case"idempotency_conflict":return CHAT_COPY.attachmentConflict;case"unknown":return CHAT_COPY.attachmentUnknown}}function attachControlLabel(used,total){return fillCopy(used>=total?CHAT_COPY.attachmentsFull:CHAT_COPY.addAttachment,{used:used,total:total})}var EMPTY_SNAPSHOT=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(options={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),maxPerMessage=options.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,build=useCallback(()=>{let{services:services}=runtime.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:services.authFor(userRef2),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),transport:options.transport??services.uploadTransport,maxPerMessage:maxPerMessage})},[runtime,userRef2,scopeEpoch,maxPerMessage,options.transport]),scoped=useMemo(()=>options.queue??build(),[options.queue,build]),disposed3=useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;useEffect(()=>{if(queue!==options.queue){if(disposed3.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed3.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot2=useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=useState(null),add=useCallback(files=>{let outcomes=(Array.isArray(files)?files:[files]).map(file=>queue.add(file)),first=outcomes.find(outcome=>!outcome.ok);return first!==void 0&&!first.ok&&setRejected(first.error),outcomes},[queue,setRejected]),retry=useCallback(id=>queue.retry(id),[queue]),remove=useCallback(id=>queue.remove(id),[queue]),clear=useCallback(()=>queue.clear(),[queue]),dismissRejected=useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot2.attachments.some(row=>row.status==="uploading"),failed=snapshot2.attachments.some(row=>row.status==="failed");return useMemo(()=>({available:queue.available,attachments:snapshot2.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot2.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[]),rejected:rejected,add:add,retry:retry,remove:remove,clear:clear,dismissRejected:dismissRejected}),[queue.available,snapshot2,maxPerMessage,uploading,failed,rejected,add,retry,remove,clear,dismissRejected])}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef2,pet,onRegistered){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),register=useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef2);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef2,scopeEpoch]),bodyKey=useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state3,setState]=useState({key:null,status:"idle",error:null,registered:null}),generation=useRef(0),onRegisteredRef=useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef2===null||bodyKey===null?null:`${String(userRef2)}|${scopeEpoch}|${petRef2}|${bodyKey}`,run=useCallback(()=>{if(petRef2===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef2,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef2,scopeKey]);useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=useCallback(()=>{state3.status==="failed"&&run()},[state3.status,run]);return useMemo(()=>scopeKey===null?IDLE:state3.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state3.status,error:state3.error,registered:state3.registered,retry:retry},[scopeKey,state3,retry])}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt,key){let clean2=sanitizeSeedPrompt(prompt),id=clean2===null?null:key!==void 0?`key:${String(key)}`:`prompt:${clean2}`,latest=useRef(askEverfur);latest.current=askEverfur;let done=useRef(null),inFlight3=useRef(null),current=useRef(id);current.current=id,useEffect(()=>{if(clean2===null||id===null||isBootstrapping||done.current===id||inFlight3.current===id)return;let ask=latest.current;if(ask===void 0)return;inFlight3.current=id;let settle=result=>{inFlight3.current===id&&(inFlight3.current=null),!isChatNotReadyResult(result)&¤t.current===id&&(done.current=id)};Promise.resolve(ask(clean2)).then(settle,()=>settle(void 0))},[clean2,id,isBootstrapping,askEverfur])}function isCoalesced(trigger,conversationId2,state3){if(trigger==="announced")return false;let last=state3.lastRefresh;return last===null||last.conversationId!==conversationId2?false:state3.now-last.at<15e3}function decideChatRefresh(trigger,state3){let conversationId2=state3.activeConversationId;return conversationId2===null||conversationId2.length===0?{action:"skip",reason:"no_thread"}:state3.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state3.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId2,state3)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId2}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}function useChatLifecycle(lifecycle,target){let latest=useRef(target);latest.current=target;let lastRefresh=useRef(null),deferred=useRef(null),probeOffline=()=>lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,isOffline=probeOffline(),run=useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId2,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId2,isTurnInFlight:isTurnInFlight,isOffline:probeOffline(),lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe2=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe2(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe2(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}function targetKey(target){if(target===void 0)return null;let conversationId2=target.conversationId??"",petRef2=target.petRef??"";return conversationId2===""&&petRef2===""?null:`${String(conversationId2)}|${String(petRef2)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=useRef(null);useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count2,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count2}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=useState(false),[query,setQuery]=useState(""),scope=chat.listConversations,generation=useRef(0),[state3,setState]=useState(()=>fresh(scope)),current=state3.scope===scope?state3:fresh(scope);useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=useCallback(async cursor2=>{let request=++generation.current,more=cursor2!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor2?{cursor:cursor2}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor2&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason()}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=useState(null),[expanded,setExpanded]=useState(false);useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=useCallback(()=>setExpanded(true),[]);return useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}function selectView2(state3){return state3.isBootstrapping?"loading":state3.status==="error"&&state3.error&&state3.messages.length===0?"error":state3.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state3,host2="native"){if(state3.messages.length===0)return null;let error=state3.status==="error"?state3.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host2==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state3.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state3){let last=state3.messages[state3.messages.length-1];if(state3.isStreaming||state3.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state3.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
|
|
148
|
+
return Object.freeze(out)}var MAX_POLICY_FOLLOW_UPS=5;function excluded(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpsWithPolicy(state3,policy){if(policy===void 0)return visibleFollowUps(state3);let last=state3.messages[state3.messages.length-1];if(state3.isStreaming||state3.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let count2=Math.max(1,Math.min(MAX_POLICY_FOLLOW_UPS,Math.floor(policy.count??MAX_VISIBLE_FOLLOW_UPS))),question=null;for(let i=state3.messages.length-1;i>=0;i-=1){let m=state3.messages[i];if(m!==void 0&&m.role==="user"){question=m.text;break}}let norm=t=>t.trim().replace(/\s+/g," ").toLowerCase(),seen=new Set(question===null?[]:[norm(question)]),out=[],take=prompt=>{let text3=prompt.trim(),key=norm(text3);out.length>=count2||key.length===0||seen.has(key)||excluded(policy.exclude,text3)||(seen.add(key),out.push(text3))};for(let prompt of state3.suggestedPrompts)take(prompt);let fill2=[];try{fill2=typeof policy.fill=="function"?policy.fill(question):policy.fill??[]}catch{fill2=[]}for(let prompt of Array.isArray(fill2)?fill2:[])typeof prompt=="string"&&take(prompt);/* @__PURE__ */
|
|
149
|
+
return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef2,conversationId2){let opts={};return petRef2!==void 0&&(opts.petRef=petRef2),conversationId2!==void 0&&(opts.conversationId=conversationId2),opts}function useEverfurPets(){let{runtime:runtime,userRef:userRef2,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),[state3,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state3.repository===repository?state3:{pets:[],loading:true,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}function headerPetOf(pets,activePetRef){if(activePetRef!==null){let active=pets.find(pet=>pet.petRef===activePetRef);if(active!==void 0)return active}return pets[0]??null}var VISUALLY_HIDDEN=/* @__PURE__ */Object.freeze({position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0});var FOCUS_RING_WIDTH=2,SELF_FOCUS_RING_ATTRIBUTE="data-ef-focus-ring",FOCUS_RING_COLOR_ATTRIBUTE="data-ef-focus-ring-color";function focusRingStyle(color){return{outline:`${FOCUS_RING_WIDTH}px solid ${color}`,outlineOffset:FOCUS_RING_WIDTH}}var keyboardDriving=false,bound=0;function onKeyDown(event){event.metaKey||event.ctrlKey||event.altKey||(keyboardDriving=true)}function onPointerDown(){keyboardDriving=false}function bindModality(){return typeof document>"u"?()=>{}:(bound===0&&(document.addEventListener("keydown",onKeyDown,true),document.addEventListener("pointerdown",onPointerDown,true),document.addEventListener("mousedown",onPointerDown,true),document.addEventListener("touchstart",onPointerDown,true)),bound+=1,()=>{bound-=1,!(bound>0)&&(document.removeEventListener("keydown",onKeyDown,true),document.removeEventListener("pointerdown",onPointerDown,true),document.removeEventListener("mousedown",onPointerDown,true),document.removeEventListener("touchstart",onPointerDown,true),keyboardDriving=false)})}var TEXT_INPUT_TYPES=/* @__PURE__ */new Set(["","text","search","email","tel","url","password","number"]);function isTextField(element){return element.tagName==="TEXTAREA"||element.isContentEditable?true:element.tagName!=="INPUT"?false:TEXT_INPUT_TYPES.has((element.getAttribute("type")??"").toLowerCase())}function useKeyboardFocusRing(root,color){useEffect(()=>{let node=root.current;if(node===null)return;let unbind=bindModality(),painted=/* @__PURE__ */new Map,onFocusIn=event=>{let target=event.target;if(!(target instanceof HTMLElement)||painted.has(target)||target.closest(`[${SELF_FOCUS_RING_ATTRIBUTE}="self"]`)!==null||!keyboardDriving&&!isTextField(target))return;painted.set(target,{outline:target.style.outline,outlineOffset:target.style.outlineOffset});let region=target.closest(`[${FOCUS_RING_COLOR_ATTRIBUTE}]`),ring=focusRingStyle(region?.getAttribute(FOCUS_RING_COLOR_ATTRIBUTE)||color);target.style.outline=ring.outline,target.style.outlineOffset=`${ring.outlineOffset}px`},onFocusOut=event=>{let target=event.target;if(!(target instanceof HTMLElement))return;let before=painted.get(target);before!==void 0&&(painted.delete(target),target.style.outline=before.outline,target.style.outlineOffset=before.outlineOffset)};return node.addEventListener("focusin",onFocusIn),node.addEventListener("focusout",onFocusOut),()=>{node.removeEventListener("focusin",onFocusIn),node.removeEventListener("focusout",onFocusOut);for(let[element,before]of painted)element.style.outline=before.outline,element.style.outlineOffset=before.outlineOffset;painted.clear(),unbind()}},[root,color])}function chatVetVisitOptions(petRef2,vet){let options={entry:"chat",petRef:petRef2};return vet?.returnTo!==void 0&&(options.returnTo=vet.returnTo),vet?.usState!==void 0&&(options.usState=vet.usState),vet?.prefer!==void 0&&(options.prefer=vet.prefer),options}var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present2=televetGlobal().presenter;if(present2===null)return"absent";try{return present2(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function subscribeTelevetExperience(listener){let g=televetGlobal();return g.listeners.add(listener),()=>{g.listeners.delete(listener)}}function televetExperienceSnapshot(){return televetGlobal().snapshot}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}function dismissTelevetExperience(){televetGlobal().snapshot.request!==null&&publish({request:null})}function claimTelevetHost(){let g=televetGlobal(),id=g.nextHost;return g.nextHost+=1,g.hosts=[...g.hosts,id],publish({activeHost:g.hosts[0]??null}),id}function releaseTelevetHost(id){let g=televetGlobal();g.hosts=g.hosts.filter(host2=>host2!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}function memoizeTelevetLoader(load){let pending2=null;return()=>{if(pending2!==null)return pending2;let started=load();return pending2=started,started.then(void 0,()=>{pending2===started&&(pending2=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=useState(null);useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot2=useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot2.activeHost===id?snapshot2.request:null,[module,setModule]=useState(null),wanted=request!==null&&module===null;return useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded2=>{live&&setModule(()=>loaded2)},cause=>{live&&(console.warn("[everfur] The in-app vet visit could not load its screens.",cause),dismissTelevetExperience())}),()=>{live=false}},[wanted,load]),request===null||module===null?null:{module:module,request:request,serial:snapshot2.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>import("@everfur/sdk/web/televet/booking"));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}){let host2=useTelevetExperienceHost(loadExperience);if(host2===null)return null;let{EverfurTelevetDialog:EverfurTelevetDialog}=host2.module;/* @__PURE__ */
|
|
150
|
+
return jsx(EverfurTelevetDialog,{request:host2.request,onClose:host2.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host2.serial)}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef2,options){let body={};petRef2!==void 0&&(body.pet_ref=petRef2);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef2===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef2,options){let pet;if(petRef2!=null){let length=typeof petRef2=="string"?[...petRef2].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef2}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state3){if(typeof state3!="string"||state3.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state3}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL2=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL2.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host2=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host2);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var warned3=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned3||(warned3=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=useState(null);if(useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef2!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef2),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef2,scopeEpoch,opts.controller]),preflightController=useRef(controller);preflightController.current=controller;let scope=useMemo(()=>({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}),[runtime,userRef2,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=useState(IDLE2),inFlight3=useRef(null),scopeRef=useRef({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch};let controllerRef=useRef(controller);controllerRef.current=controller;let availableRef=useRef(available);availableRef.current=available;let start=useCallback((petRef2,visit)=>{if(inFlight3.current)return inFlight3.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef2===void 0?defaultPet:petRef2;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight3.current===tracked&&(inFlight3.current=null)});return inFlight3.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=useCallback((petRef2,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef2===void 0?defaultPet:petRef2,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null&&"consultId"in visit?{consultId:visit.consultId}:{},...visit!==null&&"visitRef"in visit?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=useCallback(petRef2=>redirect?start(petRef2,null):openInApp(petRef2,null),[redirect,start,openInApp]),openVisit=useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]),joinVisit=useCallback(consultId=>redirect?start(void 0,null):openInApp(void 0,{consultId:consultId.trim()}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit,joinVisit:joinVisit}}function closeQuietly(tab){try{tab.closed||tab.close()}catch{}}var BROWSER_OPENER=/* @__PURE__ */Object.freeze({prepare(){let tab=null;try{tab=typeof window>"u"?null:window.open("about:blank","_blank")}catch{tab=null}if(tab===null)return{ok:false,reason:"popupBlocked"};try{tab.opener=null}catch{}return{ok:true,value:{tab:tab}}},async finish({tab:tab},handoff){if(tab.closed)return"cancelled";try{return tab.location.replace(handoff.url),null}catch{return closeQuietly(tab),"popupBlocked"}},abandon({tab:tab}){closeQuietly(tab)}});function useVetVisit(opts){return useVetVisitWith(BROWSER_OPENER,opts)}var FOCUSABLE='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function isDialogElement(node){return node.tagName==="DIALOG"}function useModalDialog(open,onClose,returnFocusTo,options){let escapeAtKeyDown=options?.escapeAtKeyDown===true,dialogRef=useRef(null),wasOpen=useRef(false),opener=useRef(null),trigger=useRef(returnFocusTo);trigger.current=returnFocusTo;let restoreFocus=useCallback(()=>{if(!wasOpen.current)return;wasOpen.current=false;let target=trigger.current===void 0?opener.current:trigger.current.current;target&&target.isConnected&&target.focus(),(!target||!target.isConnected||document.activeElement===target)&&(opener.current=null)},[]);useEffect(()=>{if(!open){restoreFocus();return}let node=dialogRef.current;if(!wasOpen.current){let active=typeof document>"u"?null:document.activeElement;active!==null&&node!==null&&node.contains(active)||(opener.current=active instanceof HTMLElement?active:null)}if(wasOpen.current=true,node===null)return;if(!isDialogElement(node)){node.contains(document.activeElement)||(node.querySelector(FOCUSABLE)??node).focus();return}let dialog=node;typeof dialog.showModal=="function"?dialog.open||dialog.showModal():dialog.setAttribute("open","")},[open,restoreFocus]),useEffect(()=>restoreFocus,[restoreFocus]),useEffect(()=>{let node=dialogRef.current;if(!open||node===null||!isDialogElement(node))return;let dialog=node;if(typeof dialog.showModal!="function")return;let lastFocused=null,onFocusIn=event=>{event.target instanceof HTMLElement&&(lastFocused=event.target)},onNativeClose=()=>{if(!dialog.isConnected||dialog.open)return;let back=lastFocused;dialog.showModal(),back!==null&&back.isConnected&&dialog.contains(back)&&document.activeElement!==back&&back.focus()};return dialog.addEventListener("focusin",onFocusIn),dialog.addEventListener("close",onNativeClose),()=>{dialog.removeEventListener("focusin",onFocusIn),dialog.removeEventListener("close",onNativeClose)}},[open]);let onKeyDown2=useCallback(event=>{let node=dialogRef.current;if(node===null)return;if(event.key==="Escape"&&!isDialogElement(node)){event.preventDefault(),event.stopPropagation(),onClose();return}if(event.key==="Escape"&&escapeAtKeyDown);if(event.key!=="Tab")return;let focusable=Array.from(node.querySelectorAll(FOCUSABLE)),first=focusable[0],last=focusable[focusable.length-1];if(!first||!last){event.preventDefault();return}let active=document.activeElement;event.shiftKey&&(active===first||!node.contains(active))?(event.preventDefault(),last.focus()):!event.shiftKey&&(active===last||!node.contains(active))&&(event.preventDefault(),first.focus())},[onClose,escapeAtKeyDown]),onCancel=useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),onClose())},[onClose]);return{dialogRef:dialogRef,onKeyDown:onKeyDown2,onCancel:onCancel}}var PATHS=/* @__PURE__ */Object.freeze({check:/* @__PURE__ */jsx("polyline",{points:"20 6 9 17 4 12"}),copy:/* @__PURE__ */jsxs(Fragment,{children:[
|
|
151
151
|
/* @__PURE__ */jsx("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),
|
|
152
152
|
/* @__PURE__ */jsx("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]}),thumbsUp:/* @__PURE__ */jsxs(Fragment,{children:[
|
|
153
153
|
/* @__PURE__ */jsx("path",{d:"M7 10v12"}),
|
|
@@ -182,7 +182,7 @@ return jsx(EverfurTelevetDialog,{request:host.request,onClose:host.dismiss,...on
|
|
|
182
182
|
/* @__PURE__ */jsx("path",{d:"M12 5v14"})]}),phone:/* @__PURE__ */jsx("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"}),alert:/* @__PURE__ */jsxs(Fragment,{children:[
|
|
183
183
|
/* @__PURE__ */jsx("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),
|
|
184
184
|
/* @__PURE__ */jsx("path",{d:"M12 9v4"}),
|
|
185
|
-
/* @__PURE__ */jsx("path",{d:"M12 17h.01"})]}),arrowUp:/* @__PURE__ */jsx("path",{d:"M12 19.5V5M6 11l6-6 6 6"}),send:/* @__PURE__ */jsx("path",{d:"M17.306 1.98864C17.7329 0.807956 16.5887 -0.336175 15.408 0.0916395L0.977949 5.31038C-0.206691 5.73918 -0.349954 7.35559 0.739836 7.98694L5.346 10.6536L9.45914 6.54047C9.64549 6.36049 9.89506 6.26091 10.1541 6.26316C10.4132 6.26541 10.661 6.36932 10.8442 6.55251C11.0274 6.73569 11.1313 6.9835 11.1335 7.24256C11.1358 7.50162 11.0362 7.75119 10.8562 7.93754L6.74307 12.0507L9.41073 16.6568C10.0411 17.7466 11.6575 17.6024 12.0863 16.4187L17.306 1.98864Z"})}),FILLED=/* @__PURE__ */Object.freeze({send:/* @__PURE__ */Object.freeze({viewBox:"0 0 17.3973 19.8995"})});function Glyph({name:name,size:size,color:color,fill:
|
|
185
|
+
/* @__PURE__ */jsx("path",{d:"M12 17h.01"})]}),arrowUp:/* @__PURE__ */jsx("path",{d:"M12 19.5V5M6 11l6-6 6 6"}),send:/* @__PURE__ */jsx("path",{d:"M17.306 1.98864C17.7329 0.807956 16.5887 -0.336175 15.408 0.0916395L0.977949 5.31038C-0.206691 5.73918 -0.349954 7.35559 0.739836 7.98694L5.346 10.6536L9.45914 6.54047C9.64549 6.36049 9.89506 6.26091 10.1541 6.26316C10.4132 6.26541 10.661 6.36932 10.8442 6.55251C11.0274 6.73569 11.1313 6.9835 11.1335 7.24256C11.1358 7.50162 11.0362 7.75119 10.8562 7.93754L6.74307 12.0507L9.41073 16.6568C10.0411 17.7466 11.6575 17.6024 12.0863 16.4187L17.306 1.98864Z"})}),FILLED=/* @__PURE__ */Object.freeze({send:/* @__PURE__ */Object.freeze({viewBox:"0 0 17.3973 19.8995"})});function Glyph({name:name,size:size,color:color,fill:fill2,strokeWidth:strokeWidth,style:style}){let filled=FILLED[name],inner=fill2===void 0?"none":fill2===color?"currentColor":fill2;/* @__PURE__ */
|
|
186
186
|
return jsx("svg",{"aria-hidden":"true",focusable:"false",width:size,height:size,viewBox:filled?.viewBox??"0 0 24 24",fill:filled!==void 0?"currentColor":inner,stroke:filled!==void 0?"none":"currentColor",strokeWidth:strokeWidth??2,strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",flexShrink:0,color:color,forcedColorAdjust:"auto",...style},"data-glyph":name,children:PATHS[name]})}var MIN_TOUCH_TARGET=44,CLOSE_DISC_SIZE=36,CLOSE_TOP=12,CLOSE_RIGHT=16,ON_BLACK="#FFFFFF";function AttachmentImageLightbox({image:image,onClose:onClose,returnFocusTo:returnFocusTo}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles2(theme),[theme]),dialog=useModalDialog(image!==null,onClose,returnFocusTo);return image===null?null:/* @__PURE__ */jsxs("dialog",{ref:dialog.dialogRef,"aria-label":fillCopy(CHAT_COPY.previewAttachment,{filename:image.filename}),onCancel:dialog.onCancel,onKeyDown:dialog.onKeyDown,style:styles.lightbox,"data-ef-focus-ring-color":ON_BLACK,children:[
|
|
187
187
|
/* @__PURE__ */jsx("img",{src:image.uri,alt:image.filename,style:styles.image}),
|
|
188
188
|
/* @__PURE__ */jsx("button",{type:"button",onClick:onClose,"aria-label":CHAT_COPY.closePreview,style:styles.closeHit,children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.closeDisc,children:/* @__PURE__ */jsx(Glyph,{name:"x",size:18,color:ON_BLACK})})})]})}function makeStyles2(theme){let r=theme.radius;return{lightbox:{boxSizing:"border-box",position:"fixed",top:0,right:0,bottom:0,left:0,margin:0,width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",padding:0,border:0,backgroundColor:"#000000",display:"flex",alignItems:"center",justifyContent:"center"},image:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",objectFit:"contain"},closeHit:{position:"absolute",top:CLOSE_TOP-(MIN_TOUCH_TARGET-CLOSE_DISC_SIZE)/2,right:CLOSE_RIGHT-(MIN_TOUCH_TARGET-CLOSE_DISC_SIZE)/2,boxSizing:"border-box",width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,minWidth:MIN_TOUCH_TARGET,minHeight:MIN_TOUCH_TARGET,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},closeDisc:{boxSizing:"border-box",width:CLOSE_DISC_SIZE,height:CLOSE_DISC_SIZE,borderRadius:r.pill,backgroundColor:"rgba(0,0,0,0.45)",display:"inline-flex",alignItems:"center",justifyContent:"center"}}}var noop=()=>{};function createBrowserLifecycle(){return{onForeground(listener){if(typeof document>"u"||typeof document.addEventListener!="function")return noop;let wasHidden=document.visibilityState==="hidden",onChange=()=>{let hidden=document.visibilityState==="hidden";wasHidden&&!hidden&&listener(),wasHidden=hidden};return document.addEventListener("visibilitychange",onChange),()=>document.removeEventListener("visibilitychange",onChange)},onOnline(listener){if(typeof window>"u"||typeof window.addEventListener!="function")return noop;let onOnline=()=>listener();return window.addEventListener("online",onOnline),()=>window.removeEventListener("online",onOnline)},isOffline(){return typeof navigator<"u"&&navigator.onLine===false}}}var FILE_FIELD="file",NO_BYTES="chat attachment upload: the file handle carries no bytes",FAILED="chat attachment upload failed";function createWebAttachmentTransport(options={}){let doFetch=options.fetch??((input,init)=>fetch(input,init));/* @__PURE__ */
|
|
@@ -234,8 +234,7 @@ return jsx("li",{children:/* @__PURE__ */jsxs("button",{type:"button","aria-labe
|
|
|
234
234
|
/* @__PURE__ */jsxs("span",{style:styles.rowText,children:[
|
|
235
235
|
/* @__PURE__ */jsx("span",{style:styles.rowTitle,children:conversationTitle(row.title)}),meta!==null?/* @__PURE__ */jsx("span",{style:{...styles.rowMeta,...unread?styles.rowMetaUnread:null},children:meta}):null]}),unread?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.unreadDot}):null]})},row.id)}),canLoadMore?/* @__PURE__ */jsx("li",{ref:observe,style:styles.sentinel,children:observable?null:/* @__PURE__ */jsx("button",{type:"button",onClick:onLoadMore,style:styles.textControl,children:HISTORY_COPY.more})}):null]})}function makeStyles5(theme,drawer){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,control=t.tierSizes.control,dialogSlot=drawer?theme.slots.dialog:void 0,panelInk=slotText(dialogSlot),inputSlot=theme.slots.input,ink=c.text.primary,panel={boxSizing:"border-box",display:"flex",flexDirection:"column",gap:s.md,padding:`${s.lg}px ${s.lg}px ${s.lg}px`,backgroundColor:c.surface,color:ink,overflowY:"auto"},textControl={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET4,minWidth:MIN_TOUCH_TARGET4,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${s.md}px`,borderRadius:r.pill,border:`1px solid ${dialogSlot?.textColor??c.brandInk}`,background:"transparent",color:dialogSlot?.textColor??c.brandInk,cursor:"pointer",...faceCss(theme,"medium"),fontSize:control.body};return{rail:{...panel,flex:`0 0 ${HISTORY_PANEL_WIDTH}px`,width:HISTORY_PANEL_WIDTH,minHeight:0,borderLeft:`1px solid ${c.borderRingCream}`},scrim:{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden",zIndex:1,backgroundColor:withAlpha(c.shadow,SCRIM_ALPHA)??"transparent"},overlay:{...panel,position:"absolute",top:0,bottom:0,left:0,margin:0,width:HISTORY_PANEL_WIDTH,maxWidth:DRAWER_MAX_WIDTH,border:0,borderRadius:0,boxShadow:`0 ${DRAWER_SHADOW.y}px ${DRAWER_SHADOW.blur}px ${withAlpha(c.brand,DRAWER_SHADOW.alpha)??"transparent"}`,outline:"none",...slotCss(dialogSlot),...dialogSlot?.borderRadius===void 0?null:{borderRadius:`0 ${dialogSlot.borderRadius}px ${dialogSlot.borderRadius}px 0`}},head:{display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm},heading:{margin:0,marginRight:"auto",...headingFaceCss(theme,"bold"),fontSize:t.tierSizes.heading.subtitle,lineHeight:`${Math.round(t.tierSizes.heading.subtitle*t.lineHeight.snug)}px`,color:ink,...panelInk},newChat:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET4,display:"inline-flex",alignItems:"center",gap:s.xs+2,margin:0,padding:`0 ${s.lg}px`,border:0,borderRadius:r.pill,backgroundColor:c.primary,color:c.onPrimary,cursor:"pointer",...faceCss(theme,"bold"),fontSize:control.bodyTight,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},searchPill:{boxSizing:"border-box",minWidth:0,minHeight:MIN_TOUCH_TARGET4,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,padding:`0 ${s.md+s.xs/2}px`,borderRadius:r.pill,backgroundColor:c.surface,border:`${SEARCH_EDGE_WIDTH}px solid ${c.brandBorderStrong}`,color:c.text.primary,...slotCss(inputSlot,SEARCH_EDGE_WIDTH)},searchInput:{boxSizing:"border-box",flex:"1 1 auto",minWidth:0,minHeight:MIN_TOUCH_TARGET4-SEARCH_EDGE_WIDTH*2,margin:0,padding:0,border:0,outline:"none",background:"transparent",...faceCss(theme,"regular"),fontSize:Math.max(16,t.size.bodyTight),lineHeight:`${t.size.bodyTight+5}px`,color:c.text.primary,...slotText(inputSlot)},roundControl:{boxSizing:"border-box",flexShrink:0,width:MIN_TOUCH_TARGET4,height:MIN_TOUCH_TARGET4,minWidth:MIN_TOUCH_TARGET4,minHeight:MIN_TOUCH_TARGET4,margin:0,padding:0,border:0,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",background:"transparent",borderRadius:r.pill},count:{margin:`${s.xs}px 0 0`,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+5}px`,color:c.text.muted,...panelInk},state:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:`${t.size.bodyTight+5}px`,color:c.text.muted,...panelInk},stateBody:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+4}px`,color:c.text.muted,...panelInk},stateBlock:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.sm},textControl:textControl,retryControl:{...textControl,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},list:{listStyle:"none",margin:`0 -${s.md}px`,padding:0,display:"flex",flexDirection:"column",gap:2},row:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET4,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,margin:0,padding:`${s.sm+s.xs/2}px ${s.md}px`,border:0,borderRadius:r.md,background:"transparent",color:ink,textAlign:"left",cursor:"pointer",font:"inherit",...panelInk},rowActive:{backgroundColor:withAlpha(c.highlight,ACTIVE_ROW_ALPHA)??"transparent"},rowText:{flex:"1 1 auto",minWidth:0,display:"flex",flexDirection:"column",gap:1},rowTitle:{...faceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*t.lineHeight.snug)}px`,color:c.brandInk,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...panelInk},rowMeta:{...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+5}px`,color:c.text.muted,...panelInk},rowMetaUnread:{...faceCss(theme,"bold"),color:c.text.primary,...panelInk},unreadDot:{boxSizing:"border-box",flexShrink:0,width:UNREAD_DOT_SIZE2,height:UNREAD_DOT_SIZE2,borderRadius:r.pill,backgroundColor:c.danger},sentinel:{minHeight:1,display:"flex",justifyContent:"center",padding:`${s.xs}px 0`}}}var SPINNER_DELAY_MS=300,MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET5=44,INPUT_MAX_HEIGHT=120;var EMPTY_LEAD_RATIO="100 / 12",EMPTY_MIN_HEIGHT=480,EMPTY_GAP=18,BUBBLE_MAX_WIDTH="min(88%, 520px)",BUBBLE_PADDING_Y_TOKEN="md",BUBBLE_PADDING_X_TOKEN="lg",BUBBLE_RADIUS_TOKEN="lg",BUBBLE_TAIL_RADIUS_TOKEN="xs",USER_LINE_HEIGHT=1.5,ASSISTANT_LINE_HEIGHT=1.6;var BUBBLE_SLOT_EDGE_WIDTH=1,PENDING_OPACITY=.6,TURN_GAP_TOKEN="lg",ASSISTANT_INSET_TOKEN="xl",COMPOSER_BORDER_WIDTH=1.5,COMPOSER_PADDING_TOKEN="sm",COMPOSER_LEAD_EXTRA_TOKEN="xs",COMPOSER_GAP_TOKEN="xs",COMPOSER_MIN_HEIGHT=60,INPUT_MIN_HEIGHT=44,INPUT_MIN_FONT_SIZE=16,INPUT_LINE_HEIGHT=1.4,SEND_DISC_SIZE=44,SEND_GLYPH_SIZE=22,STOP_GLYPH_SIZE=18,DISABLED_OPACITY=.4,EARLIER_LETTER_SPACING=.5;var SPINNER_SIZE=24,SPINNER_STROKE=3,SPINNER_LOOP_MS=900,ATTACH_GLYPH_SIZE=20,FOLLOW_UP_EDGE_WIDTH=1.5,ASSISTANT_AVATAR_SIZE=20,FOLLOW_UP_LINE_HEIGHT=1.3,FOOTNOTE_LINE_HEIGHT=1.5;function useChatTheme(){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles6(theme),[theme]);return{theme:theme,styles:styles}}function columnInset(minimum){return`max(${minimum}px, calc((100% - ${CHAT_COLUMN_MAX_WIDTH}px) / 2))`}function linePx(size,ratio){return`${Math.round(size*ratio)}px`}function makeStyles6(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,slots=theme.slots,family=cssFontFamily(t.family),body=t.size.body,inputSize=Math.max(INPUT_MIN_FONT_SIZE,body),inputLine=Math.round(inputSize*INPUT_LINE_HEIGHT),controlSize=t.tierSizes.control,compactSize=t.tierSizes.compact,bubblePadY=s[BUBBLE_PADDING_Y_TOKEN]+s.xs/2,bubblePadX=s[BUBBLE_PADDING_X_TOKEN]+s.xs/2,control={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET5,minWidth:MIN_TOUCH_TARGET5,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,border:0,cursor:"pointer",...faceCss(theme,"medium"),fontSize:controlSize.body,lineHeight:`${Math.round(controlSize.body*t.lineHeight.normal)}px`},sendSlot=slots.sendButton,discFill=sendSlot?.backgroundColor??(sendSlot?.textColor!==void 0?"transparent":c.primary),primaryOutline=c.primaryEdge!==c.primary?c.primaryEdge:null;return{container:{...SURFACE_ROOT_RESET,boxSizing:"border-box",position:"relative",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT,height:"100%",backgroundColor:c.chatGround,color:c.text.primary,fontFamily:family},split:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"row"},main:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:s.xl},spinner:{boxSizing:"border-box",width:SPINNER_SIZE,height:SPINNER_SIZE,borderRadius:r.pill,border:`${SPINNER_STROKE}px solid ${c.brandSofter}`,borderTopColor:c.brandInk},emptyScroller:{boxSizing:"border-box",flex:`1 1 ${EMPTY_MIN_HEIGHT}px`,minHeight:0,overflowY:"auto"},emptyContent:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"stretch",justifyContent:"flex-start",height:"100%",paddingLeft:columnInset(s.lg),paddingRight:columnInset(s.lg),paddingBottom:s.lg,gap:EMPTY_GAP},emptyLead:{flex:"0 1 auto",width:"100%",maxHeight:s.xxl*2,aspectRatio:EMPTY_LEAD_RATIO,minHeight:0,marginBottom:-EMPTY_GAP},errorText:{margin:`0 0 ${s.md}px`,...faceCss(theme,"regular"),fontSize:t.size.subtitle,lineHeight:`${Math.round(t.size.subtitle*t.lineHeight.snug)}px`,color:c.danger,textAlign:"center"},retryButton:{...control,padding:`${s.sm}px ${s.xl}px`,borderRadius:r.pill,backgroundColor:c.brand,color:c.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},setupNotice:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm}px ${s.lg}px`,backgroundColor:c.surfaceCream},setupNoticeText:{...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger},setupNoticeAction:{...control,padding:0,background:"none",border:"none",color:c.brandInk,fontSize:t.size.caption,minHeight:MIN_TOUCH_TARGET5},turnNotice:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.xs,padding:s.md,borderRadius:r.md,backgroundColor:c.surfaceCream,border:`1px solid ${c.borderRingCream}`},turnNoticeError:{border:`1px solid ${c.danger}`},turnNoticeTitle:{...faceCss(theme,"bold"),margin:0,fontSize:t.size.bodyTight,color:c.text.primary},turnNoticeTitleError:{color:c.danger},reconnectingCaption:{...faceCss(theme,"medium"),margin:0,fontSize:t.size.caption,color:c.text.muted,textTransform:"uppercase",letterSpacing:"0.5px"},turnNoticeBody:{...faceCss(theme,"regular"),margin:0,fontSize:t.size.caption,color:c.text.muted},turnNoticeAction:{...control,padding:0,background:"none",border:"none",color:c.brandInk,minHeight:MIN_TOUCH_TARGET5,...faceCss(theme,"bold"),fontSize:t.size.bodyTight},earlierButton:{...control,alignSelf:"center",padding:`0 ${s.md+s.xs/2}px`,backgroundColor:"transparent",color:c.linkInk,...faceCss(theme,"monoBold"),fontSize:compactSize.tiny,lineHeight:`${Math.round(compactSize.tiny*t.lineHeight.snug)}px`,letterSpacing:EARLIER_LETTER_SPACING,textTransform:"uppercase"},list:{boxSizing:"border-box",flex:"1 1 auto",minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column",gap:s[TURN_GAP_TOKEN]+s.xs/2,paddingTop:s.lg,paddingBottom:s.lg,paddingLeft:columnInset(s.lg),paddingRight:columnInset(s.lg)},messageList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:s[TURN_GAP_TOKEN]+s.xs/2},row:{display:"flex",flexDirection:"column"},rowUser:{alignItems:"flex-end"},rowAssistant:{alignItems:"flex-start"},bubble:{boxSizing:"border-box",maxWidth:BUBBLE_MAX_WIDTH,paddingTop:bubblePadY,paddingBottom:bubblePadY,paddingLeft:bubblePadX,paddingRight:bubblePadX,borderRadius:r[BUBBLE_RADIUS_TOKEN],position:"relative"},bubbleUser:{backgroundColor:c.bubbleUser,...primaryOutline!==null&&c.bubbleUser===c.primary?{border:`${BUBBLE_SLOT_EDGE_WIDTH}px solid ${primaryOutline}`}:{},borderBottomRightRadius:r[BUBBLE_TAIL_RADIUS_TOKEN],transformOrigin:"100% 100%",...slotBoxCss(slots.userBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubbleAssistant:{...slots.assistantBubble?.backgroundColor===void 0?{paddingTop:0,paddingBottom:0,paddingLeft:0,paddingRight:s[ASSISTANT_INSET_TOKEN],maxWidth:`min(100%, ${ASSISTANT_MEASURE})`}:{},transformOrigin:"0 100%",...slotBoxCss(slots.assistantBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubbleVet:{backgroundColor:c.bubbleVet,borderTopLeftRadius:r[BUBBLE_TAIL_RADIUS_TOKEN],transformOrigin:"0 100%",...slotBoxCss(slots.vetBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubblePending:{opacity:PENDING_OPACITY},bubbleTextUser:{margin:0,...faceCss(theme,"regular"),color:c.onPrimary,fontSize:body,lineHeight:linePx(body,USER_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.userBubble)},bubbleTextAssistant:{margin:0,...faceCss(theme,"regular"),color:c.text.primary,fontSize:body,lineHeight:linePx(body,ASSISTANT_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.assistantBubble)},bubbleTextVet:{margin:0,...faceCss(theme,"regular"),color:c.onBubbleVet,fontSize:body,lineHeight:linePx(body,USER_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.vetBubble)},senderRow:{display:"flex",flexDirection:"row",alignItems:"baseline",flexWrap:"wrap",gap:s.sm,margin:`0 0 ${s.sm}px`},assistantName:{margin:0,...faceCss(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,lineHeight:linePx(t.size.bodyTight,t.lineHeight.snug)},assistantAvatar:{display:"block",flexShrink:0,alignSelf:"center",width:ASSISTANT_AVATAR_SIZE,height:ASSISTANT_AVATAR_SIZE,borderRadius:r.pill,objectFit:"cover"},vetSender:{margin:0,...faceCss(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight,lineHeight:linePx(t.size.bodyTight,t.lineHeight.snug),overflowWrap:"anywhere"},bubbleBold:faceCss(theme,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:faceCss(theme,"mono"),followUps:{listStyle:"none",margin:`${s.md}px 0 0`,padding:0,display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm},followUpRow:{...control,justifyContent:"flex-start",textAlign:"left",maxWidth:"100%",padding:`${s.sm}px ${s.lg}px`,borderRadius:r.pill,border:`${FOLLOW_UP_EDGE_WIDTH}px solid ${c.brandInk}`,background:c.chatGround,color:c.brandInk,...faceCss(theme,"bold"),fontSize:controlSize.bodyTight,lineHeight:linePx(controlSize.bodyTight,FOLLOW_UP_LINE_HEIGHT),whiteSpace:"normal",overflowWrap:"anywhere",...slotCss(slots.chip,FOLLOW_UP_EDGE_WIDTH)},composerBlock:{boxSizing:"border-box",display:"flex",flexDirection:"column",width:`calc(100% - ${s.md*2}px)`,maxWidth:CHAT_COLUMN_MAX_WIDTH,margin:"0 auto"},composerError:{margin:`${s.xs}px ${s.md}px 0`,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${Math.round(t.size.caption*t.lineHeight.normal)}px`,color:c.danger},composer:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"flex-end",gap:s[COMPOSER_GAP_TOKEN],minHeight:COMPOSER_MIN_HEIGHT,width:"100%",margin:`${s.xs}px 0 0`,paddingTop:s[COMPOSER_PADDING_TOKEN],paddingRight:s[COMPOSER_PADDING_TOKEN],paddingBottom:s[COMPOSER_PADDING_TOKEN],paddingLeft:s.lg+s[COMPOSER_LEAD_EXTRA_TOKEN],backgroundColor:c.chatGround,border:`${COMPOSER_BORDER_WIDTH}px solid ${c.composerBorder}`,borderRadius:r.xl,...slotBoxCss(slots.composerInput,COMPOSER_BORDER_WIDTH)},composerFocused:{border:`${COMPOSER_BORDER_WIDTH}px solid ${slots.composerInput?.borderColor??c.brandInk}`,outline:`${FOCUS_RING_WIDTH}px solid ${c.brandInk}`,outlineOffset:FOCUS_RING_WIDTH},inputWrap:{position:"relative",flex:"1 1 auto",minWidth:0,minHeight:INPUT_MIN_HEIGHT,display:"flex",alignItems:"center"},placeholder:{position:"absolute",top:"50%",left:0,right:0,transform:"translateY(-50%)",pointerEvents:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...faceCss(theme,"regular"),fontSize:inputSize,lineHeight:`${inputLine}px`,color:c.text.placeholder,...slotText(slots.composerInput)},input:{boxSizing:"border-box",flex:"1 1 auto",width:"100%",maxHeight:INPUT_MAX_HEIGHT,margin:0,padding:`${Math.max(0,(INPUT_MIN_HEIGHT-inputLine)/2)}px 0`,border:0,outline:"none",resize:"none",background:"transparent",...faceCss(theme,"regular"),fontSize:inputSize,lineHeight:`${inputLine}px`,color:c.text.primary,...slotText(slots.composerInput)},iconControl:{...control,flexShrink:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",color:c.brandInk},actionButton:{...control,flexShrink:0,padding:0,backgroundColor:"transparent",borderRadius:r.pill},sendDisc:{boxSizing:"border-box",width:SEND_DISC_SIZE,height:SEND_DISC_SIZE,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:SEND_DISC_SIZE/2,backgroundColor:discFill,border:"1px solid transparent",...primaryOutline!==null&&discFill===c.primary?{border:`1.5px solid ${primaryOutline}`}:{},...slotBoxCss(sendSlot)},actionButtonDisabled:{opacity:DISABLED_OPACITY,cursor:"not-allowed"},footnote:{margin:`${s.md}px 0 ${s.sm}px`,padding:`0 ${s.xs}px`,...faceCss(theme,"regular"),color:c.text.muted,fontSize:t.size.caption,lineHeight:linePx(t.size.caption,FOOTNOTE_LINE_HEIGHT)},poweredBy:{margin:0,padding:`0 0 ${s.xs}px`,...faceCss(theme,"regular"),color:c.text.muted,fontSize:compactSize.micro,lineHeight:`${Math.round(compactSize.micro*t.lineHeight.normal)}px`,textAlign:"center"}}}function sendGlyphInk(theme){return theme.slots.sendButton?.textColor??theme.color.onPrimary}var UNREAD_DOT_SIZE3=8;function HistoryBar({bar:bar,history:history,triggerRef:triggerRef,empty:empty,unread:unread=false}){let{theme:theme}=useChatTheme(),cls=bar.classNames,{open:open}=history,count2=history.cursor===null?history.rows.length:0,pill={display:"inline-flex",alignItems:"center",gap:6,minHeight:36,padding:"0 12px",border:"none",borderRadius:999,background:theme.color.surfaceSubtle,color:theme.color.text.primary,font:"inherit",fontSize:theme.type.size.caption,cursor:"pointer"};/* @__PURE__ */
|
|
236
236
|
return jsxs("div",{className:cls?.bar,style:cls?.bar?void 0:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 12px"},children:[
|
|
237
|
-
/* @__PURE__ */jsxs("button",{ref:triggerRef,type:"button",className:cls?.chats,style:cls?.chats?void 0:pill,"aria-expanded":open,onClick:open?history.close:history.show,children:[bar.renderIcon?bar.renderIcon("history"):null,bar.chats,
|
|
238
|
-
/* @__PURE__ */jsx("span",{className:cls?.count,style:cls?.count?void 0:{fontWeight:700},children:count2>0?count2:""}),unread?/* @__PURE__ */jsx("span",{"aria-hidden":"true","data-testid":"everfur-chat-history-bar-unread",className:cls?.unreadDot,style:cls?.unreadDot?void 0:{width:UNREAD_DOT_SIZE3,height:UNREAD_DOT_SIZE3,borderRadius:999,background:theme.color.danger,flexShrink:0}}):null]}),bar.extra??null,empty?null:/* @__PURE__ */jsxs("button",{type:"button",className:cls?.newChat,style:cls?.newChat?void 0:pill,onClick:history.newConversation,children:[bar.renderIcon?bar.renderIcon("edit"):null,bar.newChat]})]})}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf2(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentation(client){return useEverfurPresentationState(client).presentation}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf2(client);return useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}function definedPresentation(input){let out={};for(let[key,value]of Object.entries(input))value!==void 0&&(out[key]=value);return out}var TELEVET_FOLLOW_UP=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function excludes(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpPolicyFor(host,presentation,countLocked){let televet=presentation.chatFollowUpsExcludeTelevet,count2=host?.count!==void 0&&!countLocked?host.count:presentation.chatFollowUpCount;if(host===void 0&&count2===MAX_VISIBLE_FOLLOW_UPS&&!televet)return;if(count2<=0)return{...host??{},count:1,exclude:NONE,fill:[]};let hostExclude=host?.exclude,exclude=televet?prompt=>TELEVET_FOLLOW_UP.test(prompt)||excludes(hostExclude,prompt):hostExclude;return{...host??{},count:count2,...exclude!==void 0?{exclude:exclude}:{}}}function historyDayLabel(iso,now=/* @__PURE__ */new Date,locale){let date2=new Date(iso);if(Number.isNaN(date2.getTime()))return null;let a=new Date(now);a.setHours(0,0,0,0);let b=new Date(date2);b.setHours(0,0,0,0);let days=Math.round((a.getTime()-b.getTime())/864e5);if(days===0||days===1)try{let word=new Intl.RelativeTimeFormat(locale,{numeric:"auto"}).format(-days,"day");return word.charAt(0).toLocaleUpperCase(locale)+word.slice(1)}catch{}return date2.toLocaleDateString(locale,{month:"short",day:"numeric"})}function historyTime(iso,locale){let date2=new Date(iso);return Number.isNaN(date2.getTime())?null:date2.toLocaleTimeString(locale,{hour:"numeric",minute:"2-digit"})}function groupByDay(rows,now=/* @__PURE__ */new Date){let groups=[];for(let row of rows){let day=historyDayLabel(row.updatedAt,now)??"",last=groups[groups.length-1];last!==void 0&&last.day===day?last.rows.push(row):groups.push({day:day,rows:[row]})}return groups}function sheetIcon(sheet,name,fallback){if(sheet?.renderIcon!==void 0)try{return sheet.renderIcon(name)}catch{}return fallback}function HistorySheet({chat:chat,history:history,sheet:sheet,returnFocusTo:returnFocusTo}){let{theme:theme}=useChatTheme(),open=history.open,dialog=useModalDialog(open,history.close,returnFocusTo),cls=sheet?.classNames??{},groups=useMemo(()=>groupByDay(history.rows),[history.rows]);if(!open)return null;let c=theme.color,mono={...faceCss(theme,"mono"),fontSize:10.5,letterSpacing:".06em",textTransform:"uppercase",color:c.text.muted},inline=(key,style)=>cls[key]?void 0:style,join=key=>cls[key]?[cls[key],cls.open].filter(Boolean).join(" "):void 0,title=sheet?.title??HISTORY_COPY.heading,container=null;try{container=sheet?.container?.()??null}catch{container=null}let body=/* @__PURE__ */jsxs(Fragment,{children:[
|
|
237
|
+
/* @__PURE__ */jsxs("button",{ref:triggerRef,type:"button",className:cls?.chats,style:cls?.chats?void 0:pill,"aria-expanded":open,onClick:open?history.close:history.show,children:[bar.renderIcon?bar.renderIcon("history"):null,bar.chats,count2>0?/* @__PURE__ */jsx("span",{className:cls?.count,style:cls?.count?void 0:{fontWeight:700},children:count2}):null,unread?/* @__PURE__ */jsx("span",{"aria-hidden":"true","data-testid":"everfur-chat-history-bar-unread",className:cls?.unreadDot,style:cls?.unreadDot?void 0:{width:UNREAD_DOT_SIZE3,height:UNREAD_DOT_SIZE3,borderRadius:999,background:theme.color.danger,flexShrink:0}}):null]}),bar.extra??null,empty?null:/* @__PURE__ */jsxs("button",{type:"button",className:cls?.newChat,style:cls?.newChat?void 0:pill,onClick:history.newConversation,children:[bar.renderIcon?bar.renderIcon("edit"):null,bar.newChat]})]})}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf2(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentation(client){return useEverfurPresentationState(client).presentation}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf2(client);return useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}function definedPresentation(input){let out={};for(let[key,value]of Object.entries(input))value!==void 0&&(out[key]=value);return out}var TELEVET_FOLLOW_UP=new RegExp([String.raw`\b(book|booking|schedule|scheduling|arrange|set\s+up)\s+(an?\s+|the\s+|her\s+|his\s+|their\s+|my\s+|your\s+)?(next\s+)?((vet|veterinary|video|virtual|televet|follow-up|follow up)\s+)?(visit|appointment|appt|consult|consultation|call|vet|checkup|check-up|exam)\b`,String.raw`\bmake\s+(an?\s+|the\s+)?((vet|veterinary|video|virtual|follow-up|follow up)\s+)?(appointment|appt)\b`,String.raw`\bneed\s+(an?\s+)?((vet|veterinary|video|virtual)\s+)?(appointment|appt|visit|consult|consultation)\b`,String.raw`\b(video|virtual)\s+(visit|appointment|appt|consult|consultation|call)s?\b`,String.raw`\b(televet|telehealth|telemedicine)\b`,String.raw`\b(talk|speak|chat)\s+(to|with)\s+(an?|the|your|my)\s+vet\b`,String.raw`\bsee\s+(an?|the|your|my)\s+vet\b`].join("|"),"i"),NONE=()=>true;function excludes(rule,prompt){if(rule===void 0)return false;if(typeof rule=="function")try{return rule(prompt)===!0}catch{return false}return rule.lastIndex=0,rule.test(prompt)}function followUpPolicyFor(host2,presentation,countLocked){let televet=presentation.chatFollowUpsExcludeTelevet,count2=host2?.count!==void 0&&!countLocked?host2.count:presentation.chatFollowUpCount;if(host2===void 0&&count2===MAX_VISIBLE_FOLLOW_UPS&&!televet)return;if(count2<=0)return{...host2??{},count:1,exclude:NONE,fill:[]};let hostExclude=host2?.exclude,exclude=televet?prompt=>TELEVET_FOLLOW_UP.test(prompt)||excludes(hostExclude,prompt):hostExclude;return{...host2??{},count:count2,...exclude!==void 0?{exclude:exclude}:{}}}function historyDayLabel(iso,now=/* @__PURE__ */new Date,locale){let date2=new Date(iso);if(Number.isNaN(date2.getTime()))return null;let a=new Date(now);a.setHours(0,0,0,0);let b=new Date(date2);b.setHours(0,0,0,0);let days=Math.round((a.getTime()-b.getTime())/864e5);if(days===0||days===1)try{let word=new Intl.RelativeTimeFormat(locale,{numeric:"auto"}).format(-days,"day");return word.charAt(0).toLocaleUpperCase(locale)+word.slice(1)}catch{}return date2.toLocaleDateString(locale,{month:"short",day:"numeric"})}function historyTime(iso,locale){let date2=new Date(iso);return Number.isNaN(date2.getTime())?null:date2.toLocaleTimeString(locale,{hour:"numeric",minute:"2-digit"})}function groupByDay(rows,now=/* @__PURE__ */new Date){let groups=[];for(let row of rows){let day=historyDayLabel(row.updatedAt,now)??"",last=groups[groups.length-1];last!==void 0&&last.day===day?last.rows.push(row):groups.push({day:day,rows:[row]})}return groups}function sheetIcon(sheet,name,fallback){if(sheet?.renderIcon!==void 0)try{return sheet.renderIcon(name)}catch{}return fallback}function HistorySheet({chat:chat,history:history,sheet:sheet,returnFocusTo:returnFocusTo}){let{theme:theme}=useChatTheme(),open=history.open,dialog=useModalDialog(open,history.close,returnFocusTo),cls=sheet?.classNames??{},groups=useMemo(()=>groupByDay(history.rows),[history.rows]);if(!open)return null;let c=theme.color,mono={...faceCss(theme,"mono"),fontSize:10.5,letterSpacing:".06em",textTransform:"uppercase",color:c.text.muted},inline=(key,style)=>cls[key]?void 0:style,join=key=>cls[key]?[cls[key],cls.open].filter(Boolean).join(" "):void 0,title=sheet?.title??HISTORY_COPY.heading,container=null;try{container=sheet?.container?.()??null}catch{container=null}let body=/* @__PURE__ */jsxs(Fragment,{children:[
|
|
239
238
|
/* @__PURE__ */jsx("div",{className:join("scrim"),onClick:history.close,style:inline("scrim",{position:"absolute",inset:0,zIndex:40,background:"rgba(38, 37, 35, .38)"})}),
|
|
240
239
|
/* @__PURE__ */jsxs("div",{ref:node=>{dialog.dialogRef.current=node},className:join("sheet"),role:"dialog","aria-modal":"true","aria-label":title,tabIndex:-1,onKeyDown:dialog.onKeyDown,style:inline("sheet",{position:"absolute",left:0,right:0,bottom:0,zIndex:41,maxHeight:"80%",overflowY:"auto",boxSizing:"border-box",background:c.surface,borderRadius:"28px 28px 0 0",padding:"10px 20px 40px"}),children:[
|
|
241
240
|
/* @__PURE__ */jsx("div",{className:cls.grab,"aria-hidden":"true",style:inline("grab",{width:40,height:5,borderRadius:3,background:c.borderRingCream,margin:"0 auto 10px"})}),
|
|
@@ -253,11 +252,11 @@ return jsxs("button",{type:"button",className:cls.row,"aria-label":openConversat
|
|
|
253
252
|
/* @__PURE__ */jsx("small",{style:cls.row?void 0:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13.5,color:c.text.muted},children:row.preview??"…"})]}),
|
|
254
253
|
/* @__PURE__ */jsxs("span",{style:{alignSelf:"start",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:6},children:[
|
|
255
254
|
/* @__PURE__ */jsx("span",{className:[cls.time,unread?cls.timeUnread:void 0].filter(Boolean).join(" ")||void 0,style:inline("time",{marginTop:3,...mono,letterSpacing:".04em",textTransform:"none",...unread?{...faceCss(theme,"bold"),color:c.text.primary}:null}),children:historyTime(row.updatedAt)??""}),unread?/* @__PURE__ */jsx("span",{"aria-hidden":"true","data-testid":`everfur-chat-history-sheet-unread-${String(row.id)}`,className:cls.unreadDot,style:inline("unreadDot",{width:8,height:8,borderRadius:999,background:c.danger})}):null]})]},String(row.id))})]},group.day))}),history.cursor!==null&&!history.loadingMore?/* @__PURE__ */jsx("button",{type:"button",onClick:history.loadMore,style:{marginTop:8,border:"none",background:"transparent",color:c.brandInk,...faceCss(theme,"bold"),cursor:"pointer"},children:HISTORY_COPY.more}):null,
|
|
256
|
-
/* @__PURE__ */jsxs("button",{type:"button",className:cls.newChat,onClick:history.newConversation,style:inline("newChat",{width:"100%",marginTop:16,minHeight:52,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:8,border:"none",borderRadius:999,background:c.primary,color:c.onPrimary,...faceCss(theme,"bold"),fontSize:16,cursor:"pointer"}),children:[sheetIcon(sheet,"edit",/* @__PURE__ */jsx(Glyph,{name:"squarePen",size:18,color:"currentColor"})),HISTORY_COPY.newChat]})]})]});return container!==null?createPortal(body,container):body}var RAPH_V3_LIGHT=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),cache=/* @__PURE__ */new WeakMap;function v3Palette(theme){let hit=cache.get(theme);if(hit!==void 0)return hit;let c=theme.color,dark=theme.brightness==="dark",neutrals=dark?{dark:dark,ink:c.text.primary,ink2:c.text.secondary,ink3:c.text.muted,paper:c.background,card:c.surface,line:c.borderRingCream,tile:c.surfaceSubtle,shadow:c.shadow,riskBg:c.badgeBgCritical,riskInk:c.danger,riskDot:c.danger,clearBg:c.badgeBgPositive,clearInk:c.success,clearDot:c.success,watchDot:c.warningStrong}:{dark:dark,...RAPH_V3_LIGHT},textOn=(ink,grounds2)=>pushToContrast(ink,grounds2,poleForGrounds(grounds2),V3_TEXT_CONTRAST),labelOn=(ink,
|
|
257
|
-
return jsx(Glyph,{name:"x",size:18,color:color})}function TopCard({card:card,state:
|
|
258
|
-
return jsx("div",{className:cls.wrap,hidden:!
|
|
255
|
+
/* @__PURE__ */jsxs("button",{type:"button",className:cls.newChat,onClick:history.newConversation,style:inline("newChat",{width:"100%",marginTop:16,minHeight:52,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:8,border:"none",borderRadius:999,background:c.primary,color:c.onPrimary,...faceCss(theme,"bold"),fontSize:16,cursor:"pointer"}),children:[sheetIcon(sheet,"edit",/* @__PURE__ */jsx(Glyph,{name:"squarePen",size:18,color:"currentColor"})),HISTORY_COPY.newChat]})]})]});return container!==null?createPortal(body,container):body}var RAPH_V3_LIGHT=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),cache=/* @__PURE__ */new WeakMap;function v3Palette(theme){let hit=cache.get(theme);if(hit!==void 0)return hit;let c=theme.color,dark=theme.brightness==="dark",neutrals=dark?{dark:dark,ink:c.text.primary,ink2:c.text.secondary,ink3:c.text.muted,paper:c.background,card:c.surface,line:c.borderRingCream,tile:c.surfaceSubtle,shadow:c.shadow,riskBg:c.badgeBgCritical,riskInk:c.danger,riskDot:c.danger,clearBg:c.badgeBgPositive,clearInk:c.success,clearDot:c.success,watchDot:c.warningStrong}:{dark:dark,...RAPH_V3_LIGHT},textOn=(ink,grounds2)=>pushToContrast(ink,grounds2,poleForGrounds(grounds2),V3_TEXT_CONTRAST),labelOn=(ink,fill2)=>contrastRatio(ink,fill2)>=V3_TEXT_CONTRAST?ink:legibleOn(fill2,V3_TEXT_CONTRAST),badgeGrounds=[neutrals.card,neutrals.paper].map(under=>flattenOnto(c.brandSoft,under)??under),brand={primary:c.primary,onPrimary:labelOn(c.onPrimary,c.primary),accent:c.accent,onAccent:labelOn(c.onAccent,c.accent),link:textOn(c.linkInk,[neutrals.card,neutrals.paper,neutrals.tile]),badge:c.brandSoft,onBadge:textOn(c.brandInk,badgeGrounds)},palette=/* @__PURE__ */Object.freeze({...neutrals,...brand});return cache.set(theme,palette),palette}var V3_TEXT_CONTRAST=4.5;function v3InkOn(fill2,inks){for(let ink of inks)if(contrastRatio(ink,fill2)>=V3_TEXT_CONTRAST)return ink;return legibleOn(fill2,V3_TEXT_CONTRAST)}var MIN_TOUCH_TARGET6=44,CLOSE_BLEED_Y=12,CLOSE_BLEED_RIGHT=14,CLOSE_BLEED_LEFT=6;function useTopCardState(){let[open,setOpen]=useState(true),closeRef=useRef(null),pillRef=useRef(null),id=`ef-top-card-${useId().replace(/:/g,"")}`,show=useCallback(next=>{setOpen(next);let move=()=>(next?closeRef.current:pillRef.current)?.focus({preventScroll:true});typeof requestAnimationFrame=="function"?requestAnimationFrame(move):move()},[]);return useMemo(()=>({open:open,show:show,closeRef:closeRef,pillRef:pillRef,id:id}),[open,show,id])}function icon(card,color){if(card.renderIcon!==void 0)try{return card.renderIcon("close")}catch{}/* @__PURE__ */
|
|
256
|
+
return jsx(Glyph,{name:"x",size:18,color:color})}function TopCard({card:card,state:state3,ask:ask}){let{theme:theme}=useChatTheme(),v3=v3Palette(theme),cls=card.classNames??{},titleId=`${state3.id}-title`,inline=(key,style)=>cls[key]?void 0:style,action=card.action,question=card.ask,bold=faceCss(theme,"bold"),Title=headingTag(nextHeadingLevel(useChatHeadingLevel()));/* @__PURE__ */
|
|
257
|
+
return jsx("div",{className:cls.wrap,hidden:!state3.open,children:/* @__PURE__ */jsxs("section",{className:cls.card,id:state3.id,"aria-labelledby":titleId,style:inline("card",{boxSizing:"border-box",width:"100%",padding:"14px 16px 16px",borderRadius:20,background:v3.card,color:v3.ink,textAlign:"left",boxShadow:`0 1px 3px ${v3.shadow}`}),children:[
|
|
259
258
|
/* @__PURE__ */jsxs("p",{className:cls.kicker,style:inline("kicker",{display:"flex",alignItems:"center",gap:8,margin:0,...bold,fontWeight:800,fontSize:15}),children:[cls.kicker?card.kicker:/* @__PURE__ */jsx("span",{style:{minWidth:0,overflowWrap:"anywhere"},children:card.kicker}),card.badge!==void 0?
|
|
260
|
-
/* @__PURE__ */jsx("span",{className:cls.badges,style:inline("badges",{marginLeft:"auto",display:"flex",gap:4}),children:/* @__PURE__ */jsx("span",{className:cls.badge,style:inline("badge",{display:"inline-flex",alignItems:"center",height:24,padding:"0 9px",borderRadius:999,background:v3.badge,color:v3.onBadge,...bold,fontWeight:700,fontSize:12,whiteSpace:"nowrap"}),children:card.badge})}):null,card.closeLabel!==void 0?/* @__PURE__ */jsx("button",{ref:
|
|
259
|
+
/* @__PURE__ */jsx("span",{className:cls.badges,style:inline("badges",{marginLeft:"auto",display:"flex",gap:4}),children:/* @__PURE__ */jsx("span",{className:cls.badge,style:inline("badge",{display:"inline-flex",alignItems:"center",height:24,padding:"0 9px",borderRadius:999,background:v3.badge,color:v3.onBadge,...bold,fontWeight:700,fontSize:12,whiteSpace:"nowrap"}),children:card.badge})}):null,card.closeLabel!==void 0?/* @__PURE__ */jsx("button",{ref:state3.closeRef,className:cls.close,type:"button","aria-label":card.closeLabel,onClick:()=>state3.show(false),style:inline("close",{display:"grid",placeItems:"center",flex:"none",boxSizing:"border-box",width:MIN_TOUCH_TARGET6,height:MIN_TOUCH_TARGET6,margin:`-${CLOSE_BLEED_Y}px -${CLOSE_BLEED_RIGHT}px -${CLOSE_BLEED_Y}px ${card.badge===void 0?"auto":`-${CLOSE_BLEED_LEFT}px`}`,padding:0,border:"none",borderRadius:999,background:"transparent",color:v3.ink2,cursor:"pointer"}),children:icon(card,v3.ink2)}):null]}),
|
|
261
260
|
/* @__PURE__ */jsx(Title,{id:titleId,className:cls.title,style:inline("title",{margin:"10px 0 0",...bold,fontWeight:800,fontSize:18,lineHeight:1.22,color:v3.ink,overflowWrap:"anywhere"}),children:card.title}),
|
|
262
261
|
/* @__PURE__ */jsxs("div",{className:cls.content,children:[card.lead!==void 0||card.body!==void 0?
|
|
263
262
|
/* @__PURE__ */jsxs("p",{className:cls.finding,style:inline("finding",{display:"grid",gridTemplateColumns:"9px minmax(0, 1fr)",gap:9,alignItems:"baseline",margin:"6px 0 0",fontSize:14.5,lineHeight:1.45,color:v3.ink2}),children:[
|
|
@@ -265,11 +264,11 @@ return jsx("div",{className:cls.wrap,hidden:!state.open,children:/* @__PURE__ */
|
|
|
265
264
|
/* @__PURE__ */jsxs("span",{children:[card.lead!==void 0?/* @__PURE__ */jsx("b",{style:cls.finding?void 0:{...bold,fontWeight:800,color:v3.ink},children:card.lead}):null,card.lead!==void 0&&card.body!==void 0?" ":null,card.body??null]})]}):null,action!==void 0||question!==void 0?
|
|
266
265
|
/* @__PURE__ */jsxs("div",{className:cls.actions,style:inline("actions",{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"4px 16px",marginTop:12}),children:[action!==void 0?
|
|
267
266
|
/* @__PURE__ */jsx("button",{className:cls.action,type:"button",onClick:()=>{try{action.onPress()}catch{}},style:inline("action",{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:8,minHeight:40,padding:"0 16px",border:"none",borderRadius:999,background:v3.primary,color:v3.onPrimary,...bold,fontWeight:700,fontSize:15,cursor:"pointer"}),children:action.label}):null,question!==void 0?
|
|
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:
|
|
267
|
+
/* @__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
268
|
/* @__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"]),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
|
-
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?.
|
|
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=5e3,sharedReads=/* @__PURE__ */new WeakMap;function readShared(reader,userRef2,petRef2,
|
|
272
|
-
return Object.freeze({...tier,borderColor:borderColor,backgroundColor:
|
|
269
|
+
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);return t===null?null:clean({title:t,body:str4(s?.body),source:str4(s?.source,200),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,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),added=str4(v?.added,80);return key===null||t===null||action===null||added===null?null:clean({key:key,title:t,body:str4(v?.body),price:str4(v?.price,40),was:str4(v?.was,40),tag:str4(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added,owned:v?.owned===true?true:null})},6);return title===null||items===null?null:clean({title:title,items:items})}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),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),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__ */
|
|
270
|
+
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=5e3,sharedReads=/* @__PURE__ */new WeakMap;function readShared(reader,userRef2,petRef2,fresh4){let reads=sharedReads.get(reader);reads===void 0&&(reads=/* @__PURE__ */new Map,sharedReads.set(reader,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,userRef2,pet,fresh4),[hostRepository,repository,own,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({...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
272
|
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
273
|
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:[
|
|
275
274
|
/* @__PURE__ */jsxs("p",{style:{...styles.label,color:paint.title},children:[tier.level==="emergency"?/* @__PURE__ */jsx(Glyph,{name:"alert",size:ALERT_GLYPH_SIZE,color:paint.title}):null,
|
|
@@ -279,18 +278,18 @@ return jsxs("div",{ref:ref,role:urgent?"alert":"status","aria-hidden":exiting?tr
|
|
|
279
278
|
/* @__PURE__ */jsx("span",{children:label})]}),poison=emergency?/* @__PURE__ */jsxs("a",{href:POISON_CONTROL_TEL,style:{...styles.pill,...styles.ghost,borderColor:paint.title,color:paint.title},children:[
|
|
280
279
|
/* @__PURE__ */jsx(Glyph,{name:"phone",size:PIN_GLYPH_SIZE,color:paint.title}),
|
|
281
280
|
/* @__PURE__ */jsx("span",{children:CHAT_COPY.poisonControlWeb})]}):null,vet=renderVetAction!==void 0?/* @__PURE__ */jsx(HostRender,{render:()=>renderVetAction(level),fallback:pill,resetKey:level}):pill;return vet===null&&poison===null?null:/* @__PURE__ */jsxs("div",{style:styles.actionRow,children:[vet,poison]})}function CompactIcon({exiting:exiting,onExpand:onExpand,styles:styles}){let ref=useRef(null),motion=useChatMotion(),theme=useEverfurTheme();return useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:motion.iconInMs,fromOpacity:0});return()=>animation?.cancel()},[motion.iconInMs]),useEffect(()=>{exiting&&animateExit(ref.current,motion.iconOutMs)},[exiting,motion.iconOutMs]),/* @__PURE__ */jsx("div",{ref:ref,"aria-hidden":exiting?true:void 0,style:styles.iconRow,children:/* @__PURE__ */jsx("button",{type:"button",onClick:onExpand,"aria-label":CHAT_COPY.showLatestVetAlert,style:styles.iconButton,children:/* @__PURE__ */jsx(Glyph,{name:"info",size:INFO_GLYPH_SIZE,color:theme.color.text.muted})})})}function makeStyles7(theme){let s=theme.space,r=theme.radius,t=theme.type,heading=t.tierSizes.heading,control=t.tierSizes.control;return{banner:{position:"relative",boxSizing:"border-box",width:`calc(100% - ${s.lg*2}px)`,maxWidth:CHAT_COLUMN_MAX_WIDTH,margin:`${s.sm}px auto ${s.xs}px`,padding:`${s.lg}px ${s.lg+s.xs/2}px`,borderRadius:r.lg,borderStyle:"solid",borderWidth:BANNER_BORDER,display:"flex",flexDirection:"column",gap:s.xs},label:{margin:0,paddingRight:DISMISS_SIZE,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,...faceCss(theme,"bold"),fontSize:heading.body,lineHeight:`${Math.round(heading.body*t.lineHeight.snug)}px`},reason:{margin:0,paddingRight:DISMISS_SIZE,...faceCss(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*1.5)}px`,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},erLine:{...faceCss(theme,"bold")},actionRow:{display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm,marginTop:s.sm},pill:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET7,display:"inline-flex",flexDirection:"row",alignItems:"center",gap:s.sm,margin:0,padding:`0 ${s.lg}px`,borderRadius:r.pill,borderStyle:"solid",borderWidth:ACTION_EDGE,cursor:"pointer",textDecoration:"none",...faceCss(theme,"bold"),fontSize:control.bodyTight,lineHeight:`${Math.round(control.bodyTight*t.lineHeight.snug)}px`},ghost:{backgroundColor:"transparent"},dismissHit:{position:"absolute",top:6-(MIN_TOUCH_TARGET7-DISMISS_SIZE)/2,right:6-(MIN_TOUCH_TARGET7-DISMISS_SIZE)/2,boxSizing:"border-box",width:MIN_TOUCH_TARGET7,height:MIN_TOUCH_TARGET7,minWidth:MIN_TOUCH_TARGET7,minHeight:MIN_TOUCH_TARGET7,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},dismissDisc:{boxSizing:"border-box",width:DISMISS_SIZE,height:DISMISS_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center"},iconRow:{display:"flex",flexDirection:"row",justifyContent:"flex-end",padding:`2px ${s.lg}px ${s.xs}px`},iconButton:{boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET7,minHeight:MIN_TOUCH_TARGET7,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}}}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}function liveCheckinIds(placements){let live=/* @__PURE__ */new Set;for(let[id,placement]of placements)placement.kind==="live"&&live.add(id);return live}var TIER_DOT_COLOR=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),TIER_DOT_UNKNOWN="#C8BEB4";function tierColor(authorityTier){return authorityTier?TIER_DOT_COLOR[authorityTier.toUpperCase()]??TIER_DOT_UNKNOWN:TIER_DOT_UNKNOWN}function tierLabel(authorityTier){if(!authorityTier)return null;let match=/^tier[_\s-]?(\d+)$/i.exec(authorityTier.trim());return match?`Tier ${match[1]}`:authorityTier}function text2(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}function httpsUrl(value){let raw=text2(value);return raw!==null&&/^https:\/\/\S+$/i.test(raw)?raw:null}function toCitationCard(raw,index){let sourceName=text2(raw.source_name)??text2(raw.sourceName),section=text2(raw.section),authorityTier=text2(raw.authority_tier)??text2(raw.authorityTier),label=tierLabel(authorityTier),title=sourceName??text2(raw.title)??`Source ${index+1}`,chunkId=text2(raw.monograph_chunk_id)??text2(raw.chunkId),meta=[section,label].filter(part=>part!==null).join(" · ");/* @__PURE__ */
|
|
282
|
-
return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl(raw.url),excerpt:text2(raw.excerpt),tierColor:tierColor(authorityTier),key:`${title}-${chunkId??"none"}-${index}`})}function toCitationCards(citations){return citations===void 0||citations.length===0?EMPTY_CARDS:/* @__PURE__ */Object.freeze(citations.map((citation,index)=>toCitationCard(citation,index)))}var EMPTY_CARDS=/* @__PURE__ */Object.freeze([]);function sourcesLabel(count2){return count2===1?`1 ${CHAT_COPY.sourceSingular}`:`${count2} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count2,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count2)}`}function citationA11yLabel(card){return[card.url!==null?`${CHAT_COPY.openSource}: ${card.title}`:card.title,card.meta,card.excerpt].filter(part=>part!==null&&part.length>0).join(". ")}function answerParagraphs(text3){let parts=text3.split(/\n\s*\n/).map(part=>part.trim()).filter(part=>part.length>0);return parts.length>0?parts:[text3]}var BULLET_LINE=/^\s*[-*]\s+(\S.*)$/,NUMBERED_LINE=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function answerBlocks(paragraph){let blocks=[],text3=[],list=null,flushText=()=>{text3.length>0&&blocks.push({kind:"text",text:text3.join(`\n`)}),text3=[]},flushList=()=>{list!==null&&blocks.push(list.ordered?{kind:"list",ordered:true,start:list.start,items:list.items}:{kind:"list",ordered:false,items:list.items}),list=null};for(let line of paragraph.split(`\n`)){let bullet=BULLET_LINE.exec(line),numbered=bullet===null?NUMBERED_LINE.exec(line):null,item=bullet?.[1]??numbered?.[2];if(item===void 0){flushList(),text3.push(line);continue}let ordered=numbered!==null;flushText(),list!==null&&list.ordered!==ordered&&flushList(),list===null&&(list={ordered:ordered,start:numbered===null?1:Number(numbered[1]),items:[]}),list.items.push(item.trim())}return flushText(),flushList(),blocks}function questionFor(messages,messageId){let at=messages.findIndex(message=>message.id===messageId);for(let i=at-1;i>=0;i-=1){let message=messages[i];if(message!==void 0&&message.role==="user")return message.text}return null}function hostList(fn,context){if(fn===void 0)return[];try{let out=fn(context);return Array.isArray(out)?out:[]}catch{return[]}}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}var MIN_TOUCH_TARGET8=44,RADIO_SIZE=20,NOTES_ROWS=3,PENDING_OPACITY2=.6;function FeedbackReasons(props){let{open:open,onSubmit:onSubmit,onClose:onClose,returnFocusTo:returnFocusTo}=props,theme=useEverfurTheme(),styles=useMemo(()=>makeStyles8(theme),[theme]),dialog=useModalDialog(open,onClose,returnFocusTo),[reason,setReason]=useState(null),[notes,setNotes]=useState(""),[
|
|
283
|
-
return jsxs("dialog",{ref:dialog.dialogRef,"aria-label":CHAT_COPY.feedbackTitle,"aria-busy":
|
|
281
|
+
return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl(raw.url),excerpt:text2(raw.excerpt),tierColor:tierColor(authorityTier),key:`${title}-${chunkId??"none"}-${index}`})}function toCitationCards(citations){return citations===void 0||citations.length===0?EMPTY_CARDS:/* @__PURE__ */Object.freeze(citations.map((citation,index)=>toCitationCard(citation,index)))}var EMPTY_CARDS=/* @__PURE__ */Object.freeze([]);function sourcesLabel(count2){return count2===1?`1 ${CHAT_COPY.sourceSingular}`:`${count2} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count2,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count2)}`}function citationA11yLabel(card){return[card.url!==null?`${CHAT_COPY.openSource}: ${card.title}`:card.title,card.meta,card.excerpt].filter(part=>part!==null&&part.length>0).join(". ")}function answerParagraphs(text3){let parts=text3.split(/\n\s*\n/).map(part=>part.trim()).filter(part=>part.length>0);return parts.length>0?parts:[text3]}var BULLET_LINE=/^\s*[-*]\s+(\S.*)$/,NUMBERED_LINE=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function answerBlocks(paragraph){let blocks=[],text3=[],list=null,flushText=()=>{text3.length>0&&blocks.push({kind:"text",text:text3.join(`\n`)}),text3=[]},flushList=()=>{list!==null&&blocks.push(list.ordered?{kind:"list",ordered:true,start:list.start,items:list.items}:{kind:"list",ordered:false,items:list.items}),list=null};for(let line of paragraph.split(`\n`)){let bullet=BULLET_LINE.exec(line),numbered=bullet===null?NUMBERED_LINE.exec(line):null,item=bullet?.[1]??numbered?.[2];if(item===void 0){flushList(),text3.push(line);continue}let ordered=numbered!==null;flushText(),list!==null&&list.ordered!==ordered&&flushList(),list===null&&(list={ordered:ordered,start:numbered===null?1:Number(numbered[1]),items:[]}),list.items.push(item.trim())}return flushText(),flushList(),blocks}function questionFor(messages,messageId){let at=messages.findIndex(message=>message.id===messageId);for(let i=at-1;i>=0;i-=1){let message=messages[i];if(message!==void 0&&message.role==="user")return message.text}return null}function hostList(fn,context){if(fn===void 0)return[];try{let out=fn(context);return Array.isArray(out)?out:[]}catch{return[]}}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}var MIN_TOUCH_TARGET8=44,RADIO_SIZE=20,NOTES_ROWS=3,PENDING_OPACITY2=.6;function FeedbackReasons(props){let{open:open,onSubmit:onSubmit,onClose:onClose,returnFocusTo:returnFocusTo}=props,theme=useEverfurTheme(),styles=useMemo(()=>makeStyles8(theme),[theme]),dialog=useModalDialog(open,onClose,returnFocusTo),[reason,setReason]=useState(null),[notes,setNotes]=useState(""),[pending2,setPending]=useState(false),[failed,setFailed]=useState(false);if(!open)return null;let submit=()=>{if(pending2)return;setPending(true),setFailed(false);let trimmed=notes.trim();onSubmit(reason,trimmed.length>0?trimmed:null).then(took=>{setPending(false),took?onClose():setFailed(true)})};/* @__PURE__ */
|
|
282
|
+
return jsxs("dialog",{ref:dialog.dialogRef,"aria-label":CHAT_COPY.feedbackTitle,"aria-busy":pending2?true:void 0,onCancel:dialog.onCancel,onKeyDown:dialog.onKeyDown,style:styles.sheet,children:[
|
|
284
283
|
/* @__PURE__ */jsx("h2",{style:styles.title,children:CHAT_COPY.feedbackTitle}),
|
|
285
284
|
/* @__PURE__ */jsx("p",{style:styles.subtitle,children:CHAT_COPY.feedbackSubtitle}),
|
|
286
285
|
/* @__PURE__ */jsx("div",{role:"group","aria-label":CHAT_COPY.feedbackTitle,style:styles.options,children:FEEDBACK_REASONS.map(option=>{let selected=option.key===reason;/* @__PURE__ */
|
|
287
|
-
return jsxs("button",{type:"button","aria-pressed":selected,disabled:
|
|
286
|
+
return jsxs("button",{type:"button","aria-pressed":selected,disabled:pending2,onClick:()=>setReason(selected?null:option.key),style:{...styles.option,...selected?styles.optionSelected:styles.optionRest},children:[
|
|
288
287
|
/* @__PURE__ */jsx("span",{style:styles.optionLabel,children:option.label}),
|
|
289
288
|
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:{...styles.radio,...selected?styles.radioSelected:null},children:selected?/* @__PURE__ */jsx(Glyph,{name:"check",size:12,color:theme.color.surface,strokeWidth:3}):null})]},option.key)})}),
|
|
290
|
-
/* @__PURE__ */jsx("textarea",{rows:NOTES_ROWS,value:notes,disabled:
|
|
289
|
+
/* @__PURE__ */jsx("textarea",{rows:NOTES_ROWS,value:notes,disabled:pending2,"aria-label":CHAT_COPY.feedbackNotesPlaceholder,placeholder:CHAT_COPY.feedbackNotesPlaceholder,onChange:event=>{let next=event.target.value;[...next].length<=FEEDBACK_NOTES_MAX_CHARS&&setNotes(next)},style:styles.notes}),failed?/* @__PURE__ */jsx("p",{role:"alert",style:styles.failed,children:CHAT_COPY.feedbackFailed}):null,
|
|
291
290
|
/* @__PURE__ */jsxs("div",{style:styles.actions,children:[
|
|
292
|
-
/* @__PURE__ */jsx("button",{type:"button",onClick:submit,"aria-disabled":
|
|
293
|
-
/* @__PURE__ */jsx("button",{type:"button",onClick:onClose,"aria-label":CHAT_COPY.feedbackSkipA11y,disabled:
|
|
291
|
+
/* @__PURE__ */jsx("button",{type:"button",onClick:submit,"aria-disabled":pending2,style:{...styles.submit,...pending2?styles.pending:null},children:CHAT_COPY.feedbackSubmit}),
|
|
292
|
+
/* @__PURE__ */jsx("button",{type:"button",onClick:onClose,"aria-label":CHAT_COPY.feedbackSkipA11y,disabled:pending2,style:styles.skip,children:CHAT_COPY.feedbackSkip})]})]})}function makeStyles8(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,bodyLineHeight=`${Math.round(t.size.body*t.lineHeight.normal)}px`,heading=t.tierSizes.heading.heading,controlSize=t.tierSizes.control.body,dialogText=slotText(theme.slots.dialog),control={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET8,minWidth:MIN_TOUCH_TARGET8,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,cursor:"pointer",...faceCss(theme,"medium"),fontSize:t.size.body,lineHeight:bodyLineHeight};return{sheet:{boxSizing:"border-box",position:"fixed",top:"auto",right:0,bottom:0,left:0,margin:0,width:"100%",maxWidth:"100%",maxHeight:"80vh",overflowY:"auto",padding:`${s.lg+4}px ${s.lg+4}px ${s.xxl}px`,border:0,borderRadius:`${r.lg}px ${r.lg}px 0 0`,backgroundColor:c.surface,color:c.text.primary,display:"flex",flexDirection:"column",gap:s.md,...sheetSlotCss(theme.slots.dialog)},title:{margin:0,...headingFaceCss(theme,"bold"),fontSize:heading,lineHeight:`${Math.round(heading*1.22)}px`,color:c.text.primary,...dialogText},subtitle:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.body,lineHeight:bodyLineHeight,color:c.text.muted,...dialogText},options:{display:"flex",flexDirection:"column",gap:s.sm},option:{...control,width:"100%",justifyContent:"space-between",gap:s.md,padding:`${s.sm}px ${s.md}px`,borderRadius:r.md,border:`1px solid ${c.controlEdge}`,backgroundColor:c.surfaceCream,color:c.text.primary,textAlign:"left",...slotRadius(theme.slots.chip)},optionSelected:{border:`1px solid ${c.brandInk}`,backgroundColor:c.brandSoft},optionRest:slotCss(theme.slots.chip,1),optionLabel:{flex:"1 1 auto",minWidth:0},radio:{boxSizing:"border-box",flexShrink:0,width:RADIO_SIZE,height:RADIO_SIZE,borderRadius:r.pill,border:`1.5px solid ${c.brandBorderStrong}`,backgroundColor:c.surface,display:"inline-flex",alignItems:"center",justifyContent:"center"},radioSelected:{border:`1.5px solid ${c.brandInk}`,backgroundColor:c.brandInk},notes:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET8,margin:0,padding:`${s.sm}px ${s.md}px`,borderRadius:r.md,border:`1px solid ${c.brandBorderStrong}`,backgroundColor:c.surfaceCream,color:c.text.primary,resize:"vertical",...faceCss(theme,"regular"),fontSize:t.size.body,lineHeight:bodyLineHeight,...slotCss(theme.slots.input,1)},failed:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger},actions:{display:"flex",flexDirection:"column",alignItems:"stretch",gap:s.sm},submit:{...control,fontSize:controlSize,padding:`0 ${s.xl}px`,border:0,borderRadius:r.pill,backgroundColor:c.brand,color:c.onPrimary,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},pending:{opacity:PENDING_OPACITY2,cursor:"progress"},skip:{...control,fontSize:controlSize,padding:`0 ${s.xl}px`,border:0,borderRadius:r.pill,background:"transparent",color:c.text.secondary}}}var MIN_TOUCH_TARGET9=44,GLYPH_SIZE=15,ROW_HEIGHT=16;function canCopyToClipboard(){return typeof navigator<"u"&&typeof navigator.clipboard?.writeText=="function"}function MessageFooter(props){let{role:role,text:text3,createdAt:createdAt,responseId:responseId,sentiment:sentiment,feedback:feedback}=props,theme=useEverfurTheme(),styles=useMemo(()=>makeStyles9(theme),[theme]),timeLabel=useMemo(()=>formatMessageTime(createdAt),[createdAt]),flow=useFeedbackFlow(responseId,sentiment,feedback),downRef=useRef(null);/* @__PURE__ */
|
|
294
293
|
return jsxs("div",{style:{...styles.footer,...role==="user"?styles.footerUser:styles.footerAssistant},children:[
|
|
295
294
|
/* @__PURE__ */jsxs("div",{style:styles.row,children:[timeLabel!==null?/* @__PURE__ */jsx("span",{style:styles.timestamp,children:timeLabel}):null,
|
|
296
295
|
/* @__PURE__ */jsx(CopyMessageButton,{role:role,text:text3}),role==="assistant"&&responseId!==void 0?SENTIMENT_OPTIONS.map(option=>{let active=sentiment===option.sentiment,color=theme.color.sentiment[option.sentiment];/* @__PURE__ */
|
|
@@ -323,11 +322,11 @@ return jsxs("div",{style:styles.card,children:[
|
|
|
323
322
|
/* @__PURE__ */jsx("button",{ref:previewRef,type:"button","aria-label":fillCopy(CHAT_COPY.previewAttachment,{filename:row.filename}),onClick:()=>onPreview(image,previewRef.current),style:styles.previewButton,children:/* @__PURE__ */jsx("img",{src:row.previewUri,alt:"",style:styles.thumb})}),row.status==="uploading"?/* @__PURE__ */jsx("div",{role:"status","aria-busy":"true","aria-label":fillCopy(CHAT_COPY.previewAttachment,{filename:row.filename}),style:{...styles.wash,backgroundColor:withAlpha(theme.color.brandInk,UPLOADING_ALPHA)??theme.color.brandSofter},children:/* @__PURE__ */jsx(Spinner,{styles:styles})}):null,row.status==="uploaded"&&flash?/* @__PURE__ */jsx("div",{"aria-hidden":"true",style:{...styles.wash,backgroundColor:SUCCESS_WASH}}):null,row.status==="failed"?/* @__PURE__ */jsx("button",{type:"button","aria-label":fillCopy(CHAT_COPY.retryUpload,{filename:row.filename}),onClick:()=>onRetry(row.id),style:{...styles.wash,...styles.retry,backgroundColor:FAILED_WASH},children:/* @__PURE__ */jsx(Glyph,{name:"upload",size:18,color:"#FFFFFF"})}):null,
|
|
324
323
|
/* @__PURE__ */jsx("button",{type:"button","aria-label":fillCopy(CHAT_COPY.removeAttachment,{filename:row.filename}),onClick:()=>onRemove(row.id),style:styles.removeHit,children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.removeDisc,children:/* @__PURE__ */jsx(Glyph,{name:"x",size:12,color:theme.color.surface,strokeWidth:2.5})})})]})}function Spinner({styles:styles}){let motion=useChatMotion(),ref=useRef(null);return useEffect(()=>{let node=ref.current;if(motion.reduced||!canAnimate(node))return;let animation=node.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:SPINNER_LOOP_MS2,iterations:1/0,easing:"linear"});return()=>animation.cancel()},[motion.reduced]),/* @__PURE__ */jsx("span",{ref:ref,"aria-hidden":"true",style:styles.spinner})}function MessageAttachments({images:images,onPreview:onPreview}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles10(theme),[theme]);if(images.length===0)return null;let single=images.length===1;/* @__PURE__ */
|
|
325
324
|
return jsx("ul",{style:single?styles.singleList:styles.gridList,children:images.map((image,index)=>/* @__PURE__ */jsx("li",{children:/* @__PURE__ */jsx(ImageButton,{image:image,style:single?styles.singleImage:styles.gridImage,onPreview:onPreview})},`${image.uri}-${index}`))})}function ImageButton({image:image,style:style,onPreview:onPreview}){let ref=useRef(null);/* @__PURE__ */
|
|
326
|
-
return jsx("button",{ref:ref,type:"button","aria-label":fillCopy(CHAT_COPY.attachedImage,{filename:image.filename}),onClick:()=>onPreview(image,ref.current),style:style,children:/* @__PURE__ */jsx("img",{src:image.uri,alt:"",style:{display:"block",width:"100%",height:"100%",objectFit:"cover"}})})}function makeStyles10(theme){let c=theme.color,s=theme.space,r=theme.radius,imageButton={boxSizing:"border-box",display:"block",margin:0,padding:0,border:0,overflow:"hidden",cursor:"pointer",backgroundColor:c.surfaceSubtle};return{tray:{listStyle:"none",margin:`0 ${s.md}px`,padding:`${s.xs}px 0`,display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm},cardSlot:{flex:"0 0 auto"},card:{position:"relative",boxSizing:"border-box",width:CARD_SIZE,height:CARD_SIZE},previewButton:{...imageButton,width:CARD_SIZE,height:CARD_SIZE,borderRadius:CARD_RADIUS,border:`1px solid ${c.brandBorder}`},thumb:{display:"block",width:"100%",height:"100%",objectFit:"cover"},wash:{position:"absolute",top:0,right:0,bottom:0,left:0,borderRadius:CARD_RADIUS,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},retry:{pointerEvents:"auto",margin:0,padding:0,border:0,cursor:"pointer",minWidth:CARD_SIZE,minHeight:CARD_SIZE},spinner:{boxSizing:"border-box",display:"block",width:SPINNER_SIZE2,height:SPINNER_SIZE2,borderRadius:r.pill,border:`${SPINNER_STROKE2}px solid rgba(255,255,255,0.45)`,borderTopColor:"#FFFFFF"},removeHit:{position:"absolute",top:4-(MIN_TOUCH_TARGET10-REMOVE_SIZE)/2,right:4-(MIN_TOUCH_TARGET10-REMOVE_SIZE)/2,boxSizing:"border-box",width:MIN_TOUCH_TARGET10,height:MIN_TOUCH_TARGET10,minWidth:MIN_TOUCH_TARGET10,minHeight:MIN_TOUCH_TARGET10,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},removeDisc:{boxSizing:"border-box",width:REMOVE_SIZE,height:REMOVE_SIZE,borderRadius:r.pill,backgroundColor:"rgba(0,0,0,0.78)",border:`1.5px solid ${c.surface}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},singleList:{listStyle:"none",margin:`0 0 ${s.sm}px`,padding:0},gridList:{listStyle:"none",margin:`0 0 ${s.sm}px`,padding:0,display:"flex",flexWrap:"wrap",gap:GRID_GAP},singleImage:{...imageButton,width:SINGLE_IMAGE_SIZE,height:SINGLE_IMAGE_SIZE,maxWidth:"100%",borderRadius:SINGLE_IMAGE_RADIUS},gridImage:{...imageButton,width:GRID_IMAGE_SIZE,height:GRID_IMAGE_SIZE,borderRadius:GRID_IMAGE_RADIUS}}}var CHECKIN_COPY=/* @__PURE__ */Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" · ",answers:/* @__PURE__ */Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),CHECKIN_OPTIONS=/* @__PURE__ */Object.freeze(CHECKIN_ANSWERS.map(answer=>/* @__PURE__ */Object.freeze({answer:answer,label:CHECKIN_COPY.answers[answer]})));function useCheckinCard(checkin,answerCheckin){let[
|
|
327
|
-
return jsx("li",{style:styles.row,children:/* @__PURE__ */jsxs("div",{role:"group","aria-label":CHECKIN_COPY.eyebrow,"aria-busy":
|
|
325
|
+
return jsx("button",{ref:ref,type:"button","aria-label":fillCopy(CHAT_COPY.attachedImage,{filename:image.filename}),onClick:()=>onPreview(image,ref.current),style:style,children:/* @__PURE__ */jsx("img",{src:image.uri,alt:"",style:{display:"block",width:"100%",height:"100%",objectFit:"cover"}})})}function makeStyles10(theme){let c=theme.color,s=theme.space,r=theme.radius,imageButton={boxSizing:"border-box",display:"block",margin:0,padding:0,border:0,overflow:"hidden",cursor:"pointer",backgroundColor:c.surfaceSubtle};return{tray:{listStyle:"none",margin:`0 ${s.md}px`,padding:`${s.xs}px 0`,display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm},cardSlot:{flex:"0 0 auto"},card:{position:"relative",boxSizing:"border-box",width:CARD_SIZE,height:CARD_SIZE},previewButton:{...imageButton,width:CARD_SIZE,height:CARD_SIZE,borderRadius:CARD_RADIUS,border:`1px solid ${c.brandBorder}`},thumb:{display:"block",width:"100%",height:"100%",objectFit:"cover"},wash:{position:"absolute",top:0,right:0,bottom:0,left:0,borderRadius:CARD_RADIUS,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},retry:{pointerEvents:"auto",margin:0,padding:0,border:0,cursor:"pointer",minWidth:CARD_SIZE,minHeight:CARD_SIZE},spinner:{boxSizing:"border-box",display:"block",width:SPINNER_SIZE2,height:SPINNER_SIZE2,borderRadius:r.pill,border:`${SPINNER_STROKE2}px solid rgba(255,255,255,0.45)`,borderTopColor:"#FFFFFF"},removeHit:{position:"absolute",top:4-(MIN_TOUCH_TARGET10-REMOVE_SIZE)/2,right:4-(MIN_TOUCH_TARGET10-REMOVE_SIZE)/2,boxSizing:"border-box",width:MIN_TOUCH_TARGET10,height:MIN_TOUCH_TARGET10,minWidth:MIN_TOUCH_TARGET10,minHeight:MIN_TOUCH_TARGET10,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},removeDisc:{boxSizing:"border-box",width:REMOVE_SIZE,height:REMOVE_SIZE,borderRadius:r.pill,backgroundColor:"rgba(0,0,0,0.78)",border:`1.5px solid ${c.surface}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},singleList:{listStyle:"none",margin:`0 0 ${s.sm}px`,padding:0},gridList:{listStyle:"none",margin:`0 0 ${s.sm}px`,padding:0,display:"flex",flexWrap:"wrap",gap:GRID_GAP},singleImage:{...imageButton,width:SINGLE_IMAGE_SIZE,height:SINGLE_IMAGE_SIZE,maxWidth:"100%",borderRadius:SINGLE_IMAGE_RADIUS},gridImage:{...imageButton,width:GRID_IMAGE_SIZE,height:GRID_IMAGE_SIZE,borderRadius:GRID_IMAGE_RADIUS}}}var CHECKIN_COPY=/* @__PURE__ */Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" · ",answers:/* @__PURE__ */Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),CHECKIN_OPTIONS=/* @__PURE__ */Object.freeze(CHECKIN_ANSWERS.map(answer=>/* @__PURE__ */Object.freeze({answer:answer,label:CHECKIN_COPY.answers[answer]})));function useCheckinCard(checkin,answerCheckin){let[pending2,setPending]=useState(null),[error,setError]=useState(null),[tapped,setTapped]=useState(null),choose=useCallback(answer2=>{answerCheckin!==null&&(setPending(answer2),setError(null),answerCheckin(checkin.caseId,answer2).then(result=>{setPending(null),result.ok?setTapped(answer2):setError(result.error)}))},[answerCheckin,checkin.caseId]),answer=tapped??checkin.answer;return{answer:answer,answerable:!isCheckinSettled(checkin),escalated:answer==="worse",pending:pending2,error:error,choose:choose}}var MIN_TOUCH_TARGET11=44,PENDING_OPACITY3=.6;function CheckinCard({message:message,checkin:checkin,onAnswer:onAnswer,onFindVet:onFindVet}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles11(theme),[theme]),state3=useCheckinCard(checkin,onAnswer),settled=state3.answer!==null||state3.pending!==null,answerable=onAnswer!==null&&state3.answerable;/* @__PURE__ */
|
|
326
|
+
return jsx("li",{style:styles.row,children:/* @__PURE__ */jsxs("div",{role:"group","aria-label":CHECKIN_COPY.eyebrow,"aria-busy":state3.pending!==null?true:void 0,style:styles.card,children:[
|
|
328
327
|
/* @__PURE__ */jsx("p",{style:styles.eyebrow,children:CHECKIN_COPY.eyebrow}),
|
|
329
|
-
/* @__PURE__ */jsx("p",{style:styles.question,children:message.text}),answerable?/* @__PURE__ */jsx("div",{style:{...styles.answers,...
|
|
330
|
-
return jsx("button",{type:"button",onClick:()=>
|
|
328
|
+
/* @__PURE__ */jsx("p",{style:styles.question,children:message.text}),answerable?/* @__PURE__ */jsx("div",{style:{...styles.answers,...state3.pending?styles.answersPending:null},children:CHECKIN_OPTIONS.map(({answer:answer,label:label})=>{let selected=(state3.pending??state3.answer)===answer;/* @__PURE__ */
|
|
329
|
+
return jsx("button",{type:"button",onClick:()=>state3.choose(answer),disabled:settled,"aria-pressed":selected,style:{...styles.pill,...selected?styles.pillSelected:null},children:label},answer)})}):null,state3.answer!==null?/* @__PURE__ */jsx("p",{style:styles.logged,children:CHECKIN_COPY.logged}):null,checkin.resolutionText?/* @__PURE__ */jsx("p",{style:styles.question,children:checkin.resolutionText}):null,state3.escalated&&onFindVet?/* @__PURE__ */jsx("button",{type:"button",onClick:onFindVet,style:styles.findVet,children:CHECKIN_COPY.findVet}):null,state3.error?/* @__PURE__ */jsx("p",{role:"alert",style:styles.error,children:state3.error.displayMessage}):null]})})}function makeStyles11(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,regular=faceCss(theme,"regular"),text3={margin:0,...regular,fontSize:t.size.body,lineHeight:`${Math.round(t.size.body*t.lineHeight.normal)}px`},compact=t.tierSizes.compact,control=t.tierSizes.control,cardText=slotText(theme.slots.card);return{row:{display:"flex",justifyContent:"flex-start",listStyle:"none"},card:{boxSizing:"border-box",maxWidth:"92%",padding:s.md,display:"flex",flexDirection:"column",gap:s.sm,borderRadius:r.lg,backgroundColor:c.surface,border:`1px solid ${c.brandBorder}`,...slotCss(theme.slots.card,1)},eyebrow:{margin:0,...regular,color:c.text.secondary,fontSize:compact.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},question:{...text3,color:c.text.primary,whiteSpace:"pre-wrap",...cardText},answers:{display:"flex",gap:s.sm,marginTop:s.xs},answersPending:{opacity:PENDING_OPACITY3},pill:{...text3,fontSize:control.body,lineHeight:`${Math.round(control.body*t.lineHeight.normal)}px`,boxSizing:"border-box",flex:1,minHeight:MIN_TOUCH_TARGET11,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:`0 ${s.md}px`,borderRadius:r.pill,border:`1px solid ${c.controlEdge}`,backgroundColor:c.surfaceCream,color:c.text.primary,cursor:"pointer"},pillSelected:{backgroundColor:c.brand,borderColor:c.brandInk,color:c.onPrimary},logged:{margin:0,...regular,color:c.text.secondary,fontSize:t.size.caption,...cardText},error:{margin:0,...regular,color:c.danger,fontSize:t.size.caption},findVet:{boxSizing:"border-box",alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET11,borderRadius:r.pill,border:`1.5px solid ${c.controlEdge}`,backgroundColor:c.surface,color:c.brandInk,cursor:"pointer",...faceCss(theme,"bold"),fontSize:t.size.body}}}var MIN_TOUCH_TARGET12=44,CARD_WIDTH=244,TIER_DOT_SIZE=8,PILL_GLYPH_SIZE=13,LINK_GLYPH_SIZE=14,TITLE_LINES=2,EXCERPT_LINES=3,SOURCE_PILL_HEIGHT=32;function CitationCards({citations:citations}){let cards=useMemo(()=>toCitationCards(citations),[citations]),theme=useEverfurTheme(),styles=useMemo(()=>makeStyles12(theme),[theme]),[expanded,setExpanded]=useState(false);return cards.length===0?null:/* @__PURE__ */jsxs("div",{style:styles.wrap,children:[
|
|
331
330
|
/* @__PURE__ */jsx("button",{type:"button","aria-expanded":expanded,"aria-label":sourcesToggleLabel(cards.length,expanded),onClick:()=>setExpanded(current=>!current),style:styles.pill,children:/* @__PURE__ */jsxs("span",{style:styles.pillFace,children:[
|
|
332
331
|
/* @__PURE__ */jsx(Glyph,{name:"bookOpen",size:PILL_GLYPH_SIZE,color:theme.color.text.muted}),
|
|
333
332
|
/* @__PURE__ */jsx("span",{style:styles.pillLabel,children:sourcesLabel(cards.length)}),
|
|
@@ -342,13 +341,13 @@ return jsxs(Fragment,{children:[
|
|
|
342
341
|
/* @__PURE__ */Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:PILL_ACTIVITY_ON_WHITE,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
|
|
343
342
|
/* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:QUICK_PROMPT_BRAND_EDGE,brandEdge:true,borderWidth:1}),
|
|
344
343
|
/* @__PURE__ */Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}’s vet visit",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]);function quickPromptThemePaint(everfurLook,highlight){return everfurLook?null:{fill:highlight.fill,ink:highlight.ink}}var STARTER_PROMPTS_MAX=8;function cleanColor(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length>0&&trimmed.length<=64&&!/[;{}<>]/u.test(trimmed)?trimmed:null}function resolveStarterPrompts(prompts){if(!Array.isArray(prompts))return null;let out=[];for(let entry of prompts){if(out.length>=STARTER_PROMPTS_MAX)break;if(entry===null||typeof entry!="object"||typeof entry.label!="string")continue;let label=entry.label.trim();if(label.length===0)continue;let prompt=typeof entry.prompt=="string"&&entry.prompt.trim().length>0?entry.prompt.trim():label,tint=cleanColor(entry.tint);out.push(/* @__PURE__ */Object.freeze({id:`starter-${out.length}`,label:label,prompt:prompt,tint:tint,ink:tint===null?null:cleanColor(entry.ink)}))}return out.length>0?/* @__PURE__ */Object.freeze(out):null}var TRAILING_SIZE_SUFFIX_RE=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function formatBreedForPrompt(breed){return breed==null?breed:breed.replace(TRAILING_SIZE_SUFFIX_RE,"").trim()}var UNINFORMATIVE_BREEDS=/* @__PURE__ */new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function isUninformativeBreed(breed){let key=String(breed??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return UNINFORMATIVE_BREEDS.has(key)}function unspecifiedBreedLabel(species){return species==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function emptyStateTitle(pet){let petName=pet?.name?.trim()||CHAT_COPY.emptyTitlePetFallback;return fillCopy(CHAT_COPY.emptyTitle,{petName:petName})}function isPlaceholderBreed(breed){let lower=breed.toLowerCase();return lower===unspecifiedBreedLabel("dog").toLowerCase()||lower===unspecifiedBreedLabel("cat").toLowerCase()}function chipBreed(breed){let formatted=formatBreedForPrompt(breed);if(isUninformativeBreed(formatted))return null;let clean2=String(formatted).replace(/\s+/gu," ").trim();return isPlaceholderBreed(clean2)?null:clean2}function resolveQuickPrompts(pet,brandEdge=QUICK_PROMPT_BRAND_EDGE,options){let known=canonicalPetSpecies(pet?.species),trimmedPetName=pet?.name?.trim()||null,breedToken=chipBreed(pet?.breed),age=petAgeYears(pet?.ageYears),ageToken=age===null?null:String(age),vetPrepLabel=options?.vetPrepLabel?.trim()||null;/* @__PURE__ */
|
|
345
|
-
return Object.freeze(PROMPTS.flatMap(template=>{let own=template.intent==="vet_report"&&vetPrepLabel!==null?vetPrepLabel:template.label,usesBreed=own.includes("{breed}"),usesAge=own.includes("{ageYears}"),baseLabel=template.fallbackLabel!==void 0&&(usesBreed&&!breedToken||usesAge&&!ageToken)&&template.fallbackLabel?template.fallbackLabel:own;if(baseLabel.includes("{breed}")&&breedToken===null||baseLabel.includes("{ageYears}")&&ageToken===null||known===null&&(baseLabel.includes("{species}")||baseLabel.includes("{petName}")&&trimmedPetName===null))return[];let resolvedLabel=fillCopy(baseLabel,{petName:trimmedPetName??(known==="cat"?"my cat":"my dog"),breed:breedToken??"",species:known??"",ageYears:ageToken??""}),label=!trimmedPetName&&baseLabel.startsWith("{petName}")?resolvedLabel.charAt(0).toUpperCase()+resolvedLabel.slice(1):resolvedLabel;return[/* @__PURE__ */Object.freeze({id:template.id,intent:template.intent,label:label,background:template.background,borderColor:template.brandEdge===true?brandEdge:template.borderColor,borderWidth:template.borderWidth})]}))}var NO_STYLE=/* @__PURE__ */Object.freeze({}),LIST_RESET=/* @__PURE__ */Object.freeze({listStyle:"none",margin:0,padding:0}),MIN_TOUCH_TARGET13=44,TITLE_SIZE=30,TITLE_SIZE_DESKTOP=38,TITLE_LINE_HEIGHT=1.1,TITLE_LETTER_SPACING="-0.03em",CHIPS_OFFSET_EXTRA=4;function QuickPrompts({pet:pet,onSend:onSend,onVetPrep:onVetPrep,starterPrompts:starterPrompts,emptyState:emptyState}){let theme=useEverfurTheme(),{desktop:desktop}=useChatLayout(),styles=useMemo(()=>makeStyles13(theme,desktop),[theme,desktop]),motion=useChatMotion(),hostTitle=emptyState?.title?.trim(),title=hostTitle!==void 0&&hostTitle!==""?hostTitle:emptyStateTitle(pet),cls=emptyState?.classNames,Heading=headingTag(useChatHeadingLevel()),hostChips=useMemo(()=>resolveStarterPrompts(starterPrompts),[starterPrompts]),cycle=useMemo(()=>(emptyState?.chipTints??[]).filter(t=>typeof t.tint=="string"&&t.tint.trim()!==""),[emptyState?.chipTints]),drawn=useMemo(()=>hostChips!==null?hostChips.map(
|
|
344
|
+
return Object.freeze(PROMPTS.flatMap(template=>{let own=template.intent==="vet_report"&&vetPrepLabel!==null?vetPrepLabel:template.label,usesBreed=own.includes("{breed}"),usesAge=own.includes("{ageYears}"),baseLabel=template.fallbackLabel!==void 0&&(usesBreed&&!breedToken||usesAge&&!ageToken)&&template.fallbackLabel?template.fallbackLabel:own;if(baseLabel.includes("{breed}")&&breedToken===null||baseLabel.includes("{ageYears}")&&ageToken===null||known===null&&(baseLabel.includes("{species}")||baseLabel.includes("{petName}")&&trimmedPetName===null))return[];let resolvedLabel=fillCopy(baseLabel,{petName:trimmedPetName??(known==="cat"?"my cat":"my dog"),breed:breedToken??"",species:known??"",ageYears:ageToken??""}),label=!trimmedPetName&&baseLabel.startsWith("{petName}")?resolvedLabel.charAt(0).toUpperCase()+resolvedLabel.slice(1):resolvedLabel;return[/* @__PURE__ */Object.freeze({id:template.id,intent:template.intent,label:label,background:template.background,borderColor:template.brandEdge===true?brandEdge:template.borderColor,borderWidth:template.borderWidth})]}))}var NO_STYLE=/* @__PURE__ */Object.freeze({}),LIST_RESET=/* @__PURE__ */Object.freeze({listStyle:"none",margin:0,padding:0}),MIN_TOUCH_TARGET13=44,TITLE_SIZE=30,TITLE_SIZE_DESKTOP=38,TITLE_LINE_HEIGHT=1.1,TITLE_LETTER_SPACING="-0.03em",CHIPS_OFFSET_EXTRA=4;function QuickPrompts({pet:pet,onSend:onSend,onVetPrep:onVetPrep,starterPrompts:starterPrompts,emptyState:emptyState}){let theme=useEverfurTheme(),{desktop:desktop}=useChatLayout(),styles=useMemo(()=>makeStyles13(theme,desktop),[theme,desktop]),motion=useChatMotion(),hostTitle=emptyState?.title?.trim(),title=hostTitle!==void 0&&hostTitle!==""?hostTitle:emptyStateTitle(pet),cls=emptyState?.classNames,Heading=headingTag(useChatHeadingLevel()),hostChips=useMemo(()=>resolveStarterPrompts(starterPrompts),[starterPrompts]),cycle=useMemo(()=>(emptyState?.chipTints??[]).filter(t=>typeof t.tint=="string"&&t.tint.trim()!==""),[emptyState?.chipTints]),drawn=useMemo(()=>hostChips!==null?hostChips.map(host2=>({chip:{id:host2.id,intent:"send",label:host2.label,background:host2.tint??theme.color.highlight,borderColor:"transparent",borderWidth:1},send:host2.prompt,paint:host2.tint===null?{fill:theme.color.highlight,ink:theme.color.onHighlight}:{fill:host2.tint,ink:host2.ink??theme.color.text.primary},tinted:host2.tint!==null})):resolveQuickPrompts(pet,theme.color.brandInk,{vetPrepLabel:VET_PREP_LABEL_WEB}).filter(chip=>chip.intent!=="vet_report"||onVetPrep!==null).map(chip=>({chip:chip,send:chip.label,paint:null,tinted:false})),[hostChips,pet,onVetPrep,theme.color.brandInk,theme.color.highlight,theme.color.onHighlight,theme.color.text.primary]),chips=useMemo(()=>cycle.length===0?drawn:drawn.map((d,index)=>{if(d.tinted)return d;let t=cycle[index%cycle.length];return{...d,paint:{fill:t.tint,ink:t.ink??theme.color.text.primary},tinted:true}}),[drawn,cycle,theme.color.text.primary]),themed=useMemo(()=>quickPromptThemePaint(isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),[theme]);/* @__PURE__ */
|
|
346
345
|
return jsxs("div",{...cls?.start?{className:cls.start}:{style:styles.wrap},children:[
|
|
347
346
|
/* @__PURE__ */jsx(Heading,{...cls?.title?{className:cls.title}:{style:styles.title},children:title}),
|
|
348
347
|
/* @__PURE__ */jsx("ul",{"aria-label":CHAT_COPY.suggestions,...cls?.list?{className:cls.list,style:LIST_RESET}:{style:styles.list},children:chips.map(({chip:chip,send:send,paint:paint,tinted:tinted},index)=>/* @__PURE__ */jsx("li",{children:/* @__PURE__ */jsx(Chip,{chip:chip,themed:paint??themed,delayMs:followUpDelayMs(motion,index),durationMs:motion.followUpInMs,risePx:motion.promptRisePx,style:cls?.chip?NO_STYLE:styles.chip,...cls?.chip?{className:cls.chip}:{},slotStyle:tinted&&paint!==null?{...styles.chipSlot,backgroundColor:paint.fill,color:paint.ink}:styles.chipSlot,onPress:()=>chip.intent==="vet_report"?onVetPrep?.():onSend(send)})},chip.id))})]})}function Chip({chip:chip,themed:themed,delayMs:delayMs,durationMs:durationMs,risePx:risePx,style:style,className:className,slotStyle:slotStyle,onPress:onPress}){let ref=useRef(null);return useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:durationMs,delayMs:delayMs,fromOpacity:0,fromTranslateY:risePx});return()=>animation?.cancel()},[durationMs,delayMs,risePx]),/* @__PURE__ */jsx("button",{ref:ref,type:"button",...className===void 0?{}:{className:className},onClick:onPress,style:{...themed===null?{...style,backgroundColor:chip.background}:{...style,backgroundColor:themed.fill,color:themed.ink},...slotStyle},children:chip.label})}function makeStyles13(theme,desktop){let s=theme.space,r=theme.radius,t=theme.type,titleSize=tierPx(theme,"heading",desktop?TITLE_SIZE_DESKTOP:TITLE_SIZE),chipSize=t.tierSizes.compact.bodyTight;return{wrap:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.lg+CHIPS_OFFSET_EXTRA,width:"100%"},title:{margin:0,...headingFaceCss(theme,"medium"),fontSize:titleSize,lineHeight:`${Math.round(titleSize*TITLE_LINE_HEIGHT)}px`,letterSpacing:TITLE_LETTER_SPACING,color:theme.color.brandInk,textAlign:"left",textWrap:"balance"},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"row",flexWrap:"wrap",alignItems:"flex-start",gap:s.sm},chip:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET13,minWidth:MIN_TOUCH_TARGET13,maxWidth:"100%",display:"inline-flex",alignItems:"center",justifyContent:"flex-start",margin:0,padding:`${s.sm-1}px ${s.lg-1}px`,border:"1px solid transparent",borderRadius:r.pill,cursor:"pointer",...faceCss(theme,"bold"),fontSize:chipSize,lineHeight:`${Math.round(chipSize*1.3)}px`,color:QUICK_PROMPT_TEXT_COLOR,textAlign:"left",whiteSpace:"normal"},chipSlot:slotCss(ownGroundSlot(theme.slots.chip),1)}}var DOT_SIZE=6,DOT_RISE=3,LOOP_MS=1e3,STAGGER_MS=150,OPACITY_REST=.25,OPACITY_STATIC=.5,DOT_INDICES=[0,1,2];function TypingIndicator({petName:petName}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles14(theme),[theme]),animate=!theme.motion.reducedMotion;/* @__PURE__ */
|
|
349
348
|
return jsxs("div",{style:styles.card,children:[
|
|
350
349
|
/* @__PURE__ */jsx("p",{style:styles.line,children:forPet(CHAT_COPY.reading,petName)}),
|
|
351
|
-
/* @__PURE__ */jsx("span",{"aria-hidden":"true","data-everfur-reading-dots":"",style:styles.dots,children:DOT_INDICES.map(index=>animate?/* @__PURE__ */jsx(AnimatedDot,{index:index,style:styles.dot},index):/* @__PURE__ */jsx("span",{style:{...styles.dot,...styles.dotStatic}},index))})]})}function AnimatedDot({index:index,style:style}){let ref=useRef(null);return useEffect(()=>{let node=ref.current;if(node===null||typeof node.animate!="function")return;let animation=node.animate([{opacity:OPACITY_REST,transform:"translateY(0)"},{opacity:1,transform:`translateY(-${DOT_RISE}px)`,offset:.4},{opacity:OPACITY_REST,transform:"translateY(0)"}],{duration:LOOP_MS,iterations:1/0,delay:index*STAGGER_MS,easing:"ease-in-out"});return()=>animation.cancel()},[index]),/* @__PURE__ */jsx("span",{ref:ref,style:{...style,opacity:OPACITY_REST}})}function makeStyles14(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type;return{card:{boxSizing:"border-box",alignSelf:"flex-start",display:"flex",flexDirection:"row",alignItems:"center",flexWrap:"wrap",gap:s.sm,maxWidth:"100%",padding:`${s.md}px ${s.md+s.xs/2}px`,backgroundColor:c.surfaceSubtle,borderRadius:r.md},line:{margin:0,...faceCss(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*t.lineHeight.snug)}px`},dots:{display:"inline-flex",flexDirection:"row",alignItems:"center",gap:s.xs},dot:{display:"inline-block",width:DOT_SIZE,height:DOT_SIZE,borderRadius:r.pill,backgroundColor:c.brandInk},dotStatic:{opacity:OPACITY_STATIC}}}function resolveTurnScrollTarget(assistantTop,userTop,inset){let replyTarget=assistantTop-inset,target=userTop!=null?Math.min(replyTarget,userTop):replyTarget;return Math.max(0,target)}function latestTurn(messages){let assistantIndex=messages.length-1,last=messages[assistantIndex];if(last===void 0||last.role!=="assistant")return null;let above=messages[assistantIndex-1];return{assistantIndex:assistantIndex,userIndex:above!==void 0&&above.role==="user"?assistantIndex-1:null}}function nextFollowOffset(anchor,current,maxOffset){let end=Math.max(0,maxOffset),target=anchor===null?end:Math.min(Math.max(0,anchor),end);return target>current+1?target:null}function contentTop(
|
|
350
|
+
/* @__PURE__ */jsx("span",{"aria-hidden":"true","data-everfur-reading-dots":"",style:styles.dots,children:DOT_INDICES.map(index=>animate?/* @__PURE__ */jsx(AnimatedDot,{index:index,style:styles.dot},index):/* @__PURE__ */jsx("span",{style:{...styles.dot,...styles.dotStatic}},index))})]})}function AnimatedDot({index:index,style:style}){let ref=useRef(null);return useEffect(()=>{let node=ref.current;if(node===null||typeof node.animate!="function")return;let animation=node.animate([{opacity:OPACITY_REST,transform:"translateY(0)"},{opacity:1,transform:`translateY(-${DOT_RISE}px)`,offset:.4},{opacity:OPACITY_REST,transform:"translateY(0)"}],{duration:LOOP_MS,iterations:1/0,delay:index*STAGGER_MS,easing:"ease-in-out"});return()=>animation.cancel()},[index]),/* @__PURE__ */jsx("span",{ref:ref,style:{...style,opacity:OPACITY_REST}})}function makeStyles14(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type;return{card:{boxSizing:"border-box",alignSelf:"flex-start",display:"flex",flexDirection:"row",alignItems:"center",flexWrap:"wrap",gap:s.sm,maxWidth:"100%",padding:`${s.md}px ${s.md+s.xs/2}px`,backgroundColor:c.surfaceSubtle,borderRadius:r.md},line:{margin:0,...faceCss(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*t.lineHeight.snug)}px`},dots:{display:"inline-flex",flexDirection:"row",alignItems:"center",gap:s.xs},dot:{display:"inline-block",width:DOT_SIZE,height:DOT_SIZE,borderRadius:r.pill,backgroundColor:c.brandInk},dotStatic:{opacity:OPACITY_STATIC}}}function resolveTurnScrollTarget(assistantTop,userTop,inset){let replyTarget=assistantTop-inset,target=userTop!=null?Math.min(replyTarget,userTop):replyTarget;return Math.max(0,target)}function latestTurn(messages){let assistantIndex=messages.length-1,last=messages[assistantIndex];if(last===void 0||last.role!=="assistant")return null;let above=messages[assistantIndex-1];return{assistantIndex:assistantIndex,userIndex:above!==void 0&&above.role==="user"?assistantIndex-1:null}}function nextFollowOffset(anchor,current,maxOffset){let end=Math.max(0,maxOffset),target=anchor===null?end:Math.min(Math.max(0,anchor),end);return target>current+1?target:null}var ASIDE_REVEAL_MARGIN=16;function contentTop(scroller2,row){return scroller2.scrollTop+row.getBoundingClientRect().top-scroller2.getBoundingClientRect().top}function turnAnchor(scroller2,list,messages){let turn=latestTurn(messages);if(turn===null||list===null||list.children.length!==messages.length)return null;let assistant=list.children[turn.assistantIndex];if(assistant===void 0)return null;let user=turn.userIndex===null?void 0:list.children[turn.userIndex];return resolveTurnScrollTarget(contentTop(scroller2,assistant),user===void 0?null:contentTop(scroller2,user),96)}function useTranscriptFollow(messages,isStreaming,growth){let scrollerRef=useRef(null),listRef=useRef(null),asideRef=useRef(null),following=useRef(true),wasStreaming=useRef(isStreaming),ownTop=useRef(null),onScroll=useCallback(()=>{let node=scrollerRef.current;node!==null&&(ownTop.current!==null&&Math.abs(node.scrollTop-ownTop.current)<1||(ownTop.current=null,following.current=node.scrollHeight-node.scrollTop-node.clientHeight<=24))},[]),{awaiting:awaiting,prompts:prompts,notice:notice,reconnecting:reconnecting}=growth;useLayoutEffect(()=>{isStreaming&&!wasStreaming.current&&(following.current=true),wasStreaming.current=isStreaming;let node=scrollerRef.current;if(node===null||!following.current)return;let next=nextFollowOffset(turnAnchor(node,listRef.current,messages),node.scrollTop,node.scrollHeight-node.clientHeight);next!==null&&(node.scrollTop=next,ownTop.current=node.scrollTop)},[messages,isStreaming,awaiting,prompts,notice,reconnecting]);let aside=growth.aside??null;return useLayoutEffect(()=>{let node=scrollerRef.current,row=asideRef.current;if(aside===null||node===null||row===null||!following.current)return;let bottom=contentTop(node,row)+row.getBoundingClientRect().height,next=nextFollowOffset(bottom+ASIDE_REVEAL_MARGIN-node.clientHeight,node.scrollTop,node.scrollHeight-node.clientHeight);next!==null&&(node.scrollTop=next,ownTop.current=node.scrollTop)},[aside]),{scrollerRef:scrollerRef,listRef:listRef,onScroll:onScroll,asideRef:asideRef}}function TurnNoticeCard({notice:notice,onRetry:onRetry,onStartNew:onStartNew}){let{styles:styles}=useChatTheme(),error=notice.tone==="error";/* @__PURE__ */
|
|
352
351
|
return jsxs("div",{role:"alert",style:{...styles.turnNotice,...error?styles.turnNoticeError:null},children:[
|
|
353
352
|
/* @__PURE__ */jsx("p",{style:{...styles.turnNoticeTitle,...error?styles.turnNoticeTitleError:null},children:notice.title}),
|
|
354
353
|
/* @__PURE__ */jsx("p",{style:styles.turnNoticeBody,children:notice.body}),
|
|
@@ -364,20 +363,26 @@ return jsx("li",{"data-everfur-opening-card":"",style:{listStyle:"none"},childre
|
|
|
364
363
|
/* @__PURE__ */jsx("small",{children:card.kicker}),
|
|
365
364
|
/* @__PURE__ */jsx("strong",{children:card.title}),card.body!==void 0?/* @__PURE__ */jsx("span",{className:cls?.body,children:card.body}):null]})]})})}function FollowUpRow({prompt:prompt,index:index,onSelectPrompt:onSelectPrompt}){let{styles:styles}=useChatTheme(),motion=useChatMotion(),ref=useRef(null);return useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:motion.followUpInMs,delayMs:index*motion.followUpStaggerMs,fromOpacity:0});return()=>animation?.cancel()},[motion,index]),/* @__PURE__ */jsx("li",{ref:ref,style:{display:"flex",maxWidth:"100%"},children:/* @__PURE__ */jsx("button",{type:"button",onClick:()=>onSelectPrompt(prompt),style:styles.followUpRow,children:prompt})})}function ErrorState({error:error,onRetry:onRetry,onAddPet:onAddPet}){let{styles:styles}=useChatTheme(),addPet=onAddPet!==null&&isPetNotRegistered(error)?onAddPet:null;/* @__PURE__ */
|
|
366
365
|
return jsxs("div",{role:"alert",style:styles.centered,children:[
|
|
367
|
-
/* @__PURE__ */jsx("p",{style:styles.errorText,children:error.displayMessage}),addPet!==null?/* @__PURE__ */jsx("button",{type:"button",onClick:addPet,style:styles.retryButton,children:CHAT_COPY.addPet}):null,error.retryable?/* @__PURE__ */jsx("button",{type:"button",onClick:onRetry,style:styles.retryButton,children:CHAT_COPY.retry}):null]})}function PopulatedState({options:options,chat:chat,onSelectPrompt:onSelectPrompt,onAnswerCheckin:onAnswerCheckin,imagesFor:imagesFor,onPreview:onPreview,onCheckinFindVet:onCheckinFindVet,petName:petName}){let{styles:styles}=useChatTheme(),{messages:messages,isStreaming:isStreaming}=chat,settledIds=useSettledIds(messages,chat.conversationId),prompts=followUpsWithPolicy(chat,options.followUpPolicy),cards=options.answerStyle==="cards",actions=cards?followUpActionsFor(chat,options.answerCards):[],opening=options.openingCard,first=messages[0],openingId=opening!==void 0&&first!==void 0&&first.role==="user"&&first.text.trim()===opening.prompt?first.id:null,awaiting=awaitingAssistant(messages,isStreaming),notice=turnNotice(chat,"web"),liveCheckins=useMemo(()=>liveCheckinIds(placeCheckins(messages)),[messages]),{scrollerRef:scrollerRef,listRef:listRef,onScroll:onScroll}=useTranscriptFollow(messages,isStreaming,{awaiting:awaiting,prompts:prompts.length+actions.length,notice:notice!==null,reconnecting:chat.reconnecting===true}),last=messages[messages.length-1],streamingId=isStreaming&&last!==void 0&&last.role==="assistant"?last.id:null;
|
|
366
|
+
/* @__PURE__ */jsx("p",{style:styles.errorText,children:error.displayMessage}),addPet!==null?/* @__PURE__ */jsx("button",{type:"button",onClick:addPet,style:styles.retryButton,children:CHAT_COPY.addPet}):null,error.retryable?/* @__PURE__ */jsx("button",{type:"button",onClick:onRetry,style:styles.retryButton,children:CHAT_COPY.retry}):null]})}function PopulatedState({options:options,chat:chat,onSelectPrompt:onSelectPrompt,onAnswerCheckin:onAnswerCheckin,imagesFor:imagesFor,onPreview:onPreview,onCheckinFindVet:onCheckinFindVet,petName:petName}){let{styles:styles}=useChatTheme(),{messages:messages,isStreaming:isStreaming}=chat,settledIds=useSettledIds(messages,chat.conversationId),prompts=followUpsWithPolicy(chat,options.followUpPolicy),cards=options.answerStyle==="cards",actions=cards?followUpActionsFor(chat,options.answerCards):[],opening=options.openingCard,first=messages[0],openingId=opening!==void 0&&first!==void 0&&first.role==="user"&&first.text.trim()===opening.prompt?first.id:null,awaiting=awaitingAssistant(messages,isStreaming),notice=turnNotice(chat,"web"),liveCheckins=useMemo(()=>liveCheckinIds(placeCheckins(messages)),[messages]),aside=options.threadAside??null,{scrollerRef:scrollerRef,listRef:listRef,onScroll:onScroll,asideRef:asideRef}=useTranscriptFollow(messages,isStreaming,{awaiting:awaiting,prompts:prompts.length+actions.length,notice:notice!==null,reconnecting:chat.reconnecting===true,aside:aside===null?null:options.threadAsideKey??"shown"}),last=messages[messages.length-1],streamingId=isStreaming&&last!==void 0&&last.role==="assistant"?last.id:null;
|
|
368
367
|
/* @__PURE__ */
|
|
369
368
|
return jsxs("div",{ref:scrollerRef,onScroll:onScroll,role:"region","aria-label":CHAT_COPY.transcript,tabIndex:0,style:styles.list,children:[options.threadTop??null,chat.historyCursor?/* @__PURE__ */jsx("button",{type:"button",disabled:chat.isLoadingHistory,onClick:()=>{chat.loadOlderMessages()},style:styles.earlierButton,children:chat.isLoadingHistory?HISTORY_COPY.loadingEarlier:HISTORY_COPY.earlier}):null,
|
|
370
|
-
/* @__PURE__ */jsx("ol",{ref:listRef,style:styles.messageList,children:messages.map(message=>message.id===openingId&&opening!==void 0?/* @__PURE__ */jsx(OpeningCard,{card:opening.card},message.id):message.checkin&&liveCheckins.has(message.id)?/* @__PURE__ */jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,onFindVet:onCheckinFindVet},message.id):/* @__PURE__ */jsx(MessageRow,{message:message,streaming:message.id===streamingId,chat:chat,images:imagesFor(message),onPreview:onPreview,enters:!settledIds.has(message.id),answerCards:cards?options.answerCards??NO_ANSWER_CARDS:null},message.id))}),chat.reconnecting===true?/* @__PURE__ */jsx("p",{style:styles.reconnectingCaption,children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsx(TypingIndicator,{petName:petName}):null,notice!==null?/* @__PURE__ */jsx(TurnNoticeCard,{notice:notice,onRetry:chat.retryLast,onStartNew:chat.newConversation}):null,cards?/* @__PURE__ */jsx(CardsFollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:options.followUpPolicy?.label,actions:actions,options:options.answerCards}):/* @__PURE__ */jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:options.followUpPolicy?.label}),options.answerFooter??null]})}var NO_IDS=/* @__PURE__ */new Set,NO_ANSWER_CARDS=/* @__PURE__ */Object.freeze({});function useSettledIds(messages,conversationId2){let ref=useRef(null);if(ref.current===null||ref.current.scope!==conversationId2){let carried=ref.current!==null&&ref.current.scope===null?ref.current.ids:null,opened=conversationId2===null?NO_IDS:new Set(messages.map(message=>message.id));ref.current={scope:conversationId2,ids:carried??opened}}return ref.current.ids}function AssistantSender({showName:showName}){let{theme:theme,styles:styles}=useChatTheme(),avatarUrl=theme.meta.assistantAvatarUrl,[avatarFailed,setAvatarFailed]=useState(null),avatar=avatarUrl!==null&&avatarFailed!==avatarUrl?avatarUrl:null;return!showName&&avatar===null?null:/* @__PURE__ */jsxs("p",{style:styles.senderRow,children:[avatar!==null?/* @__PURE__ */jsx(BrandImage,{src:avatar,alt:"",decorative:true,style:styles.assistantAvatar,onFailed:()=>setAvatarFailed(avatar)}):null,showName?/* @__PURE__ */jsx("span",{style:styles.assistantName,children:CHAT_COPY.assistantName}):null]})}function MessageRow({message:message,streaming:streaming,chat:chat,images:images,onPreview:onPreview,enters:enters,answerCards:answerCards}){let{theme:theme,styles:styles}=useChatTheme(),motion=useChatMotion(),bubbleRef=useRef(null),isUser=message.role==="user",isVet=message.role==="vet";useEffect(()=>{if(!enters)return;let animation=popIn(bubbleRef.current,motion);return()=>animation?.cancel()},[]);let text3=useRevealedText(message.text,streaming&&message.role==="assistant",motion),showAssistantName=message.role==="assistant"&&!theme.meta.hidePoweredBy,hiddenSender=isUser?CHAT_COPY.senderUser:message.role==="assistant"&&!showAssistantName?CHAT_COPY.senderAssistant:null,showFooter=message.pending!==true&&!streaming,footer=()=>/* @__PURE__ */jsx(MessageFooter,{role:message.role,text:message.text,createdAt:message.createdAt,...message.responseId!==void 0?{responseId:message.responseId}:{},sentiment:chat.sentimentByMessage[message.id]??null,feedback:chat.feedback});if(answerCards!==null&&(message.role==="assistant"||isUser)){let questionClass=answerCards.classNames?.question;/* @__PURE__ */
|
|
369
|
+
/* @__PURE__ */jsx("ol",{ref:listRef,style:styles.messageList,children:messages.map(message=>message.id===openingId&&opening!==void 0?/* @__PURE__ */jsx(OpeningCard,{card:opening.card},message.id):message.checkin&&liveCheckins.has(message.id)?/* @__PURE__ */jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,onFindVet:onCheckinFindVet},message.id):/* @__PURE__ */jsx(MessageRow,{message:message,streaming:message.id===streamingId,chat:chat,images:imagesFor(message),onPreview:onPreview,enters:!settledIds.has(message.id),answerCards:cards?options.answerCards??NO_ANSWER_CARDS:null},message.id))}),chat.reconnecting===true?/* @__PURE__ */jsx("p",{style:styles.reconnectingCaption,children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsx(TypingIndicator,{petName:petName}):null,notice!==null?/* @__PURE__ */jsx(TurnNoticeCard,{notice:notice,onRetry:chat.retryLast,onStartNew:chat.newConversation}):null,cards?/* @__PURE__ */jsx(CardsFollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:options.followUpPolicy?.label,actions:actions,options:options.answerCards}):/* @__PURE__ */jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt,label:options.followUpPolicy?.label}),aside!==null?/* @__PURE__ */jsx("div",{ref:asideRef,style:{display:"flex",flexDirection:"column"},children:aside}):null,options.answerFooter??null]})}var NO_IDS=/* @__PURE__ */new Set,NO_ANSWER_CARDS=/* @__PURE__ */Object.freeze({});function useSettledIds(messages,conversationId2){let ref=useRef(null);if(ref.current===null||ref.current.scope!==conversationId2){let carried=ref.current!==null&&ref.current.scope===null?ref.current.ids:null,opened=conversationId2===null?NO_IDS:new Set(messages.map(message=>message.id));ref.current={scope:conversationId2,ids:carried??opened}}return ref.current.ids}function AssistantSender({showName:showName}){let{theme:theme,styles:styles}=useChatTheme(),avatarUrl=theme.meta.assistantAvatarUrl,[avatarFailed,setAvatarFailed]=useState(null),avatar=avatarUrl!==null&&avatarFailed!==avatarUrl?avatarUrl:null;return!showName&&avatar===null?null:/* @__PURE__ */jsxs("p",{style:styles.senderRow,children:[avatar!==null?/* @__PURE__ */jsx(BrandImage,{src:avatar,alt:"",decorative:true,style:styles.assistantAvatar,onFailed:()=>setAvatarFailed(avatar)}):null,showName?/* @__PURE__ */jsx("span",{style:styles.assistantName,children:CHAT_COPY.assistantName}):null]})}function MessageRow({message:message,streaming:streaming,chat:chat,images:images,onPreview:onPreview,enters:enters,answerCards:answerCards}){let{theme:theme,styles:styles}=useChatTheme(),motion=useChatMotion(),bubbleRef=useRef(null),isUser=message.role==="user",isVet=message.role==="vet";useEffect(()=>{if(!enters)return;let animation=popIn(bubbleRef.current,motion);return()=>animation?.cancel()},[]);let text3=useRevealedText(message.text,streaming&&message.role==="assistant",motion),showAssistantName=message.role==="assistant"&&!theme.meta.hidePoweredBy,hiddenSender=isUser?CHAT_COPY.senderUser:message.role==="assistant"&&!showAssistantName?CHAT_COPY.senderAssistant:null,showFooter=message.pending!==true&&!streaming,footer=()=>/* @__PURE__ */jsx(MessageFooter,{role:message.role,text:message.text,createdAt:message.createdAt,...message.responseId!==void 0?{responseId:message.responseId}:{},sentiment:chat.sentimentByMessage[message.id]??null,feedback:chat.feedback});if(answerCards!==null&&(message.role==="assistant"||isUser)){let questionClass=answerCards.classNames?.question;/* @__PURE__ */
|
|
371
370
|
return jsx("li",{style:isUser?{...styles.row,...styles.rowUser}:{listStyle:"none",display:"flex",width:"100%"},"aria-busy":message.pending===true?true:void 0,children:isUser?/* @__PURE__ */jsxs("div",{ref:bubbleRef,className:questionClass,style:questionClass?void 0:{...styles.bubble,...styles.bubbleUser,...message.pending?styles.bubblePending:null},children:[
|
|
372
371
|
/* @__PURE__ */jsx("span",{style:VISUALLY_HIDDEN,children:`${CHAT_COPY.senderUser}: `}),images.length>0?/* @__PURE__ */jsx(MessageAttachments,{images:images,onPreview:onPreview}):null,questionClass?/* @__PURE__ */jsx("span",{style:{whiteSpace:"pre-wrap"},children:text3}):/* @__PURE__ */jsx("p",{style:styles.bubbleTextUser,children:text3})]}):/* @__PURE__ */jsx("div",{ref:bubbleRef,style:{width:"100%"},children:/* @__PURE__ */jsx(CardsAnswer,{message:message,text:text3,streaming:streaming,chat:chat,options:answerCards,hiddenSender:CHAT_COPY.senderAssistant,showFooter:showFooter,renderFooter:footer})})})}/* @__PURE__ */
|
|
373
372
|
return jsxs("li",{style:{...styles.row,...isUser?styles.rowUser:styles.rowAssistant},"aria-busy":message.pending===true?true:void 0,children:[message.role==="assistant"?/* @__PURE__ */jsx(AssistantSender,{showName:showAssistantName}):null,isVet?/* @__PURE__ */jsx("p",{style:styles.senderRow,children:/* @__PURE__ */jsx("span",{style:styles.vetSender,children:vetSenderLabel(message)})}):null,
|
|
374
373
|
/* @__PURE__ */jsxs("div",{ref:bubbleRef,style:{...styles.bubble,...isUser?styles.bubbleUser:isVet?styles.bubbleVet:styles.bubbleAssistant,...message.pending?styles.bubblePending:null},children:[hiddenSender!==null?/* @__PURE__ */jsx("span",{style:VISUALLY_HIDDEN,children:`${hiddenSender}: `}):null,images.length>0?/* @__PURE__ */jsx(MessageAttachments,{images:images,onPreview:onPreview}):null,
|
|
375
|
-
/* @__PURE__ */jsx("p",{style:isUser?styles.bubbleTextUser:isVet?styles.bubbleTextVet:styles.bubbleTextAssistant,children:message.role==="assistant"?renderInlineMarkdown(text3,{bold:styles.bubbleBold,italic:styles.bubbleItalic,code:styles.bubbleCode}):text3})]}),message.role==="assistant"&&!streaming?/* @__PURE__ */jsx(CitationCards,{citations:message.citations}):null,showFooter?footer():null]})}
|
|
374
|
+
/* @__PURE__ */jsx("p",{style:isUser?styles.bubbleTextUser:isVet?styles.bubbleTextVet:styles.bubbleTextAssistant,children:message.role==="assistant"?renderInlineMarkdown(text3,{bold:styles.bubbleBold,italic:styles.bubbleItalic,code:styles.bubbleCode}):text3})]}),message.role==="assistant"&&!streaming?/* @__PURE__ */jsx(CitationCards,{citations:message.citations}):null,showFooter?footer():null]})}var URGENT_LEVELS=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(chat){if(chat.isBootstrapping===true||chat.isLoadingHistory===true||chat.isStreaming===true||chat.status==="error"||chat.stopped===true)return false;let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true||last.checkin!==void 0||last.text.trim().length===0?false:!(typeof last.urgencyLevel=="string"&&URGENT_LEVELS.has(last.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function useTextingGranted(){let{runtime:runtime}=useEverfurContext(),source=runtime.entitlements??null,subscribe2=useCallback(listener=>source===null?()=>{}:source.subscribe(listener),[source]),read=source===null?NO_SNAPSHOT2:source.getSnapshot,snapshot2=useSyncExternalStore(subscribe2,read,read);return useMemo(()=>snapshot2!==null&&decideCapability("texting",snapshot2.decisions,{isPending:snapshot2.isPending}).enabled,[snapshot2])}var pending=null,loaded=null;function loadTextingModule(){if(pending!==null)return pending;let started=import("@everfur/sdk/web/texting");return pending=started,started.then(module=>{loaded=module},()=>{pending===started&&(pending=null)}),started}var NOTHING=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null});function useChatTextingAsk(enabled,chat){let{userRef:userRef2}=useEverfurContext(),granted=useTextingGranted(),wanted=enabled&&userRef2!==null&&granted,[module,setModule]=useState(loaded),[ask,setAsk]=useState(null);if(useEffect(()=>{if(!wanted||module!==null)return;let live=true;return loadTextingModule().then(next=>{live&&setModule(next)},()=>{}),()=>{live=false}},[wanted,module]),!wanted||module===null)return NOTHING;let runner=/* @__PURE__ */jsx(module.ChatTextingAskController,{enabled:true,ready:textingAskThreadReady(chat),onAsk:setAsk});if(ask===null||ask.stage==="hidden"||ask.stage==="dismissed")return{runner:runner,line:null,entry:null,stage:null};let lines=module.textingAskLines(ask),line=/* @__PURE__ */jsx(AskLine,{stage:ask.stage,text:ask.stage==="verified"?lines.verified:lines.line,accept:lines.accept,dismiss:lines.dismiss,onAccept:ask.accept,onDismiss:ask.dismiss}),entry=ask.stage==="enrolling"?/* @__PURE__ */jsx(module.ChatTextingAskComposer,{ask:ask}):null;return{runner:runner,line:line,entry:entry,stage:ask.stage}}function AskLine({stage:stage,text:text3,accept:accept,dismiss:dismiss,onAccept:onAccept,onDismiss:onDismiss}){let{theme:theme,styles:styles}=useChatTheme(),showName=!theme.meta.hidePoweredBy;/* @__PURE__ */
|
|
375
|
+
return jsxs("div",{"data-everfur-texting-ask":stage,style:{...styles.row,...styles.rowAssistant,marginTop:theme.space.lg},children:[
|
|
376
|
+
/* @__PURE__ */jsx(AssistantSender,{showName:showName}),
|
|
377
|
+
/* @__PURE__ */jsxs("div",{style:{...styles.bubble,...styles.bubbleAssistant},children:[showName?null:/* @__PURE__ */jsx("span",{style:VISUALLY_HIDDEN,children:`${CHAT_COPY.senderAssistant}: `}),
|
|
378
|
+
/* @__PURE__ */jsx("p",{style:styles.bubbleTextAssistant,children:text3})]}),stage==="offered"?/* @__PURE__ */jsxs("ul",{style:styles.followUps,children:[
|
|
379
|
+
/* @__PURE__ */jsx("li",{style:{display:"flex",maxWidth:"100%"},children:/* @__PURE__ */jsx("button",{type:"button",onClick:onAccept,style:styles.followUpRow,children:accept})}),
|
|
380
|
+
/* @__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 MIN_TOUCH_TARGET14=44,MIC_GLYPH_SIZE=18,STOP_GLYPH_SIZE2=14,PULSE_INSET=6,PULSE_LOOP_MS=1200,DISABLED_OPACITY2=.4;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 DictationButton({active:active,listening:listening,elapsedMs:elapsedMs,disabled:disabled=false,onToggle:onToggle}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles15(theme),[theme]);/* @__PURE__ */
|
|
376
381
|
return jsxs("span",{style:styles.wrap,children:[listening?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.timer,children:formatDictationElapsed(elapsedMs)}):null,
|
|
377
382
|
/* @__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:[
|
|
378
383
|
/* @__PURE__ */jsx(Pulse,{style:styles.pulse}),
|
|
379
384
|
/* @__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})}),
|
|
380
|
-
/* @__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={width:"calc(100% - 28px)"},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__ */
|
|
385
|
+
/* @__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__ */
|
|
381
386
|
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,
|
|
382
387
|
/* @__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:[
|
|
383
388
|
/* @__PURE__ */jsx("input",{ref:fileInput,type:"file",accept:ATTACHMENT_ACCEPT,multiple:attachments.maxPerMessage>1,onChange:onPick,tabIndex:-1,"aria-hidden":"true",style:VISUALLY_HIDDEN}),
|
|
@@ -385,13 +390,24 @@ return jsxs("div",{style:compact?{...styles.composerBlock,...COMPACT_BLOCK}:styl
|
|
|
385
390
|
/* @__PURE__ */jsxs("div",{style:styles.inputWrap,children:[draft.length===0?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.placeholder,children:placeholder}):null,
|
|
386
391
|
/* @__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__ */
|
|
387
392
|
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"?healthPlanTopCard(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,
|
|
388
|
-
/* @__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]),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}:{}}),[starterPrompts,renderEmptyHeader,emptyState,followUpPolicy,initialAskCard,askPrompt,presentation.chatAnswerStyle,answerCards,footnoteInThread,headerPet?.name,disclaimerClass,showTopCard,topCard,topCardState,onTopCardAsk,barInThread,historyBarNode]),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}),pet!==void 0?/* @__PURE__ */jsx(PetSetupNotice,{petRef:petRef2??null,pet:pet,onRegistered:pets.refresh}):null,
|
|
393
|
+
/* @__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),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}),pet!==void 0?/* @__PURE__ */jsx(PetSetupNotice,{petRef:petRef2??null,pet:pet,onRegistered:pets.refresh}):null,
|
|
389
394
|
/* @__PURE__ */jsxs("div",{style:styles.split,children:[
|
|
390
395
|
/* @__PURE__ */jsxs("div",{style:styles.main,children:[barInThread?null:historyBarNode,!presentation.chatGeneralBanner&&urgency.tier?.level==="general"?null:/* @__PURE__ */jsx(UrgencyBanner,{surface:urgency,vetEntry:vetEntry,renderVetAction:renderVetAction,onFindVet:onFindVet}),
|
|
391
|
-
/* @__PURE__ */jsx("div",{style:styles.body,children:renderView(view,chat,onSelectPrompt,renderPending,headerPet,vetPrep,sentImages.imagesFor,onPreview,addPet,checkinFindVet,emptyOptions)}),
|
|
392
|
-
/* @__PURE__ */jsx(Composer,{send:onSend,draftScope:chat.send,stop:chat.stop,isStreaming:chat.isStreaming,inputRef:inputRef,conversationId:chat.conversationId,seed:seed,draftStore:draftStore,attachments:attachmentsEnabled&&attachments.available?attachments:null,onPreview:onPreview,dictation:dictationEnabled,pet:headerPet,telemetry:telemetry,mood:composerMood(view,urgency.source?.level??null),compact:presentation.chatComposerStyle==="compact",petPlaceholder:presentation.chatComposerPlaceholder==="pet_name",dimEmptySend:presentation.chatSendButton==="dim_when_empty",children:footnoteInThread?null:footnote}),theme.meta.hidePoweredBy||hostPoweredBy?null:/* @__PURE__ */jsx("p",{style:styles.poweredBy,children:CHAT_COPY.poweredBy})]}),sheet?null:/* @__PURE__ */jsx(HistoryDrawer,{chat:chat,history:history,mode:layout.rail?"rail":"dialog",returnFocusTo:historyTrigger})]}),
|
|
396
|
+
/* @__PURE__ */jsx("div",{style:styles.body,children:renderView(view,chat,onSelectPrompt,renderPending,headerPet,vetPrep,sentImages.imagesFor,onPreview,addPet,checkinFindVet,emptyOptions)}),textingAsk.runner,textingAsk.entry!==null?/* @__PURE__ */jsxs("div",{style:styles.composerBlock,children:[textingAsk.entry,footnoteInThread?null:footnote]}):/* @__PURE__ */jsx(Composer,{send:onSend,draftScope:chat.send,stop:chat.stop,isStreaming:chat.isStreaming,inputRef:inputRef,conversationId:chat.conversationId,seed:seed,draftStore:draftStore,attachments:attachmentsEnabled&&attachments.available?attachments:null,onPreview:onPreview,dictation:dictationEnabled,pet:headerPet,telemetry:telemetry,mood:composerMood(view,urgency.source?.level??null),compact:presentation.chatComposerStyle==="compact",petPlaceholder:presentation.chatComposerPlaceholder==="pet_name",dimEmptySend:presentation.chatSendButton==="dim_when_empty",children:footnoteInThread?null:footnote}),theme.meta.hidePoweredBy||hostPoweredBy?null:/* @__PURE__ */jsx("p",{style:styles.poweredBy,children:CHAT_COPY.poweredBy})]}),sheet?null:/* @__PURE__ */jsx(HistoryDrawer,{chat:chat,history:history,mode:layout.rail?"rail":"dialog",returnFocusTo:historyTrigger})]}),
|
|
393
397
|
/* @__PURE__ */jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:VISUALLY_HIDDEN,children:announcement}),sheet?/* @__PURE__ */jsx(HistorySheet,{chat:chat,history:history,sheet:props.historySheet,returnFocusTo:historyTrigger}):null,
|
|
394
398
|
/* @__PURE__ */jsx(AttachmentImageLightbox,{image:lightbox,onClose:closeLightbox,returnFocusTo:lightboxTrigger}),
|
|
395
399
|
/* @__PURE__ */jsx("div",{"data-ef-focus-ring":"self",style:TELEVET_HOST_SCOPE,children:/* @__PURE__ */jsx(EverfurTelevetHost,{})})]})}function useSentImages(messages){let store=useRef({pending:[],byMessage:/* @__PURE__ */new Map}),latest=useRef(messages);latest.current=messages;let record=useCallback((text3,images)=>{images.length!==0&&store.current.pending.push({text:text3,images:images,before:new Set(latest.current.map(message=>message.id))})},[]),imagesFor=useCallback(message=>{let current=store.current,known=current.byMessage.get(message.id);if(known!==void 0)return known;if(message.role!=="user")return NO_IMAGES2;let at=current.pending.findIndex(entry2=>entry2.text===message.text&&!entry2.before.has(message.id));if(at<0)return NO_IMAGES2;let[entry]=current.pending.splice(at,1);return entry===void 0?NO_IMAGES2:(current.byMessage.set(message.id,entry.images),entry.images)},[]);return useMemo(()=>({record:record,imagesFor:imagesFor}),[record,imagesFor])}function useReplyAnnouncement(chat,petName){let awaiting=awaitingAssistant(chat.messages,chat.isStreaming),[settled,setSettled]=useState({send:chat.send,id:chat.conversationId,text:""}),wasStreaming=useRef(false),previousScope=useRef({send:chat.send,id:chat.conversationId});return useEffect(()=>{let previous=previousScope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),previousScope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];setSettled({send:chat.send,id:chat.conversationId,text:last!==void 0&&last.role==="assistant"?CHAT_COPY.answered:""})}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId]),awaiting?forPet(CHAT_COPY.reading,petName):settled.send===chat.send&&settled.id===chat.conversationId?settled.text:""}function composerMood(view,level){return level==="emergency"?"urgent":view==="populated"?"followUp":"ask"}function PetSetupNotice({petRef:petRef2,pet:pet,onRegistered:onRegistered}){let{styles:styles}=useChatTheme(),setup=useChatPetRegistration(petRef2,pet,onRegistered);return setup.status!=="failed"||setup.error===null?null:/* @__PURE__ */jsxs("div",{role:"alert",style:styles.setupNotice,children:[
|
|
396
400
|
/* @__PURE__ */jsx("span",{style:styles.setupNoticeText,children:setup.error.displayMessage}),
|
|
397
|
-
/* @__PURE__ */jsx("button",{type:"button",onClick:setup.retry,style:styles.setupNoticeAction,children:CHAT_COPY.retry})]})}function useEverfurPetProfile(petRef2){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),key=useMemo(()=>({repository:repository,petRef:petRef2}),[repository,petRef2]),[state,setState]=useState({key:key,profile:null,loading:petRef2!==null,error:null}),current=state.key===key?state:{profile:null,loading:petRef2!==null,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;if(key.petRef===null){setState({key:key,profile:null,loading:false,error:null});return}setState(previous=>({key:key,profile:previous.key===key?previous.profile:null,loading:true,error:null}));let result=await key.repository.getPetProfile(key.petRef);request===generation.current&&setState(result.ok?{key:key,profile:result.value,loading:false,error:null}:{key:key,profile:null,loading:false,error:result.error})},[key]);return useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useMemo(()=>({profile:current.profile,loading:current.loading,error:current.error,refresh:load}),[current.profile,current.loading,current.error,load])}function EverfurThemeProvider(props){return createElement(EverfurThemeProviderCore,{clientTheme:props.clientTheme??null,seams:webThemeSeams,children:props.children})}export{APPEARANCE_PRESETS,APPEARANCE_PRESET_NAMES,APPEARANCE_SIZE_RANGES,CapabilityGate,DEFAULT_PRESENTATION,EverfurChat,EverfurConfigError,EverfurPoweredBy,EverfurProvider,EverfurThemeProvider,EverfurThrownError,THEME_SLOT_KEYS,THEME_SLOT_KEYS_BY_SLOT,THEME_SLOT_NAMES,canonicalPetSpecies,categoryFor,conversationId,createBrowserLifecycle,createLocalStorageKv,createWebAttachmentTransport,expandAppearance,face,faceCss,fileToAttachmentHandle,headingFace,headingFaceCss,isErr,isOk,isRetryableCode,parsePresentation,petRef,previewTheme,resolvePresentation,themeAdjustments,themeSlotKeysFor,unwrap,useCapability,useChatAttachments,useEverfur,useEverfurChat,useEverfurPetProfile,useEverfurPets,useEverfurPresentation,useEverfurTheme,useHostPoweredBy,userFacingError,userRef};
|
|
401
|
+
/* @__PURE__ */jsx("button",{type:"button",onClick:setup.retry,style:styles.setupNoticeAction,children:CHAT_COPY.retry})]})}var SIGNALS_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanSignals@v1"),signalHost=globalThis;function isSignalState(value){if(typeof value!="object"||value===null)return false;let v=value;return v.landed instanceof Set&&v.noVet instanceof Set&&v.noVetByPet instanceof Map}var stored=signalHost[SIGNALS_SYMBOL],fresh2=()=>({landed:/* @__PURE__ */new Set,noVet:/* @__PURE__ */new Set,noVetByPet:/* @__PURE__ */new Map}),state=isSignalState(stored)?stored:signalHost[SIGNALS_SYMBOL]=fresh2(),landedListeners=state.landed,noVetListeners=state.noVet,noVetByPet=state.noVetByPet;function notifyHealthPlanRecordsLanded(petRef2,source="host"){for(let listener of[...landedListeners])try{listener(petRef2,source)}catch{}}function onHealthPlanRecordsLanded(listener){return landedListeners.add(listener),()=>{landedListeners.delete(listener)}}function setHealthPlanNoVet(petRef2,noVet){if((noVetByPet.get(petRef2)??false)!==noVet){noVet?noVetByPet.set(petRef2,true):noVetByPet.delete(petRef2);for(let listener of[...noVetListeners])try{listener(petRef2,noVet)}catch{}}}function healthPlanNoVet(petRef2){return noVetByPet.get(petRef2)??false}function onHealthPlanNoVet(listener){return noVetListeners.add(listener),()=>{noVetListeners.delete(listener)}}var INTRO_PATH="/widget/v1/me/intro";function disposed2(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function malformed5(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the documented shape`})}function introStateFromWire(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let o=raw;if(!("seen_at"in o))return null;let at=o.seen_at;return at===null?/* @__PURE__ */Object.freeze({seenAt:null}):typeof at!="string"||at.length===0||at.length>64||Number.isNaN(Date.parse(at))?null:/* @__PURE__ */Object.freeze({seenAt:at})}function createIntroRepository(runtime){let over=()=>{let{services:services}=runtime.registry;return createIntroRepositoryOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed2(verb)));return{read:opts=>runtime.isDisposed?gone("read"):over().read(opts),markSeen:()=>runtime.isDisposed?gone("markSeen"):over().markSeen()}}function createIntroRepositoryOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),call=async(name,req,opts)=>{let res=await funnel.send(name,req,opts);if(!res.ok)return err(res.error);let state3=introStateFromWire(res.value);return state3===null?err(malformed5(name)):ok(state3)};return{read(opts){let req=opts?.signal?{method:"GET",path:INTRO_PATH,signal:opts.signal}:{method:"GET",path:INTRO_PATH};return call("intro.read",req,{maxAttempts:1})},markSeen(){return call("intro.markSeen",{method:"PUT",path:INTRO_PATH,body:{seen:true}})}}}var INTRO_SEEN_KV_PREFIX="everfur.intro.seen.v1:",keyFor=userRef2=>`${INTRO_SEEN_KV_PREFIX}${userRef2}`;async function readIntroSeenLocally(kv,userRef2){try{return await kv.getItem(keyFor(userRef2))!==null}catch{return false}}async function keepIntroSeenLocally(kv,userRef2,at){try{await kv.setItem(keyFor(userRef2),at)}catch{}}async function shouldPlayIntro(deps){let{repo:repo,kv:kv,userRef:userRef2,signal:signal}=deps;if(userRef2===null||await readIntroSeenLocally(kv,userRef2))return false;let read;try{read=await repo.read(signal?{signal:signal}:void 0)}catch{return false}return signal?.aborted===true||!read.ok?false:read.value.seenAt!==null?(await keepIntroSeenLocally(kv,userRef2,read.value.seenAt),false):true}async function markIntroSeen(deps){let{repo:repo,kv:kv,userRef:userRef2}=deps;if(userRef2!==null){await keepIntroSeenLocally(kv,userRef2,(deps.now?.()??/* @__PURE__ */new Date).toISOString());try{await repo.markSeen()}catch{}}}function mix2(color,share,ground){let over=withAlpha(color,share);return(over===null?null:flattenOnto(over,ground))??ground}function askIntroColors(theme){let v=v3Palette(theme),c=theme.color,card=v.card;return{ink:v.ink,ink2:v.ink2,ink3:v.ink3,paper:v.paper,tile:v.tile,line:v.line,card:card,onInk:v.dark?c.background:"#FFFFFF",primary:v.primary,onPrimary:v.onPrimary,accent:v.accent,onAccent:v3InkOn(v.accent,[v.ink,v.onAccent]),accent2:mix2(v.accent,.75,card),accent4:mix2(v.accent,.17,card),accentChip:mix2(v.accent,.47,card),link:v.link,linkChip:mix2(v.link,.2,card),riskDot:v.riskDot,riskChip:v.dark?c.badgeBgCritical:"#FFD8D6",clearBg:v.clearBg,clearInk:v.clearInk,clearChip:v.dark?c.badgeBgPositive:"#DDEFC4",byInk:c.brandInk}}function askIntroTokens(theme){return{...askIntroColors(theme),sans:faceCss(theme,"regular").fontFamily,serif:headingFaceCss(theme,"bold").fontFamily,mono:cssMonoFamily(theme.type.mono)}}var warned4=/* @__PURE__ */new Set;function warnUnknownRule(key){warned4.has(key)||!isWebDevelopment()||(warned4.add(key),globalThis.console?.warn?.(`[everfur] unknown style rule ${key}`))}var camel=prop=>prop.startsWith("--")?prop:prop.replace(/-([a-z])/g,(_m,ch)=>ch.toUpperCase());function askIntroSx(theme,rules,reduced){let tokens=askIntroTokens(theme),dark=theme.brightness==="dark",fill2=value=>value.replace(/\$(n_[0-9A-F]{6}|[a-zA-Z0-9]+)/g,(whole,key)=>key.startsWith("n_")?dark?tokens.line??whole:`#${key.slice(2)}`:tokens[key]??whole),cache2=/* @__PURE__ */new Map;return(...selectors)=>{let keys=selectors.filter(s=>typeof s=="string"&&s!==""),id=keys.join("|"),hit=cache2.get(id);if(hit!==void 0)return hit;let out={};for(let key of keys){let decls=rules[key];if(decls===void 0){warnUnknownRule(key);continue}for(let[prop,value]of decls)out[camel(prop)]=fill2(value);if(theme.motion.reducedMotion)for(let[prop,value]of reduced[key]??[])out[camel(prop)]=fill2(value)}let style=/* @__PURE__ */Object.freeze(out);return cache2.set(id,style),style}}function askIntroReset(theme){let tokens=askIntroTokens(theme);return{root:{boxSizing:"border-box",fontFamily:tokens.sans,fontSize:17,lineHeight:1.5,color:tokens.ink,WebkitFontSmoothing:"antialiased",textRendering:"optimizeLegibility",fontVariationSettings:'"SOFT" 0, "WONK" 0',fontVariantLigatures:"no-common-ligatures"},button:{boxSizing:"border-box",font:"inherit",color:"inherit",background:"none",border:0,padding:0,margin:0,cursor:"pointer",textAlign:"inherit",WebkitTapHighlightColor:"transparent",touchAction:"manipulation"},text:{margin:0,boxSizing:"border-box"},srOnly:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"}}}var INTRO_OPEN_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#IntroOpen@v1"),host=globalThis;function isIntroOpenState(value){if(typeof value!="object"||value===null)return false;let v=value;return v.holds instanceof Set&&v.listeners instanceof Set}var stored2=host[INTRO_OPEN_SYMBOL],fresh3=()=>({holds:/* @__PURE__ */new Set,listeners:/* @__PURE__ */new Set}),state2=isIntroOpenState(stored2)?stored2:host[INTRO_OPEN_SYMBOL]=fresh3();function notify2(){for(let listener of[...state2.listeners])try{listener()}catch{}}function holdIntroOpen(){let token={};return state2.holds.add(token),state2.holds.size===1&¬ify2(),()=>{state2.holds.delete(token)&&state2.holds.size===0&¬ify2()}}function useIntroOpenHold(held){useEffect(()=>held?holdIntroOpen():void 0,[held])}var EVERFUR_RECORDS_REQUESTED_EVENT="everfur:records-requested",EVERFUR_RECORDS_LANDED_EVENT="everfur:records-landed";function emitRecordsEvent(name,detail){try{if(typeof window>"u"||typeof CustomEvent!="function")return;window.dispatchEvent(new CustomEvent(name,{detail:detail}))}catch{}}var EVERFUR_TABS_COPY=/* @__PURE__ */Object.freeze({ask:"Ask",plan:"Health Plan",records:"Records",listAll:"Ask, Health Plan and Records",listNoPlan:"Ask and Records"}),ALL=/* @__PURE__ */Object.freeze(["ask","plan","records"]),NO_PLAN=/* @__PURE__ */Object.freeze(["ask","records"]);function tabsFor(planHidden){return planHidden?NO_PLAN:ALL}function resolveTab(wanted,planHidden){return wanted==="plan"&&planHidden?"ask":wanted}function landingTab(opened,planHidden){return opened.via==="link"?resolveTab(opened.ask!==void 0?"ask":opened.tab,planHidden):resolveTab("plan",planHidden)}function openedKey(opened){let key=opened.key===void 0?"":String(opened.key);return opened.via==="link"?`link:${opened.tab}:${opened.ask?.prompt??""}:${key}`:`plain:${key}`}function tabKeyTarget(tabs,current,key){let at=Math.max(0,tabs.indexOf(current)),n=tabs.length;if(n===0)return null;let to=key==="ArrowRight"?(at+1)%n:key==="ArrowLeft"?(at-1+n)%n:key==="Home"?0:key==="End"?n-1:-1;return to<0?null:tabs[to]??null}var PLAN_STALE_MS=6e4;function isPlanReadStale(lastReadAt,now,staleMs=PLAN_STALE_MS){return lastReadAt!==null&&now-lastReadAt>=staleMs}function isPlanReturnReadDue(read){return read.pageVisible&&read.watching&&isPlanReadStale(read.lastReadAt,read.now)}function stableJson(value){return JSON.stringify(value,(_key,field)=>{if(field===null||typeof field!="object"||Array.isArray(field))return field;let sorted={};for(let key of Object.keys(field).sort())sorted[key]=field[key];return sorted})}function planSignature(plan){if(plan===null)return"";let items=plan.items.map(item=>[item.productId,item.partnerSku,item.title,item.description,item.category,item.price,item.currency,item.imageUrl,item.url,item.sample]).sort((a,b)=>a[0]<b[0]?-1:a[0]>b[0]?1:0);return JSON.stringify([plan.headline,items])}function pageSignature(page){return page===null?"":stableJson([page.checkout,page.page])}function readSignature(plan,page){return JSON.stringify([planSignature(plan),pageSignature(page)])}function isPlanReadSettled(planStatus,pagePhase){return planStatus!=="empty"&&planStatus!=="ready"?false:pagePhase==="ready"||pagePhase==="failed"||pagePhase==="idle"}function nextPlanVerdict(previous,read){return previous===void 0?{empty:read.empty,signature:read.signature,epoch:0}:previous.empty===read.empty&&previous.signature===read.signature?previous:{empty:read.empty,signature:read.signature,epoch:previous.signature===read.signature?previous.epoch:previous.epoch+1}}var INTRO_WAIT_MS=5e3;function introWantStep(state3){return state3.sameOpen?state3.plan===void 0?state3.planFailed?"drop":"wait":state3.plan.empty?"drop":!state3.moduleReady||state3.recordsPending?"wait":"play":"drop"}function createPaneShownSignal(){let listeners3=/* @__PURE__ */new Set;return{listen(listener){let entry=()=>listener();return listeners3.add(entry),()=>{listeners3.delete(entry)}},fire(){for(let listener of[...listeners3])try{listener()}catch{}}}}function withPaneShown(base2,shown){return{...{onForeground(listener){let stopBase=base2.onForeground(listener),stopShown=shown.listen(listener);return()=>{stopShown(),stopBase()}}},...base2.onOnline===void 0?{}:{onOnline:base2.onOnline.bind(base2)},...base2.onAnnounced===void 0?{}:{onAnnounced:base2.onAnnounced.bind(base2)},...base2.isOffline===void 0?{}:{isOffline:base2.isOffline.bind(base2)}}}function isPaneShownEdge(wasShown,shown){return!wasShown&&shown}function planProbeOver(m){return function({petRef:petRef2,pagePhase:pagePhase,page:page,refreshPage:refreshPage,watching:watching,onPlan:onPlan,onPlanFailed:onPlanFailed}){let{status:status,plan:plan,refresh:refresh}=m.useEverfurHealthPlan({petRef:petRef2}),readAt=useRef(null),latest=useRef({plan:refresh,page:refreshPage,watching:watching});latest.current={plan:refresh,page:refreshPage,watching:watching},useEffect(()=>{let settled=isPlanReadSettled(status,pagePhase);(status==="failed"||settled)&&(readAt.current=Date.now()),settled?onPlan(petRef2,{empty:status==="empty",signature:readSignature(plan,page)}):status==="failed"&&onPlanFailed(petRef2)},[status,plan,pagePhase,page,petRef2,onPlan,onPlanFailed]);let readAgainIfDue=useRef(()=>{});return readAgainIfDue.current=()=>{let reads=latest.current,pageVisible=typeof document>"u"||document.visibilityState==="visible";isPlanReturnReadDue({pageVisible:pageVisible,watching:reads.watching,lastReadAt:readAt.current,now:Date.now()})&&(readAt.current=null,reads.plan(),reads.page())},useEffect(()=>{if(typeof document>"u")return;let onVisible=()=>readAgainIfDue.current();return document.addEventListener("visibilitychange",onVisible),()=>document.removeEventListener("visibilitychange",onVisible)},[]),useEffect(()=>{watching&&readAgainIfDue.current()},[watching]),null}}function recordsProbeOver(m){return function({petRef:petRef2,onRecords:onRecords}){let{status:status}=m.useEverfurRecords({petRef:petRef2});return useEffect(()=>{onRecords(petRef2,status==="empty"?"none":status==="populated"?"some":null)},[status,petRef2,onRecords]),null}}function NoPlan({petRef:petRef2,onPlanFailed:onPlanFailed}){return useEffect(()=>onPlanFailed(petRef2),[petRef2,onPlanFailed]),null}function NoRecords({petRef:petRef2,onRecords:onRecords}){return useEffect(()=>onRecords(petRef2,null),[petRef2,onRecords]),null}var LazyPlanProbe=/* @__PURE__ */lazy(()=>import("@everfur/sdk/web/health-plan").then(m=>({default:planProbeOver(m)}),()=>({default:NoPlan}))),LazyRecordsProbe=/* @__PURE__ */lazy(()=>import("@everfur/sdk/web/records").then(m=>({default:recordsProbeOver(m)}),()=>({default:NoRecords})));function PlanProbe(props){/* @__PURE__ */
|
|
402
|
+
return jsx(Suspense,{fallback:null,children:/* @__PURE__ */jsx(LazyPlanProbe,{...props})})}function RecordsProbe(props){/* @__PURE__ */
|
|
403
|
+
return jsx(Suspense,{fallback:null,children:/* @__PURE__ */jsx(LazyRecordsProbe,{...props})})}var TAB_RULES={".ph-sub":[["flex","none"],["display","grid"],["grid-template-columns","repeat(3, 1fr)"],["height","46px"],["background","$paper"],["box-shadow","inset 0 -1px 0 $line"]],".ph-sub button":[["position","relative"],["font-size","16px"],["font-weight","600"],["color","$ink3"],["text-align","center"],["isolation","isolate"],["transition","color 240ms ease"]],'.ph-sub button[aria-selected="true"]':[["color","$ink"],["font-weight","800"]],'.ph-sub button[aria-selected="true"]::after':[["position","absolute"],["left","18%"],["right","18%"],["bottom","0"],["height","3px"],["border-radius","3px 3px 0 0"],["background","$primary"]],".ph-sub button .ph-new":[["position","absolute"],["top","12px"],["margin-left","3px"],["width","7px"],["height","7px"],["border-radius","50%"],["background","$riskDot"]],".ph-toast":[["position","absolute"],["left","16px"],["right","16px"],["top","112px"],["z-index","50"],["background","$ink"],["color","$onInk"],["border-radius","16px"],["padding","12px 15px"],["font-size","14.5px"],["line-height","1.4"],["opacity","0"],["transform","translateY(-8px)"],["pointer-events","none"],["transition","opacity 160ms ease, transform 160ms cubic-bezier(0.23, 1, 0.32, 1)"]],".ph-toast.is-on":[["opacity","1"],["transform","none"],["transition-duration","220ms"]],".ph-sub button::before":[["position","absolute"],["inset","7px 8px"],["z-index","-1"],["border-radius","999px"],["background","var(--in-tint, transparent)"],["opacity","0"],["transform","scale(.94)"],["transition","opacity 200ms ease, transform 200ms cubic-bezier(0.23, 1, 0.32, 1)"]],'.ph-sub [data-sub="ask"]':[["--in-tint","$accentChip"],["--in-k","0"]],'.ph-sub [data-sub="plan"]':[["--in-tint","$linkChip"],["--in-k","1"]],'.ph-sub [data-sub="records"]':[["--in-tint","$clearChip"],["--in-k","2"]],'#ph[data-in-frame="tabs"] .ph-sub button':[["color","$ink"],["font-weight","800"]],'#ph[data-in-frame="tabs"] .ph-sub button::before':[["opacity","1"],["transform","none"],["transition","opacity 260ms ease, transform 260ms cubic-bezier(0.23, 1, 0.32, 1)"],["transition-delay","calc(560ms + var(--in-k) * 60ms)"]],'#ph[data-in-frame="tabs"] .ph-sub button::after':[["opacity","0"]]},TAB_REDUCED_RULES={".ph-sub button::before":[["transform","none"],["transition","opacity 150ms ease"],["transition-delay","0ms"]],'#ph[data-in-frame="tabs"] .ph-sub button::before':[["transform","none"],["transition","opacity 150ms ease"],["transition-delay","0ms"]]};var TabsContext=/* @__PURE__ */createContext(null);function useEverfurTabs(){return useContext(TabsContext)}var introLoad=null;function loadIntro(){return introLoad===null&&(introLoad=import("@everfur/sdk/web/intro").then(m=>m,()=>(introLoad=null,null))),introLoad}var NoPane=()=>null,LazyHealthPlan=/* @__PURE__ */lazy(()=>import("@everfur/sdk/web/health-plan").then(m=>({default:m.EverfurHealthPlan}),()=>({default:NoPane}))),LazyRecordsPage=/* @__PURE__ */lazy(()=>import("@everfur/sdk/web/records").then(m=>({default:m.EverfurRecordsPage}),()=>({default:NoPane}))),paneLoading=/* @__PURE__ */jsx("div",{role:"status","aria-busy":"true"}),INTRO_QUIET_MS=200,TOAST_INTO_BAR=4,TOAST_MS=2600,DEFAULT_INTRO_MAX_WIDTH=600,fill={flex:1,minHeight:0,display:"flex",flexDirection:"column"},scroller={flex:1,minHeight:0,overflowY:"auto",overscrollBehavior:"contain",scrollbarWidth:"none"};function EverfurTabs(props){let{petRef:petRef2,opened:opened,onTabChange:onTabChange,onRecordsRequested:onRecordsRequested,onRecordsLanded:onRecordsLanded,onToast:onToast}=props,visible=props.visible??true,theme=useEverfurTheme(),sx=useMemo(()=>askIntroSx(theme,TAB_RULES,TAB_REDUCED_RULES),[theme]),reset=useMemo(()=>askIntroReset(theme),[theme]),copy=useMemo(()=>({...EVERFUR_TABS_COPY,...props.copy}),[props.copy]),{runtime:runtime,userRef:userRef2}=useEverfurContext(),planEnabled=useCapabilityEnabled("healthPlan"),recordsEnabled=useCapabilityEnabled("records"),clinicEnabled=useCapabilityEnabled("recordsClinic"),[planVerdicts,setPlanVerdicts]=useState(()=>/* @__PURE__ */new Map),[planFailed,setPlanFailed]=useState(()=>/* @__PURE__ */new Set),onPlanRead=useCallback((ref,read)=>{setPlanVerdicts(previous=>{let before=previous.get(ref),next=nextPlanVerdict(before,read);return next===before?previous:new Map(previous).set(ref,next)}),setPlanFailed(previous=>previous.has(ref)?new Set([...previous].filter(pet=>pet!==ref)):previous)},[]),onPlanFailed=useCallback(ref=>{setPlanFailed(previous=>previous.has(ref)?previous:new Set(previous).add(ref))},[]),planVerdict=petRef2===null?void 0:planVerdicts.get(petRef2),planHidden=!planEnabled||planVerdict?.empty===true,planKey=`${petRef2??"none"}:${planVerdict?.epoch??0}`,tabs=tabsFor(planHidden),planHiddenRef=useRef(planHidden);planHiddenRef.current=planHidden;let page=useHealthPlanPage({petRef:petRef2,enabled:planEnabled&&petRef2!==null}),[sub,setSub]=useState(()=>landingTab(opened,false)),[openedPanes,setOpenedPanes]=useState(()=>/* @__PURE__ */new Set(["ask",landingTab(opened,false)])),subRef=useRef(sub);subRef.current=sub;let open=useCallback(wanted=>{let next=resolveTab(wanted,planHiddenRef.current);setSub(next),setOpenedPanes(previous=>previous.has(next)?previous:new Set(previous).add(next))},[]);useEffect(()=>{planHidden&&sub==="plan"&&setSub("ask")},[planHidden,sub]);let tabChange=useRef(onTabChange);tabChange.current=onTabChange,useEffect(()=>{tabChange.current?.(sub)},[sub]),useEffect(()=>{!visible||props.documentTitle!==true||typeof document>"u"||(document.title=copy[sub])},[visible,sub,copy,props.documentTitle]);let[asked,setAsked]=useState(null),ask=useCallback((prompt,card)=>{prompt!==""&&setAsked(previous=>({id:(previous?.id??0)+1,prompt:prompt,petRef:petRef2,...card===void 0?{}:{card:card}})),open("ask")},[petRef2,open]),chatAsk=asked===null||asked.petRef!==petRef2?null:asked,key=openedKey(opened),handledKey=useRef(null),[plainOpen,setPlainOpen]=useState(null);useEffect(()=>{handledKey.current!==key&&(handledKey.current=key,opened.via==="link"&&opened.ask!==void 0?ask(opened.ask.prompt,opened.ask.card):open(landingTab(opened,planHiddenRef.current)),setPlainOpen(opened.via==="plain"?key:null))},[key,opened,ask,open]);let paneShown=useMemo(()=>createPaneShownSignal(),[]),hostLifecycle=props.chat?.lifecycle,chatLifecycle=useMemo(()=>hostLifecycle===null?null:withPaneShown(hostLifecycle??createBrowserLifecycle(),paneShown),[hostLifecycle,paneShown]),askShown=visible&&sub==="ask",wasAskShown=useRef(askShown);useEffect(()=>{let edge=isPaneShownEdge(wasAskShown.current,askShown);wasAskShown.current=askShown,edge&&paneShown.fire()},[askShown,paneShown]);let[toast,setToast]=useState(null),[toastOn,setToastOn]=useState(false),say=useCallback(text3=>{text3!==""&&(onToast!==void 0?onToast(text3):setToast(previous=>({id:(previous?.id??0)+1,text:text3})))},[onToast]);useEffect(()=>{if(toast===null)return;let raf=requestAnimationFrame(()=>setToastOn(true)),timer=setTimeout(()=>setToastOn(false),TOAST_MS);return()=>{cancelAnimationFrame(raf),clearTimeout(timer),setToastOn(false)}},[toast]);let introOptions=props.intro===false?null:props.intro??{},[introModule,setIntroModule]=useState(null),[run,setRun]=useState(null),[introFrame,setIntroFrame]=useState(null),[wants,setWants]=useState(null),[requested,setRequested]=useState(null),[recordsVerdicts,setRecordsVerdicts]=useState(()=>/* @__PURE__ */new Map),[banner,setBanner]=useState(false),[noVet,setNoVet]=useState(false),[introUnavailable,setIntroUnavailable]=useState(false),introFrameRef=useRef(null),focusTabOnClosed=useRef(false),rootRef=useRef(null),barRef=useRef(null),tabRefs=useRef({}),repo=useMemo(()=>createIntroRepository(runtime),[runtime]),kv=runtime.registry.services.kv,ensureIntroModule=useCallback(onUnavailable=>{loadIntro().then(m=>{if(setIntroUnavailable(m===null),m!==null){setIntroModule(previous=>previous??m);return}setWants(null),setRun(null),onUnavailable?.()})},[]),maxWidth=introOptions?.maxWidth??DEFAULT_INTRO_MAX_WIDTH,introAllowed=introOptions!==null&&planEnabled,introAsks=introAllowed&&plainOpen!==null&&visible&&userRef2!==null&&petRef2!==null,[decided,setDecided]=useState(null);useEffect(()=>{if(!introAsks)return;let forKey=plainOpen,box=props.overlayContainer??rootRef.current;if((typeof window<"u"?window.innerWidth:box?.getBoundingClientRect().width??0)>=maxWidth){setDecided(forKey);return}let control=new AbortController,forPet2=petRef2;return shouldPlayIntro({repo:repo,kv:kv,userRef:userRef2,signal:control.signal}).then(play=>{control.signal.aborted||(setDecided(forKey),play&&(ensureIntroModule(),setWants({key:forKey,petRef:forPet2})))},()=>{control.signal.aborted||setDecided(forKey)}),()=>control.abort()},[introAsks,plainOpen,userRef2,petRef2,repo,kv,maxWidth,props.overlayContainer,ensureIntroModule]);let refsPending=introAllowed&&plainOpen!==null&&visible&&(userRef2===null||petRef2===null)&&(typeof window>"u"||window.innerWidth<maxWidth),[refsWaitOver,setRefsWaitOver]=useState(null);useEffect(()=>{if(!refsPending)return;let forKey=plainOpen,timer=setTimeout(()=>setRefsWaitOver(forKey),INTRO_WAIT_MS);return()=>clearTimeout(timer)},[refsPending,plainOpen]),useIntroOpenHold(refsPending&&refsWaitOver!==plainOpen||introAsks&&decided!==plainOpen||wants!==null||run!==null);let onRecordsVerdict=useCallback((ref,verdict)=>{setRecordsVerdicts(previous=>previous.get(ref)===verdict?previous:new Map(previous).set(ref,verdict))},[]),recordsVerdict=petRef2===null?void 0:recordsVerdicts.get(petRef2),recordsConnected=recordsVerdict==="some";useEffect(()=>{petRef2!==null&&recordsConnected&&setHealthPlanNoVet(petRef2,false)},[petRef2,recordsConnected]),useEffect(()=>{if(wants===null||run!==null)return;let step=introWantStep({sameOpen:wants.key===plainOpen&&wants.petRef===petRef2,plan:planVerdict,planFailed:planFailed.has(wants.petRef),moduleReady:introModule!==null,recordsPending:recordsEnabled&&recordsVerdict===void 0});if(step==="drop"&&setWants(null),step!=="play")return;open("ask");let timer=setTimeout(()=>{setWants(null),setRun(previous=>({mode:"intro",id:(previous?.id??0)+1}))},INTRO_QUIET_MS);return()=>clearTimeout(timer)},[wants,run,plainOpen,petRef2,planVerdict,planFailed,introModule,recordsEnabled,recordsVerdict,open]),useEffect(()=>{if(wants===null)return;let timer=setTimeout(()=>setWants(current=>current===wants?null:current),INTRO_WAIT_MS);return()=>clearTimeout(timer)},[wants]);let requestRecords=useCallback(()=>{petRef2!==null&&(ensureIntroModule(()=>open("records")),setRun(previous=>({mode:"records",id:(previous?.id??0)+1})))},[petRef2,ensureIntroModule,open]),onIntroClose=useCallback(close=>{(run?.mode??"intro")==="intro"&&markIntroSeen({repo:repo,kv:kv,userRef:userRef2}),introFrameRef.current==="novet"&&petRef2!==null&&setHealthPlanNoVet(petRef2,true),close.exit==="plan"?open("plan"):close.exit==="ask"&&open("ask"),focusTabOnClosed.current=close.exit!=="stay",close.notifications!==null&&setRequested(previous=>previous===null?previous:{...previous,notified:close.notifications}),close.toast!==null&&say(close.toast)},[run,repo,kv,userRef2,petRef2,open,say]),onIntroClosed=useCallback(()=>setRun(null),[]);useEffect(()=>{run!==null||!focusTabOnClosed.current||(focusTabOnClosed.current=false,tabRefs.current[subRef.current]?.focus({preventScroll:true}))},[run]);let onRequested=useCallback(event=>{setRequested({petRef:event.petRef,notified:null}),setHealthPlanNoVet(event.petRef,false),onRecordsRequested?.(event)},[onRecordsRequested]),onFrame=useCallback(frame=>{frame!==null&&(introFrameRef.current=frame),setIntroFrame(frame)},[]);useEffect(()=>{if(petRef2===null){setNoVet(false);return}return setNoVet(healthPlanNoVet(petRef2)),onHealthPlanNoVet((pet,none)=>{pet===petRef2&&setNoVet(none)})},[petRef2]),useEffect(()=>onHealthPlanRecordsLanded(pet=>setHealthPlanNoVet(pet,false)),[]);let landedFrom=useRef(void 0),land=useCallback(()=>{if(setBanner(false),open("plan"),introModule!==null&&petRef2!==null){let facts=introModule.introFacts(page.page,props.petName);say(introModule.introText({facts:facts,copy:{...introModule.EVERFUR_INTRO_COPY,...introOptions?.copy},blanks:0,resultsPending:false}).toast.landed)}},[open,introModule,petRef2,page.page,props.petName,introOptions?.copy,say]);useEffect(()=>{let before=landedFrom.current;if(landedFrom.current=recordsVerdict,requested===null||petRef2===null||requested.petRef!==petRef2||before!=="none"||recordsVerdict!=="some")return;let event={petRef:petRef2,at:/* @__PURE__ */(new Date).toISOString()};emitRecordsEvent(EVERFUR_RECORDS_LANDED_EVENT,event),onRecordsLanded?.(event),notifyHealthPlanRecordsLanded(petRef2),setRequested(null),requested.notified===true?setBanner(true):land()},[recordsVerdict,requested,petRef2,onRecordsLanded,land]);let covered=props.overlayContainer??null,[toastTop,setToastTop]=useState(null);useLayoutEffect(()=>{let bar2=barRef.current,box=covered??rootRef.current;if(bar2===null||box===null||toast===null)return;let a=box.getBoundingClientRect(),b=bar2.getBoundingClientRect();setToastTop(Math.round(b.top-a.top+TOAST_INTO_BAR))},[covered,toast]);let onTabKey=event=>{let next=tabKeyTarget(tabs,sub,event.key);next!==null&&(event.preventDefault(),open(next),tabRefs.current[next]?.focus())},lit=introFrame==="tabs",cls=props.classNames??{},bar=/* @__PURE__ */jsx("div",{ref:barRef,role:"tablist","aria-label":planHidden?copy.listNoPlan:copy.listAll,className:cls.bar,style:{...sx(".ph-sub"),gridTemplateColumns:`repeat(${tabs.length}, 1fr)`},onKeyDown:onTabKey,children:tabs.map(id=>{let selected=sub===id;/* @__PURE__ */
|
|
404
|
+
return jsxs("button",{ref:element=>{tabRefs.current[id]=element},type:"button",role:"tab",id:`everfur-tab-${id}`,"data-sub":id,"aria-selected":selected,...openedPanes.has(id)?{"aria-controls":`everfur-pane-${id}`}:{},tabIndex:selected?0:-1,className:cls.tab,style:{...reset.button,...sx(".ph-sub button",`.ph-sub [data-sub="${id}"]`,selected&&'.ph-sub button[aria-selected="true"]',lit&&'#ph[data-in-frame="tabs"] .ph-sub button')},onClick:()=>open(id),children:[
|
|
405
|
+
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:sx(".ph-sub button::before",lit&&'#ph[data-in-frame="tabs"] .ph-sub button::before')}),copy[id],selected?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:sx('.ph-sub button[aria-selected="true"]::after',lit&&'#ph[data-in-frame="tabs"] .ph-sub button::after')}):null]},id)})}),chat=props.chat,pending2=props.resultsPending===true,chatPresentation=useMemo(()=>pending2?{...chat?.presentation,chatTopCard:"none"}:chat?.presentation,[pending2,chat?.presentation]),openPlan=useCallback(()=>open("plan"),[open]),openRecords=useCallback(()=>open("records"),[open]),plan=props.plan,planFocus=useMemo(()=>plan?.focus===void 0?void 0:{...plan.focus,onConnectRecords:plan.focus.onConnectRecords??openRecords},[plan?.focus,openRecords]),pane=id=>sub===id?{position:"absolute",inset:0,display:"flex",flexDirection:"column"}:{display:"none"},petName=props.petName??page.page?.pet.name??"",records=props.records,recordsSeams={...introUnavailable?{}:{onRequestFromClinic:requestRecords},...noVet?{noVet:true}:{}},recordsPage=petRef2===null?null:/* @__PURE__ */jsx(LazyRecordsPage,{...recordsSeams,...records,petRef:petRef2,...petName===""?{}:{petName:petName},onAsk:records?.onAsk??(prompt=>ask(prompt)),onOpenPlan:records?.onOpenPlan??openPlan},petRef2),handle=useMemo(()=>({tab:sub,open:open,ask:ask,requestRecords:requestRecords}),[sub,open,ask,requestRecords]),tabsRef=props.tabsRef;useLayoutEffect(()=>{if(tabsRef!==void 0)return tabsRef.current=handle,()=>{tabsRef.current===handle&&(tabsRef.current=null)}},[tabsRef,handle]);let Intro=introModule?.EverfurIntro,Banner2=introModule?.EverfurRecordsLandedBanner,overlay=node=>covered===null?node:createPortal(node,covered),bannerText=banner&&introModule!==null?introModule.introText({facts:introModule.introFacts(page.page,props.petName),copy:{...introModule.EVERFUR_INTRO_COPY,...introOptions?.copy},blanks:0,resultsPending:false}).banner:null;/* @__PURE__ */
|
|
406
|
+
return jsx(TabsContext.Provider,{value:handle,children:/* @__PURE__ */jsxs("div",{ref:rootRef,"data-everfur-tabs":"","data-in-frame":introFrame??void 0,className:[props.className,cls.root].filter(Boolean).join(" ")||void 0,style:{position:"relative",display:"flex",flexDirection:"column",minHeight:0,height:"100%",...props.style},children:[bar,petRef2===null||!planEnabled?null:/* @__PURE__ */jsx(PlanProbe,{petRef:petRef2,pagePhase:page.phase,page:page.page,refreshPage:page.refresh,watching:visible&&(sub==="plan"||planHidden),onPlan:onPlanRead,onPlanFailed:onPlanFailed}),petRef2!==null&&recordsEnabled&&(wants!==null||run!==null||requested!==null)?/* @__PURE__ */jsx(RecordsProbe,{petRef:petRef2,onRecords:onRecordsVerdict}):null,
|
|
407
|
+
/* @__PURE__ */jsxs("div",{className:cls.panes,style:{flex:1,minHeight:0,position:"relative"},children:[
|
|
408
|
+
/* @__PURE__ */jsxs("div",{className:cls.pane,id:"everfur-pane-ask",role:"tabpanel","aria-labelledby":"everfur-tab-ask",hidden:sub!=="ask",style:pane("ask"),children:[
|
|
409
|
+
/* @__PURE__ */jsx("div",{className:cls.ask,style:fill,children:/* @__PURE__ */jsx(EverfurChat,{...chat,style:{flex:1,minHeight:0,...chat?.style},...chatPresentation===void 0?{}:{presentation:chatPresentation},...pending2&&props.pendingStarterPrompts!==void 0?{starterPrompts:props.pendingStarterPrompts}:{},...petRef2===null?{}:{petRef:petRef2},lifecycle:chatLifecycle,onOpenHealthPlan:openPlan,...chatAsk===null?{}:{initialAsk:chatAsk.prompt,initialAskKey:chatAsk.id,...chatAsk.card===void 0?{}:{initialAskCard:chatAsk.card}}})},petRef2??"none"),props.paneFooter?.ask]}),openedPanes.has("plan")&&!planHidden?/* @__PURE__ */jsxs("div",{className:cls.pane,id:"everfur-pane-plan",role:"tabpanel","aria-labelledby":"everfur-tab-plan",hidden:sub!=="plan",style:pane("plan"),children:[
|
|
410
|
+
/* @__PURE__ */jsx("div",{className:cls.scroll,style:scroller,children:/* @__PURE__ */jsx(Suspense,{fallback:paneLoading,children:/* @__PURE__ */jsx(LazyHealthPlan,{...plan,...planFocus===void 0?{}:{focus:planFocus},petRef:petRef2},planKey)})},petRef2??"none"),props.paneFooter?.plan]}):null,openedPanes.has("records")?/* @__PURE__ */jsxs("div",{className:cls.pane,id:"everfur-pane-records",role:"tabpanel","aria-labelledby":"everfur-tab-records",hidden:sub!=="records",style:pane("records"),children:[
|
|
411
|
+
/* @__PURE__ */jsx("div",{className:cls.scroll,style:scroller,children:/* @__PURE__ */jsx(Suspense,{fallback:paneLoading,children:props.renderRecords===void 0?recordsPage:props.renderRecords(recordsPage)})},petRef2??"none"),props.paneFooter?.records]}):null]}),onToast!==void 0?null:
|
|
412
|
+
/* @__PURE__ */jsx("div",{role:"status","aria-live":"polite",style:reset.srOnly,children:toast!==null&&toastOn&&run===null?toast.text:""}),toast===null||onToast!==void 0?null:overlay(
|
|
413
|
+
/* @__PURE__ */jsx("div",{"aria-hidden":"true",style:{...reset.root,...sx(".ph-toast",toastOn&&".ph-toast.is-on"),...toastTop===null?{}:{top:toastTop}},children:toast.text},`toast-${toast.id}`)),Banner2!==void 0&&bannerText!==null?overlay(/* @__PURE__ */jsx(Banner2,{text:bannerText,...introOptions?.bannerIcon===void 0?{}:{icon:introOptions.bannerIcon},onLand:land})):null,Intro===void 0||run===null||petRef2===null?null:/* @__PURE__ */jsx(Intro,{petRef:petRef2,mode:run.mode,page:page.page,petName:props.petName??null,recordsConnected:run.mode==="intro"&&(recordsConnected||!clinicEnabled),resultsPending:pending2,...introOptions?.copy===void 0?{}:{copy:introOptions.copy},...introOptions?.blanks===void 0?{}:{blanks:introOptions.blanks},container:covered??rootRef.current,tabBar:barRef.current,tabLabels:{ask:copy.ask,plan:copy.plan,records:copy.records},onFrame:onFrame,onClose:onIntroClose,onClosed:onIntroClosed,onRequested:onRequested,...introOptions?.onEnableNotifications===void 0?{}:{onEnableNotifications:introOptions.onEnableNotifications},onUpload:introOptions?.onUpload??openRecords,...introOptions?.ownerName===void 0?{}:{ownerName:introOptions.ownerName},...introOptions?.onCaptureSignature===void 0?{}:{onCaptureSignature:introOptions.onCaptureSignature}},`intro-${run.id}`)]})})}function useEverfurPetProfile(petRef2){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),key=useMemo(()=>({repository:repository,petRef:petRef2}),[repository,petRef2]),[state3,setState]=useState({key:key,profile:null,loading:petRef2!==null,error:null}),current=state3.key===key?state3:{profile:null,loading:petRef2!==null,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;if(key.petRef===null){setState({key:key,profile:null,loading:false,error:null});return}setState(previous=>({key:key,profile:previous.key===key?previous.profile:null,loading:true,error:null}));let result=await key.repository.getPetProfile(key.petRef);request===generation.current&&setState(result.ok?{key:key,profile:result.value,loading:false,error:null}:{key:key,profile:null,loading:false,error:result.error})},[key]);return useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useMemo(()=>({profile:current.profile,loading:current.loading,error:current.error,refresh:load}),[current.profile,current.loading,current.error,load])}function EverfurThemeProvider(props){return createElement(EverfurThemeProviderCore,{clientTheme:props.clientTheme??null,seams:webThemeSeams,children:props.children})}export{APPEARANCE_PRESETS,APPEARANCE_PRESET_NAMES,APPEARANCE_SIZE_RANGES,CapabilityGate,DEFAULT_PRESENTATION,EVERFUR_RECORDS_LANDED_EVENT,EVERFUR_RECORDS_REQUESTED_EVENT,EVERFUR_TABS_COPY,EverfurChat,EverfurConfigError,EverfurPoweredBy,EverfurProvider,EverfurTabs,EverfurThemeProvider,EverfurThrownError,THEME_SLOT_KEYS,THEME_SLOT_KEYS_BY_SLOT,THEME_SLOT_NAMES,canonicalPetSpecies,categoryFor,conversationId,createBrowserLifecycle,createLocalStorageKv,createWebAttachmentTransport,expandAppearance,face,faceCss,fileToAttachmentHandle,headingFace,headingFaceCss,isErr,isOk,isRetryableCode,parsePresentation,petRef,previewTheme,resolvePresentation,themeAdjustments,themeSlotKeysFor,unwrap,useCapability,useChatAttachments,useEverfur,useEverfurChat,useEverfurPetProfile,useEverfurPets,useEverfurPresentation,useEverfurTabs,useEverfurTheme,useHostPoweredBy,userFacingError,userRef};
|