@everfur/sdk 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/dist/{Chat.d-DySDBc6L.d.ts → Chat.d-Bt0fKiOQ.d.ts} +1 -1
- package/dist/{Chat.d-DDmNIlJn.d.cts → Chat.d-CTVJ_qWQ.d.cts} +1 -1
- package/dist/animations/index.cjs +1 -1
- package/dist/animations/index.js +1 -1
- package/dist/{branding.d-DC4imCYd.d.ts → branding.d-SCzhpyTt.d.ts} +1 -1
- package/dist/{branding.d-G7rpxDhI.d.cts → branding.d-eGlNC86j.d.cts} +1 -1
- package/dist/chat/index.cjs +10 -10
- package/dist/chat/index.d.cts +3 -3
- package/dist/chat/index.d.ts +3 -3
- package/dist/chat/index.js +10 -10
- package/dist/chat/lite/index.cjs +10 -10
- package/dist/chat/lite/index.d.cts +3 -3
- package/dist/chat/lite/index.d.ts +3 -3
- package/dist/chat/lite/index.js +10 -10
- package/dist/{chunk-NO7LYPKW.js → chunk-5TWMQIT4.js} +1 -1
- package/dist/{chunk-EMINPX6C.js → chunk-LWPM4GD3.js} +2 -2
- package/dist/{chunk-QG4ZH45Q.js → chunk-PDZTFXOO.js} +1 -1
- package/dist/{chunk-VY5VTLFX.js → chunk-ZZTNGAS7.js} +3 -3
- package/dist/client/index.cjs +3 -3
- package/dist/client/index.d.cts +6 -6
- package/dist/client/index.d.ts +6 -6
- package/dist/client/index.js +3 -3
- package/dist/consent/index.cjs +1 -1
- package/dist/consent/index.js +1 -1
- package/dist/{context.d-TArU_9lj.d.ts → context.d-Bl07_JGt.d.ts} +2 -2
- package/dist/{context.d-DLHTf-fV.d.cts → context.d-CzMV_7jD.d.cts} +2 -2
- package/dist/core/index.cjs +5 -5
- package/dist/core/index.d.cts +6 -6
- package/dist/core/index.d.ts +6 -6
- package/dist/core/index.js +5 -5
- package/dist/{entitlementRepository.d-Tj7lvs4e.d.cts → entitlementRepository.d-B4ffomns.d.cts} +1 -1
- package/dist/{entitlementRepository.d-CoKN-Ksa.d.ts → entitlementRepository.d-DLMRDNUe.d.ts} +1 -1
- package/dist/health-plan/index.cjs +6 -6
- package/dist/health-plan/index.d.cts +4 -4
- package/dist/health-plan/index.d.ts +4 -4
- package/dist/health-plan/index.js +6 -6
- package/dist/index.cjs +13 -13
- package/dist/index.d.cts +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.js +13 -13
- package/dist/notifications/inbox/index.cjs +1 -1
- package/dist/notifications/inbox/index.js +1 -1
- package/dist/notifications/index.cjs +1 -1
- package/dist/notifications/index.js +1 -1
- package/dist/photo/index.cjs +1 -1
- package/dist/photo/index.js +1 -1
- package/dist/{presentation.d-BvZs_jN-.d.cts → presentation.d-tJe7zo12.d.cts} +6 -2
- package/dist/{presentation.d-BvZs_jN-.d.ts → presentation.d-tJe7zo12.d.ts} +6 -2
- package/dist/records/depth/index.cjs +1 -1
- package/dist/records/depth/index.js +1 -1
- package/dist/records/index.cjs +3 -3
- package/dist/records/index.d.cts +2 -2
- package/dist/records/index.d.ts +2 -2
- package/dist/records/index.js +3 -3
- package/dist/{runtimeTypes.d-BHdN-9aB.d.cts → runtimeTypes.d-6nkdToBS.d.cts} +1 -1
- package/dist/{runtimeTypes.d-L_CbeCKS.d.ts → runtimeTypes.d-Byb55WsJ.d.ts} +1 -1
- package/dist/server/events/index.cjs +2 -2
- package/dist/server/events/index.js +2 -2
- package/dist/server/index.cjs +2 -2
- package/dist/server/index.js +2 -2
- package/dist/shop/index.cjs +8 -8
- package/dist/shop/index.js +8 -8
- package/dist/slots/index.cjs +40 -40
- package/dist/slots/index.js +40 -40
- package/dist/tabs/index.cjs +1 -1
- package/dist/tabs/index.js +1 -1
- package/dist/televet/booking/index.cjs +1 -1
- package/dist/televet/booking/index.js +1 -1
- package/dist/televet/index.cjs +1 -1
- package/dist/televet/index.js +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/rn/index.cjs +1 -1
- package/dist/testing/rn/index.d.cts +3 -3
- package/dist/testing/rn/index.d.ts +3 -3
- package/dist/testing/rn/index.js +1 -1
- package/dist/testing/web/index.cjs +1 -1
- package/dist/testing/web/index.d.cts +3 -3
- package/dist/testing/web/index.d.ts +3 -3
- package/dist/testing/web/index.js +1 -1
- package/dist/texting/index.cjs +1 -1
- package/dist/texting/index.js +1 -1
- package/dist/{threadOptions.d-FzFN0zsK.d.ts → threadOptions.d-Cjps2yaN.d.ts} +2 -2
- package/dist/{threadOptions.d-CS-Qu_rR.d.cts → threadOptions.d-E-ZxhUSg.d.cts} +2 -2
- package/dist/{typeStyle.d-BIDpuYpg.d.cts → typeStyle.d-CuKAr0Ly.d.cts} +1 -1
- package/dist/{typeStyle.d-aRhFhBpG.d.ts → typeStyle.d-ZszGrWPf.d.ts} +1 -1
- package/dist/ui/index.cjs +26 -26
- package/dist/ui/index.js +26 -26
- package/dist/{usePresentation.d-Dr7iD-4Y.d.ts → usePresentation.d-CoyGEJOl.d.ts} +1 -1
- package/dist/{usePresentation.d-BHO_uZ31.d.cts → usePresentation.d-DUHlQyV5.d.cts} +1 -1
- package/dist/{useUnread.d-CAeYh82_.d.ts → useUnread.d-CFzIPmZt.d.ts} +1 -1
- package/dist/{useUnread.d-DXcRBQw8.d.cts → useUnread.d-D-p7oEW_.d.cts} +1 -1
- package/dist/video/index.cjs +1 -1
- package/dist/video/index.js +1 -1
- package/dist/web/consent/index.cjs +1 -1
- package/dist/web/consent/index.js +1 -1
- package/dist/web/health-plan/index.cjs +6 -6
- package/dist/web/health-plan/index.d.cts +5 -5
- package/dist/web/health-plan/index.d.ts +5 -5
- package/dist/web/health-plan/index.js +2 -2
- package/dist/web/inbox/index.cjs +1 -1
- package/dist/web/inbox/index.js +1 -1
- package/dist/web/index.cjs +8 -8
- package/dist/web/index.d.cts +12 -12
- package/dist/web/index.d.ts +12 -12
- package/dist/web/index.js +8 -8
- package/dist/web/intro/index.cjs +1 -1
- package/dist/web/intro/index.js +1 -1
- package/dist/web/notifications/index.cjs +1 -1
- package/dist/web/notifications/index.js +1 -1
- package/dist/web/records/depth/index.cjs +1 -1
- package/dist/web/records/depth/index.js +1 -1
- package/dist/web/records/index.cjs +1 -1
- package/dist/web/records/index.js +1 -1
- package/dist/web/records-sheet/index.cjs +3 -3
- package/dist/web/records-sheet/index.js +3 -3
- package/dist/web/shop/index.cjs +2 -2
- package/dist/web/shop/index.js +1 -1
- package/dist/web/televet/booking/index.cjs +2 -2
- package/dist/web/televet/booking/index.js +2 -2
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/televet/index.cjs +1 -1
- package/dist/web/televet/index.js +1 -1
- package/dist/web/texting/index.cjs +1 -1
- package/dist/web/texting/index.js +1 -1
- package/dist/web/ui/index.cjs +7 -7
- package/dist/web/ui/index.js +4 -4
- package/package.json +5 -5
package/dist/chat/lite/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
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
|
-
import{createContext,forwardRef,createElement,useCallback,useMemo,useRef,useState,useEffect,useSyncExternalStore,useContext,Component,Fragment as Fragment$1}from"react";import{TextInput as TextInput$1,StyleSheet,Platform,AppState,Text as Text$1,View,Linking,KeyboardAvoidingView,Dimensions,Keyboard,Pressable,Modal,ScrollView,ActivityIndicator,Image,AccessibilityInfo,UIManager,LayoutAnimation,Animated,useWindowDimensions,FlatList}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import*as texting from"@everfur/sdk/texting";var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}function weightBucket(weight){return weight<=450?"regular":weight<=650?"medium":"bold"}var MONO_OF={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(theme,role){let byRole=roleCache.get(theme);byRole===void 0&&(byRole=/* @__PURE__ */new Map,roleCache.set(theme,byRole));let hit=byRole.get(role);if(hit!==void 0)return hit;let style=buildRole(theme,role);return byRole.set(role,style),style}var roleCache=/* @__PURE__ */new WeakMap;function buildRole(theme,role){let r=theme.type.roles[role],weight=r.weight==="400"&&r.face!=="mono"?theme.type.weight.regular:r.weight,bucket=weightBucket(Number(weight)),f=r.face==="mono"?face(theme,MONO_OF[bucket]):r.face==="heading"?headingFace(theme,bucket):face(theme,bucket),faceWeight=r.face==="heading"?theme.type.headingWeight??weight:weight,faceStyle=f.fontWeight===void 0?f:{fontFamily:f.fontFamily,fontWeight:faceWeight},fontSize=r.size,out={...faceStyle,fontSize:fontSize,lineHeight:Math.round(fontSize*r.lineHeight*100)/100};return r.letterSpacing!==0&&(out.letterSpacing=Math.round(fontSize*r.letterSpacing*100)/100),r.uppercase&&(out.textTransform="uppercase"),/* @__PURE__ */Object.freeze(out)}var TYPE_ROLE_DEFAULTS=/* @__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 freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3});var SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES,roles:TYPE_ROLE_DEFAULTS,typeScale:1}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier,variant:variant,...props}){let theme=useEverfurTheme(),role=variant===void 0?void 0:theme.type.roles[variant],cap=tierMultiplier(theme.type,tier??role?.tier??"content"),styled=variant===void 0?props:{...props,style:[{...textRole(theme,variant),color:theme.color.text.primary,flexShrink:1},props.style]};return createElement(Text$1,cap===void 0?styled:{maxFontSizeMultiplier:cap,...styled})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...props,...ref===null?{}:{ref:ref}})});var DEFAULT_PRESENTATION=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true,serverSlots:false}),PRESENTATION_WIRE_NAMES=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask",serverSlots:"server_slots"}),FIELDS=Object.keys(PRESENTATION_WIRE_NAMES),PRESENTATION_LOCK="presentation",PRESENTATION_LOCK_PREFIX="presentation.";var ENUMS={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},BOOLS=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function parseField(field,value){if(value==null)return;let allowed=ENUMS[field];return allowed!==void 0?typeof value=="string"&&allowed.includes(value)?value:void 0:BOOLS.has(field)?typeof value=="boolean"?value:void 0:typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=3?value:void 0}function parsePresentation(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let source=raw,out={};for(let field of FIELDS){let wire=PRESENTATION_WIRE_NAMES[field],value=Object.prototype.hasOwnProperty.call(source,wire)?source[wire]:source[field],parsed=parseField(field,value);parsed!==void 0&&(out[field]=parsed)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function isPresentationFieldLocked(field,locked){if(locked==null)return false;let one=`${PRESENTATION_LOCK_PREFIX}${PRESENTATION_WIRE_NAMES[field]}`;for(let name of locked)if(name===PRESENTATION_LOCK||name===one)return true;return false}function resolvePresentation(input){let server=parsePresentation(input?.server??null)??{},client=parsePresentation(input?.client??null)??{},locked=input?.locked?[...input.locked]:null,out={};for(let field of FIELDS){let fromServer=server[field],fromClient=isPresentationFieldLocked(field,locked)?void 0:client[field];out[field]=fromClient??fromServer??DEFAULT_PRESENTATION[field]}/* @__PURE__ */
|
|
2
|
+
import{createContext,forwardRef,createElement,useCallback,useMemo,useRef,useState,useEffect,useSyncExternalStore,useContext,Component,Fragment as Fragment$1}from"react";import{TextInput as TextInput$1,StyleSheet,Platform,AppState,Text as Text$1,View,Linking,KeyboardAvoidingView,Dimensions,Keyboard,Pressable,Modal,ScrollView,ActivityIndicator,Image,AccessibilityInfo,UIManager,LayoutAnimation,Animated,useWindowDimensions,FlatList}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import*as texting from"@everfur/sdk/texting";var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}function weightBucket(weight){return weight<=450?"regular":weight<=650?"medium":"bold"}var MONO_OF={regular:"mono",medium:"monoMedium",bold:"monoBold"};function textRole(theme,role){let byRole=roleCache.get(theme);byRole===void 0&&(byRole=/* @__PURE__ */new Map,roleCache.set(theme,byRole));let hit=byRole.get(role);if(hit!==void 0)return hit;let style=buildRole(theme,role);return byRole.set(role,style),style}var roleCache=/* @__PURE__ */new WeakMap;function buildRole(theme,role){let r=theme.type.roles[role],weight=r.weight==="400"&&r.face!=="mono"?theme.type.weight.regular:r.weight,bucket=weightBucket(Number(weight)),f=r.face==="mono"?face(theme,MONO_OF[bucket]):r.face==="heading"?headingFace(theme,bucket):face(theme,bucket),faceWeight=r.face==="heading"?theme.type.headingWeight??weight:weight,faceStyle=f.fontWeight===void 0?f:{fontFamily:f.fontFamily,fontWeight:faceWeight},fontSize=r.size,out={...faceStyle,fontSize:fontSize,lineHeight:Math.round(fontSize*r.lineHeight*100)/100};return r.letterSpacing!==0&&(out.letterSpacing=Math.round(fontSize*r.letterSpacing*100)/100),r.uppercase&&(out.textTransform="uppercase"),/* @__PURE__ */Object.freeze(out)}var TYPE_ROLE_DEFAULTS=/* @__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 freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3});var SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES,roles:TYPE_ROLE_DEFAULTS,typeScale:1}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier,variant:variant,...props}){let theme=useEverfurTheme(),role=variant===void 0?void 0:theme.type.roles[variant],cap=tierMultiplier(theme.type,tier??role?.tier??"content"),styled=variant===void 0?props:{...props,style:[{...textRole(theme,variant),color:theme.color.text.primary,flexShrink:1},props.style]};return createElement(Text$1,cap===void 0?styled:{maxFontSizeMultiplier:cap,...styled})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...props,...ref===null?{}:{ref:ref}})});var DEFAULT_PRESENTATION=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true,serverSlots:false}),PRESENTATION_WIRE_NAMES=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask",serverSlots:"server_slots"}),FIELDS=Object.keys(PRESENTATION_WIRE_NAMES),PRESENTATION_LOCK="presentation",PRESENTATION_LOCK_PREFIX="presentation.";var ENUMS={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer","none"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},BOOLS=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk","serverSlots"]);function parseField(field,value){if(value==null)return;let allowed=ENUMS[field];return allowed!==void 0?typeof value=="string"&&allowed.includes(value)?value:void 0:BOOLS.has(field)?typeof value=="boolean"?value:void 0:typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=3?value:void 0}function parsePresentation(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let source=raw,out={};for(let field of FIELDS){let wire=PRESENTATION_WIRE_NAMES[field],value=Object.prototype.hasOwnProperty.call(source,wire)?source[wire]:source[field],parsed=parseField(field,value);parsed!==void 0&&(out[field]=parsed)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function isPresentationFieldLocked(field,locked){if(locked==null)return false;let one=`${PRESENTATION_LOCK_PREFIX}${PRESENTATION_WIRE_NAMES[field]}`;for(let name of locked)if(name===PRESENTATION_LOCK||name===one)return true;return false}function resolvePresentation(input){let parsedServer=parsePresentation(input?.server??null)??{},{safetyDisclaimerPlacement:serverPlacement,...serverRest}=parsedServer,server=serverPlacement==="none"||serverPlacement===void 0?serverRest:{...serverRest,safetyDisclaimerPlacement:serverPlacement},client=parsePresentation(input?.client??null)??{},locked=input?.locked?[...input.locked]:null,out={};for(let field of FIELDS){let fromServer=server[field],fromClient=isPresentationFieldLocked(field,locked)?void 0:client[field];out[field]=fromClient??fromServer??DEFAULT_PRESENTATION[field]}/* @__PURE__ */
|
|
3
3
|
return Object.freeze(out)}var EMERGENCY_ER_LINE="Go to the nearest emergency vet now.";var CHAT_COPY=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",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:EMERGENCY_ER_LINE,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";function ok(value,warning){/* @__PURE__ */
|
|
4
4
|
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
5
|
-
return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var RETRYABILITY_ROWS=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze(RETRYABILITY_ROWS.map(row=>/* @__PURE__ */Object.freeze(row)));/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
|
|
5
|
+
return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var RETRYABILITY_ROWS=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"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:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze(RETRYABILITY_ROWS.map(row=>/* @__PURE__ */Object.freeze(row)));/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",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"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
|
|
6
6
|
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function parseUrl(raw,base2){let Url=globalThis.URL;if(typeof Url=="function"){let url;try{url=base2===void 0?new Url(raw):new Url(raw,base2)}catch{return null}try{if(url.protocol)return url}catch{}}return parseByPattern(raw)}var WHOLE_URL=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,REWRITTEN_BY_STANDARD_PARSER=/[\s\u0000-\u001f\u007f\\]/,DEFAULT_PORTS={"http:":"80","https:":"443"};function parseByPattern(raw,base2){let input=raw.trim();let match=REWRITTEN_BY_STANDARD_PARSER.test(input)?null:WHOLE_URL.exec(input);if(match===null)return null;let[,scheme="",username="",password="",host="",portText="",path="",query="",fragment=""]=match,protocol=`${scheme.toLowerCase()}:`,portNumber=Number(portText);if(portNumber>65535)return null;let port=portText===""||String(portNumber)===DEFAULT_PORTS[protocol]?"":String(portNumber),special=DEFAULT_PORTS[protocol]!==void 0,hostPort=host.toLowerCase()+(port&&`:${port}`),pathname=path||(special?"/":""),credentials=username||password?`${username}${password&&`:${password}`}@`:"";return{href:`${protocol}//${credentials}${hostPort}${pathname}${query}${fragment}`,protocol:protocol,username:username,password:password,hostname:host.toLowerCase(),port:port,origin:special?`${protocol}//${hostPort}`:"null",pathname:pathname,search:query==="?"?"":query,hash:fragment==="#"?"":fragment}}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base2=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
7
7
|
/* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
|
|
8
8
|
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop2=()=>{};if(!caller)return{signal:deadline,dispose:noop2};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop2};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var str=(value,max=4e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null;function httpsUrl(value){let s=str(value,2048);return s===null?null:/^https:\/\/[^\s]+$/i.test(s)?s:null}var DETAIL_ROWS=6;function boundOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=400?value:null}function rowsOf(value,each,max){if(!Array.isArray(value))/* @__PURE__ */return Object.freeze([]);let out=[];for(let raw of value){if(out.length>=max)break;if(raw===null||typeof raw!="object"||Array.isArray(raw))continue;let row=each(raw);row!==null&&out.push(row)}/* @__PURE__ */
|
|
@@ -96,7 +96,7 @@ return jsxs(View,{style:styles3.anchor,pointerEvents:"box-none",children:[
|
|
|
96
96
|
/* @__PURE__ */jsx(View,{style:styles3.tileIconWrap,children:source==="photo"?/* @__PURE__ */jsx(PhotoGlyph,{size:TILE_GLYPH,color:theme.color.brandInk,strokeWidth:1.5}):/* @__PURE__ */jsx(CameraGlyph,{size:TILE_GLYPH,color:theme.color.brandInk,strokeWidth:1.5})}),
|
|
97
97
|
/* @__PURE__ */jsx(Text,{tier:"control",style:styles3.tileLabel,children:TILE_LABEL[source]})]},source))}),
|
|
98
98
|
/* @__PURE__ */jsx(View,{style:styles3.tail}),
|
|
99
|
-
/* @__PURE__ */jsx(View,{style:styles3.tailFill})]})]})}function makeStyles2(theme){let c=theme.color,r=theme.radius;return 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:c.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:c.shadow,shadowOpacity:BUBBLE_SHADOW_OPACITY,shadowRadius:BUBBLE_SHADOW_RADIUS,shadowOffset:{width:0,height:BUBBLE_SHADOW_OFFSET_Y},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:TILE_MIN_WIDTH,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:TILE_ICON_SIZE,height:TILE_ICON_SIZE,borderRadius:TILE_ICON_SIZE/2,backgroundColor:c.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(theme,"medium"),fontSize:12,lineHeight:14,color:c.text.primary},tail:{position:"absolute",left:24,bottom:-TAIL_SIZE/2,width:TAIL_SIZE,height:TAIL_SIZE,backgroundColor:c.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:c.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:TAIL_SIZE+4,height:2,backgroundColor:c.surfaceCream}})}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var THUMB_SIZE=56,CARD_RADIUS=12,SINGLE_IMAGE_RADIUS=14,GRID_IMAGE_RADIUS=10,UPLOADING_ALPHA=.45,SUCCESS_OVERLAY="rgba(7,193,104,0.55)",FAILED_OVERLAY="rgba(185,28,28,0.55)",SUCCESS_FLASH_FADE_IN_MS=200,SUCCESS_FLASH_FADE_OUT_MS=300,SUCCESS_GLYPH=20,REMOVE_SIZE=22,REMOVE_GLYPH=12,REMOVE_BG="rgba(0,0,0,0.78)",SINGLE_IMAGE=220,GRID_IMAGE=100,IMAGE_ON_BRAND="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:attachments,rejected:rejected,uploadFailed:uploadFailed=false,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles3(theme),[theme]);return attachments.length===0&&rejected===null?null:/* @__PURE__ */jsxs(View,{style:styles3.strip,children:[attachments.length>0?/* @__PURE__ */jsx(View,{style:styles3.cards,children:attachments.map(row=>/* @__PURE__ */jsx(PreviewCard,{row:row,styles:styles3,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview},row.id))}):null,uploadFailed?/* @__PURE__ */jsx(Text,{style:styles3.rejected,accessibilityRole:"alert",children:CHAT_COPY.attachmentsFailedBlocked}):null,rejected!==null?/* @__PURE__ */jsx(Text,{style:styles3.rejected,accessibilityRole:"alert",children:attachmentErrorMessage(rejected)}):null]})}function PreviewCard({row:row,styles:styles3,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),uploading=row.status==="uploading",failed=row.status==="failed",uploaded=row.status==="uploaded",previous=useRef(row.status),[flash,setFlash]=useState(false);return useEffect(()=>{let before=previous.current;previous.current=row.status,row.status==="uploaded"&&before==="uploading"&&setFlash(true)},[row.status]),/* @__PURE__ */jsxs(View,{style:styles3.card,children:[
|
|
99
|
+
/* @__PURE__ */jsx(View,{style:styles3.tailFill})]})]})}function makeStyles2(theme){let c=theme.color,r=theme.radius;return 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:c.surfaceCream,borderRadius:r.lg,borderWidth:1,borderColor:c.brandBorderStrong,paddingHorizontal:6,paddingVertical:8,shadowColor:c.shadow,shadowOpacity:BUBBLE_SHADOW_OPACITY,shadowRadius:BUBBLE_SHADOW_RADIUS,shadowOffset:{width:0,height:BUBBLE_SHADOW_OFFSET_Y},elevation:8},tilesRow:{flexDirection:"row",alignItems:"stretch"},tile:{minWidth:TILE_MIN_WIDTH,borderRadius:r.md},tileInner:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:10,paddingVertical:8,gap:6},tileIconWrap:{width:TILE_ICON_SIZE,height:TILE_ICON_SIZE,borderRadius:TILE_ICON_SIZE/2,backgroundColor:c.brandSoft,alignItems:"center",justifyContent:"center"},tileLabel:{...face(theme,"medium"),fontSize:12,lineHeight:14,color:c.text.primary},tail:{position:"absolute",left:24,bottom:-TAIL_SIZE/2,width:TAIL_SIZE,height:TAIL_SIZE,backgroundColor:c.surfaceCream,borderRightWidth:1,borderBottomWidth:1,borderColor:c.brandBorderStrong,transform:[{rotate:"45deg"}]},tailFill:{position:"absolute",left:22,bottom:0,width:TAIL_SIZE+4,height:2,backgroundColor:c.surfaceCream}})}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var THUMB_SIZE=56,CARD_RADIUS=12,SINGLE_IMAGE_RADIUS=14,GRID_IMAGE_RADIUS=10,UPLOADING_ALPHA=.45,SUCCESS_OVERLAY="rgba(7,193,104,0.55)",FAILED_OVERLAY="rgba(185,28,28,0.55)",SUCCESS_FLASH_FADE_IN_MS=200,SUCCESS_FLASH_FADE_OUT_MS=300,SUCCESS_GLYPH=20,REMOVE_SIZE=22,REMOVE_GLYPH=12,REMOVE_BG="rgba(0,0,0,0.78)",SINGLE_IMAGE=220,GRID_IMAGE=100,IMAGE_ON_BRAND="rgba(255,255,255,0.15)";function AttachmentStrip({attachments:attachments,rejected:rejected,uploadFailed:uploadFailed=false,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview,style:style}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles3(theme),[theme]);return attachments.length===0&&rejected===null?null:/* @__PURE__ */jsxs(View,{style:[styles3.strip,style],children:[attachments.length>0?/* @__PURE__ */jsx(View,{style:styles3.cards,children:attachments.map(row=>/* @__PURE__ */jsx(PreviewCard,{row:row,styles:styles3,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview},row.id))}):null,uploadFailed?/* @__PURE__ */jsx(Text,{style:styles3.rejected,accessibilityRole:"alert",children:CHAT_COPY.attachmentsFailedBlocked}):null,rejected!==null?/* @__PURE__ */jsx(Text,{style:styles3.rejected,accessibilityRole:"alert",children:attachmentErrorMessage(rejected)}):null]})}function PreviewCard({row:row,styles:styles3,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),uploading=row.status==="uploading",failed=row.status==="failed",uploaded=row.status==="uploaded",previous=useRef(row.status),[flash,setFlash]=useState(false);return useEffect(()=>{let before=previous.current;previous.current=row.status,row.status==="uploaded"&&before==="uploading"&&setFlash(true)},[row.status]),/* @__PURE__ */jsxs(View,{style:styles3.card,children:[
|
|
100
100
|
/* @__PURE__ */jsx(Pressable,{accessibilityRole:uploaded?"button":"image",accessibilityLabel:uploaded?fillCopy(CHAT_COPY.previewAttachment,{filename:row.filename}):row.filename,accessibilityState:{busy:uploading,disabled:!uploaded},disabled:!uploaded,style:styles3.thumbHit,onPress:()=>onPreview(row),children:/* @__PURE__ */jsxs(View,{style:styles3.thumb,children:[
|
|
101
101
|
/* @__PURE__ */jsx(Image,{source:{uri:row.previewUri},style:styles3.thumbImage,resizeMode:"cover",accessibilityIgnoresInvertColors:true}),uploading?/* @__PURE__ */jsx(View,{style:styles3.uploadingOverlay,children:/* @__PURE__ */jsx(ActivityIndicator,{size:"small",color:theme.color.surface})}):null,flash?/* @__PURE__ */jsx(SuccessFlash,{styles:styles3,onDone:()=>setFlash(false)}):null]})}),failed?/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.retryUpload,{filename:row.filename}),style:styles3.failedOverlay,onPress:()=>onRetry(row.id),children:/* @__PURE__ */jsx(View,{style:styles3.failedInner,children:/* @__PURE__ */jsx(CloseGlyph,{size:SUCCESS_GLYPH,color:theme.color.surface,strokeWidth:2})})}):null,
|
|
102
102
|
/* @__PURE__ */jsx(PressScale,{accessibilityRole:"button",accessibilityLabel:fillCopy(CHAT_COPY.removeAttachment,{filename:row.filename}),hitSlop:6,containerStyle:styles3.removeSlot,style:styles3.removeButton,onPress:()=>onRemove(row.id),children:/* @__PURE__ */jsx(CloseGlyph,{size:REMOVE_GLYPH,color:theme.color.surface,strokeWidth:1.5})})]})}function SuccessFlash({styles:styles3,onDone:onDone}){let theme=useEverfurTheme(),motion=useChatMotion(),opacity=useRef(null);opacity.current===null&&(opacity.current=new Animated.Value(0));let value=opacity.current;return useEffect(()=>{let animation=Animated.sequence([Animated.timing(value,{toValue:1,duration:SUCCESS_FLASH_FADE_IN_MS,useNativeDriver:true}),Animated.delay(motion.uploadFlashMs),Animated.timing(value,{toValue:0,duration:SUCCESS_FLASH_FADE_OUT_MS,useNativeDriver:true})]);return animation.start(({finished:finished})=>{finished&&onDone()}),()=>animation.stop()},[value,motion.uploadFlashMs,onDone]),/* @__PURE__ */jsx(Animated.View,{pointerEvents:"none",style:[styles3.successOverlay,{opacity:value}],children:/* @__PURE__ */jsx(CheckGlyph,{size:SUCCESS_GLYPH,color:theme.color.surface,strokeWidth:2})})}function SentImages({images:images,onPreview:onPreview}){let theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles3(theme),[theme]);if(images.length===0)return null;let single=images.length===1;/* @__PURE__ */
|
|
@@ -105,14 +105,14 @@ return Object.freeze({postMultipart(policy,file,opts){if(typeof file.uri!="strin
|
|
|
105
105
|
/* @__PURE__ */jsx(Pressable,{onPress:()=>onToggle(),disabled:disabled,accessibilityRole:"button",accessibilityLabel:active?CHAT_COPY.stopDictation:CHAT_COPY.dictate,accessibilityState:{selected:active,disabled:disabled},style:[styles3.button,disabled?styles3.buttonDisabled:null],testID:"everfur-dictation-button",children:active?/* @__PURE__ */jsxs(Fragment,{children:[
|
|
106
106
|
/* @__PURE__ */jsx(Pulse,{style:styles3.pulse,reduced:theme.motion.reducedMotion}),
|
|
107
107
|
/* @__PURE__ */jsx(StopGlyph,{size:STOP_GLYPH_BOX,color:theme.color.brandInk,testID:"everfur-dictation-stop"})]}):/* @__PURE__ */jsx(MicGlyph,{size:MIC_GLYPH_SIZE,color:theme.color.brandInk,testID:"everfur-dictation-mic"})})]})}function Pulse({style:style,reduced:reduced}){let opacity=useRef(new Animated.Value(1)).current;return useEffect(()=>{if(reduced)return;let loop=Animated.loop(Animated.sequence([Animated.timing(opacity,{toValue:PULSE_LOW,duration:PULSE_LOOP_MS/2,useNativeDriver:true}),Animated.timing(opacity,{toValue:1,duration:PULSE_LOOP_MS/2,useNativeDriver:true})]));return loop.start(),()=>loop.stop()},[opacity,reduced]),/* @__PURE__ */jsx(Animated.View,{style:[style,{opacity:opacity}],accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"})}function makeStyles5(theme){let c=theme.color,micro=theme.type.tierSizes.compact.micro;return StyleSheet.create({wrap:{flexDirection:"row",flexShrink:0,alignItems:"center",gap:theme.space.xs},timer:{...face(theme,"mono"),fontSize:micro,lineHeight:micro+2,fontVariant:["tabular-nums"],color:c.text.muted},button:{width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,borderRadius:theme.radius.pill,alignItems:"center",justifyContent:"center"},buttonDisabled:{opacity:DISABLED_OPACITY},pulse:{position:"absolute",top:PULSE_INSET,right:PULSE_INSET,bottom:PULSE_INSET,left:PULSE_INSET,borderRadius:theme.radius.pill,backgroundColor:c.brandSofter}})}function optionalModule(name,load,validate2){let candidate;try{candidate=load()}catch(cause){return frozenUnavailable(`optional peer '${name}' is not installed: ${describe(cause)}`)}let resolved=unwrapDefault(candidate);return resolved==null?frozenUnavailable(`optional peer '${name}' resolved to no module`):validate2&&!validate2(resolved)?frozenUnavailable(`optional peer '${name}' is present but failed its shape check`):/* @__PURE__ */Object.freeze({available:true,module:resolved})}function unwrapDefault(candidate){return typeof candidate=="object"&&candidate!==null&&"default"in candidate&&Object.keys(candidate).length<=2?candidate.default:candidate}function frozenUnavailable(reason){/* @__PURE__ */
|
|
108
|
-
return Object.freeze({available:false,module:null,reason:reason})}function describe(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"unknown load error"}var SLOT_KEY=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function slot(){let realm=globalThis,existing=realm[SLOT_KEY];if(existing!==void 0)return existing;let created={loader:null,memo:void 0};return realm[SLOT_KEY]=created,created}function registerEverfurDictation(next){let state=slot();state.loader=next,state.memo=void 0,state.version=(state.version??0)+1;for(let listener of[...state.listeners??[]])try{listener()}catch{}}function dictationRegistrationVersion(){return slot().version??0}function subscribeDictationRegistration(listener){let state=slot(),listeners2=state.listeners??/* @__PURE__ */new Set;state.listeners=listeners2;let entry=()=>listener();return listeners2.add(entry),()=>{listeners2.delete(entry)}}function isSpeechModule(candidate){if(typeof candidate!="object"||candidate===null)return false;let mod=candidate;return typeof mod.start=="function"&&typeof mod.isRecognitionAvailable=="function"&&typeof mod.addListener=="function"}function speechModuleOf(candidate){return typeof candidate!="object"||candidate===null?null:candidate.ExpoSpeechRecognitionModule??candidate}function loadNativeSpeech(){let state=slot();if(state.memo!==void 0)return state.memo;state.memo=null;let load=state.loader;if(load===null||Platform.OS!=="ios"&&Platform.OS!=="android")return state.memo;let loaded=optionalModule("expo-speech-recognition",()=>({box:speechModuleOf(load())}),box2=>typeof box2=="object"&&box2!==null&&isSpeechModule(box2.box));return loaded.available&&(state.memo=loaded.module.box),state.memo}function isNativeDictationAvailable(mod){if(mod===null)return false;try{return mod.isRecognitionAvailable()===!0}catch{return false}}function deviceLocale(){try{return Intl.DateTimeFormat().resolvedOptions().locale||FALLBACK_DICTATION_LOCALE}catch{return FALLBACK_DICTATION_LOCALE}}function normalizeTag(tag){return tag.replace(/_/g,"-").toLowerCase()}var FALLBACK_DICTATION_LOCALE="en-US";function resolveNativeDictationLocale(locale=deviceLocale()){let[base2=""]=locale.replace(/_/g,"-").split("-u-"),parts=base2.split("-");if(parts[0]?.toLowerCase()!=="en")return FALLBACK_DICTATION_LOCALE;let region=parts.slice(1).find(part=>/^[A-Za-z]{2}$/.test(part));return region?`en-${region.toUpperCase()}`:FALLBACK_DICTATION_LOCALE}function pickSupportedLocale(wanted,supported){if(supported.length===0)return null;let find=tag=>supported.find(locale=>normalizeTag(locale)===normalizeTag(tag));return find(wanted)??find(FALLBACK_DICTATION_LOCALE)??supported.find(locale=>normalizeTag(locale).startsWith("en-"))??null}async function resolveRecognizerLocale(mod,wanted){if(Platform.OS!=="ios")return wanted;try{let{locales:locales}=await mod.getSupportedLocales({});return pickSupportedLocale(wanted,locales??[])??wanted}catch{return wanted}}async function chooseNativeDictationMode(mod,lang){let onDevice=false;try{onDevice=mod.supportsOnDeviceRecognition()===!0}catch{onDevice=false}if(!onDevice)return"network";if(Platform.OS!=="android")return"on_device";try{let{installedLocales:installedLocales}=await mod.getSupportedLocales({}),wanted=normalizeTag(lang);return(installedLocales??[]).some(locale=>normalizeTag(locale)===wanted)?"on_device":"network"}catch{return"network"}}function supportsContinuous(){return Platform.OS!=="android"?true:Number(Platform.Version)>=ANDROID_13_API}var ANDROID_13_API=33;function buildStartOptions(mode,lang,phrases){return{lang:lang,interimResults:true,continuous:supportsContinuous(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:mode==="on_device",contextualStrings:phrases.slice(0,100),iosTaskHint:"dictation"}}var NOT_RETRYABLE=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),NATIVE_DICTATION_MAX_RETRIES=2;function nextDictationAttempt(mode,lang,code){return NOT_RETRYABLE.has(code)?null:code==="language-not-supported"&&normalizeTag(lang)!==normalizeTag(FALLBACK_DICTATION_LOCALE)?{mode:"network",lang:FALLBACK_DICTATION_LOCALE}:mode==="on_device"?{mode:"network",lang:lang}:null}function mapNativeDictationError(code){return code==="not-allowed"?"permissionDenied":code==="no-speech"||code==="speech-timeout"?"noSpeech":"unavailable"}async function requestNativeDictationPermission(mod){try{if((await mod.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await mod.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var NATIVE_DICTATION_AUTO_STOP_MS=55e3,END_GRACE_MS=3e3,STALE_END_WINDOW_MS=1e3,BENIGN_WITH_TEXT=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),EMPTY_TRANSCRIPT=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function clean2(text3){return text3.replace(/\s+/g," ").trim()}function applyResult(state,transcript,isFinal){let text3=clean2(transcript);return isFinal?text3?{committed:[...state.committed,text3],interim:""}:{committed:state.committed,interim:""}:{committed:state.committed,interim:text3}}function transcriptText(state){return clean2([...state.committed,state.interim].join(" "))}function createNativeDictationController(mod,events,telemetry,now=Date.now){let tokenSeq=0,attempt=null,lastAbortAt=Number.NEGATIVE_INFINITY,current=token=>attempt!==null&&attempt.token===token?attempt:null;function removeListeners(a){for(let subscription of a.subscriptions)try{subscription.remove()}catch{}a.subscriptions=[]}function teardown(a){removeListeners(a),a.autoStopTimer!==null&&clearTimeout(a.autoStopTimer),a.graceTimer!==null&&clearTimeout(a.graceTimer),a.autoStopTimer=null,a.graceTimer=null,attempt===a&&(attempt=null)}function isStaleEnd(a){return!a.sawStart&&a.errorCode===null&&a.pendingRetry===null&&transcriptText(a.transcript)===""&&a.launchedAt-lastAbortAt<STALE_END_WINDOW_MS}function modeOf(a){return a.mode??"none"}function trackCompleted(a,text3){trackDictationEvent(telemetry(),"chat_dictation_completed",{mode:modeOf(a),duration_ms:a.startedAt===null?0:Math.max(0,now()-a.startedAt),char_count:text3.length})}function fail(a,kind){trackDictationEvent(telemetry(),"chat_dictation_failed",{mode:modeOf(a),error:kind}),events.onStatus("idle"),events.onError(kind)}function finish(a){if(current(a.token)===null)return;teardown(a);let text3=transcriptText(a.transcript),code=a.errorCode;if(code!==null&&!(text3&&BENIGN_WITH_TEXT.has(code))){fail(a,mapNativeDictationError(code));return}if(!text3){fail(a,"noSpeech");return}trackCompleted(a,text3),events.onStatus("idle")}function subscribe2(a){a.subscriptions=[mod.addListener("start",()=>{current(a.token)!==null&&(a.sawStart=true,a.startedAt===null&&(a.startedAt=now()),trackDictationEvent(telemetry(),"chat_dictation_started",{mode:modeOf(a)}),events.onStatus("listening"))}),mod.addListener("result",event=>{if(current(a.token)===null)return;let first=event?.results?.[0]?.transcript??"";a.transcript=applyResult(a.transcript,first,event?.isFinal===true),events.onText(transcriptText(a.transcript))}),mod.addListener("error",event=>{if(current(a.token)===null)return;let code=event?.error??"unknown";if(code==="aborted"&&a.userStopped)return;let nothingYet=transcriptText(a.transcript)==="",retry=a.mode!==null&&!a.userStopped&¬hingYet&&a.retries<NATIVE_DICTATION_MAX_RETRIES?nextDictationAttempt(a.mode,a.lang,code):null;if(retry!==null){a.pendingRetry=retry;return}a.errorCode===null&&(a.errorCode=code)}),mod.addListener("end",()=>{if(current(a.token)!==null&&!isStaleEnd(a)){if(a.pendingRetry!==null){let retry=a.pendingRetry;a.pendingRetry=null,a.retries+=1,a.lang=retry.lang,launch(a,retry.mode);return}finish(a)}})]}function launch(a,mode){removeListeners(a),a.mode=mode,a.sawStart=false,a.launchedAt=now(),a.transcript=EMPTY_TRANSCRIPT,a.errorCode=null,subscribe2(a);try{mod.start(buildStartOptions(mode,a.lang,a.phrases))}catch{a.errorCode="unknown",finish(a)}}async function prepare(a){let permission=await requestNativeDictationPermission(mod);if(current(a.token)===null)return;if(permission!=="granted"){teardown(a),fail(a,permission==="denied"?"permissionDenied":"unavailable");return}if(a.lang=await resolveRecognizerLocale(mod,a.lang),current(a.token)===null)return;let mode=await chooseNativeDictationMode(mod,a.lang);current(a.token)!==null&&(a.autoStopTimer=setTimeout(()=>stopAttempt(a),NATIVE_DICTATION_AUTO_STOP_MS),launch(a,mode))}function stopAttempt(a){if(!(current(a.token)===null||a.userStopped)){if(a.userStopped=true,a.pendingRetry=null,a.mode===null){teardown(a),events.onStatus("idle");return}a.graceTimer=setTimeout(()=>finish(a),END_GRACE_MS);try{mod.stop()}catch{finish(a)}}}return{start(phrases){if(attempt!==null)return;let a={token:++tokenSeq,phrases:phrases,lang:resolveNativeDictationLocale(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:EMPTY_TRANSCRIPT,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null};attempt=a,events.onStatus("starting"),prepare(a)},stop(){attempt!==null&&stopAttempt(attempt)},cancel(){let a=attempt;if(a===null)return;let launched=a.mode!==null,text3=transcriptText(a.transcript);if(teardown(a),events.onStatus("idle"),!!launched){text3&&trackCompleted(a,text3),lastAbortAt=now();try{mod.abort()}catch{}}},isActive:()=>attempt!==null,isPreparing:()=>attempt!==null&&attempt.mode===null}}function useNativeDictation({enabled:enabled,input:input,setInput:setInput,phrases:phrases,maxLength:maxLength,telemetry:telemetry}){let registration=useSyncExternalStore(subscribeDictationRegistration,dictationRegistrationVersion,dictationRegistrationVersion),mod=useMemo(()=>enabled?loadNativeSpeech():null,[enabled,registration]),available=useMemo(()=>isNativeDictationAvailable(mod),[mod]),[status,setStatus]=useState("idle"),[error,setError]=useState(null),[elapsedMs,setElapsedMs]=useState(0),inputRef=useRef(input);inputRef.current=input;let setInputRef=useRef(setInput);setInputRef.current=setInput;let telemetryRef=useRef(telemetry);telemetryRef.current=telemetry;let baseRef=useRef(""),maxRef=useRef(maxLength);maxRef.current=maxLength;let controllerRef=useRef(null);mod!==null&&controllerRef.current?.mod!==mod&&(controllerRef.current?.controller.cancel(),controllerRef.current={mod:mod,controller:createNativeDictationController(mod,{onStatus:next=>{setStatus(previous=>next==="idle"&&previous==="error"?previous:next)},onText:dictated=>setInputRef.current(composeDictatedText(baseRef.current,dictated,maxRef.current)),onError:kind=>{setError(kind),setStatus("error")}},()=>telemetryRef.current)});let controller=mod===null?null:controllerRef.current?.controller??null,cancel=useCallback(()=>{controller?.cancel()},[controller]),toggle=useCallback(()=>{if(controller!==null){if(controller.isActive()){controller.stop();return}setError(null),setElapsedMs(0),baseRef.current=inputRef.current,controller.start(phrases)}},[controller,phrases]);useEffect(()=>{if(status!=="listening")return;let startedAt=Date.now();setElapsedMs(0);let handle=setInterval(()=>setElapsedMs(Date.now()-startedAt),1e3);return()=>clearInterval(handle)},[status]),useEffect(()=>{if(status!=="error")return;let handle=setTimeout(()=>{setError(null),setStatus("idle")},DICTATION_ERROR_VISIBLE_MS);return()=>clearTimeout(handle)},[status]),useEffect(()=>{if(controller===null)return;let subscription=null;try{subscription=AppState.addEventListener("change",next=>{next==="background"&&!controller.isPreparing()&&controller.cancel()})}catch{}return()=>{subscription?.remove(),controller.cancel()}},[controller]);let supported=enabled&&available;return useEffect(()=>{supported||controller?.cancel()},[supported,controller]),{supported:supported,status:status,active:status==="starting"||status==="listening",error:error,elapsedMs:elapsedMs,toggle:toggle,cancel:cancel}}var KEY=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function shared(){let g=globalThis,existing=g[KEY];if(existing!==void 0)return existing;let fresh2=createContext(true);return g[KEY]=fresh2,fresh2}var ChatPaneShownContext=shared();function useChatPaneShown(){return useContext(ChatPaneShownContext)}var DEFAULT_SOURCES=/* @__PURE__ */Object.freeze(["photo"]),COMPACT_HEIGHT=52,COMPACT_RING=1.5,COMPACT_INSET_TOP=10,COMPACT_INSET_SIDE=14,COMPACT_INSET_FOOT=10,COMPACT_DISC=40,COMPACT_ARROW=20,COMPACT_DIM_OPACITY=.3,COMPACT_RING_FOCUSED=2.5,COMPACT_INPUT_STEP=1,COMPACT_INPUT_LEAD=1.5,COMPACT_ADD=38,COMPACT_ADD_GLYPH=22,COMPACT_ADD_SLOP=3;function composerPlaceholder(branded,petName,petPlaceholder,mood="ask"){let named=typeof petName=="string"&&petName.trim()!=="";return petPlaceholder&&named&&mood!=="urgent"?forPet(CHAT_COPY.placeholder,petName):branded!==null?branded:mood==="urgent"?CHAT_COPY.placeholderUrgentWeb:mood==="followUp"?CHAT_COPY.placeholderFollowUpWeb:forPet(CHAT_COPY.placeholder,petName)}function ComposerWithAttachments({attachments:attachments,...rest}){let transport=useMemo(()=>createRnChatAttachmentTransport(),[]),state=useChatAttachments({maxPerMessage:attachments.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,transport:transport}),bound=useMemo(()=>({state:state,sources:attachments.sources??DEFAULT_SOURCES,pick:attachments.pick}),[state,attachments.sources,attachments.pick]);/* @__PURE__ */
|
|
109
|
-
return jsx(Composer,{...rest,attachments:bound})}function Composer({send:send,stop:stop,isStreaming:isStreaming,conversationId:conversationId,attachments:attachments,seed:seed,draftStore:draftStore,onStage:onStage,onPreview:onPreview,petName:petName,petBreed:petBreed=null,mood:mood="ask",dictation:dictation=false,telemetry:telemetry=null,compact:compact=false,petPlaceholder:petPlaceholder=false,dimEmptySend:dimEmptySend=false}){let{theme:theme,styles:styles3}=useChatTheme(),compactStyles=useMemo(()=>makeCompactStyles(theme),[theme]),motion=useChatMotion(),[draft,setDraft]=useChatDraft(send,conversationId,seed),[pickerOpen,setPickerOpen]=useState(false),[focused,setFocused]=useState(false),onFocus=useCallback(()=>setFocused(true),[]),onBlur=useCallback(()=>setFocused(false),[]),[pickFailed,setPickFailed]=useState(false);useEffect(()=>{setPickFailed(false)},[conversationId]);let placeholder=composerPlaceholder(theme.meta.placeholder,petName,petPlaceholder,mood),phrases=useMemo(()=>buildDictationPhrases({name:petName,breed:petBreed}),[petName,petBreed]),voice=useNativeDictation({enabled:dictation,input:draft,setInput:setDraft,phrases:phrases,maxLength:MESSAGE_MAX_CHARS,telemetry:telemetry}),cancelDictation=voice.cancel,dictating=voice.active;usePersistedDraft(draftStore,conversationId===null?null:String(conversationId),draft,setDraft,dictating);let seenConversation=useRef(conversationId);useEffect(()=>{seenConversation.current!==conversationId&&(seenConversation.current=conversationId,cancelDictation())},[conversationId,cancelDictation]);let paneShown=useChatPaneShown();useEffect(()=>{paneShown||cancelDictation()},[paneShown,cancelDictation]);let uploading=attachments?.state.uploading??false,uploadFailed=attachments?.state.failed??false,sendBlocked=uploading||uploadFailed,rows=attachments?.state.attachments??NO_ROWS;useAnimateLayoutOn(rows.length,motion);let onSend=useCallback(()=>{let text3=draft.trim();if(text3.length===0||sendBlocked||[...text3].length>MESSAGE_MAX_CHARS)return;dictating&&cancelDictation();let keys=attachments?.state.s3Keys??NO_KEYS;attachments!==null&&keys.length>0?(onStage(attachments.state.attachments.filter(row=>row.status==="uploaded").map(row=>({uri:row.previewUri,filename:row.filename}))),send(text3,{imageS3Keys:keys}),attachments.state.clear()):send(text3),setDraft(""),setPickFailed(false)},[draft,send,sendBlocked,dictating,cancelDictation,attachments,onStage]),onChangeText=useCallback(next=>{dictating&&cancelDictation(),setDraft(next)},[dictating,cancelDictation,setDraft]),onStop=useCallback(()=>{stop()},[stop]),pickFrom=useCallback(source=>{setPickerOpen(false),attachments!==null&&(setPickFailed(false),attachments.state.dismissRejected(),callHostAsync(attachments.pick,source).then(outcome=>{if(!outcome.ok){setPickFailed(true);return}outcome.value!==null&&attachments.state.add(outcome.value)}))},[attachments]),isOverLimit=useMemo(()=>[...draft.trim()].length>MESSAGE_MAX_CHARS,[draft]),sendDisabled=isOverLimit||sendBlocked||draft.trim().length===0,sendDimmed=isOverLimit||sendBlocked||dimEmptySend&&draft.trim().length===0,slotsFull=attachments!==null&&rows.length>=attachments.state.maxPerMessage,sendInk=theme.slots.sendButton?.textColor??theme.color.brandInk,compactInk=theme.slots.sendButton?.textColor??theme.color.surface;/* @__PURE__ */
|
|
110
|
-
return jsxs(View,{style:styles3.composerOuter,children:[attachments!==null&&pickerOpen?/* @__PURE__ */jsx(AttachmentPickerPopover,{sources:attachments.sources,full:slotsFull,onPick:pickFrom,onClose:()=>setPickerOpen(false)}):null,
|
|
111
|
-
/* @__PURE__ */jsxs(View,{style:compact?[styles3.composer,compactStyles.bar,focused?compactStyles.barFocused:null]:styles3.composer,children:[
|
|
108
|
+
return Object.freeze({available:false,module:null,reason:reason})}function describe(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"unknown load error"}var SLOT_KEY=/* @__PURE__ */Symbol.for("@everfur/sdk/rn-dictation");function slot(){let realm=globalThis,existing=realm[SLOT_KEY];if(existing!==void 0)return existing;let created={loader:null,memo:void 0};return realm[SLOT_KEY]=created,created}function registerEverfurDictation(next){let state=slot();state.loader=next,state.memo=void 0,state.version=(state.version??0)+1;for(let listener of[...state.listeners??[]])try{listener()}catch{}}function dictationRegistrationVersion(){return slot().version??0}function subscribeDictationRegistration(listener){let state=slot(),listeners2=state.listeners??/* @__PURE__ */new Set;state.listeners=listeners2;let entry=()=>listener();return listeners2.add(entry),()=>{listeners2.delete(entry)}}function isSpeechModule(candidate){if(typeof candidate!="object"||candidate===null)return false;let mod=candidate;return typeof mod.start=="function"&&typeof mod.isRecognitionAvailable=="function"&&typeof mod.addListener=="function"}function speechModuleOf(candidate){return typeof candidate!="object"||candidate===null?null:candidate.ExpoSpeechRecognitionModule??candidate}function loadNativeSpeech(){let state=slot();if(state.memo!==void 0)return state.memo;state.memo=null;let load=state.loader;if(load===null||Platform.OS!=="ios"&&Platform.OS!=="android")return state.memo;let loaded=optionalModule("expo-speech-recognition",()=>({box:speechModuleOf(load())}),box2=>typeof box2=="object"&&box2!==null&&isSpeechModule(box2.box));return loaded.available&&(state.memo=loaded.module.box),state.memo}function isNativeDictationAvailable(mod){if(mod===null)return false;try{return mod.isRecognitionAvailable()===!0}catch{return false}}function deviceLocale(){try{return Intl.DateTimeFormat().resolvedOptions().locale||FALLBACK_DICTATION_LOCALE}catch{return FALLBACK_DICTATION_LOCALE}}function normalizeTag(tag){return tag.replace(/_/g,"-").toLowerCase()}var FALLBACK_DICTATION_LOCALE="en-US";function resolveNativeDictationLocale(locale=deviceLocale()){let[base2=""]=locale.replace(/_/g,"-").split("-u-"),parts=base2.split("-");if(parts[0]?.toLowerCase()!=="en")return FALLBACK_DICTATION_LOCALE;let region=parts.slice(1).find(part=>/^[A-Za-z]{2}$/.test(part));return region?`en-${region.toUpperCase()}`:FALLBACK_DICTATION_LOCALE}function pickSupportedLocale(wanted,supported){if(supported.length===0)return null;let find=tag=>supported.find(locale=>normalizeTag(locale)===normalizeTag(tag));return find(wanted)??find(FALLBACK_DICTATION_LOCALE)??supported.find(locale=>normalizeTag(locale).startsWith("en-"))??null}async function resolveRecognizerLocale(mod,wanted){if(Platform.OS!=="ios")return wanted;try{let{locales:locales}=await mod.getSupportedLocales({});return pickSupportedLocale(wanted,locales??[])??wanted}catch{return wanted}}async function chooseNativeDictationMode(mod,lang){let onDevice=false;try{onDevice=mod.supportsOnDeviceRecognition()===!0}catch{onDevice=false}if(!onDevice)return"network";if(Platform.OS!=="android")return"on_device";try{let{installedLocales:installedLocales}=await mod.getSupportedLocales({}),wanted=normalizeTag(lang);return(installedLocales??[]).some(locale=>normalizeTag(locale)===wanted)?"on_device":"network"}catch{return"network"}}function supportsContinuous(){return Platform.OS!=="android"?true:Number(Platform.Version)>=ANDROID_13_API}var ANDROID_13_API=33;function buildStartOptions(mode,lang,phrases){return{lang:lang,interimResults:true,continuous:supportsContinuous(),maxAlternatives:1,addsPunctuation:true,requiresOnDeviceRecognition:mode==="on_device",contextualStrings:phrases.slice(0,100),iosTaskHint:"dictation"}}var NOT_RETRYABLE=/* @__PURE__ */new Set(["not-allowed","no-speech","speech-timeout","aborted","interrupted"]),TRANSIENT_DICTATION_CODES=/* @__PURE__ */new Set(["busy","client","network","audio-capture","too-many-requests","unknown"]);function isTransientDictationError(code){return TRANSIENT_DICTATION_CODES.has(code)}var NATIVE_DICTATION_RETRY_SETTLE_MS=600,NATIVE_DICTATION_MAX_RETRIES=3;function nextDictationAttempt(mode,lang,code){if(NOT_RETRYABLE.has(code))return null;let delayMs=isTransientDictationError(code)?NATIVE_DICTATION_RETRY_SETTLE_MS:0;return code==="language-not-supported"&&normalizeTag(lang)!==normalizeTag(FALLBACK_DICTATION_LOCALE)?{mode:"network",lang:FALLBACK_DICTATION_LOCALE,delayMs:delayMs}:mode==="on_device"?{mode:"network",lang:lang,delayMs:delayMs}:delayMs>0?{mode:"network",lang:lang,delayMs:delayMs}:null}function mapNativeDictationError(code){return code==="not-allowed"?"permissionDenied":code==="no-speech"||code==="speech-timeout"?"noSpeech":"unavailable"}async function requestNativeDictationPermission(mod){try{if((await mod.getPermissionsAsync()).granted)return"granted"}catch{}try{return(await mod.requestPermissionsAsync()).granted?"granted":"denied"}catch{return"error"}}var NATIVE_DICTATION_AUTO_STOP_MS=55e3,END_GRACE_MS=3e3,STALE_END_WINDOW_MS=1e3;function benignWithText(code){return BENIGN_ENDINGS.has(code)||isTransientDictationError(code)}var BENIGN_ENDINGS=/* @__PURE__ */new Set(["no-speech","speech-timeout","aborted","interrupted"]),EMPTY_TRANSCRIPT=/* @__PURE__ */Object.freeze({committed:/* @__PURE__ */Object.freeze([]),interim:""});function clean2(text3){return text3.replace(/\s+/g," ").trim()}function applyResult(state,transcript,isFinal){let text3=clean2(transcript);return isFinal?text3?{committed:[...state.committed,text3],interim:""}:{committed:state.committed,interim:""}:{committed:state.committed,interim:text3}}function transcriptText(state){return clean2([...state.committed,state.interim].join(" "))}function createNativeDictationController(mod,events,telemetry,now=Date.now){let tokenSeq=0,attempt=null,lastAbortAt=Number.NEGATIVE_INFINITY,current=token=>attempt!==null&&attempt.token===token?attempt:null;function removeListeners(a){for(let subscription of a.subscriptions)try{subscription.remove()}catch{}a.subscriptions=[]}function teardown(a){removeListeners(a),a.autoStopTimer!==null&&clearTimeout(a.autoStopTimer),a.graceTimer!==null&&clearTimeout(a.graceTimer),a.retryTimer!==null&&clearTimeout(a.retryTimer),a.autoStopTimer=null,a.graceTimer=null,a.retryTimer=null,attempt===a&&(attempt=null)}function isStaleEnd(a){return!a.sawStart&&a.errorCode===null&&a.pendingRetry===null&&transcriptText(a.transcript)===""&&a.launchedAt-lastAbortAt<STALE_END_WINDOW_MS}function modeOf(a){return a.mode??"none"}function trackCompleted(a,text3){trackDictationEvent(telemetry(),"chat_dictation_completed",{mode:modeOf(a),duration_ms:a.startedAt===null?0:Math.max(0,now()-a.startedAt),char_count:text3.length})}function fail(a,kind){trackDictationEvent(telemetry(),"chat_dictation_failed",{mode:modeOf(a),error:kind}),events.onStatus("idle"),events.onError(kind)}function finish(a){if(current(a.token)===null)return;teardown(a);let text3=transcriptText(a.transcript),code=a.errorCode;if(code!==null&&!(text3&&benignWithText(code))){fail(a,mapNativeDictationError(code));return}if(!text3){fail(a,"noSpeech");return}trackCompleted(a,text3),events.onStatus("idle")}function subscribe2(a){a.subscriptions=[mod.addListener("start",()=>{current(a.token)!==null&&(a.sawStart=true,a.startedAt===null&&(a.startedAt=now()),trackDictationEvent(telemetry(),"chat_dictation_started",{mode:modeOf(a)}),events.onStatus("listening"))}),mod.addListener("result",event=>{if(current(a.token)===null)return;let first=event?.results?.[0]?.transcript??"";a.transcript=applyResult(a.transcript,first,event?.isFinal===true),events.onText(transcriptText(a.transcript))}),mod.addListener("error",event=>{if(current(a.token)===null)return;let code=event?.error??"unknown";if(a.userStopped&&(code==="aborted"||isTransientDictationError(code)))return;let nothingYet=transcriptText(a.transcript)==="",retry=a.mode!==null&&!a.userStopped&¬hingYet&&a.retries<NATIVE_DICTATION_MAX_RETRIES?nextDictationAttempt(a.mode,a.lang,code):null;if(retry!==null){a.pendingRetry=retry;return}a.errorCode===null&&(a.errorCode=code)}),mod.addListener("end",()=>{if(current(a.token)!==null&&!isStaleEnd(a)){if(a.pendingRetry!==null){let retry=a.pendingRetry;if(a.pendingRetry=null,a.retries+=1,a.lang=retry.lang,retry.delayMs<=0){launch(a,retry.mode);return}removeListeners(a),a.retryTimer=setTimeout(()=>{a.retryTimer=null,!(current(a.token)===null||a.userStopped)&&launch(a,retry.mode)},retry.delayMs);return}finish(a)}})]}function launch(a,mode){removeListeners(a),a.mode=mode,a.sawStart=false,a.launchedAt=now(),a.transcript=EMPTY_TRANSCRIPT,a.errorCode=null,subscribe2(a);try{mod.start(buildStartOptions(mode,a.lang,a.phrases))}catch{a.errorCode="unknown",finish(a)}}async function prepare(a){let permission=await requestNativeDictationPermission(mod);if(current(a.token)===null)return;if(permission!=="granted"){teardown(a),fail(a,permission==="denied"?"permissionDenied":"unavailable");return}if(a.lang=await resolveRecognizerLocale(mod,a.lang),current(a.token)===null)return;let mode=await chooseNativeDictationMode(mod,a.lang);current(a.token)!==null&&(a.autoStopTimer=setTimeout(()=>stopAttempt(a),NATIVE_DICTATION_AUTO_STOP_MS),launch(a,mode))}function stopAttempt(a){if(!(current(a.token)===null||a.userStopped)){if(a.userStopped=true,a.pendingRetry=null,a.mode===null||a.retryTimer!==null){teardown(a),events.onStatus("idle");return}a.graceTimer=setTimeout(()=>finish(a),END_GRACE_MS);try{mod.stop()}catch{finish(a)}}}return{start(phrases){if(attempt!==null)return;let a={token:++tokenSeq,phrases:phrases,lang:resolveNativeDictationLocale(),mode:null,retries:0,pendingRetry:null,userStopped:false,transcript:EMPTY_TRANSCRIPT,errorCode:null,startedAt:null,sawStart:false,launchedAt:0,subscriptions:[],autoStopTimer:null,graceTimer:null,retryTimer:null};attempt=a,events.onStatus("starting"),prepare(a)},stop(){attempt!==null&&stopAttempt(attempt)},cancel(){let a=attempt;if(a===null)return;let launched=a.mode!==null&&a.retryTimer===null,text3=transcriptText(a.transcript);if(teardown(a),events.onStatus("idle"),!!launched){text3&&trackCompleted(a,text3),lastAbortAt=now();try{mod.abort()}catch{}}},isActive:()=>attempt!==null,isPreparing:()=>attempt!==null&&attempt.mode===null}}function useNativeDictation({enabled:enabled,input:input,setInput:setInput,phrases:phrases,maxLength:maxLength,telemetry:telemetry}){let registration=useSyncExternalStore(subscribeDictationRegistration,dictationRegistrationVersion,dictationRegistrationVersion),mod=useMemo(()=>enabled?loadNativeSpeech():null,[enabled,registration]),available=useMemo(()=>isNativeDictationAvailable(mod),[mod]),[status,setStatus]=useState("idle"),[error,setError]=useState(null),[elapsedMs,setElapsedMs]=useState(0),inputRef=useRef(input);inputRef.current=input;let setInputRef=useRef(setInput);setInputRef.current=setInput;let telemetryRef=useRef(telemetry);telemetryRef.current=telemetry;let baseRef=useRef(""),maxRef=useRef(maxLength);maxRef.current=maxLength;let controllerRef=useRef(null);mod!==null&&controllerRef.current?.mod!==mod&&(controllerRef.current?.controller.cancel(),controllerRef.current={mod:mod,controller:createNativeDictationController(mod,{onStatus:next=>{setStatus(previous=>next==="idle"&&previous==="error"?previous:next)},onText:dictated=>setInputRef.current(composeDictatedText(baseRef.current,dictated,maxRef.current)),onError:kind=>{setError(kind),setStatus("error")}},()=>telemetryRef.current)});let controller=mod===null?null:controllerRef.current?.controller??null,cancel=useCallback(()=>{controller?.cancel()},[controller]),toggle=useCallback(()=>{if(controller!==null){if(controller.isActive()){controller.stop();return}setError(null),setElapsedMs(0),baseRef.current=inputRef.current,controller.start(phrases)}},[controller,phrases]);useEffect(()=>{if(status!=="listening")return;let startedAt=Date.now();setElapsedMs(0);let handle=setInterval(()=>setElapsedMs(Date.now()-startedAt),1e3);return()=>clearInterval(handle)},[status]),useEffect(()=>{if(status!=="error")return;let handle=setTimeout(()=>{setError(null),setStatus("idle")},DICTATION_ERROR_VISIBLE_MS);return()=>clearTimeout(handle)},[status]),useEffect(()=>{if(controller===null)return;let subscription=null;try{subscription=AppState.addEventListener("change",next=>{next==="background"&&!controller.isPreparing()&&controller.cancel()})}catch{}return()=>{subscription?.remove(),controller.cancel()}},[controller]);let supported=enabled&&available;return useEffect(()=>{supported||controller?.cancel()},[supported,controller]),{supported:supported,status:status,active:status==="starting"||status==="listening",error:error,elapsedMs:elapsedMs,toggle:toggle,cancel:cancel}}var KEY=/* @__PURE__ */Symbol.for("everfur.sdk.rn.chatPaneShown");function shared(){let g=globalThis,existing=g[KEY];if(existing!==void 0)return existing;let fresh2=createContext(true);return g[KEY]=fresh2,fresh2}var ChatPaneShownContext=shared();function useChatPaneShown(){return useContext(ChatPaneShownContext)}var DEFAULT_SOURCES=/* @__PURE__ */Object.freeze(["photo"]),COMPACT_HEIGHT=52,COMPACT_RING=1.5,COMPACT_INSET_TOP=10,COMPACT_INSET_SIDE=14,COMPACT_INSET_FOOT=10,COMPACT_DISC=40,COMPACT_ARROW=20,COMPACT_DIM_OPACITY=.3,COMPACT_RING_FOCUSED=2.5,COMPACT_INPUT_STEP=1,COMPACT_INPUT_LEAD=1.5,COMPACT_ADD=38,COMPACT_ADD_GLYPH=22,COMPACT_ADD_SLOP=3;function composerPlaceholder(branded,petName,petPlaceholder,mood="ask"){let named=typeof petName=="string"&&petName.trim()!=="";return petPlaceholder&&named&&mood!=="urgent"?forPet(CHAT_COPY.placeholder,petName):branded!==null?branded:mood==="urgent"?CHAT_COPY.placeholderUrgentWeb:mood==="followUp"?CHAT_COPY.placeholderFollowUpWeb:forPet(CHAT_COPY.placeholder,petName)}function ComposerWithAttachments({attachments:attachments,...rest}){let transport=useMemo(()=>createRnChatAttachmentTransport(),[]),state=useChatAttachments({maxPerMessage:attachments.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,transport:transport}),bound=useMemo(()=>({state:state,sources:attachments.sources??DEFAULT_SOURCES,pick:attachments.pick}),[state,attachments.sources,attachments.pick]);/* @__PURE__ */
|
|
109
|
+
return jsx(Composer,{...rest,attachments:bound})}function Composer({send:send,stop:stop,isStreaming:isStreaming,conversationId:conversationId,attachments:attachments,seed:seed,draftStore:draftStore,onStage:onStage,onPreview:onPreview,petName:petName,petBreed:petBreed=null,mood:mood="ask",dictation:dictation=false,telemetry:telemetry=null,compact:compact=false,petPlaceholder:petPlaceholder=false,dimEmptySend:dimEmptySend=false}){let{theme:theme,styles:styles3}=useChatTheme(),compactStyles=useMemo(()=>makeCompactStyles(theme),[theme]),trayStyles=useMemo(()=>makeTrayStyles(theme),[theme]),motion=useChatMotion(),[draft,setDraft]=useChatDraft(send,conversationId,seed),[pickerOpen,setPickerOpen]=useState(false),[focused,setFocused]=useState(false),onFocus=useCallback(()=>setFocused(true),[]),onBlur=useCallback(()=>setFocused(false),[]),[pickFailed,setPickFailed]=useState(false);useEffect(()=>{setPickFailed(false)},[conversationId]);let placeholder=composerPlaceholder(theme.meta.placeholder,petName,petPlaceholder,mood),phrases=useMemo(()=>buildDictationPhrases({name:petName,breed:petBreed}),[petName,petBreed]),voice=useNativeDictation({enabled:dictation,input:draft,setInput:setDraft,phrases:phrases,maxLength:MESSAGE_MAX_CHARS,telemetry:telemetry}),cancelDictation=voice.cancel,dictating=voice.active;usePersistedDraft(draftStore,conversationId===null?null:String(conversationId),draft,setDraft,dictating);let seenConversation=useRef(conversationId);useEffect(()=>{seenConversation.current!==conversationId&&(seenConversation.current=conversationId,cancelDictation())},[conversationId,cancelDictation]);let paneShown=useChatPaneShown();useEffect(()=>{paneShown||cancelDictation()},[paneShown,cancelDictation]);let uploading=attachments?.state.uploading??false,uploadFailed=attachments?.state.failed??false,sendBlocked=uploading||uploadFailed,rows=attachments?.state.attachments??NO_ROWS;useAnimateLayoutOn(rows.length,motion);let onSend=useCallback(()=>{let text3=draft.trim();if(text3.length===0||sendBlocked||[...text3].length>MESSAGE_MAX_CHARS)return;dictating&&cancelDictation();let keys=attachments?.state.s3Keys??NO_KEYS;attachments!==null&&keys.length>0?(onStage(attachments.state.attachments.filter(row=>row.status==="uploaded").map(row=>({uri:row.previewUri,filename:row.filename}))),send(text3,{imageS3Keys:keys}),attachments.state.clear()):send(text3),setDraft(""),setPickFailed(false)},[draft,send,sendBlocked,dictating,cancelDictation,attachments,onStage]),onChangeText=useCallback(next=>{dictating&&cancelDictation(),setDraft(next)},[dictating,cancelDictation,setDraft]),onStop=useCallback(()=>{stop()},[stop]),pickFrom=useCallback(source=>{setPickerOpen(false),attachments!==null&&(setPickFailed(false),attachments.state.dismissRejected(),callHostAsync(attachments.pick,source).then(outcome=>{if(!outcome.ok){setPickFailed(true);return}outcome.value!==null&&attachments.state.add(outcome.value)}))},[attachments]),isOverLimit=useMemo(()=>[...draft.trim()].length>MESSAGE_MAX_CHARS,[draft]),sendDisabled=isOverLimit||sendBlocked||draft.trim().length===0,sendDimmed=isOverLimit||sendBlocked||dimEmptySend&&draft.trim().length===0,slotsFull=attachments!==null&&rows.length>=attachments.state.maxPerMessage,sendInk=theme.slots.sendButton?.textColor??theme.color.brandInk,compactInk=theme.slots.sendButton?.textColor??theme.color.surface;/* @__PURE__ */
|
|
110
|
+
return jsxs(View,{style:styles3.composerOuter,children:[attachments!==null&&pickerOpen?/* @__PURE__ */jsx(AttachmentPickerPopover,{sources:attachments.sources,full:slotsFull,onPick:pickFrom,onClose:()=>setPickerOpen(false)}):null,attachments!==null?/* @__PURE__ */jsx(AttachmentStrip,{attachments:rows,rejected:pickFailed?PICK_FAILED:attachments.state.rejected,uploadFailed:uploadFailed,onRetry:attachments.state.retry,onRemove:attachments.state.remove,onPreview:row=>onPreview({uri:row.previewUri,label:row.filename}),style:compact?compactStyles.tray:trayStyles.tray}):null,
|
|
111
|
+
/* @__PURE__ */jsxs(View,{style:compact?[styles3.composer,compactStyles.bar,focused?compactStyles.barFocused:null]:styles3.composer,children:[voice.supported&&voice.error!==null?/* @__PURE__ */jsxs(Fragment,{children:[
|
|
112
112
|
/* @__PURE__ */jsx(Text,{style:styles3.dictationError,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:dictationErrorMessage(voice.error)}),
|
|
113
113
|
/* @__PURE__ */jsx(AnnounceLine,{line:dictationErrorMessage(voice.error)})]}):null,
|
|
114
114
|
/* @__PURE__ */jsxs(View,{style:styles3.composerRow,children:[attachments!==null?/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:slotsFull?attachControlLabel(rows.length,attachments.state.maxPerMessage):CHAT_COPY.attachPhotoOrFileNative,accessibilityState:{disabled:slotsFull,expanded:pickerOpen},disabled:slotsFull,style:[styles3.attachControl,compact?compactStyles.add:null,slotsFull?styles3.attachControlDisabled:null],hitSlop:compact?COMPACT_ADD_SLOP:void 0,onPress:()=>setPickerOpen(open=>!open),children:/* @__PURE__ */jsx(UploadGlyph,{size:compact?COMPACT_ADD_GLYPH:ATTACH_GLYPH_SIZE,color:slotsFull?theme.color.text.muted:compact?theme.color.text.primary:theme.color.brandInk,strokeWidth:1.75})}):null,
|
|
115
|
-
/* @__PURE__ */jsx(TextInput,{style:compact?[styles3.input,compactStyles.input]:styles3.input,onFocus:onFocus,onBlur:onBlur,value:draft,onChangeText:onChangeText,placeholder:placeholder,placeholderTextColor:theme.slots.composerInput?.textColor??theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.composerLabel,onSubmitEditing:onSend,returnKeyType:"send",...SUBMIT_ON_RETURN,...compact?ONE_ROW_WEB:null,blurOnSubmit:false,multiline:true,editable:true}),voice.supported?/* @__PURE__ */jsx(DictationButton,{active:voice.active,listening:voice.status==="listening",elapsedMs:voice.elapsedMs,onToggle:voice.toggle}):null,isStreaming?/* @__PURE__ */jsx(Pressable,{onPress:onStop,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.stop,style:styles3.sendControl,children:/* @__PURE__ */jsx(View,{style:compact?compactStyles.disc:styles3.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */jsx(StopGlyph,{size:compact?COMPACT_ARROW:STOP_GLYPH_SIZE,color:compact?compactInk:sendInk,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */jsx(Pressable,{onPress:onSend,disabled:sendDisabled,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.send,accessibilityState:{disabled:sendDisabled,busy:uploading},style:[styles3.sendControl,sendDimmed?compact?compactStyles.dimmed:styles3.sendControlDisabled:null],children:compact?/* @__PURE__ */jsx(View,{style:compactStyles.disc,testID:"everfur-send-disc",children:/* @__PURE__ */jsx(ArrowUpGlyph,{size:COMPACT_ARROW,color:compactInk,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */jsx(View,{style:styles3.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */jsx(SendGlyph,{size:SEND_GLYPH_SIZE,color:sendInk,testID:"everfur-send-glyph"})})})]})]})]})}var NO_ROWS=/* @__PURE__ */Object.freeze([]),NO_KEYS=/* @__PURE__ */Object.freeze([]),SUBMIT_ON_RETURN=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),ONE_ROW_WEB=/* @__PURE__ */Object.freeze(Platform.OS==="web"?{rows:1}:{}),PICK_FAILED=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function makeCompactStyles(theme){let c=theme.color,slot2=theme.slots.sendButton,inputSize=textRole(theme,"body").fontSize+COMPACT_INPUT_STEP;return StyleSheet.create({bar:{marginTop:COMPACT_INSET_TOP,marginHorizontal:COMPACT_INSET_SIDE,marginBottom:COMPACT_INSET_FOOT,minHeight:COMPACT_HEIGHT,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:COMPACT_RING,borderColor:theme.slots.composerInput?.borderColor??c.text.primary},barFocused:{borderWidth:COMPACT_RING_FOCUSED,paddingLeft:8-(COMPACT_RING_FOCUSED-COMPACT_RING),paddingRight:6-(COMPACT_RING_FOCUSED-COMPACT_RING)},input:{fontSize:inputSize,lineHeight:Math.round(inputSize*COMPACT_INPUT_LEAD),minHeight:Math.round(inputSize*COMPACT_INPUT_LEAD),...Platform.OS==="web"?{outlineStyle:"none"}:null},add:{width:COMPACT_ADD,height:COMPACT_ADD,borderRadius:COMPACT_ADD/2},disc:{width:COMPACT_DISC,height:COMPACT_DISC,borderRadius:COMPACT_DISC/2,alignItems:"center",justifyContent:"center",backgroundColor:slot2?.backgroundColor??c.text.primary,...slotBox(slot2)},dimmed:{opacity:COMPACT_DIM_OPACITY}})}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}function headerPetOf(pets,activePetRef){if(activePetRef!==null){let active=pets.find(pet=>pet.petRef===activePetRef);if(active!==void 0)return active}return pets[0]??null}var TELEVET_COPY=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present=televetGlobal().presenter;if(present===null)return"absent";try{return present(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}var warned=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned||(warned=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var TelevetHostSlot=createContext(null);function TelevetHostOutlet(){let Host=useContext(TelevetHostSlot);return Host===null?null:/* @__PURE__ */jsx(Host,{})}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef,options){let body={};petRef!==void 0&&(body.pet_ref=petRef);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef,options){let pet;if(petRef!=null){let length=typeof petRef=="string"?[...petRef].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL2=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL2.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=useState(null);if(useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch,opts.controller]),preflightController=useRef(controller);preflightController.current=controller;let scope=useMemo(()=>({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}),[runtime,userRef,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=useState(IDLE2),inFlight2=useRef(null),scopeRef=useRef({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch};let controllerRef=useRef(controller);controllerRef.current=controller;let availableRef=useRef(available);availableRef.current=available;let start=useCallback((petRef,visit)=>{if(inFlight2.current)return inFlight2.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef===void 0?defaultPet:petRef;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight2.current===tracked&&(inFlight2.current=null)});return inFlight2.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=useCallback((petRef,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef===void 0?defaultPet:petRef,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null&&"consultId"in visit?{consultId:visit.consultId}:{},...visit!==null&&"visitRef"in visit?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=useCallback(petRef=>redirect?start(petRef,null):openInApp(petRef,null),[redirect,start,openInApp]),openVisit=useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]),joinVisit=useCallback(consultId=>redirect?start(void 0,null):openInApp(void 0,{consultId:consultId.trim()}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit,joinVisit:joinVisit}}var defaultOpenUrl=url=>Linking.openURL(url);function useVetVisit(opts={}){let{openUrl:openUrl,...rest}=opts,opener=useMemo(()=>{let openImpl=openUrl??defaultOpenUrl;return{prepare:()=>({ok:true,value:null}),async finish(_prepared,handoff){try{return await openImpl(handoff.url),null}catch{return"openFailed"}},abandon:()=>{}}},[openUrl]);return useVetVisitWith(opener,rest)}var MIN_TOUCH_TARGET2=44,BUSY_OPACITY=.6;function VetVisitButtonCore(props){let{petRef:petRef,label:label,openUrl:openUrl,onOpened:onOpened,onError:onError,style:style,labelStyle:labelStyle,controller:controller,returnTo:returnTo,usState:usState,entry:entry,visitRef:visitRef,intent:intent,onStartInApp:onStartInApp,prefer:prefer}=props,redirecting=prefer==="redirect",visit=useVetVisit({...returnTo!==void 0?{returnTo:returnTo}:{},...usState!==void 0?{usState:usState}:{},...entry!==void 0?{entry:entry}:{},...petRef!==void 0?{petRef:petRef}:{},...openUrl!==void 0?{openUrl:openUrl}:{},...controller!==void 0?{controller:controller}:{},prefer:redirecting?"redirect":"in-app"}),theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles6(theme),[theme]),settling=useRef(false);if(!visit.available)/* @__PURE__ */
|
|
115
|
+
/* @__PURE__ */jsx(TextInput,{style:compact?[styles3.input,compactStyles.input]:styles3.input,onFocus:onFocus,onBlur:onBlur,value:draft,onChangeText:onChangeText,placeholder:placeholder,placeholderTextColor:theme.slots.composerInput?.textColor??theme.color.text.placeholder,accessibilityLabel:CHAT_COPY.composerLabel,onSubmitEditing:onSend,returnKeyType:"send",...SUBMIT_ON_RETURN,...compact?ONE_ROW_WEB:null,blurOnSubmit:false,multiline:true,editable:true}),voice.supported?/* @__PURE__ */jsx(DictationButton,{active:voice.active,listening:voice.status==="listening",elapsedMs:voice.elapsedMs,onToggle:voice.toggle}):null,isStreaming?/* @__PURE__ */jsx(Pressable,{onPress:onStop,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.stop,style:styles3.sendControl,children:/* @__PURE__ */jsx(View,{style:compact?compactStyles.disc:styles3.sendDisc,testID:"everfur-stop-disc",children:/* @__PURE__ */jsx(StopGlyph,{size:compact?COMPACT_ARROW:STOP_GLYPH_SIZE,color:compact?compactInk:sendInk,testID:"everfur-stop-glyph"})})}):/* @__PURE__ */jsx(Pressable,{onPress:onSend,disabled:sendDisabled,accessibilityRole:"button",accessibilityLabel:CHAT_COPY.send,accessibilityState:{disabled:sendDisabled,busy:uploading},style:[styles3.sendControl,sendDimmed?compact?compactStyles.dimmed:styles3.sendControlDisabled:null],children:compact?/* @__PURE__ */jsx(View,{style:compactStyles.disc,testID:"everfur-send-disc",children:/* @__PURE__ */jsx(ArrowUpGlyph,{size:COMPACT_ARROW,color:compactInk,strokeWidth:2.25,testID:"everfur-send-arrow"})}):/* @__PURE__ */jsx(View,{style:styles3.sendDisc,testID:"everfur-send-disc",children:/* @__PURE__ */jsx(SendGlyph,{size:SEND_GLYPH_SIZE,color:sendInk,testID:"everfur-send-glyph"})})})]})]})]})}var NO_ROWS=/* @__PURE__ */Object.freeze([]),NO_KEYS=/* @__PURE__ */Object.freeze([]),SUBMIT_ON_RETURN=/* @__PURE__ */Object.freeze({submitBehavior:"submit"}),ONE_ROW_WEB=/* @__PURE__ */Object.freeze(Platform.OS==="web"?{rows:1}:{}),PICK_FAILED=/* @__PURE__ */Object.freeze({code:"unknown",retryable:true,filename:""});function makeCompactStyles(theme){let c=theme.color,slot2=theme.slots.sendButton,inputSize=textRole(theme,"body").fontSize+COMPACT_INPUT_STEP;return StyleSheet.create({bar:{marginTop:COMPACT_INSET_TOP,marginHorizontal:COMPACT_INSET_SIDE,marginBottom:COMPACT_INSET_FOOT,minHeight:COMPACT_HEIGHT,paddingLeft:8,paddingRight:6,paddingVertical:0,borderWidth:COMPACT_RING,borderColor:theme.slots.composerInput?.borderColor??c.text.primary},barFocused:{borderWidth:COMPACT_RING_FOCUSED,paddingLeft:8-(COMPACT_RING_FOCUSED-COMPACT_RING),paddingRight:6-(COMPACT_RING_FOCUSED-COMPACT_RING)},input:{fontSize:inputSize,lineHeight:Math.round(inputSize*COMPACT_INPUT_LEAD),minHeight:Math.round(inputSize*COMPACT_INPUT_LEAD),...Platform.OS==="web"?{outlineStyle:"none"}:null},add:{width:COMPACT_ADD,height:COMPACT_ADD,borderRadius:COMPACT_ADD/2},disc:{width:COMPACT_DISC,height:COMPACT_DISC,borderRadius:COMPACT_DISC/2,alignItems:"center",justifyContent:"center",backgroundColor:slot2?.backgroundColor??c.text.primary,...slotBox(slot2)},dimmed:{opacity:COMPACT_DIM_OPACITY},tray:{marginHorizontal:COMPACT_INSET_SIDE,marginTop:COMPACT_INSET_TOP,paddingBottom:0}})}function makeTrayStyles(theme){return StyleSheet.create({tray:{marginHorizontal:theme.space.md,marginTop:theme.space.xs,paddingBottom:0}})}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}function headerPetOf(pets,activePetRef){if(activePetRef!==null){let active=pets.find(pet=>pet.petRef===activePetRef);if(active!==void 0)return active}return pets[0]??null}var TELEVET_COPY=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present=televetGlobal().presenter;if(present===null)return"absent";try{return present(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}var warned=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned||(warned=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var TelevetHostSlot=createContext(null);function TelevetHostOutlet(){let Host=useContext(TelevetHostSlot);return Host===null?null:/* @__PURE__ */jsx(Host,{})}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef,options){let body={};petRef!==void 0&&(body.pet_ref=petRef);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef,options){let pet;if(petRef!=null){let length=typeof petRef=="string"?[...petRef].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL2=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL2.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=useState(null);if(useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch,opts.controller]),preflightController=useRef(controller);preflightController.current=controller;let scope=useMemo(()=>({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}),[runtime,userRef,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=useState(IDLE2),inFlight2=useRef(null),scopeRef=useRef({runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch};let controllerRef=useRef(controller);controllerRef.current=controller;let availableRef=useRef(available);availableRef.current=available;let start=useCallback((petRef,visit)=>{if(inFlight2.current)return inFlight2.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef===void 0?defaultPet:petRef;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight2.current===tracked&&(inFlight2.current=null)});return inFlight2.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=useCallback((petRef,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef===void 0?defaultPet:petRef,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null&&"consultId"in visit?{consultId:visit.consultId}:{},...visit!==null&&"visitRef"in visit?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=useCallback(petRef=>redirect?start(petRef,null):openInApp(petRef,null),[redirect,start,openInApp]),openVisit=useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]),joinVisit=useCallback(consultId=>redirect?start(void 0,null):openInApp(void 0,{consultId:consultId.trim()}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit,joinVisit:joinVisit}}var defaultOpenUrl=url=>Linking.openURL(url);function useVetVisit(opts={}){let{openUrl:openUrl,...rest}=opts,opener=useMemo(()=>{let openImpl=openUrl??defaultOpenUrl;return{prepare:()=>({ok:true,value:null}),async finish(_prepared,handoff){try{return await openImpl(handoff.url),null}catch{return"openFailed"}},abandon:()=>{}}},[openUrl]);return useVetVisitWith(opener,rest)}var MIN_TOUCH_TARGET2=44,BUSY_OPACITY=.6;function VetVisitButtonCore(props){let{petRef:petRef,label:label,openUrl:openUrl,onOpened:onOpened,onError:onError,style:style,labelStyle:labelStyle,controller:controller,returnTo:returnTo,usState:usState,entry:entry,visitRef:visitRef,intent:intent,onStartInApp:onStartInApp,prefer:prefer}=props,redirecting=prefer==="redirect",visit=useVetVisit({...returnTo!==void 0?{returnTo:returnTo}:{},...usState!==void 0?{usState:usState}:{},...entry!==void 0?{entry:entry}:{},...petRef!==void 0?{petRef:petRef}:{},...openUrl!==void 0?{openUrl:openUrl}:{},...controller!==void 0?{controller:controller}:{},prefer:redirecting?"redirect":"in-app"}),theme=useEverfurTheme(),styles3=useMemo(()=>makeStyles6(theme),[theme]),settling=useRef(false);if(!visit.available)/* @__PURE__ */
|
|
116
116
|
return jsxs(Fragment,{children:[null,
|
|
117
117
|
/* @__PURE__ */jsx(TelevetHostOutlet,{})]});let busy=visit.status==="opening",text3=label??TELEVET_COPY.visitButton;/* @__PURE__ */
|
|
118
118
|
return jsxs(Fragment,{children:[
|
|
@@ -340,11 +340,11 @@ return jsxs(View,{style:[styles3.rowBlock,styles3.rowBlockAssistant],testID:`eve
|
|
|
340
340
|
return jsx(CapabilityGate,{capability:"chat",style:style,...renderPending?{renderPending:renderPending}:{},children:/* @__PURE__ */jsx(MessageLinksScope,{linkHosts:props.linkHosts,onOpenUrl:props.onOpenUrl,children:/* @__PURE__ */jsx(ChatBody,{...props})})})}function useOptionalEverfurContext(){try{return useEverfurContext()}catch{return null}}function hostPresentation(props){return definedPresentation({...props.presentation,chatComposerMic:props.presentation?.chatComposerMic??(props.dictation===void 0?void 0:props.dictation!==false),chatComposerUpload:props.presentation?.chatComposerUpload??(props.attachments===void 0?void 0:true)})}function ChatBody(props){let context=useOptionalEverfurContext();return context===null?/* @__PURE__ */jsx(ChatBodyAlone,{...props}):/* @__PURE__ */jsx(ChatBodyInProvider,{...props,activePet:context.activePet,telemetry:context.runtime.registry?.services?.telemetry??null})}function ChatBodyAlone(props){let client=hostPresentation(props),key=JSON.stringify(client),planPetRef=props.petRef??null,settings=useMemo(()=>({presentation:resolvePresentation({server:null,locked:null,client:client}),isLocked:()=>false,planPage:null,planPetRef:planPetRef,inProvider:false,telemetry:null}),[key,planPetRef]);/* @__PURE__ */
|
|
341
341
|
return jsx(ChatSurface,{...props,settings:settings})}function ChatBodyInProvider({activePet:activePet,telemetry:telemetry,...props}){let{presentation:presentation,isLocked:isLocked}=useEverfurPresentationState(hostPresentation(props)),planEnabled=useCapabilityEnabled("healthPlan"),wantsPlan=presentation.chatTopCard==="focus"&&props.topCard===void 0&&planEnabled,planPetRef=props.petRef??activePet??null,plan=useHealthPlanPage({petRef:planPetRef,enabled:wantsPlan}),planPage=wantsPlan&&plan.phase==="ready"?plan.page:null,settings=useMemo(()=>({presentation:presentation,isLocked:isLocked,planPage:planPage,planPetRef:planPetRef,inProvider:true,telemetry:telemetry}),[presentation,isLocked,planPage,planPetRef,telemetry]);/* @__PURE__ */
|
|
342
342
|
return jsx(ChatSurface,{...props,settings:settings})}function ChatSurface({settings:settings,petRef:petRef,conversationId:conversationId,style:style,renderPending:renderPending,onCopy:onCopy,onPetChange:onPetChange,onVetPrep:onVetPrep,onFindVet:onFindVet,renderVetAction:renderVetAction,attachments:attachments,pet:pet,onAddPet:onAddPet,checkinTarget:checkinTarget,handoffToken:handoffToken,initialAsk:initialAsk,initialAskKey:initialAskKey,composerSeed:composerSeed,lifecycle:lifecycle,openUnreadOnRefresh:openUnreadOnRefresh,draftStore:draftStore,vetReturnTo:vetReturnTo,vetUsState:vetUsState,vetPrefer:vetPrefer,onOpenUrl:onOpenUrl,keyboardVerticalOffset:keyboardVerticalOffset,topCard:hostTopCard,onOpenHealthPlan:onOpenHealthPlan,answerCards:answerCards,historySheet:historySheet,historyBar:historyBar,starterPrompts:starterPrompts,emptyState:emptyState,header:header=true,textingEntry:textingEntry=true,renderEmptyHeader:renderEmptyHeader,followUpPolicy:hostFollowUpPolicy,initialAskCard:initialAskCard}){let{presentation:presentation,isLocked:isLocked,planPage:planPage,planPetRef:planPetRef}=settings,{theme:theme,styles:styles3}=useChatTheme(),askHomeFactory=useAskHomeFactory()??(presentation.chatAnswerStyle==="cards"?createAskHome:null),askHome=useMemo(()=>askHomeFactory===null?null:askHomeFactory(theme),[askHomeFactory,theme]),hostPoweredBy=useHostPoweredBy(),motion=useChatMotion(),chatOpts=useMemo(()=>buildChatOpts(petRef,conversationId),[petRef,conversationId]),chat=useEverfurChat(chatOpts),view=selectView(chat),pets=useChatPets(),history=useHistoryPanel(chat),insets=useSafeAreaInsets(),notice=turnNotice(chat,"web"),onCheckinFindVet=useMemo(()=>onFindVet===void 0?void 0:()=>{callHost(onFindVet,"emergency")},[onFindVet]),vet=useMemo(()=>vetReturnTo===void 0&&vetUsState===void 0&&vetPrefer===void 0?void 0:{returnTo:vetReturnTo,usState:vetUsState,prefer:vetPrefer},[vetReturnTo,vetUsState,vetPrefer]),shownPet=headerPet(pets.pets,chat.petRef),urgencySource=useMemo(()=>latestUrgencySource(chat.messages,shownPet?.name??null),[chat.messages,shownPet?.name]),urgency=useUrgencySurface(urgencySource);useSettleAnnouncement(chat),useAnimateLayoutOn(urgency.showBanner,motion);let providerContext=useOptionalEverfurContext(),handoffTarget=useChatHandoffTarget(handoffToken,providerContext);useCheckinTarget(chat.openCheckin,checkinTarget??handoffTarget,{petRef:chat.petRef,pinned:petRef!==void 0,ready:!chat.isBootstrapping,selectPet:next=>{pets.setActivePet(next),callHost(onPetChange,next)}}),useInitialAsk(chat.askEverfur,chat.isBootstrapping,initialAsk,initialAskKey);let seed=useMemo(()=>sanitizeSeedPrompt(composerSeed),[composerSeed]),askPrompt=useMemo(()=>sanitizeSeedPrompt(initialAsk),[initialAsk]),openingCard=useMemo(()=>initialAskCard!==void 0&&askPrompt!==null?{card:initialAskCard,prompt:askPrompt}:void 0,[initialAskCard,askPrompt]),lifecyclePort=useMemo(()=>lifecycle===void 0?createAppStateLifecycle():lifecycle??void 0,[lifecycle]);useChatLifecycle(lifecyclePort,{conversationId:chat.conversationId===null?null:String(chat.conversationId),isTurnInFlight:chat.isStreaming,refreshesBlankThread:openUnreadOnRefresh===true,refresh:openUnreadOnRefresh===true?()=>chat.refreshActiveThread?.(OPEN_UNREAD_HEAD)??Promise.resolve():chat.refreshActiveThread});let historyUnread=(chat.hasUnreadThreads??false)||history.rows.some(row=>row.unreadCount!==null&&row.unreadCount>0)||(chat.unreadCount??0)>0,sentImages=useSentImages(chat.messages),[preview,setPreview]=useState(null),closePreview=useCallback(()=>setPreview(null),[]),[feedbackTarget,setFeedbackTarget]=useState(null),[feedbackNote,setFeedbackNote]=useState(null),thanksTimer=useRef(null);useEffect(()=>()=>{thanksTimer.current&&clearTimeout(thanksTimer.current)},[]);let showNote=useCallback((responseId,kind)=>{setFeedbackNote({responseId:String(responseId),kind:kind}),thanksTimer.current&&clearTimeout(thanksTimer.current),thanksTimer.current=kind==="thanks"?setTimeout(()=>{setFeedbackNote(null),thanksTimer.current=null},THANKS_VISIBLE_MS):null},[]),onSentiment=useCallback((message,sentiment)=>{let responseId=message.responseId;if(responseId===void 0)return;let recorded=chat.sentimentByMessage[String(responseId)];setFeedbackNote(note=>note?.responseId===String(responseId)?null:note),chat.feedback(responseId,sentiment).then(result=>{result.ok||showNote(responseId,"failed")}),sentiment==="down"&&recorded!=="down"&&setFeedbackTarget(responseId)},[chat,showNote]),submitReasons=useCallback(async(reason,notes)=>feedbackTarget===null||!(reason==null&¬es===null?{ok:true}:await chat.feedback(feedbackTarget,"down",reason??"other",notes)).ok?false:(setFeedbackTarget(null),showNote(feedbackTarget,"thanks"),true),[chat,feedbackTarget,showNote]),skipReasons=useCallback(()=>setFeedbackTarget(null),[]),onSelectPrompt=useCallback(prompt=>{chat.send(prompt)},[chat.send]),openCitation=useMemo(()=>onOpenUrl===void 0?void 0:url=>{callHost(onOpenUrl,url,"citation")},[onOpenUrl]),avoidBehavior=Platform.OS==="ios"?"padding":void 0,keyboard=useChatKeyboardOffset(keyboardVerticalOffset,avoidBehavior!==void 0),topInset=keyboard.topInWindow===null?insets.top:Math.max(0,insets.top-keyboard.topInWindow),keyboardOpen=useKeyboardOpen(),openPlan=useMemo(()=>onOpenHealthPlan===void 0?void 0:()=>{callHost(onOpenHealthPlan,planPetRef)},[onOpenHealthPlan,planPetRef]),planCard=useMemo(()=>hostTopCard===void 0?healthPlanTopCard(planPage,{onOpenPlan:openPlan}):void 0,[hostTopCard,planPage,openPlan]),card=presentation.chatTopCard==="focus"?hostTopCard??planCard:void 0,[cardOpen,setCardOpen]=useState(true),onCardAsk=useCallback(prompt=>{chat.send(prompt)},[chat.send]),followUpPolicy=useMemo(()=>followUpPolicyFor(hostFollowUpPolicy,presentation,isLocked("chatFollowUpCount")),[hostFollowUpPolicy,presentation,isLocked]),cardsStyle=presentation.chatAnswerStyle==="cards",servedStarters=useMemo(()=>cardsStyle&&chat.messages.length===0?servedStarterPrompts(chat.suggestedPrompts):void 0,[cardsStyle,chat.messages.length,chat.suggestedPrompts]),sheet=presentation.chatHistoryStyle==="sheet",threadEmpty=chat.messages.length===0,pill=card!==void 0?/* @__PURE__ */jsx(TopCardPill,{card:card,open:cardOpen,onOpenChange:setCardOpen}):null,bar=historyBar??(header?void 0:DEFAULT_HISTORY_BAR),barNode=bar!==void 0?/* @__PURE__ */jsx(HistoryBar,{bar:bar,history:history,empty:threadEmpty,unread:historyUnread,extra:pill}):null,barInThread=presentation.chatHistoryBar==="scroll"&&(view==="empty"||view==="populated"),cardNode=card===void 0?null:/* @__PURE__ */jsxs(Fragment,{children:[
|
|
343
|
-
/* @__PURE__ */jsx(TopCard,{card:card,open:cardOpen,onOpenChange:setCardOpen,ask:onCardAsk}),bar===void 0?pill:null]}),barShown=bar!==void 0,historyLoad=history.load,historyOpen=history.open;useEffect(()=>{barShown&&!historyOpen&&historyLoad()},[barShown,historyOpen,chat.conversationId,historyLoad]);let composerProps={send:chat.send,stop:chat.stop,isStreaming:chat.isStreaming,conversationId:chat.conversationId,seed:seed,draftStore:draftStore,onStage:sentImages.stage,onPreview:setPreview,petName:shownPet?.name??null,petBreed:shownPet?.breed??null,compact:presentation.chatComposerStyle==="compact",petPlaceholder:presentation.chatComposerPlaceholder==="pet_name",dimEmptySend:presentation.chatSendButton==="dim_when_empty",mood:composerMood(view,urgency.source?.level??null),dictation:presentation.chatComposerMic,telemetry:settings.telemetry},textingAsk=useChatTextingAsk(presentation.chatTextingAsk&&settings.inProvider,chat,textingEntry),uploadOn=attachments!==void 0&&presentation.chatComposerUpload,bannerHidden=!presentation.chatGeneralBanner&&urgency.source?.level==="general",footnoteInThread=presentation.safetyDisclaimerPlacement==="answer_footer"&&(view==="empty"||view==="populated"),footnote=/* @__PURE__ */jsx(Text,{tier:"compact",style:footnoteInThread?styles3.footnoteInThread:styles3.footnote,accessibilityRole:"text",children:forPet(CHAT_COPY.footnoteWeb,shownPet?.name)});
|
|
343
|
+
/* @__PURE__ */jsx(TopCard,{card:card,open:cardOpen,onOpenChange:setCardOpen,ask:onCardAsk}),bar===void 0?pill:null]}),barShown=bar!==void 0,historyLoad=history.load,historyOpen=history.open;useEffect(()=>{barShown&&!historyOpen&&historyLoad()},[barShown,historyOpen,chat.conversationId,historyLoad]);let composerProps={send:chat.send,stop:chat.stop,isStreaming:chat.isStreaming,conversationId:chat.conversationId,seed:seed,draftStore:draftStore,onStage:sentImages.stage,onPreview:setPreview,petName:shownPet?.name??null,petBreed:shownPet?.breed??null,compact:presentation.chatComposerStyle==="compact",petPlaceholder:presentation.chatComposerPlaceholder==="pet_name",dimEmptySend:presentation.chatSendButton==="dim_when_empty",mood:composerMood(view,urgency.source?.level??null),dictation:presentation.chatComposerMic,telemetry:settings.telemetry},textingAsk=useChatTextingAsk(presentation.chatTextingAsk&&settings.inProvider,chat,textingEntry),uploadOn=attachments!==void 0&&presentation.chatComposerUpload,bannerHidden=!presentation.chatGeneralBanner&&urgency.source?.level==="general",footnoteHidden=presentation.safetyDisclaimerPlacement==="none",footnoteInThread=presentation.safetyDisclaimerPlacement==="answer_footer"&&(view==="empty"||view==="populated"),footnote=/* @__PURE__ */jsx(Text,{tier:"compact",style:footnoteInThread?styles3.footnoteInThread:styles3.footnote,accessibilityRole:"text",children:forPet(CHAT_COPY.footnoteWeb,shownPet?.name)});
|
|
344
344
|
/* @__PURE__ */
|
|
345
345
|
return jsx(AskHomeContext.Provider,{value:askHome,children:/* @__PURE__ */jsxs(KeyboardAvoidingView,{style:[styles3.container,{paddingTop:topInset},style],behavior:avoidBehavior,...keyboard.avoidingProps,children:[
|
|
346
346
|
/* @__PURE__ */jsx(KeyboardOffsetProbe,{probeRef:keyboard.probeRef}),header?/* @__PURE__ */jsx(ChatHeader,{pets:pets,petRef:chat.petRef,historyUnread:historyUnread,onOpenHistory:history.show,onNewChat:history.newConversation,onPetChange:onPetChange,onAddPet:onAddPet,vet:vet,textingEntry:textingAsk.headerEntry}):null,pet!==void 0?/* @__PURE__ */jsx(PetSetupNotice,{petRef:petRef??null,pet:pet,onRegistered:pets.refresh}):null,!header&&textingAsk.headerEntry!==null?/* @__PURE__ */jsx(TextingEntryRow,{entry:textingAsk.headerEntry,place:"thread"}):null,barInThread?null:barNode,bannerHidden?null:/* @__PURE__ */jsx(UrgencyBanner,{surface:urgency,petRef:chat.petRef,renderVetAction:renderVetAction,onFindVet:onFindVet,vet:vet,compact:keyboardOpen}),
|
|
347
|
-
/* @__PURE__ */jsx(View,{style:styles3.body,children:renderView(view,chat,{notice:notice,vet:vet,onCheckinFindVet:onCheckinFindVet,onSelectPrompt:onSelectPrompt,renderPending:renderPending,shownPet:shownPet,onVetPrep:onVetPrep,onCopy:onCopy,onSentiment:onSentiment,feedbackNote:feedbackNote,imagesByMessage:sentImages.byMessage,onPreview:setPreview,onAddPet:onAddPet,onOpenUrl:openCitation,threadTop:barInThread?barNode:null,topCard:cardNode,starterPrompts:starterPrompts??servedStarters,emptyState:emptyState,emptyCentered:presentation.chatAnswerStyle==="cards",followUpPolicy:followUpPolicy,answerCards:presentation.chatAnswerStyle==="cards"?answerCards??NO_ANSWER_CARDS:null,threadFoot:footnoteInThread?footnote:null,threadAside:textingAsk.line,threadAsideKey:textingAsk.stage,renderEmptyHeader:renderEmptyHeader,openingCard:openingCard})}),textingAsk.runner,textingAsk.entry!==null?/* @__PURE__ */jsx(View,{style:styles3.composerOuter,children:/* @__PURE__ */jsx(View,{style:styles3.askEntry,children:textingAsk.entry})}):uploadOn&&attachments!==void 0?/* @__PURE__ */jsx(ComposerWithAttachments,{...composerProps,attachments:attachments}):/* @__PURE__ */jsx(Composer,{...composerProps,attachments:null}),footnoteInThread?null:footnote,theme.meta.hidePoweredBy||hostPoweredBy?null:/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.poweredBy,accessibilityRole:"text",accessibilityLabel:CHAT_COPY.poweredBy,children:CHAT_COPY.poweredBy}),sheet?/* @__PURE__ */jsx(HistorySheet,{chat:chat,history:history,sheet:historySheet}):/* @__PURE__ */jsx(HistoryDrawer,{chat:chat,history:history}),
|
|
347
|
+
/* @__PURE__ */jsx(View,{style:styles3.body,children:renderView(view,chat,{notice:notice,vet:vet,onCheckinFindVet:onCheckinFindVet,onSelectPrompt:onSelectPrompt,renderPending:renderPending,shownPet:shownPet,onVetPrep:onVetPrep,onCopy:onCopy,onSentiment:onSentiment,feedbackNote:feedbackNote,imagesByMessage:sentImages.byMessage,onPreview:setPreview,onAddPet:onAddPet,onOpenUrl:openCitation,threadTop:barInThread?barNode:null,topCard:cardNode,starterPrompts:starterPrompts??servedStarters,emptyState:emptyState,emptyCentered:presentation.chatAnswerStyle==="cards",followUpPolicy:followUpPolicy,answerCards:presentation.chatAnswerStyle==="cards"?answerCards??NO_ANSWER_CARDS:null,threadFoot:footnoteInThread&&!footnoteHidden?footnote:null,threadAside:textingAsk.line,threadAsideKey:textingAsk.stage,renderEmptyHeader:renderEmptyHeader,openingCard:openingCard})}),textingAsk.runner,textingAsk.entry!==null?/* @__PURE__ */jsx(View,{style:styles3.composerOuter,children:/* @__PURE__ */jsx(View,{style:styles3.askEntry,children:textingAsk.entry})}):uploadOn&&attachments!==void 0?/* @__PURE__ */jsx(ComposerWithAttachments,{...composerProps,attachments:attachments}):/* @__PURE__ */jsx(Composer,{...composerProps,attachments:null}),footnoteInThread||footnoteHidden?null:footnote,theme.meta.hidePoweredBy||hostPoweredBy?null:/* @__PURE__ */jsx(Text,{tier:"compact",style:styles3.poweredBy,accessibilityRole:"text",accessibilityLabel:CHAT_COPY.poweredBy,children:CHAT_COPY.poweredBy}),sheet?/* @__PURE__ */jsx(HistorySheet,{chat:chat,history:history,sheet:historySheet}):/* @__PURE__ */jsx(HistoryDrawer,{chat:chat,history:history}),
|
|
348
348
|
/* @__PURE__ */jsx(FeedbackReasons,{visible:feedbackTarget!==null,onSubmit:submitReasons,onSkip:skipReasons}),
|
|
349
349
|
/* @__PURE__ */jsx(AttachmentImageLightbox,{uri:preview?.uri??null,label:preview?.label??"",onClose:closePreview}),
|
|
350
350
|
/* @__PURE__ */jsx(TelevetHostOutlet,{})]})})}function PetSetupNotice({petRef:petRef,pet:pet,onRegistered:onRegistered}){let{styles:styles3}=useChatTheme(),setup=useChatPetRegistration(petRef,pet,onRegistered);return setup.status!=="failed"||setup.error===null?null:/* @__PURE__ */jsxs(View,{style:styles3.setupNotice,accessible:true,accessibilityRole:"alert",children:[
|