@everfur/sdk 1.6.1 → 1.7.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/dist/{Chat.d-B4GybUU4.d.ts → Chat.d-BIr_4AJt.d.ts} +1 -1
- package/dist/{Chat.d-DPM2ncxi.d.cts → Chat.d-BhevtXn9.d.cts} +1 -1
- package/dist/{DepthViews.d-BGspxovy.d.cts → DepthViews.d-C8KdfzwR.d.cts} +1 -1
- package/dist/{DepthViews.d-BaLh7Lsi.d.cts → DepthViews.d-DWQ-J208.d.cts} +1 -1
- package/dist/{DepthViews.d-BIHVrf9r.d.ts → DepthViews.d-DYVUq4Xk.d.ts} +1 -1
- package/dist/{DepthViews.d-CEVk9poG.d.ts → DepthViews.d-oKr9R0Ql.d.ts} +1 -1
- package/dist/{IntakeMedia.d-CwSkSLNM.d.ts → IntakeMedia.d-B-ZZK6vd.d.ts} +1 -1
- package/dist/{IntakeMedia.d-LRXO38_z.d.cts → IntakeMedia.d-CuVkzIsO.d.cts} +1 -1
- package/dist/{IntakeMedia.d-DmaeGU6T.d.cts → IntakeMedia.d-CyF6NPHx.d.cts} +1 -1
- package/dist/{IntakeMedia.d-Dyb9R8b0.d.ts → IntakeMedia.d-vU8g9OM5.d.ts} +1 -1
- package/dist/{RecordsPage.d-D10RIgdc.d.ts → RecordsPage.d-DU8Nswzh.d.ts} +1 -1
- package/dist/{RecordsPage.d-DbhYNSbq.d.cts → RecordsPage.d-DzPhqMHW.d.cts} +1 -1
- package/dist/animations/index.d.cts +3 -3
- package/dist/animations/index.d.ts +3 -3
- package/dist/{attachments.d-CF4lLuGK.d.cts → attachments.d-0nOPDIng.d.cts} +1 -1
- package/dist/{attachments.d-BlukNfIf.d.ts → attachments.d-BlyI-RCY.d.ts} +1 -1
- package/dist/{bookingCopy.d-Bn8bdo89.d.ts → bookingCopy.d-ClL8OxBS.d.ts} +3 -3
- package/dist/{bookingCopy.d-Dg7bPM-U.d.cts → bookingCopy.d-DUVqhF5f.d.cts} +3 -3
- package/dist/{branding.d-XrZYClN4.d.ts → branding.d-D0LV3aFE.d.ts} +1 -1
- package/dist/{branding.d-CqDLKj1U.d.cts → branding.d-DzSPLZKl.d.cts} +1 -1
- package/dist/{casesRepository.d-CVuKTkJo.d.cts → casesRepository.d-DnanKXJ1.d.cts} +1 -1
- package/dist/{casesRepository.d-Dn1fK1b2.d.ts → casesRepository.d-_4QucKVC.d.ts} +1 -1
- package/dist/chat/index.cjs +239 -238
- package/dist/chat/index.d.cts +11 -11
- package/dist/chat/index.d.ts +11 -11
- package/dist/chat/index.js +241 -240
- package/dist/chat/lite/index.cjs +239 -238
- package/dist/chat/lite/index.d.cts +11 -11
- package/dist/chat/lite/index.d.ts +11 -11
- package/dist/chat/lite/index.js +239 -238
- package/dist/{chatHandoffToken.d-zdp23Ukr.d.ts → chatHandoffToken.d-BoZGGbIB.d.ts} +5 -5
- package/dist/{chatHandoffToken.d-Cap2z62P.d.cts → chatHandoffToken.d-DhhGdLNH.d.cts} +5 -5
- package/dist/{checkin.d-CuIUahcd.d.cts → checkin.d-DB-HlK7r.d.cts} +9 -4
- package/dist/{checkin.d-BoZXWjxX.d.ts → checkin.d-DogrR06X.d.ts} +9 -4
- package/dist/{chunk-ZSCVH4UW.js → chunk-6E3J6IVM.js} +16 -16
- package/dist/{chunk-CQUKIPRU.js → chunk-J5ZUBY3S.js} +1 -1
- package/dist/{chunk-RF4N4WUN.js → chunk-LPHBCDJP.js} +18 -18
- package/dist/{chunk-DBQYQLJT.js → chunk-ULQDOC75.js} +1 -1
- package/dist/client/index.cjs +28 -27
- package/dist/client/index.d.cts +13 -13
- package/dist/client/index.d.ts +13 -13
- package/dist/client/index.js +25 -24
- package/dist/{clinicBatch.d-C0xx5L4j.d.cts → clinicBatch.d-BvPF6vXS.d.cts} +2 -2
- package/dist/{clinicBatch.d-DNi4UURs.d.ts → clinicBatch.d-CF0GIvpx.d.ts} +2 -2
- package/dist/{config.d-B7Z-KTGq.d.ts → config.d-Bc41Ax6M.d.ts} +5 -1
- package/dist/{config.d-ClAI2RZ6.d.cts → config.d-Bn6GEGfl.d.cts} +5 -1
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/{context.d-D7zX6Q0J.d.ts → context.d-0QfLaI3W.d.ts} +5 -5
- package/dist/{context.d-guaLkx5t.d.cts → context.d-CyQpedoU.d.cts} +5 -5
- package/dist/{copy.d--F5A9cXK.d.cts → copy.d-B55PpLxr.d.cts} +2 -2
- package/dist/{copy.d-DmxuFJFe.d.ts → copy.d-B8wIE6cH.d.ts} +2 -2
- package/dist/core/index.cjs +32 -31
- package/dist/core/index.d.cts +16 -16
- package/dist/core/index.d.ts +16 -16
- package/dist/core/index.js +32 -31
- package/dist/{depth.d-CgzYE6_n.d.ts → depth.d-CrtZXnLy.d.ts} +2 -2
- package/dist/{depth.d-DLaP0o8Y.d.cts → depth.d-Cxz6VisZ.d.cts} +2 -2
- package/dist/{entitlementRepository.d-CkUTlVAb.d.ts → entitlementRepository.d-BaZTIe1B.d.ts} +3 -3
- package/dist/{entitlementRepository.d-DVTp-BB9.d.cts → entitlementRepository.d-YeNG2TKI.d.cts} +3 -3
- package/dist/{focus.d-u-HYvim0.d.ts → focus.d-520VEHKB.d.ts} +1 -1
- package/dist/{focus.d-CLTjm6In.d.cts → focus.d-DoempN1I.d.cts} +1 -1
- package/dist/health-plan/index.cjs +236 -235
- package/dist/health-plan/index.d.cts +15 -15
- package/dist/health-plan/index.d.ts +15 -15
- package/dist/health-plan/index.js +236 -235
- package/dist/{healthPlanRepository.d-CwRXeoM7.d.ts → healthPlanRepository.d-BHu9LO0r.d.ts} +2 -2
- package/dist/{healthPlanRepository.d-B22kjrYa.d.cts → healthPlanRepository.d-tUR1f_5s.d.cts} +2 -2
- package/dist/{idempotency.d-DrxKLPPe.d.cts → idempotency.d-CcFLvzYW.d.cts} +1 -1
- package/dist/{idempotency.d-CbB07p64.d.ts → idempotency.d-CvqKG3Uq.d.ts} +1 -1
- package/dist/{identity.d-D4VtpqRr.d.ts → identity.d-Bex_XJZx.d.ts} +1 -1
- package/dist/{identity.d-DDpXOtas.d.cts → identity.d-Dm0Buvn8.d.cts} +1 -1
- package/dist/{inbox.d-B2JXK0uI.d.ts → inbox.d-9ajb0oiJ.d.ts} +1 -1
- package/dist/{inbox.d-CwA1ogzV.d.cts → inbox.d-CGCYOZIq.d.cts} +1 -1
- package/dist/index.cjs +362 -361
- package/dist/index.d.cts +17 -17
- package/dist/index.d.ts +17 -17
- package/dist/index.js +253 -252
- package/dist/{introEvents.d-DW3gLljE.d.ts → introEvents.d-CuVaufTy.d.ts} +1 -1
- package/dist/{introEvents.d-B7acmGwf.d.cts → introEvents.d-DU6feqx4.d.cts} +1 -1
- package/dist/{layout.d-C8y_ki1V.d.ts → layout.d-BQ5IVS-m.d.ts} +1 -1
- package/dist/{layout.d-DfaFM_lp.d.cts → layout.d-CSPr33BP.d.cts} +1 -1
- package/dist/notifications/inbox/index.d.cts +6 -6
- package/dist/notifications/inbox/index.d.ts +6 -6
- package/dist/notifications/index.d.cts +7 -7
- package/dist/notifications/index.d.ts +7 -7
- package/dist/{optInView.d-Cps7aLQN.d.ts → optInView.d-DpGXnpGw.d.ts} +21 -3
- package/dist/{optInView.d-ChJyJMBA.d.cts → optInView.d-dLjrI3co.d.cts} +21 -3
- package/dist/{pets.d-BpLObpfM.d.ts → pets.d-CHdSIoBf.d.ts} +1 -1
- package/dist/{pets.d-DXhzTNuI.d.cts → pets.d-jnhrJhqm.d.cts} +1 -1
- package/dist/{petsRepository.d-ai_tZ3lu.d.cts → petsRepository.d-BeKRiNao.d.cts} +1 -1
- package/dist/{petsRepository.d-_QfM7F6T.d.ts → petsRepository.d-BjwB1vku.d.ts} +1 -1
- package/dist/{presentation.d-BkIvMtIl.d.cts → presentation.d-Br3TnwA6.d.cts} +17 -1
- package/dist/{presentation.d-BkIvMtIl.d.ts → presentation.d-Br3TnwA6.d.ts} +17 -1
- package/dist/records/depth/index.d.cts +9 -9
- package/dist/records/depth/index.d.ts +9 -9
- package/dist/records/index.cjs +237 -228
- package/dist/records/index.d.cts +39 -12
- package/dist/records/index.d.ts +39 -12
- package/dist/records/index.js +155 -146
- package/dist/{requestFunnel.d-DKBPTpsy.d.ts → requestFunnel.d-C_NMgz9R.d.ts} +2 -2
- package/dist/{requestFunnel.d-BwZDfWVD.d.cts → requestFunnel.d-DoJWLySc.d.cts} +2 -2
- package/dist/{route.d-QBCoO62z.d.cts → route.d-BW2abFVK.d.cts} +2 -2
- package/dist/{route.d-B3u14HJT.d.ts → route.d-Olr_gXaa.d.ts} +2 -2
- package/dist/{runtimeTypes.d-hjN6xvxm.d.ts → runtimeTypes.d-Bp2VW6YE.d.ts} +6 -6
- package/dist/{runtimeTypes.d-BSxuUCOX.d.cts → runtimeTypes.d-StvJY45N.d.cts} +6 -6
- package/dist/{screenProps.d-fHBKArt_.d.ts → screenProps.d-BTLSji0N.d.ts} +1 -1
- package/dist/{screenProps.d-6xmE1C-V.d.cts → screenProps.d-B_5Bh7aQ.d.cts} +1 -1
- package/dist/server/events/index.cjs +2 -2
- package/dist/server/events/index.d.cts +19 -5
- package/dist/server/events/index.d.ts +19 -5
- package/dist/server/events/index.js +2 -2
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +3 -3
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +1 -1
- package/dist/shop/index.d.cts +3 -3
- package/dist/shop/index.d.ts +3 -3
- package/dist/slots/index.cjs +200 -199
- package/dist/slots/index.d.cts +5 -5
- package/dist/slots/index.d.ts +5 -5
- package/dist/slots/index.js +200 -199
- package/dist/tabs/index.cjs +200 -190
- package/dist/tabs/index.d.cts +68 -11
- package/dist/tabs/index.d.ts +68 -11
- package/dist/tabs/index.js +201 -191
- package/dist/tabs-bar/index.cjs +247 -0
- package/dist/tabs-bar/index.d.cts +10 -0
- package/dist/tabs-bar/index.d.ts +10 -0
- package/dist/tabs-bar/index.js +247 -0
- package/dist/{tabsModel.d-D9GWPFrL.d.ts → tabsModel.d-B4MSQB57.d.cts} +5 -2
- package/dist/{tabsModel.d-D9GWPFrL.d.cts → tabsModel.d-C8pd-DP3.d.ts} +5 -2
- package/dist/televet/booking/index.cjs +147 -145
- package/dist/televet/booking/index.d.cts +10 -10
- package/dist/televet/booking/index.d.ts +10 -10
- package/dist/televet/booking/index.js +163 -161
- package/dist/televet/call/index.cjs +52 -52
- package/dist/televet/call/index.d.cts +5 -0
- package/dist/televet/call/index.d.ts +5 -0
- package/dist/televet/call/index.js +25 -25
- package/dist/televet/index.d.cts +3 -3
- package/dist/televet/index.d.ts +3 -3
- package/dist/{televetGlobal.d-gZrXPaLl.d.cts → televetGlobal.d-B_I_fy7O.d.cts} +9 -0
- package/dist/{televetGlobal.d-DkJkV55Y.d.ts → televetGlobal.d-DN7o45WJ.d.ts} +9 -0
- package/dist/testing/index.cjs +3 -3
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +3 -3
- package/dist/testing/rn/index.d.cts +9 -9
- package/dist/testing/rn/index.d.ts +9 -9
- package/dist/testing/web/index.d.cts +9 -9
- package/dist/testing/web/index.d.ts +9 -9
- package/dist/texting/index.cjs +32 -27
- package/dist/texting/index.d.cts +5 -5
- package/dist/texting/index.d.ts +5 -5
- package/dist/texting/index.js +52 -47
- package/dist/{threadOptions.d-NSlFx-Lp.d.ts → threadOptions.d-D_3hk79R.d.ts} +5 -5
- package/dist/{threadOptions.d-Dc57dm7h.d.cts → threadOptions.d-D_GU6lp9.d.cts} +5 -5
- package/dist/{timelineRows.d-CthNM5hV.d.ts → timelineRows.d-BbVuARtc.d.ts} +1 -1
- package/dist/{timelineRows.d-7w8NsNi4.d.cts → timelineRows.d-BiLAAbYl.d.cts} +1 -1
- package/dist/{typeStyle.d-8mcLhtbH.d.ts → typeStyle.d-DSk99BuZ.d.ts} +1 -1
- package/dist/{typeStyle.d-CLrQZW-r.d.cts → typeStyle.d-DqR6mWCF.d.cts} +1 -1
- package/dist/{useHealthPlanSubscription.d-CV7M21HS.d.ts → useHealthPlanSubscription.d-CpE6l1VW.d.ts} +3 -3
- package/dist/{useHealthPlanSubscription.d-SA9-SuKe.d.cts → useHealthPlanSubscription.d-DRiWDJXq.d.cts} +3 -3
- package/dist/{useInboxUnread.d-0DrQPn7J.d.ts → useInboxUnread.d-BV7PkWDH.d.ts} +1 -1
- package/dist/{useInboxUnread.d-CRcOTkmu.d.cts → useInboxUnread.d-CElyXBkY.d.cts} +1 -1
- package/dist/{usePresentation.d-BJzFicRQ.d.cts → usePresentation.d-BcazazQH.d.cts} +3 -3
- package/dist/{usePresentation.d-DgSGIWS-.d.ts → usePresentation.d-CMOypLlH.d.ts} +3 -3
- package/dist/{useRecordsDepth.d-ZX2rhcUx.d.ts → useRecordsDepth.d-Bka4KQhq.d.ts} +1 -1
- package/dist/{useRecordsDepth.d-C9W45gwS.d.cts → useRecordsDepth.d-TgmpxKdX.d.cts} +1 -1
- package/dist/{useUnread.d-4SbFChbd.d.ts → useUnread.d-CGqaP-dB.d.ts} +27 -5
- package/dist/{useUnread.d-B0YhhR_D.d.cts → useUnread.d-DVVnYNPU.d.cts} +27 -5
- package/dist/{view.d-3lxzyJlL.d.cts → view.d-CwruYhQy.d.cts} +3 -3
- package/dist/{view.d-DRiYNQJ8.d.ts → view.d-DamH8TQF.d.ts} +3 -3
- package/dist/web/consent/index.d.cts +5 -5
- package/dist/web/consent/index.d.ts +5 -5
- package/dist/web/health-plan/index.cjs +9 -8
- package/dist/web/health-plan/index.d.cts +16 -16
- package/dist/web/health-plan/index.d.ts +16 -16
- package/dist/web/health-plan/index.js +49 -48
- package/dist/web/inbox/index.d.cts +7 -7
- package/dist/web/inbox/index.d.ts +7 -7
- package/dist/web/index.cjs +185 -184
- package/dist/web/index.d.cts +32 -32
- package/dist/web/index.d.ts +32 -32
- package/dist/web/index.js +179 -178
- package/dist/web/intro/index.d.cts +7 -7
- package/dist/web/intro/index.d.ts +7 -7
- package/dist/web/notifications/index.d.cts +6 -6
- package/dist/web/notifications/index.d.ts +6 -6
- package/dist/web/records/depth/index.d.cts +9 -9
- package/dist/web/records/depth/index.d.ts +9 -9
- package/dist/web/records/index.d.cts +11 -11
- package/dist/web/records/index.d.ts +11 -11
- package/dist/web/records-sheet/index.cjs +111 -110
- package/dist/web/records-sheet/index.js +111 -110
- package/dist/web/shop/index.cjs +1 -1
- package/dist/web/shop/index.d.cts +3 -3
- package/dist/web/shop/index.d.ts +3 -3
- package/dist/web/shop/index.js +1 -1
- package/dist/web/televet/booking/index.cjs +3 -3
- package/dist/web/televet/booking/index.d.cts +10 -10
- package/dist/web/televet/booking/index.d.ts +10 -10
- package/dist/web/televet/booking/index.js +69 -69
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/televet/index.d.cts +3 -3
- package/dist/web/televet/index.d.ts +3 -3
- package/dist/web/texting/index.cjs +34 -29
- package/dist/web/texting/index.d.cts +5 -5
- package/dist/web/texting/index.d.ts +5 -5
- package/dist/web/texting/index.js +45 -40
- package/dist/web/ui/index.cjs +1 -1
- package/dist/web/ui/index.js +41 -41
- package/package.json +16 -1
- package/tabs-bar/package.json +8 -0
package/dist/index.cjs
CHANGED
|
@@ -1,387 +1,388 @@
|
|
|
1
1
|
/*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
|
|
2
|
-
"use strict";var e=require("zod"),t=require("react"),r=require("react-native"),n=require("react-native-safe-area-context"),
|
|
2
|
+
"use strict";var e=require("zod"),t=require("react"),r=require("react-native"),n=require("react-native-safe-area-context"),l=require("react-native-sse"),i=require("react/jsx-runtime"),o=require("@everfur/sdk/televet/booking"),s=require("@everfur/sdk/texting");function a(e){return e&&e.__esModule?e:{default:e}}function u(e){if(e&&e.__esModule)return e;var t=Object.create(null);if(e){Object.keys(e).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:true,get:function(){return e[r]}})}})}t.default=e;return Object.freeze(t)}var c=/*#__PURE__*/u(r);var d=/*#__PURE__*/a(l);var f=/*#__PURE__*/u(o);var h=/*#__PURE__*/u(s);function p(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(!(r>=56320&&r<=57343))return true;t+=1}else if(r>=56320&&r<=57343)return true}return false}function g(e){return[...e].length}function ok(e,t){/* @__PURE__ */
|
|
3
3
|
return Object.freeze({ok:true,value:e})}function err(e){/* @__PURE__ */
|
|
4
|
-
return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var m=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new m(e.error)}var b=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var y=128,v=128,x=/[\u0000-\u001F\u007F]/,w=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=g(t);if(r===0||r>v)throw new b("invalid-argument",`petRef must be 1..${v} characters`);if(x.test(t))throw new b("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=g(t);if(r===0||r>y)throw new b("invalid-argument",`userRef must be 1..${y} characters`);if(t.includes("@"))throw new b("invalid-argument","userRef must not contain '@'");if(x.test(t))throw new b("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!w.test(e))throw new b("invalid-argument","conversationId must be a UUID");return e}var k=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],C=/* @__PURE__ */Object.freeze(k.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(C.map(e=>e.wireCode));var S=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),j=/* @__PURE__ */Object.freeze(C.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:S[e.wireCode]}))),_=new Map(j.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),R=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(j.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...R]){let t=_.get(e+r);if(t)return t}}var T=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(e){return T[e]}function fromWire(e){let t=contractErrorFor(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return"authRejected";if(r.startsWith("AUTH"))return"authExpired";switch(n){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}var I=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return I.has(e)}var z=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||z.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var P=500,E=8e3,O=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(P*2**r,E);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var A="This feature isn't available on your account right now.",M="Something in that request was not right. Check the details and try again.",F=/* @__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:A,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:M,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:A,runtimeDisposed:M,unknown:"Something went wrong. Please try again."}),D="This session has ended. Please sign in again.",L="linked_account_read_only";function B(e,t,r){return e==="conflict"&&r===L?A:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?D:userFacingError(e)}function userFacingError(e){return F[e]}function V(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var H=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===L,i={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:B(e,t?.wireCode,n?L:null)};t?.httpStatus!==void 0&&(i.httpStatus=t.httpStatus),t?.requestId&&(i.requestId=t.requestId),typeof t?.reasonCode=="string"&&H.test(t.reasonCode)&&(i.reasonCode=t.reasonCode);let l=t?.retryAfterSeconds;if(typeof l=="number"&&Number.isFinite(l)&&l>=0&&(i.retryAfterSeconds=Math.round(l)),r);return t?.wireMessage&&V(i,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&V(i,"raw",t.raw),/* @__PURE__ */Object.freeze(i)}var U=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function N(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return G(e)}var $=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,W=/[\s\u0000-\u001f\u007f\\]/,q={"http:":"80","https:":"443"};function G(e,t){let r=e.trim();let n=W.test(r)?null:$.exec(r);if(n===null)return null;let[,i="",l="",o="",s="",a="",u="",c="",d=""]=n,f=`${i.toLowerCase()}:`,h=Number(a);if(h>65535)return null;let p=a===""||String(h)===q[f]?"":String(h),g=q[f]!==void 0,m=s.toLowerCase()+(p&&`:${p}`),b=u||(g?"/":""),y=l||o?`${l}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${m}${b}${c}${d}`,protocol:f,username:l,password:o,hostname:s.toLowerCase(),port:p,origin:g?`${f}//${m}`:"null",pathname:b,search:c==="?"?"":c,hash:d==="#"?"":d}}var K="application/pdf",Y=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Q=e=>Y.includes(e);function Z(e,t){return e===K||t!==void 0&&Q(e)&&t.includes(e)}var X=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function J(e){return Z(e,Y)?X[e]:X["application/pdf"]}var ee="file",te="multipart upload failed";function re(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(ee,e.file)}catch{return Promise.reject(new Error(te))}return e.fetch!==void 0?le(e.fetch,e.url,t,e.signal):ie(e.url,t,e.signal)}function ne(e){return e>=200&&e<300}function ie(e,t,r){return new Promise((n,i)=>{let l=globalThis.XMLHttpRequest;if(typeof l!="function"||r?.aborted===true){i(new Error(te));return}let o=null,s=()=>{o!==null&&r?.removeEventListener("abort",o)},a=()=>{s(),i(new Error(te))};try{let i=new l;i.open("POST",e),i.withCredentials=!1,i.onload=()=>{s(),n(ne(i.status))},i.onerror=a,i.ontimeout=a,i.onabort=a,r!==void 0&&(o=()=>{try{i.abort()}finally{a()}},r.addEventListener("abort",o,{once:!0})),i.send(t)}catch{a()}})}function le(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var oe="records upload: the file handle has no uri",se="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
|
|
5
|
-
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(oe));let{signal:
|
|
4
|
+
return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var m=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new m(e.error)}var b=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var y=128,v=128,x=/[\u0000-\u001F\u007F]/,w=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=g(t);if(r===0||r>v)throw new b("invalid-argument",`petRef must be 1..${v} characters`);if(x.test(t))throw new b("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=g(t);if(r===0||r>y)throw new b("invalid-argument",`userRef must be 1..${y} characters`);if(t.includes("@"))throw new b("invalid-argument","userRef must not contain '@'");if(x.test(t))throw new b("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!w.test(e))throw new b("invalid-argument","conversationId must be a UUID");return e}var k=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],C=/* @__PURE__ */Object.freeze(k.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(C.map(e=>e.wireCode));var S=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),j=/* @__PURE__ */Object.freeze(C.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:S[e.wireCode]}))),_=new Map(j.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),R=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(j.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...R]){let t=_.get(e+r);if(t)return t}}var T=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(e){return T[e]}function fromWire(e){let t=contractErrorFor(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return"authRejected";if(r.startsWith("AUTH"))return"authExpired";switch(n){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}var I=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return I.has(e)}var z=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||z.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var P=500,E=8e3,O=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(P*2**r,E);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var A="This feature isn't available on your account right now.",M="Something in that request was not right. Check the details and try again.",F=/* @__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:A,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:M,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:A,runtimeDisposed:M,unknown:"Something went wrong. Please try again."}),D="This session has ended. Please sign in again.",L="linked_account_read_only";function B(e,t,r){return e==="conflict"&&r===L?A:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?D:userFacingError(e)}function userFacingError(e){return F[e]}function V(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var H=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===L,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:B(e,t?.wireCode,n?L:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&H.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&V(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&V(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}var U=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function N(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return G(e)}var $=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,W=/[\s\u0000-\u001f\u007f\\]/,q={"http:":"80","https:":"443"};function G(e,t){let r=e.trim();let n=W.test(r)?null:$.exec(r);if(n===null)return null;let[,l="",i="",o="",s="",a="",u="",c="",d=""]=n,f=`${l.toLowerCase()}:`,h=Number(a);if(h>65535)return null;let p=a===""||String(h)===q[f]?"":String(h),g=q[f]!==void 0,m=s.toLowerCase()+(p&&`:${p}`),b=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${m}${b}${c}${d}`,protocol:f,username:i,password:o,hostname:s.toLowerCase(),port:p,origin:g?`${f}//${m}`:"null",pathname:b,search:c==="?"?"":c,hash:d==="#"?"":d}}var K="application/pdf",Y=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),Q=e=>Y.includes(e);function Z(e,t){return e===K||t!==void 0&&Q(e)&&t.includes(e)}var X=/* @__PURE__ */Object.freeze({"application/pdf":"document.pdf","image/jpeg":"document.jpg","image/png":"document.png","image/heic":"document.heic","image/heif":"document.heif"});function J(e){return Z(e,Y)?X[e]:X["application/pdf"]}var ee="file",te="multipart upload failed";function re(e){let t;try{t=new FormData;for(let[r,n]of Object.entries(e.fields))t.append(r,n);t.append(ee,e.file)}catch{return Promise.reject(new Error(te))}return e.fetch!==void 0?ie(e.fetch,e.url,t,e.signal):le(e.url,t,e.signal)}function ne(e){return e>=200&&e<300}function le(e,t,r){return new Promise((n,l)=>{let i=globalThis.XMLHttpRequest;if(typeof i!="function"||r?.aborted===true){l(new Error(te));return}let o=null,s=()=>{o!==null&&r?.removeEventListener("abort",o)},a=()=>{s(),l(new Error(te))};try{let l=new i;l.open("POST",e),l.withCredentials=!1,l.onload=()=>{s(),n(ne(l.status))},l.onerror=a,l.ontimeout=a,l.onabort=a,r!==void 0&&(o=()=>{try{l.abort()}finally{a()}},r.addEventListener("abort",o,{once:!0})),l.send(t)}catch{a()}})}function ie(e,t,r,n){return Promise.resolve().then(()=>e(t,{method:"POST",body:r,credentials:"omit",...n?{signal:n}:{}})).then(e=>e.ok)}var oe="records upload: the file handle has no uri",se="records upload failed";function createRnRecordsUploadTransport(e={}){/* @__PURE__ */
|
|
5
|
+
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(oe));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(se));return l?.aborted===true?o():re({url:t.upload_url,fields:t.upload_fields,file:{uri:r.uri,name:J(r.mimeType),type:ae(r.mimeType)},signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}function ae(e){return Z(e,Y)?e:"application/pdf"}var ue=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});var ce=/* @__PURE__ */Object.freeze({shouldRetry(e,t){return isAutoRetryable(e)&&t<O},maxAttempts(){return O}});var de=/* @__PURE__ */Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function optionalModule(e,t,r){let n;try{n=t()}catch(t){return he(`optional peer '${e}' is not installed: ${pe(t)}`)}let l=fe(n);return l==null?he(`optional peer '${e}' resolved to no module`):r&&!r(l)?he(`optional peer '${e}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:l})}function fe(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}function he(e){/* @__PURE__ */
|
|
6
6
|
return Object.freeze({available:false,module:null,reason:e})}function pe(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}function assertNever(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}function acceptedFrame(e,t,r=null){/* @__PURE__ */
|
|
7
7
|
return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}function heartbeatFrame(e,t=null){/* @__PURE__ */
|
|
8
8
|
return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}function deltaFrame(e,t,r=null){/* @__PURE__ */
|
|
9
9
|
return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}function doneFrame(e,t=null){/* @__PURE__ */
|
|
10
|
-
return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:/* @__PURE__ */Object.freeze([...e.followUpQuestions]),citations:/* @__PURE__ */Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}function errorFrame(e){/* @__PURE__ */
|
|
10
|
+
return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:/* @__PURE__ */Object.freeze([...e.followUpQuestions]),citations:/* @__PURE__ */Object.freeze([...e.citations]),recordCitations:/* @__PURE__ */Object.freeze([...e.recordCitations??[]]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}function errorFrame(e){/* @__PURE__ */
|
|
11
11
|
return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null,...e.freeCap?{freeCap:/* @__PURE__ */Object.freeze({...e.freeCap})}:{}})}function analysisStartedFrame(e,t,r=null){/* @__PURE__ */
|
|
12
12
|
return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}function analysisCompleteFrame(e,t=null){/* @__PURE__ */
|
|
13
13
|
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:/* @__PURE__ */Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}function unknownFrame(e,t,r=null){/* @__PURE__ */
|
|
14
|
-
return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var ge="/widget/v1/anon-identity",me="x-everfur-anon-token",be="anonTokenInvalid";function ye(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let
|
|
15
|
-
return Object.freeze({limit:
|
|
14
|
+
return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var ge="/widget/v1/anon-identity",me="x-everfur-anon-token",be="anonTokenInvalid";function ye(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let l=null,i=null,o=null,s=null,a=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>l!==null&&(l.ttlMs===null||a(l.mintedAtMs)<l.ttlMs-2592e5),d=()=>l!==null&&(l.ttlMs===null||a(l.mintedAtMs)<l.ttlMs)?l.token:null,f=()=>i||(i=(async()=>{try{let i=null,s={method:"POST",path:ge,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{i=e("date")}},a=await e.request(s),u=a.ok?a.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(o=n(),d()):(l={token:c,mintedAtMs:n(),ttlMs:ye(u?.expires_at,i)},o=null,c)}catch{return o=n(),d()}finally{i=null}})(),i);return{token(e){return e?.forceRefresh?i||(u(s,3e4)?Promise.resolve(l?.token??null):(s=n(),l=null,f())):c()||u(o,3e5)?Promise.resolve(d()):f()}}}async function ve(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function xe(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(e,t,r,n){let l=null,i=false,o=null,s=false,a=()=>o||(o=(async()=>{try{let e=await t(),n=typeof e=="string"?e:e?.token;if(typeof n!="string"||n.length===0)throw new b("invalid-argument","TokenProvider returned an empty token");return l=n,i=!1,r?.(typeof e=="string"?null:we(e.expiresAt)),n}finally{o=null}})(),o);return{userRef:e,async currentToken(e){if(s)throw new b("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(l=null),l!==null?l:a()},hasToken(){return!s&&l!==null},clear(){s=true,l=null},reportRejected(){s||i||(i=true,n?.())}}}function we(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[me]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...ke(e.headers),...authHeaders(t)}}}function ke(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===me||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await ve(t),n=await t.transport.request(withAuthHeaders(e,Ce(t,r)));if(n.ok||je(n.error.raw)!==be||t.anonIdentity===void 0||t.userRef!==null)return n;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===r?n:t.transport.request(withAuthHeaders(e,Ce(t,l)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(xe(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(xe(e,{wireCode:je(n.error.raw),requestId:n.error.requestId}))}let i=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!i.ok&&i.error.httpStatus===401?(t.identity.reportRejected?.(),err(Se(i.error))):i}function Ce(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function Se(e){let t=e.raw,r=je(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function je(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var _e="DAILY_QUOTA_EXCEEDED",Re=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function Te(e,t){if(!Re.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?_e:e}var Ie="free_cap_reached";function ze(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function Pe(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==Ie&&n.code!==Ie)return null;let l=ze(n.limit),i=ze(n.used);if(l===null||i===null)return null;let o=n.resets_at,s=n.emergency_guidance;/* @__PURE__ */
|
|
15
|
+
return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof s=="string"&&s.trim().length>0?{emergencyGuidance:s}:{}})}function Ee(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:Pe(t)}function Oe(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,s=128,a=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(s=160),t===237&&(a=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(s=144),t===244&&(a=143);else{i+="�",o+=1;continue}let c=1,d=true;for(;c<=r&&!(o+c>=l.length);){let e=l[o+c],t=c===1?s:128,r=c===1?a:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){i+="�",o+=c;continue}if(c<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function Ae(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):Oe()}var Me=`\n\n`,Fe=1048576,De=/* @__PURE__ */e.z.record(/* @__PURE__ */e.z.string(),/* @__PURE__ */e.z.unknown()),Le=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=Ae(),i="",o=0,s=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(Me,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+Me.length),o=0;let r=Be(t,n());if(r!==null&&(r.kind==="delta"&&(s=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>Fe){yield errorFrame({code:s?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=Be(i,n());if(e!==null&&(e.kind==="delta"&&(s=true),yield e,e.terminal))return}yield errorFrame({code:s?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function Be(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=De.safeParse(l);return i.success?Ve(i.data,r,t):null}function Ve(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:He(e.code)??"unknown",retryable:e.retryable===true,wireMessage:He(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:Pe(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:He(e.conversation_id)??"",messageId:He(e.message_id),title:He(e.title),followUpQuestions:We(e.follow_up_questions),citations:Ge(e.citations),recordCitations:Ge(e.record_citations),citationStatus:He(e.citation_status),urgencyLevel:Ne(e.urgency_level),urgencyReason:He(e.urgency_reason),urgencyProvided:$e(e),resultId:He(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(He(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=He(e.delta)??He(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(He(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:He(e.result_id),analysisType:He(e.analysis_type),modelVersion:He(e.model_version),confidence:Ue(e.confidence),detections:Ge(e.detections),interpretation:He(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function He(e){return typeof e=="string"?e:null}function Ue(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Ne(e){return typeof e=="string"&&Le.includes(e)?e:null}function $e(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Ne(t)!==null}function We(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e){return Array.isArray(e)?e.filter(qe):[]}function Ke(e,t,r){return{...e,surface:t,requestId:r||null}}var Ye=64,Qe=/^[A-Za-z0-9._+() -]+$/;function Ze(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Ye?null:Qe.test(t)?t:null}var Xe="1.7.0";var Je="react-native",et="2026-09-19",tt="EVERFUR_API_BASE_URL";function rt(e,t){/* @__PURE__ */
|
|
16
16
|
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:e,message:t})})}function checkPublishableKey(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{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(e,t){let r=checkPublishableKey(e?.publishableKey);if(r!==null)/* @__PURE__ */
|
|
17
|
-
return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),
|
|
18
|
-
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:
|
|
19
|
-
return Object.freeze({ok:true,value:o})}function at(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function ut(e){let t=globalThis.process?.env?.[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function ct(e,t){if(e.status!==429&&e.status!==503)return t;let r=ft(e.headers.get(dt),Date.now());if(r===null)return t;let n=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null;return n!==null&&ht(n)?t:{...n??{},retry_after_seconds:r}}var dt="retry-after";function ft(e,t){if(e===null)return null;let r=e.trim();if(/^\d+$/.test(r))return Number(r);let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):null}function ht(e){return[e,e.error,e.detail].some(e=>e!==null&&typeof e=="object"&&("retry_after_seconds"in e||"resets_at"in e))}var pt=3e4,gt="x-request-id";async function*fetchByteSource(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:e,value:r}=await t.read();if(e)break;r&&r.length>0&&(yield r)}}finally{await(t.cancel?.())}}function eventSourceByteSource(e){let t=new TextEncoder,r=bt(),n=false,
|
|
17
|
+
return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),l=tryResolveApiBaseUrl(e.apiBaseUrl);if(!l.ok)return l;let i=e.contractVersion?.trim()||et,o=Ze(e.appVersion);/* @__PURE__ */
|
|
18
|
+
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:l.value,contractVersion:i,sdkVersion:Xe,platform:t?.platform??Je,debug:e.debug===true,...o!==null?{appVersion:o}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:ut(tt);return r?st(r):rt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${tt}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function nt(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function lt(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function it(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:lt(t)}function ot(e,t){return`${e}://${t}`}function st(e){let t=e.trim(),r=U.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return rt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),l=nt(r[2]);if(l.length===0)return rt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let i=it(t,l)?`: ${ot(n,l)}`:"";if(n!=="https"){if(!(n==="http"&&at(l)))return n==="http"?rt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${i}`):rt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${i}`)}let o=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
|
|
19
|
+
return Object.freeze({ok:true,value:o})}function at(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function ut(e){let t=globalThis.process?.env?.[e];return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function ct(e,t){if(e.status!==429&&e.status!==503)return t;let r=ft(e.headers.get(dt),Date.now());if(r===null)return t;let n=t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null;return n!==null&&ht(n)?t:{...n??{},retry_after_seconds:r}}var dt="retry-after";function ft(e,t){if(e===null)return null;let r=e.trim();if(/^\d+$/.test(r))return Number(r);let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):null}function ht(e){return[e,e.error,e.detail].some(e=>e!==null&&typeof e=="object"&&("retry_after_seconds"in e||"resets_at"in e))}var pt=3e4,gt="x-request-id";async function*fetchByteSource(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:e,value:r}=await t.read();if(e)break;r&&r.length>0&&(yield r)}}finally{await(t.cancel?.())}}function eventSourceByteSource(e){let t=new TextEncoder,r=bt(),n=false,l=e=>{let n="";e.lastEventId&&(n+=`id: ${e.lastEventId}\n`);let l=e.data??"";for(let e of l.split(`\n`))n+=`data: ${e}\n`;n+=`\n`,r.push(t.encode(n))},i=()=>{s(),r.end()},o=e=>{let n=typeof e.xhrStatus=="number"?e.xhrStatus:0;if(n>=400){let l=Ct(e.message);if(l!==null){let e={type:"error",code:Ie,retryable:false,limit:l.limit,used:l.used,resets_at:l.resetsAt,emergency_guidance:l.emergencyGuidance};r.push(t.encode(`data: ${JSON.stringify(e)}\n\n`))}else{let e=wt(n),l=isAutoRetryable(fromWire(e));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:e,retryable:l})}\n\n`))}}s(),r.end()};e.addEventListener("message",l),e.addEventListener("done",i),e.addEventListener("error",o);function s(){if(!n){n=true,e.removeEventListener("message",l),e.removeEventListener("done",i),e.removeEventListener("error",o);try{e.close()}catch{}}}return mt(r.source,s)}async function*mt(e,t){try{yield*e}finally{t()}}function bt(){let e=[],t=false,r=null,n=()=>{if(r){let e=r;r=null,e()}};async function*l(){for(;;){let n=e.shift();if(n!==void 0){yield n;continue}if(t)return;await new Promise(e=>{r=e})}}return{source:l(),push:t=>{e.push(t),n()},end:()=>{t=true,n()}}}async function requestJson(e,t){let r=t.fetchImpl??getGlobalFetch(),n=St(t.config.apiBaseUrl,e.path,e.query),l=jt(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),i=Tt(pt),o=It(i.signal,e.signal),s;try{s=await r(n,_t({...e,signal:o},l))}catch(e){return err(networkError(e))}finally{i.cancel()}if(e.onResponseHeaders)try{e.onResponseHeaders(e=>s.headers.get(e))}catch{}if(e.rawText&&s.ok)try{return ok(Number(s.headers.get("content-length"))>e.rawText?null:await s.text())}catch(e){return err(networkError(e))}let a=await zt(s);return s.ok?ok(a):err(errorFromResponse(s.status,ct(s,a),requestIdOf(s)))}function createHttpTransport(e){return{request:t=>requestJson(t,e),stream:(t,r)=>yt(Rt(t,r),e)}}async function*yt(e,t){let r=St(t.config.apiBaseUrl,e.path,e.query),n=jt(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,vt(e,n));yield*parseSse(eventSourceByteSource(l),()=>eventSourceRequestId(l));return}let l=t.fetchImpl??getGlobalFetch(),i;try{i=await l(r,_t(e,n))}catch(e){yield kt("",true,Mt(e));return}let o=requestIdOf(i);if(!i.ok){let e=await zt(i),t=Et(e)??wt(i.status),r=At(e)||isAutoRetryable(fromWire(t));yield kt(t,r,Ot(e),o,Pe(e));return}if(i.body){yield*parseSse(fetchByteSource(i.body),o);return}yield*parseSse(fetchByteSource(null),o)}function vt(e,t){return{method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}function errorFromResponse(e,t,r){let n=Et(t),l=n?fromWire(n):fromHttpStatus(e),i=Ot(t);return makeEverfurError(l,{httpStatus:e,...At(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Pt(t)?{reasonCode:Pt(t)}:{},...xt(t)!==null?{retryAfterSeconds:xt(t)}:{},...i?{wireMessage:i}:{},...t!=null?{raw:t}:{}})}function xt(e){let t=e,r=t?.retry_after_seconds??t?.error?.retry_after_seconds;return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:null}function networkError(e){return makeEverfurError("internalError",{retryable:true,wireMessage:Mt(e)})}function requestIdOf(e){let t=e.headers.get(gt);return typeof t=="string"&&t.length>0?t:null}function eventSourceRequestId(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(gt)}catch{return null}return typeof t=="string"&&t.length>0?t:null}function wt(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}function kt(e,t,r,n=null,l=null){return errorFrame({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n,freeCap:l})}function Ct(e){if(typeof e!="string"||e.length===0)return null;try{return Pe(JSON.parse(e))}catch{return null}}function getGlobalFetch(){let e=globalThis.fetch;if(typeof e!="function")throw new b("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}function St(e,t,r){let n=t.startsWith("/")?t:`/${t}`,l=`${e}${n}`;if(r){let e=Object.entries(r).filter(e=>e[1]!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");e&&(l+=`?${e}`)}return l}function jt(e,t,r,n){let l={...buildBaseHeaders(e),accept:r};return n&&(l["content-type"]="application/json"),t&&Object.assign(l,t),l}function _t(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}function Rt(e,t){return e.signal?e:{...e,signal:t}}function Tt(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(r)}}function It(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}async function zt(e){try{return await e.json()}catch{return null}}function Pt(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}function Et(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?Te(r,e):Pe(e)!==null?Ie:null}function Ot(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}function At(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}function Mt(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var Ft=3e4,Dt=E*2,Lt="idempotency-key",Bt=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),Vt=/* @__PURE__ */Object.freeze({onEvent(){}}),Ht=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function Ut(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}function createRequestFunnel(e){let t=e.observer??Vt,r=e.timers??Ht,n=e.rng??Math.random,l=e.sleep??((e,t)=>lr(e,r,t)),i=e.maxAttempts??O,o=e.unaryTimeoutMs??Ft,s=e.newIdempotencyKey??$t(),a=e=>{try{t.onEvent(e)}catch{}};async function u(t,u,c){let d=c?.maxAttempts,f=Math.max(1,d??i),h=c?.idempotent??Bt.has(u.method),p=c?.idempotencyKey===void 0?null:Ut(c.idempotencyKey),g=h?p??s():null,m=Nt(u,g),b=0;for(;;){let i=e=>/* @__PURE__ */Object.freeze({call:t,method:u.method,path:u.path,attempt:b,...g?{idempotencyKey:g}:{},...e});a(i({phase:"attempt"}));let s=rr(o,r),c=nr(s.signal,u.signal),h;try{h=await authedSend({...m,signal:c.signal},e.auth)}catch(e){h=err(networkError(e))}finally{c.dispose(),s.cancel()}if(h.ok)return a(i({phase:"settled",ok:true,reason:"ok"})),h;let p=h.error,y=qt(p,b,{maxAttempts:f,rng:n,now:r.now(),aborted:u.signal?.aborted===true,...d!==void 0?{perCallMaxAttempts:d}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),v={ok:false,code:p.code,reason:y.reason,...p.httpStatus!==void 0?{httpStatus:p.httpStatus}:{},...p.requestId!==void 0?{requestId:p.requestId}:{}};if(!y.retry)return a(i({phase:"settled",...v})),err(p);if(a(i({phase:"retry",...v,delayMs:y.delayMs})),await l(y.delayMs,u.signal),u.signal?.aborted===true)return a(i({phase:"settled",...v,reason:"aborted"})),err(p);b+=1}}async function c(t){return withAuthHeaders(t,await tr(e.auth))}async function*d(t,r,n){a(
|
|
20
20
|
/* @__PURE__ */Object.freeze({call:t,phase:"stream.open",method:r.method,path:r.path,attempt:0}));try{yield*e.auth.transport.stream(r,n)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null})}}/* @__PURE__ */
|
|
21
|
-
return Object.freeze({send:u,authorize:c,stream:d})}function Nt(e,t){let r={};for(let[t,n]of Object.entries(e.headers??{}))t.toLowerCase()!==Lt&&(r[t]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}function $t(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var Wt=10;function qt(e,t,r){if(r.aborted)return{retry:false,reason:"aborted"};let n=Gt(e);if(n==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let
|
|
22
|
-
return Object.freeze({caseId:r,status:n,bodyLocation:cr(t.body_location),lastResponse:
|
|
21
|
+
return Object.freeze({send:u,authorize:c,stream:d})}function Nt(e,t){let r={};for(let[t,n]of Object.entries(e.headers??{}))t.toLowerCase()!==Lt&&(r[t]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}function $t(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var Wt=10;function qt(e,t,r){if(r.aborted)return{retry:false,reason:"aborted"};let n=Gt(e);if(n==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let l=n==="burst"?"burst-throttle":"retryable-code";if((()=>{if(r.policy===void 0)return false;try{return!r.policy.shouldRetry(e.code,t)}catch{return false}})())return{retry:false,reason:"terminal-code"};let i=()=>{if(r.policy===void 0)return null;let t;try{t=r.policy.maxAttempts(e.code)}catch{return null}return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(Wt,Math.floor(t)))},o=r.perCallMaxAttempts??i()??r.maxAttempts;if(t+1>=o)return{retry:false,reason:"attempts-exhausted"};let s=Kt(e,r.now);return s!==null?s>Dt?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:l,delayMs:s}:{retry:true,reason:l,delayMs:backoffDelayMs(t,r.rng)}}function Gt(e){let t=e.code==="unknown"?fromWire(Jt(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}function Kt(e,t){let r=Qt(e.raw);if(r!==null){let e=r-t;return e>0?e:0}let n=Yt(e.raw);return n===null?null:Math.round(n*1e3)}function Yt(e){for(let t of Zt(e)){let e=t.retry_after_seconds;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e}return null}function Qt(e){for(let t of Zt(e)){let e=t.resets_at,r=Xt(e);if(r!==null)return r}return null}function Zt(e){if(!er(e))return[];let t=[e];for(let r of["error","detail"]){let n=e[r];er(n)&&t.push(n)}return t}function Xt(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}function Jt(e){for(let t of Zt(e)){let e=t.code;if(typeof e=="string"&&e.length>0)return e}return null}function er(e){return typeof e=="object"&&e!==null}async function tr(e){if(e.mode==="anonymous"){let t=await ve(e);return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}return{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}function rr(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return{signal:r.signal,cancel:()=>t.clearTimeout(n)}}function nr(e,t){let r=()=>{};if(!t)return{signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let l=()=>n.abort();return e.addEventListener("abort",l,{once:true}),t.addEventListener("abort",l,{once:true}),{signal:n.signal,dispose:()=>{e.removeEventListener("abort",l),t.removeEventListener("abort",l)}}}function lr(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let l=t.setTimeout(()=>{r?.removeEventListener("abort",i),n()},e),i=()=>{t.clearTimeout(l),n()};r?.addEventListener("abort",i,{once:true})})}var ir=/* @__PURE__ */Object.freeze(["better","same","worse"]),or=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function sr(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function ar(){return err(makeEverfurError("internalError",{retryable:false}))}function ur(e){return typeof e!="string"||e.trim().length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):p(e)?makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}var cr=e=>typeof e=="string"?e:null,dr=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function fr(e){if(typeof e!="object"||e===null)return null;let t=e,r=cr(t.case_id),n=cr(t.status);if(r===null||n===null)return null;let l=cr(t.last_response);/* @__PURE__ */
|
|
22
|
+
return Object.freeze({caseId:r,status:n,bodyLocation:cr(t.body_location),lastResponse:l!==null&&ir.includes(l)?l:null,checkInDueAt:cr(t.check_in_due_at),openedAt:cr(t.opened_at),resolvedAt:cr(t.resolved_at),resolutionText:cr(t.resolution_text),checkinAskCount:dr(t.checkin_ask_count),checkinAnswerCount:dr(t.checkin_answer_count)})}function hr(e){return{async list(t,r){let n=ur(t);if(typeof n!="string")return err(n);let l=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!l.ok)return err(l.error);let i=typeof l.value=="object"&&l.value!==null?l.value.cases:null;if(!Array.isArray(i))return ar();let o=i.map(fr);return o.every(e=>e!==null)?ok(/* @__PURE__ */Object.freeze(o)):ar()},async checkin(t,r,n,l){let i=ur(t);if(typeof i!="string")return err(i);if(typeof r!="string"||!or.test(r))return sr("case_id must be a UUID");if(!ir.includes(n))return sr("response must be one of better, same, worse");let o=await e.send("cases.checkin",{method:"POST",path:`${i}/${r}/checkin`,body:{response:n},...l?.signal?{signal:l.signal}:{}});if(!o.ok)return err(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value:{},a=fr(s.case);return a===null?ar():ok(/* @__PURE__ */Object.freeze({case:a,ctaDeepLink:cr(s.cta_deep_link)}))}}}function pr(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}function gr(e,t){let r=t.activeConversationId===null||t.activeConversationId.length===0?null:t.activeConversationId;return r===null&&t.refreshesBlankThread!==true?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:pr(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}var mr=/* @__PURE__ */Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var br=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function yr(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let l={handle:void 0},i=()=>{r.clearTimeout(l.handle),t.removeEventListener("abort",i),n()};l.handle=r.setTimeout(i,e),t.addEventListener("abort",i,{once:true})})}function vr(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=()=>r.abort();return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}var xr=class{constructor(e){this.listeners=/* @__PURE__ */new Set;this.epoch=0;this.inFlight=null;this.snapshot=/* @__PURE__ */Object.freeze({...e})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSnapshot(){return this.snapshot}patch(e){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,...e});for(let e of this.listeners)e()}beginOperation(e){this.inFlight?.abort();let t=new AbortController;this.inFlight=t;let r=this.epoch;return{signal:e?vr(t.signal,e):t.signal,epoch:r,settle:()=>{this.inFlight===t&&(this.inFlight=null)}}}alive(e){return e===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 wr(e,t,r){/* @__PURE__ */
|
|
23
23
|
return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}function kr(e,t,r){/* @__PURE__ */
|
|
24
24
|
return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function Cr(e){/* @__PURE__ */
|
|
25
|
-
return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function Sr(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),/* @__PURE__ */Object.freeze(r)}function jr(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,/* @__PURE__ */Object.freeze(r)}function _r(e){/* @__PURE__ */
|
|
25
|
+
return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function Sr(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),/* @__PURE__ */Object.freeze(r)}function jr(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.recordCitations!==void 0&&t.recordCitations.length>0&&(r.recordCitations=t.recordCitations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,/* @__PURE__ */Object.freeze(r)}function _r(e){/* @__PURE__ */
|
|
26
26
|
return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}function Rr(e,t,r){return makeEverfurError(e,{retryable:t,...r?{wireMessage:r}:{}})}function Tr(e){let t=fromWire(e.code);return makeEverfurError(t,{retryable:e.retryable||shouldRetry(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}function Ir(e){return errorFrame({code:zr(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}function zr(e){switch(e){case"authExpired":return"AUTH_EXPIRED";case"authRejected":return"AuthorizationException";case"sessionRequired":return"session_required";case"accessDenied":return"ACCESS_DENIED";case"paymentRequired":return"TIER_UPGRADE_REQUIRED";case"quotaExceeded":return"QUOTA_EXCEEDED";case"rateLimited":return"RATE_LIMITED";case"validationFailed":return"ValidationException";case"sdkUpdateRequired":return"invalidRequest";case"conflict":return"ConflictException";case"idempotencyConflict":return"IDEMPOTENCY_CONFLICT";case"idempotencyInFlight":return"IDEMPOTENCY_KEY_IN_FLIGHT";case"conversationNotFound":return"CONVERSATION_NOT_FOUND";case"petNotFound":return"PET_NOT_FOUND";case"resourceNotFound":return"ResourceNotFoundException";case"streamTimeout":return"STREAM_TIMEOUT";case"mediaUploadFailed":return"MEDIA_UPLOAD_FAILED";case"moderationBlocked":return"MODERATION_BLOCKED";case"upstreamLlmTimeout":return"UPSTREAM_LLM_TIMEOUT";case"internalError":return"INTERNAL_ERROR";case"notImplemented":return"NotImplementedException";case"serviceUnavailable":return"ServiceUnavailableException";case"streamIncomplete":return"STREAM_INCOMPLETE";case"identitySignatureRequired":return"identitySignatureRequired";case"runtimeDisposed":return"runtimeDisposed";case"unknown":return"UNKNOWN";default:return assertNever(e)}}function Pr(e){let t=Array.isArray(e)?e:Or(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let e of t){if(!Or(e))continue;let t=Ar(e.category)??Ar(e.title)??"",n=Mr(e.prompts??e.questions);t.length===0&&n.length===0||r.push(/* @__PURE__ */Object.freeze({category:t,prompts:/* @__PURE__ */Object.freeze(n)}))}/* @__PURE__ */
|
|
27
|
-
return Object.freeze(r)}function Er(e){let t=/* @__PURE__ */new Set,r=[];for(let n of e)for(let e of n.prompts){let n=e.trim();n.length===0||t.has(n)||(t.add(n),r.push(n))}return r}function Or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ar(e){return typeof e=="string"?e:null}function Mr(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Or(r)){let e=Ar(r.text)??Ar(r.prompt)??Ar(r.title);e!==null&&t.push(e)}return t}function Fr(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Dr(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Lr(){return typeof Symbol=="function"?Symbol.asyncIterator:void 0}function Br(e){let t=e,r=Lr(),n=(r!==void 0?t[r]:void 0)??t["@@asyncIterator"];if(typeof n=="function")return n.call(e);let
|
|
28
|
-
return Object.freeze({conversationId:r,message:c,checkin:a,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==Kr}function Zr(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}function Xr(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,
|
|
29
|
-
return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:
|
|
30
|
-
return Object.freeze(e.flatMap(e=>{let r=rn(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function fn(e,t,r){let n=new Set(e.map(e=>e.id)),i=e.filter(e=>r.has(e.id)),l=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=i.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){i.splice(r,1);continue}l.push(e)}return l}var hn=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),pn=4e3;var gn=4e3;function mn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:Rr("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:Rr("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function bn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:Rr("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>gn?{reason:"too_long",error:Rr("validationFailed",false,`message is ${r} characters; the server accepts at most ${gn}`)}:null}function yn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*vn(e){yield e}async function*xn(){}var wn=6e4,kn=18e4,Cn=24,Sn=512,jn=false;function createChatController(e){return new In(e)}function _n(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function Rn(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function Tn(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var In=class extends xr{constructor(e){super(_r({status:"idle",messages:[],conversationId:e.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.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=hr(this.funnel),this.telemetry=e.telemetry??ue,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??ce,this.timers=e.timers??Vr,this.rng=e.rng??Math.random,this.newId=e.newId??Fr(),this.makeIdempotencyKey=e.makeIdempotencyKey??Dr(),this.budget={idleMs:e.budget?.idleMs??wn,overallMs:e.budget?.overallMs??kn}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=Rr(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):vn(Ir(e))}let i=bn(e)??mn(n.imageS3Keys);if(i!==null)return this.telemetry.track("chat.send.rejected",{reason:i.reason}),this.patch({status:"error",isStreaming:false,error:i.error}),r?(r.onError(i.error),()=>{}):vn(Ir(i.error));if(r)return this.driveWithHandlers(e,n,r);let l=this.beginTurn(e,n);return this.runTurn(l,n.signal)}askEverfur(e,t){if(this.disposed)return vn(Ir(Rr("accessDenied",false)));let r=bn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),vn(Ir(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):xn()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,wr(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?Cr(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(Er(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=en(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let i=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(Rr("accessDenied",false));if(!i.ok)return i;let l=on(i.value);if(l.ok){for(let e of l.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=l.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,l.value.conversations):this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return l}reportCheckinSkips(e){let t=[];e===null&&t.push("no_pet"),this.auth.userRef===null&&t.push("no_member");for(let e of t)this.reportCheckinSkip(e)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(e){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let t=this.epoch,r=e===null?"":`?pet_ref=${encodeURIComponent(String(e))}`,n=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${r}`},void 0,{maxAttempts:1});if(!this.alive(t)||this.disposed)return null;if(this.cardsInFlight=false,n.ok){this.cardsRoute="served";let e=n.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],r=[];for(let e of t){let t=Qr(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),Rn(n.error)?n.error:null;if(n.error.category==="notFound"&&Tn(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let i=Yr(n.value.messages);i===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:i,checkin:i.checkin??null,occasionRef:i.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}_n(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(Rr("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let i=n.value.conversations[0];if(i===void 0)return ok(null);let l=await this.resumeConversation(i.id);return l.ok?ok(i.id):err(l.error)}async markRead(e){if(this.disposed)return err(Rr("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(Rr("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(Rr("accessDenied",false));if(typeof e!="string"||e.trim().length===0||p(e))return err(Rr("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!hn.includes(t))return err(Rr("validationFailed",false,`feedback_type must be one of ${hn.join(", ")}`));let i=typeof r=="string"?r.trim():"";if([...i].length>pn)return err(Rr("validationFailed",false,`notes is over ${pn} characters`));let l={feedback_type:t};i.length>0&&(l.notes=i);let o=this.epoch,s=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:l},n?.signal);if(!this.alive(o)||this.disposed)return err(Rr("accessDenied",false));if(!s.ok)return err(s.error);let a=s.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof a=="string"?a:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(Rr("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(Rr("validationFailed",false,"a check-in needs the pet the case belongs to"));let i=this.epoch,l=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(i)||this.disposed)return err(Rr("accessDenied",false));if(!l.ok)return l;let o=l.value.case.openedAt,s=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null,...o!==null?{openedAt:o}:{}}),a=t=>t.checkin?.caseId===e;this.snapshot.messages.some(a)&&this.patch({messages:this.snapshot.messages.map(e=>a(e)?/* @__PURE__ */Object.freeze({...e,checkin:s}):e)}),this.answeredCases.set(e,s);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:s}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),l}async getMessages(e,t){if(!tn(e))return err(Rr("validationFailed",false));let r=en(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let i=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(Rr("accessDenied",false)):i.ok?sn(i.value):i}async resumeConversation(e){if(this.disposed)return err(Rr("accessDenied",false));if(!tn(e))return err(Rr("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===Kr).map(e=>e.caseId)),i=new Map(r.value.map(e=>[e.caseId,e])),l=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;l=true;let r=i.get(t.caseId),o=t.openedAt??r?.openedAt??null,s=n.has(t.caseId),a=r!==void 0&&(!s||Zr({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
|
|
31
|
-
return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:s?Kr:r?.status??"resolved",answer:t.answer??a,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});l&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(Rr("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),i=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=i===null?null:await i;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let l=await this.resumeConversation(r.id);return l.ok?ok(void 0):err(l.error)}let l=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(!l.ok)return err(l.error);let o=fn(this.snapshot.messages,l.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&Rn(n.error))return err(n.error);let s=i===null?null:await i;return s!==null&&r===this.historyGeneration&&!this.disposed?err(s):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(Rr("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let i=new Set(this.snapshot.messages.map(e=>e.id)),l=n.value.messages.filter(e=>!i.has(e.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield Ir(t.error))}async primeConversation(e){if(this.disposed)return err(Rr("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(Rr("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let i=await n.settled;return!this.alive(t)||this.disposed?err(Rr("accessDenied",false)):(!i.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),i)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let i=n.value?.conversation_id??n.value?.id;return typeof i!="string"||i.length===0?err(Rr("internalError",true)):ok(i)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let r=e?.petRef??null;if(r!==null&&p(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",i=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(Rr("accessDenied",false)):i.ok?ok(Pr(i.value)):err(i.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,i=vr(n.signal,t.signal),l=this.beginTurn(e,t),o=this.runTurn(l,i),s=false,a=()=>{s||(s=true,n.abort(),this.handlerTeardowns.delete(a))};return this.handlerTeardowns.add(a),(async()=>{for await(let e of o){if(s)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!s&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(a)})(),a}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,wr(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,i=false,l=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,s=t?this.unadoptedCreate:null;if(s!==null&&(e.petRef===null||e.petRef===s.petRef)){let e=await s.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,Ir(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let a=e.conversationIdOverride??this.snapshot.conversationId;if(a===null){let t=Rr("internalError",!0);yield*this.emitTerminal(e,t,Ir(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=vr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,a))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,Ir(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[me]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of Hr(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=Rr("streamIncomplete",!0);yield*this.emitTerminal(e,t,Ir(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===be||h==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,Tr(d),d);return}if(canRecreateOnNotFound(h)&&!i){i=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(h,!0);if(jn&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,Tr(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Cr(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,kr(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=Sn){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},Cn)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?Sr(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?jr(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Cr(e):e),jr(kr(r,"",this.stamp()),e)]}let i=Er([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=i.length>0?/* @__PURE__ */Object.freeze(i):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,i=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!l.ok||!this.alive(n)||this.disposed||i!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=yn(l.value?.urgency),s=typeof l.value?.reason=="string"?l.value.reason:null,a=e=>e.responseId===t;this.snapshot.messages.some(a)&&this.patch({messages:this.snapshot.messages.map(e=>a(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:s,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?Cr(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.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(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?Rr("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,i=e.resumeConversationId??null,l=[],o=false,s=false,a=false,u=null,c=null,d=i?r.resumeConversation(i).then(e=>e.ok?ok(i):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[h,p]=await Promise.all([d,f]),g=null;if(h.ok)g=h.value,h.value!==null&&l.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,Pn(e)?(s=true,u=e):(En(e)&&(o=true),a=true)}let m=[];p.ok?m=p.value:b(p.error);function b(e){Pn(e)?(s=true,u===null&&(u=e)):En(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
|
|
32
|
-
return Object.freeze({conversationId:g,petRef:n,suggestedPrompts:m,error:y,warning:y===null&&g===null&&a?
|
|
33
|
-
return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}function attachmentSize(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}function validateAttachment(e){let t=sanitizeFilename(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(r))return
|
|
34
|
-
return Object.freeze({upload_id:
|
|
35
|
-
return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:
|
|
36
|
-
return Object.freeze({petRef:
|
|
37
|
-
return Object.freeze(t.flatMap(e=>{let t=widgetPetFromWire(e);return t===null?[]:[t]}))}function createPetsRepository(e){return
|
|
27
|
+
return Object.freeze(r)}function Er(e){let t=/* @__PURE__ */new Set,r=[];for(let n of e)for(let e of n.prompts){let n=e.trim();n.length===0||t.has(n)||(t.add(n),r.push(n))}return r}function Or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ar(e){return typeof e=="string"?e:null}function Mr(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Or(r)){let e=Ar(r.text)??Ar(r.prompt)??Ar(r.title);e!==null&&t.push(e)}return t}function Fr(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Dr(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Lr(){return typeof Symbol=="function"?Symbol.asyncIterator:void 0}function Br(e){let t=e,r=Lr(),n=(r!==void 0?t[r]:void 0)??t["@@asyncIterator"];if(typeof n=="function")return n.call(e);let l=typeof Symbol=="function"?t[Symbol.iterator]:void 0;if(typeof l=="function"){let t=l.call(e);return{next:()=>Promise.resolve(t.next()),return:e=>Promise.resolve(t.return?.(e)??{done:true,value:void 0})}}return null}var Vr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*Hr(e,t,r,n){let l=Br(e);if(l===null){yield Nr();return}let i=$r(t.overallMs,n),o=$r(t.idleMs,n),s=Wr(r);try{for(;;){if(r.aborted)return;let e=l.next().then(e=>({tag:"next",value:e}),()=>({tag:"streamError"})),n=await Promise.race([e,o.promise.then(()=>({tag:"idle"})),i.promise.then(()=>({tag:"overall"})),s.then(()=>({tag:"abort"}))]);if(n.tag==="abort")return;if(n.tag==="streamError"){if(r.aborted)return;yield Nr();return}if(n.tag==="idle"||n.tag==="overall"){yield Ur();return}let a=n.value;if(a.done||(o.reset(t.idleMs),yield a.value,a.value.terminal))return}}finally{o.cancel(),i.cancel(),Promise.resolve(l.return?.(void 0)).catch(()=>{})}}function Ur(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function Nr(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function $r(e,t){let r=()=>{},n=new Promise(e=>{r=e}),l=t.setTimeout(()=>r(),e);return{promise:n,reset(e){t.clearTimeout(l),l=t.setTimeout(()=>r(),e)},cancel(){t.clearTimeout(l)}}}function Wr(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var qr="checkin",Gr=/^\d{4}-\d{2}-\d{2}$/,Kr="watching";function Yr(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r!==void 0){if(r.role==="user")return null;if(r.role==="assistant"){if(r.checkin!==void 0)return r.checkin.answer!==null||isCheckinSettled(r.checkin)?null:r;if(typeof r.proactiveOriginRef=="string"&&r.proactiveOriginRef.length>0)return r}}}return null}function Qr(e){if(e===null||typeof e!="object")return null;let t=e,r=t.conversation_id,n=t.message_id,l=t.question,i=t.occasion_ref;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0||typeof l!="string"||l.trim().length===0)return null;let o=typeof i=="string"&&i.length>0?i:null,s=Xr(o),a=s===null?null:/* @__PURE__ */Object.freeze({caseId:s.caseId,answer:null,resolutionText:null,status:null}),u=typeof t.created_at=="string"?t.created_at:"",c=/* @__PURE__ */Object.freeze({id:n,role:"assistant",text:l,createdAt:u,...o===null?{}:{proactiveOriginRef:o},...a===null?{}:{checkin:a}});/* @__PURE__ */
|
|
28
|
+
return Object.freeze({conversationId:r,message:c,checkin:a,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==Kr}function Zr(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}function Xr(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,l]=t;return r!==qr||n===void 0||l===void 0||!or.test(n)||!Gr.test(l)?null:{caseId:n,dueDay:l}}function Jr(e){return Xr(e)?.caseId??null}function en(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||p(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function tn(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function rn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function nn(e){return e==null||typeof e=="string"&&e.length>0&&!p(e)}function ln(){return err(makeEverfurError("internalError",{retryable:false}))}function on(e){let t=rn(e);if(!t||!Array.isArray(t.conversations)||!nn(t.next_cursor))return ln();let r=[];for(let e of t.conversations){let t=rn(e);if(!t||typeof t.conversation_id!="string"||!tn(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return ln();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return ln();let l=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...l.length>0?{preview:l}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function sn(e){let t=rn(e);if(!t||!Array.isArray(t.messages)||!nn(t.next_cursor))return ln();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=rn(e);if(!t||typeof t.message_id!="string"||!tn(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return ln();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(an(t,t.message_id,t.content,t.created_at));continue}let l=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,i=t.role==="assistant"?Jr(l):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:cn(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:dn(t.citations)}:{},...t.role==="assistant"&&Array.isArray(t.record_citations)?fn(t.record_citations):{},...l!==null?{proactiveOriginRef:l}:{},...i!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:i,answer:null,resolutionText:null,status:null})}:{},...t.a2ui?{a2ui:[t.a2ui]}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function an(e,t,r,n){let l=rn(e.sender),i=un(l?.display_name)??un(e.sender_display_name),o=un(l?.specialty);/* @__PURE__ */
|
|
29
|
+
return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:i,specialty:o})})}function un(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!p(t)?t:null}function cn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function dn(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
|
|
30
|
+
return Object.freeze(e.flatMap(e=>{let r=rn(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function fn(e){let t=e.flatMap(e=>{let t=rn(e);return t!==null&&typeof t.source_doc_id=="string"?[/* @__PURE__ */Object.freeze({...t})]:[]});return t.length===0?{}:{recordCitations:/* @__PURE__ */Object.freeze(t)}}function hn(e,t,r){let n=new Set(e.map(e=>e.id)),l=e.filter(e=>r.has(e.id)),i=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=l.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){l.splice(r,1);continue}i.push(e)}return i}var pn=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),gn=4e3;var mn=4e3;function bn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:Rr("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:Rr("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function yn(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:Rr("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>mn?{reason:"too_long",error:Rr("validationFailed",false,`message is ${r} characters; the server accepts at most ${mn}`)}:null}function vn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*xn(e){yield e}async function*wn(){}var kn=6e4,Cn=18e4,Sn=24,jn=512,_n=false;function createChatController(e){return new zn(e)}function Rn(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function Tn(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function In(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var zn=class extends xr{constructor(e){super(_r({status:"idle",messages:[],conversationId:e.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.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=hr(this.funnel),this.telemetry=e.telemetry??ue,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??ce,this.timers=e.timers??Vr,this.rng=e.rng??Math.random,this.newId=e.newId??Fr(),this.makeIdempotencyKey=e.makeIdempotencyKey??Dr(),this.budget={idleMs:e.budget?.idleMs??kn,overallMs:e.budget?.overallMs??Cn}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=Rr(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):xn(Ir(e))}let l=yn(e)??bn(n.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),r?(r.onError(l.error),()=>{}):xn(Ir(l.error));if(r)return this.driveWithHandlers(e,n,r);let i=this.beginTurn(e,n);return this.runTurn(i,n.signal)}askEverfur(e,t){if(this.disposed)return xn(Ir(Rr("accessDenied",false)));let r=yn(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),xn(Ir(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):wn()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,wr(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?Cr(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(Er(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=en(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(Rr("accessDenied",false));if(!l.ok)return l;let i=on(l.value);if(i.ok){for(let e of i.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=i.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,i.value.conversations):this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return i}reportCheckinSkips(e){let t=[];e===null&&t.push("no_pet"),this.auth.userRef===null&&t.push("no_member");for(let e of t)this.reportCheckinSkip(e)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(e){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let t=this.epoch,r=e===null?"":`?pet_ref=${encodeURIComponent(String(e))}`,n=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${r}`},void 0,{maxAttempts:1});if(!this.alive(t)||this.disposed)return null;if(this.cardsInFlight=false,n.ok){this.cardsRoute="served";let e=n.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],r=[];for(let e of t){let t=Qr(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),Tn(n.error)?n.error:null;if(n.error.category==="notFound"&&In(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let l=Yr(n.value.messages);l===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:l,checkin:l.checkin??null,occasionRef:l.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}Rn(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(Rr("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let l=n.value.conversations[0];if(l===void 0)return ok(null);let i=await this.resumeConversation(l.id);return i.ok?ok(l.id):err(i.error)}async markRead(e){if(this.disposed)return err(Rr("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(Rr("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(Rr("accessDenied",false));if(typeof e!="string"||e.trim().length===0||p(e))return err(Rr("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!pn.includes(t))return err(Rr("validationFailed",false,`feedback_type must be one of ${pn.join(", ")}`));let l=typeof r=="string"?r.trim():"";if([...l].length>gn)return err(Rr("validationFailed",false,`notes is over ${gn} characters`));let i={feedback_type:t};l.length>0&&(i.notes=l);let o=this.epoch,s=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:i},n?.signal);if(!this.alive(o)||this.disposed)return err(Rr("accessDenied",false));if(!s.ok)return err(s.error);let a=s.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof a=="string"?a:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(Rr("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(Rr("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,i=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(l)||this.disposed)return err(Rr("accessDenied",false));if(!i.ok)return i;let o=i.value.case.openedAt,s=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...o!==null?{openedAt:o}:{}}),a=t=>t.checkin?.caseId===e;this.snapshot.messages.some(a)&&this.patch({messages:this.snapshot.messages.map(e=>a(e)?/* @__PURE__ */Object.freeze({...e,checkin:s}):e)}),this.answeredCases.set(e,s);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:s}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!tn(e))return err(Rr("validationFailed",false));let r=en(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(Rr("accessDenied",false)):l.ok?sn(l.value):l}async resumeConversation(e){if(this.disposed)return err(Rr("accessDenied",false));if(!tn(e))return err(Rr("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===Kr).map(e=>e.caseId)),l=new Map(r.value.map(e=>[e.caseId,e])),i=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let r=l.get(t.caseId),o=t.openedAt??r?.openedAt??null,s=n.has(t.caseId),a=r!==void 0&&(!s||Zr({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
|
|
31
|
+
return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:s?Kr:r?.status??"resolved",answer:t.answer??a,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});i&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(Rr("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),l=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=l===null?null:await l;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let i=await this.resumeConversation(r.id);return i.ok?ok(void 0):err(i.error)}let i=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(!i.ok)return err(i.error);let o=hn(this.snapshot.messages,i.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&Tn(n.error))return err(n.error);let s=l===null?null:await l;return s!==null&&r===this.historyGeneration&&!this.disposed?err(s):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(Rr("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(Rr("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let l=new Set(this.snapshot.messages.map(e=>e.id)),i=n.value.messages.filter(e=>!l.has(e.id));return this.patch({messages:[...i,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield Ir(t.error))}async primeConversation(e){if(this.disposed)return err(Rr("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(Rr("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let l=await n.settled;return!this.alive(t)||this.disposed?err(Rr("accessDenied",false)):(!l.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),l)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let l=n.value?.conversation_id??n.value?.id;return typeof l!="string"||l.length===0?err(Rr("internalError",true)):ok(l)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(Rr("accessDenied",false));let r=e?.petRef??null;if(r!==null&&p(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(Rr("accessDenied",false)):l.ok?ok(Pr(l.value)):err(l.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,l=vr(n.signal,t.signal),i=this.beginTurn(e,t),o=this.runTurn(i,l),s=false,a=()=>{s||(s=true,n.abort(),this.handlerTeardowns.delete(a))};return this.handlerTeardowns.add(a),(async()=>{for await(let e of o){if(s)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!s&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(a)})(),a}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,wr(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,l=false,i=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,s=t?this.unadoptedCreate:null;if(s!==null&&(e.petRef===null||e.petRef===s.petRef)){let e=await s.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,Ir(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let a=e.conversationIdOverride??this.snapshot.conversationId;if(a===null){let t=Rr("internalError",!0);yield*this.emitTerminal(e,t,Ir(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=vr(r.signal,u.signal),d=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,a))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,Ir(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[me]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of Hr(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=Rr("streamIncomplete",!0);yield*this.emitTerminal(e,t,Ir(t));return}let h=fromWire(d.code);if(h==="authExpired"&&this.auth.mode==="personalized"&&!i){i=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===be||h==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(h==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(h==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,Tr(d),d);return}if(canRecreateOnNotFound(h)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(h,!0);if(_n&&p&&n+1<this.errorPolicy.maxAttempts(h));yield*this.emitTerminal(e,Tr(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Cr(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,kr(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=jn){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},Sn)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?Sr(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?jr(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Cr(e):e),jr(kr(r,"",this.stamp()),e)]}let l=Er([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=l.length>0?/* @__PURE__ */Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,l=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!i.ok||!this.alive(n)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=vn(i.value?.urgency),s=typeof i.value?.reason=="string"?i.value.reason:null,a=e=>e.responseId===t;this.snapshot.messages.some(a)&&this.patch({messages:this.snapshot.messages.map(e=>a(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:s,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?Cr(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.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(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?Rr("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,l=e.resumeConversationId??null,i=[],o=false,s=false,a=false,u=null,c=null,d=l?r.resumeConversation(l).then(e=>e.ok?ok(l):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[h,p]=await Promise.all([d,f]),g=null;if(h.ok)g=h.value,h.value!==null&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;c=e,En(e)?(s=true,u=e):(On(e)&&(o=true),a=true)}let m=[];p.ok?m=p.value:b(p.error);function b(e){En(e)?(s=true,u===null&&(u=e)):On(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
|
|
32
|
+
return Object.freeze({conversationId:g,petRef:n,suggestedPrompts:m,error:y,warning:y===null&&g===null&&a?Pn:null,cause:u??c,diagnostics:/* @__PURE__ */Object.freeze({candidateConversationIds:/* @__PURE__ */Object.freeze([...i]),sawForbidden:o,sawUnauthorized:s,sawConversationInitFailure:a})})}var Pn="Chat is ready. Your first message will start the conversation.";function En(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}function On(e){return e.httpStatus===403||e.code==="accessDenied"}var An=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Mn(e){return e!==An}var Fn=/* @__PURE__ */Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]);var Dn=10*1024*1024,Ln=5,Bn=120,Vn="/widget/v1/uploads/initiate";function isAttachmentMime(e){return typeof e=="string"&&Fn.includes(e.trim().toLowerCase())}function sanitizeFilename(e){if(!e)return"attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return"attachment";if(t.length<=Bn)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Bn);let n=t.slice(r);return n.length>=Bn?t.slice(0,Bn):`${t.slice(0,r).slice(0,Bn-n.length)}${n}`}function formatBytes(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}var Hn=e=>/* @__PURE__ */Object.freeze({ok:true,value:e}),Un=e=>/* @__PURE__ */Object.freeze({ok:false,error:e});function Nn(e,t,r,n){/* @__PURE__ */
|
|
33
|
+
return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}function attachmentSize(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}function validateAttachment(e){let t=sanitizeFilename(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!isAttachmentMime(r))return Un(Nn("unsupported_type",false,t));let n=attachmentSize(e);return n===null?Un(Nn("unknown",false,t)):n>Dn?Un(Nn("too_large",false,t,{sizeBytes:n})):Hn(/* @__PURE__ */Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}function $n(e){if(typeof e!="object"||e===null)return null;let t=e,r=e=>typeof e=="string"&&e.length>0?e:null,n=e=>typeof e=="number"&&Number.isFinite(e)?e:null,l=r(t.upload_id),i=r(t.upload_url),o=r(t.s3_key);if(l===null||i===null||o===null)return null;let s={},a=t.upload_fields;if(typeof a=="object"&&a!==null)for(let[e,t]of Object.entries(a))typeof t=="string"&&(s[e]=t);/* @__PURE__ */
|
|
34
|
+
return Object.freeze({upload_id:l,upload_url:i,upload_fields:/* @__PURE__ */Object.freeze(s),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??Dn,s3_key:o,purpose:r(t.purpose)})}function Wn(e,t){let r=e.httpStatus;switch(e.code){case"quotaExceeded":return Nn("quota_exceeded",false,t,{cause:e});case"rateLimited":return Nn("rate_limited",true,t,{cause:e});case"idempotencyConflict":case"idempotencyInFlight":return Nn("idempotency_conflict",true,t,{cause:e});case"validationFailed":return Nn("unsupported_type",false,t,{cause:e});case"serviceUnavailable":case"streamTimeout":return Nn("network",true,t,{cause:e});default:return r===429?Nn("rate_limited",true,t,{cause:e}):r===503?Nn("network",true,t,{cause:e}):r===void 0?Nn("network",true,t,{cause:e}):Nn("server",e.retryable,t,{httpStatus:r,cause:e})}}async function initiateAttachmentUpload(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Vn,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return Un(Wn(n.error,t.filename));let l=$n(n.value);return l===null?Un(Nn("server",false,t.filename)):Hn(l)}async function uploadAttachmentBytes(e,t,r,n){let l=()=>n?.signal?.aborted===true;if(l())return Un(Nn("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),Hn(void 0)}catch{return l()?Un(Nn("cancelled",true,r.filename)):Un(Nn("server",true,r.filename))}}var qn=2,Gn=3,Kn=/* @__PURE__ */Object.freeze([1e3,2e3,4e3]),Yn=0;function Qn(){return Yn+=1,`attachment-${Yn}`}function createAttachmentQueue(e){let t=Math.max(1,e.concurrency??qn),r=Math.max(1,e.maxAttempts??Gn),n=e.backoffMs??Kn,l=Math.max(1,e.maxPerMessage??Ln),i=e.timers??br,o=e.newId??Qn,s=Mn(e.transport),a=/* @__PURE__ */new Map,u=[],c=[],d=/* @__PURE__ */new Set,f=/* @__PURE__ */new Set,h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])}),p=false,g=()=>{h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze(u.flatMap(e=>{let t=a.get(e);return t===void 0?[]:[t.state]}))});for(let e of f)e()},m=(e,t)=>{e.state=/* @__PURE__ */Object.freeze({...e.state,...t}),g()},b=()=>{for(;!p&&d.size<t&&c.length>0;){let e=c.shift(),t=a.get(e);t!==void 0&&(d.add(e),y(t).finally(()=>{d.delete(e),b()}))}},y=async t=>{let{attachment:l}=t;for(;t.attempts<r;){if(p||t.controller.signal.aborted)return;t.attempts+=1;let o=t.controller.signal;m(t,{status:"uploading",error:null,progress:0});let s=await initiateAttachmentUpload(e.funnel,l,{signal:o});if(p||o.aborted)return;let a;if(!s.ok)a=Un(s.error);else{let r=await uploadAttachmentBytes(e.transport,s.value,l,{signal:o,onProgress:e=>{!o.aborted&&t.state.status==="uploading"&&m(t,{progress:Zn(e)})}});if(p||o.aborted)return;a=r.ok?Hn(s.value.s3_key):Un(r.error)}if(a.ok){m(t,{status:"uploaded",s3Key:a.value,error:null,progress:1});return}let u=a.error,c=u.retryable&&t.attempts<r;if(m(t,{status:c?"uploading":"failed",error:u,progress:0}),!c)return;let d=n[Math.min(t.attempts-1,n.length-1)]??0;await yr(d,o,i)}},v=e=>{c.push(e.state.id),b()},x={available:s,subscribe(e){return f.add(e),()=>{f.delete(e)}},getSnapshot:()=>h,get uploading(){return h.attachments.some(e=>e.status==="uploading")},get s3Keys(){return h.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[])},add(e){let t=validateAttachment(e);if(!t.ok)return t;if(p||u.length>=l)return Un(Nn("too_many",false,t.value.filename));let r=o(),n={attachment:t.value,controller:new AbortController,attempts:0,state:/* @__PURE__ */Object.freeze({id:r,filename:t.value.filename,previewUri:e.uri,contentType:t.value.contentType,sizeBytes:t.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return a.set(r,n),u.push(r),g(),v(n),Hn(n.state)},retry(e){let t=a.get(e);t===void 0||p||t.state.status!=="failed"||(t.controller=new AbortController,t.attempts=0,m(t,{status:"uploading",error:null,progress:0,s3Key:null}),v(t))},remove(e){let t=a.get(e);if(t===void 0)return;t.controller.abort(),a.delete(e);let r=u.indexOf(e);r>=0&&u.splice(r,1);let n=c.indexOf(e);n>=0&&c.splice(n,1),g()},clear(){for(let e of[...u])x.remove(e)},dispose(){p=true;for(let e of a.values())e.controller.abort();a.clear(),u.length=0,c.length=0,f.clear(),h=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])})}};return x}function Zn(e){return Number.isNaN(e)||e<0?0:e>1?1:e}var Xn=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Xn,t)?Xn[t]:null}var Jn=50,el=128,tl=120,rl=120,nl=2e3,ll=120,il=80,ol=/* @__PURE__ */new Set(["male","female","unknown"]),sl=/* @__PURE__ */new Set(["day","month","year"]),al=/* @__PURE__ */new Set(["low","medium","high","athletic"]),ul=/* @__PURE__ */new Set(["indoor","outdoor","both"]),cl=/* @__PURE__ */new Set(["mild","moderate","severe"]),dl=/^(\d{4})-(\d{2})-(\d{2})$/,fl=[["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"]],hl=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...fl,...hl].map(([e])=>e));function pl(e){let t=dl.exec(e);if(t===null)return false;let[r,n,l]=[Number(t[1]),Number(t[2]),Number(t[3])],i=new Date(Date.UTC(r,n-1,l));return i.getUTCFullYear()===r&&i.getUTCMonth()===n-1&&i.getUTCDate()===l}var gl=e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,ml=(e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,bl=(e,t)=>typeof t=="string"&&pl(t)?null:`${e} must be a real date written YYYY-MM-DD`,yl=(e,t={})=>(r,n)=>{if(typeof n!="string")return`${r} must be a string`;if(p(n))return`${r} contains an unpaired surrogate and cannot be encoded`;let l=t.trimmed?n.trim():n;if(t.required&&l.length===0)return`${r} is required and must not be blank`;let i=g(l);return i<=e?null:`${r} is ${i} characters; the server accepts at most ${e}`},vl={sex:gl(ol),spayedNeutered:ml,birthDate:bl,birthDatePrecision:gl(sl),activityLevel:gl(al),indoorOutdoor:gl(ul),foodBrand:yl(ll),foodType:yl(ll),microchipId:yl(il)},xl=["ref","ref",false,yl(el,{required:true,trimmed:true})],wl=["notes","notes",false,yl(nl,{trimmed:true})],kl=[xl,["name","name",true,yl(tl,{required:true,trimmed:true})],["dose","dose",false,yl(rl,{trimmed:true})],["frequency","frequency",false,yl(rl,{trimmed:true})],["startDate","start_date",false,bl],["endDate","end_date",false,bl],wl],Cl={allergies:[xl,["allergen","allergen",true,yl(tl,{required:true,trimmed:true})],["severity","severity",false,gl(cl)],wl],medications:kl,supplements:kl,conditions:[xl,["conditionName","condition_name",true,yl(tl,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,bl],wl]};function Sl(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return{error:`${n} must be an object`};let l=r,i={};for(let[t,r,o,s]of Cl[e]){let e=l[t];if(e==null){if(o)return{error:`${n}.${t} is required`};e===null&&(i[r]=null);continue}let a=s(`${n}.${t}`,e);if(a!==null)return{error:a};i[r]=e}let o=i.start_date,s=i.end_date;return typeof o=="string"&&typeof s=="string"&&s<o?{error:`${n}.endDate must not be before startDate`}:{item:i}}function jl(e,t){if(!Array.isArray(t))return{error:`${e} must be an array (send [] to clear it)`};if(t.length>Jn)return{error:`${e} has ${t.length} items; the server accepts at most ${Jn}`};let r=[],n=/* @__PURE__ */new Set;for(let l=0;l<t.length;l+=1){let i=Sl(e,l,t[l]);if("error"in i)return i;let o=i.item.ref;if(typeof o=="string"){let t=o.trim();if(n.has(t))return{error:`${e}: ref ${JSON.stringify(t)} is used twice; a ref names one item`};n.add(t)}r.push(i.item)}return{items:r}}function _l(e,t){let r=e,n={};for(let[e,t]of fl){let l=r[e];if(l!==void 0){if(l!==null){let t=vl[e](e,l);if(t!==null)return{error:t}}n[t]=l}}let l=r.birthDate!==void 0,i=r.birthDatePrecision!==void 0;if(l!==i||l&&r.birthDate===null!=(r.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[e,t]of hl){let l=r[e];if(l===void 0)continue;let i=jl(e,l);if("error"in i)return i;n[t]=i.items}return Object.keys(n).length>0&&t!==void 0&&canonicalPetSpecies(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}var Rl=e=>typeof e=="string"?e:null,Tl=(e,t)=>typeof t=="string"&&e.has(t)?t:null,Il=e=>typeof e=="boolean"?e:null;function zl(e,t){return Array.isArray(e)?/* @__PURE__ */Object.freeze(e.flatMap(e=>{if(typeof e!="object"||e===null||Array.isArray(e))return[];let r=t(e);return r===null?[]:[r]})):/* @__PURE__ */Object.freeze([])}function Pl(e){let t=Rl(e.name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:Rl(e.ref),name:t,dose:Rl(e.dose),frequency:Rl(e.frequency),startDate:Rl(e.start_date),endDate:Rl(e.end_date),notes:Rl(e.notes)})}function El(e){let t=e.profile_version;/* @__PURE__ */
|
|
35
|
+
return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:Tl(ol,e.sex),spayedNeutered:Il(e.spayed_neutered),birthDate:Rl(e.birth_date),birthDatePrecision:Tl(sl,e.birth_date_precision),activityLevel:Tl(al,e.activity_level),indoorOutdoor:Tl(ul,e.indoor_outdoor),foodBrand:Rl(e.food_brand),foodType:Rl(e.food_type),microchipId:Rl(e.microchip_id),allergies:zl(e.allergies,e=>{let t=Rl(e.allergen);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:Rl(e.ref),allergen:t,severity:Tl(cl,e.severity),notes:Rl(e.notes)})}),medications:zl(e.medications,Pl),supplements:zl(e.supplements,Pl),conditions:zl(e.conditions,e=>{let t=Rl(e.condition_name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:Rl(e.ref),conditionName:t,diagnosedDate:Rl(e.diagnosed_date),notes:Rl(e.notes)})})})}var Ol=100,Al=50,Ml=100,Fl=50,Dl=500,Ll=128,Bl=6e4;function Vl(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function Hl(e,t,r){if(typeof t!="string")return Vl(`${e} must be a string`);let n=g(t);return n<=r?null:Vl(`${e} is ${n} characters; the server accepts at most ${r}`)}function Ul(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Vl(`${e} must be a finite number between 0 and ${r}`)}function Nl(e,t){if(typeof e!="string")return Vl("pet_ref must be a string");if(e.trim().length===0)return Vl("pet_ref must not be blank");if(p(e))return Vl("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Vl("profile must be an object");let r=[Hl("pet_ref",e,Ll)];return t?.name!==void 0&&r.push(Hl("name",t.name,Ol)),t?.species!==void 0&&r.push(Hl("species",t.species,Al)),t?.breed!==void 0&&r.push(Hl("breed",t.breed,Ml)),t?.ageYears!==void 0&&r.push(Ul("age_years",t.ageYears,Fl)),t?.weightKg!==void 0&&r.push(Ul("weight_kg",t.weightKg,Dl)),r.find(e=>e!==null)??null}function $l(e,t){let r=_l(e,t);return"error"in r?{error:Vl(r.error)}:r}function Wl(e){if(typeof e!="object"||e===null)return{error:Vl("patch must be an object")};let t=e,r=[["name","name",e=>Hl("name",e,Ol)],["species","species",e=>Hl("species",e,Al)],["breed","breed",e=>Hl("breed",e,Ml)],["ageYears","age_years",e=>Ul("age_years",e,Fl)],["weightKg","weight_kg",e=>Ul("weight_kg",e,Dl)]],n={};for(let[e,l,i]of r){let r=t[e];if(r!==void 0){if(r!==null){let e=i(r);if(e!==null)return{error:e}}n[l]=r}}let l=$l(t,t.species);return"error"in l?l:(Object.assign(n,l.body),Object.keys(n).length===0?{error:Vl("patch must change at least one field")}:{body:n})}function ql(e){if(e==null)return{body:{}};let t=$l(e,e.species);return"error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}var Gl=e=>typeof e=="string"?e:null,Kl=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Yl(e,t){let r=typeof e=="object"&&e!==null?e:{};/* @__PURE__ */
|
|
36
|
+
return Object.freeze({petRef:Gl(r.pet_ref)??t,name:Gl(r.name),species:Gl(r.species),breed:Gl(r.breed),ageYears:Kl(r.age_years),weightKg:Kl(r.weight_kg)})}function widgetPetFromWire(e){if(typeof e!="object"||e===null)return null;let t=e,r=Gl(t.pet_ref);return r===null||r.length===0?null:/* @__PURE__ */Object.freeze({petId:Gl(t.pet_id),petRef:r,name:Gl(t.name),species:Gl(t.species),breed:Gl(t.breed),ageYears:Kl(t.age_years),weightKg:Kl(t.weight_kg),updatedAt:Gl(t.updated_at)})}function Ql(e){let t=widgetPetFromWire(e);return t===null?null:/* @__PURE__ */Object.freeze({...t,...El(e)})}function Zl(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];/* @__PURE__ */
|
|
37
|
+
return Object.freeze(t.flatMap(e=>{let t=widgetPetFromWire(e);return t===null?[]:[t]}))}function createPetsRepository(e){return Xl(createRequestFunnel({auth:e}),createRequestFunnel({auth:e,unaryTimeoutMs:Bl}))}function Xl(e,t=e){let r=(e,t)=>t?{...e,signal:t}:e,n=e=>Nl(e,void 0)??`/widget/v1/pets/${encodeURIComponent(e)}`;return{async list(t){let n=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},t?.signal));return n.ok?ok(Zl(n.value)):err(n.error)},async registerPet(t,r,n){let l=Nl(t,r);if(l!==null)return err(l);let i=ql(r);if("error"in i)return err(i.error);let o={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(t)}`,body:i.body},s=await e.send("pets.registerPet",n?.signal?{...o,signal:n.signal}:o);return s.ok?ok(Yl(s.value,t)):err(s.error)},async updatePet(t,l,i){let o=n(t);if(typeof o!="string")return err(o);let s=Wl(l);if("error"in s)return err(s.error);let a=await e.send("pets.updatePet",r({method:"PATCH",path:o,body:s.body},i?.signal));return a.ok?ok(Yl(a.value,t)):err(a.error)},async getPetProfile(t,l){let i=n(t);if(typeof i!="string")return err(i);let o=await e.send("pets.getPetProfile",r({method:"GET",path:`${i}/profile`},l?.signal));if(!o.ok)return err(o.error);let s=Ql(o.value);return s===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(s)},async deletePet(t,l){let i=n(t);if(typeof i!="string")return err(i);let o=await e.send("pets.deletePet",r({method:"DELETE",path:i},l?.signal));return o.ok?ok(void 0):err(o.error)},async eraseUserData(e){let n=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},e?.signal),{maxAttempts:1});return n.ok?ok(void 0):err(n.error)}}}var Jl=/* @__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(e){return Jl[e]}function deniedDecisionsFor(e,t){let r=/* @__PURE__ */Object.freeze({reason:t,level:e,recoverable:false}),n=[],l=/* @__PURE__ */new Set;for(let e of Object.keys(Jl))for(let t of Jl[e])l.has(t)||(l.add(t),n.push(/* @__PURE__ */Object.freeze({resource:t,granted:false,disabled:r}))/* @__PURE__ */);return Object.freeze(n)}function decideCapability(e,t,r){let n=requires(e),l=/* @__PURE__ */new Map;for(let e of t)l.set(e.resource,e);if(r?.isPending===true&&n.some(e=>!l.has(e)))return ri({name:e,enabled:false,isPending:true,limits:{}});let i=ei(n,l);return n.filter(e=>l.get(e)?.granted!==true).length===0?ri({name:e,enabled:true,isPending:false,limits:i}):ri({name:e,enabled:false,isPending:false,limits:i,disabled:ti(n,l)})}function ei(e,t){let r={};for(let n of e){let e=t.get(n)?.limits;if(e)for(let[t,n]of Object.entries(e)){let e=r[t];r[t]=e===void 0?n:Math.min(e,n)}}return r}function ti(e,t){for(let r of e){let e=t.get(r)?.disabled;if(e)/* @__PURE__ */
|
|
38
38
|
return Object.freeze({reason:e.reason,level:e.level,recoverable:e.recoverable})}/* @__PURE__ */
|
|
39
|
-
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function tl(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:/* @__PURE__ */Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),/* @__PURE__ */Object.freeze(t)}function rl(e,t){if(typeof e=="function")try{let r=e(t);r!==null&&typeof r=="object"&&typeof r.then=="function"&&r.then(void 0,nl)}catch(e){nl(e)}}function nl(e){let t=globalThis.console;try{t?.error?.("[everfur] onEvent threw; the SDK ignored it.",e)}catch{}}var il=/* @__PURE__ */new WeakMap,ll=/* @__PURE__ */new Map;function ol(e,t){il.set(e,t)}function sl(e,t,r,n){let i=il.get(e);if(i===void 0)return null;let l;if(t.mode==="personalized"&&typeof t.userRef=="string")l=`u:${t.userRef}`;else if(t.mode==="anonymous"&&typeof t.sessionId=="string")l=`a:${t.sessionId}|${t.userRef??""}`;else return null;return`${i}|${l}|${r}|${ul(n)}`}function al(e,t){if(e===null)return t();let r=ll.get(e);if(r!==void 0)return r;let n=t().finally(()=>{ll.get(e)===n&&ll.delete(e)});return ll.set(e,n),n}function ul(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(ul).join(",")}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${ul(t)}`).join(",")}}`}var cl=/* @__PURE__ */new WeakMap;function dl(e,t){let r=cl.get(e);return r===void 0&&(r=/* @__PURE__ */new Set,cl.set(e,r)),r.add(t),()=>{r?.delete(t)}}function fl(e){let t=cl.get(e);if(t!==void 0)for(let e of[...t])try{e()}catch{}}var hl=/* @__PURE__ */new Map;function pl(e,t){return()=>{let r=hl.get(e);if(r!==void 0)return r;let n;try{n=Promise.resolve(t())}catch(e){n=Promise.reject(e)}let i=n.finally(()=>{hl.get(e)===i&&hl.delete(e)});return hl.set(e,i),i}}var gl="/widget/v1/me/timezone",ml=/^(Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)\/[A-Za-z0-9_+-]+(\/[A-Za-z0-9_+-]+)?$/,bl=/* @__PURE__ */new Set;function yl(e){return typeof e=="string"&&e.length<=64&&ml.test(e)?e:null}function vl(e,t){try{let r=yl(Intl.DateTimeFormat().resolvedOptions().timeZone);if(r===null)return;let n=`${e}|${r}`;if(bl.has(n))return;bl.add(n),createRequestFunnel({auth:t}).send("member.deviceTimezone",{method:"PUT",path:gl,body:{timezone:r}},{maxAttempts:1,idempotent:!1}).catch(()=>{})}catch{}}function parseColor(e){let t=xl(e);return t===null?null:Rl(t)}function xl(e){if(typeof e=="number")return Cl(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return wl(t.slice(1));if(t.toLowerCase().startsWith("0x"))return wl(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return kl(t);if(/^[0-9a-fA-F]+$/.test(t)){let e=wl(t);if(e!==null)return e}return/^\d+$/.test(t)?Cl(Number.parseInt(t,10)):null}function wl(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return{r:jl(t[0]),g:jl(t[1]),b:jl(t[2]),a:1};if(t.length===6)return{r:Sl(t,0),g:Sl(t,2),b:Sl(t,4),a:1};if(t.length===8){let e=Sl(t,0);return{r:Sl(t,2),g:Sl(t,4),b:Sl(t,6),a:e/255}}return null}function kl(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(e=>e.trim());if(n.length<3)return null;let i=_l(Number(n[0])),l=_l(Number(n[1])),o=_l(Number(n[2]));if(i===null||l===null||o===null)return null;let s=1;if(n.length>=4){let e=Number(n[3]);if(!Number.isFinite(e))return null;s=Math.min(1,Math.max(0,e))}return{r:i,g:l,b:o,a:s}}function Cl(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return{r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}function Sl(e,t){return Number.parseInt(e.slice(t,t+2),16)}function jl(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}function _l(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}function Rl(e){if(e.a>=1)return Tl(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return`rgba(${e.r},${e.g},${e.b},${t})`}function Tl(e,t,r){return`#${Il(e)}${Il(t)}${Il(r)}`.toUpperCase()}function Il(e){return e.toString(16).padStart(2,"0")}var zl="#111111",Pl="#FFFFFF",El="#000000";function readableOn(e){let t=xl(e);if(t===null)return Pl;let r=Ml(t),n=Ml({r:17,g:17,b:17}),i=Ml({r:255,g:255,b:255});return Dl(r,i)>=Dl(r,n)?Pl:zl}function Ol(e,t){let r=readableOn(e);return contrastRatio(r,e)>=t?r:contrastRatio(Pl,e)>=contrastRatio(El,e)?Pl:El}function Al(e){let t=t=>e.reduce((e,r)=>Math.min(e,contrastRatio(t,r)),Number.POSITIVE_INFINITY);return t(Pl)>=t(El)?Pl:El}function Ml(e){let t=Fl(e.r/255),r=Fl(e.g/255),n=Fl(e.b/255);return.2126*t+.7152*r+.0722*n}function Fl(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}function Dl(e,t){let r=Math.max(e,t),n=Math.min(e,t);return(r+.05)/(n+.05)}function contrastRatio(e,t){let r=xl(e),n=xl(t);if(r===null||n===null)return 1;let i=n.a>=1?n:{...n},l=r.a>=1?r:Ll(r,i);return Dl(Ml(l),Ml(i))}function Ll(e,t){let r=e.a,n=(e,t)=>Math.round(e*r+t*(1-r));return{r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}function Bl(e,t){let r=xl(e),n=xl(t);if(r===null||n===null)return null;let i=r.a>=1?r:Ll(r,{...n});return Tl(i.r,i.g,i.b)}function Vl(e,t){let r=xl(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return`rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}var Hl=.05;function Ul(e,t,r,n){let i=t[0];if(i===void 0)return r;let l=e=>t.every(t=>contrastRatio(e,t)>=n);if(xl(e)===null)return r;if(l(e))return e;let o=Bl(e,i),s=o===null?null:xl(o),a=xl(r);if(s===null||a===null)return r;for(let e=1;e<1/Hl;e+=1){let t=e*Hl,r=(e,r)=>Math.round(e+(r-e)*t),n=Tl(r(s.r,a.r),r(s.g,a.g),r(s.b,a.b));if(l(n))return n}return r}function Nl(e,t,r){let n=e/255,i=t/255,l=r/255,o=Math.max(n,i,l),s=Math.min(n,i,l),a=(o+s)/2;if(o===s)return{h:0,s:0,l:a};let u=o-s,c=u/(1-Math.abs(2*a-1)),d;return o===n?(d=(i-l)/u*60,d<0&&(d=d+360)):o===i?d=((l-n)/u+2)*60:d=((n-i)/u+4)*60,{h:d,s:c,l:a}}function $l(e){let{h:t,s:r,l:n}=e,i=(1-Math.abs(2*n-1))*r,l=t/60,o=i*(1-Math.abs(l%2-1)),s=n-i/2,a=Math.floor(l)%6,u=[[i,o,0],[o,i,0],[0,i,o],[0,o,i],[o,0,i],[i,0,o]],[c,d,f]=u[a];return{r:Wl(c+s),g:Wl(d+s),b:Wl(f+s)}}function Wl(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}var ql=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog","cartBar","planCard","planReasonLabel","planWash","planChip"]),Gl=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),Kl=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"]),planWash:/* @__PURE__ */Object.freeze(["backgroundColor"]),planChip:/* @__PURE__ */Object.freeze(["backgroundColor"])});function themeSlotKeysFor(e){return Kl[e]??Gl}var Yl=4.5,Ql=/* @__PURE__ */Object.freeze({});function Zl(e){return ql.includes(e)}function Xl(e){let t=typeof e=="string"&&e.length<=16?e.trim().replace(/ ?px$/i,""):null,r=typeof e=="number"?e:t!==null&&t.length>0?Number(t):Number.NaN;return Number.isFinite(r)?Math.max(0,r):null}function parseThemeSlots(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,i]of Object.entries(e)){if(!Zl(n)||i===null||typeof i!="object")continue;let e=to(i);if(e===null)continue;let l=Jl(n,e);l!==null&&(t[n]=l,r=true)}return r?/* @__PURE__ */Object.freeze(t):null}function Jl(e,t){let r=Kl[e];if(r===void 0)return t;let n={};for(let e of r)t[e]!==void 0&&(n[e]=t[e]);return Object.keys(n).length===0?null:/* @__PURE__ */Object.freeze(n)}function eo(e,t,r){return e[t]!==void 0?e[t]:e[r]}function to(e){let t={},r=parseColor(eo(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=parseColor(eo(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let i=Xl(eo(e,"border_radius","borderRadius"));i!==null&&(t.borderRadius=i);let l=parseColor(eo(e,"text_color","textColor"));return l!==null&&(t.textColor=l),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function mergeThemeSlots(e,t){return t===null||Object.keys(t).length===0?e??Ql:e===null||Object.keys(e).length===0?t:/* @__PURE__ */Object.freeze({...e,...t})}function ro(e){let t=xl(e);return t!==null&&t.a>=1}var no=3,io=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function lo(e,t){let r=parseColor(e);return r!==null&&r===parseColor(t)}function oo(e,t,r=[]){if(t.length===0)return null;let n=t.map(t=>Bl(e,t)??e);if(t.every((e,t)=>contrastRatio(n[t],e)>=no))return null;let i=[...t,...n,...r];return Ul(n[0],i,Al(i),no)}function so(e,t){return e===void 0?t:t.length===0?[e]:t.map(t=>Bl(e,t)??t)}function ao(e,t){let r=Al(e);return e.every(e=>contrastRatio(r,e)>=t)}function uo(e,t){let r=t[0];return r===void 0?null:Bl(e,r)}function co(e){let t=Ol(e[0],Yl);return e.every(e=>contrastRatio(t,e)>=Yl)?t:Al(e)}function fo(e,t,r,n,i){return io.has(e)?false:i?true:r!==void 0&&lo(t,r)?false:!(n!==void 0&&r!==void 0&&ro(r))}function guardSlotContrast(e,t,r){let n=false,i={};for(let l of ql){let o=e[l];if(o===void 0)continue;let s=o.backgroundColor,a=t?.[l]??[],u=so(s,a),c={...o},d=false;if(s!==void 0&&u.length>1&&!ao(u,Yl)){let e=uo(s,a);e!==null&&(c.backgroundColor=e,u=[e],d=true)}let f=r?.[l],h=c.backgroundColor,p=f!==void 0&&h!==void 0&&ro(h)&&oo(h,f,u)!==null;if(u.length>0){let e=o.textColor;if(s!==void 0)(e===void 0||u.some(t=>contrastRatio(e,t)<Yl))&&(c.textColor=co(u),d=true);else if(e!==void 0){let t=Ul(e,u,Al(u),Yl);t!==e&&(c.textColor=t,d=true)}if(o.borderColor!==void 0&&fo(l,o.borderColor,h,f,p)){let e=p?[...u,...f??[]]:u,t=Ul(o.borderColor,e,Al(e),no);t!==o.borderColor&&(c.borderColor=t,d=true)}}if(p&&h!==void 0&&f!==void 0&&c.borderColor===void 0){let e=oo(h,f,u);e!==null&&(c.borderColor=e,d=true)}i[l]=d?/* @__PURE__ */Object.freeze(c):o,n=n||d}return n?/* @__PURE__ */Object.freeze(i):e}var ho=/* @__PURE__ */Object.freeze(["display","title","cardTitle","rowTitle","body","message","bodySmall","caption","label","eyebrow","chip","tab","button","badge"]),po=/* @__PURE__ */Object.freeze({display:/* @__PURE__ */Object.freeze({size:29,lineHeight:1.06,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),title:/* @__PURE__ */Object.freeze({size:23,lineHeight:1.12,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),cardTitle:/* @__PURE__ */Object.freeze({size:19,lineHeight:1.22,weight:"800",face:"sans",letterSpacing:0,uppercase:false,tier:"heading"}),rowTitle:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.4,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),body:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),message:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),bodySmall:/* @__PURE__ */Object.freeze({size:14.5,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),caption:/* @__PURE__ */Object.freeze({size:13,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),label:/* @__PURE__ */Object.freeze({size:10.5,lineHeight:1.4,weight:"400",face:"mono",letterSpacing:.05,uppercase:true,tier:"compact"}),eyebrow:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"mono",letterSpacing:.07,uppercase:true,tier:"compact"}),chip:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.3,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),tab:/* @__PURE__ */Object.freeze({size:16,lineHeight:1.5,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"control"}),badge:/* @__PURE__ */Object.freeze({size:12,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"badge"})});var go=Object.freeze;function deepFreeze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){go(e);for(let t of Object.keys(e))deepFreeze(e[t])}return e}var mo=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),bo=/* @__PURE__ */Object.freeze({content:0,heading:1.4,control:1.35,compact:1.3,badge:1.2}),yo={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},vo={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},xo={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},wo={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},ko={regular:"400",medium:"500",bold:"700"},Co={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},So=0,jo="System",_o="monospace",Ro=["content","heading","control","compact","badge"];function To(e){let t={};for(let r of Ro)t[r]=e;return t}var Io=[];function zo(){return{family:jo,mono:_o,fontUrl:null,families:{regular:jo,medium:jo,bold:jo,mono:_o,monoMedium:_o,monoBold:_o},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:xo,tierSizes:To(xo),lineHeight:wo,weight:ko,letterSpacing:Co,scale:1,maxScale:So,scaleCaps:mo,headingFamily:null,headingWeight:null,fontSources:Io,roles:po,typeScale:1}}var Po={},Eo=/* @__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(e){return`cubic-bezier(${e.join(", ")})`}var Oo={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(Eo.standard),emphasized:cssCubicBezier(Eo.emphasized),exit:cssCubicBezier(Eo.exit)},reducedMotion:false},Ao={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)"},Mo=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:Ao,space:yo,radius:vo,type:zo(),motion:Oo,slots:Po}),Fo={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)"},Do=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:Fo,space:yo,radius:vo,type:zo(),motion:Oo,slots:Po});function Lo(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function Bo(e){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}function Vo(e){return Bo(e).every(t=>contrastRatio(e.brand,t)>=no)}function Ho(e){return[e.chatGround,e.surface,e.surfaceCream]}function Uo(e,t){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...No(e,t)]}function No(e,t){return[Bl(t,e.surface)??e.surface,Bl(t,e.surfaceCream)??e.surfaceCream]}function $o(e){return[e.composerFill,e.chatGround]}var Wo=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function qo(e,t){let r=new Set(Lo(t));return Lo(e).every(e=>r.has(e))}function Go(e){let t=e.color,r=(e.brightness==="dark"?Do:Mo).color,n=(e.brightness==="dark"?Mo:Do).color,i=Lo(t),l=Al(i)!==Al(Lo(r)),o=qo(t,r),s=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,a=(e,t,r,n,i,a)=>{let u=t===r&&(e!=="errorRed"||s);return u&&o&&Wo.has(e)?t:Ul(u&&l?n:t,i,Al(i),a)},u=(e,i,l)=>a(`text.${e}`,t.text[e],r.text[e],n.text[e],i,l),c=(e,t,i,l)=>a(e,t,r[e],n[e],i,l),d=e=>l&&t[e]===r[e]?n[e]:t[e],f=t.primary,h=Ol(f,Yl),p=c("danger",t.danger,[...i,...No(t,t.badgeBgCritical)],Yl),g={...t,onPrimary:h,onAccent:Ol(t.accent,Yl),onDanger:contrastRatio(h,p)>=Yl?h:Ol(p,Yl),brandSoft:d("brandSoft"),brandSofter:d("brandSofter"),brandBorder:d("brandBorder"),borderHairlineGreen:d("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,i,Yl),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,Ho(t),Yl),text:{...t.text,primary:u("primary",i,Yl),secondary:u("secondary",i,Yl),muted:u("muted",i,Yl),metaCool:u("metaCool",i,Yl),timestamp:u("timestamp",i,Yl),placeholder:u("placeholder",Bo(t),no)},danger:p,errorRed:c("errorRed",t.errorRed,Uo(t,t.badgeBgCritical),Yl),warningStrong:c("warningStrong",t.warningStrong,Uo(t,t.badgeBgCaution),Yl),composerBorder:c("composerBorder",t.composerBorder,$o(t),no),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,Bo(t),no)},m={...g,...ts(g,r,o)};return{...m,...Ko(t,m,r)}}function Ko(e,t,r){let n={},i=(e,t,r)=>Ul(e,t,Al(t),r);if((!Xo(e.success,r.success)||!Xo(e.badgeBgPositive,r.badgeBgPositive))&&(n.success=i(e.success,Uo(t,e.badgeBgPositive),Yl)),(!Xo(e.cautionAccent,r.cautionAccent)||!Xo(e.badgeBgCaution,r.badgeBgCaution))&&(n.cautionAccent=i(e.cautionAccent,Uo(t,e.badgeBgCaution),Yl)),Yo(e,r)){n.info=i(e.info,Uo(t,e.badgeBgInfo),Yl);let r=[t.surface,t.chatGround,...No(t,e.badgeBgInfo)];n.infoEdge=i(e.infoEdge,r,no)}else n.info=t.brandInk,n.badgeBgInfo=t.brandSoft,n.infoEdge=t.structureEdge;return n}function Yo(e,t){return!Xo(e.info,t.info)||!Xo(e.badgeBgInfo,t.badgeBgInfo)}var Qo=.24,Zo=.3;function Xo(e,t){return parseColor(e)===parseColor(t)}function Jo(e,t){return Xo(e.accent,t.accent)?Xo(e.brand,t.brand)?null:e.brand:e.accent}function es(e,t,r){let n=Vl(e,r);return(n===null?null:Bl(n,t))??t}function ts(e,t,r){let n=Jo(e,t),i=Bo(e),l=Al(i),o=Al([e.surface])===Pl,s=n===null&&r,a;s?a=t.highlight:n===null?a=o?es(Mo.color.highlight,e.surface,Zo):Mo.color.highlight:a=es(n,e.surface,o?Zo:Qo);let u=s?t.onHighlight:Ul(e.text.primary,[a],Al([a]),Yl),c=n===null?t.mark:Ul(n,i,l,no),d=Vo(e)?e.brand:l,f=(e,t,n)=>r&&Xo(e,t)?n:Ul(e,i,d,no),h=[e.chatGround,e.composerFill,e.surface,e.surfaceCream],p=h.every(t=>contrastRatio(e.primary,t)>=no)?e.primary:Ul(e.primary,h,Al(h),no);return{highlight:a,onHighlight:u,mark:c,controlEdge:f(e.brandBorder,t.brandBorder,t.controlEdge),structureEdge:f(e.borderHairlineGreen,t.borderHairlineGreen,t.structureEdge),primaryEdge:p}}var rs=(e,t)=>e!==void 0&&t!==void 0&&parseColor(e)===parseColor(t);function ns(e,t){let r=(e.brightness==="dark"?Do:Mo).color,n=e.color,i=t.color,l=[],o=(e,t,r,n)=>{l.push(/* @__PURE__ */Object.freeze({field:e,role:t,requested:r,painted:n}))},s=(e,t)=>!rs(e,t);s(n.text.primary,r.text.primary)&&!rs(i.text.primary,n.text.primary)&&o("text_color","body text",n.text.primary,i.text.primary),s(n.brand,r.brand)&&(rs(i.brandInk,n.brand)||o("primary_color","brand text and icons",n.brand,i.brandInk),rs(i.primaryEdge,n.primary)||o("primary_color","edge of a filled control",n.primary,i.primaryEdge),!rs(i.controlEdge,n.brandBorder)&&!Vo({...i,brand:n.brand})&&o("primary_color","control outline",n.brand,i.controlEdge)),s(n.accent,r.accent)&&e.slots.link?.textColor===void 0&&!rs(i.linkInk,n.accent)&&o("accent_color","link text",n.accent,i.linkInk),s(n.danger,r.danger)&&!rs(i.danger,n.danger)&&o("danger_color","error text",n.danger,i.danger),s(n.success,r.success)&&!rs(i.success,n.success)&&o("success_color","positive status",n.success,i.success),s(n.warningStrong,r.warningStrong)&&!rs(i.warningStrong,n.warningStrong)&&o("warning_color","caution text",n.warningStrong,i.warningStrong),s(n.cautionAccent,r.cautionAccent)&&!rs(i.cautionAccent,n.cautionAccent)&&o("warning_color","caution accent",n.cautionAccent,i.cautionAccent),(s(n.info,r.info)||s(n.badgeBgInfo,r.badgeBgInfo))&&(rs(i.info,n.info)||o("info_color","information text",n.info,i.info),rs(i.infoEdge,n.infoEdge)||o("info_color","information outline",n.infoEdge,i.infoEdge));for(let r of ql){let n=e.slots[r],i=t.slots[r];n===void 0||i===void 0||n===i||(i.backgroundColor!==void 0&&!rs(i.backgroundColor,n.backgroundColor)&&o(`slots.${r}.background_color`,"fill",n.backgroundColor??null,i.backgroundColor),n.textColor!==void 0&&i.textColor!==void 0&&!rs(i.textColor,n.textColor)&&o(`slots.${r}.text_color`,"text",n.textColor??null,i.textColor),i.borderColor!==void 0&&!rs(i.borderColor,n.borderColor)&&o(`slots.${r}.border_color`,"outline",n.borderColor??null,i.borderColor))}/* @__PURE__ */
|
|
40
|
-
return Object.freeze(l)}var is=/* @__PURE__ */new Set;function ls(e){if(e.length===0)return;let t=`[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${e.map(e=>` ${e.field} (${e.role}): ${e.requested??"not set"} -> ${e.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(is.has(t))return;is.add(t);let r=globalThis.console;try{r?.warn?.(t)}catch{}}var os="#23272C",ss=4.5,as=.6,us=.9,cs=.02,ds="#FFFFFF",fs="#111111";function hs(e){return contrastRatio(e,os)>=ss&&Math.max(contrastRatio(e,ds),contrastRatio(e,fs))>=ss}function deriveDarkVariant(e){let t=xl(e);if(t===null)return null;let{h:r,s:n,l:i}=Nl(t.r,t.g,t.b),l=Math.min(Math.max(i,as),us);for(let e=0;;e+=1){let t=l+e*cs;if(t>us)break;let i=$l({h:r,s:n,l:t}),o=Tl(i.r,i.g,i.b);if(hs(o))return o}let o=$l({h:r,s:n,l:us});return Tl(o.r,o.g,o.b)}var ps=7,gs=.05,ms="#000000",bs="#FFFFFF";function ys(e,t,r,n){let i=Bl(e,t);if(i===null)return r;if(contrastRatio(i,t)>=n)return i;let l=xl(i),o=xl(r);if(l===null||o===null)return r;for(let e=1;e<1/gs;e+=1){let r=e*gs,i=(e,t)=>Math.round(e+(t-e)*r),s=Tl(i(l.r,o.r),i(l.g,o.g),i(l.b,o.b));if(contrastRatio(s,t)>=n)return s}return r}function vs(e,t){let r=Lo(e),n=r[0],i=xs(n);for(let e of r){let r=xs(e);(t?r>i:r<i)&&(n=e,i=r)}return n}function xs(e){let t=xl(e);return t===null?0:Ml(t)}function ws(e,t){return Bl(e,t)??parseColor(e)??t}function deriveHighContrast(e){let t=e.color,r=Al(Lo(t))===bs,n=r?bs:ms,i=vs(t,r),l=e=>ys(e,i,n,ps),o={...t,brandSoft:ws(t.brandSoft,t.surface),brandSofter:ws(t.brandSofter,t.surface),brandBorder:l(t.brandBorder),borderHairlineGreen:l(t.borderHairlineGreen),brandBorderStrong:l(t.brandBorderStrong),controlEdge:l(t.controlEdge),structureEdge:l(t.structureEdge),brandInk:l(t.brandInk),linkInk:l(t.linkInk),borderRingCream:l(t.borderRingCream),composerBorder:l(t.composerBorder),text:{primary:l(t.text.primary),secondary:l(t.text.secondary),muted:l(t.text.muted),placeholder:l(t.text.placeholder),onBrand:t.text.onBrand,metaCool:l(t.text.metaCool),timestamp:l(t.text.timestamp)},badgeBgPositive:ws(t.badgeBgPositive,t.surface),badgeBgCaution:ws(t.badgeBgCaution,t.surface),badgeBgCritical:ws(t.badgeBgCritical,t.surface),badgeBgNeutral:ws(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:ws(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:ws(t.checkupCardConcernBg,t.surface),info:l(t.info),infoEdge:l(t.infoEdge),badgeBgInfo:ws(t.badgeBgInfo,t.surface)};return deepFreeze({...e,highContrast:true,color:o})}var ks=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),Cs=ks.cream,Ss=ks.subtle,js=ks.ring,_s=10;function Rs(e,t,r){let n=xl(e),i=xl(t);if(n===null||i===null)return null;let l=(e,t)=>Math.round(e+(t-e)*r);return Tl(l(n.r,i.r),l(n.g,i.g),l(n.b,i.b))}function Ts(e){if(e===null)return{};let t=Al([e]),r=Rs(e,t,Cs),n=Rs(e,t,Ss),i=Rs(e,t,js);return r===null||n===null||i===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:i}}function Is(e){if(e===null)return{};let t=xl(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}function zs(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let i={};for(let[e,t]of Object.entries(r.type.size))i[e]=Math.max(_s,Math.round(t*n*10)/10);return i}function Ps(e,t,r){if(e===null)return t;let n=e/r.space.xs,i=e=>Math.round(e*n),l=r.space;return{xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),xxl:i(l.xxl)}}function Es(e,t){let r=e/t.radius.md,n=e=>Math.round(e*r),i=t.radius;return{tile:n(i.tile),xs:n(i.xs),sm:n(i.sm),md:n(i.md),lg:n(i.lg),xl:n(i.xl),pill:i.pill}}var Os=/* @__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 As(e,t){let r=xl(e);return r===null?null:`rgba(${r.r},${r.g},${r.b},${t})`}function Ms(e,t){if(e===null)return{};let r=As(e,t?Os.success.dark:Os.success.light),n=As(e,t?Os.successCard.dark:Os.successCard.light);return r===null||n===null?{}:{success:e,badgeBgPositive:r,checkupCardLowRiskBg:n}}function Fs(e,t){if(e===null)return{};let r=As(e,t?Os.warning.dark:Os.warning.light);return r===null?{}:{warningStrong:e,cautionAccent:e,badgeBgCaution:r}}function Ds(e,t){if(e===null)return{};let r=As(e,t?Os.info.dark:Os.info.light);return r===null?{}:{info:e,infoEdge:e,badgeBgInfo:r}}function Ls(e,t,r){if(e===null)return t;let n=r.type.lineHeight,i=e/n.normal;if(i===1)return n;let l=e=>Math.round(e*i*100)/100;return{tight:l(n.tight),snug:l(n.snug),normal:l(n.normal),relaxed:l(n.relaxed)}}function Bs(e){return{composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],vetBubble:[e.bubbleVet],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Ho(e),header:[e.surface,e.background,e.chatGround],banner:[Bl(e.badgeBgInfo,e.surface)??e.surface,Bl(e.badgeBgCaution,e.surface)??e.surface,e.surface],chip:[e.chatGround,e.surface,e.background,e.surfaceCream],card:[e.surface],input:[e.surface,e.composerFill,e.surfaceCream,e.surfaceSubtle],tab:[e.surface,e.background],bookingStep:[e.surface,e.background],dialog:[e.surface],cartBar:[e.brand],planCard:[e.surface],planReasonLabel:[e.surface],planWash:[e.surface],planChip:[e.surface]}}function Vs(e){return{userBubble:[e.chatGround],assistantBubble:[e.chatGround],vetBubble:[e.chatGround],sendButton:[e.composerFill],vetVisitButton:[e.surfaceCream,e.surface,e.chatGround],primaryButton:[e.surface,e.surfaceCream]}}function Hs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Us=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),Ns=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),$s=/* @__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 Ws(e){return typeof e=="string"&&Us.includes(e.trim().toLowerCase())}function qs(e,t){let r=e[t];return r??void 0}var Gs=16;function parsePx(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>Gs)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}var Ks=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],Ys=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],Qs=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],Zs=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],Xs=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(e){if(!Hs(e))return null;let t=Ws(e.theme)?Ns[e.theme.trim().toLowerCase()]:{},r=Hs(e.variables)?e.variables:{},n={...t};for(let[e,t]of Object.entries(r))t!=null&&(n[e]=t);let i={},l=qs(n,"colorScheme"),o=typeof l=="string"?l.trim().toLowerCase():null;(o==="light"||o==="dark"||o==="auto")&&(i.color_scheme=o);let s=o==="dark"?"_dark":"";for(let[e,t]of Ks){let r=qs(n,e);r!==void 0&&(i[`${t}${s}`]=r)}for(let[e,t]of Ys){let r=qs(n,e);r!==void 0&&(i[`${t}${s}`]=r)}for(let[e,t]of Zs){let r=qs(n,e);typeof r=="string"&&r.trim().length>0&&(i[t]=r.trim())}for(let[e,t]of Xs){let r=parsePx(qs(n,e));r!==void 0&&(i[t]=r)}for(let[e,t]of Qs){let r=qs(n,e);(typeof r=="number"||typeof r=="string")&&(i[t]=r)}let a=e.fonts;Array.isArray(a)&&a.length>0&&(i.font_sources=a);let u=e.rules;if(Hs(u)){let e={};for(let t of ql){let r=u[t];Hs(r)&&(e[t]=r)}Object.keys(e).length>0&&(i.slots=e)}return Object.keys(i).length===0?null:/* @__PURE__ */Object.freeze(i)}var Js="https:\\/\\/sdk(?:-[a-z]+)?\\.everfur\\.com";function ea(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}var ta=typeof __EVERFUR_BRAND_CDN_ORIGIN__=="string"&&__EVERFUR_BRAND_CDN_ORIGIN__.length>0?ea(__EVERFUR_BRAND_CDN_ORIGIN__):Js;var ra=/* @__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,serverSlots:false}),na=/* @__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",serverSlots:"server_slots"}),ia=Object.keys(na),la="presentation",oa="presentation.";function isPresentationLockName(e){if(e===la)return true;if(!e.startsWith(oa))return false;let t=e.slice(oa.length);return Object.values(na).includes(t)}var sa={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer","none"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},aa=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function ua(e,t){if(t==null)return;let r=sa[e];return r!==void 0?typeof t=="string"&&r.includes(t)?t:void 0:aa.has(e)?typeof t=="boolean"?t:void 0:typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=3?t:void 0}function parsePresentation(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of ia){let n=na[e],i=Object.prototype.hasOwnProperty.call(t,n)?t[n]:t[e],l=ua(e,i);l!==void 0&&(r[e]=l)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}function isPresentationFieldLocked(e,t){if(t==null)return false;let r=`${oa}${na[e]}`;for(let e of t)if(e===la||e===r)return true;return false}function resolvePresentation(e){let t=parsePresentation(e?.server??null)??{},{safetyDisclaimerPlacement:r,...n}=t,i=r==="none"||r===void 0?n:{...n,safetyDisclaimerPlacement:r},l=parsePresentation(e?.client??null)??{},o=e?.locked?[...e.locked]:null,s={};for(let e of ia){let t=i[e],r=isPresentationFieldLocked(e,o)?void 0:l[e];s[e]=r??t??ra[e]}/* @__PURE__ */
|
|
41
|
-
return Object.freeze(
|
|
42
|
-
return Object.freeze(
|
|
43
|
-
return new Set(["hide_powered_by",...e?.lockedFields??[]])}function Na(e){return e==="hide_powered_by"||Va.includes(e)||isPresentationLockName(e)?true:e.startsWith(Ha)&&ql.includes(e.slice(Ha.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=Wa(t),n=expandAppearance(Ka(t,"appearance")),i=n===null?r:$a(Wa(n),r);return isEmptyBranding(i)?null:/* @__PURE__ */Object.freeze(i)}function $a(e,t){let r={...e};for(let[e,n]of Object.entries(t))n!=null&&(r[e]=n);let n=mergeThemeSlots(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}function Wa(e){return{displayName:Ya(Ka(e,"display_name","displayName")),logoUrl:Ya(Ka(e,"logo_url","logoUrl")),primaryColor:parseColor(Ka(e,"primary_color","primaryColor")),accentColor:parseColor(Ka(e,"accent_color","accentColor")),brightness:tu(Ka(e,"brightness","color_scheme","colorScheme")),fontFamily:Ya(Ka(e,"font_family","fontFamily")),fontUrl:Ya(Ka(e,"font_url","fontUrl")),fonts:Za(Ka(e,"fonts")),fontUrls:Za(Ka(e,"font_urls","fontUrls")),placeholder:Ya(Ka(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Ga(Ka(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(Ka(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(Ka(e,"accent_color_dark","accentColorDark")),surfaceStyle:eu(Ka(e,"surface_style","surfaceStyle"),Xa),radiusScale:eu(Ka(e,"radius_scale","radiusScale"),Ja),logoUrlDark:Ya(Ka(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(Ka(e,"slots")),accessibilityMaxFontScale:lu(Ka(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:au(Ka(e,"locked_fields","lockedFields")),presentation:parsePresentation(Ka(e,"presentation")),schemaVersion:ou(Ka(e,"schema_version","schemaVersion")),backgroundColor:parseColor(Ka(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(Ka(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(Ka(e,"text_color","textColor")),textColorDark:parseColor(Ka(e,"text_color_dark","textColorDark")),dangerColor:parseColor(Ka(e,"danger_color","dangerColor")),dangerColorDark:parseColor(Ka(e,"danger_color_dark","dangerColorDark")),fontSizeBase:qa(Ka(e,"font_size_base","fontSizeBase"),$s.fontSizeBase),borderRadius:qa(Ka(e,"border_radius","borderRadius"),$s.borderRadius),spacingUnit:qa(Ka(e,"spacing_unit","spacingUnit"),$s.spacingUnit),successColor:parseColor(Ka(e,"success_color","successColor")),successColorDark:parseColor(Ka(e,"success_color_dark","successColorDark")),warningColor:parseColor(Ka(e,"warning_color","warningColor")),warningColorDark:parseColor(Ka(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(Ka(e,"info_color","infoColor")),infoColorDark:parseColor(Ka(e,"info_color_dark","infoColorDark")),headingFontFamily:Ya(Ka(e,"heading_font_family","headingFontFamily")),fontWeightBody:ma(Ka(e,"font_weight_body","fontWeightBody")),fontWeightHeading:ma(Ka(e,"font_weight_heading","fontWeightHeading")),lineHeight:ba(Ka(e,"line_height","lineHeight")),fontSources:ka(Ka(e,"font_sources","fontSources")),assistantAvatarUrl:Ya(Ka(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:Ea(Ka(e,"text_scale_caps","textScaleCaps")),typeScale:Pa(Ka(e,"type_scale","typeScale")),typeRoles:Aa(Ka(e,"type_roles","typeRoles"))}}function qa(e,t){let r=ru(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function Ga(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}function Ka(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let t=e[r];if(t!==void 0)return t}}function Ya(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var Qa=["regular","medium","bold","mono","monoMedium","monoBold"];function Za(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of Qa){let n=Ya(Ka(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var Xa=["white","cream","subtle"],Ja=["sharp","default","round"];function eu(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function tu(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function ru(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}var nu=1,iu=3.1;function lu(e){let t=ru(e);return t===null?null:t<=0?0:Math.min(iu,Math.max(nu,t))}function ou(e){if(e==null)return null;let t=ru(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function su(e){let t=e.trim();return t.startsWith(Ha)?t:t.startsWith(oa)?oa+t.slice(oa.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function au(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let e=su(r);Na(e)&&!t.includes(e)&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}function hardenHttpsUrl(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}var uu=/* @__PURE__ */new RegExp(`^${ta}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&uu.test(t)?t:null}function withServerBranding(e,t){if(t===null||isEmptyBranding(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Do:Mo:e,n=r.brightness==="dark"?Do:Mo,i=r.brightness==="dark",l=i?t.primaryColorDark??pu(t.primaryColor):t.primaryColor,o=i?t.accentColorDark??pu(t.accentColor):t.accentColor,s=l??r.color.primary,a=o??r.color.accent,u=l!==null&&bu(t,s,n,i),c=u?n.color.primary:s,d=l!==null&&!u?xl(c):null,f=e=>Math.round(e+(255-e)*.4),h=d!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${d.r}, ${d.g}, ${d.b}, 0.10)`,brandSofter:`rgba(${d.r}, ${d.g}, ${d.b}, 0.15)`,brandBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.20)`,borderHairlineGreen:`rgba(${d.r}, ${d.g}, ${d.b}, 0.28)`,brandBorderStrong:`rgba(${d.r}, ${d.g}, ${d.b}, 0.55)`,composerBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.75)`,accentEdge:`rgb(${f(d.r)}, ${f(d.g)}, ${f(d.b)})`}:u?yu(n,r.color.text):{},p=(i?t.backgroundColorDark:t.backgroundColor)??null,g=Ts(p),m={...r.color,...g},b=(i?t.textColorDark:t.textColor)??null,y=(e,t)=>(i?t??pu(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(i?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,...(t.placeholder!==null?t.placeholderFillsPet===true:r.meta.placeholderFillsPet===true)?{placeholderFillsPet:true}:{},hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy,assistantAvatarUrl:t.assistantAvatarUrl??r.meta.assistantAvatarUrl},color:{...r.color,...h,...g,...Is(y(t.dangerColor,t.dangerColorDark)),...Ms(y(t.successColor,t.successColorDark),i),...Fs(y(t.warningColor,t.warningColorDark),i),...Ds(y(t.infoColor,t.infoColorDark),i),...b!==null?{text:{...h.text??r.color.text,primary:b}}:{},...gu(t.surfaceStyle??null,m),primary:c,accent:a,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:Ps(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?Es(t.borderRadius,n):xu(t.radiusScale??null,r.radius,n),type:{...r.type,...hu(r.type,t),size:zs(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:Ls(t.lineHeight??null,r.type.lineHeight,n),weight:t.fontWeightBody==null?r.type.weight:{...r.type.weight,regular:t.fontWeightBody},headingFamily:t.headingFontFamily??r.type.headingFamily,headingWeight:t.fontWeightHeading??r.type.headingWeight,fontSources:t.fontSources??r.type.fontSources,roles:Da(r.type.roles,t.fontSizeBase??null,t.lineHeight??null,t.typeRoles??null),typeScale:t.typeScale??r.type.typeScale,scaleCaps:t.textScaleCaps==null?r.type.scaleCaps:{...r.type.scaleCaps,...t.textScaleCaps}},motion:r.motion,slots:mergeThemeSlots(r.slots,t.slots??null)};return deepFreeze(v)}var cu={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},du=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function fu(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function hu(e,t){let r=t.fonts??{},n=t.fontUrls??{},i={...e.families},l={...e.namedFaces},o={...e.fontUrls};for(let e of Qa){let s=cu[e].map(e=>r[e]).find(e=>e!==void 0),a=fu(e)?null:t.fontFamily;s!==void 0?(i[e]=s,l[e]=true):a!==null&&(i[e]=a,l[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:s!==void 0&&delete o[e]}for(let e of du)for(let t of e)l[t]&&e.some(e=>e!==t&&i[e]===i[t])&&(l[t]=false);return{family:i.regular,mono:i.mono,fontUrl:o.regular??null,families:i,namedFaces:l,fontUrls:o}}function pu(e){return e===null?null:deriveDarkVariant(e)}function gu(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function mu(e,t){return e==null?false:parseColor(e)===parseColor(t)}function bu(e,t,r,n){return mu(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&mu(e.primaryColor,Mo.color.primary)}function yu(e,t){let r=e.color;return{text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}var vu={sharp:.5,default:1,round:1.5};function xu(e,t,r){if(e===null)return t;let n=vu[e],i=r.radius,l=e=>Math.round(e*n);return{tile:l(i.tile),xs:l(i.xs),sm:l(i.sm),md:l(i.md),lg:l(i.lg),xl:l(i.xl),pill:i.pill}}var wu="Everfur",ku=.5;function resolveTheme(e){return Lu(Cu(e),e)}function themeAdjustments(e){let t=Cu(e);return ns(t,Lu(t,{...e,highContrast:false}))}function Cu(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=Ru(e?.clientOverride??null,lockedFieldsOf(r)),i=e?.colorScheme==="dark"?"dark":"light",l=n?.brightness??r?.brightness??"light",o=Iu((l==="auto"?i:l)==="dark"?Do:Mo,e?.typeProfile),s=withServerBranding(o,Tu(r));return withServerBranding(s,Tu(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function Su(e){return e==="placeholder"?"chat_placeholder":su(e)}var ju={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 _u(e,t){return t.has(Su(e))?true:(ju[e]??[]).some(e=>t.has(e))}function Ru(e,t){if(e===null)return null;let r=false,n={...e};for(let i of Object.keys(e))(e[i]??null)!==null&&(_u(i,t)||i==="lockedFields")&&(n[i]=null,r=true);let i=n.slots??null;if(i!==null){let e={},l=false;for(let r of ql){let n=i[r];n!==void 0&&(t.has(`${Ha}${r}`)?l=true:e[r]=n)}l&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let l=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(l)?null:l}function Tu(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function Iu(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:bo}})}function zu(e,t){if(t===1)return e;let r={};for(let[n,i]of Object.entries(e))r[n]=Math.round(i*t*10)/10;return r}function Pu(e){return e===void 0||!Number.isFinite(e)?1:Math.max(ku,e)}var Eu=["content","heading","control","compact","badge"];function Ou(e,t){let r={};for(let n of Eu){let i=e[n],l=typeof i=="number"&&Number.isFinite(i)&&i>=0?i:mo[n];n==="content"||!(t>0)?r[n]=l:r[n]=l===0?t:Math.min(l,t)}return Eu.every(e=>r[e]===mo[e])?mo:r}function Au(e,t){return t>0?Math.min(e,t):e}function Mu(e,t,r,n){let i={};for(let l of Eu)i[l]=n?zu(e,Au(t,r[l])):e;return i}function Fu(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function Du(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return{family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces,headingFamily:e.headingFamily};let i=e.headingFamily!==null&&r!==void 0&&Fu(r,e.headingFamily)===false?null:e.headingFamily,l={...e.families},o={...e.namedFaces};for(let e of Qa)!(l[e]===jo||l[e]===_o)&&r!==void 0&&Fu(r,l[e])===false&&(l[e]=fu(e)?_o:jo,o[e]=false),n!==null&&fu(e)&&l[e]===_o&&(l[e]=n);return{family:l.regular,mono:l.mono,families:l,namedFaces:o,headingFamily:i}}function Lu(e,t){let r=e.meta.displayName.trim().length===0?wu:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),i={};for(let t of Qa){let r=e.type.fontUrls[t];r!==void 0&&(i[t]=hardenHttpsUrl(r))}let l=i.regular??null,o=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,s=Number.isFinite(e.type.maxScale)?e.type.maxScale:So,a=Pu(t?.textScale),u=Ou(e.type.scaleCaps,s),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=La(e.type.roles,()=>d),h=c?La(f,e=>Au(a,u[e.tier])):f,p=t?.typeProfile==="phone"?Ba(e.type.size,f,d):zu(e.type.size,d),g=Mu(p,a,u,c),m=Go(e),b={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,...e.meta.placeholderFillsPet===true?{placeholderFillsPet:true}:{},hidePoweredBy:e.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(e.meta.assistantAvatarUrl)},color:m,space:e.space,radius:e.radius,type:{...e.type,...Du(e.type,t),fontUrl:l,fontUrls:i,size:g.content,tierSizes:g,scale:a,maxScale:s,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,Bs(m),Vs(m))};return t?.highContrast===true?deriveHighContrast(deepFreeze(b)):deepFreeze(b)}var Bu="/widget/v1/entitlements",Vu=304,Hu=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",Nu(t));return n.ok?$u(n.value):n.error.httpStatus===Vu?Hu:{kind:"failed",error:n.error}}var Uu=64;function Nu(e){let t={};return Qu(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Uu?{method:"GET",path:Bu,headers:t,query:{region:e.region}}:{method:"GET",path:Bu,headers:t}}function $u(e){if(e===null||typeof e!="object"||!Qu(e.revision))return Yu();let t=typeof e.region=="string"?e.region:"",r=Qu(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
|
|
44
|
-
return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Gu(e.capabilities),branding:qu(e),livemode:e.livemode!==false,...Wu(e)})}function Wu(e){let t=e.render_hints,r=e.sms_profile_public??(t!==null&&typeof t=="object"?t.sms_profile_public:void 0);return r!==null&&typeof r=="object"?{smsProfilePublic:r}:{}}function qu(e){let t=parseClientBranding(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let e=parseClientBranding(r.branding);return e!==null?e:parseClientBranding(r)}return null}function Gu(e){if(e===null||typeof e!="object")/* @__PURE__ */return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Ku(n)&&t.push(/* @__PURE__ */Object.freeze({resource:r,granted:true}));/* @__PURE__ */
|
|
45
|
-
return Object.freeze(
|
|
46
|
-
return Object.freeze(
|
|
47
|
-
return Object.freeze({
|
|
48
|
-
return Object.freeze({request(){return Promise.resolve(err(Cc(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return async function*(){r.aborted||(yield n)}()}})}var Pc=/* @__PURE__ */new WeakSet;function Ec(){let e=/* @__PURE__ */new Map,t={async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r)},async removeItem(t){e.delete(t)},async keys(t){return[...e.keys()].filter(e=>e.startsWith(t))}};return Pc.add(t),t}var Oc=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new Mc(e,t)}var Ac=6e4,Mc=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;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 r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new b("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.errorContext=/* @__PURE__ */Object.freeze({sdkVersion:Xe,platform:t?.platform??Je,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:Ze(r?.appVersion)}),this.telemetry=r.telemetry?jc(r.telemetry,this.errorContext):ue,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",i=checkPublishableKey(r?.publishableKey),l=r.transport!==void 0,o,s=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(i!==null)o=zc(i);else if(r.transport!==void 0)o=r.transport;else{let e=Sc(r,t?.platform);e.ok?(s=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(i=e.failure,o=zc(e.failure))}if(this.configFailure=i,this.reportsDeviceTimezone=i===null&&(t?.reportDeviceTimezone??!l),this.publishableKey=i===null?n:"",this.mintScope=`${this.publishableKey}|${s??""}`,ol(this,this.mintScope),this.transport=o,i!==null&&(Ic(i,this.telemetry,t?.platform),this.emit({type:"error",code:Cc(i).code,requestId:null,context:Ke(this.errorContext,"runtime",null)})),this.errorPolicy=Rc(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??de,this.upload=r.upload??mr,this.uploadTransport=r.uploadTransport??On,this.imageCache=r.imageCache??Oc,this.kv=r.storage??Ec(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=i===null?fc():fc(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:s},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",Fc(e),()=>this.buildChatController(e),Dc),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${Fc(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=tc({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:rc(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),i===null){this.brandingCache=xc(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=i===null?kc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let a=i===null&&(t?.startEntitlementPolling??!l);this.poller=i===null?this.buildPoller(t?.pollScheduler):null,a&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=pl(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,t=>{this.armTokenRefresh(r,t),this.reportsDeviceTimezone&&!this.disposed&&r===this.identity&&vl(`${this.mintScope}|${e.userRef}`,this.buildAuth(e.userRef))},()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-Ac,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||rl(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let i=this.store.getSnapshot().branding??null,l=i!==null&&t!=null&&bc(i)===bc(t)?i:t;this.updateEntitlements({decisions:e,isPending:false,branding:l,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(l??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,i=false){let l=`${this.epoch}|${e}|${t}`,o=this.entries.get(l);if(o)return i||(o.warm?o.warm=false:o.refCount+=1),o.controller;let s=r();return this.entries.set(l,{controller:s,refCount:1,warm:i}),this.destroyers.set(s,n),s}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:Rc(this.errorPolicy,this.errorContext,"chat")}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){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:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await cc(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return ac({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>uc({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>al(sl(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(Lc(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&fl(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let i={key:r,result:null,promise:this.runPrepare(t).then(e=>(i.result=e,e))};return this.prepared=i,i.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?Lc("prepare"):r===null?null:Cc(r),i=this.identity,[l,o,s]=await Promise.all([n?err(n):i===null?ok(void 0):i.currentToken().then(()=>ok(void 0),e=>(i.reportRejected?.(),err(xe(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),a=l.ok?o.ok&&(s?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:a})}catch{}if(a==="ready")this.emit({type:"ready"});else if(a==="failed"&&!l.ok&&r===null&&!this.disposed){let e=l.error.requestId??null;this.emit({type:"error",code:l.error.code,requestId:e,context:Ke(this.errorContext,"runtime",e)})}/* @__PURE__ */
|
|
49
|
-
return Object.freeze({status:a,durationMs:u,session:l,entitlements:o,...s?{chat:s}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",Fc(t),()=>this.buildChatController(t),Dc,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function Fc(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function Dc(e){e.dispose()}function Lc(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function Bc(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function Vc(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function Hc(e){return e.ok?e:err(Vc(e.error))}function Uc(e){return{send:async(...t)=>Hc(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var Nc=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),$c=globalThis,Wc=$c[Nc]??($c[Nc]=t.createContext(null));Wc.displayName??="EverfurContext";function qc(){let e=t.useContext(Wc);if(e===null)throw new b("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return qc().handle}var Gc=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Kc=globalThis,Yc=Kc[Gc]??(Kc[Gc]=t.createContext(Mo));Yc.displayName??="EverfurThemeContext";function useEverfurTheme(){return t.useContext(Yc)}var Qc=()=>()=>{},Zc=()=>null;function Xc(e,r){return t.useSyncExternalStore(r?.subscribe??Qc,r?.get??Zc,r?.get??Zc)??e}function EverfurThemeProviderCore(e){let{runtime:r}=qc(),n=r.entitlements,i=t.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot),l=e.seams.useColorScheme(),o=e.seams.useReducedMotion(),s=e.seams.useTextScale(),a=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,c=e.seams.typeProfile,d=e.seams.platformMonoFamily?.(),f=e.seams.isFontRegistered,h=e.clientTheme?Jc(e.clientTheme):"",p=t.useMemo(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[h]),g=Xc(i.branding??null,r.sdkConfigHost?.branding),m=t.useMemo(()=>resolveTheme({branding:g,clientOverride:p,colorScheme:l,reducedMotion:o,textScale:s,scaleTypeSizes:u,highContrast:a,...c===void 0?{}:{typeProfile:c},...d===void 0?{}:{platformMonoFamily:d},...f===void 0?{}:{isFontRegistered:f}}),[g,p,l,o,s,u,c,a,d,f]);e.seams.useResolvedTheme?.(m);let b=e.seams.isDevelopment;return t.useEffect(()=>{b===void 0||!ed(b)||ls(themeAdjustments({branding:g,clientOverride:p,colorScheme:l}))},[b,g,p,l]),t.createElement(Yc.Provider,{value:m},e.children)}function Jc(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function ed(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:r,user:n,activePet:i,theme:l,warmUp:o,children:s,seams:a}=e,u=`${r?.publishableKey??""}|${r?.apiBaseUrl??""}|${r?.contractVersion??""}`,c=t.useRef(null),d=t.useRef(null),f=t.useRef(r?.onEvent);f.current=r?.onEvent;let h=t.useRef(e=>{f.current?.(e)}),[p,g]=t.useReducer(e=>e+1,0),m=t.useRef(null),b=t.useRef(void 0),y=n?.userRef??null;b.current!==y&&(b.current!==void 0&&(m.current=null),b.current=y);let v=m.current!==null?m.current.user:n??null,x=t.useRef(null),w=t.useRef(void 0),k=i??null;w.current!==k&&(w.current!==void 0&&(x.current=null),w.current=k);let C=x.current!==null?x.current.pet:i??null;(c.current===null||c.current.key!==u||c.current.runtime.isDisposed)&&(c.current!==null&&!c.current.runtime.isDisposed&&(d.current=c.current.runtime),c.current={key:u,runtime:createEverfurRuntime({config:td(a.withDefaults?a.withDefaults(r):r,h.current),user:v,activePet:C,theme:l??null},{platform:a.platform,...a.eventSourceFactory?{eventSourceFactory:a.eventSourceFactory}:{}})});let S=c.current.runtime,j=t.useRef(null);t.useEffect(()=>{let e=c.current?.runtime;e===void 0||!e.isDisposed||j.current!==e&&(j.current=e,g())}),t.useEffect(()=>{let e=d.current;e!==null&&(d.current=null,e.dispose())});let _=v?.userRef??null;t.useLayoutEffect(()=>{S.setUser(v)},[S,_]),t.useLayoutEffect(()=>{S.setActivePet(C)},[S,C]);let R=t.useRef(null);t.useEffect(()=>(R.current===S&&(R.current=null),()=>{R.current=S,rd(()=>{R.current===S&&(R.current=null,S.dispose())})}),[S]),t.useEffect(()=>{o==="onMount"&&S.prepare(C===null?{}:{petRef:C})},[S,o,_,C]);let T=t.useMemo(()=>({setUser:e=>{m.current={user:e},S.setUser(e),g()},setActivePet:e=>{x.current={pet:e},S.setActivePet(e),g()},open:e=>S.open(e),prepare:e=>S.prepare(e),registerPet:(e,t)=>S.registerPet(e,t),updatePet:(e,t)=>S.updatePet(e,t),deletePet:e=>S.deletePet(e),eraseUserData:()=>S.eraseUserData(),logout:()=>{m.current={user:null};let e=S.logout();return g(),e}}),[S,g]),I=t.useMemo(()=>({runtime:S,handle:T,userRef:_,activePet:C,scopeEpoch:S.scopeEpoch,publishableKey:nd(r)}),[S,T,_,C,p,u]),z=t.createElement(EverfurThemeProviderCore,{clientTheme:l??null,seams:a.theme,children:s});return t.createElement(Wc.Provider,{value:I},a.wrap?a.wrap(z):z)}function td(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function rd(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function nd(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var id=2;function ld(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<id)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function od(){let e=d.default;return(t,r)=>{let n=globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.chatCards.v1")]?.tap?.(t,r),i=new e(t,{method:r.method,headers:n?{...r.headers,...n.headers}:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return n?.watch(i),Object.assign(i,{getResponseHeader:e=>ld(i,e)})}}function sd(){let e=r.useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}function ad(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function ud(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=true,t=r.AccessibilityInfo?.isReduceMotionEnabled;if(typeof t=="function"){let i=t.call(r.AccessibilityInfo);i!=null&&typeof i.then=="function"&&i.then(t=>{e&&n(t===true)},()=>{})}let i=r.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",e=>n(e===true));return()=>{e=false,i?.remove?.()}},[]),e}function cd(){let e=r.PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(r.PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function dd(e){let t=r.Dimensions?.addEventListener;if(typeof t!="function")return()=>{};let n=t.call(r.Dimensions,"change",e);return()=>n?.remove?.()}function fd(){return t.useSyncExternalStore(dd,cd,cd)}function hd(){try{let e=r.Platform?.OS;return typeof e=="string"?e:null}catch{return null}}function pd(){return hd()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function gd(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=true,{query:t,event:i}=pd(),l=r.AccessibilityInfo?.[t];if(typeof l!="function")return()=>{};try{let t=l.call(r.AccessibilityInfo);ad(t)&&Promise.resolve(t).then(t=>{e&&n(t===!0)},()=>{})}catch{}let o=r.AccessibilityInfo?.addEventListener,s=typeof o=="function"?o.call(r.AccessibilityInfo,i,e=>n(e===true)):void 0;return()=>{e=false,s?.remove?.()}},[]),e}function md(){return hd()==="ios"?"Menlo":_o}function bd(){return globalThis.__DEV__!==false}var yd=/* @__PURE__ */new Set;function vd(e){if(!bd()||yd.has(e))return;yd.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function xd(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t)}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let i=n.includes(e);return i||vd(e),i}var wd=/* @__PURE__ */new Set;function kd(e){let t=[];return e.type.fontSources.length>0&&t.push("fontSources"),Object.values(e.type.fontUrls).some(e=>typeof e=="string"&&e.length>0)&&t.push("fontUrls"),t}var Cd=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function Sd(e){if(!bd())return;let t=kd(e).filter(e=>!wd.has(e));if(t.length===0)return;for(let e of t)wd.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>Cd[e]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function jd(e){t.useEffect(()=>{try{Sd(e)}catch{}},[e])}var _d=/* @__PURE__ */Object.freeze({useColorScheme:sd,useReducedMotion:ud,useTextScale:fd,useHighContrast:gd,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:md,isFontRegistered:xd,useResolvedTheme:jd,isDevelopment:bd});function Rd(e){return t.createElement(n.SafeAreaProvider,null,e)}var Td=/* @__PURE__ */Object.freeze({platform:"react-native",...r.Platform.OS==="web"?{}:{eventSourceFactory:od()},wrap:Rd,theme:_d});function EverfurProvider(e){return t.createElement(EverfurProviderCore,{...e,seams:Td})}function useCapability(e){let{runtime:r}=qc(),n=r.entitlements,i=t.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot);return t.useMemo(()=>decideCapability(e,i.decisions,{isPending:i.isPending}),[e,i])}function Id(e){let{runtime:r}=qc(),n=r.entitlements,i=t.useCallback(e=>n===void 0?()=>{}:n.subscribe(e),[n]),l=t.useCallback(()=>{if(n===void 0)return false;let t=n.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[n,e]);return t.useSyncExternalStore(i,l,l)}var zd=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[zd[t]]}}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[zd[t]]};let i=face(e,t);return i.fontWeight===void 0||n===null?i:{fontFamily:i.fontFamily,fontWeight:n}}function Pd(e){return e<=450?"regular":e<=650?"medium":"bold"}var Ed={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=Od.get(e);r===void 0&&(r=/* @__PURE__ */new Map,Od.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=Ad(e,t);return r.set(t,i),i}var Od=/* @__PURE__ */new WeakMap;function Ad(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,i=Pd(Number(n)),l=r.face==="mono"?face(e,Ed[i]):r.face==="heading"?headingFace(e,i):face(e,i),o=r.face==="heading"?e.type.headingWeight??n:n,s=l.fontWeight===void 0?l:{fontFamily:l.fontFamily,fontWeight:o},a=r.size,u={...s,fontSize:a,lineHeight:Math.round(a*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(a*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function Md(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:n,...i}){let l=useEverfurTheme(),o=n===void 0?void 0:l.type.roles[n],s=Md(l.type,e??o?.tier??"content"),a=n===void 0?i:{...i,style:[{...textRole(l,n),color:l.color.text.primary,flexShrink:1},i.style]};return t.createElement(r.Text,s===void 0?a:{maxFontSizeMultiplier:s,...a})}var Fd=t.forwardRef(function(e,n){return t.createElement(r.TextInput,{...e,...n===null?{}:{ref:n}})});var Dd=class extends t.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:r,resetKey:n}){return t.createElement(Dd,{fallback:r,resetKey:n,children:t.createElement(RenderHost,{render:e})})}var Ld=48;function Bd(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:r,children:n,renderDisabled:i,renderPending:o,style:s}=e,a=useCapability(r),u=t.useMemo(()=>Bd(a),[a]);switch(u){case"enabled":return n;case"pending":return o?/* @__PURE__ */l.jsx(HostRender,{render:o,fallback:/* @__PURE__ */l.jsx(PendingSkeleton,{capability:r,style:s})}):/* @__PURE__ */l.jsx(PendingSkeleton,{capability:r,style:s});case"disabled":return i?/* @__PURE__ */l.jsx(HostRender,{render:()=>i(a),fallback:/* @__PURE__ */l.jsx(OffState,{decision:a,style:s}),resetKey:a}):/* @__PURE__ */l.jsx(OffState,{decision:a,style:s});default:return assertNever(u)}}function PendingSkeleton({capability:e,style:n}){let i=useEverfurTheme(),o=t.useMemo(()=>Vd(i),[i]);/* @__PURE__ */
|
|
50
|
-
return l.jsx(r.View,{style:[o.offstate,n],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */l.jsx(r.View,{style:o.skeletonBar})})}function OffState({decision:e,style:n}){let i=useEverfurTheme(),o=t.useMemo(()=>Vd(i),[i]),s=e.disabled?.reason??"";/* @__PURE__ */
|
|
51
|
-
return
|
|
52
|
-
return
|
|
53
|
-
return
|
|
54
|
-
return Object.freeze(
|
|
55
|
-
return Object.freeze(
|
|
56
|
-
return Object.freeze(n)}
|
|
57
|
-
return Object.freeze(s)}function Oh(e){return e.sender?.displayName??mf.senderVet}function Ah(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var Mh=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 Fh(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function Dh(e,t,r){let n=t.chatFollowUpsExcludeTelevet,i=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&i===Rh&&!n)return;if(i<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let l=e?.exclude,o=n?e=>Mh.test(e)||Fh(l,e):l;return{...e??{},count:i,...o!==void 0?{exclude:o}:{}}}var Lh="pet_not_registered";function Bh(e){return e!=null&&e.reasonCode===Lh}var Vh=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function Hh(e,r,n){let{runtime:i,userRef:l,scopeEpoch:o}=qc(),s=t.useCallback((e,t)=>{let r=i.registry.services.authFor(l);return al(sl(i,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[i,l,o]),a=t.useMemo(()=>r===void 0?null:ul(r),[r]),[u,c]=t.useState({key:null,status:"idle",error:null,registered:null}),d=t.useRef(0),f=t.useRef(n);f.current=n;let h=e===null||a===null?null:`${String(l)}|${o}|${e}|${a}`,p=t.useCallback(()=>{if(e===null||r===void 0||h===null)return;let t=++d.current;c({key:h,status:"registering",error:null,registered:null}),s(e,r).then(e=>{t===d.current&&(e.ok?(c({key:h,status:"registered",error:null,registered:e.value}),f.current?.()):c({key:h,status:"failed",error:e.error,registered:null}))})},[s,e,h]);t.useEffect(()=>{if(h===null){d.current+=1;return}return p(),()=>{d.current+=1}},[h,p]);let g=t.useCallback(()=>{u.status==="failed"&&p()},[u.status,p]);return t.useMemo(()=>h===null?Vh:u.key!==h?{status:"registering",error:null,registered:null,retry:g}:{status:u.status,error:u.error,registered:u.registered,retry:g},[h,u,g])}var Uh=/* @__PURE__ */Object.freeze({});function Nh(e){let[r,n]=t.useState(Uh),i=t.useRef(null),l=t.useRef([]);l.current=e.map(e=>e.id),t.useEffect(()=>{if(e.length===0){i.current=null,n(e=>e===Uh?e:Uh);return}let t=i.current;if(t===null)return;let r=e.find(e=>e.role==="user"&&!t.known.has(e.id));r!==void 0&&(i.current=null,n(e=>({...e,[r.id]:t.images})))},[e]);let o=t.useCallback(e=>{i.current=e.length===0?null:{images:e,known:new Set(l.current)}},[]);return t.useMemo(()=>({byMessage:r,stage:o}),[r,o])}var $h=/* @__PURE__ */new WeakSet;function Wh(){let e=makeEverfurError("internalError",{retryable:true});return $h.add(e),err(e)}function qh(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&$h.has(t)}var Gh=500;function Kh(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,Gh):null}function Yh(e,r,n,i){let l=Kh(n),o=l===null?null:i!==void 0?`key:${String(i)}`:`prompt:${l}`,s=t.useRef(e);s.current=e;let a=t.useRef(null),u=t.useRef(null),c=t.useRef(o);c.current=o,t.useEffect(()=>{if(l===null||o===null||r||a.current===o||u.current===o)return;let e=s.current;if(e===void 0)return;u.current=o;let t=e=>{u.current===o&&(u.current=null),!qh(e)&&c.current===o&&(a.current=o)};Promise.resolve(e(l)).then(t,()=>t(void 0))},[l,o,r,e])}var Qh=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),Zh=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),Xh=/* @__PURE__ */Object.freeze({...Qh,markRead:true}),Jh=/* @__PURE__ */Object.freeze({...Zh,markRead:true});function ep(e,t){return e?t?Xh:Qh:t?Jh:Zh}function tp(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:sh(()=>r()!==!1)===true}function rp(e,r){let n=t.useRef({target:e,isVisible:r});n.current={target:e,isVisible:r};let i=t.useRef(e.isStreaming);t.useEffect(()=>{let t=i.current;if(i.current=e.isStreaming,!t||e.isStreaming)return;let{target:r,isVisible:l}=n.current;r.status!=="complete"||r.conversationId===null||r.unreadCount===null||!l()||r.markRead()},[e.isStreaming])}var np=3e5;function ip(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function lp(e,r,n){let i=t.useRef(r);i.current=r;let l=t.useRef(null),o=t.useRef(null),s=t.useRef(false),a=t.useRef(0),u=t.useRef(0),c=t.useRef(3e4),d=()=>e?.isOffline===void 0?false:sh(()=>e.isOffline?.()===!0)===true,f=d(),h=t.useRef(()=>{});h.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:f}=i.current,p=gr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:f===true,isOffline:d(),lastRefresh:l.current,now:Date.now()});if(p.action==="skip")return;if(p.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(s.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,l.current={conversationId:p.conversationId,at:Date.now()},n===void 0)return;s.current=true;let g=e=>{s.current=false,ip(e)?(a.current=Math.min(a.current===0?c.current*2:a.current*2,np),u.current=Date.now()+a.current):(a.current=0,u.current=0);let t=o.current;t!==null&&h.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},t.useEffect(()=>{if(r.isTurnInFlight||f)return;let e=o.current;e!==null&&h.current(e)},[r.isTurnInFlight,f]),t.useEffect(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=sh(()=>e(()=>{h.current(r)}));typeof n=="function"&&t.push(n)};return r(e.onForeground?.bind(e),"foreground"),r(e.onOnline?.bind(e),"foreground"),r(e.onAnnounced?.bind(e),"announced"),()=>{for(let e of t)sh(e)}},[e]);let p=n?.intervalMs??null,g=n?.isVisibleFallback;t.useEffect(()=>{if(e===void 0||p===null||!Number.isFinite(p)||p<=0)return;c.current=p;let t=setInterval(()=>{Date.now()<u.current||tp(e,g)&&h.current("poll")},p);return()=>clearInterval(t)},[e,p,g])}var op=/^efch_[A-Za-z0-9_-]{43}$/,sp="efch";function ap(e){return typeof e=="string"&&op.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${sp}=`))continue;let e=r.slice(sp.length+1);return ap(e)?e:null}return null}var up=128,cp=/[\u0000-\u001f\u007f]/;function dp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function fp(e){return typeof e!="string"||e.length===0||e.length>up||cp.test(e)||e.includes("://")?null:e}function hp(e){if(e===null)return null;let t=e.conversation_id,r=fp(e.pet_ref);return typeof t!="string"||!tn(t)||r===null?null:{conversationId:t,petRef:r}}function pp(e,t,r){return ap(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(hp(dp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(Rr("internalError",false))):Promise.resolve(ok(null))}function gp(e,r){let n=r?.runtime??null,i=r?.userRef??null,l=ap(e)?e:null,o=l===null||i===null?null:`${String(i)}|${l}`,[s,a]=t.useState(null);return t.useEffect(()=>{if(o===null||l===null||i===null||n===null)return;let e=true,t=n.registry.services;return pp(t.authFor(i),l,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||a({key:o,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[o,n,l,i]),s!==null&&s.key===o?s.target:void 0}function mp(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function bp(e,r,n){let i=mp(r),l=r?.kind==="chat",o=r?.petRef??null,s=l&&!n.pinned&&o!==null&&n.petRef!==null&&o!==n.petRef,a=t.useRef({openCheckin:e,target:r,selectPet:n.selectPet});a.current={openCheckin:e,target:r,selectPet:n.selectPet};let u=t.useRef(null),c=t.useRef(null),d=n.petRef;t.useEffect(()=>{if(i===null||u.current===i)return;let{openCheckin:e,target:t,selectPet:r}=a.current;if(s&&o!==null){if(c.current?.key!==i){c.current={key:i,from:d},r(o);return}d!==c.current.from&&(u.current=i);return}l&&!n.ready||(u.current=i,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[i,l,s,o,d,n.ready])}var yp=/* @__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 vp(e){let t=e?.replace(/\s+/g," ").trim();return t||yp.untitled}function xp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function wp(e){let t=xp(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?yp.newReply.replace("{date}",t):t}function kp(e,t){return t?`${yp.countLabel}${yp.countSeparator}${e}`:yp.countLabel}function Cp(e){return`${e.unreadCount!==null&&e.unreadCount>0?yp.unreadPrefix:""}${yp.openConversation} ${vp(e.title)}`}function Sp(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function jp(e,t){let r=Sp(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=Sp(vp(t.title)),i=e.indexOf(r);if(i<0)continue;let l=i===0?0:e.charAt(i-1)===" "?1:2;n[l]?.push(t)}return n.flat()}function _p(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function Rp(e){let[r,n]=t.useState(false),[i,l]=t.useState(""),o=e.listConversations,s=t.useRef(0),[a,u]=t.useState(()=>_p(o)),c=a.scope===o?a:_p(o);t.useEffect(()=>(s.current+=1,n(false),l(""),u(_p(o)),()=>{s.current+=1}),[o]);let d=t.useCallback(async t=>{let r=++s.current,n=t!==void 0;u(e=>({...e,scope:o,loading:!n,loadingMore:n,error:null}));let i=await e.listConversations(t?{cursor:t}:void 0);if(r===s.current){if(!i.ok){u(e=>({...e,loading:false,loadingMore:false,error:i.error.displayMessage}));return}u(e=>{let r=t&&e.scope===o?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:o,loading:false,loadingMore:false,error:null,rows:[...r,...i.value.conversations.filter(e=>!n.has(e.id))],cursor:i.value.nextCursor===t?null:i.value.nextCursor}})}},[e.listConversations,o]),f=()=>{n(true),l(""),d()},h=()=>{s.current+=1,n(false)},p=async t=>{let r=++s.current;u(e=>({...e,loading:true,error:null}));let i=await e.resumeConversation(t);r===s.current&&(u(e=>({...e,loading:false,error:i.ok?null:i.error.displayMessage})),i.ok&&n(false))},g=async()=>{let t=s.current,r=await e.loadOlderMessages();t===s.current&&!r.ok&&u(e=>({...e,error:r.error.displayMessage}))},m=()=>{e.newConversation(),s.current+=1,n(false)},b=()=>{c.cursor===null||c.loading||c.loadingMore||i.trim().length>0||d(c.cursor)},y=t.useMemo(()=>jp(c.rows,i),[c.rows,i]),v=i.trim().length>0;return{...c,open:r,show:f,close:h,load:d,resume:p,earlier:g,newConversation:m,loadMore:b,query:i,setQuery:l,searching:v,filtered:y,emptyKind:c.rows.length===0?"empty":"noMatch"}}var Tp="#111111",Ip="#FFFFFF",zp=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:Tp,pillColor:Ip,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:Tp,pillColor:Ip,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Tp,pillColor:Ip,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Tp,pillColor:Ip,showsVetAction:false})});function Pp(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function Ep(e){return bf(mf.urgencyGeneralReason,{petName:e?.trim()||mf.emptyTitlePetFallback})}function Op(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let i=n.urgencyLevel;return i?{messageId:n.id,level:i,reason:Ap(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Ep(t)}:null}return null}function Ap(e){return typeof e=="string"&&e.trim().length>0?e:null}function Mp(e){let r=e===null?null:Pp(e),[n,i]=t.useState(null),[l,o]=t.useState(false);t.useEffect(()=>o(false),[r]);let s=e!==null&&(l||!(n!==null&&n===r)),a=e===null?null:zp[e.level],u=e!==null&&!s&&e.level!=="general",c=t.useCallback(()=>{r!==null&&i(r),o(false)},[r]),d=t.useCallback(()=>o(true),[]);return t.useMemo(()=>({source:e,tier:a,signature:r,showBanner:s,showCompactIcon:u,showVetAction:s&&a!==null&&a.showsVetAction,dismissLabel:a===null?null:bf(mf.dismissBanner,{label:a.label}),dismiss:c,expand:d}),[e,a,r,s,u,c,d])}var Fp=()=>globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.chatCards.v1")]??={loader:null,lazy:null};var Dp=Fp;function registerEverfurChatCards(e){let r=Dp();r.loader=e;let n=e&&Promise.resolve().then(e).then(e=>typeof e.ServerCards=="function"?e.ServerCards:NONE3,()=>NONE3);r.lazy=n&&t.lazy(async()=>({default:await n}))}var NONE3=()=>null,Lp=t.createContext(null);function ServerCardsSlot({message:e}){let r=t.useContext(Lp),n=Dp(),i=e.a2ui??n.frames?.get(e.responseId),l=n.lazy;return i===void 0||r===null||l===null?null:t.createElement(t.Suspense,{fallback:null},t.createElement(l,{message:e,a2ui:i,host:r}))}var Bp="everfur.com",Vp=2048,Hp=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function Up(e){if(!Array.isArray(e))return[];let t=/* @__PURE__ */new Set;for(let r of e){if(typeof r!="string")continue;let e=r.trim().toLowerCase();e.length<=253&&Hp.test(e)&&t.add(e)}/* @__PURE__ */
|
|
58
|
-
return Object.freeze([...t])}function Np(e,t){if(e===Bp||e.endsWith(`.${Bp}`))return true;for(let r of t)if(r.startsWith("*.")?e.endsWith(r.slice(1)):e===r)return true;return false}function $p(e,t){if(typeof e!="string"||e.length===0||e.length>Vp||!/^https:\/\//i.test(e))return null;let r=N(e);return r===null||r.protocol!=="https:"||r.username!==""||r.password!==""||r.port!==""?null:Np(r.hostname,t)?r.href:null}function Wp(e){try{Promise.resolve(r.Linking.openURL(e)).catch(()=>{})}catch{}}var qp=t.createContext(null);function Gp(){return t.useContext(qp)??void 0}function MessageLinksScope({linkHosts:e,onOpenUrl:r,children:n}){let i=e===false?null:Array.isArray(e)?e.join(`\n`):"",l=t.useMemo(()=>{if(i===null)return null;let e=Up(i===""?[]:i.split(`\n`));/* @__PURE__ */
|
|
59
|
-
return Object.freeze(
|
|
60
|
-
return
|
|
61
|
-
|
|
62
|
-
/* @__PURE__ */
|
|
63
|
-
/* @__PURE__ */
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
/* @__PURE__ */
|
|
67
|
-
|
|
68
|
-
return
|
|
69
|
-
return
|
|
70
|
-
return
|
|
71
|
-
return
|
|
72
|
-
|
|
73
|
-
/* @__PURE__ */
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
/* @__PURE__ */
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
/* @__PURE__ */
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
/* @__PURE__ */
|
|
83
|
-
/* @__PURE__ */
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
/* @__PURE__ */
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
/* @__PURE__ */
|
|
90
|
-
/* @__PURE__ */
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
/* @__PURE__ */
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
/* @__PURE__ */
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
/* @__PURE__ */
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
/* @__PURE__ */
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
/* @__PURE__ */
|
|
106
|
-
|
|
107
|
-
return
|
|
108
|
-
return
|
|
109
|
-
|
|
110
|
-
/* @__PURE__ */
|
|
111
|
-
/* @__PURE__ */
|
|
112
|
-
|
|
113
|
-
return
|
|
114
|
-
|
|
115
|
-
/* @__PURE__ */
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
/* @__PURE__ */
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
/* @__PURE__ */
|
|
122
|
-
/* @__PURE__ */
|
|
123
|
-
/* @__PURE__ */
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
/* @__PURE__ */
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
/* @__PURE__ */
|
|
130
|
-
/* @__PURE__ */
|
|
131
|
-
/* @__PURE__ */
|
|
132
|
-
/* @__PURE__ */
|
|
133
|
-
/* @__PURE__ */
|
|
134
|
-
/* @__PURE__ */
|
|
135
|
-
/* @__PURE__ */
|
|
136
|
-
/* @__PURE__ */
|
|
137
|
-
/* @__PURE__ */
|
|
138
|
-
|
|
139
|
-
return
|
|
140
|
-
|
|
141
|
-
/* @__PURE__ */
|
|
142
|
-
/* @__PURE__ */l.jsx(StopGlyph,{size:wb,color:a.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */l.jsx(MicGlyph,{size:xb,color:a.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:n}){let i=t.useRef(new r.Animated.Value(1)).current;return t.useEffect(()=>{if(n)return;let e=r.Animated.loop(r.Animated.sequence([r.Animated.timing(i,{toValue:Sb,duration:Cb/2,useNativeDriver:true}),r.Animated.timing(i,{toValue:1,duration:Cb/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[i,n]),/* @__PURE__ */l.jsx(r.Animated.View,{style:[e,{opacity:i}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function _b(e){let t=e.color,n=e.type.tierSizes.compact.micro;return r.StyleSheet.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:n,lineHeight:n+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:Rm,height:Rm,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:jb},pulse:{position:"absolute",top:kb,right:kb,bottom:kb,left:kb,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var Rb=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function Tb(){let e=globalThis,t=e[Rb];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[Rb]=r,r}function registerEverfurDictation(e){let t=Tb();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function Ib(){return Tb().version??0}function zb(e){let t=Tb(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function Pb(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.start=="function"&&typeof t.isRecognitionAvailable=="function"&&typeof t.addListener=="function"}function Eb(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function Ob(){let e=Tb();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||r.Platform.OS!=="ios"&&r.Platform.OS!=="android")return e.memo;let n=optionalModule("expo-speech-recognition",()=>({box:Eb(t())}),e=>typeof e=="object"&&e!==null&&Pb(e.box));return n.available&&(e.memo=n.module.box),e.memo}function Ab(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function Mb(){try{return Intl.DateTimeFormat().resolvedOptions().locale||Db}catch{return Db}}function Fb(e){return e.replace(/_/g,"-").toLowerCase()}var Db="en-US";function Lb(e=Mb()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return Db;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:Db}function Bb(e,t){if(t.length===0)return null;let r=e=>t.find(t=>Fb(t)===Fb(e));return r(e)??r(Db)??t.find(e=>Fb(e).startsWith("en-"))??null}async function Vb(e,t){if(r.Platform.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return Bb(t,r??[])??t}catch{return t}}async function Hb(e,t){let n=false;try{n=e.supportsOnDeviceRecognition()===!0}catch{n=false}if(!n)return"network";if(r.Platform.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=Fb(t);return(r??[]).some(e=>Fb(e)===n)?"on_device":"network"}catch{return"network"}}function Ub(){return r.Platform.OS!=="android"?true:Number(r.Platform.Version)>=Nb}var Nb=33;function $b(e,t,r){return{lang:t,interimResults:true,continuous:Ub(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var Wb=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),qb=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function Gb(e){return qb.has(e)}var Kb=600,Yb=3;function Qb(e,t,r){if(Wb.has(r))return null;let n=Gb(r)?Kb:0;return r==="language-not-supported"&&Fb(t)!==Fb(Db)?{mode:"network",lang:Db,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function Zb(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function Xb(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var Jb=55e3,ey=3e3,ty=1e3;function ry(e){return ny.has(e)||Gb(e)}var ny=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),iy=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function ly(e){return e.replace(/\s+/g," ").trim()}function oy(e,t,r){let n=ly(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function sy(e){return ly([...e.committed,e.interim].join(" "))}function ay(e,t,r,n=Date.now){let i=0,l=null,o=Number.NEGATIVE_INFINITY,s=e=>l!==null&&l.token===e?l:null;function a(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){a(e),e.autoStopTimer!==null&&clearTimeout(e.autoStopTimer),e.graceTimer!==null&&clearTimeout(e.graceTimer),e.retryTimer!==null&&clearTimeout(e.retryTimer),e.autoStopTimer=null,e.graceTimer=null,e.retryTimer=null,l===e&&(l=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&sy(e.transcript)===""&&e.launchedAt-o<ty}function d(e){return e.mode??"none"}function f(e,t){Ug(r(),"chat_dictation_completed",{mode:d(e),duration_ms:e.startedAt===null?0:Math.max(0,n()-e.startedAt),char_count:t.length})}function h(e,n){Ug(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(s(e.token)===null)return;u(e);let r=sy(e.transcript),n=e.errorCode;if(n!==null&&!(r&&ry(n))){h(e,Zb(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(i){i.subscriptions=[e.addListener("start",()=>{s(i.token)!==null&&(i.sawStart=true,i.startedAt===null&&(i.startedAt=n()),Ug(r(),"chat_dictation_started",{mode:d(i)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(s(i.token)===null)return;let r=e?.results?.[0]?.transcript??"";i.transcript=oy(i.transcript,r,e?.isFinal===true),t.onText(sy(i.transcript))}),e.addListener("error",e=>{if(s(i.token)===null)return;let t=e?.error??"unknown";if(i.userStopped&&(t==="aborted"||Gb(t)))return;let r=sy(i.transcript)==="",n=i.mode!==null&&!i.userStopped&&r&&i.retries<Yb?Qb(i.mode,i.lang,t):null;if(n!==null){i.pendingRetry=n;return}i.errorCode===null&&(i.errorCode=t)}),e.addListener("end",()=>{if(s(i.token)!==null&&!c(i)){if(i.pendingRetry!==null){let e=i.pendingRetry;if(i.pendingRetry=null,i.retries+=1,i.lang=e.lang,e.delayMs<=0){m(i,e.mode);return}a(i),i.retryTimer=setTimeout(()=>{i.retryTimer=null,!(s(i.token)===null||i.userStopped)&&m(i,e.mode)},e.delayMs);return}p(i)}})]}function m(t,r){a(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=iy,t.errorCode=null,g(t);try{e.start($b(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function b(t){let r=await Xb(e);if(s(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await Vb(e,t.lang),s(t.token)===null)return;let n=await Hb(e,t.lang);s(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),Jb),m(t,n))}function y(r){if(!(s(r.token)===null||r.userStopped)){if(r.userStopped=true,r.pendingRetry=null,r.mode===null||r.retryTimer!==null){u(r),t.onStatus("idle");return}r.graceTimer=setTimeout(()=>p(r),ey);try{e.stop()}catch{p(r)}}}return{start(e){if(l!==null)return;let r={token:++i,phrases:e,lang:Lb(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:iy,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};l=r,t.onStatus("starting"),b(r)},stop(){l!==null&&y(l)},cancel(){let r=l;if(r===null)return;let i=r.mode!==null&&r.retryTimer===null,s=sy(r.transcript);if(u(r),t.onStatus("idle"),!!i){s&&f(r,s),o=n();try{e.abort()}catch{}}},isActive:()=>l!==null,isPreparing:()=>l!==null&&l.mode===null}}function uy({enabled:e,input:n,setInput:i,phrases:l,maxLength:o,telemetry:s}){let a=t.useSyncExternalStore(zb,Ib,Ib),u=t.useMemo(()=>e?Ob():null,[e,a]),c=t.useMemo(()=>Ab(u),[u]),[d,f]=t.useState("idle"),[h,p]=t.useState(null),[g,m]=t.useState(0),b=t.useRef(n);b.current=n;let y=t.useRef(i);y.current=i;let v=t.useRef(s);v.current=s;let x=t.useRef(""),w=t.useRef(o);w.current=o;let k=t.useRef(null);u!==null&&k.current?.mod!==u&&(k.current?.controller.cancel(),k.current={mod:u,controller:ay(u,{onStatus:e=>{f(t=>e==="idle"&&t==="error"?t:e)},onText:e=>y.current(Bg(x.current,e,w.current)),onError:e=>{p(e),f("error")}},()=>v.current)});let C=u===null?null:k.current?.controller??null,S=t.useCallback(()=>{C?.cancel()},[C]),j=t.useCallback(()=>{if(C!==null){if(C.isActive()){C.stop();return}p(null),m(0),x.current=b.current,C.start(l)}},[C,l]);t.useEffect(()=>{if(d!=="listening")return;let e=Date.now();m(0);let t=setInterval(()=>m(Date.now()-e),1e3);return()=>clearInterval(t)},[d]),t.useEffect(()=>{if(d!=="error")return;let e=setTimeout(()=>{p(null),f("idle")},Lg);return()=>clearTimeout(e)},[d]),t.useEffect(()=>{if(C===null)return;let e=null;try{e=r.AppState.addEventListener("change",e=>{e==="background"&&!C.isPreparing()&&C.cancel()})}catch{}return()=>{e?.remove(),C.cancel()}},[C]);let _=e&&c;return t.useEffect(()=>{_||C?.cancel()},[_,C]),{supported:_,status:d,active:d==="starting"||d==="listening",error:h,elapsedMs:g,toggle:j,cancel:S}}var cy=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function dy(){let e=globalThis,r=e[cy];if(r!==void 0)return r;let n=t.createContext(true);return e[cy]=n,n}var fy=dy();function hy(){return t.useContext(fy)}var py=/* @__PURE__ */Object.freeze(["photo"]),gy=52,my=1.5,by=10,yy=14,vy=10,xy=40,wy=20,ky=.3,Cy=2.5,Sy=1,jy=1.5,_y=38,Ry=22,Ty=3;function Iy(e,t,r,n="ask",i=false){let l=typeof t=="string"&&t.trim()!=="";return r&&l&&n!=="urgent"?vf(mf.placeholder,t):e!==null?!i||!e.includes("{pet}")?e:l?e.split("{pet}").join(t.trim()):vf(mf.placeholder,t):n==="urgent"?mf.placeholderUrgentWeb:n==="followUp"?mf.placeholderFollowUpWeb:vf(mf.placeholder,t)}function ComposerWithAttachments({attachments:e,...r}){let n=t.useMemo(()=>createRnChatAttachmentTransport(),[]),i=useChatAttachments({maxPerMessage:e.maxPerMessage??Dn,transport:n}),o=t.useMemo(()=>({state:i,sources:e.sources??py,pick:e.pick}),[i,e.sources,e.pick]);/* @__PURE__ */
|
|
143
|
-
return l.jsx(Composer,{...r,attachments:o})}function Composer({send:e,stop:n,isStreaming:i,conversationId:o,attachments:s,seed:a,draftStore:u,onStage:c,onPreview:d,petName:f,petBreed:h=null,mood:p="ask",dictation:g=false,telemetry:m=null,compact:b=false,petPlaceholder:y=false,dimEmptySend:v=false}){let{theme:x,styles:w}=yb(),k=t.useMemo(()=>My(x),[x]),C=t.useMemo(()=>Fy(x),[x]),S=ig(),[j,_]=Wg(e,o,a),[R,T]=t.useState(false),[I,z]=t.useState(false),P=t.useCallback(()=>z(true),[]),E=t.useCallback(()=>z(false),[]),[O,A]=t.useState(false);t.useEffect(()=>{A(false)},[o]);let M=Iy(x.meta.placeholder,f,y,p,x.meta.placeholderFillsPet===true),F=t.useMemo(()=>$g({name:f,breed:h}),[f,h]),D=uy({enabled:g,input:j,setInput:_,phrases:F,maxLength:gn,telemetry:m}),L=D.cancel,B=D.active;qg(u,o===null?null:String(o),j,_,B);let V=t.useRef(o);t.useEffect(()=>{V.current!==o&&(V.current=o,L())},[o,L]);let H=hy();t.useEffect(()=>{H||L()},[H,L]);let U=s?.state.uploading??false,N=s?.state.failed??false,$=U||N,W=s?.state.attachments??zy;wg(W.length,S);let q=t.useCallback(()=>{let t=j.trim();if(t.length===0||$||[...t].length>gn)return;B&&L();let r=s?.state.s3Keys??Py;s!==null&&r.length>0?(c(s.state.attachments.filter(e=>e.status==="uploaded").map(e=>({uri:e.previewUri,filename:e.filename}))),e(t,{imageS3Keys:r}),s.state.clear()):e(t),_(""),A(false)},[j,e,$,B,L,s,c]),G=t.useCallback(e=>{B&&L(),_(e)},[B,L,_]),K=t.useCallback(()=>{n()},[n]),Y=t.useCallback(e=>{T(false),s!==null&&(A(false),s.state.dismissRejected(),ch(s.pick,e).then(e=>{if(!e.ok){A(true);return}e.value!==null&&s.state.add(e.value)}))},[s]),Q=t.useMemo(()=>[...j.trim()].length>gn,[j]),Z=Q||$||j.trim().length===0,X=Q||$||v&&j.trim().length===0,J=s!==null&&W.length>=s.state.maxPerMessage,ee=x.slots.sendButton?.textColor??x.color.brandInk,te=x.slots.sendButton?.textColor??x.color.surface;/* @__PURE__ */
|
|
144
|
-
return
|
|
145
|
-
|
|
146
|
-
/* @__PURE__ */
|
|
147
|
-
/* @__PURE__ */
|
|
148
|
-
/* @__PURE__ */
|
|
149
|
-
/* @__PURE__ */l.jsx(Fd,{style:b?[w.input,k.input]:w.input,onFocus:P,onBlur:E,value:j,onChangeText:G,placeholder:M,placeholderTextColor:x.slots.composerInput?.textColor??x.color.text.placeholder,accessibilityLabel:mf.composerLabel,onSubmitEditing:q,returnKeyType:"send",...Ey,...b?Oy:null,blurOnSubmit:false,multiline:true,editable:true}),D.supported?/* @__PURE__ */l.jsx(DictationButton,{active:D.active,listening:D.status==="listening",elapsedMs:D.elapsedMs,onToggle:D.toggle}):null,i?/* @__PURE__ */l.jsx(r.Pressable,{onPress:K,accessibilityRole:"button",accessibilityLabel:mf.stop,style:w.sendControl,children:/* @__PURE__ */l.jsx(r.View,{style:b?k.disc:w.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */l.jsx(StopGlyph,{size:b?wy:qm,color:b?te:ee,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */l.jsx(r.Pressable,{onPress:q,disabled:Z,accessibilityRole:"button",accessibilityLabel:mf.send,accessibilityState:{disabled:Z,busy:U},style:[w.sendControl,X?b?k.dimmed:w.sendControlDisabled:null],children:b?/* @__PURE__ */l.jsx(r.View,{style:k.disc,testID:"everfur-send-disc",children:/* @__PURE__ */l.jsx(ArrowUpGlyph,{size:wy,color:te,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */l.jsx(r.View,{style:w.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */l.jsx(SendGlyph,{size:Wm,color:ee,testID:"everfur-send-glyph"})})})]})]})]})}var zy=/* @__PURE__ */Object.freeze([]),Py=/* @__PURE__ */Object.freeze([]),Ey=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),Oy=/* @__PURE__ */Object.freeze(r.Platform.OS==="web"?{rows:1}:{}),Ay=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function My(e){let t=e.color,n=e.slots.sendButton,i=textRole(e,"body").fontSize+Sy;return r.StyleSheet.create({bar:{marginTop:by,marginHorizontal:yy,marginBottom:vy,minHeight:gy,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:my,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:Cy,paddingLeft:8-(Cy-my),paddingRight:6-(Cy-my)},input:{fontSize:i,lineHeight:Math.round(i*jy),minHeight:Math.round(i*jy),...r.Platform.OS==="web"?{outlineStyle:"none"}:null},add:{width:_y,height:_y,borderRadius:_y/2},disc:{width:xy,height:xy,borderRadius:xy/2,alignItems:"center",justifyContent:"center",backgroundColor:n?.backgroundColor??t.text.primary,...Eg(n)},dimmed:{opacity:ky},tray:{marginHorizontal:yy,marginTop:by,paddingBottom:0}})}function Fy(e){return r.StyleSheet.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:r,activePet:n,scopeEpoch:i}=qc(),l=t.useMemo(()=>createPetsRepository(e.registry.services.authFor(r)),[e,r,i]),[o,s]=t.useState({repository:l,pets:[],loading:true,error:null}),a=o.repository===l?o:{pets:[],loading:true,error:null},u=t.useRef(0),c=t.useCallback(async()=>{let e=++u.current;s(e=>({...e,repository:l,loading:true,error:null,pets:e.repository===l?e.pets:[]}));let t=await l.list();e===u.current&&s(t.ok?{repository:l,pets:t.value,loading:false,error:null}:e=>({repository:l,pets:e.repository===l?e.pets:[],loading:false,error:t.error}))},[l]);t.useEffect(()=>(c(),()=>{u.current+=1}),[c]),t.useEffect(()=>dl(e,()=>{c()}),[e,c]);let d=t.useMemo(()=>n===null?null:a.pets.find(e=>e.petRef===n)??null,[n,a.pets]);return t.useMemo(()=>({pets:a.pets,activePet:d,loading:a.loading,error:a.error,refresh:c}),[a.pets,a.loading,a.error,d,c])}function Dy(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var Ly=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var By=false;function Vy(e,t){return t!==void 0?(sh(t,e),"onStartInApp"):Wd(e)==="presented"?"presenter":Yd(e)?"experience":(By||(By=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var Hy=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&Hy.includes(e)}var Uy="/widget/v1/televet/handoffs",Ny="/widget/v1/televet/availability",$y="/widget/v1/televet/chat-entry",Wy=/^[a-z0-9][a-z0-9_-]{0,39}$/,qy=/^[A-Za-z0-9_-]{22}$/;var Gy=32,Ky=128,Yy=64;function vetVisitErrorReasonOf(e){let t=e.httpStatus;switch(e.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 t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}function Qy(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Zy(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function Xy(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Wy.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let i=t?.entry;if(i!=null){if(i!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=i}let l=t?.visitRef,o=t?.intent,s=l!=null;if(s){let e=typeof l=="string"?l.trim():"";if(e.length<1||[...e].length>Yy)return{ok:false,message:`visitRef must be 1..${Yy} characters`};r.visit_ref=e}if(o!=null){if(!s)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${Hy.join(", ")}`};r.intent=o}return{ok:true,body:r}}function Jy(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!isVetVisitIntent(r)?null:/* @__PURE__ */Object.freeze({visitRef:t,intent:r})}function ev(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(ov(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,i){let l;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>Ky)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${Ky} characters`}));l=e}let o=Xy(l,i);if(!o.ok){let e=Qy(o.message);return e.ok?e:n(e.error)}let s=o.body,a=await t.send("televet.visit.handoff",{method:"POST",path:Uy,body:s},{idempotent:false,maxAttempts:1});if(!a.ok)return n(a.error);let u=tv(a.value),c=s.return_to!==void 0,d=c?a.value?.flow_id:void 0;if(c&&(typeof d!="string"||!qy.test(d))){let e=Zy("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=s.visit_ref!==void 0,h=f?Jy(a.value?.visit):null;if(f&&h===null){let e=Zy("the handoff response did not confirm the visit it opens");return e.ok?e:n(e.error)}let p=u===null?null:/* @__PURE__ */Object.freeze({...u,...c?{flowId:d}:{},...h!==null?{visit:h}:{}});return p===null?n(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(ov(r,"televet.visit.handoff_created",{pet_scoped:s.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>Gy)return Qy(`state must be at most ${Gy} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:Ny,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?Zy("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:n}))},async chatEntryOpen(){try{let e=await t.send("televet.visit.chat_entry",{method:"GET",path:$y},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function tv(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!lv(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var rv=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),nv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,iv=/[\s\u0000-\u001f\u007f]/;function lv(e){if(iv.test(e))return false;let t=nv.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let i=n.replace(/:\d+$/,"").toLowerCase(),l=r==="https",o=r==="http"&&rv.has(i);if(!l&&!o)return false;let s=e.indexOf("#");if(s<0)return false;let a=e.slice(s);return a.startsWith("#h=")&&a.length>3}function ov(e,t,r){if(e)try{e.track(t,r)}catch{}}var sv=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function av(e,r,n){let{usState:i,chat:l,scope:o}=n,s=r&&(i!==null||l),a=`${i??""}|${l?"chat":""}`,[u,c]=t.useState(null);if(t.useEffect(()=>{if(!s)return;let t=true,r=e.current;return c(null),(async()=>{try{if(l&&!(r.chatEntryOpen&&await r.chatEntryOpen()))return!1;if(i===null)return!0;if(!r.checkAvailability)return!1;let e=await r.checkAvailability(i);return e.ok&&e.value.available}catch{return false}})().then(e=>{t&&c({key:a,open:e})}),()=>{t=false}},[s,a,i,l,o,e]),!s)return null;let d=u!==null&&u.key===a;return{open:d&&u.open,pending:!d}}var uv=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function cv(e,r={}){let{runtime:n,userRef:i,scopeEpoch:l}=qc(),o=useCapability("televet"),s=o.enabled&&i!==null,a=r.usState??null,u=r.entry==="chat",c=r.petRef??null,d=r.prefer==="redirect",f=t.useMemo(()=>{if(r.controller)return r.controller;let{services:e}=n.registry;return ev({auth:e.authFor(i),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[n,i,l,r.controller]),h=t.useRef(f);h.current=f;let p=t.useMemo(()=>({runtime:n,userRef:i,scopeEpoch:l}),[n,i,l]),g=av(h,s,{usState:a,chat:u,scope:p}),m=s&&(g===null||g.open)&&(!u||c!==null),b=r.returnTo??null,[y,v]=t.useState(sv),x=t.useRef(null),w=t.useRef({runtime:n,userRef:i,scopeEpoch:l});w.current={runtime:n,userRef:i,scopeEpoch:l};let k=t.useRef(f);k.current=f;let C=t.useRef(m);C.current=m;let S=t.useCallback((t,r)=>{if(x.current)return x.current;let n=(e,t)=>(v({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!C.current)return Promise.resolve(n("unavailable",null));let i=e.prepare();if(!i.ok)return Promise.resolve(n(i.reason,null));let l=w.current,o=k.current;v(uv);let s=(async()=>{let s,a={...b!==null?{returnTo:b}:{},...u?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},d=Object.keys(a).length===0?void 0:a,f=t===void 0?c:t;try{s=await(d===void 0?o.createHandoff(f):o.createHandoff(f,d))}catch{return e.abandon(i.value),n("unknown",null)}let h=w.current;if(h.runtime!==l.runtime||h.userRef!==l.userRef||h.scopeEpoch!==l.scopeEpoch)return e.abandon(i.value),n("cancelled",null);if(!s.ok)return e.abandon(i.value),n(vetVisitErrorReasonOf(s.error),s.error);let p=await e.finish(i.value,s.value);return p!==null?n(p,null):(v(sv),/* @__PURE__ */Object.freeze(s.value.flowId===void 0?{opened:true}:{opened:true,flowId:s.value.flowId}))})().finally(()=>{x.current===s&&(x.current=null)});return x.current=s,s},[e,c,b,u]),j=t.useCallback((e,t)=>{if(!C.current)return v({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?c:e,n={...r!==null?{petRef:r}:{},...a!==null?{usState:a}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return Vy(n)===null?(v({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(v(sv),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[c,a]),_=t.useCallback(e=>d?S(e,null):j(e,null),[d,S,j]),R=t.useCallback((e,t)=>d?S(void 0,{visitRef:e,intent:t??null}):j(void 0,{visitRef:e,intent:t??null}),[d,S,j]),T=t.useCallback(e=>d?S(void 0,null):j(void 0,{consultId:e.trim()}),[d,S,j]);return{available:m,isPending:o.isPending||(g?.pending??false),status:y.status,error:y.error,errorReason:y.errorReason,open:_,openVisit:R,joinVisit:T}}var dv=e=>r.Linking.openURL(e);function useVetVisit(e={}){let{openUrl:r,...n}=e,i=t.useMemo(()=>{let e=r??dv;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[r]);return cv(i,n)}var fv=44,hv=.6;function VetVisitButtonCore(e){let{petRef:n,label:i,openUrl:o,onOpened:s,onError:a,style:u,labelStyle:c,controller:d,returnTo:f,usState:h,entry:p,visitRef:g,intent:m,onStartInApp:b,prefer:y}=e,v=y==="redirect",x=useVetVisit({...f!==void 0?{returnTo:f}:{},...h!==void 0?{usState:h}:{},...p!==void 0?{entry:p}:{},...n!==void 0?{petRef:n}:{},...o!==void 0?{openUrl:o}:{},...d!==void 0?{controller:d}:{},prefer:v?"redirect":"in-app"}),w=useEverfurTheme(),k=t.useMemo(()=>pv(w),[w]),C=t.useRef(false);if(!x.available)/* @__PURE__ */
|
|
150
|
-
return l.jsxs(l.Fragment,{children:[null,
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
/* @__PURE__ */
|
|
155
|
-
|
|
39
|
+
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function ri(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:/* @__PURE__ */Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),/* @__PURE__ */Object.freeze(t)}function ni(e,t){if(typeof e=="function")try{let r=e(t);r!==null&&typeof r=="object"&&typeof r.then=="function"&&r.then(void 0,li)}catch(e){li(e)}}function li(e){let t=globalThis.console;try{t?.error?.("[everfur] onEvent threw; the SDK ignored it.",e)}catch{}}var ii=/* @__PURE__ */new WeakMap,oi=/* @__PURE__ */new Map;function si(e,t){ii.set(e,t)}function ai(e,t,r,n){let l=ii.get(e);if(l===void 0)return null;let i;if(t.mode==="personalized"&&typeof t.userRef=="string")i=`u:${t.userRef}`;else if(t.mode==="anonymous"&&typeof t.sessionId=="string")i=`a:${t.sessionId}|${t.userRef??""}`;else return null;return`${l}|${i}|${r}|${ci(n)}`}function ui(e,t){if(e===null)return t();let r=oi.get(e);if(r!==void 0)return r;let n=t().finally(()=>{oi.get(e)===n&&oi.delete(e)});return oi.set(e,n),n}function ci(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(ci).join(",")}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${ci(t)}`).join(",")}}`}var di=/* @__PURE__ */new WeakMap;function fi(e,t){let r=di.get(e);return r===void 0&&(r=/* @__PURE__ */new Set,di.set(e,r)),r.add(t),()=>{r?.delete(t)}}function hi(e){let t=di.get(e);if(t!==void 0)for(let e of[...t])try{e()}catch{}}var pi=/* @__PURE__ */new Map;function gi(e,t){return()=>{let r=pi.get(e);if(r!==void 0)return r;let n;try{n=Promise.resolve(t())}catch(e){n=Promise.reject(e)}let l=n.finally(()=>{pi.get(e)===l&&pi.delete(e)});return pi.set(e,l),l}}var mi="/widget/v1/me/timezone",bi=/^(Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)\/[A-Za-z0-9_+-]+(\/[A-Za-z0-9_+-]+)?$/,yi=/* @__PURE__ */new Set;function vi(e){return typeof e=="string"&&e.length<=64&&bi.test(e)?e:null}function xi(e,t){try{let r=vi(Intl.DateTimeFormat().resolvedOptions().timeZone);if(r===null)return;let n=`${e}|${r}`;if(yi.has(n))return;yi.add(n),createRequestFunnel({auth:t}).send("member.deviceTimezone",{method:"PUT",path:mi,body:{timezone:r}},{maxAttempts:1,idempotent:!1}).catch(()=>{})}catch{}}function parseColor(e){let t=wi(e);return t===null?null:Ti(t)}function wi(e){if(typeof e=="number")return Si(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return ki(t.slice(1));if(t.toLowerCase().startsWith("0x"))return ki(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Ci(t);if(/^[0-9a-fA-F]+$/.test(t)){let e=ki(t);if(e!==null)return e}return/^\d+$/.test(t)?Si(Number.parseInt(t,10)):null}function ki(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return{r:_i(t[0]),g:_i(t[1]),b:_i(t[2]),a:1};if(t.length===6)return{r:ji(t,0),g:ji(t,2),b:ji(t,4),a:1};if(t.length===8){let e=ji(t,0);return{r:ji(t,2),g:ji(t,4),b:ji(t,6),a:e/255}}return null}function Ci(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(e=>e.trim());if(n.length<3)return null;let l=Ri(Number(n[0])),i=Ri(Number(n[1])),o=Ri(Number(n[2]));if(l===null||i===null||o===null)return null;let s=1;if(n.length>=4){let e=Number(n[3]);if(!Number.isFinite(e))return null;s=Math.min(1,Math.max(0,e))}return{r:l,g:i,b:o,a:s}}function Si(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return{r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}function ji(e,t){return Number.parseInt(e.slice(t,t+2),16)}function _i(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}function Ri(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}function Ti(e){if(e.a>=1)return Ii(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return`rgba(${e.r},${e.g},${e.b},${t})`}function Ii(e,t,r){return`#${zi(e)}${zi(t)}${zi(r)}`.toUpperCase()}function zi(e){return e.toString(16).padStart(2,"0")}var Pi="#111111",Ei="#FFFFFF",Oi="#000000";function readableOn(e){let t=wi(e);if(t===null)return Ei;let r=Fi(t),n=Fi({r:17,g:17,b:17}),l=Fi({r:255,g:255,b:255});return Li(r,l)>=Li(r,n)?Ei:Pi}function Ai(e,t){let r=readableOn(e);return contrastRatio(r,e)>=t?r:contrastRatio(Ei,e)>=contrastRatio(Oi,e)?Ei:Oi}function Mi(e){let t=t=>e.reduce((e,r)=>Math.min(e,contrastRatio(t,r)),Number.POSITIVE_INFINITY);return t(Ei)>=t(Oi)?Ei:Oi}function Fi(e){let t=Di(e.r/255),r=Di(e.g/255),n=Di(e.b/255);return.2126*t+.7152*r+.0722*n}function Di(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}function Li(e,t){let r=Math.max(e,t),n=Math.min(e,t);return(r+.05)/(n+.05)}function contrastRatio(e,t){let r=wi(e),n=wi(t);if(r===null||n===null)return 1;let l=n.a>=1?n:{...n},i=r.a>=1?r:Bi(r,l);return Li(Fi(i),Fi(l))}function Bi(e,t){let r=e.a,n=(e,t)=>Math.round(e*r+t*(1-r));return{r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}function Vi(e,t){let r=wi(e),n=wi(t);if(r===null||n===null)return null;let l=r.a>=1?r:Bi(r,{...n});return Ii(l.r,l.g,l.b)}function Hi(e,t){let r=wi(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return`rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}var Ui=.05;function Ni(e,t,r,n){let l=t[0];if(l===void 0)return r;let i=e=>t.every(t=>contrastRatio(e,t)>=n);if(wi(e)===null)return r;if(i(e))return e;let o=Vi(e,l),s=o===null?null:wi(o),a=wi(r);if(s===null||a===null)return r;for(let e=1;e<1/Ui;e+=1){let t=e*Ui,r=(e,r)=>Math.round(e+(r-e)*t),n=Ii(r(s.r,a.r),r(s.g,a.g),r(s.b,a.b));if(i(n))return n}return r}function $i(e,t,r){let n=e/255,l=t/255,i=r/255,o=Math.max(n,l,i),s=Math.min(n,l,i),a=(o+s)/2;if(o===s)return{h:0,s:0,l:a};let u=o-s,c=u/(1-Math.abs(2*a-1)),d;return o===n?(d=(l-i)/u*60,d<0&&(d=d+360)):o===l?d=((i-n)/u+2)*60:d=((n-l)/u+4)*60,{h:d,s:c,l:a}}function Wi(e){let{h:t,s:r,l:n}=e,l=(1-Math.abs(2*n-1))*r,i=t/60,o=l*(1-Math.abs(i%2-1)),s=n-l/2,a=Math.floor(i)%6,u=[[l,o,0],[o,l,0],[0,l,o],[0,o,l],[o,0,l],[l,0,o]],[c,d,f]=u[a];return{r:qi(c+s),g:qi(d+s),b:qi(f+s)}}function qi(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}var Gi=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog","cartBar","planCard","planReasonLabel","planWash","planChip"]),Ki=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),Yi=/* @__PURE__ */Object.freeze({planReasonLabel:/* @__PURE__ */Object.freeze(["textColor"]),planWash:/* @__PURE__ */Object.freeze(["backgroundColor"]),planChip:/* @__PURE__ */Object.freeze(["backgroundColor"])});function themeSlotKeysFor(e){return Yi[e]??Ki}var Qi=4.5,Zi=/* @__PURE__ */Object.freeze({});function Xi(e){return Gi.includes(e)}function Ji(e){let t=typeof e=="string"&&e.length<=16?e.trim().replace(/ ?px$/i,""):null,r=typeof e=="number"?e:t!==null&&t.length>0?Number(t):Number.NaN;return Number.isFinite(r)?Math.max(0,r):null}function parseThemeSlots(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,l]of Object.entries(e)){if(!Xi(n)||l===null||typeof l!="object")continue;let e=ro(l);if(e===null)continue;let i=eo(n,e);i!==null&&(t[n]=i,r=true)}return r?/* @__PURE__ */Object.freeze(t):null}function eo(e,t){let r=Yi[e];if(r===void 0)return t;let n={};for(let e of r)t[e]!==void 0&&(n[e]=t[e]);return Object.keys(n).length===0?null:/* @__PURE__ */Object.freeze(n)}function to(e,t,r){return e[t]!==void 0?e[t]:e[r]}function ro(e){let t={},r=parseColor(to(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=parseColor(to(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let l=Ji(to(e,"border_radius","borderRadius"));l!==null&&(t.borderRadius=l);let i=parseColor(to(e,"text_color","textColor"));return i!==null&&(t.textColor=i),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function mergeThemeSlots(e,t){return t===null||Object.keys(t).length===0?e??Zi:e===null||Object.keys(e).length===0?t:/* @__PURE__ */Object.freeze({...e,...t})}function no(e){let t=wi(e);return t!==null&&t.a>=1}var lo=3,io=/* @__PURE__ */new Set(["card","recordCard","banner","header","dialog","bookingStep","cartBar","planCard"]);function oo(e,t){let r=parseColor(e);return r!==null&&r===parseColor(t)}function so(e,t,r=[]){if(t.length===0)return null;let n=t.map(t=>Vi(e,t)??e);if(t.every((e,t)=>contrastRatio(n[t],e)>=lo))return null;let l=[...t,...n,...r];return Ni(n[0],l,Mi(l),lo)}function ao(e,t){return e===void 0?t:t.length===0?[e]:t.map(t=>Vi(e,t)??t)}function uo(e,t){let r=Mi(e);return e.every(e=>contrastRatio(r,e)>=t)}function co(e,t){let r=t[0];return r===void 0?null:Vi(e,r)}function fo(e){let t=Ai(e[0],Qi);return e.every(e=>contrastRatio(t,e)>=Qi)?t:Mi(e)}function ho(e,t,r,n,l){return io.has(e)?false:l?true:r!==void 0&&oo(t,r)?false:!(n!==void 0&&r!==void 0&&no(r))}function guardSlotContrast(e,t,r){let n=false,l={};for(let i of Gi){let o=e[i];if(o===void 0)continue;let s=o.backgroundColor,a=t?.[i]??[],u=ao(s,a),c={...o},d=false;if(s!==void 0&&u.length>1&&!uo(u,Qi)){let e=co(s,a);e!==null&&(c.backgroundColor=e,u=[e],d=true)}let f=r?.[i],h=c.backgroundColor,p=f!==void 0&&h!==void 0&&no(h)&&so(h,f,u)!==null;if(u.length>0){let e=o.textColor;if(s!==void 0)(e===void 0||u.some(t=>contrastRatio(e,t)<Qi))&&(c.textColor=fo(u),d=true);else if(e!==void 0){let t=Ni(e,u,Mi(u),Qi);t!==e&&(c.textColor=t,d=true)}if(o.borderColor!==void 0&&ho(i,o.borderColor,h,f,p)){let e=p?[...u,...f??[]]:u,t=Ni(o.borderColor,e,Mi(e),lo);t!==o.borderColor&&(c.borderColor=t,d=true)}}if(p&&h!==void 0&&f!==void 0&&c.borderColor===void 0){let e=so(h,f,u);e!==null&&(c.borderColor=e,d=true)}l[i]=d?/* @__PURE__ */Object.freeze(c):o,n=n||d}return n?/* @__PURE__ */Object.freeze(l):e}var po=/* @__PURE__ */Object.freeze(["display","title","cardTitle","rowTitle","body","message","bodySmall","caption","label","eyebrow","chip","tab","button","badge"]),go=/* @__PURE__ */Object.freeze({display:/* @__PURE__ */Object.freeze({size:29,lineHeight:1.06,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),title:/* @__PURE__ */Object.freeze({size:23,lineHeight:1.12,weight:"800",face:"heading",letterSpacing:-.01,uppercase:false,tier:"heading"}),cardTitle:/* @__PURE__ */Object.freeze({size:19,lineHeight:1.22,weight:"800",face:"sans",letterSpacing:0,uppercase:false,tier:"heading"}),rowTitle:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.4,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),body:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),message:/* @__PURE__ */Object.freeze({size:15.5,lineHeight:1.5,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),bodySmall:/* @__PURE__ */Object.freeze({size:14.5,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),caption:/* @__PURE__ */Object.freeze({size:13,lineHeight:1.4,weight:"400",face:"sans",letterSpacing:0,uppercase:false,tier:"content"}),label:/* @__PURE__ */Object.freeze({size:10.5,lineHeight:1.4,weight:"400",face:"mono",letterSpacing:.05,uppercase:true,tier:"compact"}),eyebrow:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"400",face:"mono",letterSpacing:.07,uppercase:true,tier:"compact"}),chip:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.3,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),tab:/* @__PURE__ */Object.freeze({size:16,lineHeight:1.5,weight:"600",face:"sans",letterSpacing:0,uppercase:false,tier:"compact"}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"control"}),badge:/* @__PURE__ */Object.freeze({size:12,lineHeight:1.5,weight:"700",face:"sans",letterSpacing:0,uppercase:false,tier:"badge"})});var mo=Object.freeze;function deepFreeze(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){mo(e);for(let t of Object.keys(e))deepFreeze(e[t])}return e}var bo=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),yo=/* @__PURE__ */Object.freeze({content:0,heading:1.4,control:1.35,compact:1.3,badge:1.2}),vo={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},xo={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},wo={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},ko={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Co={regular:"400",medium:"500",bold:"700"},So={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},jo=0,_o="System",Ro="monospace",To=["content","heading","control","compact","badge"];function Io(e){let t={};for(let r of To)t[r]=e;return t}var zo=[];function Po(){return{family:_o,mono:Ro,fontUrl:null,families:{regular:_o,medium:_o,bold:_o,mono:Ro,monoMedium:Ro,monoBold:Ro},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:wo,tierSizes:Io(wo),lineHeight:ko,weight:Co,letterSpacing:So,scale:1,maxScale:jo,scaleCaps:bo,headingFamily:null,headingWeight:null,fontSources:zo,roles:go,typeScale:1}}var Eo={},Oo=/* @__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(e){return`cubic-bezier(${e.join(", ")})`}var Ao={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(Oo.standard),emphasized:cssCubicBezier(Oo.emphasized),exit:cssCubicBezier(Oo.exit)},reducedMotion:false},Mo={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)"},Fo=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:Mo,space:vo,radius:xo,type:Po(),motion:Ao,slots:Eo}),Do={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)"},Lo=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:Do,space:vo,radius:xo,type:Po(),motion:Ao,slots:Eo});function Bo(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function Vo(e){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}function Ho(e){return Vo(e).every(t=>contrastRatio(e.brand,t)>=lo)}function Uo(e){return[e.chatGround,e.surface,e.surfaceCream]}function No(e,t){return[e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill,...$o(e,t)]}function $o(e,t){return[Vi(t,e.surface)??e.surface,Vi(t,e.surfaceCream)??e.surfaceCream]}function Wo(e){return[e.composerFill,e.chatGround]}var qo=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function Go(e,t){let r=new Set(Bo(t));return Bo(e).every(e=>r.has(e))}function Ko(e){let t=e.color,r=(e.brightness==="dark"?Lo:Fo).color,n=(e.brightness==="dark"?Fo:Lo).color,l=Bo(t),i=Mi(l)!==Mi(Bo(r)),o=Go(t,r),s=t.danger===r.danger&&t.badgeBgCritical===r.badgeBgCritical,a=(e,t,r,n,l,a)=>{let u=t===r&&(e!=="errorRed"||s);return u&&o&&qo.has(e)?t:Ni(u&&i?n:t,l,Mi(l),a)},u=(e,l,i)=>a(`text.${e}`,t.text[e],r.text[e],n.text[e],l,i),c=(e,t,l,i)=>a(e,t,r[e],n[e],l,i),d=e=>i&&t[e]===r[e]?n[e]:t[e],f=t.primary,h=Ai(f,Qi),p=c("danger",t.danger,[...l,...$o(t,t.badgeBgCritical)],Qi),g={...t,onPrimary:h,onAccent:Ai(t.accent,Qi),onDanger:contrastRatio(h,p)>=Qi?h:Ai(p,Qi),brandSoft:d("brandSoft"),brandSofter:d("brandSofter"),brandBorder:d("brandBorder"),borderHairlineGreen:d("borderHairlineGreen"),brandInk:c("brandInk",t.brandInk,l,Qi),linkInk:c("linkInk",e.slots.link?.textColor??t.accent,Uo(t),Qi),text:{...t.text,primary:u("primary",l,Qi),secondary:u("secondary",l,Qi),muted:u("muted",l,Qi),metaCool:u("metaCool",l,Qi),timestamp:u("timestamp",l,Qi),placeholder:u("placeholder",Vo(t),lo)},danger:p,errorRed:c("errorRed",t.errorRed,No(t,t.badgeBgCritical),Qi),warningStrong:c("warningStrong",t.warningStrong,No(t,t.badgeBgCaution),Qi),composerBorder:c("composerBorder",t.composerBorder,Wo(t),lo),brandBorderStrong:c("brandBorderStrong",t.brandBorderStrong,Vo(t),lo)},m={...g,...rs(g,r,o)};return{...m,...Yo(t,m,r)}}function Yo(e,t,r){let n={},l=(e,t,r)=>Ni(e,t,Mi(t),r);if((!Jo(e.success,r.success)||!Jo(e.badgeBgPositive,r.badgeBgPositive))&&(n.success=l(e.success,No(t,e.badgeBgPositive),Qi)),(!Jo(e.cautionAccent,r.cautionAccent)||!Jo(e.badgeBgCaution,r.badgeBgCaution))&&(n.cautionAccent=l(e.cautionAccent,No(t,e.badgeBgCaution),Qi)),Qo(e,r)){n.info=l(e.info,No(t,e.badgeBgInfo),Qi);let r=[t.surface,t.chatGround,...$o(t,e.badgeBgInfo)];n.infoEdge=l(e.infoEdge,r,lo)}else n.info=t.brandInk,n.badgeBgInfo=t.brandSoft,n.infoEdge=t.structureEdge;return n}function Qo(e,t){return!Jo(e.info,t.info)||!Jo(e.badgeBgInfo,t.badgeBgInfo)}var Zo=.24,Xo=.3;function Jo(e,t){return parseColor(e)===parseColor(t)}function es(e,t){return Jo(e.accent,t.accent)?Jo(e.brand,t.brand)?null:e.brand:e.accent}function ts(e,t,r){let n=Hi(e,r);return(n===null?null:Vi(n,t))??t}function rs(e,t,r){let n=es(e,t),l=Vo(e),i=Mi(l),o=Mi([e.surface])===Ei,s=n===null&&r,a;s?a=t.highlight:n===null?a=o?ts(Fo.color.highlight,e.surface,Xo):Fo.color.highlight:a=ts(n,e.surface,o?Xo:Zo);let u=s?t.onHighlight:Ni(e.text.primary,[a],Mi([a]),Qi),c=n===null?t.mark:Ni(n,l,i,lo),d=Ho(e)?e.brand:i,f=(e,t,n)=>r&&Jo(e,t)?n:Ni(e,l,d,lo),h=[e.chatGround,e.composerFill,e.surface,e.surfaceCream],p=h.every(t=>contrastRatio(e.primary,t)>=lo)?e.primary:Ni(e.primary,h,Mi(h),lo);return{highlight:a,onHighlight:u,mark:c,controlEdge:f(e.brandBorder,t.brandBorder,t.controlEdge),structureEdge:f(e.borderHairlineGreen,t.borderHairlineGreen,t.structureEdge),primaryEdge:p}}var ns=(e,t)=>e!==void 0&&t!==void 0&&parseColor(e)===parseColor(t);function ls(e,t){let r=(e.brightness==="dark"?Lo:Fo).color,n=e.color,l=t.color,i=[],o=(e,t,r,n)=>{i.push(/* @__PURE__ */Object.freeze({field:e,role:t,requested:r,painted:n}))},s=(e,t)=>!ns(e,t);s(n.text.primary,r.text.primary)&&!ns(l.text.primary,n.text.primary)&&o("text_color","body text",n.text.primary,l.text.primary),s(n.brand,r.brand)&&(ns(l.brandInk,n.brand)||o("primary_color","brand text and icons",n.brand,l.brandInk),ns(l.primaryEdge,n.primary)||o("primary_color","edge of a filled control",n.primary,l.primaryEdge),!ns(l.controlEdge,n.brandBorder)&&!Ho({...l,brand:n.brand})&&o("primary_color","control outline",n.brand,l.controlEdge)),s(n.accent,r.accent)&&e.slots.link?.textColor===void 0&&!ns(l.linkInk,n.accent)&&o("accent_color","link text",n.accent,l.linkInk),s(n.danger,r.danger)&&!ns(l.danger,n.danger)&&o("danger_color","error text",n.danger,l.danger),s(n.success,r.success)&&!ns(l.success,n.success)&&o("success_color","positive status",n.success,l.success),s(n.warningStrong,r.warningStrong)&&!ns(l.warningStrong,n.warningStrong)&&o("warning_color","caution text",n.warningStrong,l.warningStrong),s(n.cautionAccent,r.cautionAccent)&&!ns(l.cautionAccent,n.cautionAccent)&&o("warning_color","caution accent",n.cautionAccent,l.cautionAccent),(s(n.info,r.info)||s(n.badgeBgInfo,r.badgeBgInfo))&&(ns(l.info,n.info)||o("info_color","information text",n.info,l.info),ns(l.infoEdge,n.infoEdge)||o("info_color","information outline",n.infoEdge,l.infoEdge));for(let r of Gi){let n=e.slots[r],l=t.slots[r];n===void 0||l===void 0||n===l||(l.backgroundColor!==void 0&&!ns(l.backgroundColor,n.backgroundColor)&&o(`slots.${r}.background_color`,"fill",n.backgroundColor??null,l.backgroundColor),n.textColor!==void 0&&l.textColor!==void 0&&!ns(l.textColor,n.textColor)&&o(`slots.${r}.text_color`,"text",n.textColor??null,l.textColor),l.borderColor!==void 0&&!ns(l.borderColor,n.borderColor)&&o(`slots.${r}.border_color`,"outline",n.borderColor??null,l.borderColor))}/* @__PURE__ */
|
|
40
|
+
return Object.freeze(i)}var is=/* @__PURE__ */new Set;function os(e){if(e.length===0)return;let t=`[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${e.map(e=>` ${e.field} (${e.role}): ${e.requested??"not set"} -> ${e.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(is.has(t))return;is.add(t);let r=globalThis.console;try{r?.warn?.(t)}catch{}}var ss="#23272C",as=4.5,us=.6,cs=.9,ds=.02,fs="#FFFFFF",hs="#111111";function ps(e){return contrastRatio(e,ss)>=as&&Math.max(contrastRatio(e,fs),contrastRatio(e,hs))>=as}function deriveDarkVariant(e){let t=wi(e);if(t===null)return null;let{h:r,s:n,l:l}=$i(t.r,t.g,t.b),i=Math.min(Math.max(l,us),cs);for(let e=0;;e+=1){let t=i+e*ds;if(t>cs)break;let l=Wi({h:r,s:n,l:t}),o=Ii(l.r,l.g,l.b);if(ps(o))return o}let o=Wi({h:r,s:n,l:cs});return Ii(o.r,o.g,o.b)}var gs=7,ms=.05,bs="#000000",ys="#FFFFFF";function vs(e,t,r,n){let l=Vi(e,t);if(l===null)return r;if(contrastRatio(l,t)>=n)return l;let i=wi(l),o=wi(r);if(i===null||o===null)return r;for(let e=1;e<1/ms;e+=1){let r=e*ms,l=(e,t)=>Math.round(e+(t-e)*r),s=Ii(l(i.r,o.r),l(i.g,o.g),l(i.b,o.b));if(contrastRatio(s,t)>=n)return s}return r}function xs(e,t){let r=Bo(e),n=r[0],l=ws(n);for(let e of r){let r=ws(e);(t?r>l:r<l)&&(n=e,l=r)}return n}function ws(e){let t=wi(e);return t===null?0:Fi(t)}function ks(e,t){return Vi(e,t)??parseColor(e)??t}function deriveHighContrast(e){let t=e.color,r=Mi(Bo(t))===ys,n=r?ys:bs,l=xs(t,r),i=e=>vs(e,l,n,gs),o={...t,brandSoft:ks(t.brandSoft,t.surface),brandSofter:ks(t.brandSofter,t.surface),brandBorder:i(t.brandBorder),borderHairlineGreen:i(t.borderHairlineGreen),brandBorderStrong:i(t.brandBorderStrong),controlEdge:i(t.controlEdge),structureEdge:i(t.structureEdge),brandInk:i(t.brandInk),linkInk:i(t.linkInk),borderRingCream:i(t.borderRingCream),composerBorder:i(t.composerBorder),text:{primary:i(t.text.primary),secondary:i(t.text.secondary),muted:i(t.text.muted),placeholder:i(t.text.placeholder),onBrand:t.text.onBrand,metaCool:i(t.text.metaCool),timestamp:i(t.text.timestamp)},badgeBgPositive:ks(t.badgeBgPositive,t.surface),badgeBgCaution:ks(t.badgeBgCaution,t.surface),badgeBgCritical:ks(t.badgeBgCritical,t.surface),badgeBgNeutral:ks(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:ks(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:ks(t.checkupCardConcernBg,t.surface),info:i(t.info),infoEdge:i(t.infoEdge),badgeBgInfo:ks(t.badgeBgInfo,t.surface)};return deepFreeze({...e,highContrast:true,color:o})}var Cs=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),Ss=Cs.cream,js=Cs.subtle,_s=Cs.ring,Rs=10;function Ts(e,t,r){let n=wi(e),l=wi(t);if(n===null||l===null)return null;let i=(e,t)=>Math.round(e+(t-e)*r);return Ii(i(n.r,l.r),i(n.g,l.g),i(n.b,l.b))}function Is(e){if(e===null)return{};let t=Mi([e]),r=Ts(e,t,Ss),n=Ts(e,t,js),l=Ts(e,t,_s);return r===null||n===null||l===null?{}:{surface:e,background:e,chatGround:e,bubbleAssistant:e,surfaceCream:r,composerFill:r,surfaceSubtle:n,skeleton:n,borderRingCream:l}}function zs(e){if(e===null)return{};let t=wi(e);return t===null?{}:{danger:e,errorRed:e,badgeBgCritical:`rgba(${t.r},${t.g},${t.b},0.12)`}}function Ps(e,t,r){if(e===null)return t;let n=e/r.type.size.body;if(n===1)return r.type.size;let l={};for(let[e,t]of Object.entries(r.type.size))l[e]=Math.max(Rs,Math.round(t*n*10)/10);return l}function Es(e,t,r){if(e===null)return t;let n=e/r.space.xs,l=e=>Math.round(e*n),i=r.space;return{xs:l(i.xs),sm:l(i.sm),md:l(i.md),lg:l(i.lg),xl:l(i.xl),xxl:l(i.xxl)}}function Os(e,t){let r=e/t.radius.md,n=e=>Math.round(e*r),l=t.radius;return{tile:n(l.tile),xs:n(l.xs),sm:n(l.sm),md:n(l.md),lg:n(l.lg),xl:n(l.xl),pill:l.pill}}var As=/* @__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 Ms(e,t){let r=wi(e);return r===null?null:`rgba(${r.r},${r.g},${r.b},${t})`}function Fs(e,t){if(e===null)return{};let r=Ms(e,t?As.success.dark:As.success.light),n=Ms(e,t?As.successCard.dark:As.successCard.light);return r===null||n===null?{}:{success:e,badgeBgPositive:r,checkupCardLowRiskBg:n}}function Ds(e,t){if(e===null)return{};let r=Ms(e,t?As.warning.dark:As.warning.light);return r===null?{}:{warningStrong:e,cautionAccent:e,badgeBgCaution:r}}function Ls(e,t){if(e===null)return{};let r=Ms(e,t?As.info.dark:As.info.light);return r===null?{}:{info:e,infoEdge:e,badgeBgInfo:r}}function Bs(e,t,r){if(e===null)return t;let n=r.type.lineHeight,l=e/n.normal;if(l===1)return n;let i=e=>Math.round(e*l*100)/100;return{tight:i(n.tight),snug:i(n.snug),normal:i(n.normal),relaxed:i(n.relaxed)}}function Vs(e){return{composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],vetBubble:[e.bubbleVet],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Uo(e),header:[e.surface,e.background,e.chatGround],banner:[Vi(e.badgeBgInfo,e.surface)??e.surface,Vi(e.badgeBgCaution,e.surface)??e.surface,e.surface],chip:[e.chatGround,e.surface,e.background,e.surfaceCream],card:[e.surface],input:[e.surface,e.composerFill,e.surfaceCream,e.surfaceSubtle],tab:[e.surface,e.background],bookingStep:[e.surface,e.background],dialog:[e.surface],cartBar:[e.brand],planCard:[e.surface],planReasonLabel:[e.surface],planWash:[e.surface],planChip:[e.surface]}}function Hs(e){return{userBubble:[e.chatGround],assistantBubble:[e.chatGround],vetBubble:[e.chatGround],sendButton:[e.composerFill],vetVisitButton:[e.surfaceCream,e.surface,e.chatGround],primaryButton:[e.surface,e.surfaceCream]}}function Us(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ns=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),$s=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),Ws=/* @__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 qs(e){return typeof e=="string"&&Ns.includes(e.trim().toLowerCase())}function Gs(e,t){let r=e[t];return r??void 0}var Ks=16;function parsePx(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.length>Ks)return;let t=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(e.trim());return t===null?void 0:Number(t[1])}var Ys=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],Qs=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],Zs=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],Xs=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],Js=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(e){if(!Us(e))return null;let t=qs(e.theme)?$s[e.theme.trim().toLowerCase()]:{},r=Us(e.variables)?e.variables:{},n={...t};for(let[e,t]of Object.entries(r))t!=null&&(n[e]=t);let l={},i=Gs(n,"colorScheme"),o=typeof i=="string"?i.trim().toLowerCase():null;(o==="light"||o==="dark"||o==="auto")&&(l.color_scheme=o);let s=o==="dark"?"_dark":"";for(let[e,t]of Ys){let r=Gs(n,e);r!==void 0&&(l[`${t}${s}`]=r)}for(let[e,t]of Qs){let r=Gs(n,e);r!==void 0&&(l[`${t}${s}`]=r)}for(let[e,t]of Xs){let r=Gs(n,e);typeof r=="string"&&r.trim().length>0&&(l[t]=r.trim())}for(let[e,t]of Js){let r=parsePx(Gs(n,e));r!==void 0&&(l[t]=r)}for(let[e,t]of Zs){let r=Gs(n,e);(typeof r=="number"||typeof r=="string")&&(l[t]=r)}let a=e.fonts;Array.isArray(a)&&a.length>0&&(l.font_sources=a);let u=e.rules;if(Us(u)){let e={};for(let t of Gi){let r=u[t];Us(r)&&(e[t]=r)}Object.keys(e).length>0&&(l.slots=e)}return Object.keys(l).length===0?null:/* @__PURE__ */Object.freeze(l)}var ea="https:\\/\\/sdk(?:-[a-z]+)?\\.everfur\\.com";function ta(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}var ra=typeof __EVERFUR_BRAND_CDN_ORIGIN__=="string"&&__EVERFUR_BRAND_CDN_ORIGIN__.length>0?ta(__EVERFUR_BRAND_CDN_ORIGIN__):ea;var na=/* @__PURE__ */Object.freeze(["ask","vet","plan","records"]),la=/* @__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,serverSlots:false,shellTabs:null,shellHeader:"classic"}),ia=/* @__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",serverSlots:"server_slots",shellTabs:"shell_tabs",shellHeader:"shell_header"}),oa=Object.keys(ia),sa="presentation",aa="presentation.";function isPresentationLockName(e){if(e===sa)return true;if(!e.startsWith(aa))return false;let t=e.slice(aa.length);return Object.values(ia).includes(t)}var ua={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer","none"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"],shellHeader:["classic","tabs_bar"]};function ca(e){if(!Array.isArray(e)||e.length===0)return;let t=/* @__PURE__ */new Set;for(let r of e){if(typeof r!="string"||!na.includes(r)||t.has(r))return;t.add(r)}/* @__PURE__ */
|
|
41
|
+
return Object.freeze([...e])}var da=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function fa(e,t){if(t==null)return;if(e==="shellTabs")return ca(t);let r=ua[e];return r!==void 0?typeof t=="string"&&r.includes(t)?t:void 0:da.has(e)?typeof t=="boolean"?t:void 0:typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=3?t:void 0}function parsePresentation(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of oa){let n=ia[e],l=Object.prototype.hasOwnProperty.call(t,n)?t[n]:t[e],i=fa(e,l);i!==void 0&&(r[e]=i)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}function isPresentationFieldLocked(e,t){if(t==null)return false;let r=`${aa}${ia[e]}`;for(let e of t)if(e===sa||e===r)return true;return false}function resolvePresentation(e){let t=parsePresentation(e?.server??null)??{},{safetyDisclaimerPlacement:r,...n}=t,l=r==="none"||r===void 0?n:{...n,safetyDisclaimerPlacement:r},i=parsePresentation(e?.client??null)??{},o=e?.locked?[...e.locked]:null,s={};for(let e of oa){let t=l[e],r=isPresentationFieldLocked(e,o)?void 0:i[e];s[e]=r??t??la[e]}/* @__PURE__ */
|
|
42
|
+
return Object.freeze(s)}var ha=4,pa=/* @__PURE__ */Object.freeze({min:1,max:2}),ga=100,ma=2048,ba=["100","200","300","400","500","600","700","800","900"];function ya(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim().length===0||e.length>16)return null;let t=Number(e.trim());return Number.isFinite(t)?t:null}function va(e){let t=ya(e);if(t===null)return null;let r=String(t);return ba.includes(r)?r:null}function xa(e){let t=ya(e);return t===null?null:Math.min(pa.max,Math.max(pa.min,t))}function wa(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>ma?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(t)?t:null}function ka(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>ga||/[\u0000-\u001F\u007F]/.test(t)?null:t}function Ca(e,...t){for(let r of t)if(e[r]!==void 0&&e[r]!==null)return e[r]}function Sa(e){if(!Us(e))return null;let t=ka(e.family);if(t===null)return null;let r=Ca(e,"src"),n=Ca(e,"cssSrc","css_src");if(r===void 0==(n===void 0))return null;if(n!==void 0){let e=wa(n);return e===null?null:/* @__PURE__ */Object.freeze({family:t,cssSrc:e})}let l=wa(r);if(l===null)return null;let i={family:t,src:l},o=va(e.weight);o!==null&&(i.weight=o);let s=typeof e.style=="string"?e.style.trim().toLowerCase():null;return(s==="normal"||s==="italic")&&(i.style=s),/* @__PURE__ */Object.freeze(i)}function ja(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=ha)break;let e=Sa(r);e!==null&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}var _a=/* @__PURE__ */Object.freeze({size:/* @__PURE__ */Object.freeze({min:8,max:48}),letterSpacing:/* @__PURE__ */Object.freeze({min:-.1,max:.3}),typeScale:/* @__PURE__ */Object.freeze({min:.8,max:1.3})}),Ra=["content","heading","control","compact","badge"],Ta=["sans","heading","mono"],Ia=/* @__PURE__ */Object.freeze({min:1,max:3.1});function za(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e.trim().replace(/px$/i,"")):Number.NaN;return Number.isFinite(t)?t:null}function Pa(e,t){return Math.min(t.max,Math.max(t.min,e))}function Ea(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Oa(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==void 0)return e[r]}function Aa(e){let t=za(e);return t===null?null:Pa(t,_a.typeScale)}function Ma(e){if(!Ea(e))return null;let t={};for(let r of Ra){let n=za(Oa(e,r));n!==null&&(t[r]=n<=0?0:Pa(n,Ia))}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function Fa(e){if(!Ea(e))return null;let t={},r=za(Oa(e,"size","fontSize","font_size"));r!==null&&(t.size=Pa(r,_a.size));let n=xa(Oa(e,"lineHeight","line_height"));n!==null&&(t.lineHeight=n);let l=va(Oa(e,"weight","fontWeight","font_weight"));l!==null&&(t.weight=l);let i=Oa(e,"face");typeof i=="string"&&Ta.includes(i.trim())&&(t.face=i.trim());let o=za(Oa(e,"letterSpacing","letter_spacing"));o!==null&&(t.letterSpacing=Pa(o,_a.letterSpacing));let s=Oa(e,"uppercase");return typeof s=="boolean"&&(t.uppercase=s),Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}function Da(e){if(!Ea(e))return null;let t={};for(let r of po){let n=Fa(Oa(e,r));n!==null&&(t[r]=n)}return Object.keys(t).length===0?null:/* @__PURE__ */Object.freeze(t)}var La=e=>Math.round(e*10)/10,Ba=e=>Math.round(e*100)/100;function Va(e,t,r,n){if(t===null&&r===null&&n===null)return e;let l=t===null?null:t/go.body.size,i=r===null?null:r/go.body.lineHeight,o={};for(let t of po){let r=e[t],s=go[t];o[t]=/* @__PURE__ */Object.freeze({...r,...l===null?{}:{size:La(s.size*l)},...i===null?{}:{lineHeight:Ba(s.lineHeight*i)},...n?.[t]??{}})}/* @__PURE__ */
|
|
43
|
+
return Object.freeze(o)}function Ha(e,t){let r=false,n={};for(let l of po){let i=e[l],o=t(i);o===1?n[l]=i:(r=true,n[l]=/* @__PURE__ */Object.freeze({...i,size:La(i.size*o)}))}return r?/* @__PURE__ */Object.freeze(n):e}function Ua(e,t,r){return{nano:La(e.nano*r),small:La(e.small*r),micro:La(e.micro*r),tiny:La(e.tiny*r),caption:t.caption.size,bodyTight:t.bodySmall.size,body:t.body.size,subtitle:t.cardTitle.size,heading:t.title.size,verdict:La(e.verdict*r)}}var Na=/* @__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"]),$a="slots.",Wa=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}function isKnownBrandingSchema(e){let t=e?.schemaVersion??null;return t===null||Wa.includes(t)}function lockedFieldsOf(e){/* @__PURE__ */
|
|
44
|
+
return new Set(["hide_powered_by",...e?.lockedFields??[]])}function qa(e){return e==="hide_powered_by"||Na.includes(e)||isPresentationLockName(e)?true:e.startsWith($a)&&Gi.includes(e.slice($a.length))}function parseClientBranding(e){if(e===null||typeof e!="object")return null;let t=e,r=Ka(t),n=expandAppearance(Za(t,"appearance")),l=n===null?r:Ga(Ka(n),r);return isEmptyBranding(l)?null:/* @__PURE__ */Object.freeze(l)}function Ga(e,t){let r={...e};for(let[e,n]of Object.entries(t))n!=null&&(r[e]=n);let n=mergeThemeSlots(e.slots??null,t.slots??null);return r.slots=Object.keys(n).length===0?null:n,r}function Ka(e){return{displayName:Xa(Za(e,"display_name","displayName")),logoUrl:Xa(Za(e,"logo_url","logoUrl")),primaryColor:parseColor(Za(e,"primary_color","primaryColor")),accentColor:parseColor(Za(e,"accent_color","accentColor")),brightness:lu(Za(e,"brightness","color_scheme","colorScheme")),fontFamily:Xa(Za(e,"font_family","fontFamily")),fontUrl:Xa(Za(e,"font_url","fontUrl")),fonts:eu(Za(e,"fonts")),fontUrls:eu(Za(e,"font_urls","fontUrls")),placeholder:Xa(Za(e,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Qa(Za(e,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(Za(e,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(Za(e,"accent_color_dark","accentColorDark")),surfaceStyle:nu(Za(e,"surface_style","surfaceStyle"),tu),radiusScale:nu(Za(e,"radius_scale","radiusScale"),ru),logoUrlDark:Xa(Za(e,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(Za(e,"slots")),accessibilityMaxFontScale:au(Za(e,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:du(Za(e,"locked_fields","lockedFields")),presentation:parsePresentation(Za(e,"presentation")),schemaVersion:uu(Za(e,"schema_version","schemaVersion")),backgroundColor:parseColor(Za(e,"background_color","backgroundColor")),backgroundColorDark:parseColor(Za(e,"background_color_dark","backgroundColorDark")),textColor:parseColor(Za(e,"text_color","textColor")),textColorDark:parseColor(Za(e,"text_color_dark","textColorDark")),dangerColor:parseColor(Za(e,"danger_color","dangerColor")),dangerColorDark:parseColor(Za(e,"danger_color_dark","dangerColorDark")),fontSizeBase:Ya(Za(e,"font_size_base","fontSizeBase"),Ws.fontSizeBase),borderRadius:Ya(Za(e,"border_radius","borderRadius"),Ws.borderRadius),spacingUnit:Ya(Za(e,"spacing_unit","spacingUnit"),Ws.spacingUnit),successColor:parseColor(Za(e,"success_color","successColor")),successColorDark:parseColor(Za(e,"success_color_dark","successColorDark")),warningColor:parseColor(Za(e,"warning_color","warningColor")),warningColorDark:parseColor(Za(e,"warning_color_dark","warningColorDark")),infoColor:parseColor(Za(e,"info_color","infoColor")),infoColorDark:parseColor(Za(e,"info_color_dark","infoColorDark")),headingFontFamily:Xa(Za(e,"heading_font_family","headingFontFamily")),fontWeightBody:va(Za(e,"font_weight_body","fontWeightBody")),fontWeightHeading:va(Za(e,"font_weight_heading","fontWeightHeading")),lineHeight:xa(Za(e,"line_height","lineHeight")),fontSources:ja(Za(e,"font_sources","fontSources")),assistantAvatarUrl:Xa(Za(e,"assistant_avatar_url","assistantAvatarUrl")),textScaleCaps:Ma(Za(e,"text_scale_caps","textScaleCaps")),typeScale:Aa(Za(e,"type_scale","typeScale")),typeRoles:Da(Za(e,"type_roles","typeRoles"))}}function Ya(e,t){let r=iu(typeof e=="string"?e.trim().replace(/px$/i,""):e);return r===null?null:Math.min(t.max,Math.max(t.min,r))}function Qa(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}function Za(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let t=e[r];if(t!==void 0)return t}}function Xa(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}var Ja=["regular","medium","bold","mono","monoMedium","monoBold"];function eu(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let e of Ja){let n=Xa(Za(t,e));n!==null&&(r[e]=n)}return Object.keys(r).length===0?null:/* @__PURE__ */Object.freeze(r)}var tu=["white","cream","subtle"],ru=["sharp","default","round"];function nu(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}function lu(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}function iu(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}var ou=1,su=3.1;function au(e){let t=iu(e);return t===null?null:t<=0?0:Math.min(su,Math.max(ou,t))}function uu(e){if(e==null)return null;let t=iu(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}function cu(e){let t=e.trim();return t.startsWith($a)?t:t.startsWith(aa)?aa+t.slice(aa.length).replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase():t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function du(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let e=cu(r);qa(e)&&!t.includes(e)&&t.push(e)}return t.length===0?null:/* @__PURE__ */Object.freeze(t)}function hardenHttpsUrl(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}var fu=/* @__PURE__ */new RegExp(`^${ra}\\/brand\\/[0-9a-f]{16}\\.(png|jpg|webp)$`);function hardenBrandAssetUrl(e){let t=hardenHttpsUrl(e);return t!==null&&fu.test(t)?t:null}function withServerBranding(e,t){if(t===null||isEmptyBranding(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Lo:Fo:e,n=r.brightness==="dark"?Lo:Fo,l=r.brightness==="dark",i=l?t.primaryColorDark??bu(t.primaryColor):t.primaryColor,o=l?t.accentColorDark??bu(t.accentColor):t.accentColor,s=i??r.color.primary,a=o??r.color.accent,u=i!==null&&xu(t,s,n,l),c=u?n.color.primary:s,d=i!==null&&!u?wi(c):null,f=e=>Math.round(e+(255-e)*.4),h=d!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${d.r}, ${d.g}, ${d.b}, 0.10)`,brandSofter:`rgba(${d.r}, ${d.g}, ${d.b}, 0.15)`,brandBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.20)`,borderHairlineGreen:`rgba(${d.r}, ${d.g}, ${d.b}, 0.28)`,brandBorderStrong:`rgba(${d.r}, ${d.g}, ${d.b}, 0.55)`,composerBorder:`rgba(${d.r}, ${d.g}, ${d.b}, 0.75)`,accentEdge:`rgb(${f(d.r)}, ${f(d.g)}, ${f(d.b)})`}:u?wu(n,r.color.text):{},p=(l?t.backgroundColorDark:t.backgroundColor)??null,g=Is(p),m={...r.color,...g},b=(l?t.textColorDark:t.textColor)??null,y=(e,t)=>(l?t??bu(e??null):e)??null,v={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(l?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,...(t.placeholder!==null?t.placeholderFillsPet===true:r.meta.placeholderFillsPet===true)?{placeholderFillsPet:true}:{},hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy,assistantAvatarUrl:t.assistantAvatarUrl??r.meta.assistantAvatarUrl},color:{...r.color,...h,...g,...zs(y(t.dangerColor,t.dangerColorDark)),...Fs(y(t.successColor,t.successColorDark),l),...Ds(y(t.warningColor,t.warningColorDark),l),...Ls(y(t.infoColor,t.infoColorDark),l),...b!==null?{text:{...h.text??r.color.text,primary:b}}:{},...yu(t.surfaceStyle??null,m),primary:c,accent:a,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:Es(t.spacingUnit??null,r.space,n),radius:t.borderRadius!=null?Os(t.borderRadius,n):Cu(t.radiusScale??null,r.radius,n),type:{...r.type,...mu(r.type,t),size:Ps(t.fontSizeBase??null,r.type.size,n),maxScale:t.accessibilityMaxFontScale??r.type.maxScale,lineHeight:Bs(t.lineHeight??null,r.type.lineHeight,n),weight:t.fontWeightBody==null?r.type.weight:{...r.type.weight,regular:t.fontWeightBody},headingFamily:t.headingFontFamily??r.type.headingFamily,headingWeight:t.fontWeightHeading??r.type.headingWeight,fontSources:t.fontSources??r.type.fontSources,roles:Va(r.type.roles,t.fontSizeBase??null,t.lineHeight??null,t.typeRoles??null),typeScale:t.typeScale??r.type.typeScale,scaleCaps:t.textScaleCaps==null?r.type.scaleCaps:{...r.type.scaleCaps,...t.textScaleCaps}},motion:r.motion,slots:mergeThemeSlots(r.slots,t.slots??null)};return deepFreeze(v)}var hu={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},pu=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function gu(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}function mu(e,t){let r=t.fonts??{},n=t.fontUrls??{},l={...e.families},i={...e.namedFaces},o={...e.fontUrls};for(let e of Ja){let s=hu[e].map(e=>r[e]).find(e=>e!==void 0),a=gu(e)?null:t.fontFamily;s!==void 0?(l[e]=s,i[e]=true):a!==null&&(l[e]=a,i[e]=false);let u=n[e]??(e==="regular"?t.fontUrl:null)??null;u!==null?o[e]=u:s!==void 0&&delete o[e]}for(let e of pu)for(let t of e)i[t]&&e.some(e=>e!==t&&l[e]===l[t])&&(i[t]=false);return{family:l.regular,mono:l.mono,fontUrl:o.regular??null,families:l,namedFaces:i,fontUrls:o}}function bu(e){return e===null?null:deriveDarkVariant(e)}function yu(e,t){if(e===null)return{};let r=t;return{chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}function vu(e,t){return e==null?false:parseColor(e)===parseColor(t)}function xu(e,t,r,n){return vu(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&vu(e.primaryColor,Fo.color.primary)}function wu(e,t){let r=e.color;return{text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}var ku={sharp:.5,default:1,round:1.5};function Cu(e,t,r){if(e===null)return t;let n=ku[e],l=r.radius,i=e=>Math.round(e*n);return{tile:i(l.tile),xs:i(l.xs),sm:i(l.sm),md:i(l.md),lg:i(l.lg),xl:i(l.xl),pill:l.pill}}var Su="Everfur",ju=.5;function resolveTheme(e){return Hu(_u(e),e)}function themeAdjustments(e){let t=_u(e);return ls(t,Hu(t,{...e,highContrast:false}))}function _u(e){let t=e?.branding??null,r=isKnownBrandingSchema(t)?t:null,n=zu(e?.clientOverride??null,lockedFieldsOf(r)),l=e?.colorScheme==="dark"?"dark":"light",i=n?.brightness??r?.brightness??"light",o=Eu((i==="auto"?l:i)==="dark"?Lo:Fo,e?.typeProfile),s=withServerBranding(o,Pu(r));return withServerBranding(s,Pu(n))}function previewTheme(e,t,r){return resolveTheme({...r,branding:parseClientBranding(t),clientOverride:parseClientBranding(e)})}function Ru(e){return e==="placeholder"?"chat_placeholder":cu(e)}var Tu={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 Iu(e,t){return t.has(Ru(e))?true:(Tu[e]??[]).some(e=>t.has(e))}function zu(e,t){if(e===null)return null;let r=false,n={...e};for(let l of Object.keys(e))(e[l]??null)!==null&&(Iu(l,t)||l==="lockedFields")&&(n[l]=null,r=true);let l=n.slots??null;if(l!==null){let e={},i=false;for(let r of Gi){let n=l[r];n!==void 0&&(t.has(`${$a}${r}`)?i=true:e[r]=n)}i&&(n.slots=Object.keys(e).length===0?null:/* @__PURE__ */Object.freeze(e),r=true)}if(!r)return e;let i=/* @__PURE__ */Object.freeze(n);return isEmptyBranding(i)?null:i}function Pu(e){return e===null||e.brightness===null?e:/* @__PURE__ */Object.freeze({...e,brightness:null})}function Eu(e,t){return t!=="phone"?e:deepFreeze({...e,type:{...e.type,scaleCaps:yo}})}function Ou(e,t){if(t===1)return e;let r={};for(let[n,l]of Object.entries(e))r[n]=Math.round(l*t*10)/10;return r}function Au(e){return e===void 0||!Number.isFinite(e)?1:Math.max(ju,e)}var Mu=["content","heading","control","compact","badge"];function Fu(e,t){let r={};for(let n of Mu){let l=e[n],i=typeof l=="number"&&Number.isFinite(l)&&l>=0?l:bo[n];n==="content"||!(t>0)?r[n]=i:r[n]=i===0?t:Math.min(i,t)}return Mu.every(e=>r[e]===bo[e])?bo:r}function Du(e,t){return t>0?Math.min(e,t):e}function Lu(e,t,r,n){let l={};for(let i of Mu)l[i]=n?Ou(e,Du(t,r[i])):e;return l}function Bu(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}function Vu(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return{family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces,headingFamily:e.headingFamily};let l=e.headingFamily!==null&&r!==void 0&&Bu(r,e.headingFamily)===false?null:e.headingFamily,i={...e.families},o={...e.namedFaces};for(let e of Ja)!(i[e]===_o||i[e]===Ro)&&r!==void 0&&Bu(r,i[e])===false&&(i[e]=gu(e)?Ro:_o,o[e]=false),n!==null&&gu(e)&&i[e]===Ro&&(i[e]=n);return{family:i.regular,mono:i.mono,families:i,namedFaces:o,headingFamily:l}}function Hu(e,t){let r=e.meta.displayName.trim().length===0?Su:e.meta.displayName,n=hardenBrandAssetUrl(e.meta.logoUrl),l={};for(let t of Ja){let r=e.type.fontUrls[t];r!==void 0&&(l[t]=hardenHttpsUrl(r))}let i=l.regular??null,o=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,s=Number.isFinite(e.type.maxScale)?e.type.maxScale:jo,a=Au(t?.textScale),u=Fu(e.type.scaleCaps,s),c=t?.scaleTypeSizes===true,d=Number.isFinite(e.type.typeScale)&&e.type.typeScale>0?e.type.typeScale:1,f=Ha(e.type.roles,()=>d),h=c?Ha(f,e=>Du(a,u[e.tier])):f,p=t?.typeProfile==="phone"?Ua(e.type.size,f,d):Ou(e.type.size,d),g=Lu(p,a,u,c),m=Ko(e),b={brightness:e.brightness,highContrast:false,meta:{displayName:r,logoUrl:n,placeholder:e.meta.placeholder,...e.meta.placeholderFillsPet===true?{placeholderFillsPet:true}:{},hidePoweredBy:e.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(e.meta.assistantAvatarUrl)},color:m,space:e.space,radius:e.radius,type:{...e.type,...Vu(e.type,t),fontUrl:i,fontUrls:l,size:g.content,tierSizes:g,scale:a,maxScale:s,scaleCaps:u,roles:h,typeScale:d},motion:o,slots:guardSlotContrast(e.slots,Vs(m),Hs(m))};return t?.highContrast===true?deriveHighContrast(deepFreeze(b)):deepFreeze(b)}var Uu="/widget/v1/entitlements",Nu=304,$u=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(e,t={},r=createRequestFunnel({auth:e})){let n=await r.send("entitlements.fetch",qu(t));return n.ok?Gu(n.value):n.error.httpStatus===Nu?$u:{kind:"failed",error:n.error}}var Wu=64;function qu(e){let t={};return Ju(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Wu?{method:"GET",path:Uu,headers:t,query:{region:e.region}}:{method:"GET",path:Uu,headers:t}}function Gu(e){if(e===null||typeof e!="object"||!Ju(e.revision))return Xu();let t=typeof e.region=="string"?e.region:"",r=Ju(e.ttl_seconds)?e.ttl_seconds:0;/* @__PURE__ */
|
|
45
|
+
return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Qu(e.capabilities),branding:Yu(e),livemode:e.livemode!==false,...Ku(e)})}function Ku(e){let t=e.render_hints,r=e.sms_profile_public??(t!==null&&typeof t=="object"?t.sms_profile_public:void 0);return r!==null&&typeof r=="object"?{smsProfilePublic:r}:{}}function Yu(e){let t=parseClientBranding(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let e=parseClientBranding(r.branding);return e!==null?e:parseClientBranding(r)}return null}function Qu(e){if(e===null||typeof e!="object")/* @__PURE__ */return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Zu(n)&&t.push(/* @__PURE__ */Object.freeze({resource:r,granted:true}));/* @__PURE__ */
|
|
46
|
+
return Object.freeze(t)}function Zu(e){return typeof e=="object"&&e!==null&&e.enabled===true}function Xu(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function Ju(e){return typeof e=="number"&&Number.isFinite(e)}var ec=30;function createEntitlementPoller(e){let t=e.scheduler??tc,r=e.resolve??fetchEntitlements,n=Math.max(1,e.floorSeconds??ec),l=e.rng??Math.random,i=()=>n+l()*n,o=false,s=false,a=null,u=null,c=n,d=0,f=()=>{a!==null&&(t.clear(a),a=null)},h=e=>{s||!o||(c=Math.max(n,e),a=t.set(()=>{a=null,m()},c*1e3))},p=null,g=async()=>{if(s)return null;let t=d;e.onFetch?.();let n=e.region?{cachedRevision:u,region:e.region}:{cachedRevision:u},l;try{l=await r(e.authFor(),n)}catch(r){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:rc(r)}),!s&&t===d&&(e.onSettled?.(),h(i())),null}if(s||t!==d)return null;switch(l.kind){case"updated":u=l.revision,l.smsProfilePublic!==void 0?e.update(l.decisions,l.branding??null,l.livemode!==false,l.smsProfilePublic):e.update(l.decisions,l.branding??null,l.livemode!==false),h(l.ttlSeconds);break;case"notModified":h(c);break;case"failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:l.error.code}),h(i());break;default:h(i())}return e.onSettled?.(),l},m=()=>{let e=g().finally(()=>{p===e&&(p=null)});return p=e,e};return{start(){o||s||(o=true,m())},prime(){return s?Promise.resolve(null):p??m()},stop(){s||(s=true,d++,f())},refresh(){s||!o||(d++,u=null,f(),m())}}}var tc={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e)}};function rc(e){return e instanceof Error?e.message:"poll failed"}var nc=20;function lc(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map,n=e=>{let t=e??"",n=r.get(t);return n===void 0&&(n=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:e}),r.set(t,n)),n},l=/* @__PURE__ */new Map,i=/* @__PURE__ */new Set,o=0,s=/* @__PURE__ */new Map,a=(r,l)=>{let o=r??"",s=t.get(o)??n(r);if(!(s.hasUnread===l.hasUnread&&s.unreadCount===l.unreadCount&&s.conversationId===l.conversationId)){t.set(o,l);for(let e of[...i])e();i.size>0&&l.hasUnread!==null&&l.unreadCount!==null&&e.emit({type:"unread_changed",petRef:r,conversationId:l.conversationId,unreadCount:l.unreadCount,hasUnread:l.hasUnread})}},u=(e,t)=>{s.set(e??"",t);let r=0,n=null;for(let e of t){let t=e.unreadCount??0;r+=t,t>0&&n===null&&(n=e.id)}a(e,/* @__PURE__ */Object.freeze({hasUnread:r>0,unreadCount:r,conversationId:n??t[0]?.id??null,petRef:e}))},c=(e,t,r)=>{if(t.some(e=>e.unreadCount===null)){s.delete(e??""),a(e,/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:t[0]?.id??null,petRef:e}));return}let n=t.slice(0,nc).map(e=>/* @__PURE__ */Object.freeze({id:e.id,unreadCount:e.unreadCount}));if(r||n.length===0){u(e,n);return}let l=new Set(n.map(e=>e.id)),i=(s.get(e??"")??[]).filter(e=>!l.has(e.id));u(e,[...n,...i].slice(0,nc))};return{subscribe(e){return i.add(e),()=>{i.delete(e)}},get(e){return t.get(e??"")??n(e)},refresh(t){let r=t??"",n=l.get(r);if(n!==void 0)return n;let i=e.read(t);if(i===null)return Promise.resolve();let s=o,a=i.then(e=>{s!==o||!e.ok||c(t,e.value.conversations,true)},()=>{}).finally(()=>{l.get(r)===a&&l.delete(r)});return l.set(r,a),a},reportPage(e,t){c(e,t,false)},reportHead(e,t){c(e,t===null?[]:[t],false)},reportRead(e){for(let r of[...t.values()]){let t=s.get(r.petRef??"");t===void 0||!t.some(t=>t.id===e&&(t.unreadCount??0)>0)||u(r.petRef,t.map(t=>t.id===e?/* @__PURE__ */Object.freeze({id:t.id,unreadCount:0}):t))}},reset(){if(o+=1,l.clear(),s.clear(),t.size!==0){t.clear();for(let e of[...i])e()}}}}function ic(e,t,r){let n=en({...t===null?{}:{petRef:t},limit:nc},100);return n.ok?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${n.value}`},{maxAttempts:1}).then(e=>e.ok?on(e.value):err(e.error)):Promise.resolve(err(n.error))}var oc="everfur.notifications.device";var sc="everfur.slots.v2",ac="everfur.slots.installId.v2";var uc=3e3,cc=/* @__PURE__ */Object.freeze([oc,sc,ac]);function dc(e){let{leaving:t,identity:r,hooks:n,telemetry:l}=e;if(t===null||r===null||n.size===0)return null;let i=/* @__PURE__ */Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),o=[...n].map(e=>{try{return Promise.resolve(e(i))}catch(e){return Promise.reject(e)}}),s=(e,t)=>{try{l.track("sdk.logout.hookFailed",{reason:e,count:t,totalCount:o.length})}catch{}},a=Promise.allSettled(o).then(e=>{let t=e.filter(e=>e.status==="rejected").length;t>0&&s("failed",t)});return new Promise(e=>{let t=false,r=()=>{t||(t=true,clearTimeout(n),e())},n=setTimeout(()=>{t||s("timeout",o.length),r()},uc);a.then(r,r)})}function fc(e){let{leaving:t,identity:r,transport:n,sessionId:l}=e,i=r.currentToken();i.catch(()=>{});let o={userRef:t.userRef,currentToken:()=>i,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:n,identity:o,userRef:t.userRef,sessionId:l}}async function hc(e,t){if(cc.length===0)return;let r=await Promise.allSettled(cc.map(t=>e.removeItem(t))),n=r.filter(e=>e.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length})}function pc(){/* @__PURE__ */
|
|
47
|
+
return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function gc(e=pc){let t=/* @__PURE__ */new Set,r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:null}),n=()=>{for(let e of t)e()};return{subscribe(e){return t.add(e),()=>{t.delete(e)}},getSnapshot(){return r},set(e){r=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...e.decisions]),isPending:e.isPending,branding:e.branding??null,...e.livemode===false?{livemode:false}:{},...e.smsProfilePublic!==void 0&&e.smsProfilePublic!==null?{smsProfilePublic:e.smsProfilePublic}:{}}),n()},reset(t){r=/* @__PURE__ */Object.freeze({decisions:e(),isPending:false,branding:t?.keepBranding===true?r.branding??null:null,...t?.keepBranding===true&&r.smsProfilePublic!==void 0?{smsProfilePublic:r.smsProfilePublic}:{}}),n()},setPending(e){r.isPending!==e&&(r=/* @__PURE__ */Object.freeze({...r,isPending:e}),n())}}}var mc="everfur.branding.v1.";function bc(e){let t=[];for(let r of e){let e=r.codePointAt(0);e<128?t.push(e):e<2048?t.push(192|e>>6,128|e&63):e<65536?t.push(224|e>>12,128|e>>6&63,128|e&63):t.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|e&63)}return t}function yc(e){let t=3421674724,r=2216829733;for(let n of bc(e)){r=(r^n)>>>0;let e=r*435,l=Math.floor(e/4294967296),i=e>>>0;t=t*435+l+r*256>>>0,r=i}return t.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")}function vc(e){return`${mc}${yc(e)}`}function xc(e){return e?JSON.stringify(e):null}async function wc(e,t){try{let r=await e.getItem(vc(t));if(r===null)return null;let n=parseClientBranding(JSON.parse(r));return n===null?null:/* @__PURE__ */Object.freeze({...n,logoUrl:hardenBrandAssetUrl(n.logoUrl??null),logoUrlDark:hardenBrandAssetUrl(n.logoUrlDark??null),assistantAvatarUrl:hardenBrandAssetUrl(n.assistantAvatarUrl??null)})}catch{return null}}async function kc(e,t,r){try{r===null?await e.removeItem(vc(t)):await e.setItem(vc(t),r)}catch{}}function Cc(e,t){let r;return{restore(r){wc(e,t).then(e=>{e!==null&&r(e)})},persist(n){let l=xc(n);l!==r&&(r=l,kc(e,t,l))}}}function Sc(){let e=null,t=/* @__PURE__ */new Set;return{get:()=>e,subscribe(e){return t.add(e),()=>{t.delete(e)}},set(r){if(r!==e){e=r;for(let e of[...t])try{e()}catch{}}}}}function jc(e){return{kv:e.kv,scope:e.scope,funnel:e.funnel,branding:Sc(),store:null,disposed:false}}function _c(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}function Rc(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{},...e.appVersion!==void 0?{appVersion:e.appVersion}:{}};return tryResolveClientConfig(r,t===void 0?void 0:{platform:t})}function Tc(e,t){/* @__PURE__ */
|
|
48
|
+
return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(r,n){try{e.trackExpectedFailure(r,t===void 0?n:Ic(r,n,t))}catch{}}})}function Ic(e,t,r){let n=e.indexOf("."),l=typeof t?.surface=="string"?t.surface:n>0?e.slice(0,n):"sdk",i=typeof t?.requestId=="string"?t.requestId:null;return{...Ke(r,l,i),...t}}function zc(e,t,r){if(e===void 0)return;let n=e.onExpectedFailure;return{shouldRetry:(t,r)=>e.shouldRetry(t,r),maxAttempts:t=>e.maxAttempts(t),...typeof n=="function"?{onExpectedFailure:(l,i)=>n.call(e,l,i??Ke(t,r,l.requestId))}:{}}}var Pc=/* @__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 ${tt} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function Ec(e,t,r=Je){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+Pc[r])}function Oc(e){/* @__PURE__ */
|
|
49
|
+
return Object.freeze({request(){return Promise.resolve(err(_c(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return async function*(){r.aborted||(yield n)}()}})}var Ac=/* @__PURE__ */new WeakSet;function Mc(){let e=/* @__PURE__ */new Map,t={async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r)},async removeItem(t){e.delete(t)},async keys(t){return[...e.keys()].filter(e=>e.startsWith(t))}};return Ac.add(t),t}var Fc=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new Lc(e,t)}var Dc=6e4,Lc=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;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 r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new b("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.errorContext=/* @__PURE__ */Object.freeze({sdkVersion:Xe,platform:t?.platform??Je,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:Ze(r?.appVersion)}),this.telemetry=r.telemetry?Tc(r.telemetry,this.errorContext):ue,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,s=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=Oc(l);else if(r.transport!==void 0)o=r.transport;else{let e=Rc(r,t?.platform);e.ok?(s=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=Oc(e.failure))}if(this.configFailure=l,this.reportsDeviceTimezone=l===null&&(t?.reportDeviceTimezone??!i),this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${s??""}`,si(this,this.mintScope),this.transport=o,l!==null&&(Ec(l,this.telemetry,t?.platform),this.emit({type:"error",code:_c(l).code,requestId:null,context:Ke(this.errorContext,"runtime",null)})),this.errorPolicy=zc(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??de,this.upload=r.upload??mr,this.uploadTransport=r.uploadTransport??An,this.imageCache=r.imageCache??Fc,this.kv=r.storage??Mc(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?gc():gc(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:s},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",Bc(e),()=>this.buildChatController(e),Vc),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${Bc(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=lc({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:ic(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=Cc(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=l===null?jc({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let a=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,a&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=gi(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,t=>{this.armTokenRefresh(r,t),this.reportsDeviceTimezone&&!this.disposed&&r===this.identity&&xi(`${this.mintScope}|${e.userRef}`,this.buildAuth(e.userRef))},()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-Dc,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||ni(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&xc(l)===xc(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let s=r();return this.entries.set(i,{controller:s,refCount:1,warm:l}),this.destroyers.set(s,n),s}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:zc(this.errorPolicy,this.errorContext,"chat")}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){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:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await hc(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return dc({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>fc({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>ui(ai(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(Hc(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&hi(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?Hc("prepare"):r===null?null:_c(r),l=this.identity,[i,o,s]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err(xe(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),a=i.ok?o.ok&&(s?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:a})}catch{}if(a==="ready")this.emit({type:"ready"});else if(a==="failed"&&!i.ok&&r===null&&!this.disposed){let e=i.error.requestId??null;this.emit({type:"error",code:i.error.code,requestId:e,context:Ke(this.errorContext,"runtime",e)})}/* @__PURE__ */
|
|
50
|
+
return Object.freeze({status:a,durationMs:u,session:i,entitlements:o,...s?{chat:s}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",Bc(t),()=>this.buildChatController(t),Vc,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function Bc(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function Vc(e){e.dispose()}function Hc(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function Uc(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function Nc(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function $c(e){return e.ok?e:err(Nc(e.error))}function Wc(e){return{send:async(...t)=>$c(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var qc=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),Gc=globalThis,Kc=Gc[qc]??(Gc[qc]=t.createContext(null));Kc.displayName??="EverfurContext";function Yc(){let e=t.useContext(Kc);if(e===null)throw new b("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return Yc().handle}var Qc=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Zc=globalThis,Xc=Zc[Qc]??(Zc[Qc]=t.createContext(Fo));Xc.displayName??="EverfurThemeContext";function useEverfurTheme(){return t.useContext(Xc)}var Jc=()=>()=>{},ed=()=>null;function td(e,r){return t.useSyncExternalStore(r?.subscribe??Jc,r?.get??ed,r?.get??ed)??e}function EverfurThemeProviderCore(e){let{runtime:r}=Yc(),n=r.entitlements,l=t.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot),i=e.seams.useColorScheme(),o=e.seams.useReducedMotion(),s=e.seams.useTextScale(),a=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,c=e.seams.typeProfile,d=e.seams.platformMonoFamily?.(),f=e.seams.isFontRegistered,h=e.clientTheme?rd(e.clientTheme):"",p=t.useMemo(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[h]),g=td(l.branding??null,r.sdkConfigHost?.branding),m=t.useMemo(()=>resolveTheme({branding:g,clientOverride:p,colorScheme:i,reducedMotion:o,textScale:s,scaleTypeSizes:u,highContrast:a,...c===void 0?{}:{typeProfile:c},...d===void 0?{}:{platformMonoFamily:d},...f===void 0?{}:{isFontRegistered:f}}),[g,p,i,o,s,u,c,a,d,f]);e.seams.useResolvedTheme?.(m);let b=e.seams.isDevelopment;return t.useEffect(()=>{b===void 0||!nd(b)||os(themeAdjustments({branding:g,clientOverride:p,colorScheme:i}))},[b,g,p,i]),t.createElement(Xc.Provider,{value:m},e.children)}function rd(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function nd(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:r,user:n,activePet:l,theme:i,warmUp:o,children:s,seams:a}=e,u=`${r?.publishableKey??""}|${r?.apiBaseUrl??""}|${r?.contractVersion??""}`,c=t.useRef(null),d=t.useRef(null),f=t.useRef(r?.onEvent);f.current=r?.onEvent;let h=t.useRef(e=>{f.current?.(e)}),[p,g]=t.useReducer(e=>e+1,0),m=t.useRef(null),b=t.useRef(void 0),y=n?.userRef??null;b.current!==y&&(b.current!==void 0&&(m.current=null),b.current=y);let v=m.current!==null?m.current.user:n??null,x=t.useRef(null),w=t.useRef(void 0),k=l??null;w.current!==k&&(w.current!==void 0&&(x.current=null),w.current=k);let C=x.current!==null?x.current.pet:l??null;(c.current===null||c.current.key!==u||c.current.runtime.isDisposed)&&(c.current!==null&&!c.current.runtime.isDisposed&&(d.current=c.current.runtime),c.current={key:u,runtime:createEverfurRuntime({config:ld(a.withDefaults?a.withDefaults(r):r,h.current),user:v,activePet:C,theme:i??null},{platform:a.platform,...a.eventSourceFactory?{eventSourceFactory:a.eventSourceFactory}:{}})});let S=c.current.runtime,j=t.useRef(null);t.useEffect(()=>{let e=c.current?.runtime;e===void 0||!e.isDisposed||j.current!==e&&(j.current=e,g())}),t.useEffect(()=>{let e=d.current;e!==null&&(d.current=null,e.dispose())});let _=v?.userRef??null;t.useLayoutEffect(()=>{S.setUser(v)},[S,_]),t.useLayoutEffect(()=>{S.setActivePet(C)},[S,C]);let R=t.useRef(null);t.useEffect(()=>(R.current===S&&(R.current=null),()=>{R.current=S,id(()=>{R.current===S&&(R.current=null,S.dispose())})}),[S]),t.useEffect(()=>{o==="onMount"&&S.prepare(C===null?{}:{petRef:C})},[S,o,_,C]);let T=t.useMemo(()=>({setUser:e=>{m.current={user:e},S.setUser(e),g()},setActivePet:e=>{x.current={pet:e},S.setActivePet(e),g()},open:e=>S.open(e),prepare:e=>S.prepare(e),registerPet:(e,t)=>S.registerPet(e,t),updatePet:(e,t)=>S.updatePet(e,t),deletePet:e=>S.deletePet(e),eraseUserData:()=>S.eraseUserData(),logout:()=>{m.current={user:null};let e=S.logout();return g(),e}}),[S,g]),I=t.useMemo(()=>({runtime:S,handle:T,userRef:_,activePet:C,scopeEpoch:S.scopeEpoch,publishableKey:od(r)}),[S,T,_,C,p,u]),z=t.createElement(EverfurThemeProviderCore,{clientTheme:i??null,seams:a.theme,children:s});return t.createElement(Kc.Provider,{value:I},a.wrap?a.wrap(z):z)}function ld(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function id(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function od(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var sd=2;function ad(e,t){let r=e?._xhr;if(!r||typeof r.getResponseHeader!="function"||typeof r.readyState=="number"&&r.readyState<sd)return null;let n;try{n=r.getResponseHeader(t)}catch{return null}return typeof n=="string"&&n.length>0?n:null}function ud(){let e=d.default;return(t,r)=>{let n=globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.chatCards.v1")]?.tap?.(t,r),l=new e(t,{method:r.method,headers:n?{...r.headers,...n.headers}:r.headers,pollingInterval:r.pollingInterval??0,...r.body!==void 0?{body:r.body}:{}});return n?.watch(l),Object.assign(l,{getResponseHeader:e=>ad(l,e)})}}function cd(){let e=r.useColorScheme();return e==="dark"?"dark":e==="light"?"light":null}function dd(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function fd(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=true,t=r.AccessibilityInfo?.isReduceMotionEnabled;if(typeof t=="function"){let l=t.call(r.AccessibilityInfo);l!=null&&typeof l.then=="function"&&l.then(t=>{e&&n(t===true)},()=>{})}let l=r.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",e=>n(e===true));return()=>{e=false,l?.remove?.()}},[]),e}function hd(){let e=r.PixelRatio?.getFontScale;if(typeof e!="function")return 1;try{let t=e.call(r.PixelRatio);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}catch{return 1}}function pd(e){let t=r.Dimensions?.addEventListener;if(typeof t!="function")return()=>{};let n=t.call(r.Dimensions,"change",e);return()=>n?.remove?.()}function gd(){return t.useSyncExternalStore(pd,hd,hd)}function md(){try{let e=r.Platform?.OS;return typeof e=="string"?e:null}catch{return null}}function bd(){return md()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function yd(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=true,{query:t,event:l}=bd(),i=r.AccessibilityInfo?.[t];if(typeof i!="function")return()=>{};try{let t=i.call(r.AccessibilityInfo);dd(t)&&Promise.resolve(t).then(t=>{e&&n(t===!0)},()=>{})}catch{}let o=r.AccessibilityInfo?.addEventListener,s=typeof o=="function"?o.call(r.AccessibilityInfo,l,e=>n(e===true)):void 0;return()=>{e=false,s?.remove?.()}},[]),e}function vd(){return md()==="ios"?"Menlo":Ro}function xd(){return globalThis.__DEV__!==false}var wd=/* @__PURE__ */new Set;function kd(e){if(!xd()||wd.has(e))return;wd.add(e);let t=globalThis.console;try{t?.warn?.(`[everfur] The theme names the font face "${e}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function Cd(e){let t=globalThis.expo?.modules?.ExpoFontLoader,r=t?.getLoadedFonts;if(typeof r!="function")return null;let n;try{n=r.call(t)}catch{return null}if(!Array.isArray(n)||n.length===0)return null;let l=n.includes(e);return l||kd(e),l}var Sd=/* @__PURE__ */new Set;function jd(e){let t=[];return e.type.fontSources.length>0&&t.push("fontSources"),Object.values(e.type.fontUrls).some(e=>typeof e=="string"&&e.length>0)&&t.push("fontUrls"),t}var _d=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function Rd(e){if(!xd())return;let t=jd(e).filter(e=>!Sd.has(e));if(t.length===0)return;for(let e of t)Sd.add(e);let r=globalThis.console;try{r?.warn?.(`[everfur] The theme sets ${t.map(e=>_d[e]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function Td(e){t.useEffect(()=>{try{Rd(e)}catch{}},[e])}var Id=/* @__PURE__ */Object.freeze({useColorScheme:cd,useReducedMotion:fd,useTextScale:gd,useHighContrast:yd,scaleTypeSizes:false,typeProfile:"phone",platformMonoFamily:vd,isFontRegistered:Cd,useResolvedTheme:Td,isDevelopment:xd});function zd(e){return t.createElement(n.SafeAreaProvider,null,e)}var Pd=/* @__PURE__ */Object.freeze({platform:"react-native",...r.Platform.OS==="web"?{}:{eventSourceFactory:ud()},wrap:zd,theme:Id});function EverfurProvider(e){return t.createElement(EverfurProviderCore,{...e,seams:Pd})}function useCapability(e){let{runtime:r}=Yc(),n=r.entitlements,l=t.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot);return t.useMemo(()=>decideCapability(e,l.decisions,{isPending:l.isPending}),[e,l])}function Ed(e){let{runtime:r}=Yc(),n=r.entitlements,l=t.useCallback(e=>n===void 0?()=>{}:n.subscribe(e),[n]),i=t.useCallback(()=>{if(n===void 0)return false;let t=n.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[n,e]);return t.useSyncExternalStore(l,i,i)}var Od=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[Od[t]]}}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[Od[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function Ad(e){return e<=450?"regular":e<=650?"medium":"bold"}var Md={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(e,t){let r=Fd.get(e);r===void 0&&(r=/* @__PURE__ */new Map,Fd.set(e,r));let n=r.get(t);if(n!==void 0)return n;let l=Dd(e,t);return r.set(t,l),l}var Fd=/* @__PURE__ */new WeakMap;function Dd(e,t){let r=e.type.roles[t],n=r.weight==="400"&&r.face!=="mono"?e.type.weight.regular:r.weight,l=Ad(Number(n)),i=r.face==="mono"?face(e,Md[l]):r.face==="heading"?headingFace(e,l):face(e,l),o=r.face==="heading"?e.type.headingWeight??n:n,s=i.fontWeight===void 0?i:{fontFamily:i.fontFamily,fontWeight:o},a=r.size,u={...s,fontSize:a,lineHeight:Math.round(a*r.lineHeight*100)/100};return r.letterSpacing!==0&&(u.letterSpacing=Math.round(a*r.letterSpacing*100)/100),r.uppercase&&(u.textTransform="uppercase"),/* @__PURE__ */Object.freeze(u)}function Ld(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}function Text({tier:e,variant:n,...l}){let i=useEverfurTheme(),o=n===void 0?void 0:i.type.roles[n],s=Ld(i.type,e??o?.tier??"content"),a=n===void 0?l:{...l,style:[{...textRole(i,n),color:i.color.text.primary,flexShrink:1},l.style]};return t.createElement(r.Text,s===void 0?a:{maxFontSizeMultiplier:s,...a})}var Bd=t.forwardRef(function(e,n){return t.createElement(r.TextInput,{...e,...n===null?{}:{ref:n}})});var Vd=class extends t.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:r,resetKey:n}){return t.createElement(Vd,{fallback:r,resetKey:n,children:t.createElement(RenderHost,{render:e})})}var Hd=48;function Ud(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:r,children:n,renderDisabled:l,renderPending:o,style:s}=e,a=useCapability(r),u=t.useMemo(()=>Ud(a),[a]);switch(u){case"enabled":return n;case"pending":return o?/* @__PURE__ */i.jsx(HostRender,{render:o,fallback:/* @__PURE__ */i.jsx(PendingSkeleton,{capability:r,style:s})}):/* @__PURE__ */i.jsx(PendingSkeleton,{capability:r,style:s});case"disabled":return l?/* @__PURE__ */i.jsx(HostRender,{render:()=>l(a),fallback:/* @__PURE__ */i.jsx(OffState,{decision:a,style:s}),resetKey:a}):/* @__PURE__ */i.jsx(OffState,{decision:a,style:s});default:return assertNever(u)}}function PendingSkeleton({capability:e,style:n}){let l=useEverfurTheme(),o=t.useMemo(()=>Nd(l),[l]);/* @__PURE__ */
|
|
51
|
+
return i.jsx(r.View,{style:[o.offstate,n],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:/* @__PURE__ */i.jsx(r.View,{style:o.skeletonBar})})}function OffState({decision:e,style:n}){let l=useEverfurTheme(),o=t.useMemo(()=>Nd(l),[l]),s=e.disabled?.reason??"";/* @__PURE__ */
|
|
52
|
+
return i.jsx(r.View,{style:[o.offstate,n],accessible:true,accessibilityRole:"text",accessibilityLabel:s,children:s.length>0?/* @__PURE__ */i.jsx(Text,{style:o.offstateText,children:s}):null})}function Nd(e){let{color:t,space:n,radius:l,type:i}=e;return r.StyleSheet.create({offstate:{minHeight:Hd,justifyContent:"center",paddingHorizontal:n.lg,paddingVertical:n.md,backgroundColor:t.surfaceCream,borderRadius:l.md,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...face(e,"regular"),fontSize:i.size.body,lineHeight:Math.round(i.size.body*i.lineHeight.normal),color:t.text.muted},skeletonBar:{height:n.md,borderRadius:l.xs,backgroundColor:t.brandSofter}})}var $d=t.createContext(null);function TelevetHostOutlet(){let e=t.useContext($d);return e===null?null:/* @__PURE__ */i.jsx(e,{})}var Wd=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function qd(){let e=globalThis,t=e[Wd];if(t!==void 0)return t;let r={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return e[Wd]=r,r}function Gd(e){let t=qd();t.snapshot=/* @__PURE__ */Object.freeze({...t.snapshot,...e});for(let e of[...t.listeners])try{e()}catch{}}function Kd(e){let t=qd().presenter;if(t===null)return"absent";try{return t(e)===!1?"declined":"presented"}catch(e){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",e),"threw"}}function Yd(e){let t=qd();return t.listeners.add(e),()=>{t.listeners.delete(e)}}function Qd(){return qd().snapshot}function Zd(){return qd().hosts.length>0}function Xd(e){if(!Zd())return false;let t=/* @__PURE__ */Object.freeze({...e});return Gd({request:t,serial:qd().snapshot.serial+1}),true}function Jd(){qd().snapshot.request!==null&&Gd({request:null})}function ef(){let e=qd(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],Gd({activeHost:e.hosts[0]??null}),t}function tf(e){let t=qd();t.hosts=t.hosts.filter(t=>t!==e);let r=t.hosts[0]??null;Gd(r===null?{activeHost:r,request:null}:{activeHost:r})}function rf(e){let t=null;return()=>{if(t!==null)return t;let r=e();return t=r,r.then(void 0,()=>{t===r&&(t=null)}),r}}function nf(e){let[r,n]=t.useState(null);t.useEffect(()=>{let e=ef();return n(e),()=>{tf(e)}},[]);let l=t.useSyncExternalStore(Yd,Qd,Qd),i=r!==null&&l.activeHost===r?l.request:null,[o,s]=t.useState(null),a=i!==null&&o===null;return t.useEffect(()=>{if(!a)return;let t=true;return e().then(e=>{t&&s(()=>e)},e=>{t&&(console.warn("[everfur] The in-app vet visit could not load its screens.",e),Jd())}),()=>{t=false}},[a,e]),i===null||o===null?null:{module:o,request:i,serial:l.serial,dismiss:Jd}}var lf=rf(()=>Promise.resolve(f));function EverfurTelevetHost({onAddToCalendar:e,onPickMedia:t,primaryVet:r,onFindEmergencyVet:n}={}){let l=nf(lf);if(l===null)return null;let{EverfurTelevetModal:o}=l.module;/* @__PURE__ */
|
|
53
|
+
return i.jsx(o,{request:l.request,onClose:l.dismiss,...e?{onAddToCalendar:e}:{},...t?{onPickMedia:t}:{},...r?{primaryVet:r}:{},...n?{onFindEmergencyVet:n}:{}},l.serial)}var of=640,sf=600,af=/* @__PURE__ */Object.freeze({width:0,height:0}),uf="useWindowDimensions"in c&&typeof c.useWindowDimensions=="function"?c.useWindowDimensions:()=>af,cf=/* @__PURE__ */Object.freeze({width:"100%",maxWidth:of,alignSelf:"center"});/* @__PURE__ */Object.freeze({...cf,flex:1});var df=/* @__PURE__ */Object.freeze({...cf,flexGrow:1,flexShrink:1});function ff(){return uf().width>=sf}function hf(e="flow"){let{width:t}=uf();if(t<sf)return null;if(e==="flow")return cf;let r=Math.max(0,Math.round((t-of)/2));return{left:r,right:r}}function pf(e,t){return t===null?e:[e,t]}var gf=/* @__PURE__ */Symbol.for("@everfur/sdk#InSdkColumn@v1"),mf=globalThis,bf=mf[gf]??(mf[gf]=t.createContext(false));bf.displayName??="EverfurInSdkColumn";function SdkTabletColumn({children:e,style:n,testID:l}){let o=ff(),s=t.useContext(bf);return!o||s?e:/* @__PURE__ */i.jsx(r.View,{style:n===void 0?df:[df,n],testID:l??"everfur-tablet-column",children:/* @__PURE__ */i.jsx(bf.Provider,{value:true,children:e})})}var yf="Go to the nearest emergency vet now.";var vf=/* @__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",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",sourcesHeading:"Sources",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:yf,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",capReached:"You've used your {cap} free messages this month.",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 xf(e,t){return e.replace(/\{(\w+)\}/g,(e,r)=>{let n=t[r];return n===void 0?e:String(n)})}function wf(e){return e?.trim()||vf.emptyTitlePetFallback}function kf(e,t){return xf(e,{petName:wf(t)})}var Cf="tel:+18884264435";var Sf=(e,t=4e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null;function jf(e){let t=Sf(e,2048);return t===null?null:/^https:\/\/[^\s]+$/i.test(t)?t:null}var _f=6;function Rf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=400?e:null}function Tf(e,t,r){if(!Array.isArray(e))/* @__PURE__ */return Object.freeze([]);let n=[];for(let l of e){if(n.length>=r)break;if(l===null||typeof l!="object"||Array.isArray(l))continue;let e=t(l);e!==null&&n.push(e)}/* @__PURE__ */
|
|
54
|
+
return Object.freeze(n)}function If(e){let t=Sf(e.title,80),r=Sf(e.body,600);return t===null||r===null?null:/* @__PURE__ */Object.freeze({title:t,body:r})}function zf(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,r=[];if(Array.isArray(t.gallery))for(let e of t.gallery){let t=jf(e);t!==null&&r.length<_f&&r.push(t)}let n=Tf(t.doses,e=>{let t=Sf(e.label,60),r=Sf(e.amount,60);return t===null||r===null?null:/* @__PURE__ */Object.freeze({label:t,amount:r,minLb:Rf(e.minLb??e.min_lb),maxLb:Rf(e.maxLb??e.max_lb)})},_f),l=Tf(t.details,If,_f),i=t.fit,o=i!==null&&typeof i=="object"&&!Array.isArray(i)?If(i):null,s=o!==null&&i.pet===true?/* @__PURE__ */Object.freeze({...o,pet:true}):o,a=/* @__PURE__ */Object.freeze({kicker:Sf(t.kicker,80),gallery:/* @__PURE__ */Object.freeze(r),doses:n,details:l,fine:Sf(t.fine,300),fit:s});return a.kicker===null&&r.length===0&&n.length===0&&l.length===0&&a.fine===null&&s===null?void 0:a}var Pf=128;var Ef=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),Of=/* @__PURE__ */new Set(["y","c","g","r"]),Af=/* @__PURE__ */new Set(["done","now","next"]),Mf=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,Ff=(e,t=1e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null,Df=e=>typeof e=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(e)?e:null,Lf=e=>typeof e=="string"&&Ef.has(e)?e:null;function Bf(e){let t=Ff(e,2048);return t===null||/\s/.test(t)?null:/^https:\/\/[^/]/i.test(t)||/^\/(?![/\\])/.test(t)?t:null}var Vf=e=>typeof e=="number"&&Number.isInteger(e)?String(e):Ff(e,Pf);function Hf(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function Uf(e){/* @__PURE__ */
|
|
55
|
+
return Object.freeze(Object.fromEntries(Object.entries(e).filter(([,e])=>e!=null)))}function Nf(e,t,r=20){if(!Array.isArray(e))return null;let n=[];for(let l of e){if(n.length>=r)break;let e=t(l);e!==null&&n.push(e)}return n.length===0?null:/* @__PURE__ */Object.freeze(n)}var $f=(e,t=12,r=300)=>Nf(e,e=>Ff(e,r),t);function Wf(e){let t=Mf(e),r=Ff(t?.kicker,120),n=Ff(t?.title,300);if(t===null||r===null||n===null)return null;let l=Mf(t.risk),i=Mf(t.odds),o=Mf(t.quote),s=Mf(t.jump);return Uf({kicker:r,title:n,sources:Nf(t.sources,e=>{let t=Ff(Mf(e)?.label,60);return t===null?null:Uf({label:t,kind:Df(Mf(e)?.kind)})},6),risk:Ff(l?.lead,300)===null?null:Uf({lead:Ff(l?.lead,300),body:Ff(l?.body),kind:Df(l?.kind)}),odds:Ff(i?.label,120)===null||Ff(i?.from,20)===null||Ff(i?.to,20)===null?null:Uf({label:Ff(i?.label,120),tag:Ff(i?.tag,40),from:Ff(i?.from,20),to:Ff(i?.to,20),toLabel:Ff(i?.toLabel,120)}),quote:Ff(o?.text)===null?null:Uf({kicker:Ff(o?.kicker,120),tag:Ff(o?.tag,40),text:Ff(o?.text)}),jump:Ff(s?.title,300)===null||Ff(s?.go,60)===null?null:Uf({title:Ff(s?.title,300),go:Ff(s?.go,60)}),report:qf(t.report)})}function qf(e){let t=Mf(e),r=Ff(t?.label,120),n=Ff(t?.text,1200);return r===null||n===null?null:Uf({label:r,text:n,actions:$f(t?.actions,5,300)})}function Gf(e){let t=Mf(e),r=Ff(t?.title,300),n=Nf(t?.steps,e=>{let t=Mf(e),r=Ff(t?.title,300),n=t?.tone;return r===null?null:Uf({title:r,body:Ff(t?.body),source:Ff(t?.source,200),tone:typeof n=="string"&&Of.has(n)?n:null,icon:Lf(t?.icon),fromVet:t?.fromVet===true?true:null})});return r===null||n===null?null:Uf({title:r,label:Ff(t?.label,60),steps:n})}function Kf(e){let t=Mf(e),r=Ff(t?.title,300);if(t===null||r===null)return null;let n=Mf(t.rating),l=Mf(t.reviews),i=Mf(t.why),o=Mf(i?.score),s=Mf(t.dose),a=Mf(t.ingredients),u=Nf(l?.items,e=>{let t=Mf(e),r=t?.stars,n=Ff(t?.text),l=Ff(t?.by,80);return typeof r!="number"||!Number.isFinite(r)||r<1||r>5||n===null||l===null?null:Uf({stars:Math.round(r),text:n,by:l})},5),c=Nf(i?.rows,e=>{let t=Mf(e),r=Ff(t?.chip,40),n=Ff(t?.title,300);return r===null||n===null?null:Uf({chip:r,kind:Df(t?.kind),title:n,body:Ff(t?.body)})}),d=Nf(s?.stats,e=>{let t=Mf(e),r=Ff(t?.value,40),n=Ff(t?.label,120),l=t?.kind;return r===null||n===null?null:Uf({value:r,label:n,kind:l==="weight"||l==="dose"||l==="days"?l:null})},6),f=$f(a?.items,12,80);return Uf({title:r,none:t.none===true?true:null,hidden:t.none===true&&t.hidden===true?true:null,productId:Vf(t.productId),partnerSku:Ff(t.partnerSku,200),rating:Ff(n?.value,20)===null?null:Uf({value:Ff(n?.value,20),label:Ff(n?.label,120)}),line:Ff(t.line),reviews:Ff(l?.label,200)===null||u===null?null:Uf({label:Ff(l?.label,200),items:u}),checkoutLine:Ff(t.checkoutLine,300),why:Ff(i?.title,200)===null||c===null?null:Uf({title:Ff(i?.title,200),rows:c,score:Ff(o?.text,200)===null||Ff(o?.value,20)===null?null:Uf({text:Ff(o?.text,200),value:Ff(o?.value,20)})}),dose:Ff(s?.title,200)===null||d===null?null:Uf({title:Ff(s?.title,200),stats:d,note:Ff(s?.note)}),doseLabel:Ff(t.doseLabel,120),ingredients:f===null?null:Uf({label:Ff(a?.label,200),items:f}),proof:Ff(t.proof,300),trust:Nf(t.trust,e=>{let t=Mf(e),r=Lf(t?.icon),n=Ff(t?.label,120);return r===null||n===null?null:Uf({icon:r,label:n})},6),more:Ff(t.more,120),fine:Ff(t.fine),checkin:Ff(t.checkin,200),detail:zf(t.detail)??null})}function Yf(e){let t=Mf(e),r=Ff(t?.title,200),n=Nf(t?.items,e=>{let t=Mf(e),r=Ff(t?.title,300),n=Ff(t?.body);return r===null||n===null?null:Uf({title:r,body:n,urgent:t?.urgent===true?true:null,callVet:t?.callVet===true?true:null})});return r===null||n===null?null:Uf({title:r,items:n})}function Qf(e){let t=Mf(e),r=Ff(t?.title,200),n=$f(t?.questions,12,300),l=Ff(t?.add,80),i=Ff(t?.added,80);return r===null||n===null||l===null||i===null?null:Uf({title:r,questions:n,add:l,added:i})}function Zf(e){let t=Mf(e),r=Ff(t?.title,200),n=Nf(t?.items,e=>{let t=Mf(e),r=Ff(t?.key,Pf),n=Ff(t?.title,300),l=Ff(t?.action,80),i=Vf(t?.productId),o=Ff(t?.added,80)??(i!==null?l:null);return r===null||n===null||l===null||o===null?null:Uf({key:r,productId:i,title:n,body:Ff(t?.body),price:Ff(t?.price,40),was:Ff(t?.was,40),tag:Ff(t?.tag,40),imageUrl:Bf(t?.imageUrl),icon:Lf(t?.icon),kind:Df(t?.kind),action:l,added:o,owned:t?.owned===true?true:null,detail:zf(t?.detail)??null})},6);return r===null||n===null?null:Uf({title:r,items:n})}function Xf(e){let t=Mf(e),r=Ff(t?.kicker,120),n=Ff(t?.title,120);return t===null||r===null||n===null?null:Uf({kicker:r,title:n,icon:Lf(t.icon),track:Nf(t.track,e=>{let t=Mf(e),r=Ff(t?.title,120),n=t?.state;return r===null?null:Uf({title:r,detail:Ff(t?.detail,120),state:typeof n=="string"&&Af.has(n)?n:null,tag:Ff(t?.tag,40)})},6),heading:Ff(t.heading,200),rows:Nf(t.rows,e=>{let t=Mf(e),r=Lf(t?.icon),n=Ff(t?.label,120);if(r===null||n===null)return null;if(t?.fromVet===true)return Uf({icon:r,label:n,text:"",fromVet:true});let l=Ff(t?.text,300);return l===null?null:Uf({icon:r,label:n,text:l})},6),note:Ff(t.note,300),action:Ff(t.action,80)})}function healthPlanFocusDesignFromWire(e){let t=Mf(e),r=Ff(t?.title,300),n=Kf(t?.pick);if(t===null||r===null||n===null)return null;let l=Mf(t.byline);return Uf({eyebrow:Ff(t.eyebrow,120),title:r,subtitle:Ff(t.subtitle,300),subtitleNoRecords:Ff(t.subtitleNoRecords,300),headImageUrl:Bf(t.headImageUrl),byline:Ff(l?.name,120)===null?null:Uf({name:Ff(l?.name,120),role:Ff(l?.role,120),imageUrl:Bf(l?.imageUrl),shortName:Ff(l?.shortName,60)}),focus:Wf(t.focus),routine:Gf(t.routine),pick:n,signs:Yf(t.signs),checkup:Qf(t.checkup),extras:Zf(t.extras),wait:Xf(t.wait),fine:Ff(t.fine),checkoutRows:Nf(t.checkoutRows,e=>{let t=Mf(e),r=Lf(t?.icon),n=Ff(t?.label,60),l=Ff(t?.value,200);return r===null||n===null||l===null?null:Uf({icon:r,label:n,value:l})},6)})}function healthPlanPageFromWire(e,t){let r=Mf(e);if(r===null||!("page"in r))return null;let n=Mf(r.pet),l=n?.sex;/* @__PURE__ */
|
|
56
|
+
return Object.freeze({petRef:Ff(r.pet_ref,Pf)??t,pet:/* @__PURE__ */Object.freeze({name:Ff(n?.name,120),species:Ff(n?.species,60),sex:l==="female"||l==="male"?l:null,breed:Ff(n?.breed,120),weightKg:Hf(n?.weight_kg),weightLb:Hf(n?.weight_lb)}),checkout:r.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(r.page),vetReviewed:r.vet_reviewed===true,trackingTextsEnabled:r.tracking_texts_enabled===true})}function Jf(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function eh(e){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${e}: the response was not the expected shape`})}function th(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}var rh=e=>typeof e=="string"&&e.length>0&&e.length<=Pf;function nh(e){return`/widget/v1/pets/${encodeURIComponent(e)}/plan`}async function lh(e,t,r){if(!rh(t))return err(Jf("petRef must be 1..128 characters"));let n=await e.send("healthPlan.page.read",{method:"GET",path:`${nh(t)}/page`,...r?.signal?{signal:r.signal}:{}});if(!n.ok)return err(n.error);let l=healthPlanPageFromWire(n.value,t);return l===null?err(eh("healthPlan.page.read")):ok(l)}var ih=/* @__PURE__ */new WeakMap;function oh(e){let t=ih.get(e);if(t!==void 0)return t;let r=sh(e);return ih.set(e,r),r}function sh(e){return{getPage:(t,r)=>{if(e.isDisposed)return Promise.resolve(err(th("getPage")));let{services:n}=e.registry,l=Wc(createRequestFunnel({auth:n.authFor(null),...n.errorPolicy?{errorPolicy:n.errorPolicy}:{}}));return lh(l,t,r)}}}function ah(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function uh(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function ch(e,...t){if(typeof e=="function")try{let r=e(...t);return uh(r)&&Promise.resolve(r).then(void 0,ah),r}catch(e){ah(e);return}}var dh=/* @__PURE__ */new WeakMap;function fh(e){if(typeof e!="function")return;let t=dh.get(e);if(t!==void 0)return t;let r=(...t)=>{ch(e,...t)};return dh.set(e,r),r}function hh(e,...t){let r;try{r=e(...t)}catch(e){return ah(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(r).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var ph=6e4;function gh({lifecycle:e,refreshKey:r,readyAt:n,revalidate:l,refresh:i,now:o=Date.now}){let s=t.useRef({readyAt:n,revalidate:l,refresh:i??l,now:o});s.current={readyAt:n,revalidate:l,refresh:i??l,now:o},t.useEffect(()=>{if(e==null)return;let t=ch(()=>e.onForeground(()=>{let{readyAt:e,revalidate:t,now:r}=s.current;e!==null&&r()-e>=ph&&t()}));return()=>{typeof t=="function"&&ch(t)}},[e]);let a=t.useRef(r);t.useEffect(()=>{Object.is(a.current,r)||(a.current=r,s.current.refresh())},[r])}var mh=ph,bh=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function yh(){let e=globalThis,t=e[bh];if(t instanceof WeakMap)return t;let r=/* @__PURE__ */new WeakMap;return e[bh]=r,r}function vh(e,t,r,n,l){let i=yh(),o=i.get(t);o===void 0&&(o=/* @__PURE__ */new Map,i.set(t,o));let s=o,a=`${r}\0${n}`,u=s.get(a);if(!l&&u!==void 0&&(u.at===null||Date.now()-u.at<mh))return u.promise;let c={at:null,promise:e.getPage(n).then(e=>(s.get(a)===c&&(e.ok||Uc(e.error)?c.at=Date.now():s.delete(a)),e))};return s.set(a,c),c.promise}function useHealthPlanPage(e){let{userRef:r,runtime:n}=Yc(),l=t.useMemo(()=>oh(n),[n]),i=e.repository,o=i??l,s=t.useCallback((e,t)=>i!==void 0||r==null?o.getPage(e):vh(l,n,r,e,t),[i,o,l,n,r]),{petRef:a}=e,u=e.enabled!==false&&r!=null&&a!==null,[c,d]=t.useState({phase:"idle",petRef:null,page:null,error:null}),f=t.useRef(0),h=t.useRef(0),p=t.useCallback(async e=>{let t=++f.current;if(!u||a===null){d(e=>e.phase==="idle"&&e.petRef===null?e:{phase:"idle",petRef:null,page:null,error:null});return}d(e=>({phase:"loading",petRef:a,page:e.petRef===a?e.page:null,error:null}));let r=await s(a,e);t===f.current&&(r.ok?d({phase:"ready",petRef:a,page:r.value,error:null,readyAt:Date.now()}):Uc(r.error)?d({phase:"ready",petRef:a,page:null,error:null,missing:true,readyAt:Date.now()}):d({phase:"failed",petRef:a,page:null,error:r.error}))},[u,a,s]),g=t.useCallback(()=>p(true),[p]),m=c.phase==="ready"&&c.petRef===a,b=t.useCallback(async()=>{if(!u||a===null||!m)return;let e=f.current,t=++h.current,r=await s(a,true);e!==f.current||t!==h.current||!r.ok||d(e=>e.phase==="ready"&&e.petRef===a?{phase:"ready",petRef:a,page:r.value,error:null,readyAt:Date.now()}:e)},[u,a,m,s]);gh({lifecycle:e.lifecycle,refreshKey:e.refreshKey,readyAt:m?c.readyAt??null:null,revalidate:()=>{b()},refresh:()=>{m?b():g()}}),t.useEffect(()=>(p(false),()=>{f.current+=1}),[p]);let y=u&&c.petRef!==a;return t.useMemo(()=>({phase:y?"loading":c.phase,page:y?null:c.page,error:y?null:c.error,missing:!y&&c.missing===true,refresh:g}),[y,c,g])}var xh=/* @__PURE__ */Object.freeze({branding:null}),wh=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>xh});function kh(e){return e?Object.keys(e).sort().map(t=>`${t}=${String(e[t])}`).join("&"):""}function Ch(e){let{runtime:r}=Yc(),n=r?.entitlements??wh,l=t.useCallback(()=>n.getSnapshot()?.branding??null,[n]),i=td(t.useSyncExternalStore(n.subscribe,l,l),r?.sdkConfigHost?.branding),o=kh(e);return t.useMemo(()=>{let t=i?.lockedFields??null;return{presentation:resolvePresentation({server:i?.presentation??null,locked:t,client:e??null}),isLocked:e=>isPresentationFieldLocked(e,t)}},[i,o])}function Sh(e){let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=n);return t}function jh(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}function _h(e){let t=Ee(e);return t===null?null:{reached:vf.capReached.replace("{cap}",String(t.limit)),guidance:t.emergencyGuidance??null}}function Rh(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}function Th(e,t="native"){if(e.messages.length===0)return null;let r=e.status==="error"?e.error:null;if(r!==null){let e=Rh(r),n=t==="web",l=_h(r);return{tone:"error",title:l!==null?l.reached:e?vf.turnUnreachableTitle:n?vf.turnFailedTitleWeb:vf.turnFailedTitle,body:r.displayMessage,actionLabel:e?vf.turnStartNewChat:n?vf.retry:vf.turnRetry,action:e?"startNew":"retry",...l!==null&&l.guidance!==null?{guidance:l.guidance}:{}}}return e.stopped===true?{tone:"neutral",title:vf.turnStoppedTitle,body:vf.turnStoppedBody,actionLabel:vf.turnRetry,action:"retry"}:null}function Ih(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}var zh=3,Ph=/* @__PURE__ */Object.freeze([]);function Eh(e){let t=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||t===void 0||t.role!=="assistant")return Ph;let r=/* @__PURE__ */new Set,n=[];for(let t of e.suggestedPrompts){let e=t.trim(),l=e.replace(/\s+/g," ").toLowerCase();if(!(l.length===0||r.has(l))&&(r.add(l),n.push(e),n.length===zh))break}/* @__PURE__ */
|
|
57
|
+
return Object.freeze(n)}var Oh=5;function Ah(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function Mh(e,t){if(t===void 0)return Eh(e);let r=e.messages[e.messages.length-1];if(e.isStreaming||e.status==="error"||r===void 0||r.role!=="assistant")return Ph;let n=Math.max(1,Math.min(Oh,Math.floor(t.count??zh))),l=null;for(let t=e.messages.length-1;t>=0;t-=1){let r=e.messages[t];if(r!==void 0&&r.role==="user"){l=r.text;break}}let i=e=>e.trim().replace(/\s+/g," ").toLowerCase(),o=new Set(l===null?[]:[i(l)]),s=[],a=e=>{let r=e.trim(),l=i(r);s.length>=n||l.length===0||o.has(l)||Ah(t.exclude,r)||(o.add(l),s.push(r))};for(let t of e.suggestedPrompts)a(t);let u=[];try{u=typeof t.fill=="function"?t.fill(l):t.fill??[]}catch{u=[]}for(let e of Array.isArray(u)?u:[])typeof e=="string"&&a(e);/* @__PURE__ */
|
|
58
|
+
return Object.freeze(s)}function Fh(e){return e.sender?.displayName??vf.senderVet}function Dh(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}var Lh=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 Bh(e,t){if(e===void 0)return false;if(typeof e=="function")try{return e(t)===!0}catch{return false}return e.lastIndex=0,e.test(t)}function Vh(e,t,r){let n=t.chatFollowUpsExcludeTelevet,l=e?.count!==void 0&&!r?e.count:t.chatFollowUpCount;if(e===void 0&&l===zh&&!n)return;if(l<=0)return{...e??{},count:1,exclude:NONE,fill:[]};let i=e?.exclude,o=n?e=>Lh.test(e)||Bh(i,e):i;return{...e??{},count:l,...o!==void 0?{exclude:o}:{}}}var Hh="pet_not_registered";function Uh(e){return e!=null&&e.reasonCode===Hh}var Nh=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function $h(e,r,n){let{runtime:l,userRef:i,scopeEpoch:o}=Yc(),s=t.useCallback((e,t)=>{let r=l.registry.services.authFor(i);return ui(ai(l,r,e,t),()=>createPetsRepository(r).registerPet(e,t))},[l,i,o]),a=t.useMemo(()=>r===void 0?null:ci(r),[r]),[u,c]=t.useState({key:null,status:"idle",error:null,registered:null}),d=t.useRef(0),f=t.useRef(n);f.current=n;let h=e===null||a===null?null:`${String(i)}|${o}|${e}|${a}`,p=t.useCallback(()=>{if(e===null||r===void 0||h===null)return;let t=++d.current;c({key:h,status:"registering",error:null,registered:null}),s(e,r).then(e=>{t===d.current&&(e.ok?(c({key:h,status:"registered",error:null,registered:e.value}),f.current?.()):c({key:h,status:"failed",error:e.error,registered:null}))})},[s,e,h]);t.useEffect(()=>{if(h===null){d.current+=1;return}return p(),()=>{d.current+=1}},[h,p]);let g=t.useCallback(()=>{u.status==="failed"&&p()},[u.status,p]);return t.useMemo(()=>h===null?Nh:u.key!==h?{status:"registering",error:null,registered:null,retry:g}:{status:u.status,error:u.error,registered:u.registered,retry:g},[h,u,g])}var Wh=/* @__PURE__ */Object.freeze({});function qh(e){let[r,n]=t.useState(Wh),l=t.useRef(null),i=t.useRef([]);i.current=e.map(e=>e.id),t.useEffect(()=>{if(e.length===0){l.current=null,n(e=>e===Wh?e:Wh);return}let t=l.current;if(t===null)return;let r=e.find(e=>e.role==="user"&&!t.known.has(e.id));r!==void 0&&(l.current=null,n(e=>({...e,[r.id]:t.images})))},[e]);let o=t.useCallback(e=>{l.current=e.length===0?null:{images:e,known:new Set(i.current)}},[]);return t.useMemo(()=>({byMessage:r,stage:o}),[r,o])}var Gh=/* @__PURE__ */new WeakSet;function Kh(){let e=makeEverfurError("internalError",{retryable:true});return Gh.add(e),err(e)}function Yh(e){if(typeof e!="object"||e===null||e.ok!==false)return false;let t=e.error;return typeof t=="object"&&t!==null&&Gh.has(t)}var Qh=500;function Zh(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,Qh):null}function Xh(e,r,n,l){let i=Zh(n),o=i===null?null:l!==void 0?`key:${String(l)}`:`prompt:${i}`,s=t.useRef(e);s.current=e;let a=t.useRef(null),u=t.useRef(null),c=t.useRef(o);c.current=o,t.useEffect(()=>{if(i===null||o===null||r||a.current===o||u.current===o)return;let e=s.current;if(e===void 0)return;u.current=o;let t=e=>{u.current===o&&(u.current=null),!Yh(e)&&c.current===o&&(a.current=o)};Promise.resolve(e(i)).then(t,()=>t(void 0))},[i,o,r,e])}var Jh=/* @__PURE__ */Object.freeze({openUnreadHead:true,reportLoadFailures:true}),ep=/* @__PURE__ */Object.freeze({reportLoadFailures:true}),tp=/* @__PURE__ */Object.freeze({...Jh,markRead:true}),rp=/* @__PURE__ */Object.freeze({...ep,markRead:true});function np(e,t){return e?t?tp:Jh:t?rp:ep}function lp(e,t){let r=e?.isVisible===void 0?t:e.isVisible.bind(e);return r===void 0?true:ch(()=>r()!==!1)===true}function ip(e,r){let n=t.useRef({target:e,isVisible:r});n.current={target:e,isVisible:r};let l=t.useRef(e.isStreaming);t.useEffect(()=>{let t=l.current;if(l.current=e.isStreaming,!t||e.isStreaming)return;let{target:r,isVisible:i}=n.current;r.status!=="complete"||r.conversationId===null||r.unreadCount===null||!i()||r.markRead()},[e.isStreaming])}var op=3e5;function sp(e){if(e===null||typeof e!="object"||e.ok!==false)return false;let t=e.error;if(t===null||typeof t!="object")return false;if(t.category==="rateLimit"||t.category==="server")return true;let r=t.httpStatus;return typeof r=="number"&&(r===429||r>=500)}function ap(e,r,n){let l=t.useRef(r);l.current=r;let i=t.useRef(null),o=t.useRef(null),s=t.useRef(false),a=t.useRef(0),u=t.useRef(0),c=t.useRef(3e4),d=()=>e?.isOffline===void 0?false:ch(()=>e.isOffline?.()===!0)===true,f=d(),h=t.useRef(()=>{});h.current=e=>{let{conversationId:t,isTurnInFlight:r,refresh:n,refreshesBlankThread:f}=l.current,p=gr(e,{activeConversationId:t,isTurnInFlight:r,refreshesBlankThread:f===true,isOffline:d(),lastRefresh:i.current,now:Date.now()});if(p.action==="skip")return;if(p.action==="defer"){o.current!=="announced"&&(o.current=e);return}if(s.current){if(e==="poll")return;o.current!=="announced"&&(o.current=e);return}if(o.current=null,i.current={conversationId:p.conversationId,at:Date.now()},n===void 0)return;s.current=true;let g=e=>{s.current=false,sp(e)?(a.current=Math.min(a.current===0?c.current*2:a.current*2,op),u.current=Date.now()+a.current):(a.current=0,u.current=0);let t=o.current;t!==null&&h.current(t)};Promise.resolve(n()).then(g,()=>g({ok:false,error:{category:"server"}}))},t.useEffect(()=>{if(r.isTurnInFlight||f)return;let e=o.current;e!==null&&h.current(e)},[r.isTurnInFlight,f]),t.useEffect(()=>{if(e===void 0)return;let t=[],r=(e,r)=>{if(e===void 0)return;let n=ch(()=>e(()=>{h.current(r)}));typeof n=="function"&&t.push(n)};return r(e.onForeground?.bind(e),"foreground"),r(e.onOnline?.bind(e),"foreground"),r(e.onAnnounced?.bind(e),"announced"),()=>{for(let e of t)ch(e)}},[e]);let p=n?.intervalMs??null,g=n?.isVisibleFallback;t.useEffect(()=>{if(e===void 0||p===null||!Number.isFinite(p)||p<=0)return;c.current=p;let t=setInterval(()=>{Date.now()<u.current||lp(e,g)&&h.current("poll")},p);return()=>clearInterval(t)},[e,p,g])}var up=/^efch_[A-Za-z0-9_-]{43}$/,cp="efch";function dp(e){return typeof e=="string"&&up.test(e)}function chatHandoffTokenFromUrl(e){if(typeof e!="string")return null;let t=e.indexOf("#");if(t<0)return null;for(let r of e.slice(t+1).split("&")){if(!r.startsWith(`${cp}=`))continue;let e=r.slice(cp.length+1);return dp(e)?e:null}return null}var fp=128,hp=/[\u0000-\u001f\u007f]/;function pp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function gp(e){return typeof e!="string"||e.length===0||e.length>fp||hp.test(e)||e.includes("://")?null:e}function mp(e){if(e===null)return null;let t=e.conversation_id,r=gp(e.pet_ref);return typeof t!="string"||!tn(t)||r===null?null:{conversationId:t,petRef:r}}function bp(e,t,r){return dp(t)?createRequestFunnel({auth:e,...r?{errorPolicy:r}:{}}).send("chat.redeemHandoff",{method:"POST",path:"/widget/v1/chat/handoffs/redeem",body:{token:t}},{maxAttempts:1}).then(e=>e.ok?ok(mp(pp(e.value))):e.error.httpStatus===404?ok(null):err(e.error),()=>err(Rr("internalError",false))):Promise.resolve(ok(null))}function yp(e,r){let n=r?.runtime??null,l=r?.userRef??null,i=dp(e)?e:null,o=i===null||l===null?null:`${String(l)}|${i}`,[s,a]=t.useState(null);return t.useEffect(()=>{if(o===null||i===null||l===null||n===null)return;let e=true,t=n.registry.services;return bp(t.authFor(l),i,t.errorPolicy).then(t=>{!e||!t.ok||t.value===null||a({key:o,target:/* @__PURE__ */Object.freeze({kind:"chat",conversationId:t.value.conversationId,petRef:t.value.petRef})})}),()=>{e=false}},[o,n,i,l]),s!==null&&s.key===o?s.target:void 0}function vp(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}function xp(e,r,n){let l=vp(r),i=r?.kind==="chat",o=r?.petRef??null,s=i&&!n.pinned&&o!==null&&n.petRef!==null&&o!==n.petRef,a=t.useRef({openCheckin:e,target:r,selectPet:n.selectPet});a.current={openCheckin:e,target:r,selectPet:n.selectPet};let u=t.useRef(null),c=t.useRef(null),d=n.petRef;t.useEffect(()=>{if(l===null||u.current===l)return;let{openCheckin:e,target:t,selectPet:r}=a.current;if(s&&o!==null){if(c.current?.key!==l){c.current={key:l,from:d},r(o);return}d!==c.current.from&&(u.current=l);return}i&&!n.ready||(u.current=l,!(e===void 0||t===void 0)&&Promise.resolve(e(t)).catch(()=>{}))},[l,i,s,o,d,n.ready])}var wp=/* @__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 kp(e){let t=e?.replace(/\s+/g," ").trim();return t||wp.untitled}function Cp(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString([],{month:"short",day:"numeric"})}function Sp(e){let t=Cp(e.updatedAt);return t===null?null:e.unreadCount!==null&&e.unreadCount>0?wp.newReply.replace("{date}",t):t}function jp(e,t){return t?`${wp.countLabel}${wp.countSeparator}${e}`:wp.countLabel}function _p(e){return`${e.unreadCount!==null&&e.unreadCount>0?wp.unreadPrefix:""}${wp.openConversation} ${kp(e.title)}`}function Rp(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function Tp(e,t){let r=Rp(t);if(r.length===0)return e;let n=[[],[],[]];for(let t of e){let e=Rp(kp(t.title)),l=e.indexOf(r);if(l<0)continue;let i=l===0?0:e.charAt(l-1)===" "?1:2;n[i]?.push(t)}return n.flat()}function Ip(e){return{scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function zp(e){let[r,n]=t.useState(false),[l,i]=t.useState(""),o=e.listConversations,s=t.useRef(0),[a,u]=t.useState(()=>Ip(o)),c=a.scope===o?a:Ip(o);t.useEffect(()=>(s.current+=1,n(false),i(""),u(Ip(o)),()=>{s.current+=1}),[o]);let d=t.useCallback(async t=>{let r=++s.current,n=t!==void 0;u(e=>({...e,scope:o,loading:!n,loadingMore:n,error:null}));let l=await e.listConversations(t?{cursor:t}:void 0);if(r===s.current){if(!l.ok){u(e=>({...e,loading:false,loadingMore:false,error:l.error.displayMessage}));return}u(e=>{let r=t&&e.scope===o?e.rows:[],n=new Set(r.map(e=>e.id));return{scope:o,loading:false,loadingMore:false,error:null,rows:[...r,...l.value.conversations.filter(e=>!n.has(e.id))],cursor:l.value.nextCursor===t?null:l.value.nextCursor}})}},[e.listConversations,o]),f=()=>{n(true),i(""),d()},h=()=>{s.current+=1,n(false)},p=async t=>{let r=++s.current;u(e=>({...e,loading:true,error:null}));let l=await e.resumeConversation(t);r===s.current&&(u(e=>({...e,loading:false,error:l.ok?null:l.error.displayMessage})),l.ok&&n(false))},g=async()=>{let t=s.current,r=await e.loadOlderMessages();t===s.current&&!r.ok&&u(e=>({...e,error:r.error.displayMessage}))},m=()=>{e.newConversation(),s.current+=1,n(false)},b=()=>{c.cursor===null||c.loading||c.loadingMore||l.trim().length>0||d(c.cursor)},y=t.useMemo(()=>Tp(c.rows,l),[c.rows,l]),v=l.trim().length>0;return{...c,open:r,show:f,close:h,load:d,resume:p,earlier:g,newConversation:m,loadMore:b,query:l,setQuery:i,searching:v,filtered:y,emptyKind:c.rows.length===0?"empty":"noMatch"}}var Pp="#111111",Ep="#FFFFFF",Op=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:Pp,pillColor:Ep,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:Pp,pillColor:Ep,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Pp,pillColor:Ep,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:Pp,pillColor:Ep,showsVetAction:false})});function Ap(e){return`${e.messageId}:${e.level}:${e.reason??""}`}function Mp(e){return xf(vf.urgencyGeneralReason,{petName:e?.trim()||vf.emptyTitlePetFallback})}function Fp(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let l=n.urgencyLevel;return l?{messageId:n.id,level:l,reason:Dp(n.urgencyReason)}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:Mp(t)}:null}return null}function Dp(e){return typeof e=="string"&&e.trim().length>0?e:null}function Lp(e){let r=e===null?null:Ap(e),[n,l]=t.useState(null),[i,o]=t.useState(false);t.useEffect(()=>o(false),[r]);let s=e!==null&&(i||!(n!==null&&n===r)),a=e===null?null:Op[e.level],u=e!==null&&!s&&e.level!=="general",c=t.useCallback(()=>{r!==null&&l(r),o(false)},[r]),d=t.useCallback(()=>o(true),[]);return t.useMemo(()=>({source:e,tier:a,signature:r,showBanner:s,showCompactIcon:u,showVetAction:s&&a!==null&&a.showsVetAction,dismissLabel:a===null?null:xf(vf.dismissBanner,{label:a.label}),dismiss:c,expand:d}),[e,a,r,s,u,c,d])}var Bp=()=>globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.chatCards.v1")]??={loader:null,lazy:null};var Vp=Bp;function registerEverfurChatCards(e){let r=Vp();r.loader=e;let n=e&&Promise.resolve().then(e).then(e=>typeof e.ServerCards=="function"?e.ServerCards:NONE3,()=>NONE3);r.lazy=n&&t.lazy(async()=>({default:await n}))}var NONE3=()=>null,Hp=t.createContext(null);function ServerCardsSlot({message:e}){let r=t.useContext(Hp),n=Vp(),l=e.a2ui??n.frames?.get(e.responseId),i=n.lazy;return l===void 0||r===null||i===null?null:t.createElement(t.Suspense,{fallback:null},t.createElement(i,{message:e,a2ui:l,host:r}))}var Up="everfur.com",Np=2048,$p=/^(\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function Wp(e){if(!Array.isArray(e))return[];let t=/* @__PURE__ */new Set;for(let r of e){if(typeof r!="string")continue;let e=r.trim().toLowerCase();e.length<=253&&$p.test(e)&&t.add(e)}/* @__PURE__ */
|
|
59
|
+
return Object.freeze([...t])}function qp(e,t){if(e===Up||e.endsWith(`.${Up}`))return true;for(let r of t)if(r.startsWith("*.")?e.endsWith(r.slice(1)):e===r)return true;return false}function Gp(e,t){if(typeof e!="string"||e.length===0||e.length>Np||!/^https:\/\//i.test(e))return null;let r=N(e);return r===null||r.protocol!=="https:"||r.username!==""||r.password!==""||r.port!==""?null:qp(r.hostname,t)?r.href:null}function Kp(e){try{Promise.resolve(r.Linking.openURL(e)).catch(()=>{})}catch{}}var Yp=t.createContext(null);function Qp(){return t.useContext(Yp)??void 0}function MessageLinksScope({linkHosts:e,onOpenUrl:r,children:n}){let l=e===false?null:Array.isArray(e)?e.join(`\n`):"",i=t.useMemo(()=>{if(l===null)return null;let e=Wp(l===""?[]:l.split(`\n`));/* @__PURE__ */
|
|
60
|
+
return Object.freeze({hosts:e,open:r!==void 0?e=>{ch(r,e,"message")}:Kp})},[l,r]);return t.createElement(Yp.Provider,{value:i},n)}var Zp={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function Xp(e){return{width:e,height:e,alignItems:"center",justifyContent:"center"}}function Jp(e,t){return t??Math.max(1.5,Math.round(e/11*10)/10)}function MenuGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n),o={width:e*.82,height:l,borderRadius:l,backgroundColor:t};/* @__PURE__ */
|
|
61
|
+
return i.jsxs(r.View,{style:[Xp(e),{gap:e*.22}],...Zp,children:[
|
|
62
|
+
/* @__PURE__ */i.jsx(r.View,{style:o}),
|
|
63
|
+
/* @__PURE__ */i.jsx(r.View,{style:o}),
|
|
64
|
+
/* @__PURE__ */i.jsx(r.View,{style:o})]})}function Cross({size:e,color:t,strokeWidth:n,rotate:l}){let o=Jp(e,n),s=e*.78;/* @__PURE__ */
|
|
65
|
+
return i.jsxs(r.View,{style:[Xp(e),{transform:[{rotate:l}]}],...Zp,children:[
|
|
66
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",width:s,height:o,borderRadius:o,backgroundColor:t}}),
|
|
67
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",width:o,height:s,borderRadius:o,backgroundColor:t}})]})}function PlusGlyph(e){/* @__PURE__ */
|
|
68
|
+
return i.jsx(Cross,{...e,rotate:"0deg"})}function CloseGlyph(e){/* @__PURE__ */
|
|
69
|
+
return i.jsx(Cross,{...e,rotate:"45deg"})}function CheckGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n);/* @__PURE__ */
|
|
70
|
+
return i.jsx(r.View,{style:Xp(e),...Zp,children:/* @__PURE__ */i.jsx(r.View,{style:{width:e*.36,height:e*.66,marginTop:-e*.14,borderBottomWidth:l,borderRightWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})})}var eg={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:e,color:t,strokeWidth:n,direction:l}){let o=Jp(e,n),s=e*.46,a=eg[l];/* @__PURE__ */
|
|
71
|
+
return i.jsx(r.View,{style:Xp(e),...Zp,children:/* @__PURE__ */i.jsx(r.View,{style:{width:s,height:s,borderRightWidth:o,borderBottomWidth:o,borderColor:t,marginTop:s*a.marginTop,marginLeft:s*a.marginLeft,transform:[{rotate:a.rotate}]}})})}function BookGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n),o={width:e*.42,height:e*.7,borderWidth:l,borderColor:t,borderRadius:l};/* @__PURE__ */
|
|
72
|
+
return i.jsxs(r.View,{style:[Xp(e),{flexDirection:"row",gap:1}],...Zp,children:[
|
|
73
|
+
/* @__PURE__ */i.jsx(r.View,{style:[o,{borderTopLeftRadius:e*.2}]}),
|
|
74
|
+
/* @__PURE__ */i.jsx(r.View,{style:[o,{borderTopRightRadius:e*.2}]})]})}function ArrowUpRightGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n),o=e*.5;/* @__PURE__ */
|
|
75
|
+
return i.jsxs(r.View,{style:Xp(e),...Zp,children:[
|
|
76
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",width:e*.78,height:l,borderRadius:l,backgroundColor:t,transform:[{rotate:"-45deg"}]}}),
|
|
77
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.16,right:e*.16,width:o,height:o,borderTopWidth:l,borderRightWidth:l,borderColor:t}})]})}function CopyGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n),o=e*.6,s={position:"absolute",width:o,height:o,borderWidth:l,borderColor:t,borderRadius:e*.14};/* @__PURE__ */
|
|
78
|
+
return i.jsxs(r.View,{style:Xp(e),...Zp,children:[
|
|
79
|
+
/* @__PURE__ */i.jsx(r.View,{style:[s,{top:0,left:0}]}),
|
|
80
|
+
/* @__PURE__ */i.jsx(r.View,{style:[s,{bottom:0,right:0}]})]})}function ThumbGlyph({size:e,color:t,strokeWidth:n,active:l,rotate:o}){let s=Jp(e,n),a=l?t:"transparent";/* @__PURE__ */
|
|
81
|
+
return i.jsxs(r.View,{style:[Xp(e),{transform:[{rotate:o}]}],...Zp,children:[
|
|
82
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",bottom:e*.08,left:e*.12,width:e*.62,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.12,borderTopLeftRadius:e*.04}}),
|
|
83
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.04,left:e*.4,width:e*.3,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.15,transform:[{rotate:"-20deg"}]}}),
|
|
84
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",bottom:e*.08,left:0,width:e*.2,height:e*.5,borderWidth:s,borderColor:t,backgroundColor:a,borderRadius:e*.05}})]})}function InfoGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n);/* @__PURE__ */
|
|
85
|
+
return i.jsxs(r.View,{style:[Xp(e),{borderRadius:e/2,borderWidth:l,borderColor:t}],...Zp,children:[
|
|
86
|
+
/* @__PURE__ */i.jsx(r.View,{style:{width:l,height:l,borderRadius:l,backgroundColor:t,marginBottom:e*.1}}),
|
|
87
|
+
/* @__PURE__ */i.jsx(r.View,{style:{width:l,height:e*.34,borderRadius:l,backgroundColor:t}})]})}function UploadGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n),o=e*.34;/* @__PURE__ */
|
|
88
|
+
return i.jsxs(r.View,{style:Xp(e),...Zp,children:[
|
|
89
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.06,width:o,height:o,borderTopWidth:l,borderLeftWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}}),
|
|
90
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.1,width:l,height:e*.56,borderRadius:l,backgroundColor:t}}),
|
|
91
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",bottom:0,width:e*.84,height:e*.3,borderBottomWidth:l,borderLeftWidth:l,borderRightWidth:l,borderColor:t,borderBottomLeftRadius:l,borderBottomRightRadius:l}})]})}function PhotoGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n);/* @__PURE__ */
|
|
92
|
+
return i.jsxs(r.View,{style:[Xp(e),{borderWidth:l,borderColor:t,borderRadius:e*.14,overflow:"hidden"}],...Zp,children:[
|
|
93
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.16,left:e*.18,width:e*.16,height:e*.16,borderRadius:e,backgroundColor:t}}),
|
|
94
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",bottom:-e*.3,right:-e*.1,width:e*.7,height:e*.7,borderTopWidth:l,borderLeftWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function CameraGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n);/* @__PURE__ */
|
|
95
|
+
return i.jsxs(r.View,{style:Xp(e),...Zp,children:[
|
|
96
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.08,width:e*.34,height:e*.2,borderTopWidth:l,borderLeftWidth:l,borderRightWidth:l,borderColor:t,borderTopLeftRadius:l,borderTopRightRadius:l}}),
|
|
97
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.22,width:e*.92,height:e*.66,borderWidth:l,borderColor:t,borderRadius:e*.16,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */i.jsx(r.View,{style:{width:e*.3,height:e*.3,borderRadius:e,borderWidth:l,borderColor:t}})})]})}function SearchGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n),o=e/24,s=16*o+l,a=11*o-s/2,u=11+8/Math.SQRT2,c=(21-u)*Math.SQRT2*o,d=(u+21)/2*o;/* @__PURE__ */
|
|
98
|
+
return i.jsxs(r.View,{style:Xp(e),...Zp,children:[
|
|
99
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:a,left:a,width:s,height:s,borderRadius:s,borderWidth:l,borderColor:t}}),
|
|
100
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:d-l/2,left:d-(c+l)/2,width:c+l,height:l,borderRadius:l,backgroundColor:t,transform:[{rotate:"45deg"}]}})]})}function EditGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n);/* @__PURE__ */
|
|
101
|
+
return i.jsxs(r.View,{style:Xp(e),...Zp,children:[
|
|
102
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",width:e*.3,height:e*.82,borderWidth:l,borderColor:t,borderRadius:l,transform:[{rotate:"45deg"}]}}),
|
|
103
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",bottom:0,left:0,width:e*.4,height:l,borderRadius:l,backgroundColor:t}})]})}function MapPinGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n),o=e*.62;/* @__PURE__ */
|
|
104
|
+
return i.jsxs(r.View,{style:Xp(e),...Zp,children:[
|
|
105
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:0,width:o,height:o,borderRadius:o,borderWidth:l,borderColor:t,alignItems:"center",justifyContent:"center"},children:/* @__PURE__ */i.jsx(r.View,{style:{width:l*1.4,height:l*1.4,borderRadius:l,backgroundColor:t}})}),
|
|
106
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",bottom:e*.04,width:o*.5,height:o*.5,borderRightWidth:l,borderBottomWidth:l,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function SendGlyph({size:e,color:t,testID:n}){let l=e*.36;/* @__PURE__ */
|
|
107
|
+
return i.jsx(r.View,{style:Xp(e),testID:n,...Zp,children:/* @__PURE__ */i.jsx(r.View,{style:{width:0,height:0,marginLeft:e*.12,borderLeftWidth:e*.78,borderTopWidth:l,borderBottomWidth:l,borderLeftColor:t,borderTopColor:"transparent",borderBottomColor:"transparent",transform:[{rotate:"-45deg"}]}})})}function StopGlyph({size:e,color:t,testID:n}){/* @__PURE__ */
|
|
108
|
+
return i.jsx(r.View,{style:Xp(e),testID:n,...Zp,children:/* @__PURE__ */i.jsx(r.View,{style:{width:e*.5,height:e*.5,backgroundColor:t}})})}function MicGlyph({size:e,color:t,strokeWidth:n,testID:l}){let o=Jp(e,n);/* @__PURE__ */
|
|
109
|
+
return i.jsxs(r.View,{style:Xp(e),testID:l,...Zp,children:[
|
|
110
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.08,width:e*.26,height:e*.48,borderWidth:o,borderColor:t,borderRadius:e*.13}}),
|
|
111
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.38,width:e*.56,height:e*.36,borderBottomWidth:o,borderLeftWidth:o,borderRightWidth:o,borderColor:t,borderBottomLeftRadius:e*.28,borderBottomRightRadius:e*.28}}),
|
|
112
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.74,width:o,height:e*.18,backgroundColor:t}})]})}function Ring({size:e,strokeWidth:t,color:n,children:l}){/* @__PURE__ */
|
|
113
|
+
return i.jsx(r.View,{style:[Xp(e),{borderRadius:e/2,borderWidth:t??r.StyleSheet.hairlineWidth,borderColor:n}],children:l})}function ArrowUpGlyph({size:e,color:t,strokeWidth:n,testID:l}){let o=Jp(e,n),s=e*.46;/* @__PURE__ */
|
|
114
|
+
return i.jsxs(r.View,{style:Xp(e),testID:l,...Zp,children:[
|
|
115
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.16,bottom:e*.12,width:o,borderRadius:o,backgroundColor:t}}),
|
|
116
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.16+o/2,width:s,height:s,borderLeftWidth:o,borderTopWidth:o,borderColor:t,transform:[{rotate:"45deg"}]}})]})}function ChatBubbleGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n);/* @__PURE__ */
|
|
117
|
+
return i.jsxs(r.View,{style:Xp(e),...Zp,children:[
|
|
118
|
+
/* @__PURE__ */i.jsx(r.View,{style:{width:e*.8,height:e*.6,marginTop:-e*.12,borderWidth:l,borderColor:t,borderRadius:e*.14}}),
|
|
119
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",bottom:e*.1,left:e*.22,width:e*.2,height:e*.2,borderLeftWidth:l,borderBottomWidth:l,borderColor:t}})]})}function HistoryGlyph({size:e,color:t,strokeWidth:n}){let l=Jp(e,n),o=e*.72,s=e/2;/* @__PURE__ */
|
|
120
|
+
return i.jsxs(r.View,{style:Xp(e),...Zp,children:[
|
|
121
|
+
/* @__PURE__ */i.jsx(r.View,{style:{width:o,height:o,borderRadius:o/2,borderWidth:l,borderColor:t,borderLeftColor:"transparent",transform:[{rotate:"45deg"}]}}),
|
|
122
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:e*.16,left:e*.12,width:e*.2,height:e*.2,borderLeftWidth:l,borderBottomWidth:l,borderColor:t}}),
|
|
123
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:s-e*.2,left:s-l/2,width:l,height:e*.2+l/2,borderRadius:l,backgroundColor:t}}),
|
|
124
|
+
/* @__PURE__ */i.jsx(r.View,{style:{position:"absolute",top:s-l/2,left:s-l/2,width:e*.15+l/2,height:l,borderRadius:l,backgroundColor:t}})]})}var tg=/* @__PURE__ */Object.freeze({standard:Oo.standard,emphasized:Oo.emphasized,exit:Oo.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])});var rg=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),ng=/* @__PURE__ */Object.freeze({...rg,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function lg(e){return e.motion.reducedMotion?ng:rg}function ig(e,t){return Math.max(0,t)*e.followUpStaggerMs}function og(e,t,r){if(e.reduced||t>=r)return r;let n=Math.max(1,Math.ceil((r-t)/e.revealDivisor));return Math.min(r,t+n)}function sg(){let e=useEverfurTheme();return lg(e)}var ag=8;function ug(e,t,r){return((1-3*r+3*t)*e+(3*r-6*t))*e*e+3*t*e}function cg(e,t,r){return 3*(1-3*r+3*t)*e*e+2*(3*r-6*t)*e+3*t}function dg(e){let[t,r,n,l]=e;return e=>{if(e<=0)return 0;if(e>=1)return 1;let i=e;for(let r=0;r<ag;r+=1){let r=cg(i,t,n);if(r===0)break;i-=(ug(i,t,n)-e)/r}return ug(Math.min(1,Math.max(0,i)),r,l)}}var fg=dg(tg.standard),hg=dg(tg.outQuad),pg=dg(tg.out);function gg(e){let n=t.useRef(null);return n.current===null&&(n.current=new r.Animated.Value(e)),n.current}function mg(e,n={}){let l=n.risePx??0,i=n.delayMs??0,o=gg(e>0?0:1);return t.useEffect(()=>{if(e<=0){o.setValue(1);return}let t=r.Animated.timing(o,{toValue:1,duration:e,easing:hg,useNativeDriver:true}),n=i>0?r.Animated.sequence([r.Animated.delay(i),t]):t;return n.start(),()=>n.stop()},[o,e,i]),t.useMemo(()=>({opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[l,0]})}]}),[o,l])}function FadePresence({visible:e,inMs:n,outMs:l,style:o,children:s}){let[a,u]=t.useState(e),c=gg(e&&n<=0?1:0);return t.useEffect(()=>{if(e){u(true);let e=r.Animated.timing(c,{toValue:1,duration:Math.max(0,n),easing:fg,useNativeDriver:true});return e.start(),()=>e.stop()}if(!a)return;if(l<=0){u(false);return}let t=r.Animated.timing(c,{toValue:0,duration:l,easing:fg,useNativeDriver:true});return t.start(({finished:e})=>{e&&u(false)}),()=>t.stop()},[e,a,n,l,c]),!a&&!e?null:/* @__PURE__ */i.jsx(r.Animated.View,{style:[o,{opacity:c}],children:s})}var bg=/* @__PURE__ */Object.freeze({opacity:1,transform:/* @__PURE__ */Object.freeze([{translateY:0},{scale:1}])});function yg(e,n){let[l]=t.useState(()=>e?n.bubbleInMs:0),i=l>0,o=gg(i?0:1);t.useEffect(()=>{if(l<=0)return;let e=r.Animated.timing(o,{toValue:1,duration:l,easing:pg,useNativeDriver:true});return e.start(),()=>e.stop()},[l,o]);let s=n.bubbleFromScale,a=n.bubbleRisePx;return t.useMemo(()=>i?{opacity:o,transform:[{translateY:o.interpolate({inputRange:[0,1],outputRange:[a,0]})},{scale:o.interpolate({inputRange:[0,1],outputRange:[s,1]})}]}:bg,[i,o,a,s])}function vg(e){let r=t.useRef(null),n=t.useRef(null),l=e[0]?.id??null;if(r.current===null||n.current!==l){let t=r.current===null;r.current=new Map(e.map(e=>[e.id,t&&e.pending===true])),n.current=l}let i=r.current;for(let t of e)i.has(t.id)||i.set(t.id,true);return t.useCallback(e=>i.get(e)===true,[i])}var xg=12;function PressScale({style:e,containerStyle:n,children:l,onPressIn:o,onPressOut:s,hitSlop:a,...u}){let c=sg(),d=gg(1),f=t.useCallback(e=>{c.pressMs<=0||c.pressScale===1||r.Animated.timing(d,{toValue:e,duration:c.pressMs,easing:fg,useNativeDriver:true}).start()},[d,c.pressMs,c.pressScale]);/* @__PURE__ */
|
|
125
|
+
return i.jsx(r.Pressable,{...u,hitSlop:a??xg,style:n,onPressIn:e=>{f(c.pressScale),o?.(e)},onPressOut:e=>{f(1),s?.(e)},children:/* @__PURE__ */i.jsx(r.Animated.View,{style:[e,{transform:[{scale:d}]}],children:l})})}function wg(e,r,n){let l=r&&n.revealTickMs>0,[i,o]=t.useState(0),s=t.useRef(e);return s.current=e,t.useEffect(()=>{if(!l)return;let e=setInterval(()=>{o(e=>og(n,e,s.current.length))},n.revealTickMs);return()=>clearInterval(e)},[l,n]),l?e.slice(0,Math.min(i,e.length)):e}var kg=false;function Cg(e){e.layoutMs<=0||(kg||(kg=true,r.Platform.OS==="android"&&typeof r.UIManager.setLayoutAnimationEnabledExperimental=="function"&&r.UIManager.setLayoutAnimationEnabledExperimental(true)),r.LayoutAnimation.configureNext({duration:e.layoutMs,create:{type:"easeInEaseOut",property:"opacity"},update:{type:"easeInEaseOut"},delete:{type:"easeInEaseOut",property:"opacity"}}))}function Sg(e,r){let n=t.useRef(e);n.current!==e&&(n.current=e,Cg(r))}var jg=36,_g=22,Rg=12,Tg=12,Ig=16,zg="#000",Pg="rgba(0,0,0,0.45)";function AttachmentImageLightbox({uri:e,label:t,onClose:l}){let o=useEverfurTheme(),s=n.useSafeAreaInsets();return e===null?null:/* @__PURE__ */i.jsxs(r.Modal,{visible:true,animationType:o.motion.reducedMotion?"none":"fade",transparent:false,statusBarTranslucent:true,onRequestClose:l,children:[
|
|
126
|
+
/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:vf.closePreview,style:Eg.backdrop,onPress:l,children:/* @__PURE__ */i.jsx(r.Image,{source:{uri:e},style:Eg.image,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,accessibilityIgnoresInvertColors:true})}),
|
|
127
|
+
/* @__PURE__ */i.jsx(r.View,{pointerEvents:"box-none",style:[Eg.closeWrap,{top:s.top+Tg}],children:/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:vf.closePreview,hitSlop:Rg,style:Eg.closeButton,onPress:l,children:/* @__PURE__ */i.jsx(CloseGlyph,{size:_g,color:o.color.surface,strokeWidth:2})})})]})}var Eg=r.StyleSheet.create({backdrop:{flex:1,backgroundColor:zg,alignItems:"center",justifyContent:"center"},image:{width:"100%",height:"100%"},closeWrap:{position:"absolute",right:Ig},closeButton:{width:jg,height:jg,borderRadius:jg/2,backgroundColor:Pg,alignItems:"center",justifyContent:"center"}});var Og=()=>{};function Ag(){try{return r.AppState.currentState==="active"}catch{return false}}function createAppStateLifecycle(){return{onForeground(e){let t;try{let n=r.AppState.currentState==="background";t=r.AppState.addEventListener("change",t=>{t==="background"?n=!0:t==="active"&&n&&(n=!1,e())})}catch{return Og}return()=>t.remove()},isVisible:Ag}}function Mg(e,t){if(e===void 0)return{};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}function Fg(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}function Dg(e){return e?.textColor===void 0?{}:{color:e.textColor}}function Lg(e){switch(e.code){case"too_large":return xf(vf.attachmentTooLarge,{max:formatBytes(Dn),filename:e.filename,size:formatBytes(e.sizeBytes??0)});case"too_many":return xf(vf.attachmentTooMany,{max:Ln});case"unsupported_type":return xf(vf.attachmentUnsupported,{filename:e.filename});case"network":return vf.attachmentNetwork;case"server":return xf(vf.attachmentServer,{status:""});case"cancelled":return vf.attachmentCancelled;case"rate_limited":return vf.attachmentRateLimited;case"quota_exceeded":return vf.attachmentQuota;case"idempotency_conflict":return vf.attachmentConflict;case"unknown":return vf.attachmentUnknown}}function Bg(e,t){return xf(e>=t?vf.attachmentsFull:vf.addAttachment,{used:e,total:t})}var Vg=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(e={}){let{runtime:r,userRef:n,scopeEpoch:l}=Yc(),i=e.maxPerMessage??Ln,o=t.useCallback(()=>{let{services:t}=r.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:t.authFor(n),...t.errorPolicy?{errorPolicy:t.errorPolicy}:{}}),transport:e.transport??t.uploadTransport,maxPerMessage:i})},[r,n,l,i,e.transport]),s=t.useMemo(()=>e.queue??o(),[e.queue,o]),a=t.useRef(/* @__PURE__ */new WeakSet),[u,c]=t.useState(null),d=u!==null&&u.of===s?u.queue:s;t.useEffect(()=>{if(d!==e.queue){if(a.current.has(d)){c({of:s,queue:o()});return}return()=>{d.dispose(),a.current.add(d)}}},[d,s,o,e.queue]);let f=t.useSyncExternalStore(d.subscribe,d.getSnapshot,()=>Vg),[h,p]=t.useState(null),g=t.useCallback(e=>{let t=(Array.isArray(e)?e:[e]).map(e=>d.add(e)),r=t.find(e=>!e.ok);return r!==void 0&&!r.ok&&p(r.error),t},[d,p]),m=t.useCallback(e=>d.retry(e),[d]),b=t.useCallback(e=>d.remove(e),[d]),y=t.useCallback(()=>d.clear(),[d]),v=t.useCallback(()=>p(null),[p]),x=f.attachments.some(e=>e.status==="uploading"),w=f.attachments.some(e=>e.status==="failed");return t.useMemo(()=>({available:d.available,attachments:f.attachments,maxPerMessage:i,uploading:x,failed:w,blocked:x||w,s3Keys:f.attachments.flatMap(e=>e.status==="uploaded"&&e.s3Key!==null?[e.s3Key]:[]),rejected:h,add:g,retry:m,remove:b,clear:y,dismissRejected:v}),[d.available,f,i,x,w,h,g,m,b,y,v])}var Hg=6e3;function Ug(e,t,r){let n=t.trim();if(!n)return e;let l=e===""||/\s$/.test(e)?"":" ",i=`${e}${l}${n}`;return typeof r=="number"&&r>0?i.slice(0,r):i}function Ng(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return`${r}:${n.toString().padStart(2,"0")}`}function $g(e){switch(e){case"permissionDenied":return vf.micBlocked;case"noSpeech":return vf.noSpeech;case"unavailable":return vf.dictationUnavailable}}function Wg(e,t,r){if(e)try{e.track(t,{...r})}catch{}}var qg=["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 Gg(e={}){let t=/* @__PURE__ */new Set,r=[];for(let n of[e.name,e.breed,...qg]){let e=(n??"").trim();if(!e)continue;let l=e.toLowerCase();if(!t.has(l)&&(t.add(l),r.push(e),r.length>=100))break}return r}function Kg(e,r,n){let[l,i]=t.useState({send:e,conversationId:r,text:n??"",seeded:n??null}),o=l.send===e&&(l.conversationId===null||l.conversationId===r);t.useEffect(()=>{i(t=>{let l=t.send===e&&(t.conversationId===null||t.conversationId===r),i=l?t.text:"",o=l?t.seeded:null,s=n!=null&&n!==o&&i.length===0;return{send:e,conversationId:r,text:s?n:i,seeded:s?n:o}})},[e,r,n]);let s=t.useCallback(t=>i(n=>({send:e,conversationId:r,text:t,seeded:n.seeded})),[e,r]);return[o?l.text:"",s]}function Yg(e,r,n,l,i=false){let o=t.useRef({draft:n,setDraft:l});o.current={draft:n,setDraft:l};let s=t.useRef(null),[a,u]=t.useState(null);t.useEffect(()=>{if(e===void 0)return;let t=`${r??""}`;if(s.current===t)return;s.current=t;let n=true;return(async()=>{let l=await hh(()=>e.read(r));if(!n)return;let i=l.ok&&typeof l.value=="string"?l.value:"";i.length>0&&o.current.draft.length===0&&o.current.setDraft(i),u(t)})(),()=>{n=false}},[e,r]),t.useEffect(()=>{e===void 0||i||a!==`${r??""}`||ch(()=>e.write(r,n))},[e,r,n,a,i])}function Qg(e){if(!(r.Platform.OS!=="ios"||e===""))try{let t=r.AccessibilityInfo?.announceForAccessibility;typeof t=="function"&&t.call(r.AccessibilityInfo,e)}catch{}}function AnnounceLine({line:e}){return t.useEffect(()=>{Qg(e)},[e]),null}var Zg=12,Xg=80,Jg=44,em=22,tm=.14,rm=18,nm=8,lm=/* @__PURE__ */Object.freeze({photo:vf.attachmentPhoto,camera:vf.attachmentCamera});function AttachmentPickerPopover({sources:e,full:n,onPick:l,onClose:o}){let s=useEverfurTheme(),a=t.useMemo(()=>im(s),[s]);/* @__PURE__ */
|
|
128
|
+
return i.jsxs(r.View,{style:a.anchor,pointerEvents:"box-none",children:[
|
|
129
|
+
/* @__PURE__ */i.jsx(r.Pressable,{style:a.dismissLayer,accessibilityRole:"button",accessibilityLabel:vf.closeAttachmentPicker,onPress:o}),
|
|
130
|
+
/* @__PURE__ */i.jsxs(r.View,{style:a.bubble,children:[
|
|
131
|
+
/* @__PURE__ */i.jsx(r.View,{style:a.tilesRow,children:e.map(e=>/* @__PURE__ */i.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:lm[e],accessibilityState:{disabled:n},disabled:n,containerStyle:a.tile,style:a.tileInner,onPress:()=>l(e),children:[
|
|
132
|
+
/* @__PURE__ */i.jsx(r.View,{style:a.tileIconWrap,children:e==="photo"?/* @__PURE__ */i.jsx(PhotoGlyph,{size:em,color:s.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */i.jsx(CameraGlyph,{size:em,color:s.color.brandInk,strokeWidth:1.5})}),
|
|
133
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:a.tileLabel,children:lm[e]})]},e))}),
|
|
134
|
+
/* @__PURE__ */i.jsx(r.View,{style:a.tail}),
|
|
135
|
+
/* @__PURE__ */i.jsx(r.View,{style:a.tailFill})]})]})}function im(e){let t=e.color,n=e.radius;return r.StyleSheet.create({anchor:{position:"absolute",left:0,right:0,bottom:"100%",paddingHorizontal:8,paddingBottom:10,alignItems:"flex-start"},dismissLayer:{position:"absolute",left:-1e3,right:-1e3,top:-2e3,bottom:0},bubble:{backgroundColor:t.surfaceCream,borderRadius:n.lg,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:t.shadow,shadowOpacity:tm,shadowRadius:rm,shadowOffset:{width:0,height:nm},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:Xg,borderRadius:n.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:Jg,height:Jg,borderRadius:Jg/2,backgroundColor:t.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(e,"medium"),fontSize:12,lineHeight:14,color:t.text.primary},tail:{position:"absolute",left:24,bottom:-Zg/2,width:Zg,height:Zg,backgroundColor:t.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:t.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:Zg+4,height:2,backgroundColor:t.surfaceCream}})}var om=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var sm=56,am=12,um=14,cm=10,dm=.45,fm="rgba(7,193,104,0.55)",hm="rgba(185,28,28,0.55)",pm=200,gm=300,mm=20,bm=22,ym=12,vm="rgba(0,0,0,0.78)",xm=220,wm=100,km="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:e,rejected:n,uploadFailed:l=false,onRetry:o,onRemove:s,onPreview:a,style:u}){let c=useEverfurTheme(),d=t.useMemo(()=>Cm(c),[c]);return e.length===0&&n===null?null:/* @__PURE__ */i.jsxs(r.View,{style:[d.strip,u],children:[e.length>0?/* @__PURE__ */i.jsx(r.View,{style:d.cards,children:e.map(e=>/* @__PURE__ */i.jsx(PreviewCard,{row:e,styles:d,onRetry:o,onRemove:s,onPreview:a},e.id))}):null,l?/* @__PURE__ */i.jsx(Text,{style:d.rejected,accessibilityRole:"alert",children:vf.attachmentsFailedBlocked}):null,n!==null?/* @__PURE__ */i.jsx(Text,{style:d.rejected,accessibilityRole:"alert",children:Lg(n)}):null]})}function PreviewCard({row:e,styles:n,onRetry:l,onRemove:o,onPreview:s}){let a=useEverfurTheme(),u=e.status==="uploading",c=e.status==="failed",d=e.status==="uploaded",f=t.useRef(e.status),[h,p]=t.useState(false);return t.useEffect(()=>{let t=f.current;f.current=e.status,e.status==="uploaded"&&t==="uploading"&&p(true)},[e.status]),/* @__PURE__ */i.jsxs(r.View,{style:n.card,children:[
|
|
136
|
+
/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:d?"button":"image",accessibilityLabel:d?xf(vf.previewAttachment,{filename:e.filename}):e.filename,accessibilityState:{busy:u,disabled:!d},disabled:!d,style:n.thumbHit,onPress:()=>s(e),children:/* @__PURE__ */i.jsxs(r.View,{style:n.thumb,children:[
|
|
137
|
+
/* @__PURE__ */i.jsx(r.Image,{source:{uri:e.previewUri},style:n.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),u?/* @__PURE__ */i.jsx(r.View,{style:n.uploadingOverlay,children:/* @__PURE__ */i.jsx(r.ActivityIndicator,{size:"small",color:a.color.surface})}):null,h?/* @__PURE__ */i.jsx(SuccessFlash,{styles:n,onDone:()=>p(false)}):null]})}),c?/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:xf(vf.retryUpload,{filename:e.filename}),style:n.failedOverlay,onPress:()=>l(e.id),children:/* @__PURE__ */i.jsx(r.View,{style:n.failedInner,children:/* @__PURE__ */i.jsx(CloseGlyph,{size:mm,color:a.color.surface,strokeWidth:2})})}):null,
|
|
138
|
+
/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:xf(vf.removeAttachment,{filename:e.filename}),hitSlop:6,containerStyle:n.removeSlot,style:n.removeButton,onPress:()=>o(e.id),children:/* @__PURE__ */i.jsx(CloseGlyph,{size:ym,color:a.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:e,onDone:n}){let l=useEverfurTheme(),o=sg(),s=t.useRef(null);s.current===null&&(s.current=new r.Animated.Value(0));let a=s.current;return t.useEffect(()=>{let e=r.Animated.sequence([r.Animated.timing(a,{toValue:1,duration:pm,useNativeDriver:true}),r.Animated.delay(o.uploadFlashMs),r.Animated.timing(a,{toValue:0,duration:gm,useNativeDriver:true})]);return e.start(({finished:e})=>{e&&n()}),()=>e.stop()},[a,o.uploadFlashMs,n]),/* @__PURE__ */i.jsx(r.Animated.View,{pointerEvents:"none",style:[e.successOverlay,{opacity:a}],children:/* @__PURE__ */i.jsx(CheckGlyph,{size:mm,color:l.color.surface,strokeWidth:2})})}function SentImages({images:e,onPreview:n}){let l=useEverfurTheme(),o=t.useMemo(()=>Cm(l),[l]);if(e.length===0)return null;let s=e.length===1;/* @__PURE__ */
|
|
139
|
+
return i.jsx(r.View,{style:s?o.sentSingle:o.sentGrid,children:e.map((e,t)=>/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:xf(vf.attachedImage,{filename:e.filename}),onPress:()=>n(e),children:/* @__PURE__ */i.jsx(r.Image,{source:{uri:e.uri},style:s?o.singleImage:o.gridImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true})},`${e.uri}-${t}`))})}function Cm(e){let t=e.color,n=e.type;return r.StyleSheet.create({strip:{gap:6,paddingBottom:8},cards:{flexDirection:"row",flexWrap:"wrap",gap:8},card:{width:sm,height:sm,overflow:"visible"},thumbHit:{width:"100%",height:"100%"},thumb:{width:"100%",height:"100%",borderRadius:am,overflow:"hidden",backgroundColor:t.composerFill,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.brandBorder},thumbImage:{width:"100%",height:"100%"},uploadingOverlay:{...om,alignItems:"center",justifyContent:"center",backgroundColor:Hi(e.color.brandInk,dm)??e.color.brandSofter},successOverlay:{...om,alignItems:"center",justifyContent:"center",backgroundColor:fm},failedOverlay:{...om,borderRadius:am,overflow:"hidden"},failedInner:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:hm},removeSlot:{position:"absolute",top:4,right:4},removeButton:{width:bm,height:bm,borderRadius:bm/2,backgroundColor:vm,borderWidth:1.5,borderColor:t.surface,alignItems:"center",justifyContent:"center"},rejected:{...face(e,"regular"),fontSize:n.size.caption,lineHeight:n.size.caption*n.lineHeight.normal,color:t.danger},sentSingle:{marginBottom:6},sentGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,marginBottom:6},singleImage:{width:xm,height:xm,borderRadius:um,backgroundColor:km},gridImage:{width:wm,height:wm,borderRadius:cm,backgroundColor:km}})}var Sm="chat attachment upload: the file handle has no uri",jm="chat attachment upload failed";function _m(e){return{uri:e.uri,name:sanitizeFilename(e.name),type:e.mimeType}}function createRnChatAttachmentTransport(e={}){/* @__PURE__ */
|
|
140
|
+
return Object.freeze({postMultipart(t,r,n){if(typeof r.uri!="string"||r.uri.length===0)return Promise.reject(new Error(Sm));let{signal:l,onProgress:i}=n,o=()=>Promise.reject(new Error(jm));return l?.aborted===true?o():re({url:t.upload_url,fields:t.upload_fields,file:_m(r),signal:l,fetch:e.fetch}).then(e=>{if(!e)return o();i?.(1)},o)}})}var Rm=300,Tm=3e3,Im=120,zm=44,Pm=120,Em="88%",Om=520,Am=2,Mm=.5,Fm=1.5,Dm=1.6,Lm=.6,Bm=56,Vm=1.5,Hm=5,Um=5,Nm=36,$m=20,Wm=14,qm=zm,Gm=4,Km=24,Ym=22,Qm=.4,Zm=zm,Xm=20,Jm=.4,eb=480,tb=12,rb=.72,nb=48,lb=1.5,ib=1.3,ob=1,sb=1,ab="12%",ub=14,cb=16,db=28,fb=18,hb="84%",pb=10,gb=15,mb=1.42,bb=4,yb=3,vb=14,xb=20;function wb(){let e=useEverfurTheme(),r=t.useMemo(()=>kb(e),[e]);return{theme:e,styles:r}}function kb(e){let t=e.color,n=e.space,l=e.radius,i=e.type,o=Math.round(i.size.body*Fm),s=Math.round(i.size.body*Dm),a=Math.round($m*i.size.body/Wm),u=t.borderRingCream,c=e.slots;return r.StyleSheet.create({container:{flex:1,minHeight:Im,backgroundColor:t.chatGround},body:{flex:1},centered:{minHeight:Im,flexGrow:1,alignItems:"center",justifyContent:"center",padding:n.xl},homeEmpty:{flexGrow:1},emptyContent:{flexGrow:1,alignItems:"stretch",justifyContent:"flex-start",paddingTop:ab,paddingHorizontal:n.lg,paddingBottom:n.lg,minHeight:eb,gap:n.lg},errorText:{...face(e,"regular"),fontSize:i.size.subtitle,lineHeight:i.size.subtitle*i.lineHeight.snug,color:t.danger,textAlign:"center",marginBottom:n.md},retryButton:{minHeight:zm,minWidth:zm,alignItems:"center",justifyContent:"center",paddingHorizontal:n.xl,paddingVertical:n.sm,borderRadius:l.pill,backgroundColor:t.brand,...Mg(c.primaryButton)},retryLabel:{...face(e,"medium"),color:t.onPrimary,fontSize:i.size.body,...Dg(c.primaryButton)},setupNotice:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:n.sm,paddingHorizontal:n.lg,paddingVertical:n.sm,backgroundColor:t.surfaceCream},setupNoticeText:{...face(e,"regular"),color:t.danger,fontSize:i.size.caption,flexShrink:1},turnNotice:{gap:n.xs,padding:n.md,borderRadius:l.md,backgroundColor:t.surfaceCream,borderWidth:sb,borderColor:t.borderRingCream,alignItems:"flex-start"},turnNoticeError:{borderColor:t.danger},turnNoticeTitle:{...face(e,"bold"),color:t.text.primary,fontSize:i.size.bodyTight},turnNoticeTitleError:{color:t.danger},turnNoticeBody:{...face(e,"regular"),color:t.text.muted,fontSize:i.size.caption,lineHeight:i.size.caption*i.lineHeight.normal},turnNoticeAction:{minHeight:zm,justifyContent:"center"},turnNoticeActionLabel:{...face(e,"bold"),color:t.brandInk,fontSize:i.size.bodyTight},setupNoticeAction:{...face(e,"medium"),color:t.brandInk,fontSize:i.size.caption},reconnectingCaption:{...face(e,"medium"),color:t.text.secondary,fontSize:i.size.caption,lineHeight:i.size.caption*i.lineHeight.normal,textTransform:"uppercase",letterSpacing:.5},readingBox:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:n.xs,paddingVertical:n.md,paddingHorizontal:n.md+n.xs/2,backgroundColor:t.surfaceSubtle,borderRadius:l.md},readingDot:{width:6,height:6,borderRadius:l.pill,backgroundColor:t.brandInk},readingInline:{alignSelf:"flex-start",flexDirection:"row",alignItems:"center",gap:yb,minHeight:vb},readingDotInline:{width:bb,height:bb,borderRadius:l.pill,backgroundColor:t.text.muted},list:{flex:1},earlierButton:{alignSelf:"center",minHeight:zm,justifyContent:"center",paddingHorizontal:n.md+n.xs/2},earlierLabel:{...face(e,"monoBold"),color:t.linkInk,fontSize:i.size.caption},listContent:{padding:n.lg,gap:n.xl},listContentCards:{paddingTop:ub,paddingHorizontal:cb,paddingBottom:db,gap:fb},rowBlock:{gap:n.sm},rowBlockUser:{},rowBlockAssistant:{paddingRight:n.xl},row:{flexDirection:"row"},rowUser:{justifyContent:"flex-end"},rowAssistant:{justifyContent:"flex-start"},bubble:{maxWidth:Em,alignItems:"flex-start"},bubbleSideUser:{alignItems:"flex-end"},bubbleUser:{maxWidth:Om,paddingVertical:n.md,paddingHorizontal:n.lg+Am,backgroundColor:t.bubbleUser,...t.primaryEdge!==t.primary&&t.bubbleUser===t.primary?{borderWidth:Mm,borderColor:t.primaryEdge}:{},borderRadius:l.lg,borderBottomRightRadius:l.xs,...Mg(c.userBubble,Mm)},bubbleAssistant:c.assistantBubble?.backgroundColor===void 0?{...Mg(c.assistantBubble,Mm)}:{paddingVertical:n.md,paddingHorizontal:n.lg+Am,borderRadius:l.lg,...Mg(c.assistantBubble,Mm)},bubbleVet:{maxWidth:Om,paddingVertical:n.md,paddingHorizontal:n.lg+Am,backgroundColor:t.bubbleVet,borderRadius:l.lg,borderTopLeftRadius:l.xs,...Mg(c.vetBubble,Mm)},bubbleCards:{maxWidth:hb},bubbleUserCards:{paddingVertical:pb,paddingHorizontal:gb},bubbleTextUserCards:{fontSize:textRole(e,"message").fontSize,lineHeight:Math.round(textRole(e,"message").fontSize*mb)},bubblePending:{opacity:Lm},bubbleTextUser:{...face(e,"regular"),color:t.onPrimary,fontSize:i.size.body,lineHeight:o,...Dg(c.userBubble)},bubbleTextAssistant:{...face(e,"regular"),color:t.text.primary,fontSize:i.size.body,lineHeight:s,...Dg(c.assistantBubble)},bubbleTextVet:{...face(e,"regular"),color:t.onBubbleVet,fontSize:i.size.body,lineHeight:o,...Dg(c.vetBubble)},assistantName:{...face(e,"bold"),color:t.brandInk,fontSize:i.size.bodyTight,marginBottom:n.xs},assistantSender:{flexDirection:"row",alignItems:"center",gap:n.sm,marginBottom:n.xs},assistantAvatar:{width:xb,height:xb,borderRadius:xb/2},assistantNameInRow:{marginBottom:0},vetHeader:{flexDirection:"row",alignItems:"baseline",gap:n.sm,marginBottom:n.xs},vetSender:{...face(e,"bold"),color:t.text.primary,fontSize:i.size.bodyTight},vetTime:{...face(e,"regular"),color:t.text.muted,fontSize:i.size.caption},bubbleBold:face(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:face(e,"mono"),followUps:{alignSelf:"stretch",marginTop:n.md},followUpsHeading:{...face(e,"monoBold"),color:t.text.muted,fontSize:tb,textTransform:"uppercase",letterSpacing:rb,paddingBottom:n.sm,borderBottomWidth:ob,borderBottomColor:u},followUpSlot:{alignSelf:"stretch"},followUpSlotRuled:{borderTopWidth:ob,borderTopColor:u},followUpRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:n.md,minHeight:nb,paddingVertical:n.sm+Am,...c.chip?.backgroundColor!==void 0||c.chip?.borderColor!==void 0?{paddingHorizontal:n.md}:{},...Mg(c.chip)},followUpText:{...face(e,"bold"),flex:1,color:t.brandInk,fontSize:i.size.bodyTight,...Dg(c.chip)},askChips:{flexDirection:"row",flexWrap:"wrap",gap:n.sm,marginTop:n.md},askChip:{minHeight:zm,maxWidth:"100%",justifyContent:"center",paddingVertical:n.sm,paddingHorizontal:n.lg,borderRadius:l.pill,borderWidth:lb,borderColor:t.brandInk,backgroundColor:t.chatGround,...Mg(c.chip,lb)},askChipText:{...face(e,"bold"),color:t.brandInk,fontSize:i.size.bodyTight,lineHeight:Math.round(i.size.bodyTight*ib),...Dg(c.chip)},composerOuter:{position:"relative"},askEntry:{marginHorizontal:n.md,marginTop:n.xs},composer:{marginHorizontal:n.md,marginTop:n.xs,minHeight:Bm,justifyContent:"center",paddingLeft:n.sm,paddingRight:Hm,paddingVertical:Um,backgroundColor:t.composerFill,borderWidth:Vm,borderColor:t.composerBorder,borderRadius:l.pill,...Mg(c.composerInput,Vm)},composerRow:{flexDirection:"row",alignItems:"center",gap:n.xs,minHeight:Nm},dictationError:{...face(e,"regular"),fontSize:i.size.caption,lineHeight:i.size.caption*i.lineHeight.normal,color:t.danger,paddingHorizontal:n.xs},attachControl:{width:Zm,height:Zm,alignItems:"center",justifyContent:"center"},attachControlDisabled:{opacity:Jm},input:{flex:1,minHeight:Nm,maxHeight:Pm,paddingHorizontal:0,paddingVertical:0,...face(e,"regular"),fontSize:i.size.body,lineHeight:a,color:t.text.primary,...Dg(c.composerInput)},sendControl:{minHeight:qm,minWidth:qm,alignItems:"center",justifyContent:"center"},sendDisc:{width:qm,height:qm,borderRadius:qm/2,alignItems:"center",justifyContent:"center",...Mg(c.sendButton)},sendControlDisabled:{opacity:Qm},poweredBy:{...face(e,"regular"),color:t.text.muted,fontSize:i.size.micro,textAlign:"center",paddingBottom:n.xs}})}var Cb=18,Sb=28,jb=6,_b=1200,Rb=.4,Tb=.4;function DictationButton({active:e,listening:n,elapsedMs:l,disabled:o=false,onToggle:s}){let a=useEverfurTheme(),u=t.useMemo(()=>Ib(a),[a]);return t.useEffect(()=>{if(n)try{r.AccessibilityInfo.announceForAccessibility(vf.listening)}catch{}},[n]),/* @__PURE__ */i.jsxs(r.View,{style:u.wrap,children:[n?/* @__PURE__ */i.jsx(Text,{style:u.timer,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"everfur-dictation-timer",children:Ng(l)}):null,
|
|
141
|
+
/* @__PURE__ */i.jsx(r.Pressable,{onPress:()=>s(),disabled:o,accessibilityRole:"button",accessibilityLabel:e?vf.stopDictation:vf.dictate,accessibilityState:{selected:e,disabled:o},style:[u.button,o?u.buttonDisabled:null],testID:"everfur-dictation-button",children:e?/* @__PURE__ */i.jsxs(i.Fragment,{children:[
|
|
142
|
+
/* @__PURE__ */i.jsx(Pulse,{style:u.pulse,reduced:a.motion.reducedMotion}),
|
|
143
|
+
/* @__PURE__ */i.jsx(StopGlyph,{size:Sb,color:a.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */i.jsx(MicGlyph,{size:Cb,color:a.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:e,reduced:n}){let l=t.useRef(new r.Animated.Value(1)).current;return t.useEffect(()=>{if(n)return;let e=r.Animated.loop(r.Animated.sequence([r.Animated.timing(l,{toValue:Rb,duration:_b/2,useNativeDriver:true}),r.Animated.timing(l,{toValue:1,duration:_b/2,useNativeDriver:true})]));return e.start(),()=>e.stop()},[l,n]),/* @__PURE__ */i.jsx(r.Animated.View,{style:[e,{opacity:l}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function Ib(e){let t=e.color,n=e.type.tierSizes.compact.micro;return r.StyleSheet.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...face(e,"mono"),fontSize:n,lineHeight:n+2,fontVariant:["tabular-nums"],color:t.text.muted},button:{width:zm,height:zm,borderRadius:e.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:Tb},pulse:{position:"absolute",top:jb,right:jb,bottom:jb,left:jb,borderRadius:e.radius.pill,backgroundColor:t.brandSofter}})}var zb=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function Pb(){let e=globalThis,t=e[zb];if(t!==void 0)return t;let r={loader:null,memo:void 0};return e[zb]=r,r}function registerEverfurDictation(e){let t=Pb();t.loader=e,t.memo=void 0,t.version=(t.version??0)+1;for(let e of[...t.listeners??[]])try{e()}catch{}}function Eb(){return Pb().version??0}function Ob(e){let t=Pb(),r=t.listeners??/* @__PURE__ */new Set;t.listeners=r;let n=()=>e();return r.add(n),()=>{r.delete(n)}}function Ab(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.start=="function"&&typeof t.isRecognitionAvailable=="function"&&typeof t.addListener=="function"}function Mb(e){return typeof e!="object"||e===null?null:e.ExpoSpeechRecognitionModule??e}function Fb(){let e=Pb();if(e.memo!==void 0)return e.memo;e.memo=null;let t=e.loader;if(t===null||r.Platform.OS!=="ios"&&r.Platform.OS!=="android")return e.memo;let n=optionalModule("expo-speech-recognition",()=>({box:Mb(t())}),e=>typeof e=="object"&&e!==null&&Ab(e.box));return n.available&&(e.memo=n.module.box),e.memo}function Db(e){if(e===null)return false;try{return e.isRecognitionAvailable()===!0}catch{return false}}function Lb(){try{return Intl.DateTimeFormat().resolvedOptions().locale||Vb}catch{return Vb}}function Bb(e){return e.replace(/_/g,"-").toLowerCase()}var Vb="en-US";function Hb(e=Lb()){let[t=""]=e.replace(/_/g,"-").split("-u-"),r=t.split("-");if(r[0]?.toLowerCase()!=="en")return Vb;let n=r.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e));return n?`en-${n.toUpperCase()}`:Vb}function Ub(e,t){if(t.length===0)return null;let r=e=>t.find(t=>Bb(t)===Bb(e));return r(e)??r(Vb)??t.find(e=>Bb(e).startsWith("en-"))??null}async function Nb(e,t){if(r.Platform.OS!=="ios")return t;try{let{locales:r}=await e.getSupportedLocales({});return Ub(t,r??[])??t}catch{return t}}async function $b(e,t){let n=false;try{n=e.supportsOnDeviceRecognition()===!0}catch{n=false}if(!n)return"network";if(r.Platform.OS!=="android")return"on_device";try{let{installedLocales:r}=await e.getSupportedLocales({}),n=Bb(t);return(r??[]).some(e=>Bb(e)===n)?"on_device":"network"}catch{return"network"}}function Wb(){return r.Platform.OS!=="android"?true:Number(r.Platform.Version)>=qb}var qb=33;function Gb(e,t,r){return{lang:t,interimResults:true,continuous:Wb(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:e==="on_device",contextualStrings:r.slice(0,100),iosTaskHint:"dictation"}}var Kb=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),Yb=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function Qb(e){return Yb.has(e)}var Zb=600,Xb=3;function Jb(e,t,r){if(Kb.has(r))return null;let n=Qb(r)?Zb:0;return r==="language-not-supported"&&Bb(t)!==Bb(Vb)?{mode:"network",lang:Vb,delayMs:n}:e==="on_device"?{mode:"network",lang:t,delayMs:n}:n>0?{mode:"network",lang:t,delayMs:n}:null}function ey(e){return e==="not-allowed"?"permissionDenied":e==="no-speech"||e==="speech-timeout"?"noSpeech":"unavailable"}async function ty(e){try{if((await e.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await e.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var ry=55e3,ny=3e3,ly=1e3;function iy(e){return oy.has(e)||Qb(e)}var oy=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),sy=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function ay(e){return e.replace(/\s+/g," ").trim()}function uy(e,t,r){let n=ay(t);return r?n?{committed:[...e.committed,n],interim:""}:{committed:e.committed,interim:""}:{committed:e.committed,interim:n}}function cy(e){return ay([...e.committed,e.interim].join(" "))}function dy(e,t,r,n=Date.now){let l=0,i=null,o=Number.NEGATIVE_INFINITY,s=e=>i!==null&&i.token===e?i:null;function a(e){for(let t of e.subscriptions)try{t.remove()}catch{}e.subscriptions=[]}function u(e){a(e),e.autoStopTimer!==null&&clearTimeout(e.autoStopTimer),e.graceTimer!==null&&clearTimeout(e.graceTimer),e.retryTimer!==null&&clearTimeout(e.retryTimer),e.autoStopTimer=null,e.graceTimer=null,e.retryTimer=null,i===e&&(i=null)}function c(e){return!e.sawStart&&e.errorCode===null&&e.pendingRetry===null&&cy(e.transcript)===""&&e.launchedAt-o<ly}function d(e){return e.mode??"none"}function f(e,t){Wg(r(),"chat_dictation_completed",{mode:d(e),duration_ms:e.startedAt===null?0:Math.max(0,n()-e.startedAt),char_count:t.length})}function h(e,n){Wg(r(),"chat_dictation_failed",{mode:d(e),error:n}),t.onStatus("idle"),t.onError(n)}function p(e){if(s(e.token)===null)return;u(e);let r=cy(e.transcript),n=e.errorCode;if(n!==null&&!(r&&iy(n))){h(e,ey(n));return}if(!r){h(e,"noSpeech");return}f(e,r),t.onStatus("idle")}function g(l){l.subscriptions=[e.addListener("start",()=>{s(l.token)!==null&&(l.sawStart=true,l.startedAt===null&&(l.startedAt=n()),Wg(r(),"chat_dictation_started",{mode:d(l)}),t.onStatus("listening"))}),e.addListener("result",e=>{if(s(l.token)===null)return;let r=e?.results?.[0]?.transcript??"";l.transcript=uy(l.transcript,r,e?.isFinal===true),t.onText(cy(l.transcript))}),e.addListener("error",e=>{if(s(l.token)===null)return;let t=e?.error??"unknown";if(l.userStopped&&(t==="aborted"||Qb(t)))return;let r=cy(l.transcript)==="",n=l.mode!==null&&!l.userStopped&&r&&l.retries<Xb?Jb(l.mode,l.lang,t):null;if(n!==null){l.pendingRetry=n;return}l.errorCode===null&&(l.errorCode=t)}),e.addListener("end",()=>{if(s(l.token)!==null&&!c(l)){if(l.pendingRetry!==null){let e=l.pendingRetry;if(l.pendingRetry=null,l.retries+=1,l.lang=e.lang,e.delayMs<=0){m(l,e.mode);return}a(l),l.retryTimer=setTimeout(()=>{l.retryTimer=null,!(s(l.token)===null||l.userStopped)&&m(l,e.mode)},e.delayMs);return}p(l)}})]}function m(t,r){a(t),t.mode=r,t.sawStart=false,t.launchedAt=n(),t.transcript=sy,t.errorCode=null,g(t);try{e.start(Gb(r,t.lang,t.phrases))}catch{t.errorCode="unknown",p(t)}}async function b(t){let r=await ty(e);if(s(t.token)===null)return;if(r!=="granted"){u(t),h(t,r==="denied"?"permissionDenied":"unavailable");return}if(t.lang=await Nb(e,t.lang),s(t.token)===null)return;let n=await $b(e,t.lang);s(t.token)!==null&&(t.autoStopTimer=setTimeout(()=>y(t),ry),m(t,n))}function y(r){if(!(s(r.token)===null||r.userStopped)){if(r.userStopped=true,r.pendingRetry=null,r.mode===null||r.retryTimer!==null){u(r),t.onStatus("idle");return}r.graceTimer=setTimeout(()=>p(r),ny);try{e.stop()}catch{p(r)}}}return{start(e){if(i!==null)return;let r={token:++l,phrases:e,lang:Hb(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:sy,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};i=r,t.onStatus("starting"),b(r)},stop(){i!==null&&y(i)},cancel(){let r=i;if(r===null)return;let l=r.mode!==null&&r.retryTimer===null,s=cy(r.transcript);if(u(r),t.onStatus("idle"),!!l){s&&f(r,s),o=n();try{e.abort()}catch{}}},isActive:()=>i!==null,isPreparing:()=>i!==null&&i.mode===null}}function fy({enabled:e,input:n,setInput:l,phrases:i,maxLength:o,telemetry:s}){let a=t.useSyncExternalStore(Ob,Eb,Eb),u=t.useMemo(()=>e?Fb():null,[e,a]),c=t.useMemo(()=>Db(u),[u]),[d,f]=t.useState("idle"),[h,p]=t.useState(null),[g,m]=t.useState(0),b=t.useRef(n);b.current=n;let y=t.useRef(l);y.current=l;let v=t.useRef(s);v.current=s;let x=t.useRef(""),w=t.useRef(o);w.current=o;let k=t.useRef(null);u!==null&&k.current?.mod!==u&&(k.current?.controller.cancel(),k.current={mod:u,controller:dy(u,{onStatus:e=>{f(t=>e==="idle"&&t==="error"?t:e)},onText:e=>y.current(Ug(x.current,e,w.current)),onError:e=>{p(e),f("error")}},()=>v.current)});let C=u===null?null:k.current?.controller??null,S=t.useCallback(()=>{C?.cancel()},[C]),j=t.useCallback(()=>{if(C!==null){if(C.isActive()){C.stop();return}p(null),m(0),x.current=b.current,C.start(i)}},[C,i]);t.useEffect(()=>{if(d!=="listening")return;let e=Date.now();m(0);let t=setInterval(()=>m(Date.now()-e),1e3);return()=>clearInterval(t)},[d]),t.useEffect(()=>{if(d!=="error")return;let e=setTimeout(()=>{p(null),f("idle")},Hg);return()=>clearTimeout(e)},[d]),t.useEffect(()=>{if(C===null)return;let e=null;try{e=r.AppState.addEventListener("change",e=>{e==="background"&&!C.isPreparing()&&C.cancel()})}catch{}return()=>{e?.remove(),C.cancel()}},[C]);let _=e&&c;return t.useEffect(()=>{_||C?.cancel()},[_,C]),{supported:_,status:d,active:d==="starting"||d==="listening",error:h,elapsedMs:g,toggle:j,cancel:S}}var hy=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatTabsAsk.v1");function py(){let e=globalThis;return e[hy]??=t.createContext(null)}var gy=py();function my(){return t.useContext(gy)}var by=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function yy(){let e=globalThis,r=e[by];if(r!==void 0)return r;let n=t.createContext(true);return e[by]=n,n}var vy=yy();function xy(){return t.useContext(vy)}var wy=/* @__PURE__ */Object.freeze(["photo"]),ky=52,Cy=1.5,Sy=10,jy=14,_y=10,Ry=40,Ty=20,Iy=.3,zy=2.5,Py=1,Ey=1.5,Oy=38,Ay=22,My=3;function Fy(e,t,r,n="ask",l=false){let i=typeof t=="string"&&t.trim()!=="";return r&&i&&n!=="urgent"?kf(vf.placeholder,t):e!==null?!l||!e.includes("{pet}")?e:i?e.split("{pet}").join(t.trim()):kf(vf.placeholder,t):n==="urgent"?vf.placeholderUrgentWeb:n==="followUp"?vf.placeholderFollowUpWeb:kf(vf.placeholder,t)}function ComposerWithAttachments({attachments:e,...r}){let n=t.useMemo(()=>createRnChatAttachmentTransport(),[]),l=useChatAttachments({maxPerMessage:e.maxPerMessage??Ln,transport:n}),o=t.useMemo(()=>({state:l,sources:e.sources??wy,pick:e.pick}),[l,e.sources,e.pick]);/* @__PURE__ */
|
|
144
|
+
return i.jsx(Composer,{...r,attachments:o})}function Composer({send:e,stop:n,isStreaming:l,conversationId:o,attachments:s,seed:a,draftStore:u,onStage:c,onPreview:d,petName:f,petBreed:h=null,mood:p="ask",dictation:g=false,telemetry:m=null,compact:b=false,petPlaceholder:y=false,dimEmptySend:v=false}){let{theme:x,styles:w}=wb(),k=my(),C=b||k!==null,S=t.useMemo(()=>Uy(x),[x]),j=k?.paint.composer??null,_=t.useMemo(()=>Wy(x),[x]),R=sg(),[T,I]=Kg(e,o,a),[z,P]=t.useState(false),[E,O]=t.useState(false),A=t.useCallback(()=>O(true),[]),M=t.useCallback(()=>O(false),[]),[F,D]=t.useState(false);t.useEffect(()=>{D(false)},[o]);let L=Fy(x.meta.placeholder,f,y,p,x.meta.placeholderFillsPet===true),B=k?.paint.placeholder(L,p!=="ask")??L,V=t.useMemo(()=>Gg({name:f,breed:h}),[f,h]),H=fy({enabled:g,input:T,setInput:I,phrases:V,maxLength:mn,telemetry:m}),U=H.cancel,N=H.active;Yg(u,o===null?null:String(o),T,I,N);let $=t.useRef(o);t.useEffect(()=>{$.current!==o&&($.current=o,U())},[o,U]);let W=xy();t.useEffect(()=>{W||U()},[W,U]);let q=s?.state.uploading??false,G=s?.state.failed??false,K=q||G,Y=s?.state.attachments??Dy;Sg(Y.length,R);let Q=t.useCallback(()=>{let t=T.trim();if(t.length===0||K||[...t].length>mn)return;N&&U();let r=s?.state.s3Keys??Ly;s!==null&&r.length>0?(c(s.state.attachments.filter(e=>e.status==="uploaded").map(e=>({uri:e.previewUri,filename:e.filename}))),e(t,{imageS3Keys:r}),s.state.clear()):e(t),I(""),D(false)},[T,e,K,N,U,s,c]),Z=t.useCallback(e=>{N&&U(),I(e)},[N,U,I]),X=t.useCallback(()=>{n()},[n]),J=t.useCallback(e=>{P(false),s!==null&&(D(false),s.state.dismissRejected(),hh(s.pick,e).then(e=>{if(!e.ok){D(true);return}e.value!==null&&s.state.add(e.value)}))},[s]),ee=t.useMemo(()=>[...T.trim()].length>mn,[T]),te=ee||K||T.trim().length===0,re=ee||K||v&&T.trim().length===0,ne=s!==null&&Y.length>=s.state.maxPerMessage,le=x.slots.sendButton?.textColor??x.color.brandInk,ie=x.slots.sendButton?.textColor??x.color.surface;/* @__PURE__ */
|
|
145
|
+
return i.jsxs(r.View,{style:w.composerOuter,children:[s!==null&&z?/* @__PURE__ */i.jsx(AttachmentPickerPopover,{sources:s.sources,full:ne,onPick:J,onClose:()=>P(false)}):null,s!==null?/* @__PURE__ */i.jsx(AttachmentStrip,{attachments:Y,rejected:F?Hy:s.state.rejected,uploadFailed:G,onRetry:s.state.retry,onRemove:s.state.remove,onPreview:e=>d({uri:e.previewUri,label:e.filename}),style:C?S.tray:_.tray}):null,
|
|
146
|
+
/* @__PURE__ */i.jsxs(r.View,{style:C?[w.composer,S.bar,E?S.barFocused:null,j?.bar]:w.composer,children:[H.supported&&H.error!==null?/* @__PURE__ */i.jsxs(i.Fragment,{children:[
|
|
147
|
+
/* @__PURE__ */i.jsx(Text,{style:w.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:$g(H.error)}),
|
|
148
|
+
/* @__PURE__ */i.jsx(AnnounceLine,{line:$g(H.error)})]}):null,
|
|
149
|
+
/* @__PURE__ */i.jsxs(r.View,{style:w.composerRow,children:[s!==null?/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:ne?Bg(Y.length,s.state.maxPerMessage):vf.attachPhotoOrFileNative,accessibilityState:{disabled:ne,expanded:z},disabled:ne,style:[w.attachControl,C?S.add:null,ne?w.attachControlDisabled:null],hitSlop:C?My:void 0,onPress:()=>P(e=>!e),children:k!==null?/* @__PURE__ */i.jsx(k.paint.Icon,{name:"upload",size:Ny,color:ne?x.color.text.muted:k.paint.accent}):/* @__PURE__ */i.jsx(UploadGlyph,{size:C?Ay:Xm,color:ne?x.color.text.muted:C?x.color.text.primary:x.color.brandInk,strokeWidth:1.75})}):null,
|
|
150
|
+
/* @__PURE__ */i.jsx(Bd,{style:C?[w.input,S.input,j?.input]:w.input,onFocus:A,onBlur:M,value:T,onChangeText:Z,placeholder:B,placeholderTextColor:k?.paint.muted??x.slots.composerInput?.textColor??x.color.text.placeholder,accessibilityLabel:vf.composerLabel,onSubmitEditing:Q,returnKeyType:"send",...By,...C?Vy:null,blurOnSubmit:false,multiline:true,editable:true}),H.supported?/* @__PURE__ */i.jsx(DictationButton,{active:H.active,listening:H.status==="listening",elapsedMs:H.elapsedMs,onToggle:H.toggle}):null,l?/* @__PURE__ */i.jsx(r.Pressable,{onPress:X,accessibilityRole:"button",accessibilityLabel:vf.stop,style:w.sendControl,children:/* @__PURE__ */i.jsx(r.View,{style:C?[S.disc,j?.stopDisc]:w.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */i.jsx(StopGlyph,{size:C?Ty:Ym,color:C?ie:le,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */i.jsx(r.Pressable,{onPress:Q,disabled:te,accessibilityRole:"button",accessibilityLabel:vf.send,accessibilityState:{disabled:te,busy:q},style:[w.sendControl,re?C?S.dimmed:w.sendControlDisabled:null],children:k!==null&&j!==null?/* @__PURE__ */i.jsx(r.View,{style:j.send,testID:"everfur-send-disc",children:/* @__PURE__ */i.jsx(k.paint.Icon,{name:"send",size:$y,color:k.paint.accent})}):C?/* @__PURE__ */i.jsx(r.View,{style:S.disc,testID:"everfur-send-disc",children:/* @__PURE__ */i.jsx(ArrowUpGlyph,{size:Ty,color:ie,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */i.jsx(r.View,{style:w.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */i.jsx(SendGlyph,{size:Km,color:le,testID:"everfur-send-glyph"})})})]})]})]})}var Dy=/* @__PURE__ */Object.freeze([]),Ly=/* @__PURE__ */Object.freeze([]),By=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),Vy=/* @__PURE__ */Object.freeze(r.Platform.OS==="web"?{rows:1}:{}),Hy=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function Uy(e){let t=e.color,n=e.slots.sendButton,l=textRole(e,"body").fontSize+Py;return r.StyleSheet.create({bar:{marginTop:Sy,marginHorizontal:jy,marginBottom:_y,minHeight:ky,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:Cy,borderColor:e.slots.composerInput?.borderColor??t.text.primary},barFocused:{borderWidth:zy,paddingLeft:8-(zy-Cy),paddingRight:6-(zy-Cy)},input:{fontSize:l,lineHeight:Math.round(l*Ey),minHeight:Math.round(l*Ey),...r.Platform.OS==="web"?{outlineStyle:"none"}:null},add:{width:Oy,height:Oy,borderRadius:Oy/2},disc:{width:Ry,height:Ry,borderRadius:Ry/2,alignItems:"center",justifyContent:"center",backgroundColor:n?.backgroundColor??t.text.primary,...Mg(n)},dimmed:{opacity:Iy},tray:{marginHorizontal:jy,marginTop:Sy,paddingBottom:0}})}var Ny=20,$y=22;function Wy(e){return r.StyleSheet.create({tray:{marginHorizontal:e.space.md,marginTop:e.space.xs,paddingBottom:0}})}function useEverfurPets(){let{runtime:e,userRef:r,activePet:n,scopeEpoch:l}=Yc(),i=t.useMemo(()=>createPetsRepository(e.registry.services.authFor(r)),[e,r,l]),[o,s]=t.useState({repository:i,pets:[],loading:true,error:null}),a=o.repository===i?o:{pets:[],loading:true,error:null},u=t.useRef(0),c=t.useCallback(async()=>{let e=++u.current;s(e=>({...e,repository:i,loading:true,error:null,pets:e.repository===i?e.pets:[]}));let t=await i.list();e===u.current&&s(t.ok?{repository:i,pets:t.value,loading:false,error:null}:e=>({repository:i,pets:e.repository===i?e.pets:[],loading:false,error:t.error}))},[i]);t.useEffect(()=>(c(),()=>{u.current+=1}),[c]),t.useEffect(()=>fi(e,()=>{c()}),[e,c]);let d=t.useMemo(()=>n===null?null:a.pets.find(e=>e.petRef===n)??null,[n,a.pets]);return t.useMemo(()=>({pets:a.pets,activePet:d,loading:a.loading,error:a.error,refresh:c}),[a.pets,a.loading,a.error,d,c])}function qy(e,t){if(t!==null){let r=e.find(e=>e.petRef===t);if(r!==void 0)return r}return e[0]??null}var Gy=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var Ky=false;function Yy(e,t){return t!==void 0?(ch(t,e),"onStartInApp"):Kd(e)==="presented"?"presenter":Xd(e)?"experience":(Ky||(Ky=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var Qy=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(e){return typeof e=="string"&&Qy.includes(e)}var Zy="/widget/v1/televet/handoffs",Xy="/widget/v1/televet/availability",Jy="/widget/v1/televet/chat-entry",ev=/^[a-z0-9][a-z0-9_-]{0,39}$/,tv=/^[A-Za-z0-9_-]{22}$/;var rv=32,nv=128,lv=64;function vetVisitErrorReasonOf(e){let t=e.httpStatus;switch(e.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 t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}function iv(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function ov(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function sv(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!ev.test(n))return{ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n}let l=t?.entry;if(l!=null){if(l!=="chat"||e===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=l}let i=t?.visitRef,o=t?.intent,s=i!=null;if(s){let e=typeof i=="string"?i.trim():"";if(e.length<1||[...e].length>lv)return{ok:false,message:`visitRef must be 1..${lv} characters`};r.visit_ref=e}if(o!=null){if(!s)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(o))return{ok:false,message:`intent must be one of ${Qy.join(", ")}`};r.intent=o}return{ok:true,body:r}}function av(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!isVetVisitIntent(r)?null:/* @__PURE__ */Object.freeze({visitRef:t,intent:r})}function uv(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=e=>(gv(r,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(e)}),err(e));return{async createHandoff(e,l){let i;if(e!=null){let t=typeof e=="string"?[...e].length:0;if(t<1||t>nv)return n(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${nv} characters`}));i=e}let o=sv(i,l);if(!o.ok){let e=iv(o.message);return e.ok?e:n(e.error)}let s=o.body,a=await t.send("televet.visit.handoff",{method:"POST",path:Zy,body:s},{idempotent:false,maxAttempts:1});if(!a.ok)return n(a.error);let u=cv(a.value),c=s.return_to!==void 0,d=c?a.value?.flow_id:void 0;if(c&&(typeof d!="string"||!tv.test(d))){let e=ov("the handoff response carried no usable return flow id");return e.ok?e:n(e.error)}let f=s.visit_ref!==void 0,h=f?av(a.value?.visit):null;if(f&&h===null){let e=ov("the handoff response did not confirm the visit it opens");return e.ok?e:n(e.error)}let p=u===null?null:/* @__PURE__ */Object.freeze({...u,...c?{flowId:d}:{},...h!==null?{visit:h}:{}});return p===null?n(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(gv(r,"televet.visit.handoff_created",{pet_scoped:s.pet_ref!==void 0}),ok(p))},async checkAvailability(e){if(typeof e!="string"||e.length>rv)return iv(`state must be at most ${rv} characters`);let r=await t.send("televet.visit.availability",{method:"POST",path:Xy,body:{state:e}},{idempotent:false,maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.available;return typeof n!="boolean"?ov("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:n}))},async chatEntryOpen(){try{let e=await t.send("televet.visit.chat_entry",{method:"GET",path:Jy},{maxAttempts:1});return e.ok&&e.value?.open===!0}catch{return false}}}}function cv(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!pv(t)?null:/* @__PURE__ */Object.freeze({url:t,expiresAt:r})}var dv=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),fv=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,hv=/[\s\u0000-\u001f\u007f]/;function pv(e){if(hv.test(e))return false;let t=fv.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let l=n.replace(/:\d+$/,"").toLowerCase(),i=r==="https",o=r==="http"&&dv.has(l);if(!i&&!o)return false;let s=e.indexOf("#");if(s<0)return false;let a=e.slice(s);return a.startsWith("#h=")&&a.length>3}function gv(e,t,r){if(e)try{e.track(t,r)}catch{}}var mv=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function bv(e,r,n){let{usState:l,chat:i,scope:o}=n,s=r&&(l!==null||i),a=`${l??""}|${i?"chat":""}`,[u,c]=t.useState(null);if(t.useEffect(()=>{if(!s)return;let t=true,r=e.current;return c(null),(async()=>{try{if(i&&!(r.chatEntryOpen&&await r.chatEntryOpen()))return!1;if(l===null)return!0;if(!r.checkAvailability)return!1;let e=await r.checkAvailability(l);return e.ok&&e.value.available}catch{return false}})().then(e=>{t&&c({key:a,open:e})}),()=>{t=false}},[s,a,l,i,o,e]),!s)return null;let d=u!==null&&u.key===a;return{open:d&&u.open,pending:!d}}var yv=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function vv(e,r={}){let{runtime:n,userRef:l,scopeEpoch:i}=Yc(),o=useCapability("televet"),s=o.enabled&&l!==null,a=r.usState??null,u=r.entry==="chat",c=r.petRef??null,d=r.prefer==="redirect",f=t.useMemo(()=>{if(r.controller)return r.controller;let{services:e}=n.registry;return uv({auth:e.authFor(l),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})},[n,l,i,r.controller]),h=t.useRef(f);h.current=f;let p=t.useMemo(()=>({runtime:n,userRef:l,scopeEpoch:i}),[n,l,i]),g=bv(h,s,{usState:a,chat:u,scope:p}),m=s&&(g===null||g.open)&&(!u||c!==null),b=r.returnTo??null,[y,v]=t.useState(mv),x=t.useRef(null),w=t.useRef({runtime:n,userRef:l,scopeEpoch:i});w.current={runtime:n,userRef:l,scopeEpoch:i};let k=t.useRef(f);k.current=f;let C=t.useRef(m);C.current=m;let S=t.useCallback((t,r)=>{if(x.current)return x.current;let n=(e,t)=>(v({status:e==="cancelled"?"idle":"error",error:t,errorReason:e==="cancelled"?null:e}),/* @__PURE__ */Object.freeze({opened:false,reason:e,error:t}));if(!C.current)return Promise.resolve(n("unavailable",null));let l=e.prepare();if(!l.ok)return Promise.resolve(n(l.reason,null));let i=w.current,o=k.current;v(yv);let s=(async()=>{let s,a={...b!==null?{returnTo:b}:{},...u?{entry:"chat"}:{},...r!==null?{visitRef:r.visitRef}:{},...r!==null&&r.intent!==null&&r.intent!==void 0?{intent:r.intent}:{}},d=Object.keys(a).length===0?void 0:a,f=t===void 0?c:t;try{s=await(d===void 0?o.createHandoff(f):o.createHandoff(f,d))}catch{return e.abandon(l.value),n("unknown",null)}let h=w.current;if(h.runtime!==i.runtime||h.userRef!==i.userRef||h.scopeEpoch!==i.scopeEpoch)return e.abandon(l.value),n("cancelled",null);if(!s.ok)return e.abandon(l.value),n(vetVisitErrorReasonOf(s.error),s.error);let p=await e.finish(l.value,s.value);return p!==null?n(p,null):(v(mv),/* @__PURE__ */Object.freeze(s.value.flowId===void 0?{opened:true}:{opened:true,flowId:s.value.flowId}))})().finally(()=>{x.current===s&&(x.current=null)});return x.current=s,s},[e,c,b,u]),j=t.useCallback((e,t)=>{if(!C.current)return v({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let r=e===void 0?c:e,n={...r!==null?{petRef:r}:{},...a!==null?{usState:a}:{},...t!==null&&"consultId"in t?{consultId:t.consultId}:{},...t!==null&&"visitRef"in t?{visitRef:t.visitRef,intent:t.intent}:{}};return Yy(n)===null?(v({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(v(mv),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[c,a]),_=t.useCallback(e=>d?S(e,null):j(e,null),[d,S,j]),R=t.useCallback((e,t)=>d?S(void 0,{visitRef:e,intent:t??null}):j(void 0,{visitRef:e,intent:t??null}),[d,S,j]),T=t.useCallback(e=>d?S(void 0,null):j(void 0,{consultId:e.trim()}),[d,S,j]);return{available:m,isPending:o.isPending||(g?.pending??false),status:y.status,error:y.error,errorReason:y.errorReason,open:_,openVisit:R,joinVisit:T}}var xv=e=>r.Linking.openURL(e);function useVetVisit(e={}){let{openUrl:r,...n}=e,l=t.useMemo(()=>{let e=r??xv;return{prepare:()=>({ok:true,value:null}),async finish(t,r){try{return await e(r.url),null}catch{return"openFailed"}},abandon:()=>{}}},[r]);return vv(l,n)}var wv=44,kv=.6;function VetVisitButtonCore(e){let{petRef:n,label:l,openUrl:o,onOpened:s,onError:a,style:u,labelStyle:c,controller:d,returnTo:f,usState:h,entry:p,visitRef:g,intent:m,onStartInApp:b,prefer:y}=e,v=y==="redirect",x=useVetVisit({...f!==void 0?{returnTo:f}:{},...h!==void 0?{usState:h}:{},...p!==void 0?{entry:p}:{},...n!==void 0?{petRef:n}:{},...o!==void 0?{openUrl:o}:{},...d!==void 0?{controller:d}:{},prefer:v?"redirect":"in-app"}),w=useEverfurTheme(),k=t.useMemo(()=>Cv(w),[w]),C=t.useRef(false);if(!x.available)/* @__PURE__ */
|
|
151
|
+
return i.jsxs(i.Fragment,{children:[null,
|
|
152
|
+
/* @__PURE__ */i.jsx(TelevetHostOutlet,{})]});let S=x.status==="opening",j=l??Gy.visitButton;/* @__PURE__ */
|
|
153
|
+
return i.jsxs(i.Fragment,{children:[
|
|
154
|
+
/* @__PURE__ */i.jsx(r.Pressable,{onPress:()=>{if(!(S||C.current)){if(!v){let e={...n!==void 0?{petRef:n}:{},...h!==void 0?{usState:h}:{},...g!=null?{visitRef:g,intent:m??null}:{}};Yy(e,b)===null&&ch(a,"unavailable",null);return}C.current=true,(g==null?x.open():x.openVisit(g,m??null)).then(e=>{e.opened?ch(s,e.flowId??null):e.reason!=="cancelled"&&ch(a,e.reason,e.error)}).finally(()=>{C.current=false})}},accessibilityRole:"button",accessibilityLabel:j,accessibilityState:{busy:S,disabled:S},style:[k.button,S?k.busy:null,u],children:/* @__PURE__ */i.jsx(Text,{style:[k.label,c],children:j})}),
|
|
155
|
+
/* @__PURE__ */i.jsx(TelevetHostOutlet,{})]})}function Cv(e){let{color:t,space:n,radius:l,type:i,slots:o}=e;return r.StyleSheet.create({button:{minHeight:wv,minWidth:wv,alignItems:"center",justifyContent:"center",paddingHorizontal:n.xl,paddingVertical:n.sm,borderRadius:l.pill,backgroundColor:t.primary,...Mg(o.vetVisitButton)},busy:{opacity:kv},label:{...face(e,"medium"),color:t.onPrimary,fontSize:i.size.body,lineHeight:i.size.body*i.lineHeight.snug,...Dg(o.vetVisitButton)}})}function Sv(e){let[r,n]=t.useState(null);return{shown:e!==null&&r!==e,onError:()=>n(e)}}function BrandImage({uri:e,label:t,decorative:n=false,style:l,resizeMode:o="contain",fallback:s=null,onError:a,testID:u}){let c=Sv(e);if(e===null||!c.shown)return s;let d=n?{accessible:false,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"}:{accessible:true,accessibilityRole:"image",...t===void 0?{}:{accessibilityLabel:t}};/* @__PURE__ */
|
|
156
|
+
return i.jsx(r.Image,{source:{uri:e},style:l,resizeMode:o,...d,onError:()=>{c.onError(),a?.()},...u===void 0?{}:{testID:u}})}function BrandLogo({logoUrl:e,name:t,barStyle:n,logoStyle:l,testID:o}){let s=Sv(e);return e===null||!s.shown?null:/* @__PURE__ */i.jsx(r.View,{style:n,...o===void 0?{}:{testID:o},children:/* @__PURE__ */i.jsx(r.Image,{source:{uri:e},style:l,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:t,onError:s.onError})})}var jv=/* @__PURE__ */Object.freeze({row:null,leading:null,trailing:null}),_v=/* @__PURE__ */Object.freeze({leading:void 0,trailing:void 0});function Rv(e,t,r){if(e.row===null||e.leading===null||e.trailing===null)return _v;let n=Math.abs(e.leading-e.trailing);if(n<.5)return _v;let l=e.row-t-e.leading-e.trailing,i=Math.min(n,Math.max(0,l-r));return i<.5?_v:e.leading<e.trailing?{leading:e.leading+i,trailing:void 0}:{leading:void 0,trailing:e.trailing+i}}function Tv(e,t,r){let n=e[t];return n!==null&&Math.abs(n-r)<.5?e:{...e,[t]:r}}function Iv(e){return[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}function zv(e){if(e.brightness!=="light")return false;let t=Fo.color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t),l=new Set(Iv(t));return n(r.brand,t.brand)&&n(r.accent,t.accent)&&Iv(r).every(e=>l.has(e))}function Pv(e){let t=(e.brightness==="dark"?Lo:Fo).color,r=e.color,n=(e,t)=>parseColor(e)===parseColor(t);return{success:!n(r.success,t.success),warning:!n(r.warningStrong,t.warningStrong)||!n(r.cautionAccent,t.cautionAccent),info:!(n(r.info,r.brandInk)&&n(r.badgeBgInfo,r.brandSoft)&&n(r.infoEdge,r.structureEdge))}}function Ev(e){return canonicalPetSpecies(e)==="cat"?"cat":"dog"}function Ov(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}function Av(e){let t=Ov(e.ageYears),r=Ev(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return`${r} · ${n}`}var Mv=/* @__PURE__ */Object.freeze([
|
|
156
157
|
/* @__PURE__ */Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),
|
|
157
158
|
/* @__PURE__ */Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),
|
|
158
159
|
/* @__PURE__ */Object.freeze({background:"#fbc558",foreground:"#10462e"}),
|
|
159
160
|
/* @__PURE__ */Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),
|
|
160
161
|
/* @__PURE__ */Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),
|
|
161
|
-
/* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function
|
|
162
|
-
return
|
|
163
|
-
/* @__PURE__ */
|
|
164
|
-
/* @__PURE__ */
|
|
165
|
-
/* @__PURE__ */
|
|
166
|
-
/* @__PURE__ */
|
|
167
|
-
return
|
|
168
|
-
/* @__PURE__ */
|
|
169
|
-
/* @__PURE__ */
|
|
170
|
-
/* @__PURE__ */
|
|
171
|
-
/* @__PURE__ */
|
|
172
|
-
/* @__PURE__ */
|
|
173
|
-
/* @__PURE__ */
|
|
174
|
-
/* @__PURE__ */
|
|
175
|
-
return
|
|
176
|
-
/* @__PURE__ */
|
|
177
|
-
/* @__PURE__ */
|
|
178
|
-
/* @__PURE__ */
|
|
179
|
-
/* @__PURE__ */
|
|
180
|
-
/* @__PURE__ */
|
|
181
|
-
/* @__PURE__ */
|
|
182
|
-
/* @__PURE__ */
|
|
183
|
-
/* @__PURE__ */
|
|
184
|
-
/* @__PURE__ */
|
|
185
|
-
/* @__PURE__ */
|
|
186
|
-
/* @__PURE__ */
|
|
187
|
-
return
|
|
188
|
-
/* @__PURE__ */Object.freeze({key:"inaccurate",label:
|
|
189
|
-
/* @__PURE__ */Object.freeze({key:"outdated",label:
|
|
190
|
-
/* @__PURE__ */Object.freeze({key:"unsafe",label:
|
|
191
|
-
/* @__PURE__ */Object.freeze({key:"unclear",label:
|
|
192
|
-
/* @__PURE__ */Object.freeze({key:"other",label:
|
|
193
|
-
/* @__PURE__ */Object.freeze({sentiment:"up",label:
|
|
194
|
-
/* @__PURE__ */Object.freeze({sentiment:"down",label:
|
|
195
|
-
return
|
|
196
|
-
/* @__PURE__ */
|
|
197
|
-
/* @__PURE__ */
|
|
198
|
-
/* @__PURE__ */
|
|
199
|
-
/* @__PURE__ */
|
|
200
|
-
/* @__PURE__ */
|
|
201
|
-
/* @__PURE__ */
|
|
202
|
-
/* @__PURE__ */
|
|
203
|
-
/* @__PURE__ */
|
|
204
|
-
/* @__PURE__ */
|
|
205
|
-
return
|
|
206
|
-
/* @__PURE__ */
|
|
207
|
-
/* @__PURE__ */
|
|
208
|
-
/* @__PURE__ */
|
|
209
|
-
/* @__PURE__ */
|
|
210
|
-
/* @__PURE__ */
|
|
211
|
-
/* @__PURE__ */
|
|
212
|
-
/* @__PURE__ */
|
|
213
|
-
return
|
|
214
|
-
/* @__PURE__ */
|
|
215
|
-
/* @__PURE__ */
|
|
216
|
-
/* @__PURE__ */
|
|
217
|
-
/* @__PURE__ */
|
|
218
|
-
/* @__PURE__ */
|
|
219
|
-
/* @__PURE__ */
|
|
220
|
-
/* @__PURE__ */
|
|
221
|
-
/* @__PURE__ */
|
|
222
|
-
/* @__PURE__ */
|
|
223
|
-
/* @__PURE__ */
|
|
224
|
-
/* @__PURE__ */
|
|
225
|
-
/* @__PURE__ */
|
|
226
|
-
return
|
|
227
|
-
/* @__PURE__ */
|
|
228
|
-
/* @__PURE__ */
|
|
229
|
-
/* @__PURE__ */
|
|
230
|
-
/* @__PURE__ */
|
|
231
|
-
/* @__PURE__ */
|
|
232
|
-
/* @__PURE__ */
|
|
233
|
-
/* @__PURE__ */
|
|
234
|
-
/* @__PURE__ */
|
|
235
|
-
/* @__PURE__ */
|
|
236
|
-
/* @__PURE__ */
|
|
237
|
-
/* @__PURE__ */
|
|
238
|
-
return
|
|
239
|
-
/* @__PURE__ */
|
|
240
|
-
/* @__PURE__ */
|
|
241
|
-
return
|
|
242
|
-
/* @__PURE__ */
|
|
243
|
-
/* @__PURE__ */
|
|
244
|
-
/* @__PURE__ */
|
|
245
|
-
/* @__PURE__ */
|
|
246
|
-
/* @__PURE__ */
|
|
247
|
-
/* @__PURE__ */
|
|
248
|
-
/* @__PURE__ */
|
|
249
|
-
/* @__PURE__ */
|
|
250
|
-
/* @__PURE__ */
|
|
251
|
-
/* @__PURE__ */
|
|
252
|
-
/* @__PURE__ */
|
|
253
|
-
return
|
|
254
|
-
/* @__PURE__ */
|
|
255
|
-
/* @__PURE__ */
|
|
256
|
-
/* @__PURE__ */
|
|
257
|
-
/* @__PURE__ */
|
|
258
|
-
/* @__PURE__ */
|
|
259
|
-
/* @__PURE__ */
|
|
260
|
-
return
|
|
261
|
-
/* @__PURE__ */
|
|
262
|
-
/* @__PURE__ */
|
|
263
|
-
/* @__PURE__ */
|
|
264
|
-
/* @__PURE__ */
|
|
265
|
-
/* @__PURE__ */
|
|
266
|
-
return
|
|
267
|
-
/* @__PURE__ */
|
|
268
|
-
/* @__PURE__ */l.jsx(Text,{tier:"control",style:a.pillText,numberOfLines:1,children:u})]})}var Yw=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:Uw};function Qw(e){let t=e.text(".hp-need__s",".ask-focus .hp-need__s"),r=typeof t.lineHeight=="number"?t.lineHeight:21,n=e.view(".dot",".dot--risk"),i=typeof n.height=="number"?n.height:Nw;return{card:e.view(".ask-focus"),kickerRow:e.view(".hp-need__k"),kicker:[e.text(".hp-need__k"),{flexShrink:1}],badge:[e.view(".hp-srcs"),e.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:e.text(".hp-src",".hp-src--dna"),close:e.view(".ask-focus__x"),title:[e.view(".ask-focus h3"),e.text(".ask-focus h3")],finding:[e.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[e.col(".hp-need__s",0),n,{marginTop:Math.round((r-i)/2)}],findingText:[e.col(".hp-need__s",1),t],lead:(({fontFamily:e,fontWeight:t,color:r})=>({fontFamily:e,fontWeight:t,color:r}))(e.strong(".hp-need__s b")),actions:e.view(".ask-focus__acts"),action:[e.view(".emb-btn",".emb-btn--sm"),{maxWidth:"100%"}],actionText:e.text(".emb-btn",".emb-btn--sm"),ask:[e.view(".ask-focus__q"),{justifyContent:"center",maxWidth:"100%"}],askText:e.text(".ask-focus__q"),pill:[e.view(".ask-focus-pill"),{maxWidth:"100%"}],pillDot:e.view(".ask-focus-pill i"),pillText:[e.text(".ask-focus-pill"),{flexShrink:1}]}}function Zw(e){let t=e.color,n=e.space;return r.StyleSheet.create({card:{paddingTop:Pw,paddingHorizontal:Ew,paddingBottom:Ew,borderRadius:zw,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:n.sm,minHeight:Rm-8},kicker:{...Iw(e),fontSize:Mw,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:Dw,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:Fw,color:t.text.secondary},close:{width:Rm,height:Rm,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:Rm/2},title:{...Iw(e),fontSize:Ow,lineHeight:Aw,color:t.text.primary,marginTop:n.xs},finding:{flexDirection:"row",gap:n.sm,marginTop:n.xs+2},dot:{width:Nw,height:Nw,borderRadius:Nw/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:Bw,lineHeight:Vw,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:n.lg,marginTop:14},action:{minHeight:Math.max(Kw,Rm),paddingHorizontal:n.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:Lw,color:t.onPrimary},ask:{minHeight:Rm,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:Hw,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:n.sm,minHeight:Math.max($w,Rm),paddingHorizontal:Ww,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:Gw,height:Gw,borderRadius:Gw/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:qw,color:t.danger,flexShrink:1}})}var Xw=/* @__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"}),Jw=/* @__PURE__ */new WeakMap;function ek(e){let t=Jw.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",i=n?{dark:n,ink:r.text.primary,ink2:r.text.secondary,ink3:r.text.muted,paper:r.background,card:r.surface,line:r.borderRingCream,tile:r.surfaceSubtle,shadow:r.shadow,riskBg:r.badgeBgCritical,riskInk:r.danger,riskDot:r.danger,clearBg:r.badgeBgPositive,clearInk:r.success,clearDot:r.success,watchDot:r.warningStrong}:{dark:n,...Xw},l=(e,t)=>Ul(e,t,Al(t),tk),o=(e,t)=>contrastRatio(e,t)>=tk?e:Ol(t,tk),s=[i.card,i.paper].map(e=>Bl(r.brandSoft,e)??e),a={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:l(r.linkInk,[i.card,i.paper,i.tile]),badge:r.brandSoft,onBadge:l(r.brandInk,s)},u=/* @__PURE__ */Object.freeze({...i,...a});return Jw.set(e,u),u}var tk=4.5;function rk(e,t){for(let r of t)if(contrastRatio(r,e)>=tk)return r;return Ol(e,tk)}function nk(e,t,r){let n=Vl(e,t);return(n===null?null:Bl(n,r))??r}function ik(e){let t=ek(e),r=e.color,n=t.card;return{ink:t.ink,ink2:t.ink2,ink3:t.ink3,paper:t.paper,tile:t.tile,line:t.line,card:n,onInk:t.dark?r.background:"#FFFFFF",primary:t.primary,onPrimary:t.onPrimary,accent:t.accent,onAccent:rk(t.accent,[t.ink,t.onAccent]),accent2:nk(t.accent,.75,n),accent4:nk(t.accent,.17,n),accentChip:nk(t.accent,.47,n),link:t.link,linkChip:nk(t.link,.2,n),riskDot:t.riskDot,riskChip:t.dark?r.badgeBgCritical:"#FFD8D6",clearBg:t.clearBg,clearInk:t.clearInk,clearChip:t.dark?r.badgeBgPositive:"#DDEFC4",byInk:r.brandInk}}var lk=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),sk=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),ak=["paddingTop","paddingRight","paddingBottom","paddingLeft"],uk=17,ck=1.5,dk=400,fk=700;function hk(e){return e<=450?"regular":e<=650?"medium":"bold"}function pk(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function gk(e,t,r){if(t==="$mono"){let t=r<=450?"mono":r<=650?"monoMedium":"monoBold",n=face(e,t);return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:pk(r)}}let n=t==="$serif"?headingFace(e,hk(r)):face(e,hk(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:pk(r)}}function mk(e,t,r={}){let n=ik(e),i=e.brightness==="dark",l=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?i?n.line??e:`#${t.slice(2)}`:t==="sans"||t==="serif"||t==="mono"?e:n[t]??e}return Array.isArray(e)?e.map(e=>o(e)):e},s=/* @__PURE__ */new Map,a=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),i=n.join("|"),a=s.get(i);if(a!==void 0)return a;let u={},c=e=>{if(e!==void 0)for(let[t,r]of Object.entries(e))u[t]=o(r)};for(let e of n)c(t[e]),l&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return s.set(i,d),d},u=/* @__PURE__ */new Map,c=(...e)=>{let t=e.filter(Boolean).join("|"),r=u.get(t);if(r!==void 0)return r;let n=a(e),i={};for(let[e,t]of Object.entries(n))lk.has(e)||sk.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(i[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=i.height;delete i.height,typeof i.minHeight!="number"&&(i.minHeight=e)}let l=n.ring;if(Array.isArray(l)){let[e,t]=l;i.borderWidth=e,i.borderColor=t;for(let t of ak){let r=i[t];typeof r=="number"&&(i[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;i.borderBottomWidth=e,i.borderBottomColor=t}let s=n.shadow;if(Array.isArray(s)){let[e,t,r,n]=s;i.shadowColor=n,i.shadowOffset={width:e,height:t},i.shadowOpacity=1,i.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;i.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(i);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let i=`${t}|${r.filter(Boolean).join("|")}`,l=d.get(i);if(l!==void 0)return l;let o=a(r),s=typeof o.fontSize=="number"?o.fontSize:uk,u=typeof o.lh=="number"?o.lh:ck,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...gk(e,f,c),fontSize:s,lineHeight:Math.round(s*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*s*100)/100);for(let e of["fontStyle","textAlign","textTransform","textDecorationLine"])typeof o[e]=="string"&&(h[e]=o[e]);let p=/* @__PURE__ */Object.freeze(h);return d.set(i,p),p};return{reduced:l,colors:n,view:c,text:(...e)=>f(dk,e),strong:(...e)=>f(fk,e),icon:(...e)=>{let t=a(e),r={tintColor:typeof t.color=="string"?t.color:n.ink};for(let e of["width","height","opacity"])typeof t[e]=="number"&&(r[e]=t[e]);return r},col:(e,t)=>{let r=a([e]).cols;if(!Array.isArray(r))return{};let n=r[Math.min(t,r.length-1)];if(typeof n=="number")return{width:n,flexShrink:0};let i=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(i)?i:1,minWidth:0}},motion:(...e)=>{let t=a(e),r=t.ease;return{dur:typeof t.dur=="number"?t.dur:0,delay:typeof t.delay=="number"?t.delay:0,stagger:typeof t.stagger=="number"?t.stagger:0,ease:Array.isArray(r)&&r.length===4?r:null}},raw:(e,...t)=>a(t)[e]}}var bk={".serif":{family:"$serif",fontWeight:"800",ls:-.01},".emb-btn":{flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48,paddingTop:0,paddingRight:22,paddingBottom:0,paddingLeft:22,borderRadius:999,backgroundColor:"$primary",color:"$onPrimary",fontWeight:"700",fontSize:16,textDecorationLine:"none",dur:160,ease:[.23,1,.32,1],gap:8},".emb-btn--sm":{minHeight:40,paddingTop:0,paddingRight:16,paddingBottom:0,paddingLeft:16,fontSize:15},".dot":{width:9,height:9,round:1,flexGrow:0,flexShrink:0},".dot--risk":{backgroundColor:"$riskDot"},".ask-chips":{flexDirection:"column",alignItems:"center",marginTop:22,gap:10},".chip":{paddingTop:10,paddingRight:16,paddingBottom:10,paddingLeft:16,borderRadius:999,fontSize:15,fontWeight:"600",lh:1.3,textAlign:"center",dur:160,ease:[.23,1,.32,1]},".ask-empty":{minHeight:"100%",flexDirection:"column",alignItems:"center",paddingTop:14,paddingRight:16,paddingBottom:22,paddingLeft:16,textAlign:"center"},".ask-empty h2":{fontSize:23,lh:1.12},".ask-start":{width:"100%",marginTop:"auto",marginRight:0,marginBottom:"auto",marginLeft:0,paddingTop:18,paddingRight:0,paddingBottom:18,paddingLeft:0,flexDirection:"column",alignItems:"center"},".ask-empty .ask-chips":{marginTop:14,alignSelf:"center",alignItems:"stretch",width:"100%",maxWidth:340},".hp-need__k":{flexDirection:"row",alignItems:"center",fontSize:15,fontWeight:"800",gap:8},".hp-srcs":{marginLeft:"auto",flexDirection:"row",gap:4},".hp-src":{height:24,paddingTop:0,paddingRight:9,paddingBottom:0,paddingLeft:9,borderRadius:999,backgroundColor:"$tile",color:"$ink2",fontSize:12,fontWeight:"700",flexDirection:"row",alignItems:"center",nowrap:1},".hp-src--dna":{backgroundColor:"$n_E0FDFF",color:"$link"},".hp-need__s":{alignItems:"baseline",marginTop:6,fontSize:15,lh:1.45,color:"$ink2",flexDirection:"row",cols:[9,"1fr"],gap:9},".hp-need__s b":{color:"$ink",fontWeight:"800"},".ask-focus":{width:"100%",paddingTop:14,paddingRight:16,paddingBottom:16,paddingLeft:16,borderRadius:20,backgroundColor:"$card",textAlign:"left",shadow:[0,1,3,"rgba(38, 37, 35, .07)"]},".ask-focus h3":{marginTop:10,fontSize:18,fontWeight:"800",lh:1.22},".ask-focus__x":{width:36,height:36,marginTop:-8,marginRight:-10,marginBottom:-8,marginLeft:-2,alignItems:"center",justifyContent:"center",round:1,color:"$ink2"},".ask-focus__x svg":{width:18,height:18},".ask-focus-pill":{marginLeft:"auto",flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:14,paddingBottom:0,paddingLeft:14,borderRadius:999,backgroundColor:"$n_FFE3E1",color:"$n_B0231B",fontSize:15,fontWeight:"800",gap:7},".ask-focus-pill i":{width:8,height:8,round:1,backgroundColor:"$riskDot"},".ask-focus .hp-need__s":{fontSize:14.5},".ask-focus__acts":{flexDirection:"row",flexWrap:"wrap",alignItems:"center",marginTop:12,rowGap:4,columnGap:16},".ask-focus__q":{minHeight:36,fontSize:14.5,fontWeight:"700",color:"$link",textDecorationLine:"underline"},".ask-top":{alignSelf:"stretch",flexDirection:"row",marginTop:-8,marginRight:0,marginBottom:6,marginLeft:0},".thread__hist":{flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:4,paddingBottom:0,paddingLeft:4,fontSize:15,fontWeight:"700",color:"$link",gap:6},".thread__hist svg":{width:18,height:18},".thread__count":{minWidth:22,height:20,paddingTop:0,paddingRight:6,paddingBottom:0,paddingLeft:6,borderRadius:999,backgroundColor:"$card",color:"$ink2",fontSize:12,fontWeight:"800",alignItems:"center",justifyContent:"center",ring:[1,"$line"]}},yk=16;var vk=4e3,xk=.5;function wk(e,t,r){let n=1,i=-1;for(let l of e)i<0?i=l:i+t+l<=r?i+=t+l:(n+=1,i=l);return n}function kk(e,t,r){if(e.length===0)return r;let n=wk(e,t,r),i=[];for(let n=0;n<e.length;n+=1){let l=0;for(let o=n;o<e.length;o+=1)l+=(o>n?t:0)+e[o],l<=r&&i.push(l)}i.sort((e,t)=>e-t);let l=xk*e.length+1;for(let o of i)if(wk(e,t,o)<=n)return Math.min(r,o+l);return r}function BalancedTitle({text:e,style:n,measureCh:i}){let o=t.useMemo(()=>e.split(/\s+/).filter(e=>e!==""),[e]),s=r.StyleSheet.flatten(n),a=[e,s.fontFamily,s.fontSize,s.fontWeight,s.letterSpacing].join("|"),u=t.useRef({key:"",ch:null,line:null,words:[]});u.current.key!==a&&(u.current={key:a,ch:null,line:null,words:o.map(()=>null)});let[c,d]=t.useState(null),f=c!==null&&c.key===a?c.value:null,h=()=>{let e=u.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,r=t.reduce((e,t)=>e+t,0),n=t.length>1?Math.max(0,(e.line-r)/(t.length-1)):0,l=kk(t,n,(e.ch+xk)*i);d(t=>t!==null&&t.key===e.key&&t.value===l?t:{key:e.key,value:l})},p=e=>t=>{u.current.key===a&&(e(u.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
|
|
269
|
-
return
|
|
270
|
-
/* @__PURE__ */
|
|
271
|
-
/* @__PURE__ */
|
|
272
|
-
/* @__PURE__ */
|
|
273
|
-
/* @__PURE__ */
|
|
274
|
-
return Object.freeze({...e,borderColor:o,backgroundColor:
|
|
275
|
-
return
|
|
276
|
-
/* @__PURE__ */
|
|
277
|
-
/* @__PURE__ */
|
|
278
|
-
return
|
|
279
|
-
/* @__PURE__ */
|
|
280
|
-
return
|
|
281
|
-
return
|
|
282
|
-
/* @__PURE__ */
|
|
283
|
-
/* @__PURE__ */
|
|
284
|
-
return
|
|
285
|
-
/* @__PURE__ */
|
|
286
|
-
/* @__PURE__ */
|
|
287
|
-
/* @__PURE__ */
|
|
288
|
-
return Object.freeze({title:o,sourceName:r,section:n,authorityTier:
|
|
289
|
-
return
|
|
290
|
-
return
|
|
291
|
-
return
|
|
292
|
-
/* @__PURE__ */
|
|
293
|
-
/* @__PURE__ */
|
|
294
|
-
return
|
|
295
|
-
return
|
|
296
|
-
return
|
|
297
|
-
/* @__PURE__ */
|
|
298
|
-
/* @__PURE__ */
|
|
299
|
-
/* @__PURE__ */
|
|
300
|
-
/* @__PURE__ */
|
|
301
|
-
/* @__PURE__ */
|
|
302
|
-
return
|
|
303
|
-
/* @__PURE__ */
|
|
304
|
-
/* @__PURE__ */
|
|
305
|
-
return
|
|
306
|
-
return
|
|
307
|
-
return
|
|
308
|
-
/* @__PURE__ */
|
|
309
|
-
/* @__PURE__ */
|
|
310
|
-
/* @__PURE__ */
|
|
311
|
-
/* @__PURE__ */
|
|
312
|
-
/* @__PURE__ */
|
|
313
|
-
return
|
|
314
|
-
return
|
|
315
|
-
/* @__PURE__ */
|
|
316
|
-
/* @__PURE__ */
|
|
317
|
-
return
|
|
318
|
-
return
|
|
319
|
-
/* @__PURE__ */
|
|
320
|
-
/* @__PURE__ */
|
|
321
|
-
/* @__PURE__ */
|
|
322
|
-
/* @__PURE__ */
|
|
323
|
-
return
|
|
324
|
-
/* @__PURE__ */
|
|
325
|
-
/* @__PURE__ */
|
|
326
|
-
/* @__PURE__ */
|
|
327
|
-
return
|
|
328
|
-
return
|
|
329
|
-
/* @__PURE__ */
|
|
330
|
-
/* @__PURE__ */
|
|
331
|
-
/* @__PURE__ */
|
|
332
|
-
return
|
|
333
|
-
/* @__PURE__ */
|
|
334
|
-
/* @__PURE__ */
|
|
335
|
-
/* @__PURE__ */
|
|
162
|
+
/* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function Fv(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return Mv[t%Mv.length]}function Dv(e){let t=(e??"").trim();return(Array.from(t)[0]??"?").toUpperCase()}function Lv(e){return{...Fv(e.petRef),initial:Dv(e.name)}}function Bv(e,t,r){let n=Lv(e);return t?n:{background:r.fill,foreground:r.ink,initial:n.initial}}function Vv(e){return Math.max(12,Math.round(e*.42))}function PetDisc({pet:e,size:n,ringStroke:l}){let o=useEverfurTheme(),s=t.useMemo(()=>Hv(o),[o]),a=n-l*2,u=e===null?null:Bv(e,zv(o),{fill:o.color.highlight,ink:o.color.onHighlight}),c=Vv(a);/* @__PURE__ */
|
|
163
|
+
return i.jsx(Ring,{size:n,strokeWidth:l,color:o.color.mark,children:/* @__PURE__ */i.jsx(r.View,{style:[s.disc,{width:a,height:a,borderRadius:a/2},u===null?s.discEmpty:{backgroundColor:u.background}],children:/* @__PURE__ */i.jsx(Text,{tier:"badge",style:[s.letter,{fontSize:c,lineHeight:Math.round(c*1.2),color:u===null?o.color.text.muted:u.foreground}],children:u===null?Dv(null):u.initial})})})}function Hv(e){return r.StyleSheet.create({disc:{alignItems:"center",justifyContent:"center",overflow:"hidden"},discEmpty:{backgroundColor:e.color.brandSoft},letter:{...face(e,"bold"),textAlign:"center",includeFontPadding:false}})}function Uv(e,t){let{borderRadius:r,...n}=Mg(e,t);return r===void 0?n:{...n,borderTopLeftRadius:r,borderTopRightRadius:r}}function Nv(e,t){let{backgroundColor:r,borderColor:n,borderWidth:l,borderRadius:i}=Mg(e,t);return{...r===void 0?{}:{backgroundColor:r},...n===void 0?{}:{borderRightColor:n,borderRightWidth:l??1},...i===void 0?{}:{borderTopRightRadius:i,borderBottomRightRadius:i}}}var $v=48,Wv=2,qv=320,Gv="80%",Kv="rgba(17,17,17,0.45)",Yv=18,Qv=22,Zv=12,Xv=.4,Jv=44;function ex(e){return e?.name?.trim()||vf.yourPet}function PetSwitcherSheet({visible:e,pets:n,activePetRef:l,onSelect:o,onAddPet:s=null,onClose:a}){let u=useEverfurTheme(),c=t.useMemo(()=>tx(u),[u]),d=hf();return e?/* @__PURE__ */i.jsx(r.Modal,{visible:true,transparent:true,animationType:u.motion.reducedMotion?"none":"fade",onRequestClose:a,children:/* @__PURE__ */i.jsxs(r.View,{style:c.root,children:[
|
|
164
|
+
/* @__PURE__ */i.jsx(r.Pressable,{style:om,onPress:a,accessibilityRole:"button",accessibilityLabel:vf.close,children:/* @__PURE__ */i.jsx(r.View,{style:c.backdrop})}),
|
|
165
|
+
/* @__PURE__ */i.jsxs(r.View,{style:pf(c.panel,d),accessibilityViewIsModal:true,children:[
|
|
166
|
+
/* @__PURE__ */i.jsx(Text,{tier:"heading",style:c.title,accessibilityRole:"header",children:vf.yourPets}),
|
|
167
|
+
/* @__PURE__ */i.jsx(r.ScrollView,{style:c.list,contentContainerStyle:c.listContent,showsVerticalScrollIndicator:true,children:n.map(e=>{let t=e.petRef===l,n=ex(e),s=Av(e);/* @__PURE__ */
|
|
168
|
+
return i.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:xf(t?vf.petCurrentlyActive:vf.switchToPet,{name:n}),accessibilityState:{selected:t},style:[c.row,t?c.rowActive:null],onPress:()=>o(e.petRef),children:[
|
|
169
|
+
/* @__PURE__ */i.jsx(PetDisc,{pet:e,size:$v,ringStroke:Wv}),
|
|
170
|
+
/* @__PURE__ */i.jsxs(r.View,{style:c.copy,children:[
|
|
171
|
+
/* @__PURE__ */i.jsx(Text,{style:c.name,numberOfLines:1,children:n}),
|
|
172
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:c.meta,numberOfLines:1,children:t?`${vf.activePrefix}${s}`:s})]}),t?/* @__PURE__ */i.jsx(CheckGlyph,{size:Yv,color:u.color.brandInk}):null]},e.petRef)})}),s!==null?/* @__PURE__ */i.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:vf.addAnotherPet,style:c.addRow,onPress:s,children:[
|
|
173
|
+
/* @__PURE__ */i.jsx(r.View,{style:c.addDisc,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:c.addPlus,children:"+"})}),
|
|
174
|
+
/* @__PURE__ */i.jsx(Text,{style:c.addLabel,children:vf.addAnotherPet})]}):null,
|
|
175
|
+
/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:vf.close,containerStyle:c.closeSlot,style:c.closeButton,onPress:a,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:c.closeText,children:vf.close})})]})]})}):null}function tx(e){let t=e.color,n=e.radius,l=Dg(e.slots.dialog);return r.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},backdrop:{flex:1,backgroundColor:Kv},panel:{backgroundColor:t.surface,paddingHorizontal:20,paddingTop:20,paddingBottom:32,borderTopLeftRadius:Qv,borderTopRightRadius:Qv,gap:14,maxHeight:Gv,...Uv(e.slots.dialog)},title:{...headingFace(e,"bold"),fontSize:18,lineHeight:22,color:t.brandInk,...l},list:{maxHeight:qv,flexShrink:1},listContent:{gap:10},addRow:{flexDirection:"row",alignItems:"center",gap:12,minHeight:Jv,paddingHorizontal:8},addDisc:{width:$v,height:$v,borderRadius:n.pill,alignItems:"center",justifyContent:"center",borderWidth:Wv,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream},addPlus:{...face(e,"bold"),fontSize:20,lineHeight:22,color:t.brandInk},addLabel:{...face(e,"bold"),fontSize:15,lineHeight:20,color:t.text.primary,...l},row:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:n.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface},rowActive:{borderColor:t.brandInk,backgroundColor:t.brandSoft},copy:{flex:1,gap:2},name:{...face(e,"bold"),fontSize:15,lineHeight:18,color:t.text.primary},meta:{...face(e,"monoBold"),fontSize:11,lineHeight:13,color:t.text.muted,textTransform:"uppercase",letterSpacing:Xv},closeSlot:{alignSelf:"flex-end"},closeButton:{paddingHorizontal:18,paddingVertical:10,borderRadius:Zv,backgroundColor:t.brandSoft},closeText:{...face(e,"bold"),color:t.brandInk,fontSize:13,lineHeight:16,letterSpacing:Xv}})}var rx=44,nx=36,lx=22,ix=20,ox=9,sx=1.5,ax=6,ux=35,cx=1.75,dx=12.4,fx=.5,hx=8,px=28,gx=160,mx=16,bx=8;function yx(e,t){return qy(e,t)}function ChatHeader({pets:e,petRef:n,historyUnread:l,onOpenHistory:o,onNewChat:s,onPetChange:a,onAddPet:u,vet:c,textingEntry:d=null}){let f=useEverfurTheme(),h=t.useMemo(()=>vx(f),[f]),[p,g]=t.useState(false),m=yx(e.pets,n),b=m!==null&&(e.pets.length>=2||u!==void 0),y=n??m?.petRef??null,v=ex(m),[x,w]=t.useState(jv),k=t.useCallback(e=>t=>{let r=t.nativeEvent.layout.width;w(t=>Tv(t,e,r))},[]),C=t.useMemo(()=>k("row"),[k]),S=t.useMemo(()=>k("leading"),[k]),j=t.useMemo(()=>k("trailing"),[k]),_=2*mx+2*(f.slots.header?.borderColor!==void 0?1:0)+2*bx,R=Rv(x,_,gx),T=t=>{g(false),e.setActivePet(t),ch(a,t)},I=u===void 0?null:()=>{g(false),ch(u)};/* @__PURE__ */
|
|
176
|
+
return i.jsxs(i.Fragment,{children:[
|
|
177
|
+
/* @__PURE__ */i.jsxs(r.View,{style:h.row,onLayout:C,children:[
|
|
178
|
+
/* @__PURE__ */i.jsx(r.View,{style:[h.leading,R.leading===void 0?null:{minWidth:R.leading}],children:/* @__PURE__ */i.jsxs(r.View,{style:h.sideContent,onLayout:S,children:[s!==void 0?/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:wp.newChat,containerStyle:h.iconSlot,style:h.iconButton,onPress:s,children:/* @__PURE__ */i.jsx(EditGlyph,{size:ix,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2})}):null,
|
|
179
|
+
/* @__PURE__ */i.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:l?`${vf.openHistoryNative}${vf.newReplySuffix}`:vf.openHistoryNative,containerStyle:h.iconSlot,style:h.iconButton,onPress:o,children:[
|
|
180
|
+
/* @__PURE__ */i.jsx(MenuGlyph,{size:lx,color:f.slots.header?.textColor??f.color.text.primary,strokeWidth:2}),l?/* @__PURE__ */i.jsx(r.View,{style:h.unreadDot,pointerEvents:"none"}):null]})]})}),
|
|
181
|
+
/* @__PURE__ */i.jsx(r.View,{style:h.centre,pointerEvents:"box-none",children:/* @__PURE__ */i.jsx(BrandLogo,{logoUrl:f.meta.logoUrl,name:f.meta.displayName,barStyle:h.logoBar,logoStyle:h.logo})}),
|
|
182
|
+
/* @__PURE__ */i.jsx(r.View,{style:[h.trailing,R.trailing===void 0?null:{minWidth:R.trailing}],children:/* @__PURE__ */i.jsxs(r.View,{style:h.trailingContent,onLayout:j,children:[y===null?null:/* @__PURE__ */i.jsx(VetVisitButtonCore,{entry:"chat",petRef:y,...c?.returnTo!==void 0?{returnTo:c.returnTo}:{},...c?.usState!==void 0?{usState:c.usState}:{},...c?.prefer!==void 0?{prefer:c.prefer}:{},style:h.vetEntry,labelStyle:h.vetEntryLabel}),
|
|
183
|
+
/* @__PURE__ */i.jsx(r.View,{style:h.right,children:b?/* @__PURE__ */i.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:xf(vf.switchActivePet,{name:v}),containerStyle:h.avatarSlot,style:h.avatarWrap,onPress:()=>g(true),children:[
|
|
184
|
+
/* @__PURE__ */i.jsx(PetDisc,{pet:m,size:ux,ringStroke:cx}),
|
|
185
|
+
/* @__PURE__ */i.jsx(r.View,{style:h.addBadge,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */i.jsx(PlusGlyph,{size:hx,color:f.color.brandInk,strokeWidth:2})})]}):e.loading&&m===null?
|
|
186
|
+
/* @__PURE__ */i.jsx(r.View,{style:h.avatarWrap,accessible:true,accessibilityLabel:vf.yourPet,children:/* @__PURE__ */i.jsx(Ring,{size:ux,strokeWidth:cx,color:f.color.mark,children:/* @__PURE__ */i.jsx(r.View,{style:h.placeholderDisc})})}):/* @__PURE__ */i.jsx(r.View,{style:h.avatarWrap,accessible:true,accessibilityRole:"image",accessibilityLabel:m===null?vf.yourPet:v,children:/* @__PURE__ */i.jsx(PetDisc,{pet:m,size:ux,ringStroke:cx})})})]})}),
|
|
187
|
+
/* @__PURE__ */i.jsx(PetSwitcherSheet,{visible:p,pets:e.pets,activePetRef:m?.petRef??null,onSelect:T,onAddPet:I,onClose:()=>g(false)})]}),d===null?null:/* @__PURE__ */i.jsx(TextingEntryRow,{entry:d,place:"header"})]})}function TextingEntryRow({entry:e,place:n}){let l=useEverfurTheme(),o=t.useMemo(()=>vx(l),[l]);/* @__PURE__ */
|
|
188
|
+
return i.jsx(r.View,{style:n==="header"?o.textingEntryRowHeader:o.textingEntryRowThread,children:/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,containerStyle:o.textingEntrySlot,style:o.vetEntry,onPress:e.onOpen,testID:"everfur-texting-entry",children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:o.vetEntryLabel,numberOfLines:1,children:e.label})})})}function vx(e){let t=e.color,n=ux-cx*2,l=e.slots.header;return r.StyleSheet.create({vetEntry:{minHeight:rx,justifyContent:"center",paddingHorizontal:12,borderRadius:e.radius.pill,backgroundColor:t.surfaceCream,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.controlEdge},vetEntryLabel:{...face(e,"bold"),color:t.brandInk,fontSize:e.type.size.caption},textingEntrySlot:{borderRadius:e.radius.pill,maxWidth:"100%"},textingEntryRowHeader:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:mx,paddingBottom:10,backgroundColor:l?.backgroundColor??t.surface},textingEntryRowThread:{flexDirection:"row",justifyContent:"flex-end",paddingHorizontal:mx,paddingTop:e.space.md,paddingBottom:e.space.xs},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:mx,paddingVertical:10,backgroundColor:t.surface,...Mg(l)},iconSlot:{borderRadius:nx/2},iconButton:{width:nx,height:nx,borderRadius:nx/2,alignItems:"center",justifyContent:"center"},unreadDot:{position:"absolute",top:ax,right:ax,width:ox,height:ox,borderRadius:ox,backgroundColor:t.danger,borderWidth:sx,borderColor:l?.backgroundColor??t.surface},leading:{flexShrink:0,alignItems:"flex-start"},trailing:{flexShrink:0,alignItems:"flex-end"},sideContent:{flexDirection:"row",alignItems:"center"},trailingContent:{flexDirection:"row",alignItems:"center",gap:e.space.sm},centre:{flexGrow:1,flexShrink:1,flexBasis:0,minWidth:0,marginHorizontal:bx,alignItems:"center",justifyContent:"center"},logoBar:{alignSelf:"stretch",alignItems:"center"},logo:{height:px,width:gx,maxWidth:"100%"},right:{alignItems:"flex-end"},avatarSlot:{borderRadius:ux/2},avatarWrap:{width:ux,height:ux,position:"relative"},placeholderDisc:{width:n,height:n,borderRadius:n/2,backgroundColor:t.brandSoft},addBadge:{position:"absolute",bottom:0,right:0,width:dx,height:dx,borderRadius:dx/2,borderWidth:fx,borderColor:t.mark,backgroundColor:t.surface,alignItems:"center",justifyContent:"center"}})}var xx=/* @__PURE__ */Object.freeze([
|
|
189
|
+
/* @__PURE__ */Object.freeze({key:"inaccurate",label:vf.feedbackReasonInaccurate,feedbackType:"wrong"}),
|
|
190
|
+
/* @__PURE__ */Object.freeze({key:"outdated",label:vf.feedbackReasonOutdated,feedbackType:"outdated"}),
|
|
191
|
+
/* @__PURE__ */Object.freeze({key:"unsafe",label:vf.feedbackReasonUnsafe,feedbackType:"dangerous"}),
|
|
192
|
+
/* @__PURE__ */Object.freeze({key:"unclear",label:vf.feedbackReasonUnclear,feedbackType:"unclear"}),
|
|
193
|
+
/* @__PURE__ */Object.freeze({key:"other",label:vf.feedbackReasonOther,feedbackType:"not_helpful"})]),wx=/* @__PURE__ */Object.freeze([
|
|
194
|
+
/* @__PURE__ */Object.freeze({sentiment:"up",label:vf.feedbackHelpful}),
|
|
195
|
+
/* @__PURE__ */Object.freeze({sentiment:"down",label:vf.feedbackNotHelpful})]);function kx(e){switch(e){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function Cx(e,t){if(e==="down"&&t!==null){let e=xx.find(e=>e.key===t);if(e!==void 0)return e.feedbackType}return kx(e)}var Sx=44,jx="rgba(17,17,17,0.55)",_x=26,Rx=36,Tx=4,Ix=20,zx=38,Px=18,Ex=12;function FeedbackReasons({visible:e,onSubmit:n,onSkip:l}){let o=useEverfurTheme(),s=t.useMemo(()=>Ox(o),[o]),a=hf(),[u,c]=t.useState(null),[d,f]=t.useState(""),[h,p]=t.useState(false),[g,m]=t.useState(false),b=()=>{c(null),f(""),p(false),m(false)},y=()=>{h||(b(),l())},v=async()=>{if(h)return;p(true),m(false);let e=d.trim();await n(u,e.length>0?e:null)?b():(p(false),m(true))};if(!e)return null;let x=[...d].length>gn;/* @__PURE__ */
|
|
196
|
+
return i.jsx(r.Modal,{visible:true,transparent:true,animationType:o.motion.reducedMotion?"none":"slide",onRequestClose:y,children:/* @__PURE__ */i.jsxs(r.KeyboardAvoidingView,{behavior:r.Platform.OS==="ios"?"padding":void 0,style:s.root,children:[
|
|
197
|
+
/* @__PURE__ */i.jsx(r.Pressable,{style:s.scrim,onPress:y,accessibilityRole:"button",accessibilityLabel:vf.feedbackSkipA11y}),
|
|
198
|
+
/* @__PURE__ */i.jsxs(r.View,{style:pf(s.sheet,a),accessibilityViewIsModal:true,accessibilityLiveRegion:"polite",children:[
|
|
199
|
+
/* @__PURE__ */i.jsx(r.View,{style:s.handle}),
|
|
200
|
+
/* @__PURE__ */i.jsxs(r.View,{style:s.header,children:[
|
|
201
|
+
/* @__PURE__ */i.jsx(r.View,{style:s.iconBadge,children:/* @__PURE__ */i.jsx(ThumbGlyph,{size:Px,color:o.color.brandInk,active:false,rotate:"180deg"})}),
|
|
202
|
+
/* @__PURE__ */i.jsxs(r.View,{style:s.headerText,children:[
|
|
203
|
+
/* @__PURE__ */i.jsx(Text,{tier:"heading",style:s.title,accessibilityRole:"header",children:vf.feedbackTitle}),
|
|
204
|
+
/* @__PURE__ */i.jsx(Text,{style:s.subtitle,children:vf.feedbackSubtitle})]})]}),
|
|
205
|
+
/* @__PURE__ */i.jsx(r.View,{style:s.options,children:xx.map(e=>{let t=u===e.key;/* @__PURE__ */
|
|
206
|
+
return i.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,accessibilityState:{selected:t},style:[s.option,t?s.optionSelected:null],onPress:()=>c(t=>t===e.key?null:e.key),children:[
|
|
207
|
+
/* @__PURE__ */i.jsx(Text,{style:[s.optionLabel,t?s.optionLabelSelected:null],children:e.label}),
|
|
208
|
+
/* @__PURE__ */i.jsx(r.View,{style:[s.radio,t?s.radioSelected:null],children:t?/* @__PURE__ */i.jsx(CheckGlyph,{size:Ex,color:o.color.surface,strokeWidth:2}):null})]},e.key)})}),
|
|
209
|
+
/* @__PURE__ */i.jsxs(r.View,{style:s.inputWrap,children:[
|
|
210
|
+
/* @__PURE__ */i.jsx(Bd,{style:s.input,placeholder:vf.feedbackNotesPlaceholder,placeholderTextColor:o.color.text.placeholder,accessibilityLabel:vf.feedbackNotesPlaceholder,value:d,onChangeText:f,multiline:true,editable:!h}),d.length>0?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:[s.counter,x?s.counterOver:null],children:`${[...d].length}/${gn}`}):null]}),g?/* @__PURE__ */i.jsx(Text,{style:s.failed,accessibilityRole:"alert",children:vf.feedbackFailed}):null,
|
|
211
|
+
/* @__PURE__ */i.jsxs(r.View,{style:s.actions,children:[
|
|
212
|
+
/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:vf.feedbackSubmit,accessibilityState:{busy:h,disabled:h||x},disabled:h||x,style:[s.submit,h||x?s.submitDisabled:null],onPress:()=>{v()},children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:s.submitLabel,children:vf.feedbackSubmit})}),
|
|
213
|
+
/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:vf.feedbackSkipA11y,hitSlop:8,onPress:y,style:s.skip,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:s.skipLabel,children:vf.feedbackSkip})})]})]})]})})}function Ox(e){let t=e.color,n=e.type,l=e.radius,i=e.slots,o=Dg(i.dialog);return r.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{...om,backgroundColor:jx},sheet:{backgroundColor:t.surface,borderTopLeftRadius:_x,borderTopRightRadius:_x,paddingHorizontal:22,paddingTop:12,paddingBottom:34,gap:14,...Uv(i.dialog)},handle:{alignSelf:"center",width:Rx,height:Tx,borderRadius:Tx/2,backgroundColor:t.brandBorder,marginBottom:2},header:{flexDirection:"row",alignItems:"center",gap:12},iconBadge:{width:zx,height:zx,borderRadius:zx/2,alignItems:"center",justifyContent:"center",backgroundColor:t.brandSoft},headerText:{flex:1,gap:2},title:{...headingFace(e,"bold"),fontSize:20,lineHeight:28,color:t.text.primary,letterSpacing:n.letterSpacing.tight,...o},subtitle:{...face(e,"regular"),fontSize:n.size.body,lineHeight:n.size.body*n.lineHeight.relaxed,color:t.text.muted,...o},options:{gap:8},option:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:14,paddingVertical:13,borderRadius:l.md,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.controlEdge,backgroundColor:t.surface,...Mg(i.chip,r.StyleSheet.hairlineWidth)},optionSelected:{borderColor:t.brandInk,backgroundColor:t.brandSoft},optionLabel:{...face(e,"medium"),fontSize:n.size.body,color:t.text.primary,...Dg(i.chip)},optionLabelSelected:{color:t.brandInk},radio:{width:Ix,height:Ix,borderRadius:Ix/2,borderWidth:2,borderColor:t.brandBorderStrong,alignItems:"center",justifyContent:"center"},radioSelected:{borderColor:t.brandInk,backgroundColor:t.brandInk},inputWrap:{gap:4},input:{minHeight:72,maxHeight:132,borderRadius:l.md,borderWidth:1,borderColor:t.brandBorderStrong,paddingHorizontal:14,paddingTop:12,paddingBottom:12,...face(e,"regular"),fontSize:n.size.body,color:t.text.primary,textAlignVertical:"top",...Mg(i.input,1),...Dg(i.input)},counter:{...face(e,"mono"),alignSelf:"flex-end",fontSize:n.size.caption,letterSpacing:.3,color:t.text.placeholder},counterOver:{color:t.danger},failed:{...face(e,"regular"),fontSize:n.size.caption,lineHeight:n.size.caption*n.lineHeight.normal,color:t.danger},actions:{gap:10,alignItems:"center"},submit:{alignSelf:"stretch",minHeight:Sx,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.xl,borderRadius:l.pill,backgroundColor:t.brand,...Mg(i.primaryButton)},submitDisabled:{opacity:.6},submitLabel:{...face(e,"medium"),fontSize:n.size.body,color:t.onPrimary,...Dg(i.primaryButton)},skip:{minHeight:Sx,alignItems:"center",justifyContent:"center",paddingHorizontal:e.space.lg},skipLabel:{...face(e,"medium"),fontSize:n.size.body,color:t.text.muted}})}var Ax=/* @__PURE__ */Symbol.for("everfur.sdk.rn.askHome");function Mx(){let e=globalThis,r=e[Ax];if(r!==void 0)return r;let n={factory:t.createContext(null),home:t.createContext(null)};return e[Ax]=n,n}var Fx=Mx().factory,Dx=Mx().home;function Lx(){return t.useContext(Fx)}function Bx(){return t.useContext(Dx)?.kit??null}function Vx(){return t.useContext(Dx)}var Hx=15,Ux=8;function HistoryBar({bar:e,history:n,empty:l,unread:o,extra:s}){let a=useEverfurTheme(),u=Bx(),c=my(),d=t.useMemo(()=>c!==null?{...qx(a),...c.paint.history}:u!==null?Wx(a,u):qx(a),[a,u,c]),f=c===null&&n.cursor===null?n.rows.length:0,h=c!==null||u!==null,p=t=>{let n=e.renderIcon;if(n!==void 0)/* @__PURE__ */return i.jsx(HostRender,{render:()=>n(t),fallback:null});if(!h)return null;let l=String(r.StyleSheet.flatten(d.label).color??a.color.linkInk);return c!==null?/* @__PURE__ */i.jsx(c.paint.Icon,{name:t==="history"?"clock":"pen",size:20,color:l}):t==="history"?/* @__PURE__ */i.jsx(HistoryGlyph,{size:$x,color:l,strokeWidth:1.8}):/* @__PURE__ */i.jsx(EditGlyph,{size:$x,color:l,strokeWidth:1.8})};/* @__PURE__ */
|
|
214
|
+
return i.jsxs(r.View,{style:d.bar,testID:"everfur-history-bar",children:[
|
|
215
|
+
/* @__PURE__ */i.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:f>0?`${e.chats} ${f}`:e.chats,accessibilityState:{expanded:n.open},onPress:n.open?n.close:n.show,style:d.control,hitSlop:h?Nx:void 0,children:[p("history"),
|
|
216
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:d.label,children:e.chats}),f>0?/* @__PURE__ */i.jsx(r.View,{style:d.count,children:/* @__PURE__ */i.jsx(Text,{tier:"badge",style:d.countText,children:String(f)})}):null,o?/* @__PURE__ */i.jsx(r.View,{style:d.dot,testID:"everfur-chat-history-bar-unread"}):null]}),e.extra??null,s??null,
|
|
217
|
+
/* @__PURE__ */i.jsx(r.View,{style:d.spacer}),l?null:/* @__PURE__ */i.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:e.newChat,onPress:n.newConversation,style:d.control,hitSlop:h?Nx:void 0,children:[p("edit"),
|
|
218
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:d.label,children:e.newChat})]})]})}var Nx=4,$x=18;function Wx(e,t){return{...qx(e),bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:e.space.sm},control:t.view(".thread__hist"),label:t.text(".thread__hist"),count:t.view(".thread__count"),countText:t.text(".thread__count")}}function qx(e){let t=e.color,n=e.space;return r.StyleSheet.create({bar:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:n.sm,paddingHorizontal:n.lg,paddingVertical:n.xs},control:{flexDirection:"row",alignItems:"center",gap:6,minHeight:zm},label:{...face(e,"bold"),fontSize:Hx,color:t.brandInk},count:{minWidth:22,paddingHorizontal:7,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,alignItems:"center"},countText:{...face(e,"bold"),fontSize:e.type.size.caption,color:t.text.primary},dot:{width:Ux,height:Ux,borderRadius:Ux/2,backgroundColor:t.danger},spacer:{flexGrow:1}})}var Gx=.88,Kx=420,Yx=58,Qx="rgba(17,17,17,0.28)",Zx=.15,Xx=14,Jx=12,ew=44,tw=16,rw=14,nw=12,lw=14,iw=8,ow=2,sw=.5,aw=dg(tg.standard);function uw(e){return Math.min(Math.round(e*Gx),Kx)}function HistoryDrawer({chat:e,history:r}){let[n,l]=t.useState(r.open),o=t.useCallback(()=>l(false),[]);return r.open&&!n&&l(true),n?/* @__PURE__ */i.jsx(DrawerModal,{chat:e,history:r,onHidden:o}):null}function DrawerModal({chat:e,history:l,onHidden:o}){let s=useEverfurTheme(),a=t.useMemo(()=>cw(s),[s]),u=sg(),c=n.useSafeAreaInsets(),{width:d}=r.useWindowDimensions(),f=uw(d),h=l.open,p=t.useRef(null);p.current===null&&(p.current=new r.Animated.Value(u.drawerMs<=0&&h?1:0));let g=p.current;t.useEffect(()=>{if(!h&&u.drawerMs<=0){o();return}let e=r.Animated.timing(g,{toValue:h?1:0,duration:u.drawerMs,easing:aw,useNativeDriver:true});return e.start(({finished:e})=>{e&&!h&&o()}),()=>e.stop()},[h,g,u.drawerMs,o]);let m=g.interpolate({inputRange:[0,1],outputRange:[-f,0]}),b=l.filtered,y=l.rows.length===0,v=l.cursor===null&&!l.loading&&l.error===null,x=y&&l.loading?/* @__PURE__ */i.jsxs(r.View,{style:a.emptyCard,accessibilityLabel:wp.loading,accessibilityState:{busy:true},children:[
|
|
219
|
+
/* @__PURE__ */i.jsx(r.ActivityIndicator,{color:a.emptyTitle.color}),
|
|
220
|
+
/* @__PURE__ */i.jsx(Text,{style:a.emptyBody,children:wp.loading})]}):y&&l.error!==null?/* @__PURE__ */i.jsxs(r.View,{style:a.emptyCard,children:[
|
|
221
|
+
/* @__PURE__ */i.jsx(Text,{style:a.emptyTitle,accessibilityRole:"alert",children:wp.loadFailed}),
|
|
222
|
+
/* @__PURE__ */i.jsx(Text,{style:a.emptyBody,children:l.error}),
|
|
223
|
+
/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:wp.retry,containerStyle:a.retrySlot,style:a.retryButton,onPress:()=>{l.load()},children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:a.retryText,children:wp.retry})})]}):l.emptyKind==="empty"?/* @__PURE__ */i.jsxs(r.View,{style:a.emptyCard,children:[
|
|
224
|
+
/* @__PURE__ */i.jsx(Text,{style:a.emptyTitle,children:wp.empty}),
|
|
225
|
+
/* @__PURE__ */i.jsx(Text,{style:a.emptyBody,children:wp.emptyBody})]}):
|
|
226
|
+
/* @__PURE__ */i.jsx(Text,{style:a.noMatch,children:wp.noMatch}),w=!l.searching&&l.loadingMore?/* @__PURE__ */i.jsx(r.View,{style:a.loadMoreFooter,children:/* @__PURE__ */i.jsx(Text,{style:a.loadMoreLabel,children:wp.loadingMore})}):null;/* @__PURE__ */
|
|
227
|
+
return i.jsx(r.Modal,{visible:true,transparent:true,animationType:"none",onRequestClose:l.close,children:/* @__PURE__ */i.jsxs(r.View,{style:a.root,children:[
|
|
228
|
+
/* @__PURE__ */i.jsx(r.Pressable,{style:om,onPress:l.close,accessibilityRole:"button",accessibilityLabel:wp.closeA11y,children:/* @__PURE__ */i.jsx(r.Animated.View,{style:[a.backdrop,{opacity:g}]})}),
|
|
229
|
+
/* @__PURE__ */i.jsx(r.Animated.View,{style:[a.panel,{width:f,paddingTop:Math.max(Yx,c.top+s.space.md),transform:[{translateX:m}]}],accessibilityViewIsModal:true,children:/* @__PURE__ */i.jsxs(r.KeyboardAvoidingView,{style:a.keyboardAvoider,behavior:r.Platform.OS==="ios"?"padding":"height",children:[
|
|
230
|
+
/* @__PURE__ */i.jsxs(r.View,{style:a.header,children:[
|
|
231
|
+
/* @__PURE__ */i.jsx(Text,{tier:"heading",style:a.heading,accessibilityRole:"header",children:wp.heading}),
|
|
232
|
+
/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:wp.newChat,style:a.newChat,onPress:l.newConversation,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:a.newChatLabel,children:wp.newChat})}),
|
|
233
|
+
/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:wp.close,hitSlop:0,style:a.closeButton,onPress:l.close,children:/* @__PURE__ */i.jsx(CloseGlyph,{size:tw,color:s.color.text.muted,strokeWidth:1.75})})]}),
|
|
234
|
+
/* @__PURE__ */i.jsxs(r.View,{style:a.searchPill,children:[
|
|
235
|
+
/* @__PURE__ */i.jsx(SearchGlyph,{size:lw,color:s.color.text.muted,strokeWidth:1.5}),
|
|
236
|
+
/* @__PURE__ */i.jsx(Bd,{value:l.query,onChangeText:e=>l.setQuery(e.replace(/^\s+/,"")),style:a.searchInput,placeholder:wp.searchPlaceholder,placeholderTextColor:s.color.text.placeholder,accessibilityLabel:wp.search,autoCorrect:false,autoCapitalize:"none",returnKeyType:"search"})]}),
|
|
237
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:a.countLabel,children:jp(l.rows.length,v)}),l.error!==null&&!y?/* @__PURE__ */i.jsx(r.View,{style:a.errorCard,children:/* @__PURE__ */i.jsx(Text,{style:a.errorText,accessibilityRole:"alert",children:l.error})}):null,
|
|
238
|
+
/* @__PURE__ */i.jsx(r.FlatList,{data:b,keyExtractor:e=>e.id,renderItem:({item:t})=>/* @__PURE__ */i.jsx(Row,{row:t,active:t.id===e.conversationId,disabled:l.loading,styles:a,onPress:()=>{l.resume(t.id)}}),contentContainerStyle:b.length===0?a.listEmpty:a.list,keyboardShouldPersistTaps:"handled",ListEmptyComponent:x,ListFooterComponent:w,onEndReached:l.loadMore,onEndReachedThreshold:sw})]})})]})})}function Row({row:e,active:t,disabled:n,styles:l,onPress:o}){let s=e.unreadCount!==null&&e.unreadCount>0,a=Sp(e);/* @__PURE__ */
|
|
239
|
+
return i.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:_p(e),accessibilityState:{selected:t,disabled:n},disabled:n,style:[l.item,t?l.itemActive:null],onPress:o,children:[
|
|
240
|
+
/* @__PURE__ */i.jsxs(r.View,{style:l.itemRow,children:[
|
|
241
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:l.itemTitle,numberOfLines:1,children:kp(e.title)}),s?/* @__PURE__ */i.jsx(r.View,{style:l.unreadDot}):null]}),a!==null?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:l.itemMeta,numberOfLines:1,children:a}):null]})}function cw(e){let t=e.color,n=e.space,l=e.type,i=e.slots,o=t.text.primary,s=Dg(i.card);return r.StyleSheet.create({root:{flex:1},backdrop:{flex:1,backgroundColor:Qx},panel:{position:"absolute",left:0,top:0,bottom:0,backgroundColor:t.surface,paddingHorizontal:n.lg,borderRightWidth:r.StyleSheet.hairlineWidth,borderRightColor:t.borderRingCream,gap:n.md,...Nv(i.dialog,r.StyleSheet.hairlineWidth)},keyboardAvoider:{flex:1,gap:n.md},header:{flexDirection:"row",alignItems:"center",gap:n.sm},heading:{...headingFace(e,"bold"),flex:1,fontSize:l.size.subtitle,color:o,...Dg(i.dialog)},newChat:{minHeight:ew,justifyContent:"center",paddingHorizontal:n.xs},newChatLabel:{...face(e,"bold"),fontSize:Xx,color:t.brandInk},closeButton:{width:ew,height:ew,alignItems:"center",justifyContent:"center"},searchPill:{flexDirection:"row",alignItems:"center",gap:n.sm,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,paddingHorizontal:n.md+ow,paddingVertical:n.sm+ow,borderWidth:1,borderColor:t.borderRingCream,...Mg(i.input,1)},searchInput:{...face(e,"regular"),flex:1,fontSize:l.size.bodyTight,color:t.text.primary,padding:0,...Dg(i.input)},countLabel:{...face(e,"mono"),fontSize:Jx,color:t.text.muted},list:{gap:n.xs,paddingBottom:n.xl},listEmpty:{flexGrow:1},item:{paddingVertical:n.sm+ow,paddingHorizontal:n.sm,borderRadius:e.radius.md,gap:ow},itemActive:{backgroundColor:Hi(t.highlight,Zx)??t.surfaceSubtle},itemRow:{flexDirection:"row",alignItems:"center",gap:n.sm},itemTitle:{...face(e,"bold"),flex:1,fontSize:l.size.bodyTight,color:o},itemMeta:{...face(e,"regular"),fontSize:l.size.caption,color:t.text.muted},unreadDot:{width:iw,height:iw,borderRadius:iw/2,backgroundColor:t.danger},errorCard:{borderRadius:nw,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.danger,backgroundColor:t.surface,padding:n.md},errorText:{...face(e,"regular"),fontSize:l.size.caption,color:t.danger},emptyCard:{borderRadius:rw,padding:n.md+ow,gap:n.xs+ow,backgroundColor:t.surfaceSubtle,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.borderRingCream,...Mg(i.card,r.StyleSheet.hairlineWidth)},emptyTitle:{...headingFace(e,"bold"),fontSize:l.size.bodyTight,color:o,...s},emptyBody:{...face(e,"regular"),fontSize:l.size.caption,color:t.text.secondary,...s},noMatch:{...face(e,"regular"),fontSize:l.size.bodyTight,color:t.text.muted,paddingVertical:n.sm},retrySlot:{marginTop:n.sm,alignSelf:"flex-start"},retryButton:{borderRadius:e.radius.pill,paddingHorizontal:n.md+ow,paddingVertical:n.sm,borderWidth:1,borderColor:t.brandInk,...Mg(i.primaryButton)},retryText:{...face(e,"bold"),fontSize:l.size.caption,color:t.brandInk,...Dg(i.primaryButton)},loadMoreFooter:{paddingVertical:n.md+ow,alignItems:"center"},loadMoreLabel:{...face(e,"regular"),fontSize:l.size.caption,color:t.text.muted}})}function dw(e,t=/* @__PURE__ */new Date,r){let n=new Date(e);if(Number.isNaN(n.getTime()))return null;let l=new Date(t);l.setHours(0,0,0,0);let i=new Date(n);i.setHours(0,0,0,0);let o=Math.round((l.getTime()-i.getTime())/864e5);if(o===0||o===1)try{let e=new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(-o,"day");return e.charAt(0).toLocaleUpperCase(r)+e.slice(1)}catch{}return n.toLocaleDateString(r,{month:"short",day:"numeric"})}function fw(e,t){let r=new Date(e);return Number.isNaN(r.getTime())?null:r.toLocaleTimeString(t,{hour:"numeric",minute:"2-digit"})}function hw(e,t=/* @__PURE__ */new Date){let r=[];for(let n of e){let e=dw(n.updatedAt,t)??"",l=r[r.length-1];l!==void 0&&l.day===e?l.rows.push(n):r.push({day:e,rows:[n]})}return r}var pw="rgba(38,37,35,0.38)",gw=28,mw=40,bw=5,yw=11,vw=10.5,xw=36,ww=11,kw=14,Cw=15,Sw=13.5,jw=48,_w=2,Rw=1.3,Tw=.12,Iw=16,zw=8,Pw="80%";function Ew(e,t,r){let n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */i.jsx(HostRender,{render:()=>n(t),fallback:r})}function HistorySheet({chat:e,history:l,sheet:o}){let s=useEverfurTheme(),a=t.useMemo(()=>Ow(s),[s]),u=n.useSafeAreaInsets(),c=t.useMemo(()=>hw(l.rows),[l.rows]),d=hf();if(!l.open)return null;let f=s.color,h=o?.title?.trim(),p=h!==void 0&&h!==""?h:wp.heading;/* @__PURE__ */
|
|
242
|
+
return i.jsx(r.Modal,{visible:true,transparent:true,animationType:"slide",onRequestClose:l.close,children:/* @__PURE__ */i.jsxs(r.View,{style:a.root,children:[
|
|
243
|
+
/* @__PURE__ */i.jsx(r.Pressable,{style:[om,a.scrim],onPress:l.close,accessibilityRole:"button",accessibilityLabel:wp.closeA11y}),
|
|
244
|
+
/* @__PURE__ */i.jsxs(r.View,{style:pf([a.sheet,{paddingBottom:Math.max(40,u.bottom+s.space.lg)}],d),accessibilityViewIsModal:true,testID:"everfur-history-sheet",children:[
|
|
245
|
+
/* @__PURE__ */i.jsx(r.View,{style:a.grab}),
|
|
246
|
+
/* @__PURE__ */i.jsxs(r.View,{style:a.top,children:[
|
|
247
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:a.kicker,accessibilityRole:"header",children:p}),
|
|
248
|
+
/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:wp.closeA11y,onPress:l.close,style:a.close,children:Ew(o,"close",/* @__PURE__ */i.jsx(CloseGlyph,{size:22,color:f.text.primary,strokeWidth:2}))})]}),
|
|
249
|
+
/* @__PURE__ */i.jsxs(r.ScrollView,{style:a.scroll,contentContainerStyle:a.scrollContent,keyboardShouldPersistTaps:"handled",children:[l.loading&&l.rows.length===0?/* @__PURE__ */i.jsxs(r.View,{style:a.state,accessibilityLabel:wp.loading,accessibilityState:{busy:true},children:[
|
|
250
|
+
/* @__PURE__ */i.jsx(r.ActivityIndicator,{color:f.brandInk}),
|
|
251
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:a.mono,children:wp.loading})]}):null,l.error!==null?/* @__PURE__ */i.jsxs(r.View,{style:a.state,children:[
|
|
252
|
+
/* @__PURE__ */i.jsx(Text,{style:a.stateText,accessibilityRole:"alert",children:wp.loadFailed}),
|
|
253
|
+
/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:wp.retry,onPress:()=>{l.load()},style:a.link,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:a.linkText,children:wp.retry})})]}):null,!l.loading&&l.error===null&&l.rows.length===0?/* @__PURE__ */i.jsx(Text,{style:[a.stateText,a.state],children:wp.empty}):null,c.map((n,s)=>/* @__PURE__ */i.jsxs(t.Fragment,{children:[n.day?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:[a.mono,a.day,s===0?a.dayFirst:null],children:n.day}):null,n.rows.map(t=>{let n=t.id===e.conversationId,s=t.unreadCount!==null&&t.unreadCount>0,u=fw(t.updatedAt);/* @__PURE__ */
|
|
254
|
+
return i.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:_p(t),accessibilityState:{selected:n},onPress:()=>{l.resume(t.id)},style:[a.row,n?a.rowCurrent:null],children:[
|
|
255
|
+
/* @__PURE__ */i.jsx(r.View,{style:a.icon,children:Ew(o,"chat",/* @__PURE__ */i.jsx(ChatBubbleGlyph,{size:19,color:f.linkInk,strokeWidth:1.75}))}),
|
|
256
|
+
/* @__PURE__ */i.jsxs(r.View,{style:a.rowWords,children:[
|
|
257
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:a.rowTitle,numberOfLines:1,children:kp(t.title)}),t.preview!==void 0?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:a.preview,numberOfLines:1,children:t.preview}):null]}),
|
|
258
|
+
/* @__PURE__ */i.jsxs(r.View,{style:a.rowEnd,children:[u!==null?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:[a.mono,a.time,s?a.timeUnread:null],children:u}):null,s?/* @__PURE__ */i.jsx(r.View,{style:a.unreadDot,testID:`everfur-history-sheet-unread-${String(t.id)}`}):null]})]},String(t.id))})]},n.day)),l.cursor!==null&&!l.loadingMore?/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:wp.more,onPress:l.loadMore,style:a.link,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:a.linkText,children:wp.more})}):null]}),
|
|
259
|
+
/* @__PURE__ */i.jsxs(r.Pressable,{accessibilityRole:"button",accessibilityLabel:wp.newChat,onPress:l.newConversation,style:a.newChat,children:[Ew(o,"edit",/* @__PURE__ */i.jsx(EditGlyph,{size:18,color:s.slots.primaryButton?.textColor??f.onPrimary,strokeWidth:1.75})),
|
|
260
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:a.newChatText,children:wp.newChat})]})]})]})})}function Ow(e){let t=e.color,n=e.space,l={...face(e,"mono"),fontSize:vw,letterSpacing:vw*.06,textTransform:"uppercase",color:t.text.muted};return r.StyleSheet.create({root:{flex:1,justifyContent:"flex-end"},scrim:{backgroundColor:pw},sheet:{maxHeight:Pw,backgroundColor:t.surface,borderTopLeftRadius:gw,borderTopRightRadius:gw,paddingTop:10,paddingHorizontal:20},grab:{width:mw,height:bw,borderRadius:3,backgroundColor:t.borderRingCream,alignSelf:"center",marginBottom:10},top:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},kicker:{...l,fontSize:yw,letterSpacing:yw*.08,flexShrink:1},close:{width:zm,height:zm,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:zm/2},scroll:{flexGrow:0},scrollContent:{paddingBottom:n.xs},mono:l,day:{marginTop:n.lg,marginBottom:n.xs},dayFirst:{marginTop:_w},state:{marginVertical:n.md,gap:n.sm,alignItems:"flex-start"},stateText:{...face(e,"regular"),fontSize:e.type.size.body,color:t.text.primary},link:{minHeight:zm,justifyContent:"center"},linkText:{...face(e,"bold"),fontSize:e.type.size.body,color:t.brandInk},row:{flexDirection:"row",alignItems:"center",gap:n.md,paddingVertical:10,paddingHorizontal:n.sm,borderRadius:kw,minHeight:zm},rowCurrent:{backgroundColor:t.surfaceSubtle},icon:{width:xw,height:xw,borderRadius:ww,backgroundColor:Hi(t.linkInk,Tw)??t.surfaceSubtle,alignItems:"center",justifyContent:"center"},rowWords:{flex:1,minWidth:0},rowTitle:{...face(e,"bold"),fontSize:Cw,lineHeight:Cw*Rw,color:t.text.primary},preview:{...face(e,"regular"),fontSize:Sw,color:t.text.muted,marginTop:2},rowEnd:{alignSelf:"flex-start",alignItems:"flex-end",gap:6},time:{marginTop:3,letterSpacing:vw*.04,textTransform:"none"},timeUnread:{...face(e,"monoBold"),color:t.text.primary},unreadDot:{width:zw,height:zw,borderRadius:zw/2,backgroundColor:t.danger},newChat:{marginTop:n.lg,minHeight:jw,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:n.sm,borderRadius:e.radius.pill,backgroundColor:t.primary,...Mg(e.slots.primaryButton)},newChatText:{...face(e,"bold"),fontSize:Iw,color:t.onPrimary,...Dg(e.slots.primaryButton)}})}var Aw="Close",Mw=/* @__PURE__ */Object.freeze({action:e=>e.possessive===null?null:`See ${e.possessive} Health Plan`,ask:"What does it mean?",askPrompt:(e,t)=>e.risk?.lead?`${e.risk.lead} ${t}`:`${e.title}: ${t}`,close:e=>e.possessive===null?null:`Close ${e.possessive} focus`,resultsKicker:e=>e.possessive===null?null:`${Fw(e.possessive)} results`,resultsClose:e=>e.possessive===null?null:`Close ${e.possessive} results`,resultsTopRisk:"Top risk"});function Fw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function healthPlanPossessive(e){let t=typeof e.sex=="string"?e.sex.trim().toLowerCase():null;if(t==="female")return"her";if(t==="male")return"his";let r=typeof e.name=="string"?e.name.trim():"";return r!==""?`${r}'s`:null}function healthPlanTopCard(e,t={}){let r=e?.page?.focus;if(e===null||r===void 0||r.title.trim()===""||r.kicker.trim()==="")return;let n={...Mw,...t.copy},l={pet:e.pet,possessive:healthPlanPossessive(e.pet)},i=r.sources?.find(e=>e.label.trim()!=="")?.label,o=t.onOpenPlan,s=o===void 0?null:n.action(l),a=n.close(l),u=n.ask.trim(),c=t.results!==void 0&&r.report!==void 0?t.results:void 0;if(c!==void 0){let e=n.resultsKicker(l)?.trim()||r.kicker,a=n.resultsClose(l),d=c.onTopRisk??o,f={key:"top-risk",label:n.resultsTopRisk,title:r.title,...r.risk?.lead?{line:r.risk.lead}:{},tone:"risk",...d===void 0?{}:{onPress:d}};return{kicker:e,...i===void 0?{}:{badge:i},title:r.title,results:[f,...c.rows??[]],...s===null||s.trim()===""||o===void 0?{}:{action:{label:s,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:a===null||a.trim()===""?Aw:a,pill:e,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}return{kicker:r.kicker,...i===void 0?{}:{badge:i},title:r.title,...r.risk?.lead?{lead:r.risk.lead}:{},...r.risk?.body?{body:r.risk.body}:{},...s===null||s.trim()===""||o===void 0?{}:{action:{label:s,onPress:o}},...u===""?{}:{ask:{label:u,prompt:n.askPrompt(r,u)}},closeLabel:a===null||a.trim()===""?Aw:a,pill:r.kicker,...t.renderIcon===void 0?{}:{renderIcon:t.renderIcon}}}function Dw(e){let t=face(e,"medium");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"600"}}function Lw(e){let t=face(e,"bold");return t.fontWeight===void 0?t:{fontFamily:t.fontFamily,fontWeight:"800"}}var Bw=20,Vw=14,Hw=16,Uw=18,Nw=22,$w=15,Ww=12,qw=24,Gw=15,Kw=14.5,Yw=21,Qw=14.5,Zw=18,Xw=9,Jw=36,ek=14,tk=15,rk=8,nk=40;function TopCard({card:e,open:n,onOpenChange:l,ask:o}){let s=useEverfurTheme(),a=Bx(),u=t.useMemo(()=>a!==null?ik(a):sk(s),[s,a]),c=t.useMemo(()=>Mg(s.slots.card),[s.slots.card]);if(!n)return null;let d=e.closeLabel===void 0?null:e.closeLabel.trim()!==""?e.closeLabel:vf.close,f=e.action,h=e.ask,p=/* @__PURE__ */i.jsx(CloseGlyph,{size:a!==null?HOME_CLOSE_GLYPH(a):Zw,color:a!==null?String(a.text(".ask-focus__x").color):s.color.text.primary,strokeWidth:2});/* @__PURE__ */
|
|
261
|
+
return i.jsxs(r.View,{style:[u.card,c],testID:"everfur-top-card",children:[
|
|
262
|
+
/* @__PURE__ */i.jsxs(r.View,{style:u.kickerRow,children:[
|
|
263
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:u.kicker,children:e.kicker}),e.badge!==void 0?/* @__PURE__ */i.jsx(r.View,{style:u.badge,children:/* @__PURE__ */i.jsx(Text,{tier:"compact",style:u.badgeText,numberOfLines:1,children:e.badge})}):null,d!==null?/* @__PURE__ */i.jsx(r.Pressable,{onPress:()=>l(false),accessibilityRole:"button",accessibilityLabel:d,style:u.close,hitSlop:a!==null?lk:void 0,testID:"everfur-top-card-close",children:e.renderIcon!==void 0?/* @__PURE__ */i.jsx(HostRender,{render:()=>e.renderIcon?.("close"),fallback:p}):p}):null]}),
|
|
264
|
+
/* @__PURE__ */i.jsx(Text,{tier:"heading",style:u.title,accessibilityRole:"header",children:e.title}),e.lead!==void 0||e.body!==void 0?/* @__PURE__ */i.jsxs(r.View,{style:u.finding,children:[
|
|
265
|
+
/* @__PURE__ */i.jsx(r.View,{style:u.dot}),
|
|
266
|
+
/* @__PURE__ */i.jsxs(Text,{style:u.findingText,children:[e.lead!==void 0?/* @__PURE__ */i.jsx(Text,{style:u.lead,children:e.lead}):null,e.lead!==void 0&&e.body!==void 0?" ":null,e.body??null]})]}):null,f!==void 0||h!==void 0?/* @__PURE__ */i.jsxs(r.View,{style:u.actions,children:[f!==void 0?/* @__PURE__ */i.jsx(r.Pressable,{onPress:()=>{ch(f.onPress)},accessibilityRole:"button",accessibilityLabel:f.label,style:u.action,hitSlop:a!==null?lk:void 0,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:u.actionText,children:f.label})}):null,h!==void 0?/* @__PURE__ */i.jsx(r.Pressable,{onPress:()=>o(h.prompt),accessibilityRole:"button",accessibilityLabel:h.label,style:u.ask,hitSlop:a!==null?lk:void 0,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:u.askText,children:h.label})}):null]}):null]})}function TopCardPill({card:e,open:n,onOpenChange:l}){let o=useEverfurTheme(),s=Bx(),a=t.useMemo(()=>s!==null?ik(s):sk(o),[o,s]);if(n||e.closeLabel===void 0)return null;let u=e.pill??e.kicker;/* @__PURE__ */
|
|
267
|
+
return i.jsxs(r.Pressable,{onPress:()=>l(true),accessibilityRole:"button",accessibilityLabel:u,accessibilityState:{expanded:false},style:a.pill,hitSlop:s!==null?lk:void 0,testID:"everfur-top-card-pill",children:[
|
|
268
|
+
/* @__PURE__ */i.jsx(r.View,{style:a.pillDot}),
|
|
269
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:a.pillText,numberOfLines:1,children:u})]})}var lk=4,HOME_CLOSE_GLYPH=e=>{let t=e.icon(".ask-focus__x svg").width;return typeof t=="number"?t:Zw};function ik(e){let t=e.text(".hp-need__s",".ask-focus .hp-need__s"),r=typeof t.lineHeight=="number"?t.lineHeight:21,n=e.view(".dot",".dot--risk"),l=typeof n.height=="number"?n.height:Xw;return{card:e.view(".ask-focus"),kickerRow:e.view(".hp-need__k"),kicker:[e.text(".hp-need__k"),{flexShrink:1}],badge:[e.view(".hp-srcs"),e.view(".hp-src",".hp-src--dna"),{flexShrink:1}],badgeText:e.text(".hp-src",".hp-src--dna"),close:e.view(".ask-focus__x"),title:[e.view(".ask-focus h3"),e.text(".ask-focus h3")],finding:[e.view(".hp-need__s"),{alignItems:"flex-start"}],dot:[e.col(".hp-need__s",0),n,{marginTop:Math.round((r-l)/2)}],findingText:[e.col(".hp-need__s",1),t],lead:(({fontFamily:e,fontWeight:t,color:r})=>({fontFamily:e,fontWeight:t,color:r}))(e.strong(".hp-need__s b")),actions:e.view(".ask-focus__acts"),action:[e.view(".emb-btn",".emb-btn--sm"),{maxWidth:"100%"}],actionText:e.text(".emb-btn",".emb-btn--sm"),ask:[e.view(".ask-focus__q"),{justifyContent:"center",maxWidth:"100%"}],askText:e.text(".ask-focus__q"),pill:[e.view(".ask-focus-pill"),{maxWidth:"100%"}],pillDot:e.view(".ask-focus-pill i"),pillText:[e.text(".ask-focus-pill"),{flexShrink:1}]}}function sk(e){let t=e.color,n=e.space;return r.StyleSheet.create({card:{paddingTop:Vw,paddingHorizontal:Hw,paddingBottom:Hw,borderRadius:Bw,backgroundColor:t.surface,borderWidth:1,borderColor:t.borderRingCream,alignSelf:"stretch"},kickerRow:{flexDirection:"row",alignItems:"center",gap:n.sm,minHeight:zm-8},kicker:{...Lw(e),fontSize:$w,color:t.text.primary,flexShrink:1},badge:{marginLeft:"auto",minHeight:qw,justifyContent:"center",paddingHorizontal:9,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,flexShrink:1},badgeText:{...face(e,"bold"),fontSize:Ww,color:t.text.secondary},close:{width:zm,height:zm,marginVertical:-4,marginRight:-10,alignItems:"center",justifyContent:"center",borderRadius:zm/2},title:{...Lw(e),fontSize:Uw,lineHeight:Nw,color:t.text.primary,marginTop:n.xs},finding:{flexDirection:"row",gap:n.sm,marginTop:n.xs+2},dot:{width:Xw,height:Xw,borderRadius:Xw/2,marginTop:7,backgroundColor:t.danger},findingText:{...face(e,"regular"),flex:1,fontSize:Kw,lineHeight:Yw,color:t.text.primary},lead:face(e,"bold"),actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:n.lg,marginTop:14},action:{minHeight:Math.max(nk,zm),paddingHorizontal:n.lg,borderRadius:e.radius.pill,backgroundColor:t.primary,alignItems:"center",justifyContent:"center",maxWidth:"100%"},actionText:{...face(e,"bold"),fontSize:Gw,color:t.onPrimary},ask:{minHeight:zm,justifyContent:"center",maxWidth:"100%"},askText:{...face(e,"bold"),fontSize:Qw,color:t.brandInk,textDecorationLine:"underline"},pill:{flexDirection:"row",alignItems:"center",gap:n.sm,minHeight:Math.max(Jw,zm),paddingHorizontal:ek,borderRadius:e.radius.pill,backgroundColor:t.badgeBgCritical,alignSelf:"flex-start",maxWidth:"100%"},pillDot:{width:rk,height:rk,borderRadius:rk/2,backgroundColor:t.danger},pillText:{...face(e,"bold"),fontSize:tk,color:t.danger,flexShrink:1}})}var ak=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatShellTabsBar");function uk(){let e=globalThis,r=e[ak];if(r!==void 0)return r;let n=t.createContext(false);return e[ak]=n,n}var ck=uk();function dk(){return t.useContext(ck)}var fk=/* @__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"}),hk=/* @__PURE__ */new WeakMap;function pk(e){let t=hk.get(e);if(t!==void 0)return t;let r=e.color,n=e.brightness==="dark",l=n?{dark:n,ink:r.text.primary,ink2:r.text.secondary,ink3:r.text.muted,paper:r.background,card:r.surface,line:r.borderRingCream,tile:r.surfaceSubtle,shadow:r.shadow,riskBg:r.badgeBgCritical,riskInk:r.danger,riskDot:r.danger,clearBg:r.badgeBgPositive,clearInk:r.success,clearDot:r.success,watchDot:r.warningStrong}:{dark:n,...fk},i=(e,t)=>Ni(e,t,Mi(t),gk),o=(e,t)=>contrastRatio(e,t)>=gk?e:Ai(t,gk),s=[l.card,l.paper].map(e=>Vi(r.brandSoft,e)??e),a={primary:r.primary,onPrimary:o(r.onPrimary,r.primary),accent:r.accent,onAccent:o(r.onAccent,r.accent),link:i(r.linkInk,[l.card,l.paper,l.tile]),badge:r.brandSoft,onBadge:i(r.brandInk,s)},u=/* @__PURE__ */Object.freeze({...l,...a});return hk.set(e,u),u}var gk=4.5;function mk(e,t){for(let r of t)if(contrastRatio(r,e)>=gk)return r;return Ai(e,gk)}function bk(e,t,r){let n=Hi(e,t);return(n===null?null:Vi(n,r))??r}function yk(e){let t=pk(e),r=e.color,n=t.card;return{ink:t.ink,ink2:t.ink2,ink3:t.ink3,paper:t.paper,tile:t.tile,line:t.line,card:n,onInk:t.dark?r.background:"#FFFFFF",primary:t.primary,onPrimary:t.onPrimary,accent:t.accent,onAccent:mk(t.accent,[t.ink,t.onAccent]),accent2:bk(t.accent,.75,n),accent4:bk(t.accent,.17,n),accentChip:bk(t.accent,.47,n),link:t.link,linkChip:bk(t.link,.2,n),riskDot:t.riskDot,riskChip:t.dark?r.badgeBgCritical:"#FFD8D6",clearBg:t.clearBg,clearInk:t.clearInk,clearChip:t.dark?r.badgeBgPositive:"#DDEFC4",byInk:r.brandInk}}var vk=/* @__PURE__ */new Set(["color","fontSize","fontWeight","fontStyle","lh","ls","family","textAlign","textTransform","textDecorationLine"]),xk=/* @__PURE__ */new Set(["dur","delay","stagger","ease","tint","k","cols","nowrap"]),wk=["paddingTop","paddingRight","paddingBottom","paddingLeft"],kk=17,Ck=1.5,Sk=400,jk=700;function _k(e){return e<=450?"regular":e<=650?"medium":"bold"}function Rk(e){let t=Math.min(900,Math.max(100,Math.round(e/100)*100));return String(t)}function Tk(e,t,r){if(t==="$mono"){let t=r<=450?"mono":r<=650?"monoMedium":"monoBold",n=face(e,t);return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:Rk(r)}}let n=t==="$serif"?headingFace(e,_k(r)):face(e,_k(r));return n.fontWeight===void 0?{fontFamily:n.fontFamily}:{fontFamily:n.fontFamily,fontWeight:Rk(r)}}function Ik(e,t,r={}){let n=yk(e),l=e.brightness==="dark",i=e.motion.reducedMotion,o=e=>{if(typeof e=="string"&&e.startsWith("$")){let t=e.slice(1);return t.startsWith("n_")?l?n.line??e:`#${t.slice(2)}`:t==="sans"||t==="serif"||t==="mono"?e:n[t]??e}return Array.isArray(e)?e.map(e=>o(e)):e},s=/* @__PURE__ */new Map,a=e=>{let n=e.filter(e=>typeof e=="string"&&e!==""),l=n.join("|"),a=s.get(l);if(a!==void 0)return a;let u={},c=e=>{if(e!==void 0)for(let[t,r]of Object.entries(e))u[t]=o(r)};for(let e of n)c(t[e]),i&&c(r[e]);let d=/* @__PURE__ */Object.freeze(u);return s.set(l,d),d},u=/* @__PURE__ */new Map,c=(...e)=>{let t=e.filter(Boolean).join("|"),r=u.get(t);if(r!==void 0)return r;let n=a(e),l={};for(let[e,t]of Object.entries(n))vk.has(e)||xk.has(e)||e==="ring"||e==="edge"||e==="shadow"||e==="round"||e==="zIndex"&&typeof t=="number"&&t<0||t!==null&&(l[e]=t);if((typeof n.fontSize=="number"||n.flexDirection==="row")&&n.position!=="absolute"&&typeof n.height=="number"&&typeof n.width!="number"){let e=l.height;delete l.height,typeof l.minHeight!="number"&&(l.minHeight=e)}let i=n.ring;if(Array.isArray(i)){let[e,t]=i;l.borderWidth=e,l.borderColor=t;for(let t of wk){let r=l[t];typeof r=="number"&&(l[t]=Math.max(0,r-e))}}let o=n.edge;if(Array.isArray(o)){let[e,t]=o;l.borderBottomWidth=e,l.borderBottomColor=t}let s=n.shadow;if(Array.isArray(s)){let[e,t,r,n]=s;l.shadowColor=n,l.shadowOffset={width:e,height:t},l.shadowOpacity=1,l.shadowRadius=r/2}if(n.round===1){let e=typeof n.width=="number"?n.width:typeof n.height=="number"?n.height:999;l.borderRadius=e/2}let c=/* @__PURE__ */Object.freeze(l);return u.set(t,c),c},d=/* @__PURE__ */new Map,f=(t,r)=>{let l=`${t}|${r.filter(Boolean).join("|")}`,i=d.get(l);if(i!==void 0)return i;let o=a(r),s=typeof o.fontSize=="number"?o.fontSize:kk,u=typeof o.lh=="number"?o.lh:Ck,c=typeof o.fontWeight=="string"?Number(o.fontWeight):t,f=typeof o.family=="string"?o.family:"$sans",h={...Tk(e,f,c),fontSize:s,lineHeight:Math.round(s*u*100)/100,color:typeof o.color=="string"?o.color:n.ink};typeof o.ls=="number"&&(h.letterSpacing=Math.round(o.ls*s*100)/100);for(let e of["fontStyle","textAlign","textTransform","textDecorationLine"])typeof o[e]=="string"&&(h[e]=o[e]);let p=/* @__PURE__ */Object.freeze(h);return d.set(l,p),p};return{reduced:i,colors:n,view:c,text:(...e)=>f(Sk,e),strong:(...e)=>f(jk,e),icon:(...e)=>{let t=a(e),r={tintColor:typeof t.color=="string"?t.color:n.ink};for(let e of["width","height","opacity"])typeof t[e]=="number"&&(r[e]=t[e]);return r},col:(e,t)=>{let r=a([e]).cols;if(!Array.isArray(r))return{};let n=r[Math.min(t,r.length-1)];if(typeof n=="number")return{width:n,flexShrink:0};let l=typeof n=="string"?Number.parseFloat(n):1;return{flex:Number.isFinite(l)?l:1,minWidth:0}},motion:(...e)=>{let t=a(e),r=t.ease;return{dur:typeof t.dur=="number"?t.dur:0,delay:typeof t.delay=="number"?t.delay:0,stagger:typeof t.stagger=="number"?t.stagger:0,ease:Array.isArray(r)&&r.length===4?r:null}},raw:(e,...t)=>a(t)[e]}}var zk={".serif":{family:"$serif",fontWeight:"800",ls:-.01},".emb-btn":{flexDirection:"row",alignItems:"center",justifyContent:"center",minHeight:48,paddingTop:0,paddingRight:22,paddingBottom:0,paddingLeft:22,borderRadius:999,backgroundColor:"$primary",color:"$onPrimary",fontWeight:"700",fontSize:16,textDecorationLine:"none",dur:160,ease:[.23,1,.32,1],gap:8},".emb-btn--sm":{minHeight:40,paddingTop:0,paddingRight:16,paddingBottom:0,paddingLeft:16,fontSize:15},".dot":{width:9,height:9,round:1,flexGrow:0,flexShrink:0},".dot--risk":{backgroundColor:"$riskDot"},".ask-chips":{flexDirection:"column",alignItems:"center",marginTop:22,gap:10},".chip":{paddingTop:10,paddingRight:16,paddingBottom:10,paddingLeft:16,borderRadius:999,fontSize:15,fontWeight:"600",lh:1.3,textAlign:"center",dur:160,ease:[.23,1,.32,1]},".ask-empty":{minHeight:"100%",flexDirection:"column",alignItems:"center",paddingTop:14,paddingRight:16,paddingBottom:22,paddingLeft:16,textAlign:"center"},".ask-empty h2":{fontSize:23,lh:1.12},".ask-start":{width:"100%",marginTop:"auto",marginRight:0,marginBottom:"auto",marginLeft:0,paddingTop:18,paddingRight:0,paddingBottom:18,paddingLeft:0,flexDirection:"column",alignItems:"center"},".ask-empty .ask-chips":{marginTop:14,alignSelf:"center",alignItems:"stretch",width:"100%",maxWidth:340},".hp-need__k":{flexDirection:"row",alignItems:"center",fontSize:15,fontWeight:"800",gap:8},".hp-srcs":{marginLeft:"auto",flexDirection:"row",gap:4},".hp-src":{height:24,paddingTop:0,paddingRight:9,paddingBottom:0,paddingLeft:9,borderRadius:999,backgroundColor:"$tile",color:"$ink2",fontSize:12,fontWeight:"700",flexDirection:"row",alignItems:"center",nowrap:1},".hp-src--dna":{backgroundColor:"$n_E0FDFF",color:"$link"},".hp-need__s":{alignItems:"baseline",marginTop:6,fontSize:15,lh:1.45,color:"$ink2",flexDirection:"row",cols:[9,"1fr"],gap:9},".hp-need__s b":{color:"$ink",fontWeight:"800"},".ask-focus":{width:"100%",paddingTop:14,paddingRight:16,paddingBottom:16,paddingLeft:16,borderRadius:20,backgroundColor:"$card",textAlign:"left",shadow:[0,1,3,"rgba(38, 37, 35, .07)"]},".ask-focus h3":{marginTop:10,fontSize:18,fontWeight:"800",lh:1.22},".ask-focus__x":{width:36,height:36,marginTop:-8,marginRight:-10,marginBottom:-8,marginLeft:-2,alignItems:"center",justifyContent:"center",round:1,color:"$ink2"},".ask-focus__x svg":{width:18,height:18},".ask-focus-pill":{marginLeft:"auto",flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:14,paddingBottom:0,paddingLeft:14,borderRadius:999,backgroundColor:"$n_FFE3E1",color:"$n_B0231B",fontSize:15,fontWeight:"800",gap:7},".ask-focus-pill i":{width:8,height:8,round:1,backgroundColor:"$riskDot"},".ask-focus .hp-need__s":{fontSize:14.5},".ask-focus__acts":{flexDirection:"row",flexWrap:"wrap",alignItems:"center",marginTop:12,rowGap:4,columnGap:16},".ask-focus__q":{minHeight:36,fontSize:14.5,fontWeight:"700",color:"$link",textDecorationLine:"underline"},".ask-top":{alignSelf:"stretch",flexDirection:"row",marginTop:-8,marginRight:0,marginBottom:6,marginLeft:0},".thread__hist":{flexDirection:"row",alignItems:"center",minHeight:36,paddingTop:0,paddingRight:4,paddingBottom:0,paddingLeft:4,fontSize:15,fontWeight:"700",color:"$link",gap:6},".thread__hist svg":{width:18,height:18},".thread__count":{minWidth:22,height:20,paddingTop:0,paddingRight:6,paddingBottom:0,paddingLeft:6,borderRadius:999,backgroundColor:"$card",color:"$ink2",fontSize:12,fontWeight:"800",alignItems:"center",justifyContent:"center",ring:[1,"$line"]}},Pk=16;var Ek=4e3,Ok=.5;function Ak(e,t,r){let n=1,l=-1;for(let i of e)l<0?l=i:l+t+i<=r?l+=t+i:(n+=1,l=i);return n}function Mk(e,t,r){if(e.length===0)return r;let n=Ak(e,t,r),l=[];for(let n=0;n<e.length;n+=1){let i=0;for(let o=n;o<e.length;o+=1)i+=(o>n?t:0)+e[o],i<=r&&l.push(i)}l.sort((e,t)=>e-t);let i=Ok*e.length+1;for(let o of l)if(Ak(e,t,o)<=n)return Math.min(r,o+i);return r}function BalancedTitle({text:e,style:n,measureCh:l}){let o=t.useMemo(()=>e.split(/\s+/).filter(e=>e!==""),[e]),s=r.StyleSheet.flatten(n),a=[e,s.fontFamily,s.fontSize,s.fontWeight,s.letterSpacing].join("|"),u=t.useRef({key:"",ch:null,line:null,words:[]});u.current.key!==a&&(u.current={key:a,ch:null,line:null,words:o.map(()=>null)});let[c,d]=t.useState(null),f=c!==null&&c.key===a?c.value:null,h=()=>{let e=u.current;if(e.ch===null||e.line===null||e.words.some(e=>e===null))return;let t=e.words,r=t.reduce((e,t)=>e+t,0),n=t.length>1?Math.max(0,(e.line-r)/(t.length-1)):0,i=Mk(t,n,(e.ch+Ok)*l);d(t=>t!==null&&t.key===e.key&&t.value===i?t:{key:e.key,value:i})},p=e=>t=>{u.current.key===a&&(e(u.current,t.nativeEvent.layout.width),h())};/* @__PURE__ */
|
|
270
|
+
return i.jsxs(r.View,{style:Fk.wrap,children:[
|
|
271
|
+
/* @__PURE__ */i.jsx(Text,{tier:"heading",style:f===null?n:[n,{maxWidth:f}],accessibilityRole:"header",children:e}),
|
|
272
|
+
/* @__PURE__ */i.jsx(r.View,{style:Fk.probeClip,pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */i.jsxs(r.View,{style:Fk.probeRow,children:[
|
|
273
|
+
/* @__PURE__ */i.jsx(Text,{tier:"heading",style:n,onLayout:p((e,t)=>{e.ch=t}),children:"0"}),
|
|
274
|
+
/* @__PURE__ */i.jsx(Text,{tier:"heading",style:n,onLayout:p((e,t)=>{e.line=t}),children:o.join(" ")}),o.map((e,t)=>/* @__PURE__ */i.jsx(Text,{tier:"heading",style:n,onLayout:p((e,r)=>{e.words[t]=r}),children:e},`${t}:${e}`))]})})]})}var Fk=r.StyleSheet.create({wrap:{alignSelf:"stretch",alignItems:"center"},probeClip:{position:"absolute",left:0,top:0,width:0,height:0,overflow:"hidden",opacity:0},probeRow:{width:Ek,flexDirection:"row",alignItems:"flex-start"}});function Dk(e){return{kit:Ik(e,zk),Title:BalancedTitle,titleCh:Pk}}var Lk=/* @__PURE__ */Symbol.for("everfur.sdk.rn.poweredBy");function Bk(){let e=globalThis,t=e[Lk];if(t!==void 0)return t;let r={count:0,listeners:/* @__PURE__ */new Set};return e[Lk]=r,r}var Vk=e=>{let t=Bk();return t.listeners.add(e),()=>t.listeners.delete(e)},Hk=()=>Bk().count>0;function useHostPoweredBy(){return t.useSyncExternalStore(Vk,Hk,Hk)}var Uk=/* @__PURE__ */Object.freeze({}),Nk=100,$k=20;function Wk(e,t,r,n){return![e,t,r,n].every(Number.isFinite)||e+r>n+1?null:{chatTop:Math.max(0,e),parentTop:Math.max(0,e-t)}}function qk(e,n){let l=typeof e=="number"&&Number.isFinite(e),i=t.useRef(null),[o,s]=t.useState(null),a=t.useRef(null),u=t.useRef(null),c=t.useRef(true),d=t.useCallback(()=>{u.current!==null&&clearTimeout(u.current),u.current=null},[]);t.useEffect(()=>(c.current=true,()=>{c.current=false,d()}),[d]);let f=t.useCallback(function e(t){i.current?.measureInWindow((n,l)=>{let i=a.current;if(!c.current||i===null)return;let o=Wk(l,i.y,i.height,r.Dimensions.get("window").height);if(o!==null){s(e=>e!==null&&e.chatTop===o.chatTop&&e.parentTop===o.parentTop?e:o);return}t>=$k||(u.current=setTimeout(()=>{u.current=null,e(t+1)},Nk))})},[]),h=t.useCallback(e=>{let{y:t,height:r}=e.nativeEvent.layout;a.current={y:t,height:r},d(),f(0)},[f,d]);return t.useMemo(()=>{if(!n)return{avoidingProps:l?{keyboardVerticalOffset:e}:Uk,probeRef:null,topInWindow:null};let t=o?.parentTop??0;return{avoidingProps:l?{keyboardVerticalOffset:e,onLayout:h}:t>0?{keyboardVerticalOffset:t,onLayout:h}:{onLayout:h},probeRef:i,topInWindow:o?.chatTop??null}},[n,l,e,o,h])}function KeyboardOffsetProbe({probeRef:e}){return e===null?null:/* @__PURE__ */i.jsx(r.View,{ref:e,collapsable:false,pointerEvents:"none",style:Gk})}var Gk=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function Kk(){let[e,n]=t.useState(false);return t.useEffect(()=>{let e=r.Keyboard;if(typeof e?.addListener!="function")return;let t=r.Platform.OS==="ios",l=e.addListener(t?"keyboardWillShow":"keyboardDidShow",()=>n(true)),i=e.addListener(t?"keyboardWillHide":"keyboardDidHide",()=>n(false));return()=>{l.remove(),i.remove()}},[]),e}function Yk(e,t,r){return Ni(e,t,Mi(t),r)}function Qk(e,t){if(e.level==="emergency")return e;let r=e.level==="schedule_soon",n=Pv(t),l=r?n.warning:n.info,i=zv(t)&&!l?e:Zk(e,t,r);return Xk(i,t.slots.banner)}function Zk(e,t,r){let n=t.color,l=Vi(r?n.badgeBgCaution:n.badgeBgInfo,n.surface)??n.surface,i=r?n.cautionAccent:n.infoEdge,o=Yk(Vi(i,n.surface)??i,[n.surface,n.chatGround],lo),s=Yk(r?n.warningStrong:n.info,[l,n.surface],Qi);/* @__PURE__ */
|
|
275
|
+
return Object.freeze({...e,borderColor:o,backgroundColor:l,textColor:s,reasonColor:Yk(n.text.primary,[l],Qi),pillColor:n.surface})}function Xk(e,t){if(t===void 0)return e;let r={...e};return t.backgroundColor!==void 0&&(r.backgroundColor=t.backgroundColor),t.borderColor!==void 0&&(r.borderColor=t.borderColor),t.textColor!==void 0&&(r.textColor=t.textColor,r.reasonColor=t.textColor),/* @__PURE__ */Object.freeze(r)}function Jk(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),t?.prefer!==void 0&&(r.prefer=t.prefer),r}var eC=.75,tC=1.5,rC=.4,nC=4,lC=1.5,iC=22,oC=14,sC=8,aC=20,uC=10,cC=13,dC=12,fC=15,hC=44,pC=14,gC=1.25,mC=14,bC=6,yC=2;function vC(e,t){let r=e.color;if(t.level==="emergency")return{card:{backgroundColor:r.badgeBgCritical,borderColor:Hi(r.danger,rC)??r.danger,borderWidth:tC},label:r.danger,reason:r.text.primary,close:r.danger,action:{fill:r.surface,edge:r.danger,ink:r.danger}};let n=e.slots.banner?.borderRadius;return{card:{backgroundColor:t.backgroundColor,borderColor:t.borderColor,borderWidth:eC,...n===void 0?{}:{borderRadius:n}},label:t.textColor,reason:t.reasonColor,close:t.textColor,action:null}}function UrgencyBanner({surface:e,petRef:r,renderVetAction:n,onFindVet:l,vet:o,compact:s=false}){let a=useEverfurTheme(),u=t.useMemo(()=>xC(a),[a]),c=sg(),d=e.tier===null?null:Qk(e.tier,a),f=e.source;/* @__PURE__ */
|
|
276
|
+
return i.jsxs(i.Fragment,{children:[
|
|
277
|
+
/* @__PURE__ */i.jsx(FadePresence,{visible:e.showBanner&&d!==null,inMs:c.bannerInMs,outMs:c.bannerOutMs,style:u.pinned,children:d!==null&&f!==null?/* @__PURE__ */i.jsx(BannerCard,{tier:d,reason:f.reason,surface:e,petRef:r,renderVetAction:n,onFindVet:l,vet:o,styles:u,compact:s}):null}),
|
|
278
|
+
/* @__PURE__ */i.jsx(FadePresence,{visible:e.showCompactIcon,inMs:c.iconInMs,outMs:c.iconOutMs,style:u.indicatorRow,children:/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:vf.showLatestVetAlert,hitSlop:uC,onPress:e.expand,children:/* @__PURE__ */i.jsx(InfoGlyph,{size:aC,color:a.color.text.muted,strokeWidth:2})})})]})}function BannerCard({tier:e,reason:t,surface:n,petRef:l,renderVetAction:o,onFindVet:s,vet:a,styles:u,compact:c}){let d=useEverfurTheme(),f=vC(d,e),h=/* @__PURE__ */i.jsx(VetAction,{tier:e,paint:f,petRef:l,onFindVet:s,vet:a,styles:u}),p=n.showVetAction?o!==void 0?/* @__PURE__ */i.jsx(HostRender,{render:()=>o(e.level),fallback:h,resetKey:e.level}):h:null,g=f.action!==null?/* @__PURE__ */i.jsx(PoisonControl,{paint:f.action,styles:u}):null,m=e.level==="emergency"&&s===void 0,b=e.level==="emergency"||e.level==="schedule_soon";/* @__PURE__ */
|
|
279
|
+
return i.jsxs(r.View,{...b?{accessibilityRole:"alert"}:{accessibilityLiveRegion:"polite"},style:[u.card,f.card,c?u.cardCompact:null],testID:c?"chat-urgency-compact":void 0,children:[
|
|
280
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:[u.label,{color:f.label}],children:e.label}),t!==null?/* @__PURE__ */i.jsx(Text,{style:[u.reason,{color:f.reason}],numberOfLines:c?yC:void 0,accessibilityLabel:c?t:void 0,children:t}):null,m?/* @__PURE__ */i.jsx(Text,{style:[u.reason,u.erLine,{color:f.reason}],children:vf.goToNearestEmergencyVet}):null,p!==null||g!==null?/* @__PURE__ */i.jsxs(r.View,{style:u.actions,children:[p,g]}):null,n.dismissLabel!==null?/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:n.dismissLabel,hitSlop:sC,containerStyle:u.closeSlot,style:u.closeButton,onPress:n.dismiss,children:/* @__PURE__ */i.jsx(CloseGlyph,{size:oC,color:f.close,strokeWidth:1.5})}):null]})}function PoisonControl({paint:e,styles:t}){let n=()=>{try{r.Linking.openURL(Cf).catch(()=>{})}catch{}};/* @__PURE__ */
|
|
281
|
+
return i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:vf.poisonControlNative,hitSlop:0,style:[t.action,{backgroundColor:e.fill,borderColor:e.edge}],onPress:n,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:[t.actionLabel,{color:e.ink}],children:vf.poisonControlNative})})}function VetAction({tier:e,paint:t,petRef:r,onFindVet:n,vet:l,styles:o}){let s=useEverfurTheme(),a=useVetVisit(Jk(r,l)),u=a.status==="opening",c=!a.available&&n!==void 0,d=a.available?()=>{a.open()}:n!==void 0?()=>{ch(n,e.level)}:null;if(d===null)return null;let f=t.action;if(f!==null){let e=c?vf.nearestEmergencyVet:vf.findVet,t=Fg(s.slots.vetVisitButton)?.textColor??f.ink;/* @__PURE__ */
|
|
282
|
+
return i.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:c?vf.nearestEmergencyVet:vf.findVetA11y,accessibilityState:{busy:u},hitSlop:0,style:[o.action,{backgroundColor:f.fill,borderColor:f.edge},o.findVetSlotBox,u?o.findVetBusy:null],onPress:d,children:[
|
|
283
|
+
/* @__PURE__ */i.jsx(MapPinGlyph,{size:cC,color:t,strokeWidth:1.5}),
|
|
284
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:[o.actionLabel,{color:t}],children:e})]})}let h=Fg(s.slots.vetVisitButton)?.textColor??e.textColor;/* @__PURE__ */
|
|
285
|
+
return i.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:vf.findVetA11y,accessibilityState:{busy:u},style:[o.findVetButton,{borderColor:e.borderColor,backgroundColor:e.pillColor},o.findVetSlotBox,u?o.findVetBusy:null],onPress:d,children:[
|
|
286
|
+
/* @__PURE__ */i.jsx(MapPinGlyph,{size:cC,color:h,strokeWidth:1.5}),
|
|
287
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:[o.findVetLabel,{color:h}],children:vf.findVet})]})}function xC(e){let t=Fg(e.slots.vetVisitButton),n=e.space,l=e.type;return r.StyleSheet.create({pinned:{marginTop:0,marginBottom:n.xs,paddingHorizontal:n.lg},card:{borderRadius:e.radius.lg,paddingHorizontal:n.lg+nC,paddingVertical:n.lg,gap:n.sm},cardCompact:{paddingVertical:n.md,gap:n.xs},label:{...face(e,"bold"),fontSize:l.size.body,paddingRight:iC},reason:{...face(e,"regular"),fontSize:l.size.bodyTight,lineHeight:Math.round(l.size.bodyTight*lC),paddingRight:iC},erLine:{...face(e,"bold")},actions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:n.sm},action:{flexDirection:"row",alignItems:"center",gap:bC,minHeight:hC,paddingHorizontal:pC,borderRadius:e.radius.pill,borderWidth:gC},actionLabel:{...face(e,"bold"),fontSize:mC},findVetButton:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:5,borderRadius:e.radius.pill,borderWidth:1},findVetSlotBox:{...Mg(t,1)},findVetBusy:{opacity:.6},findVetLabel:{...face(e,"monoBold"),fontSize:dC,lineHeight:fC},closeSlot:{position:"absolute",top:n.md,right:n.md},closeButton:{width:iC,height:iC,borderRadius:iC/2,alignItems:"center",justifyContent:"center"},indicatorRow:{alignItems:"flex-end",paddingHorizontal:n.lg,paddingTop:2,paddingBottom:n.xs}})}var wC=/* @__PURE__ */Symbol.for("everfur.sdk.tabsBar.v1");function kC(){return globalThis[wC]??null}function CC(e){return e==="tabs_bar"&&kC()!==null}function SeverityCard(e){let t=kC()?.ask.SeverityCard;return t===void 0?null:/* @__PURE__ */i.jsx(t,{...e})}function AnswerRecordCards(e){let t=kC()?.ask.AnswerRecordCards;return t===void 0?null:/* @__PURE__ */i.jsx(t,{...e})}function PrivacyLine(e){let t=kC()?.ask.PrivacyLine;return t===void 0?null:/* @__PURE__ */i.jsx(t,{...e})}function AskBarDisclaimer(){let e=kC()?.ask.AskBarDisclaimer;return e===void 0?null:/* @__PURE__ */i.jsx(e,{})}function SC(e,r,n,l){let[i,o]=t.useState({pet:n,user:r}),s=i.pet!==n||i.user===null&&r!==null;s&&o({pet:n,user:r});let a=s?{user:r}:i,u=n!==null&&a.user!==null&&a.user!==r;return t.useEffect(()=>{if(!u||r===null||n===null)return;let t=true,l=createPetsRepository(e.registry.services.authFor(r)),i=async()=>{let e=await l.list();t&&e.ok&&e.value.some(e=>e.petRef===n)&&o({pet:n,user:r})};i();let s=fi(e,()=>{i()});return()=>{t=false,s()}},[u,e,r,n,l]),u}var jC=/* @__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(e){let{runtime:r,userRef:n,activePet:l,scopeEpoch:i}=Yc(),o=e?.petRef??l??null,s=e?.conversationId??null,a=SC(r,n,o,i),u=t.useMemo(()=>({runtime:r,userRef:n,petRef:o,conversationId:s,scopeEpoch:i,held:a}),[r,n,o,s,i,a]),[c,d]=t.useState(null),f=a?null:c?.scope===u?c.controller:r.registry.peekChat({userRef:n,petRef:o,conversationId:s}),h=t.useRef(null);t.useEffect(()=>{if(a)return;let e=r.registry.acquireChat({userRef:n,petRef:o,conversationId:s});return h.current=e,d({scope:u,controller:e}),()=>{h.current=null,d(t=>t?.controller===e?null:t),r.registry.releaseChat(e)}},[r,n,o,s,i,a,u]);let p=t.useCallback(e=>f?f.subscribe(e):NOOP_UNSUBSCRIBE,[f]),g=t.useCallback(()=>f?f.getSnapshot():jC,[f]),m=t.useSyncExternalStore(p,g,g),b=t.useCallback((e,t)=>f&&h.current===f&&!f.getSnapshot().isBootstrapping?RC(f,f.send(e,t?.imageS3Keys===void 0?{}:{imageS3Keys:t.imageS3Keys}),()=>h.current===f):Promise.resolve(IC()),[f]),y=t.useCallback(e=>f&&h.current===f&&!f.getSnapshot().isBootstrapping?RC(f,f.askEverfur(e),()=>h.current===f):Promise.resolve(IC()),[f]),v=t.useCallback(()=>f&&h.current===f?RC(f,f.retryLast(),()=>h.current===f):Promise.resolve(IC()),[f]),x=t.useCallback(()=>{f&&h.current===f&&f.stop()},[f]),w=t.useCallback(()=>{f&&h.current===f&&f.newConversation()},[f]),[k,C]=t.useState({controller:null,byMessage:{}}),S=k.controller===f?k.byMessage:_C,j=t.useCallback(async(e,t,r,n)=>{if(!f||h.current!==f)return err(makeEverfurError("accessDenied"));let l=String(e),i=k.controller===f?k.byMessage[l]:void 0;if(i===t&&r==null)return C(e=>{let t={...e.controller===f?e.byMessage:{}};return delete t[l],{controller:f,byMessage:t}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));C(e=>({controller:f,byMessage:{...e.controller===f?e.byMessage:{},[l]:t}}));let o=await f.submitFeedback(e,Cx(t,r??null),n??null);return h.current!==f?err(makeEverfurError("accessDenied")):(o.ok||C(e=>{let t={...e.controller===f?e.byMessage:{}};return i===void 0?delete t[l]:t[l]=i,{controller:f,byMessage:t}}),o)},[f,k]),_=t.useMemo(()=>{let e=async e=>{if(!f||h.current!==f)return err(makeEverfurError("accessDenied"));let t=await e(f);return h.current===f?t:err(makeEverfurError("accessDenied"))};return{listConversations:t=>e(e=>e.listConversations({...o?{petRef:o}:{},...t})),getMessages:(t,r)=>e(e=>e.getMessages(t,r)),resumeConversation:t=>e(e=>e.resumeConversation(t)),loadOlderMessages:()=>e(e=>e.loadOlderMessages()),markRead:()=>e(e=>e.markRead()),refreshActiveThread:t=>e(e=>e.refreshActiveThread(t)),answerCheckin:(t,r)=>e(e=>e.answerCheckin(t,r)),openCheckin:t=>e(e=>e.openCheckin(t))}},[f,o]);return t.useMemo(()=>({status:m.status,messages:m.messages,conversationId:m.conversationId,petRef:o,error:m.error,isStreaming:m.isStreaming,isBootstrapping:m.isBootstrapping,historyCursor:m.historyCursor??null,isLoadingHistory:m.isLoadingHistory??false,stopped:m.stopped??false,reconnecting:m.reconnecting??false,..._,suggestedPrompts:m.suggestedPrompts,unreadCount:m.unreadCount,hasUnreadThreads:m.hasUnreadThreads??false,pendingCheckin:m.pendingCheckin??null,newConversation:w,sentimentByMessage:S,feedback:j,send:b,askEverfur:y,retryLast:v,stop:x}),[m,o,b,y,v,x,_,w,S,j])}var NOOP_UNSUBSCRIBE=()=>{},_C=/* @__PURE__ */Object.freeze({});async function RC(e,t,r){for await(let e of t);if(!r())return err(makeEverfurError("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?err(n.error):ok(TC(n.messages))}function TC(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}function IC(){return Kh()}function zC(){let e=useEverfurPets(),{handle:r}=Yc(),n=t.useCallback(e=>r.setActivePet(e),[r]);return t.useMemo(()=>({...e,setActivePet:n}),[e,n])}function PC(){try{let e=r.AccessibilityInfo?.announceForAccessibility;typeof e=="function"&&e.call(r.AccessibilityInfo,vf.answered)}catch{}}function EC(e){let r=t.useRef(false),n=t.useRef({send:e.send,id:e.conversationId});t.useEffect(()=>{let t=n.current;if((t.send!==e.send||t.id!==null&&t.id!==e.conversationId)&&(r.current=false),n.current={send:e.send,id:e.conversationId},r.current&&!e.isStreaming){let t=e.messages[e.messages.length-1];t!==void 0&&t.role==="assistant"&&PC()}r.current=e.isStreaming},[e.isStreaming,e.messages,e.send,e.conversationId])}var OC=/* @__PURE__ */Object.freeze({kind:"live"}),AC=/* @__PURE__ */Object.freeze({kind:"folded"});function MC(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=Xr(e.proactiveOriginRef);return{caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}function FC(e){let t=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map;for(let t of e){let e=MC(t);if(e===null)continue;let n=r.get(e.caseId);(n===void 0||e.dueDay>=n.dueDay)&&r.set(e.caseId,{messageId:t.id,dueDay:e.dueDay})}if(r.size===0)return t;let n=null;for(let l of e){let e=MC(l);if(e===null){n=null;continue}if(r.get(e.caseId)?.messageId===l.id){t.set(l.id,OC),n=null;continue}if(n!==null&&n.caseId===e.caseId){n.days.push(e.dueDay),t.set(l.id,AC);continue}let i=[e.dueDay];n={id:l.id,caseId:e.caseId,days:i},t.set(l.id,{kind:"past",runDueDays:i})}return t}function DC(e){let t=/* @__PURE__ */new Set;for(let[r,n]of e)n.kind==="live"&&t.add(r);return t}var LC=864e5,BC=365;function VC(e,t){if(typeof e!="string"||typeof t!="string")return null;let r=Date.parse(e),n=Date.parse(t);if(Number.isNaN(r)||Number.isNaN(n))return null;let l=Math.floor(n/LC)-Math.floor(r/LC);return l<1||l>BC?null:l}function HC(e){return MC(e)?.dueDay||null}function UC(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function AssistantSender({avatarUrl:e,named:t,styles:n}){let l=Sv(e);return l.shown?/* @__PURE__ */i.jsxs(r.View,{style:n.assistantSender,testID:"everfur-assistant-sender",children:[
|
|
288
|
+
/* @__PURE__ */i.jsx(BrandImage,{uri:e,decorative:true,style:n.assistantAvatar,resizeMode:"cover",onError:l.onError,testID:"everfur-assistant-avatar"}),t?/* @__PURE__ */i.jsx(Text,{tier:"control",style:[n.assistantName,n.assistantNameInRow],children:vf.assistantName}):null]}):t?/* @__PURE__ */i.jsx(Text,{tier:"control",style:n.assistantName,children:vf.assistantName}):null}var NC=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),$C="#C8BEB4";function WC(e){return e?NC[e.toUpperCase()]??$C:$C}function qC(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}function GC(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}function KC(e){let t=GC(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}function YC(e,t){let r=GC(e.source_name)??GC(e.sourceName),n=GC(e.section),l=GC(e.authority_tier)??GC(e.authorityTier),i=qC(l),o=r??GC(e.title)??`Source ${t+1}`,s=GC(e.monograph_chunk_id)??GC(e.chunkId),a=[n,i].filter(e=>e!==null).join(" · ");/* @__PURE__ */
|
|
289
|
+
return Object.freeze({title:o,sourceName:r,section:n,authorityTier:l,tierLabel:i,meta:a.length===0?null:a,url:KC(e.url),excerpt:GC(e.excerpt),tierColor:WC(l),key:`${o}-${s??"none"}-${t}`})}function QC(e){return e===void 0||e.length===0?ZC:/* @__PURE__ */Object.freeze(e.map((e,t)=>YC(e,t)))}var ZC=/* @__PURE__ */Object.freeze([]);function XC(e){return e===1?`1 ${vf.sourceSingular}`:`${e} ${vf.sourcePlural}`}function JC(e,t){return`${t?vf.hideSources:vf.showSources} ${XC(e)}`}function eS(e){return[e.url!==null?`${vf.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(e=>e!==null&&e.length>0).join(". ")}function tS(e){let t=e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}var rS=/^\s*[-*]\s+(\S.*)$/,nS=/^\s*(\d{1,3})[.)]\s+(\S.*)$/;function lS(e){let t=[],r=[],n=null,l=()=>{r.length>0&&t.push({kind:"text",text:r.join(`\n`)}),r=[]},i=()=>{n!==null&&t.push(n.ordered?{kind:"list",ordered:true,start:n.start,items:n.items}:{kind:"list",ordered:false,items:n.items}),n=null};for(let t of e.split(`\n`)){let e=rS.exec(t),o=e===null?nS.exec(t):null,s=e?.[1]??o?.[2];if(s===void 0){i(),r.push(t);continue}let a=o!==null;l(),n!==null&&n.ordered!==a&&i(),n===null&&(n={ordered:a,start:o===null?1:Number(o[1]),items:[]}),n.items.push(s.trim())}return l(),i(),t}function iS(e,t){let r=e.findIndex(e=>e.id===t);for(let t=r-1;t>=0;t-=1){let r=e[t];if(r!==void 0&&r.role==="user")return r.text}return null}function oS(e,t){if(e===void 0)return[];try{let r=e(t);return Array.isArray(r)?r:[]}catch{return[]}}function sS(e){return hardenHttpsUrl(e.trim())}function aS(e,t){if(t?.followUpActions===void 0||e.isStreaming||e.status==="error")return[];let r=e.messages[e.messages.length-1];return r===void 0||r.role!=="assistant"||r.pending===true?[]:oS(t.followUpActions,{answer:r.text,question:iS(e.messages,r.id),messageId:r.id})}var uS=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g,cS=new RegExp(`\\[([^\\]\\n]{1,300})\\]\\((https:\\/\\/[^\\s()<>]{1,${Np}})\\)|(https:\\/\\/[^\\s<>"'\`*\\[\\]]{1,${Np}})`,"gi"),dS=/https:\/\//i,fS=`.,;:!?'"`;function hS(e,t){return e.includes("*")||e.includes("`")||t!==void 0&&dS.test(e)}function pS(e,t){let r=[],n=e=>{t===void 0?r.push({kind:"text",text:e}):bS(r,e,t)},l=0;uS.lastIndex=0;for(let t=uS.exec(e);t!==null;t=uS.exec(e)){t.index>l&&n(e.slice(l,t.index));let i=t[1],o=t[2],s=t[3];i!==void 0?r.push({kind:"bold",text:i}):o!==void 0?r.push({kind:"italic",text:o}):s!==void 0&&r.push({kind:"code",text:s}),l=t.index+t[0].length}return l<e.length&&n(e.slice(l)),r}function gS(e){let t=e.length;for(;;){let r=e[t-1];if(r===void 0)break;if(fS.includes(r))t-=1;else if(r===")"&&mS(e,"(",t)<mS(e,")",t))t-=1;else break}return e.slice(0,t)}function mS(e,t,r){let n=0;for(let l=0;l<r;l+=1)e[l]===t&&(n+=1);return n}function bS(e,t,r){if(!dS.test(t)){e.push({kind:"text",text:t});return}let n=0;cS.lastIndex=0;for(let l=cS.exec(t);l!==null;l=cS.exec(t)){let i=l[1],o=l[2],s=l[3],a,u,c;if(i!==void 0&&o!==void 0)a=i.trim(),u=a.length>0?Gp(o,r):null,c=l[0].length;else if(s!==void 0)a=gS(s),u=Gp(a,r),c=a.length;else continue;u!==null&&(l.index>n&&e.push({kind:"text",text:t.slice(n,l.index)}),e.push({kind:"link",text:a,href:u}),n=l.index+c,cS.lastIndex=n)}n<t.length&&e.push({kind:"text",text:t.slice(n)})}var yS=/* @__PURE__ */Object.freeze({textDecorationLine:"underline"});function vS(e,t){return t===void 0||!hS(e,t.hosts)?false:pS(e,t.hosts).some(e=>e.kind==="link")}function xS(e,t,r){let n=r?.hosts;return hS(e,n)?pS(e,n).map((e,n)=>{switch(e.kind){case"bold":/* @__PURE__ */
|
|
290
|
+
return i.jsx(Text,{style:t.bold,children:e.text},n);case"italic":return t.italic?/* @__PURE__ */i.jsx(Text,{style:t.italic,children:e.text},n):e.text;case"code":return t.code?/* @__PURE__ */i.jsx(Text,{style:t.code,children:e.text},n):e.text;case"link":{if(r===void 0)return e.text;let{href:t}=e;/* @__PURE__ */
|
|
291
|
+
return i.jsx(Text,{style:yS,accessibilityRole:"link",accessibilityLabel:e.text,onPress:()=>r.open(t),children:e.text},n)}default:return e.text}}):e}var wS=10.5,kS=16,CS=12,SS=38,jS=11,_S=15,RS=22,TS=32,IS=13.5,zS=14,PS=15,ES=16,OS=13,AS=13,MS=26,FS=21,DS=42,LS=1,BS=.06,VS=.07,HS=.12,US="45%";function NS(){let e=useEverfurTheme(),r=t.useMemo(()=>$S(e),[e]);return{theme:e,styles:r}}function Chevron({options:e,color:t}){let r=/* @__PURE__ */i.jsx(ChevronGlyph,{size:ES,color:t,strokeWidth:2,direction:"right"}),n=e?.renderIcon;return n===void 0?r:/* @__PURE__ */i.jsx(HostRender,{render:()=>n("chevron"),fallback:r})}function AnswerCard({card:e,options:t}){let{theme:n,styles:l}=NS();if(e.render!==void 0){let n=e.render;/* @__PURE__ */
|
|
292
|
+
return i.jsx(r.View,{style:[l.card,e.variant!==void 0?t?.styles?.cardVariant?.[e.variant]:null],accessible:false,accessibilityLabel:e.title,testID:"everfur-answer-host-card",children:/* @__PURE__ */i.jsx(HostRender,{render:n,fallback:null})})}let o=e.value!==void 0,s=t?.styles,a=[l.card,o?s?.cardStat:null,e.variant!==void 0?s?.cardVariant?.[e.variant]:null],u=e.tile?.tone,c=e.pill?.tone,d=e.tile?.imageUrl!==void 0?sS(e.tile.imageUrl):null,f=/* @__PURE__ */i.jsxs(i.Fragment,{children:[o?null:/* @__PURE__ */i.jsx(r.View,{style:[l.tile,u!==void 0?s?.tileTone?.[u]:null],children:d!==null?/* @__PURE__ */i.jsx(r.Image,{source:{uri:d},style:l.tileImage,accessibilityIgnoresInvertColors:true}):e.tile?.icon??null}),
|
|
293
|
+
/* @__PURE__ */i.jsxs(r.View,{style:l.cardWords,children:[
|
|
294
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:l.cardTitle,children:e.title}),e.meta!==void 0?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:l.cardMeta,children:e.meta}):null]}),o?/* @__PURE__ */i.jsxs(Text,{tier:"control",style:l.stat,children:[e.value?.amount,e.value?.unit!==void 0?/* @__PURE__ */i.jsx(Text,{style:l.statUnit,children:e.value.unit}):null]}):/* @__PURE__ */i.jsxs(i.Fragment,{children:[e.pill!==void 0?/* @__PURE__ */i.jsx(r.View,{style:[l.pill,c!==void 0?s?.pillTone?.[c]:null],children:/* @__PURE__ */i.jsx(Text,{tier:"badge",style:[l.pillText,c!==void 0?s?.pillToneText?.[c]:null],numberOfLines:1,ellipsizeMode:"tail",children:e.pill.label})}):null,e.onPress!==void 0?/* @__PURE__ */i.jsx(Chevron,{options:t,color:n.color.text.muted}):null]})]});if(e.onPress!==void 0){let t=e.onPress;/* @__PURE__ */
|
|
295
|
+
return i.jsx(r.Pressable,{onPress:()=>{ch(t)},accessibilityRole:"button",accessibilityLabel:e.title,style:a,children:f})}/* @__PURE__ */
|
|
296
|
+
return i.jsx(r.View,{style:a,children:f})}function CardsAnswer({message:e,text:n,streaming:l,messages:o,options:s,sentiment:a,onSentiment:u,sender:c,footer:d,onOpenUrl:f}){let{styles:h}=NS(),p=t.useMemo(()=>({answer:e.text,question:iS(o,e.id),messageId:e.id}),[e.text,e.id,o]),g=!l&&e.pending!==true,m=g?oS(s?.cards,p):[],b=t.useMemo(()=>g?QC(e.citations):[],[g,e.citations]),y=s?.byline,v=s?.feedback!==void 0&&e.responseId!==void 0&&u!==void 0?s.feedback:null,x={bold:h.bold,italic:h.italic,code:h.code},w=Qp(),k=g?w:void 0;/* @__PURE__ */
|
|
297
|
+
return i.jsxs(r.View,{style:h.answer,testID:"everfur-answer-cards",children:[y!==void 0?/* @__PURE__ */i.jsxs(r.View,{style:h.byline,children:[y.icon??null,
|
|
298
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:h.bylineText,children:y.label})]}):c,g?/* @__PURE__ */i.jsx(SeverityCard,{message:e}):null,
|
|
299
|
+
/* @__PURE__ */i.jsx(r.View,{style:h.body,children:tS(n).flatMap((e,t)=>lS(e).map((e,n)=>{let l=`${t}-${n}`;return e.kind==="text"?/* @__PURE__ */i.jsx(Text,{style:h.paragraph,children:xS(e.text,x,k)},l):/* @__PURE__ */i.jsx(r.View,{style:h.list,children:e.items.map((t,n)=>/* @__PURE__ */i.jsxs(r.View,{style:h.listItem,children:[
|
|
300
|
+
/* @__PURE__ */i.jsx(Text,{style:h.paragraph,children:e.ordered?`${e.start+n}.`:"•"}),
|
|
301
|
+
/* @__PURE__ */i.jsx(Text,{style:[h.paragraph,h.listText],children:xS(t,x,k)})]},n))},l)}))}),m.length>0?/* @__PURE__ */i.jsx(r.View,{style:h.cards,children:m.map(e=>/* @__PURE__ */i.jsx(AnswerCard,{card:e,options:s},e.key))}):null,g?/* @__PURE__ */i.jsx(AnswerRecordCards,{message:e}):null,g?/* @__PURE__ */i.jsx(ServerCardsSlot,{message:e}):null,b.length>0?/* @__PURE__ */i.jsxs(r.View,{style:h.cards,accessibilityLabel:XC(b.length),children:[
|
|
302
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:h.label,children:vf.sourcesHeading}),b.map(e=>{let t=e.url;/* @__PURE__ */
|
|
303
|
+
return i.jsx(AnswerCard,{card:{key:e.key,title:e.title,...e.meta!==null?{meta:e.meta}:{},tile:{icon:/* @__PURE__ */i.jsx(SourceTileGlyph,{})},...f!==void 0&&t!==null?{onPress:()=>f(t)}:{}},options:s},e.key)})]}):null,g&&v!==null&&u!==void 0?/* @__PURE__ */i.jsxs(r.View,{style:[h.feedback,s?.styles?.feedback],children:[
|
|
304
|
+
/* @__PURE__ */i.jsx(FeedbackChip,{label:v.helpful,on:a==="up",onPress:()=>u("up"),styles:h,host:s?.styles}),
|
|
305
|
+
/* @__PURE__ */i.jsx(FeedbackChip,{label:v.notHelpful,on:a==="down",onPress:()=>u("down"),styles:h,host:s?.styles})]}):null,g?d(v===null):null]})}function SourceTileGlyph(){let e=useEverfurTheme();/* @__PURE__ */
|
|
306
|
+
return i.jsx(BookGlyph,{size:FS,color:e.color.linkInk,strokeWidth:1.5})}function FeedbackChip({label:e,on:t,onPress:n,styles:l,host:o}){/* @__PURE__ */
|
|
307
|
+
return i.jsx(r.Pressable,{onPress:n,accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{selected:t},style:[l.chip,o?.feedbackChip,t?l.chipOn:null],hitSlop:(zm-TS)/2,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:[l.chipText,o?.feedbackChipText],children:e})})}function CardsFollowUps({prompts:e,onSelectPrompt:n,label:l,actions:o,options:s}){let{theme:a,styles:u}=NS(),c=my(),d=t.useMemo(()=>c===null?null:kC()?.ask.followUpStyles(c.paint)??null,[c]);if(e.length===0&&o.length===0)return null;let f=s?.styles,h=l??vf.followUpsHeadingNative;/* @__PURE__ */
|
|
308
|
+
return i.jsxs(r.View,{style:[u.followUps,d?.followUps,f?.followUps],accessibilityLabel:h,testID:"everfur-cards-follow-ups",children:[
|
|
309
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:[u.label,d?.label,f?.followUpsLabel],accessibilityRole:"header",children:h}),o.map(e=>/* @__PURE__ */i.jsxs(r.Pressable,{onPress:()=>{ch(e.onPress)},accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:LS,style:[u.row,u.rowAction,d?.row,f?.followUp,f?.followUpAction],children:[e.icon??null,
|
|
310
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:[u.rowText,u.rowTextAction,d?.rowText,f?.followUpText,f?.followUpActionText],children:e.label}),
|
|
311
|
+
/* @__PURE__ */i.jsx(Chevron,{options:s,color:c?.paint.accent??a.color.text.primary})]},`action:${e.key}`)),e.map(e=>/* @__PURE__ */i.jsxs(r.Pressable,{onPress:()=>n(e),accessibilityRole:"button",accessibilityLabel:e,hitSlop:LS,style:[u.row,d?.row,f?.followUp],children:[
|
|
312
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:[u.rowText,d?.rowText,f?.followUpText],children:e}),
|
|
313
|
+
/* @__PURE__ */i.jsx(Chevron,{options:s,color:c?.paint.accent??a.color.linkInk})]},e))]})}function CardsByline({label:e}){let{styles:t}=NS();/* @__PURE__ */
|
|
314
|
+
return i.jsx(r.View,{style:t.byline,children:/* @__PURE__ */i.jsx(Text,{tier:"compact",style:t.bylineText,children:e})})}function $S(e){let t=e.color,n=e.space,l={...face(e,"mono"),fontSize:wS,textTransform:"uppercase",color:t.text.muted},i={borderWidth:1,borderColor:t.borderRingCream},o={borderWidth:1,borderColor:Hi(t.text.primary,BS)??t.borderRingCream},s={shadowColor:t.text.primary,shadowOffset:{width:0,height:1},shadowOpacity:VS,shadowRadius:2,elevation:1},a=textRole(e,"message"),chipInk=Dg(e.slots.chip);return r.StyleSheet.create({answer:{gap:n.md,alignSelf:"stretch"},byline:{flexDirection:"row",alignItems:"center",gap:10,minHeight:14},bylineText:{...l,letterSpacing:wS*.06,flexShrink:1},body:{gap:10},paragraph:{...face(e,"regular"),fontSize:a.fontSize,lineHeight:Math.round(a.lineHeight),color:t.text.primary},list:{gap:4},listItem:{flexDirection:"row",gap:n.sm,paddingLeft:n.xs},listText:{flex:1},bold:face(e,"bold"),italic:{fontStyle:"italic"},code:face(e,"mono"),cards:{gap:n.sm},card:{flexDirection:"row",alignItems:"center",gap:n.md,padding:CS,borderRadius:kS,backgroundColor:t.surface,...o,...s,minHeight:zm,...Mg(e.slots.card)},tile:{width:SS,height:SS,borderRadius:jS,backgroundColor:Hi(t.linkInk,HS)??t.surfaceSubtle,alignItems:"center",justifyContent:"center",overflow:"hidden"},tileImage:{width:SS,height:SS},cardWords:{flex:1,minWidth:0},cardTitle:{...face(e,"bold"),fontSize:_S,lineHeight:Math.round(_S*1.25),color:t.text.primary,...Dg(e.slots.card)},cardMeta:{...l,letterSpacing:wS*.04,marginTop:3},stat:{...face(e,"mono"),fontSize:RS,color:t.text.primary},statUnit:{...face(e,"mono"),fontSize:wS+2,color:t.text.muted},pill:{minHeight:MS,paddingHorizontal:10,borderRadius:e.radius.pill,backgroundColor:t.surfaceSubtle,justifyContent:"center",flexShrink:1,maxWidth:US},pillText:{...face(e,"bold"),fontSize:AS,color:t.text.primary},feedback:{flexDirection:"row",flexWrap:"wrap",gap:n.sm,alignItems:"center"},chip:{minHeight:TS,paddingHorizontal:12,borderRadius:e.radius.pill,...i,justifyContent:"center"},chipOn:{backgroundColor:t.surfaceSubtle},chipText:{...Dw(e),fontSize:IS,color:t.text.primary,...chipInk},followUps:{gap:n.sm,alignSelf:"stretch",marginTop:n.xs},label:{...face(e,"bold"),fontSize:OS,lineHeight:Math.round(OS*1.5),color:t.text.muted,marginTop:2},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:DS,paddingTop:11,paddingBottom:11,paddingRight:12,paddingLeft:14,borderRadius:zS,backgroundColor:t.surface,...o},rowAction:{},rowText:{...Dw(e),flex:1,fontSize:PS,lineHeight:Math.round(PS*1.3),color:t.linkInk},rowTextAction:{color:t.text.primary}})}var WS=/* @__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"})}),qS=/* @__PURE__ */Object.freeze(ir.map(e=>/* @__PURE__ */Object.freeze({answer:e,label:WS.answers[e]})));function GS(e,r){let[n,l]=t.useState(null),[i,o]=t.useState(null),[s,a]=t.useState(null),u=t.useCallback(t=>{r!==null&&(l(t),o(null),r(e.caseId,t).then(e=>{l(null),e.ok?a(t):o(e.error)}))},[r,e.caseId]),c=s??e.answer;return{answer:c,answerable:!isCheckinSettled(e),escalated:c==="worse",pending:n,error:i,choose:u}}var KS=44,YS=.6,QS=/* @__PURE__ */Object.freeze({caseId:"",answer:null,resolutionText:null,status:null});function CheckinCard({message:e,checkin:n,onAnswer:l,petRef:o,onFindVet:s,vet:a,onLayout:u,onOpen:c}){let d=useEverfurTheme(),f=t.useMemo(()=>ZS(d),[d]),h=GS(n??QS,n===null?null:l),p=h.answer!==null||h.pending!==null,g=n!==null&&l!==null&&h.answerable,m=n===null?null:VC(n.openedAt,HC(e));/* @__PURE__ */
|
|
315
|
+
return i.jsxs(r.View,{style:f.card,accessibilityLabel:WS.eyebrow,onLayout:u,children:[
|
|
316
|
+
/* @__PURE__ */i.jsxs(r.View,{style:f.head,children:[
|
|
317
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:f.eyebrow,children:WS.eyebrow}),m!==null?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:f.headDay,children:xf(WS.day,{day:m})}):null]}),c?/* @__PURE__ */i.jsx(r.Pressable,{onPress:c,accessibilityRole:"button",accessibilityLabel:e.text,style:f.open,children:/* @__PURE__ */i.jsx(Text,{style:[f.question,f.openText],children:e.text})}):/* @__PURE__ */i.jsx(Text,{style:f.question,accessibilityRole:"text",children:e.text}),g?/* @__PURE__ */i.jsx(r.View,{style:[f.row,h.pending?f.rowPending:null],children:qS.map(({answer:e,label:t})=>{let n=(h.pending??h.answer)===e;/* @__PURE__ */
|
|
318
|
+
return i.jsx(r.Pressable,{onPress:()=>h.choose(e),disabled:p,accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:n,disabled:p,busy:h.pending===e},style:[f.pill,n?f.pillSelected:null],children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:[f.pillLabel,n?f.pillLabelSelected:null],children:t})},e)})}):null,h.answer!==null?/* @__PURE__ */i.jsx(Text,{style:f.logged,children:WS.logged}):null,h.escalated?/* @__PURE__ */i.jsx(CheckinFindVet,{petRef:o??null,onFindVet:s,vet:a,styles:f}):null,n?.resolutionText?/* @__PURE__ */i.jsx(Text,{style:f.resolution,children:n.resolutionText}):null,h.error?/* @__PURE__ */i.jsx(Text,{style:f.error,accessibilityRole:"alert",children:h.error.displayMessage}):null]})}function CheckinFindVet({petRef:e,onFindVet:t,vet:n,styles:l}){return useVetVisit(Jk(e,n)).available&&e!==null?/* @__PURE__ */i.jsx(VetVisitButtonCore,{entry:"chat",petRef:e,label:WS.findVet,...n?.returnTo!==void 0?{returnTo:n.returnTo}:{},...n?.usState!==void 0?{usState:n.usState}:{},...n?.prefer!==void 0?{prefer:n.prefer}:{},style:l.findVet,labelStyle:l.findVetLabel}):t===void 0?null:/* @__PURE__ */i.jsx(r.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:WS.findVet,style:l.findVet,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:l.findVetLabel,children:WS.findVet})})}function ZS(e){let t=e.color,n=e.space,l=e.radius,i=e.type,o=Fg(e.slots.card),s=Dg(o);return r.StyleSheet.create({card:{maxWidth:"92%",padding:n.md,gap:n.sm,borderRadius:l.lg,backgroundColor:t.brandSoft,borderWidth:r.StyleSheet.hairlineWidth,borderColor:t.brandBorder,...Mg(o,r.StyleSheet.hairlineWidth)},head:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:n.sm},eyebrow:{...face(e,"regular"),color:t.text.secondary,fontSize:i.size.caption,letterSpacing:i.letterSpacing.eyebrow,textTransform:"uppercase",...s},headDay:{...face(e,"bold"),color:t.text.primary,fontSize:i.size.caption,letterSpacing:i.letterSpacing.eyebrow,textTransform:"uppercase",...s},question:{...face(e,"regular"),color:t.text.primary,fontSize:i.size.body,lineHeight:i.size.body*i.lineHeight.normal,...s},open:{minHeight:KS,justifyContent:"center"},openText:{textDecorationLine:"underline"},row:{flexDirection:"row",gap:n.sm,marginTop:n.xs},rowPending:{opacity:YS},pill:{flex:1,minHeight:KS,alignItems:"center",justifyContent:"center",paddingHorizontal:n.md,borderRadius:l.pill,borderWidth:1,borderColor:t.controlEdge,backgroundColor:t.surface},pillSelected:{backgroundColor:t.brand,borderColor:t.brandInk},pillLabel:{...face(e,"regular"),color:t.text.primary,fontSize:i.size.body},pillLabelSelected:{color:t.onPrimary},logged:{...face(e,"regular"),color:t.text.secondary,fontSize:i.size.caption,...s},resolution:{...face(e,"regular"),color:t.text.primary,fontSize:i.size.body,lineHeight:i.size.body*i.lineHeight.normal,...s},error:{...face(e,"regular"),color:t.danger,fontSize:i.size.caption},findVet:{alignSelf:"stretch",minHeight:KS,alignItems:"center",justifyContent:"center",borderRadius:l.pill,borderWidth:1.5,borderColor:t.controlEdge,backgroundColor:t.surface},findVetLabel:{...face(e,"bold"),color:t.brandInk,fontSize:i.size.body}})}var XS=244,JS=8,ej=13,tj=14,rj=.3,nj=-.24,lj=22,ij=10,oj=15;function CitationCards({citations:e,onOpenUrl:n}){let l=useEverfurTheme(),o=t.useMemo(()=>sj(l),[l]),s=t.useMemo(()=>QC(e),[e]),[a,u]=t.useState(false);if(s.length===0)return null;let c=s.length;/* @__PURE__ */
|
|
319
|
+
return i.jsxs(r.View,{style:o.block,children:[
|
|
320
|
+
/* @__PURE__ */i.jsxs(PressScale,{accessibilityRole:"button",accessibilityLabel:JC(c,a),accessibilityState:{expanded:a},containerStyle:o.toggleSlot,style:o.togglePill,onPress:()=>u(e=>!e),children:[
|
|
321
|
+
/* @__PURE__ */i.jsx(BookGlyph,{size:ej,color:l.color.brandInk,strokeWidth:1.5}),
|
|
322
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:o.toggleLabel,children:XC(c)}),
|
|
323
|
+
/* @__PURE__ */i.jsx(ChevronGlyph,{size:ej,color:l.color.brandInk,strokeWidth:1.5,direction:a?"up":"down"})]}),a?/* @__PURE__ */i.jsx(Deck,{cards:s,styles:o,open:n}):null]})}function Deck({cards:e,styles:t,open:n}){let l=sg(),o=mg(l.citationsInMs,{risePx:l.citationsRisePx});/* @__PURE__ */
|
|
324
|
+
return i.jsx(r.Animated.View,{style:o,children:/* @__PURE__ */i.jsx(r.ScrollView,{horizontal:true,nestedScrollEnabled:true,showsHorizontalScrollIndicator:false,contentContainerStyle:t.row,children:e.map(e=>/* @__PURE__ */i.jsx(Card,{card:e,styles:t,open:n},e.key))})})}function Card({card:e,styles:t,open:n}){let l=useEverfurTheme(),o=e.url!==null&&n!==void 0,s=eS(o?e:{...e,url:null}),a=/* @__PURE__ */i.jsxs(i.Fragment,{children:[
|
|
325
|
+
/* @__PURE__ */i.jsxs(r.View,{style:t.cardHeader,children:[
|
|
326
|
+
/* @__PURE__ */i.jsx(r.View,{style:[t.tierDot,{backgroundColor:e.tierColor}]}),
|
|
327
|
+
/* @__PURE__ */i.jsx(Text,{style:[t.cardTitle,o?t.cardTitleLink:null],numberOfLines:2,children:e.title}),o?/* @__PURE__ */i.jsx(ArrowUpRightGlyph,{size:tj,color:l.color.linkInk,strokeWidth:1.5}):null]}),e.meta!==null?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:t.cardMeta,numberOfLines:1,children:e.meta}):null,e.excerpt!==null?/* @__PURE__ */i.jsx(Text,{style:t.cardExcerpt,numberOfLines:3,children:e.excerpt}):null]});if(e.url!==null&&n!==void 0){let r=e.url;/* @__PURE__ */
|
|
328
|
+
return i.jsx(PressScale,{accessibilityRole:"link",accessibilityLabel:s,style:t.card,onPress:()=>n(r),children:a})}/* @__PURE__ */
|
|
329
|
+
return i.jsx(r.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:s,style:t.card,children:a})}function sj(e){let t=e.color,n=e.space,l=e.radius,i=e.type.size,o=Dg(e.slots.card);return r.StyleSheet.create({block:{gap:n.sm},toggleSlot:{alignSelf:"flex-start",borderRadius:l.pill},togglePill:{flexDirection:"row",alignItems:"center",gap:n.xs+2,paddingHorizontal:n.md,paddingVertical:n.xs+2,borderRadius:l.pill,backgroundColor:t.brandSoft},toggleLabel:{...face(e,"monoBold"),fontSize:i.micro,lineHeight:i.micro,letterSpacing:rj,color:t.brandInk,textTransform:"uppercase"},row:{gap:n.sm,paddingRight:n.xl,paddingTop:n.xs},card:{width:XS,borderRadius:l.md,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,padding:n.md,gap:n.xs+2,...Mg(e.slots.card,1)},cardHeader:{flexDirection:"row",alignItems:"center",gap:n.sm},tierDot:{width:JS,height:JS,borderRadius:l.pill},cardTitle:{...headingFace(e,"bold"),flex:1,fontSize:i.bodyTight,lineHeight:lj,color:t.text.primary,letterSpacing:nj,...o},cardTitleLink:{color:t.linkInk},cardMeta:{...face(e,"monoMedium"),fontSize:i.nano,lineHeight:ij,letterSpacing:e.type.letterSpacing.monoWide,color:t.text.metaCool,textTransform:"uppercase",...o},cardExcerpt:{...face(e,"regular"),fontSize:i.tiny,lineHeight:oj,color:t.text.muted,...o}})}var aj=15,uj=44,cj=16,dj=/* @__PURE__ */Object.freeze({up:"0deg",neutral:"270deg",down:"180deg"});function MessageFooter({message:e,onCopy:n,sentiment:l=null,onSentiment:o,note:s=null}){let a=useEverfurTheme(),u=t.useMemo(()=>fj(a),[a]),c=sg(),d=e.role==="user",f=my(),h=t.useMemo(()=>f?null:UC(e.createdAt),[f,e.createdAt]),p=n!==void 0&&e.role!=="vet"&&e.text.length>0,g=e.role==="assistant"&&o!==void 0&&e.responseId!==void 0,[m,b]=t.useState(false),y=t.useRef(null);t.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);let v=()=>{n!==void 0&&(hh(n,e.text),b(true),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{b(false),y.current=null},c.copiedMs))};return h===null&&!p&&!g?null:/* @__PURE__ */i.jsxs(r.View,{style:u.wrap,children:[
|
|
330
|
+
/* @__PURE__ */i.jsxs(r.View,{style:[u.row,d?u.rowUser:u.rowAssistant],children:[h!==null?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:u.timestamp,children:h}):null,p?/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:m?vf.copied:d?vf.copyUserMessage:vf.copyAssistantMessage,onPress:v,style:u.iconHit,children:m?/* @__PURE__ */i.jsx(CheckGlyph,{size:aj,color:a.color.success,strokeWidth:2}):/* @__PURE__ */i.jsx(CopyGlyph,{size:aj,color:a.color.text.timestamp,strokeWidth:1.5})}):null,g?wx.map(({sentiment:e,label:t})=>/* @__PURE__ */i.jsx(r.Pressable,{accessibilityRole:"button",accessibilityLabel:t,accessibilityState:{selected:l===e},onPress:()=>o?.(e),style:u.iconHit,children:/* @__PURE__ */i.jsx(ThumbGlyph,{size:aj,color:l===e?a.color.sentiment[e]:a.color.text.timestamp,active:l===e,rotate:dj[e],strokeWidth:1.5})},e)):null]}),s==="thanks"?/* @__PURE__ */i.jsx(Text,{style:u.thanks,accessibilityLiveRegion:"polite",children:vf.feedbackThanks}):null,s==="failed"?/* @__PURE__ */i.jsxs(i.Fragment,{children:[
|
|
331
|
+
/* @__PURE__ */i.jsx(Text,{style:u.failed,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:vf.feedbackFailed}),
|
|
332
|
+
/* @__PURE__ */i.jsx(AnnounceLine,{line:vf.feedbackFailed})]}):null]})}function fj(e){let t=e.type;return r.StyleSheet.create({wrap:{gap:4},row:{flexDirection:"row",alignItems:"center",gap:10,minHeight:cj,paddingTop:6},rowAssistant:{alignSelf:"flex-start"},rowUser:{alignSelf:"flex-end"},timestamp:{...face(e,"monoMedium"),fontSize:t.size.nano,lineHeight:t.size.nano+2,color:e.color.text.timestamp,textAlign:"center"},iconHit:{width:uj,height:uj,marginVertical:-28/2,alignItems:"center",justifyContent:"center"},thanks:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.text.secondary},failed:{...face(e,"regular"),fontSize:t.size.caption,lineHeight:t.size.caption*t.lineHeight.normal,color:e.color.danger}})}var hj=16,pj=10,gj=12,mj=10,bj=2,yj=.06,vj=34,xj=9,wj=10.5,kj=.06,Cj=15,Sj=19.5,jj=14,_j=19.6;function OpeningCard({card:e,onLayout:n}){let l=useEverfurTheme(),o=t.useMemo(()=>Rj(l),[l]),s=e.styles;/* @__PURE__ */
|
|
333
|
+
return i.jsxs(r.View,{testID:"everfur-opening-card",onLayout:n,accessible:true,accessibilityLabel:[e.kicker,e.title,e.body].filter(e=>e!==void 0).join(", "),style:[o.card,s?.card],children:[e.icon!==void 0?/* @__PURE__ */i.jsx(r.View,{style:[o.icon,s?.icon],children:e.icon}):null,
|
|
334
|
+
/* @__PURE__ */i.jsxs(r.View,{style:o.words,children:[
|
|
335
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:[o.kicker,s?.kicker],children:e.kicker}),
|
|
336
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:[o.title,s?.title],children:e.title}),e.body!==void 0?/* @__PURE__ */i.jsx(Text,{style:[o.body,s?.body],children:e.body}):null]})]})}function Rj(e){let t=e.color;return r.StyleSheet.create({card:{flexDirection:"row",alignItems:"flex-start",gap:mj,paddingVertical:pj,paddingHorizontal:gj,alignSelf:"stretch",borderRadius:hj,backgroundColor:t.surface,borderWidth:1,borderColor:Hi(t.text.primary,yj)??t.borderRingCream},icon:{flexShrink:0,width:vj,height:vj,borderRadius:xj,backgroundColor:t.highlight,alignItems:"center",justifyContent:"center",overflow:"hidden"},words:{flex:1,minWidth:0,gap:bj},kicker:{...face(e,"mono"),fontSize:wj,letterSpacing:wj*kj,textTransform:"uppercase",color:t.text.muted},title:{...face(e,"bold"),fontSize:Cj,lineHeight:Sj,color:t.text.primary},body:{...face(e,"regular"),fontSize:jj,lineHeight:_j,color:t.text.secondary}})}var Tj="#10462E",Ij="Book a video visit",zj="#000000",Pj="#83E0B4",Ej=/* @__PURE__ */Object.freeze([
|
|
336
337
|
/* @__PURE__ */Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
|
|
337
|
-
/* @__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:
|
|
338
|
-
/* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:
|
|
339
|
-
/* @__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
|
|
340
|
-
return Object.freeze(
|
|
338
|
+
/* @__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:Pj,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),
|
|
339
|
+
/* @__PURE__ */Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:Tj,brandEdge:true,borderWidth:1}),
|
|
340
|
+
/* @__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 Oj(e,t){return e?null:{fill:t.fill,ink:t.ink}}var Aj=8;function Mj(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&t.length<=64&&!/[;{}<>]/u.test(t)?t:null}function Fj(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(t.length>=Aj)break;if(r===null||typeof r!="object"||typeof r.label!="string")continue;let e=r.label.trim();if(e.length===0)continue;let n=typeof r.prompt=="string"&&r.prompt.trim().length>0?r.prompt.trim():e,l=Mj(r.tint);t.push(/* @__PURE__ */Object.freeze({id:`starter-${t.length}`,label:e,prompt:n,tint:l,ink:l===null?null:Mj(r.ink)}))}return t.length>0?/* @__PURE__ */Object.freeze(t):null}var Dj=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function Lj(e){return e==null?e:e.replace(Dj,"").trim()}var Bj=/* @__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 Vj(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return Bj.has(t)}function Hj(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}function Uj(e,t){let r=e?.trim();if(r===void 0||r==="")return Nj(t);let n=t?.name?.trim()||vf.emptyTitlePetFallback,l=n.charAt(0).toUpperCase()+n.slice(1);return r.replace(/\{(pet|petName)\}/g,(e,t,r)=>r===0?l:n)}function Nj(e){let t=e?.name?.trim()||vf.emptyTitlePetFallback;return xf(vf.emptyTitle,{petName:t})}function $j(e){let t=e.toLowerCase();return t===Hj("dog").toLowerCase()||t===Hj("cat").toLowerCase()}function Wj(e){let t=Lj(e);if(Vj(t))return null;let r=String(t).replace(/\s+/gu," ").trim();return $j(r)?null:r}function qj(e,t=Tj,r){let n=canonicalPetSpecies(e?.species),l=e?.name?.trim()||null,i=Wj(e?.breed),o=Ov(e?.ageYears),s=o===null?null:String(o),a=r?.vetPrepLabel?.trim()||null;/* @__PURE__ */
|
|
341
|
+
return Object.freeze(Ej.flatMap(e=>{let r=e.intent==="vet_report"&&a!==null?a:e.label,o=r.includes("{breed}"),u=r.includes("{ageYears}"),c=e.fallbackLabel!==void 0&&(o&&!i||u&&!s)&&e.fallbackLabel?e.fallbackLabel:r;if(c.includes("{breed}")&&i===null||c.includes("{ageYears}")&&s===null||n===null&&(c.includes("{species}")||c.includes("{petName}")&&l===null))return[];let d=xf(c,{petName:l??(n==="cat"?"my cat":"my dog"),breed:i??"",species:n??"",ageYears:s??""}),f=!l&&c.startsWith("{petName}")?d.charAt(0).toUpperCase()+d.slice(1):d;return[/* @__PURE__ */Object.freeze({id:e.id,intent:e.intent,label:f,background:e.background,borderColor:e.brandEdge===true?t:e.borderColor,borderWidth:e.borderWidth})]}))}var Gj=44,Kj=0,Yj={top:3,bottom:3},Qj=1,Zj=.28,Xj=2,Jj=2,e_=1.3,t_=-.015,r_=/* @__PURE__ */Object.freeze([
|
|
341
342
|
/* @__PURE__ */Object.freeze({tint:"#FFE7A1",ink:"#262523"}),
|
|
342
343
|
/* @__PURE__ */Object.freeze({tint:"#C8F4F8",ink:"#262523"}),
|
|
343
344
|
/* @__PURE__ */Object.freeze({tint:"#DDEFC4",ink:"#262523"}),
|
|
344
|
-
/* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:n,onSend:
|
|
345
|
-
return
|
|
346
|
-
/* @__PURE__ */
|
|
347
|
-
return
|
|
348
|
-
return
|
|
349
|
-
return
|
|
350
|
-
return
|
|
351
|
-
/* @__PURE__ */
|
|
345
|
+
/* @__PURE__ */Object.freeze({tint:"#FFD8D6",ink:"#262523"})]);function QuickPrompts({pet:e,petRef:n,onSend:l,onVetPrep:o,vet:s,starterPrompts:a,emptyState:u,centered:c=false}){let d=useEverfurTheme(),f=t.useMemo(()=>n_(d),[d]),h=t.useMemo(()=>Fj(a),[a]),p=t.useMemo(()=>h!==null?h.map(e=>({prompt:{id:e.id,intent:"send",label:e.label,background:e.tint??d.color.highlight,borderColor:"transparent",borderWidth:1},send:e.prompt,paint:e.tint===null?null:{fill:e.tint,ink:e.ink??d.color.text.primary}})):qj(e,d.color.brandInk,{vetPrepLabel:Ij}).map(e=>({prompt:e,send:e.label,paint:null})),[h,e,d.color.brandInk,d.color.highlight,d.color.text.primary]),g=my(),m=u?.chipTints!==void 0,b=t.useMemo(()=>g===null?null:g.paint.pastels.map(e=>({tint:e,ink:g.paint.ink})),[g]),y=t.useMemo(()=>(u?.chipTints??b??(d.brightness==="light"?r_:[])).filter(e=>typeof e.tint=="string"&&e.tint.trim()!==""),[u?.chipTints,b,d.brightness]),v=t.useMemo(()=>y.length===0?p:p.map((e,t)=>{if(e.paint!==null)return e;let r=y[t%y.length];return{...e,paint:{fill:r.tint,ink:r.ink??d.color.text.primary},...m||b!==null?{}:{cycleDefault:true}}}),[p,y,m,b,d.color.text.primary]),x=t.useMemo(()=>Oj(zv(d),{fill:d.color.highlight,ink:d.color.onHighlight}),[d]),w=t.useMemo(()=>({fill:d.color.highlight,ink:d.color.onHighlight}),[d.color.highlight,d.color.onHighlight]),k=Uj(u?.title,e),C=Bx(),S=g!==null?null:C,j=Vx(),_=g!==null?/* @__PURE__ */i.jsx(Text,{tier:"heading",style:[f.title,f.tabsTitle,{color:g.paint.ink}],accessibilityRole:"header",children:k}):S!==null&&j!==null?/* @__PURE__ */i.jsx(j.Title,{text:k,style:[f.title,S.text(".serif",".ask-empty h2"),f.centerText],measureCh:j.titleCh}):/* @__PURE__ */i.jsx(Text,{tier:"heading",style:c?[f.title,f.centerText]:f.title,accessibilityRole:"header",children:k});/* @__PURE__ */
|
|
346
|
+
return i.jsxs(r.View,{style:S!==null?f.homeBlock:f.block,children:[_,
|
|
347
|
+
/* @__PURE__ */i.jsx(r.View,{style:g!==null?[f.list,f.tabsList]:S!==null?[f.list,f.listCentered,S.view(".ask-chips",".ask-empty .ask-chips")]:c?[f.list,f.listCentered]:f.list,accessibilityLabel:vf.suggestions,children:v.map(({prompt:t,send:r,paint:a,cycleDefault:u},d)=>/* @__PURE__ */i.jsx(Chip,{prompt:t,send:r,themed:a??(h!==null?w:x),index:d,petRef:n,onSend:l,onVetPrep:o,vet:s,pet:e,styles:f,tinted:a!==null&&u!==true,soft:a!==null,centered:c,tabs:g!==null},t.id))})]})}function Chip({prompt:e,send:t,themed:n,index:l,pet:o,petRef:s,onSend:a,onVetPrep:u,vet:c,styles:d,tinted:f,soft:h,centered:p,tabs:g}){let m=sg(),b=mg(m.followUpInMs,{delayMs:ig(m,l),risePx:m.promptRisePx}),y=Bx(),v=g?null:y,x=g?[d.chipNoEdge,d.tabsChip]:v!==null?[d.chipHome,v.view(".chip")]:p&&h?d.chipNoEdge:d.chipEdge,w={backgroundColor:n?.fill??e.background},k=d.chipSlot===null?w:f?{...d.chipSlot,...w}:{...w,...d.chipSlot},C=g?[d.chipLabel,d.tabsChipLabel]:v!==null?[d.chipLabel,v.text(".chip")]:p?[d.chipLabel,d.centerText]:[d.chipLabel],S=v!==null?Yj:Kj,j=n===null?d.chipSlotLabel===null?C:[...C,d.chipSlotLabel]:f?[...C,...d.chipSlotLabel===null?[]:[d.chipSlotLabel],{color:n.ink}]:[...C,{color:n.ink},...d.chipSlotLabel===null?[]:[d.chipSlotLabel]];return e.intent==="vet_report"?u!==void 0?/* @__PURE__ */i.jsx(r.Animated.View,{style:b,children:/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:S,style:[d.chip,x,k],onPress:()=>{ch(u,o)},children:/* @__PURE__ */i.jsx(Text,{tier:"compact",style:j,children:e.label})})}):s===null?null:/* @__PURE__ */i.jsx(r.Animated.View,{style:b,children:/* @__PURE__ */i.jsx(VetVisitButtonCore,{entry:"chat",petRef:s,label:e.label,...c?.returnTo!==void 0?{returnTo:c.returnTo}:{},...c?.usState!==void 0?{usState:c.usState}:{},...c?.prefer!==void 0?{prefer:c.prefer}:{},style:[d.chip,x,k],labelStyle:j})}):/* @__PURE__ */i.jsx(r.Animated.View,{style:b,children:/* @__PURE__ */i.jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:e.label,hitSlop:S,style:[d.chip,x,k],onPress:()=>a(t),children:/* @__PURE__ */i.jsx(Text,{tier:"compact",style:j,children:e.label})})})}function n_(e){let t=Fg(e.slots.chip),r=Dg(t);return{chipSlot:t===void 0?null:Mg(t,Qj),chipSlotLabel:r.color===void 0?null:r,...l_(e)}}function l_(e){let t=e.color,n=e.space,l=e.type;return r.StyleSheet.create({block:{gap:n.lg,alignItems:"stretch",width:"100%"},homeBlock:{alignItems:"stretch",width:"100%"},chipHome:{borderWidth:0,minHeight:0},title:{...headingFace(e,"medium"),fontSize:l.size.heading,lineHeight:Math.round(l.size.heading*l.lineHeight.snug),color:t.brandInk,letterSpacing:l.size.heading*t_,textAlign:"left"},list:{width:"100%",flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-start",gap:n.sm+Xj},listCentered:{flexDirection:"column",flexWrap:"nowrap",alignItems:"stretch"},centerText:{textAlign:"center"},chipNoEdge:{borderWidth:Qj,borderColor:"transparent"},tabsTitle:{...headingFace(e,"bold"),fontWeight:"800",fontSize:26,lineHeight:32,letterSpacing:0,textAlign:"center",maxWidth:260,alignSelf:"center"},tabsList:{justifyContent:"center",gap:10},tabsChip:{paddingHorizontal:16,paddingVertical:9,minHeight:0},tabsChipLabel:{fontSize:14,lineHeight:20,textAlign:"center"},chip:{borderRadius:e.radius.pill,paddingHorizontal:n.lg+Jj,paddingVertical:n.sm,minHeight:Gj,minWidth:0,alignItems:"center",justifyContent:"center",maxWidth:"100%"},chipEdge:{borderWidth:Qj,borderColor:Hi(t.brandInk,Zj)??t.borderRingCream},chipLabel:{...face(e,"bold"),fontSize:l.size.bodyTight,lineHeight:Math.round(l.size.bodyTight*e_),color:zj,textAlign:"left"}})}var i_=1e3,o_=150,s_=.25,a_=.5,u_=3;function TypingIndicator({petName:e=null,inline:n=false}){let{theme:l,styles:o}=wb(),s=l.motion.reducedMotion,a=kf(vf.reading,e),u=t.useRef(Array.from({length:u_},()=>new r.Animated.Value(0))).current;return t.useEffect(()=>{if(s)return;let e=u.map((e,t)=>r.Animated.loop(r.Animated.sequence([r.Animated.delay(t*o_),r.Animated.timing(e,{toValue:1,duration:i_*.4,useNativeDriver:true}),r.Animated.timing(e,{toValue:0,duration:i_*.6,useNativeDriver:true}),r.Animated.delay((u_-t-1)*o_)])));for(let t of e)t.start();return()=>{for(let t of e)t.stop()}},[s,u]),/* @__PURE__ */i.jsx(r.View,{style:n?o.readingInline:o.readingBox,accessible:true,accessibilityRole:"text",accessibilityLabel:a,accessibilityLiveRegion:"polite",accessibilityState:{busy:true},children:u.map((e,t)=>/* @__PURE__ */i.jsx(r.Animated.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",style:[n?o.readingDotInline:o.readingDot,s?{opacity:a_}:{opacity:e.interpolate({inputRange:[0,1],outputRange:[s_,1]}),transform:[{translateY:e.interpolate({inputRange:[0,1],outputRange:[0,-3]})}]}]},t))})}function c_(e,t,r){let n=e-r,l=t!=null?Math.min(n,t):n;return Math.max(0,l)}function d_(e){let t=e.length-1,r=e[t];if(r===void 0||r.role!=="assistant")return null;let n=e[t-1];return{assistantIndex:t,userIndex:n!==void 0&&n.role==="user"?t-1:null}}function f_(e,t,r){let n=Math.max(0,r),l=e===null?n:Math.min(Math.max(0,e),n);return l>t+1?l:null}var h_=16;function p_(e,r,n=null){let l=t.useRef(null),i=t.useRef(true),o=t.useRef(r),s=t.useRef(0),a=t.useRef(0),u=t.useRef(0),c=t.useRef(/* @__PURE__ */new Map),d=t.useRef(null),f=t.useRef(false),h=e[0]?.id??null,p=t.useRef(h),g=t.useRef(null);t.useEffect(()=>{let t=p.current;if(p.current=h,t===null||t===h||(g.current=null,i.current||!e.some(e=>e.id===t)))return;let r=c.current.get(t);r!==void 0&&(g.current={id:t,top:r,offset:s.current})},[h,e]);let m=d_(e),b=m===null?null:e[m.assistantIndex]?.id??null,y=m===null||m.userIndex===null?null:e[m.userIndex]?.id??null,v=t.useCallback(()=>{let e=l.current;if(e===null||!i.current||a.current===0)return;let t=null;if(b!==null){let e=c.current.get(b);if(e===void 0)return;let r=y===null?null:c.current.get(y)??null;t=c_(e,r,96)}let r=f_(t,s.current,u.current-a.current);if(r!==null&&(s.current=r,e.scrollTo({y:r,animated:false})),!f.current||d.current===null)return;let n=f_(d.current+h_-a.current,s.current,u.current-a.current);n!==null&&(s.current=n,e.scrollTo({y:n,animated:false}))},[b,y]);t.useEffect(()=>{f.current=n!==null,n===null&&(d.current=null),v()},[n,v]),t.useEffect(()=>{r&&!o.current&&(i.current=true,f.current=false),o.current=r,v()},[e,r,v]);let x=t.useCallback(e=>{a.current=e.nativeEvent.layout.height,v()},[v]),w=t.useCallback((e,t)=>{u.current=t,a.current>0&&(s.current=Math.min(s.current,Math.max(0,t-a.current))),v()},[v]),k=t.useCallback(e=>{s.current=e.nativeEvent.contentOffset.y},[]),C=t.useCallback(()=>{i.current=false,f.current=false},[]),S=t.useCallback(e=>{let{contentOffset:t,contentSize:r,layoutMeasurement:n}=e.nativeEvent;s.current=t.y,i.current=r.height-t.y-n.height<=24},[]),j=t.useCallback(e=>t=>{let r=t.nativeEvent.layout.y;c.current.set(e,r);let n=g.current;if(n!==null&&n.id===e&&r!==n.top){g.current=null;let e=Math.max(0,n.offset+r-n.top);s.current=e,l.current?.scrollTo({y:e,animated:false})}(e===b||e===y)&&v()},[b,y,v]),_=t.useCallback(e=>{let{y:t,height:r}=e.nativeEvent.layout;d.current=t+r,v()},[v]);return{ref:l,onLayout:x,onContentSizeChange:w,onScroll:k,onScrollBeginDrag:C,onScrollEnd:S,rowLayout:j,asideLayout:_}}function g_(e,t,r){switch(e){case"loading":return r.renderPending?/* @__PURE__ */i.jsx(HostRender,{render:r.renderPending,fallback:/* @__PURE__ */i.jsx(LoadingState,{})}):/* @__PURE__ */i.jsx(LoadingState,{});case"empty":/* @__PURE__ */
|
|
348
|
+
return i.jsx(EmptyState,{pet:r.shownPet,petRef:t.petRef,onSelectPrompt:r.onSelectPrompt,onVetPrep:r.onVetPrep,vet:r.vet,top:r.threadTop,pendingCheckin:r.pendingCheckin??null,topCard:r.topCard,starterPrompts:r.starterPrompts,emptyState:r.emptyState,centered:r.emptyCentered===true,renderEmptyHeader:r.renderEmptyHeader});case"error":/* @__PURE__ */
|
|
349
|
+
return i.jsx(ErrorState,{error:t.error,onRetry:t.retryLast,onAddPet:r.onAddPet});case"populated":/* @__PURE__ */
|
|
350
|
+
return i.jsx(PopulatedState,{messages:t.messages,prompts:Mh(t,r.followUpPolicy),actions:r.answerCards?aS(t,r.answerCards):b_,answerCards:r.answerCards??null,threadTop:r.threadTop,pendingCheckin:r.pendingCheckin??null,threadAside:r.threadAside,threadAsideKey:r.threadAsideKey??null,onSelectPrompt:r.onSelectPrompt,isStreaming:t.isStreaming,onAnswerCheckin:t.petRef?t.answerCheckin:null,onCopy:r.onCopy,sentimentByMessage:t.sentimentByMessage,onSentiment:r.onSentiment,feedbackNote:r.feedbackNote,imagesByMessage:r.imagesByMessage,onPreview:r.onPreview,notice:r.notice,reconnecting:t.reconnecting===true,onRetry:t.retryLast,onStartNew:t.newConversation,petRef:t.petRef,onFindVet:r.onCheckinFindVet,vet:r.vet,onOpenUrl:r.onOpenUrl,petName:r.shownPet?.name??null,followUpLabel:r.followUpPolicy?.label,openingCard:r.openingCard,earlier:t.historyCursor?{loading:t.isLoadingHistory,load:t.loadOlderMessages}:null});default:return assertNever(e)}}function LoadingState(){let{theme:e,styles:n}=wb(),[l,o]=t.useState(false);return t.useEffect(()=>{let e=setTimeout(()=>o(true),Rm);return()=>clearTimeout(e)},[]),/* @__PURE__ */i.jsx(r.View,{style:n.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:vf.loading,children:l?/* @__PURE__ */i.jsx(r.ActivityIndicator,{color:e.color.brandInk}):null})}function EmptyState({pet:e,petRef:t,onSelectPrompt:n,onVetPrep:l,vet:o,top:s,topCard:a,pendingCheckin:u,starterPrompts:c,emptyState:d,centered:f,renderEmptyHeader:h}){let{styles:p}=wb(),g=Bx(),m=h===void 0?null:/* @__PURE__ */i.jsx(r.View,{testID:"everfur-empty-header",children:/* @__PURE__ */i.jsx(HostRender,{render:()=>h({ask:n}),fallback:null})});if(g!==null){let{minHeight:f,...h}=g.view(".ask-empty");/* @__PURE__ */
|
|
351
|
+
return i.jsxs(r.ScrollView,{contentContainerStyle:[h,p.homeEmpty],keyboardShouldPersistTaps:"handled",keyboardDismissMode:v_,nestedScrollEnabled:true,accessibilityLabel:vf.empty,children:[s!=null?/* @__PURE__ */i.jsx(r.View,{style:g.view(".ask-top"),children:s}):null,u,a??null,m,
|
|
352
|
+
/* @__PURE__ */i.jsx(r.View,{style:g.view(".ask-start"),children:/* @__PURE__ */i.jsx(QuickPrompts,{pet:e,petRef:t,onSend:n,onVetPrep:l,vet:o,starterPrompts:c,emptyState:d,centered:true})})]})}
|
|
352
353
|
/* @__PURE__ */
|
|
353
|
-
return
|
|
354
|
-
/* @__PURE__ */
|
|
355
|
-
/* @__PURE__ */
|
|
356
|
-
return
|
|
357
|
-
/* @__PURE__ */
|
|
358
|
-
/* @__PURE__ */
|
|
359
|
-
return
|
|
360
|
-
/* @__PURE__ */
|
|
361
|
-
return
|
|
362
|
-
return
|
|
363
|
-
/* @__PURE__ */
|
|
364
|
-
/* @__PURE__ */
|
|
365
|
-
/* @__PURE__ */
|
|
366
|
-
/* @__PURE__ */
|
|
367
|
-
/* @__PURE__ */
|
|
368
|
-
/* @__PURE__ */
|
|
369
|
-
/* @__PURE__ */
|
|
370
|
-
return
|
|
371
|
-
/* @__PURE__ */
|
|
372
|
-
/* @__PURE__ */
|
|
373
|
-
return
|
|
374
|
-
return
|
|
375
|
-
return
|
|
376
|
-
/* @__PURE__ */
|
|
354
|
+
return i.jsxs(r.ScrollView,{contentContainerStyle:p.emptyContent,keyboardShouldPersistTaps:"handled",keyboardDismissMode:v_,nestedScrollEnabled:true,accessibilityLabel:vf.empty,children:[s??null,u,a??null,m,
|
|
355
|
+
/* @__PURE__ */i.jsx(QuickPrompts,{pet:e,petRef:t,onSend:n,onVetPrep:l,vet:o,starterPrompts:c,emptyState:d,centered:f})]})}function FollowUps({prompts:e,onSelectPrompt:t,label:n}){let{styles:l}=wb();return e.length===0?null:/* @__PURE__ */i.jsxs(r.View,{style:l.followUps,children:[
|
|
356
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:l.followUpsHeading,accessibilityRole:"header",children:n??vf.followUpsHeadingNative}),e.map((e,r)=>/* @__PURE__ */i.jsx(FollowUpRow,{prompt:e,index:r,onSelectPrompt:t},e))]})}function FollowUpRow({prompt:e,index:t,onSelectPrompt:n}){let{theme:l,styles:o}=wb(),s=sg(),a=mg(s.followUpInMs,{delayMs:ig(s,t)});/* @__PURE__ */
|
|
357
|
+
return i.jsx(r.Animated.View,{style:a,children:/* @__PURE__ */i.jsxs(PressScale,{onPress:()=>n(e),accessibilityRole:"button",accessibilityLabel:e,containerStyle:[o.followUpSlot,t>0?o.followUpSlotRuled:null],style:o.followUpRow,children:[
|
|
358
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:o.followUpText,children:e}),
|
|
359
|
+
/* @__PURE__ */i.jsx(PlusGlyph,{size:x_,color:l.slots.chip?.textColor??l.color.text.muted,strokeWidth:1.75})]})})}function ErrorState({error:e,onRetry:t,onAddPet:n}){let{styles:l}=wb(),o=Uh(e)?fh(n):void 0,s=_h(e);/* @__PURE__ */
|
|
360
|
+
return i.jsxs(r.View,{style:l.centered,accessible:true,accessibilityRole:"alert",children:[s!==null?/* @__PURE__ */i.jsx(Text,{style:l.errorText,testID:"everfur-chat-cap-reached",children:s.reached}):null,
|
|
361
|
+
/* @__PURE__ */i.jsx(Text,{style:l.errorText,children:e.displayMessage}),s!==null&&s.guidance!==null?/* @__PURE__ */i.jsx(Text,{style:l.errorText,testID:"everfur-chat-cap-guidance",children:s.guidance}):null,o!==void 0?/* @__PURE__ */i.jsx(r.Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:vf.addPet,style:l.retryButton,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:l.retryLabel,children:vf.addPet})}):null,e.retryable?/* @__PURE__ */i.jsx(r.Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:vf.retry,style:l.retryButton,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:l.retryLabel,children:vf.retry})}):null]})}function PopulatedState({messages:e,prompts:n,onSelectPrompt:l,isStreaming:o,onAnswerCheckin:s,onCopy:a,sentimentByMessage:u,onSentiment:c,feedbackNote:d,imagesByMessage:f,onPreview:h,notice:p,reconnecting:g,onRetry:m,onStartNew:b,petRef:y,onFindVet:v,vet:x,onOpenUrl:w,petName:k,actions:C,answerCards:S,threadTop:j,pendingCheckin:_,threadAside:R,threadAsideKey:T,followUpLabel:I,openingCard:z,earlier:P}){let E=my(),{styles:O}=wb(),A=sg();Sg(e.length,A);let M=t.useMemo(()=>DC(FC(e)),[e]),F=Ih(e,o),D=e[e.length-1],L=R??null,B=p_(e,o,L===null?null:T??"shown"),V=vg(e),H=e[0],U=z!==void 0&&H!==void 0&&H.role==="user"&&H.text.trim()===z.prompt?H.id:null;/* @__PURE__ */
|
|
362
|
+
return i.jsxs(r.ScrollView,{ref:B.ref,style:O.list,contentContainerStyle:S!==null?O.listContentCards:O.listContent,accessibilityLabel:vf.transcript,keyboardShouldPersistTaps:"handled",keyboardDismissMode:v_,nestedScrollEnabled:true,onLayout:B.onLayout,onContentSizeChange:B.onContentSizeChange,onScroll:B.onScroll,scrollEventThrottle:y_,onScrollBeginDrag:B.onScrollBeginDrag,onScrollEndDrag:B.onScrollEnd,onMomentumScrollEnd:B.onScrollEnd,children:[j??null,_,P!==null?/* @__PURE__ */i.jsx(r.Pressable,{onPress:()=>{P.load()},disabled:P.loading,accessibilityRole:"button",accessibilityLabel:P.loading?wp.loadingEarlier:wp.earlier,accessibilityState:{disabled:P.loading,busy:P.loading},hitSlop:Gm,style:O.earlierButton,children:/* @__PURE__ */i.jsx(Text,{tier:"compact",style:O.earlierLabel,children:P.loading?wp.loadingEarlier:wp.earlier})}):null,e.map(t=>t.id===U&&z!==void 0?/* @__PURE__ */i.jsx(OpeningCard,{card:z.card,onLayout:B.rowLayout(t.id)},t.id):t.checkin&&M.has(t.id)?/* @__PURE__ */i.jsx(CheckinCard,{message:t,checkin:t.checkin,onAnswer:s,petRef:y,onFindVet:v,vet:x,onLayout:B.rowLayout(t.id)},t.id):/* @__PURE__ */i.jsx(MessageRow,{onLayout:B.rowLayout(t.id),message:t,revealing:o&&t===D&&t.role==="assistant",onCopy:a,sentiment:t.responseId===void 0?null:u[String(t.responseId)]??null,onSentiment:c,note:t.responseId!==void 0&&d?.responseId===String(t.responseId)?d.kind:null,images:f[t.id]??m_,onPreview:h,onOpenUrl:w,entering:V(t.id),answerCards:S,messages:e},t.id)),g?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:O.reconnectingCaption,accessibilityRole:"text",children:vf.reconnecting}):null,F?/* @__PURE__ */i.jsx(TypingIndicator,{petName:k,inline:S!==null}):null,p!==null?/* @__PURE__ */i.jsx(TurnNoticeCard,{notice:p,onRetry:m,onStartNew:b}):null,S!==null||E!==null?/* @__PURE__ */i.jsx(CardsFollowUps,{prompts:n,onSelectPrompt:l,label:I,actions:C,options:S??void 0}):/* @__PURE__ */i.jsx(FollowUps,{prompts:n,onSelectPrompt:l,label:I}),L!==null?/* @__PURE__ */i.jsx(r.View,{onLayout:B.asideLayout,children:L}):null]})}function TurnNoticeCard({notice:e,onRetry:t,onStartNew:n}){let{styles:l}=wb(),o=e.tone==="error";/* @__PURE__ */
|
|
363
|
+
return i.jsxs(r.View,{style:[l.turnNotice,o?l.turnNoticeError:null],accessible:true,accessibilityRole:"alert",children:[
|
|
364
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:[l.turnNoticeTitle,o?l.turnNoticeTitleError:null],children:e.title}),
|
|
365
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:l.turnNoticeBody,children:e.body}),e.guidance!==void 0?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:l.turnNoticeBody,testID:"everfur-chat-cap-guidance",children:e.guidance}):null,
|
|
366
|
+
/* @__PURE__ */i.jsx(r.Pressable,{onPress:e.action==="startNew"?n:t,accessibilityRole:"button",accessibilityLabel:e.actionLabel,hitSlop:Gm,style:l.turnNoticeAction,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:l.turnNoticeActionLabel,children:e.actionLabel})})]})}var m_=/* @__PURE__ */Object.freeze([]),b_=/* @__PURE__ */Object.freeze([]),y_=16,v_=r.Platform.OS==="ios"?"interactive":"on-drag",x_=18;function MessageRow({message:e,revealing:n,onCopy:l,sentiment:o,onSentiment:s,note:a,images:u,onPreview:c,onOpenUrl:d,onLayout:f,entering:h,answerCards:p,messages:g}){let{theme:m,styles:b}=wb(),y=my()?.paint,v=sg(),x=yg(h,v),w=wg(e.text,n,v),k=e.role==="user",C=e.role==="vet",S=e.role==="assistant",j=Qp(),_=S&&!n?j:void 0,R=_!==void 0&&vS(e.text,_),T=S&&!m.meta.hidePoweredBy,I=k?vf.senderUser:C?Fh(e):T?vf.assistantName:vf.senderAssistant,z=C?UC(e.createdAt):null,P=t.useCallback(t=>s(e,t),[s,e]),E=e.pending!==true,O=T&&y!==void 0?/* @__PURE__ */i.jsx(y.Byline,{}):S&&m.meta.assistantAvatarUrl!==null?/* @__PURE__ */i.jsx(AssistantSender,{avatarUrl:m.meta.assistantAvatarUrl,named:T,styles:b}):T?p!==null?/* @__PURE__ */i.jsx(CardsByline,{label:vf.assistantName}):/* @__PURE__ */i.jsx(Text,{tier:"control",style:b.assistantName,children:vf.assistantName}):null,A=p!==null;return S&&p!==null?/* @__PURE__ */i.jsx(r.Animated.View,{style:[b.rowBlock,x],onLayout:f,accessibilityLabel:`${I}: ${e.text}`,children:/* @__PURE__ */i.jsx(CardsAnswer,{message:e,text:w,streaming:n,messages:g,options:p,sentiment:o,onSentiment:e.responseId===void 0?void 0:P,sender:O,onOpenUrl:d,footer:t=>/* @__PURE__ */i.jsx(MessageFooter,{message:e,onCopy:l,sentiment:o,onSentiment:t&&e.responseId!==void 0?P:void 0,note:a})})}):/* @__PURE__ */i.jsxs(r.View,{style:[b.rowBlock,k?b.rowBlockUser:b.rowBlockAssistant],onLayout:f,children:[
|
|
367
|
+
/* @__PURE__ */i.jsx(r.View,{style:[b.row,k?b.rowUser:b.rowAssistant],accessible:!R,accessibilityRole:R?void 0:"text",accessibilityLabel:R?void 0:`${I}: ${e.text}`,accessibilityState:e.pending===true?{busy:true}:void 0,children:/* @__PURE__ */i.jsxs(r.Animated.View,{style:[b.bubble,A?b.bubbleCards:null,k?b.bubbleSideUser:null,x],children:[O,S&&E&&!n?/* @__PURE__ */i.jsx(SeverityCard,{message:e,spaced:true}):null,C?/* @__PURE__ */i.jsxs(r.View,{style:b.vetHeader,children:[
|
|
368
|
+
/* @__PURE__ */i.jsx(Text,{tier:"control",style:b.vetSender,children:I}),z!==null?/* @__PURE__ */i.jsx(Text,{tier:"compact",style:b.vetTime,children:z}):null]}):null,
|
|
369
|
+
/* @__PURE__ */i.jsxs(r.View,{style:[k?[b.bubbleUser,y?.userBubble]:C?b.bubbleVet:b.bubbleAssistant,k&&A?b.bubbleUserCards:null,e.pending?b.bubblePending:null],children:[k&&u.length>0?/* @__PURE__ */i.jsx(SentImages,{images:u,onPreview:e=>c({uri:e.uri,label:e.filename})}):null,
|
|
370
|
+
/* @__PURE__ */i.jsx(Text,{style:k?[b.bubbleTextUser,A?b.bubbleTextUserCards:null,y?.userText]:C?b.bubbleTextVet:b.bubbleTextAssistant,children:S?xS(w,{bold:b.bubbleBold,italic:b.bubbleItalic,code:b.bubbleCode},_):e.text})]})]})}),S&&!n?/* @__PURE__ */i.jsx(ServerCardsSlot,{message:e}):null,S&&!n?/* @__PURE__ */i.jsx(CitationCards,{citations:e.citations,onOpenUrl:d}):null,S&&!n?/* @__PURE__ */i.jsx(AnswerRecordCards,{message:e,spaced:true}):null,E&&!(k&&p!==null)?/* @__PURE__ */i.jsx(MessageFooter,{message:e,onCopy:l,sentiment:o,onSentiment:e.responseId===void 0?void 0:P,note:a}):null]})}var w_=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(e){if(e.isBootstrapping===true||e.isLoadingHistory===true||e.isStreaming===true||e.status==="error"||e.stopped===true)return false;let t=e.messages[e.messages.length-1];return t===void 0||t.role!=="assistant"||t.pending===true||t.checkin!==void 0||t.text.trim().length===0?false:!(typeof t.urgencyLevel=="string"&&w_.has(t.urgencyLevel))}var NO_SNAPSHOT2=()=>null;function k_(){let{runtime:e}=Yc(),r=e.entitlements??null,n=t.useCallback(e=>r===null?()=>{}:r.subscribe(e),[r]),l=r===null?NO_SNAPSHOT2:r.getSnapshot,i=t.useSyncExternalStore(n,l,l);return t.useMemo(()=>i!==null&&decideCapability("texting",i.decisions,{isPending:i.isPending}).enabled,[i])}var C_=/* @__PURE__ */Object.freeze({runner:null,line:null,entry:null,stage:null,headerEntry:null});function S_(e,r,n=false){let[l,o]=t.useState(null);if(!e)return C_;let s=/* @__PURE__ */i.jsx(AskRunner,{ready:textingAskThreadReady(r),onAsk:o,entry:n}),a=n&&l!==null&&l.canOpen?{label:h.textingAskLines(l).accept,onOpen:l.open}:null;if(l===null||l.stage==="hidden"||l.stage==="dismissed")return{runner:s,line:null,entry:null,stage:null,headerEntry:a};let u=h.textingAskLines(l),c=/* @__PURE__ */i.jsx(AskLine,{stage:l.stage,text:l.stage==="verified"?u.verified:u.line,accept:u.accept,dismiss:u.dismiss,onAccept:l.accept,onDismiss:l.dismiss}),d=l.stage==="enrolling"?/* @__PURE__ */i.jsx(h.ChatTextingAskComposer,{ask:l}):null;return{runner:s,line:c,entry:d,stage:l.stage,headerEntry:a}}function AskRunner({ready:e,onAsk:r,entry:n}){let{userRef:l}=Yc(),o=k_(),s=l!==null&&o;return t.useEffect(()=>{s||r(null)},[s,r]),s?/* @__PURE__ */i.jsx(h.ChatTextingAskController,{enabled:true,ready:e,onAsk:r,entry:n}):null}function AskLine({stage:e,text:t,accept:n,dismiss:l,onAccept:o,onDismiss:s}){let{theme:a,styles:u}=wb(),c=!a.meta.hidePoweredBy,d=c?vf.assistantName:vf.senderAssistant,f=a.meta.assistantAvatarUrl!==null?/* @__PURE__ */i.jsx(AssistantSender,{avatarUrl:a.meta.assistantAvatarUrl,named:c,styles:u}):c?/* @__PURE__ */i.jsx(Text,{tier:"control",style:u.assistantName,children:vf.assistantName}):null;/* @__PURE__ */
|
|
371
|
+
return i.jsxs(r.View,{style:[u.rowBlock,u.rowBlockAssistant],testID:`everfur-texting-ask-${e}`,children:[
|
|
372
|
+
/* @__PURE__ */i.jsx(r.View,{style:[u.row,u.rowAssistant],accessible:true,accessibilityRole:"text",accessibilityLabel:`${d}: ${t}`,children:/* @__PURE__ */i.jsxs(r.View,{style:u.bubble,children:[f,
|
|
373
|
+
/* @__PURE__ */i.jsx(r.View,{style:u.bubbleAssistant,children:/* @__PURE__ */i.jsx(Text,{style:u.bubbleTextAssistant,children:t})})]})}),e==="offered"?/* @__PURE__ */i.jsx(r.View,{style:u.askChips,children:[{label:n,onPress:o,testID:"everfur-texting-ask-accept"},{label:l,onPress:s,testID:"everfur-texting-ask-dismiss"}].map(e=>/* @__PURE__ */i.jsx(PressScale,{onPress:e.onPress,accessibilityRole:"button",accessibilityLabel:e.label,style:u.askChip,testID:e.testID,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:u.askChipText,children:e.label})},e.testID))}):null]})}function j_(){let e=/* @__PURE__ */Symbol.for("@everfur/sdk#SdkSurfaceHooks@v1"),r=globalThis;return r[e]??(r[e]=t.createContext(null))}var __=/* @__PURE__ */j_();function R_(e){return typeof e=="object"&&e!==null&&e.ok===true}function T_(e){if(typeof e!="object"||e===null)return null;let t=e;return t.ok!==false||typeof t.error!="object"||t.error===null?null:Ee(t.error)}function I_(e){let r=t.useContext(__),n=r?.onMessageSent,l=r?.onFreeCapReached,i=t.useCallback((...t)=>{let r=e(...t);return Promise.resolve(r).then(e=>{try{if(R_(e)){n?.();return}let t=l===void 0?null:T_(e);t!==null&&l?.(t)}catch{}},()=>{}),r},[e,n,l]);return n===void 0&&l===void 0?e:i}function EverfurChatCore(e){let{style:t,renderPending:r}=e;/* @__PURE__ */
|
|
374
|
+
return i.jsx(CapabilityGate,{capability:"chat",style:t,...r?{renderPending:r}:{},children:/* @__PURE__ */i.jsx(MessageLinksScope,{linkHosts:e.linkHosts,onOpenUrl:e.onOpenUrl,children:/* @__PURE__ */i.jsx(ChatBody,{...e})})})}function z_(){try{return Yc()}catch{return null}}function P_(e){return Sh({...e.presentation,chatComposerMic:e.presentation?.chatComposerMic??(e.dictation===void 0?void 0:e.dictation!==false),chatComposerUpload:e.presentation?.chatComposerUpload??(e.attachments===void 0?void 0:true)})}function E_(e,t){let r=CC(t?"tabs_bar":e.shellHeader);return r===(e.shellHeader==="tabs_bar")?e:/* @__PURE__ */Object.freeze({...e,shellHeader:r?"tabs_bar":"classic"})}function ChatBody(e){let t=z_();return t===null?/* @__PURE__ */i.jsx(ChatBodyAlone,{...e}):/* @__PURE__ */i.jsx(ChatBodyInProvider,{...e,activePet:t.activePet,telemetry:t.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(e){let r=P_(e),n=JSON.stringify(r),l=e.petRef??null,o=t.useMemo(()=>({presentation:E_(resolvePresentation({server:null,locked:null,client:r}),false),isLocked:()=>false,planPage:null,planPetRef:l,inProvider:false,telemetry:null}),[n,l]);/* @__PURE__ */
|
|
375
|
+
return i.jsx(ChatSurface,{...e,settings:o})}function ChatBodyInProvider({activePet:e,telemetry:r,...n}){let{presentation:l,isLocked:isLocked}=Ch(P_(n)),o=dk(),s=t.useMemo(()=>E_(l,o),[o,l]),a=Ed("healthPlan"),u=s.chatTopCard==="focus"&&s.shellHeader!=="tabs_bar"&&n.topCard===void 0&&a,c=n.petRef??e??null,d=useHealthPlanPage({petRef:c,enabled:u}),f=u&&d.phase==="ready"?d.page:null,h=t.useMemo(()=>({presentation:s,isLocked:isLocked,planPage:f,planPetRef:c,inProvider:true,telemetry:r}),[s,isLocked,f,c,r]);/* @__PURE__ */
|
|
376
|
+
return i.jsx(ChatSurface,{...n,settings:h})}function ChatSurface({settings:e,petRef:l,conversationId:o,style:s,renderPending:a,onCopy:u,onPetChange:c,onVetPrep:d,onFindVet:f,renderVetAction:h,attachments:p,pet:g,onAddPet:m,checkinTarget:b,handoffToken:y,initialAsk:v,initialAskKey:x,composerSeed:w,lifecycle:k,refreshIntervalMs:C,refreshesBlankThread:S,openUnreadOnRefresh:j,draftStore:_,vetReturnTo:R,vetUsState:T,vetPrefer:I,onOpenUrl:z,keyboardVerticalOffset:P,topCard:E,onOpenHealthPlan:O,onOpenRecord:A,answerCards:M,historySheet:F,historyBar:D,starterPrompts:L,emptyState:B,header:V=true,textingEntry:H=true,renderEmptyHeader:U,followUpPolicy:N,initialAskCard:$}){let{presentation:W,isLocked:isLocked,planPage:q,planPetRef:G}=e,{theme:K,styles:Y}=wb(),Q=Lx()??(W.chatAnswerStyle==="cards"?Dk:null),Z=t.useMemo(()=>Q===null?null:Q(K),[Q,K]),X=useHostPoweredBy(),J=sg(),ee=t.useMemo(()=>Dh(l,o),[l,o]),te=useEverfurChat(ee),re=I_(te.send),ne=t.useMemo(()=>re===te.send?te:{...te,send:re},[te,re]),le=jh(ne),ie=zC(),oe=zp(ne),se=n.useSafeAreaInsets(),ae=Th(ne,"web"),ue=t.useMemo(()=>f===void 0?void 0:()=>{ch(f,"emergency")},[f]),ce=t.useMemo(()=>R===void 0&&T===void 0&&I===void 0?void 0:{returnTo:R,usState:T,prefer:I},[R,T,I]),de=yx(ie.pets,ne.petRef),[fe,he]=t.useState(null),pe=t.useMemo(()=>{let e=Fp(ne.messages,de?.name??null);return e?.level==="schedule_soon"&&e.messageId===fe?null:e},[ne.messages,de?.name,fe]),ge=Lp(pe);EC(ne),Sg(ge.showBanner,J);let me=z_(),be=yp(y,me);xp(ne.openCheckin,b??be,{petRef:ne.petRef,pinned:l!==void 0,ready:!ne.isBootstrapping,selectPet:e=>{ie.setActivePet(e),ch(c,e)}}),Xh(ne.askEverfur,ne.isBootstrapping,v,x);let ye=t.useMemo(()=>Zh(w),[w]),ve=t.useMemo(()=>Zh(v),[v]),xe=t.useMemo(()=>$!==void 0&&ve!==null?{card:$,prompt:ve}:void 0,[$,ve]),we=t.useMemo(()=>k===void 0?createAppStateLifecycle():k??void 0,[k]);ap(we,{conversationId:ne.conversationId===null?null:String(ne.conversationId),isTurnInFlight:ne.isStreaming,refreshesBlankThread:S===true||j===true,refresh:ne.refreshActiveThread===void 0?void 0:()=>ne.refreshActiveThread?.(np(j===true,lp(we,Ag)))??Promise.resolve()},{intervalMs:C===void 0?3e4:C,isVisibleFallback:Ag}),ip({isStreaming:ne.isStreaming,status:ne.status,conversationId:ne.conversationId===null?null:String(ne.conversationId),unreadCount:ne.unreadCount,markRead:ne.markRead},()=>lp(we,Ag));let ke=ne.pendingCheckin??null,Ce=ke===null?null:/* @__PURE__ */i.jsx(r.View,{testID:"everfur-pending-checkin",accessibilityLiveRegion:"polite",children:/* @__PURE__ */i.jsx(CheckinCard,{message:ke.message,checkin:ke.checkin,onAnswer:ne.petRef?ne.answerCheckin:null,petRef:ne.petRef,onFindVet:ue,vet:ce,onOpen:()=>{ne.resumeConversation(ke.conversationId)}})}),Se=(ne.hasUnreadThreads??false)||oe.rows.some(e=>e.unreadCount!==null&&e.unreadCount>0)||(ne.unreadCount??0)>0,je=qh(ne.messages),[_e,Re]=t.useState(null),Te=t.useCallback(()=>Re(null),[]),[Ie,ze]=t.useState(null),[Pe,Ee]=t.useState(null),Oe=t.useRef(null);t.useEffect(()=>()=>{Oe.current&&clearTimeout(Oe.current)},[]);let Ae=t.useCallback((e,t)=>{Ee({responseId:String(e),kind:t}),Oe.current&&clearTimeout(Oe.current),Oe.current=t==="thanks"?setTimeout(()=>{Ee(null),Oe.current=null},Tm):null},[]),Me=t.useCallback((e,t)=>{let r=e.responseId;if(r===void 0)return;let n=ne.sentimentByMessage[String(r)];Ee(e=>e?.responseId===String(r)?null:e),ne.feedback(r,t).then(e=>{e.ok||Ae(r,"failed")}),t==="down"&&n!=="down"&&ze(r)},[ne,Ae]),Fe=t.useCallback(async(e,t)=>Ie===null||!(e==null&&t===null?{ok:true}:await ne.feedback(Ie,"down",e??"other",t)).ok?false:(ze(null),Ae(Ie,"thanks"),true),[ne,Ie,Ae]),De=t.useCallback(()=>ze(null),[]),Le=t.useCallback(e=>{ne.send(e)},[ne.send]),Be=t.useMemo(()=>z===void 0?void 0:e=>{ch(z,e,"citation")},[z]),Ve=r.Platform.OS==="ios"?"padding":void 0,He=qk(P,Ve!==void 0),Ue=He.topInWindow===null?se.top:Math.max(0,se.top-He.topInWindow),Ne=Kk(),$e=t.useMemo(()=>O===void 0?void 0:()=>{ch(O,G)},[O,G]),We=t.useMemo(()=>({petRef:ne.petRef,vet:ce,cover:he}),[ne.petRef,ce]),qe=t.useMemo(()=>E===void 0?healthPlanTopCard(q,{onOpenPlan:$e}):void 0,[E,q,$e]),Ge=W.chatTopCard==="focus"?E??(W.shellHeader==="tabs_bar"?void 0:qe):void 0,[Ke,Ye]=t.useState(true),Qe=t.useCallback(e=>{ne.send(e)},[ne.send]),Ze=t.useMemo(()=>Vh(N,W,isLocked("chatFollowUpCount")),[N,W,isLocked]),Xe=W.chatAnswerStyle==="cards",Je=W.shellHeader==="tabs_bar",et=t.useMemo(()=>Xe&&ne.messages.length===0?A_(ne.suggestedPrompts,Je?4:3):void 0,[Xe,ne.messages.length,ne.suggestedPrompts,Je]),tt=W.chatHistoryStyle==="sheet",rt=ne.messages.length===0,nt=Ge!==void 0?/* @__PURE__ */i.jsx(TopCardPill,{card:Ge,open:Ke,onOpenChange:Ye}):null,lt=D??(V?void 0:M_),it=lt!==void 0?/* @__PURE__ */i.jsx(HistoryBar,{bar:lt,history:oe,empty:rt,unread:Se,extra:nt}):null,ot=W.chatHistoryBar==="scroll"&&!Je&&(le==="empty"||le==="populated"),st=Ge===void 0?null:/* @__PURE__ */i.jsxs(i.Fragment,{children:[
|
|
377
|
+
/* @__PURE__ */i.jsx(TopCard,{card:Ge,open:Ke,onOpenChange:Ye,ask:Qe}),lt===void 0?nt:null]}),at=lt!==void 0,ut=oe.load,ct=oe.open;t.useEffect(()=>{at&&!ct&&ut()},[at,ct,ne.conversationId,ut]);let dt={send:ne.send,stop:ne.stop,isStreaming:ne.isStreaming,conversationId:ne.conversationId,seed:ye,draftStore:_,onStage:je.stage,onPreview:Re,petName:de?.name??null,petBreed:de?.breed??null,compact:W.chatComposerStyle==="compact",petPlaceholder:W.chatComposerPlaceholder==="pet_name",dimEmptySend:W.chatSendButton==="dim_when_empty",mood:F_(le,ge.source?.level??null),dictation:W.chatComposerMic,telemetry:e.telemetry},ft=S_(W.chatTextingAsk&&e.inProvider,ne,H),ht=p!==void 0&&W.chatComposerUpload,pt=!W.chatGeneralBanner&&ge.source?.level==="general",gt=Je?kC()?.ask??null:null,mt=t.useMemo(()=>gt!==null?{paint:gt.paint(K),petRef:ne.petRef??null,vet:ce,onFindVet:f,renderVetAction:h,onOpenRecord:A}:null,[gt,K,ne.petRef,ce,f,h,A]),bt=mt!==null&&mt.paint.partner!==null,yt=bt&&le!=="empty"?/* @__PURE__ */i.jsx(PrivacyLine,{}):null,vt=bt&&le==="empty"?/* @__PURE__ */i.jsx(PrivacyLine,{empty:true}):null,xt=ot?yt===null?it:/* @__PURE__ */i.jsxs(i.Fragment,{children:[it,yt]}):null;
|
|
377
378
|
/* @__PURE__ */
|
|
378
|
-
return
|
|
379
|
-
/* @__PURE__ */
|
|
380
|
-
/* @__PURE__ */
|
|
381
|
-
/* @__PURE__ */
|
|
382
|
-
/* @__PURE__ */
|
|
383
|
-
/* @__PURE__ */
|
|
384
|
-
/* @__PURE__ */
|
|
385
|
-
/* @__PURE__ */
|
|
386
|
-
/* @__PURE__ */
|
|
387
|
-
return
|
|
379
|
+
return i.jsx(Dx.Provider,{value:Z,children:/* @__PURE__ */i.jsx(gy.Provider,{value:mt,children:/* @__PURE__ */i.jsxs(r.KeyboardAvoidingView,{style:[Y.container,{paddingTop:Ue},s],behavior:Ve,...He.avoidingProps,children:[
|
|
380
|
+
/* @__PURE__ */i.jsx(KeyboardOffsetProbe,{probeRef:He.probeRef}),
|
|
381
|
+
/* @__PURE__ */i.jsxs(SdkTabletColumn,{children:[V?/* @__PURE__ */i.jsx(ChatHeader,{pets:ie,petRef:ne.petRef,historyUnread:Se,onOpenHistory:oe.show,onNewChat:oe.newConversation,onPetChange:c,onAddPet:m,vet:ce,textingEntry:ft.headerEntry}):null,g!==void 0?/* @__PURE__ */i.jsx(PetSetupNotice,{petRef:l??null,pet:g,onRegistered:ie.refresh}):null,!V&&ft.headerEntry!==null?/* @__PURE__ */i.jsx(TextingEntryRow,{entry:ft.headerEntry,place:"thread"}):null,ot?null:it,ot?null:yt,pt||mt!==null?null:/* @__PURE__ */i.jsx(UrgencyBanner,{surface:ge,petRef:ne.petRef,renderVetAction:h,onFindVet:f,vet:ce,compact:Ne}),
|
|
382
|
+
/* @__PURE__ */i.jsx(r.View,{style:Y.body,children:/* @__PURE__ */i.jsx(Hp.Provider,{value:We,children:g_(le,ne,{notice:ae,vet:ce,onCheckinFindVet:ue,onSelectPrompt:Le,renderPending:a,shownPet:de,onVetPrep:d,onCopy:u,onSentiment:Me,feedbackNote:Pe,imagesByMessage:je.byMessage,onPreview:Re,onAddPet:m,onOpenUrl:Be,threadTop:xt,pendingCheckin:Ce,topCard:st,starterPrompts:L??et,emptyState:B,emptyCentered:W.chatAnswerStyle==="cards",followUpPolicy:Ze,answerCards:W.chatAnswerStyle==="cards"?M??O_:null,threadAside:ft.line,threadAsideKey:ft.stage,renderEmptyHeader:U,openingCard:xe})})}),ft.runner,vt,ft.entry!==null?/* @__PURE__ */i.jsx(r.View,{style:Y.composerOuter,children:/* @__PURE__ */i.jsx(r.View,{style:Y.askEntry,children:ft.entry})}):ht&&p!==void 0?/* @__PURE__ */i.jsx(ComposerWithAttachments,{...dt,attachments:p}):/* @__PURE__ */i.jsx(Composer,{...dt,attachments:null}),mt!==null?/* @__PURE__ */i.jsx(AskBarDisclaimer,{}):K.meta.hidePoweredBy||X?null:/* @__PURE__ */i.jsx(Text,{tier:"compact",style:Y.poweredBy,accessibilityRole:"text",accessibilityLabel:vf.poweredBy,children:vf.poweredBy})]}),tt?/* @__PURE__ */i.jsx(HistorySheet,{chat:ne,history:oe,sheet:F}):/* @__PURE__ */i.jsx(HistoryDrawer,{chat:ne,history:oe}),
|
|
383
|
+
/* @__PURE__ */i.jsx(FeedbackReasons,{visible:Ie!==null,onSubmit:Fe,onSkip:De}),
|
|
384
|
+
/* @__PURE__ */i.jsx(AttachmentImageLightbox,{uri:_e?.uri??null,label:_e?.label??"",onClose:Te}),
|
|
385
|
+
/* @__PURE__ */i.jsx(TelevetHostOutlet,{})]})})})}function PetSetupNotice({petRef:e,pet:t,onRegistered:n}){let{styles:l}=wb(),o=$h(e,t,n);return o.status!=="failed"||o.error===null?null:/* @__PURE__ */i.jsxs(r.View,{style:l.setupNotice,accessible:true,accessibilityRole:"alert",children:[
|
|
386
|
+
/* @__PURE__ */i.jsx(Text,{tier:"compact",style:l.setupNoticeText,children:o.error.displayMessage}),
|
|
387
|
+
/* @__PURE__ */i.jsx(r.Pressable,{onPress:o.retry,accessibilityRole:"button",accessibilityLabel:vf.retry,hitSlop:Gm,children:/* @__PURE__ */i.jsx(Text,{tier:"control",style:l.setupNoticeAction,children:vf.retry})})]})}var O_=/* @__PURE__ */Object.freeze({});function A_(e,t){let r=[];for(let n of e){let e=n.trim();if(e.length>0&&!r.some(t=>t.label===e)&&r.push(/* @__PURE__ */Object.freeze({label:e})),r.length===t)break}return r.length>0?/* @__PURE__ */Object.freeze(r):void 0}var M_=/* @__PURE__ */Object.freeze({chats:wp.heading,newChat:wp.newChat});function F_(e,t){return t==="emergency"?"urgent":e==="populated"?"followUp":"ask"}function EverfurChat(e){/* @__PURE__ */
|
|
388
|
+
return i.jsx($d.Provider,{value:EverfurTelevetHost,children:/* @__PURE__ */i.jsx(EverfurChatCore,{...e})})}var D_=/* @__PURE__ */Object.freeze({hasUnread:null,unreadCount:null,conversationId:null,petRef:null}),NO_SUBSCRIPTION=()=>()=>{};function L_(e,r){let{runtime:n,userRef:l,activePet:i,scopeEpoch:o}=Yc(),s=n.unread??null,a=e===void 0?i:e,u=t.useCallback(e=>s===null?NO_SUBSCRIPTION():s.subscribe(e),[s]),c=t.useCallback(()=>s===null||l===null?D_:s.get(a),[s,l,a]),d=t.useSyncExternalStore(u,c,c),f=t.useCallback(()=>s===null||l===null?Promise.resolve():s.refresh(a),[s,l,a]);return t.useEffect(()=>{f()},[f,o]),ap(r,{conversationId:null,isTurnInFlight:false,refreshesBlankThread:true,refresh:f}),t.useMemo(()=>({...d,refresh:f}),[d,f])}function useEverfurUnread(e={}){let{lifecycle:r}=e,n=t.useMemo(()=>r===void 0?createAppStateLifecycle():r??void 0,[r]);return L_(e.petRef,n)}function useEverfurPetProfile(e){let{runtime:r,userRef:n,scopeEpoch:l}=Yc(),i=t.useMemo(()=>createPetsRepository(r.registry.services.authFor(n)),[r,n,l]),o=t.useMemo(()=>({repository:i,petRef:e}),[i,e]),[s,a]=t.useState({key:o,profile:null,loading:e!==null,error:null}),u=s.key===o?s:{profile:null,loading:e!==null,error:null},c=t.useRef(0),d=t.useCallback(async()=>{let e=++c.current;if(o.petRef===null){a({key:o,profile:null,loading:false,error:null});return}a(e=>({key:o,profile:e.key===o?e.profile:null,loading:true,error:null}));let t=await o.repository.getPetProfile(o.petRef);e===c.current&&a(t.ok?{key:o,profile:t.value,loading:false,error:null}:{key:o,profile:null,loading:false,error:t.error})},[o]);return t.useEffect(()=>(d(),()=>{c.current+=1}),[d]),t.useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:d}),[u.profile,u.loading,u.error,d])}function EverfurThemeProvider(e){return t.createElement(EverfurThemeProviderCore,{clientTheme:e.clientTheme??null,seams:Id,children:e.children})}exports.APPEARANCE_PRESETS=$s;exports.APPEARANCE_PRESET_NAMES=Ns;exports.APPEARANCE_SIZE_RANGES=Ws;exports.CapabilityGate=CapabilityGate;exports.EverfurChat=EverfurChat;exports.EverfurConfigError=b;exports.EverfurProvider=EverfurProvider;exports.EverfurThemeProvider=EverfurThemeProvider;exports.EverfurThrownError=m;exports.PHONE_TEXT_SCALE_CAPS=yo;exports.THEME_SLOT_KEYS=Ki;exports.THEME_SLOT_KEYS_BY_SLOT=Yi;exports.THEME_SLOT_NAMES=Gi;exports.TYPE_ROLE_DEFAULTS=go;exports.TYPE_ROLE_NAMES=po;exports.canonicalPetSpecies=canonicalPetSpecies;exports.categoryFor=categoryFor;exports.chatHandoffTokenFromUrl=chatHandoffTokenFromUrl;exports.conversationId=conversationId;exports.createAppStateLifecycle=createAppStateLifecycle;exports.createRnRecordsUploadTransport=createRnRecordsUploadTransport;exports.expandAppearance=expandAppearance;exports.face=face;exports.headingFace=headingFace;exports.isErr=isErr;exports.isOk=isOk;exports.isRetryableCode=isRetryableCode;exports.petRef=petRef;exports.previewTheme=previewTheme;exports.registerEverfurChatCards=registerEverfurChatCards;exports.registerEverfurDictation=registerEverfurDictation;exports.textRole=textRole;exports.themeAdjustments=themeAdjustments;exports.themeSlotKeysFor=themeSlotKeysFor;exports.unwrap=unwrap;exports.useCapability=useCapability;exports.useChatAttachments=useChatAttachments;exports.useEverfur=useEverfur;exports.useEverfurChat=useEverfurChat;exports.useEverfurPetProfile=useEverfurPetProfile;exports.useEverfurPets=useEverfurPets;exports.useEverfurTheme=useEverfurTheme;exports.useEverfurUnread=useEverfurUnread;exports.userFacingError=userFacingError;exports.userRef=userRef;
|