@everfur/sdk 0.9.0 → 0.9.2

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.
Files changed (175) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +1 -1
  3. package/dist/{Chat-Cb3Y8VwS.d.cts → Chat-B7oN62ww.d.cts} +3 -3
  4. package/dist/{Chat-ClhB_8sp.d.ts → Chat-Cugs9Dsl.d.ts} +3 -3
  5. package/dist/{DepthViews-DDiPxyzg.d.cts → DepthViews-C6qFJ3fV.d.ts} +1 -1
  6. package/dist/{DepthViews-CSCS-tZg.d.ts → DepthViews-CUNmy99u.d.cts} +1 -1
  7. package/dist/{DepthViews-CW1z8pnl.d.cts → DepthViews-CiYBIBEZ.d.ts} +1 -1
  8. package/dist/{DepthViews-BSkuUGBB.d.ts → DepthViews-GxV7wSzT.d.cts} +1 -1
  9. package/dist/{ErrorPolicyPort-NFDPe-5w.d.cts → ErrorPolicyPort-10s3HJCt.d.cts} +1 -1
  10. package/dist/{ErrorPolicyPort-DwSnmGcX.d.ts → ErrorPolicyPort-C3nNSS_j.d.ts} +1 -1
  11. package/dist/{EverfurError-pEXDbUJ1.d.cts → EverfurError-DeBqRpQV.d.cts} +1 -1
  12. package/dist/{EverfurError-pEXDbUJ1.d.ts → EverfurError-DeBqRpQV.d.ts} +1 -1
  13. package/dist/{EverfurResult-dtl8ERAw.d.cts → EverfurResult-COlXj1wq.d.cts} +1 -1
  14. package/dist/{EverfurResult-sKkoXew0.d.ts → EverfurResult-ClPTS0P2.d.ts} +1 -1
  15. package/dist/{IntakeMedia-BFZfBLjB.d.cts → IntakeMedia-B-_vA9ZB.d.cts} +2 -1
  16. package/dist/{IntakeMedia-C8GlN_GK.d.ts → IntakeMedia-CIoTXAWs.d.ts} +2 -1
  17. package/dist/animations/index.cjs +1 -1
  18. package/dist/animations/index.d.cts +6 -6
  19. package/dist/animations/index.d.ts +6 -6
  20. package/dist/animations/index.js +1 -1
  21. package/dist/{attachments-DAUy3vPR.d.ts → attachments-20X7Vuip.d.ts} +3 -3
  22. package/dist/{attachments-BD70jZZL.d.cts → attachments-CkaPnIUw.d.cts} +3 -3
  23. package/dist/{attachments-CC7aHpwZ.d.ts → attachments-DN2cNGwe.d.ts} +7 -7
  24. package/dist/{attachments-DaOaIBNf.d.cts → attachments-HXFmzk-D.d.cts} +7 -7
  25. package/dist/{bookingCopy-CUW9Gdzc.d.ts → bookingCopy-B5igVNE0.d.ts} +7 -6
  26. package/dist/{bookingCopy-oEjqkiNA.d.cts → bookingCopy-pJpizqgz.d.cts} +7 -6
  27. package/dist/{branding-ctD0B2Th.d.cts → branding-BCfwLj0h.d.cts} +1 -1
  28. package/dist/{branding-aGleD_ki.d.ts → branding-DJf4h12Q.d.ts} +1 -1
  29. package/dist/{callCopy-DHjem0R-.d.cts → callCopy-Bw6oZT54.d.cts} +7 -2
  30. package/dist/{callCopy-DHjem0R-.d.ts → callCopy-Bw6oZT54.d.ts} +7 -2
  31. package/dist/{callRoom-B1qq_D-4.d.ts → callRoom-B92eH_ij.d.ts} +1 -1
  32. package/dist/{callRoom-DfZTWFXh.d.cts → callRoom-BhIdadyV.d.cts} +1 -1
  33. package/dist/{casesRepository-Bzs7aw4t.d.cts → casesRepository-DFoK5N1O.d.cts} +2 -2
  34. package/dist/{casesRepository-CywqL6mj.d.ts → casesRepository-qAkKKgji.d.ts} +2 -2
  35. package/dist/chat/index.cjs +9 -9
  36. package/dist/chat/index.d.cts +12 -12
  37. package/dist/chat/index.d.ts +12 -12
  38. package/dist/chat/index.js +9 -9
  39. package/dist/client/index.cjs +4 -4
  40. package/dist/client/index.d.cts +14 -14
  41. package/dist/client/index.d.ts +14 -14
  42. package/dist/client/index.js +4 -4
  43. package/dist/{config-BysLVhku.d.ts → config-BB7e52FP.d.ts} +3 -3
  44. package/dist/{config-EZzEyS-c.d.cts → config-u6rK4mKt.d.cts} +3 -3
  45. package/dist/consent/index.cjs +2 -2
  46. package/dist/consent/index.d.cts +9 -9
  47. package/dist/consent/index.d.ts +9 -9
  48. package/dist/consent/index.js +2 -2
  49. package/dist/{context-DUwYArkM.d.cts → context-BZ1k4qE3.d.cts} +9 -9
  50. package/dist/{context-DpfgbnOU.d.ts → context-CJYmubjx.d.ts} +9 -9
  51. package/dist/{copy-LxZGnFXJ.d.ts → copy-CtfctY-J.d.ts} +5 -5
  52. package/dist/{copy-DK4r9oGz.d.cts → copy-DCO_lUXd.d.cts} +5 -5
  53. package/dist/core/index.cjs +4 -4
  54. package/dist/core/index.d.cts +19 -19
  55. package/dist/core/index.d.ts +19 -19
  56. package/dist/core/index.js +4 -4
  57. package/dist/{depth-DAd77kRe.d.cts → depth-C_ym3qyi.d.cts} +6 -6
  58. package/dist/{depth-Mk7quUNa.d.ts → depth-_vMRMm4x.d.ts} +6 -6
  59. package/dist/{entitlementRepository-Dra_4FU_.d.cts → entitlementRepository-DA04yM54.d.cts} +4 -4
  60. package/dist/{entitlementRepository-CrD0O7VR.d.ts → entitlementRepository-tSY9WWad.d.ts} +4 -4
  61. package/dist/{identity-75whJXyP.d.cts → identity-CUynm8S2.d.cts} +2 -2
  62. package/dist/{identity-BiyMDMrR.d.ts → identity-D5uywCtp.d.ts} +2 -2
  63. package/dist/index.cjs +14 -14
  64. package/dist/index.d.cts +19 -19
  65. package/dist/index.d.ts +19 -19
  66. package/dist/index.js +14 -14
  67. package/dist/{models-DzvqEjMm.d.cts → models-A4A5S7AG.d.cts} +1 -1
  68. package/dist/{models-CrbUwbuS.d.ts → models-CnXY5LuO.d.ts} +1 -1
  69. package/dist/notifications/index.cjs +1 -1
  70. package/dist/notifications/index.d.cts +5 -5
  71. package/dist/notifications/index.d.ts +5 -5
  72. package/dist/notifications/index.js +1 -1
  73. package/dist/{pets-DoXxTw4x.d.cts → pets-BrdkpNJH.d.cts} +2 -2
  74. package/dist/{pets-W2BuLYko.d.ts → pets-mnbN0kZG.d.ts} +2 -2
  75. package/dist/{petsRepository-yyoo0k2I.d.cts → petsRepository-CQgzEFyz.d.cts} +2 -2
  76. package/dist/{petsRepository-ByMzq1Z9.d.ts → petsRepository-RGI_xPK1.d.ts} +2 -2
  77. package/dist/photo/index.cjs +1 -1
  78. package/dist/photo/index.d.cts +3 -3
  79. package/dist/photo/index.d.ts +3 -3
  80. package/dist/photo/index.js +1 -1
  81. package/dist/{ports-zYl8S_lI.d.ts → ports-Cu_Wc5Aw.d.ts} +7 -7
  82. package/dist/{ports-BeVJYP0_.d.cts → ports-DibY-h60.d.cts} +7 -7
  83. package/dist/records/depth/index.cjs +7 -5
  84. package/dist/records/depth/index.d.cts +11 -11
  85. package/dist/records/depth/index.d.ts +11 -11
  86. package/dist/records/depth/index.js +7 -5
  87. package/dist/records/index.cjs +23 -21
  88. package/dist/records/index.d.cts +14 -14
  89. package/dist/records/index.d.ts +14 -14
  90. package/dist/records/index.js +23 -21
  91. package/dist/{requestFunnel-BPeBZdKp.d.ts → requestFunnel-BkSFsLKh.d.ts} +5 -5
  92. package/dist/{requestFunnel-DHeSzCT6.d.cts → requestFunnel-nmhlEdbM.d.cts} +5 -5
  93. package/dist/{runtimeTypes-Cc207nbn.d.ts → runtimeTypes-CU2xVmiQ.d.ts} +7 -7
  94. package/dist/{runtimeTypes-DgMizQKz.d.cts → runtimeTypes-CWG1Cm4N.d.cts} +7 -7
  95. package/dist/server/events/index.cjs +2 -2
  96. package/dist/server/events/index.d.cts +4 -4
  97. package/dist/server/events/index.d.ts +4 -4
  98. package/dist/server/events/index.js +2 -2
  99. package/dist/server/index.cjs +2 -2
  100. package/dist/server/index.d.cts +5 -5
  101. package/dist/server/index.d.ts +5 -5
  102. package/dist/server/index.js +2 -2
  103. package/dist/televet/booking/index.cjs +9 -8
  104. package/dist/televet/booking/index.d.cts +12 -12
  105. package/dist/televet/booking/index.d.ts +12 -12
  106. package/dist/televet/booking/index.js +9 -8
  107. package/dist/televet/call/index.cjs +3 -5
  108. package/dist/televet/call/index.d.cts +3 -3
  109. package/dist/televet/call/index.d.ts +3 -3
  110. package/dist/televet/call/index.js +3 -5
  111. package/dist/televet/index.cjs +2 -2
  112. package/dist/televet/index.d.cts +7 -7
  113. package/dist/televet/index.d.ts +7 -7
  114. package/dist/televet/index.js +2 -2
  115. package/dist/testing/index.cjs +2 -2
  116. package/dist/testing/index.d.cts +3 -3
  117. package/dist/testing/index.d.ts +3 -3
  118. package/dist/testing/index.js +2 -2
  119. package/dist/testing/rn/index.cjs +2 -2
  120. package/dist/testing/rn/index.d.cts +13 -13
  121. package/dist/testing/rn/index.d.ts +13 -13
  122. package/dist/testing/rn/index.js +2 -2
  123. package/dist/testing/web/index.cjs +1 -1
  124. package/dist/testing/web/index.d.cts +14 -14
  125. package/dist/testing/web/index.d.ts +14 -14
  126. package/dist/testing/web/index.js +1 -1
  127. package/dist/{timelineRows-DUQIWSjc.d.cts → timelineRows-CYF_I5Aq.d.cts} +1 -1
  128. package/dist/{timelineRows-D22vGN9t.d.ts → timelineRows-PWRoTntZ.d.ts} +1 -1
  129. package/dist/{tokens-RAKZj7M8.d.cts → tokens-DLj8OnLH.d.cts} +4 -2
  130. package/dist/{tokens-RAKZj7M8.d.ts → tokens-DLj8OnLH.d.ts} +4 -2
  131. package/dist/{typeStyle-DVj8iCC1.d.ts → typeStyle-BxVyF71R.d.ts} +2 -2
  132. package/dist/{typeStyle-Nt7w0rhE.d.cts → typeStyle-DJedEu14.d.cts} +2 -2
  133. package/dist/{useRecordsDepth-Mbysp548.d.cts → useRecordsDepth-Cg4cc4bQ.d.cts} +4 -4
  134. package/dist/{useRecordsDepth-C0Qfoghi.d.ts → useRecordsDepth-eS9BJv_a.d.ts} +4 -4
  135. package/dist/{useVetVisit-RPBOabl8.d.ts → useVetVisit-DmWa7lt1.d.ts} +2 -2
  136. package/dist/{useVetVisit-BQX_aTJs.d.cts → useVetVisit-PtBjNwZr.d.cts} +2 -2
  137. package/dist/video/index.cjs +1 -1
  138. package/dist/video/index.d.cts +3 -3
  139. package/dist/video/index.d.ts +3 -3
  140. package/dist/video/index.js +1 -1
  141. package/dist/{view-CskIgOFV.d.cts → view-D4UOm-yo.d.cts} +11 -5
  142. package/dist/{view-DqKXtxEZ.d.ts → view-n_oSGiiT.d.ts} +11 -5
  143. package/dist/web/consent/index.cjs +2 -2
  144. package/dist/web/consent/index.d.cts +9 -9
  145. package/dist/web/consent/index.d.ts +9 -9
  146. package/dist/web/consent/index.js +2 -2
  147. package/dist/web/index.cjs +10 -10
  148. package/dist/web/index.d.cts +22 -22
  149. package/dist/web/index.d.ts +22 -22
  150. package/dist/web/index.js +10 -10
  151. package/dist/web/notifications/index.cjs +1 -1
  152. package/dist/web/notifications/index.d.cts +7 -7
  153. package/dist/web/notifications/index.d.ts +7 -7
  154. package/dist/web/notifications/index.js +1 -1
  155. package/dist/web/records/depth/index.cjs +6 -5
  156. package/dist/web/records/depth/index.d.cts +11 -11
  157. package/dist/web/records/depth/index.d.ts +11 -11
  158. package/dist/web/records/depth/index.js +7 -6
  159. package/dist/web/records/index.cjs +13 -11
  160. package/dist/web/records/index.d.cts +15 -15
  161. package/dist/web/records/index.d.ts +15 -15
  162. package/dist/web/records/index.js +13 -11
  163. package/dist/web/televet/booking/index.cjs +6 -6
  164. package/dist/web/televet/booking/index.d.cts +14 -11
  165. package/dist/web/televet/booking/index.d.ts +14 -11
  166. package/dist/web/televet/booking/index.js +6 -6
  167. package/dist/web/televet/call/index.cjs +3 -5
  168. package/dist/web/televet/call/index.d.cts +3 -3
  169. package/dist/web/televet/call/index.d.ts +3 -3
  170. package/dist/web/televet/call/index.js +3 -5
  171. package/dist/web/televet/index.cjs +1 -1
  172. package/dist/web/televet/index.d.cts +5 -5
  173. package/dist/web/televet/index.d.ts +5 -5
  174. package/dist/web/televet/index.js +1 -1
  175. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- import{createContext,forwardRef,createElement,useMemo,useState,useRef,useEffect,useCallback,useReducer,useContext,useSyncExternalStore,Component}from"react";import{TextInput as TextInput$1,StyleSheet,Pressable,View,Linking,Animated,Alert,BackHandler,Image,ActivityIndicator,ScrollView,Modal,StatusBar,Text as Text$1}from"react-native";import{z}from"zod";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import{useSafeAreaInsets}from"react-native-safe-area-context";function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
2
- 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 reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}function createTelevetBackChannel(){let handlers=[];return{register(handler){return handlers=[...handlers,handler],()=>{handlers=handlers.filter(h=>h!==handler)}},dispatch(){for(let handler of[...handlers].reverse())try{if(handler())return!0}catch{}return false}}}var TelevetBackChannelContext=createContext(null);function useTelevetBackChannel(handler,enabled=true){let channel=useContext(TelevetBackChannelContext),current=useRef(handler);current.current=handler,useEffect(()=>{if(!(channel===null||!enabled))return channel.register(()=>current.current())},[channel,enabled])}var DRAFT=s=>s,PLACEHOLDER_MARKERS=["[PLACEHOLDER","[PLAN NAME]","[LINK]","[Last]","TODO","TBD"];function isPlaceholderCopy(value){return PLACEHOLDER_MARKERS.some(m=>value.toUpperCase().includes(m.toUpperCase()))}function fill(template,slots){let out=template;for(let[key,value]of Object.entries(slots))out=out.split(`{${key}}`).join(value);return out}var TELEVET_BOOKING_COPY=/* @__PURE__ */Object.freeze({stateBlockedTitle:DRAFT("Not available in this state yet"),noCliniciansTitle:DRAFT("No vets available right now"),noCliniciansBody:DRAFT("Nobody is free in your area at the moment. This changes through the day."),noCliniciansRetryCta:DRAFT("Check again"),noCliniciansRegionBody:DRAFT("Video visits have to be with a vet licensed in your state, and we don’t have one there yet."),yourVetTitle:DRAFT("Your vet"),licensedPillTemplate:DRAFT("Licensed in {state}"),reviewsLabel:DRAFT("reviews"),rescheduleFromTemplate:DRAFT("Moving your visit on {when}"),rescheduleFailed:DRAFT("That did not move. Your original time is unchanged."),rescheduleStepLabel:DRAFT("Reschedule"),rescheduleTitleTemplate:DRAFT("Pick a new time for {pet}"),rescheduleNowLabel:DRAFT("Now"),rescheduleMoveTemplate:DRAFT("Move to {when}"),rescheduleMoving:DRAFT("Moving…"),rescheduleKeepLabel:DRAFT("Keep the visit as it is"),keepExistingCta:DRAFT("Keep my current time"),bookingPausedTitle:DRAFT("Booking is not available right now."),slotsErrorTitle:DRAFT("Could not load times"),noSlotsTitle:DRAFT("No times available"),nextOpeningTemplate:DRAFT("Next opening across our vets: {when}"),seeOtherVetsCta:DRAFT("See other vets"),retryCta:DRAFT("Try again"),holdExpired:DRAFT("That time is no longer held. Pick another."),slotTaken:DRAFT("That time was just taken. Pick another."),reasonPlaceholder:DRAFT("What is going on with your pet?"),reasonTooLong:DRAFT("That is too long. Please shorten it."),shareRecordsOff:DRAFT("Share health records with this vet"),confirmNotEntitled:DRAFT("A Pro membership is needed to book a video visit."),confirmFailed:DRAFT("That did not book. Try again."),checkAvailabilityCta:DRAFT("Check availability"),stateInterest:/* @__PURE__ */Object.freeze({cta:DRAFT("Add me to the list"),submitting:DRAFT("Adding you to the list…"),joinedTitle:DRAFT("You are on the list"),joinedBody:DRAFT("We will let you know when this changes."),failed:DRAFT("That did not save. Try again.")}),media:/* @__PURE__ */Object.freeze({droppedTemplate:DRAFT("{n} attachment did not upload."),droppedPluralTemplate:DRAFT("{n} attachments did not upload."),refusedSizeTemplate:DRAFT("{n} attachment was too large to send."),refusedSizePluralTemplate:DRAFT("{n} attachments were too large to send."),refusedTypeTemplate:DRAFT("{n} attachment is a file type that cannot be sent."),refusedTypePluralTemplate:DRAFT("{n} attachments are file types that cannot be sent."),refusedUnreadableTemplate:DRAFT("{n} attachment could not be read."),refusedUnreadablePluralTemplate:DRAFT("{n} attachments could not be read.")}),navTitle:DRAFT("Book a visit"),petFallback:"your pet",whereTitleTemplate:DRAFT("Where will {pet} be during the visit?"),whereLeadTemplate:DRAFT("Pick where {pronoun} be for the call, not where you live. It decides what the vet can do."),wherePronounFallback:"they’ll",whereFormLabelTemplate:DRAFT("Where {pet} will be"),whereLegend:DRAFT("State"),wherePrescribeMetaTemplate:DRAFT("Video visit, and prescriptions if {pet} needs them"),whereWellnessMeta:DRAFT("Wellness visit: advice and a care plan, no prescriptions yet"),whereAnotherState:DRAFT("Another state"),whereWhichState:DRAFT("Which state?"),whereLicensedTemplate:DRAFT("{vet} is licensed in {state}, so a prescription can be part of {pet}’s plan."),whereAskEveryTime:DRAFT("We ask every time: state rules require it."),issuesTitleTemplate:DRAFT("What’s going on with {pet}?"),issuesHint:DRAFT("Pick as many as you like."),issuesFormLabel:DRAFT("What’s going on"),issuesLegend:DRAFT("Main issues"),issuesPickOne:DRAFT("Pick at least one. Not sure? Choose Something else."),otherIssue:DRAFT("Something else"),describeHeadingTemplate:DRAFT("Tell {vet} what you’re seeing"),describeFieldLabel:DRAFT("What you’re seeing"),emergencyCheck:/* @__PURE__ */Object.freeze({titleTemplate:DRAFT("Is {pet} doing any of these right now?"),lead:DRAFT("A scheduled video visit isn’t the right place for an emergency."),signs:/* @__PURE__ */Object.freeze([DRAFT("Trouble breathing, or blue, grey or very pale gums"),DRAFT("Collapsed, or can’t stand up"),DRAFT("A seizure"),DRAFT("Ate something toxic, like grapes, chocolate, xylitol or medicine"),DRAFT("A swollen, hard belly, or retching with nothing coming up"),DRAFT("Bleeding that won’t stop"),DRAFT("Straining to pee with nothing coming out")]),formLabel:DRAFT("Emergency check"),legend:DRAFT("Any of these now?"),noneCta:DRAFT("No, none of these"),someCta:DRAFT("Yes, at least one")}),timeHeading:DRAFT("Pick a time"),timeMorning:DRAFT("Morning"),timeAfternoon:DRAFT("Afternoon"),timeEvening:DRAFT("Evening"),timeLegendTemplate:DRAFT("Time on {day}"),dayLegend:DRAFT("Day"),reviewHeading:DRAFT("Does this look right?"),summaryWhere:DRAFT("Where"),changeCta:DRAFT("Change"),whereAttestTemplate:DRAFT("{pet} and I will be in {state} during the visit."),attestBoth:DRAFT("Check both boxes to book the visit."),bookedStepLabel:DRAFT("Booked"),bookedTitleTemplate:DRAFT("You’re booked with {vet}"),bookedLeadTemplate:DRAFT("{when}, for {pet}."),footnote:DRAFT("Video visits are with a licensed veterinarian. Prescriptions where allowed, starting with California. In an emergency, go to the nearest emergency animal hospital."),rescheduleNavTitle:DRAFT("Change your visit"),close:DRAFT("Close"),continueCta:DRAFT("Continue"),petSelectTitle:DRAFT("Who is this visit for?"),addPetCta:DRAFT("Add a pet"),addAnotherPetCta:DRAFT("Add another pet"),locationUnknownTitle:DRAFT("We need your location to find a vet"),locationUnknownBody:DRAFT("Turn on location for Everfur, then try again."),locationUnknownCta:DRAFT("Allow location"),locationBlockedTitle:DRAFT("Location is turned off"),locationBlockedBody:DRAFT("Everfur needs your location to match you with a vet in your area."),locationBlockedCta:DRAFT("Open Settings"),locationUnavailableTitle:DRAFT("We could not read your location"),locationUnavailableBody:DRAFT("Try again in a moment."),stateAttestTemplate:DRAFT("I confirm my pet and I are in {state} right now."),describeHeading:DRAFT("Tell the vet what you are seeing"),describeHelpLong:DRAFT("When it started, what’s changed, what you’ve tried. Anything helps."),addPhotoCta:DRAFT("Add photos or videos"),addPhotoMeta:DRAFT("Optional. A close-up in good light helps."),removePhotoLabel:DRAFT("Remove photo"),summaryPet:DRAFT("Pet"),summaryVet:DRAFT("Vet"),summaryWhen:DRAFT("When"),summaryLength:DRAFT("Length"),summaryReason:DRAFT("About"),summaryLengthTemplate:DRAFT("{n} minutes"),confirmCta:DRAFT("Book the visit"),confirmBusy:DRAFT("Booking…"),bookedTitle:DRAFT("You are booked."),addToCalendarCta:DRAFT("Add to calendar"),doneCta:DRAFT("Done"),booked:/* @__PURE__ */Object.freeze({remindPromise:DRAFT("We will notify you 30 minutes before."),summaryPromise:DRAFT("{pet}'s summary goes to the vet ahead of the call."),recordsPromiseTemplate:DRAFT("{pet}’s records and your notes go to {vet} ahead of the call."),recordsPhotoPromiseTemplate:DRAFT("{pet}’s records, your notes and the photo go to {vet} ahead of the call."),stepsLabel:DRAFT("What happens next"),joinPromise:DRAFT("Join right here in the app. No links to hunt for."),backToPet:DRAFT("Back to {pet}"),calendarAdded:DRAFT("Added to your calendar"),calendarFailedBody:DRAFT("That did not save to your calendar.")}),chrome:/* @__PURE__ */Object.freeze({closeHint:DRAFT("Closes without saving"),discardTitle:DRAFT("Leave without booking?"),discardBody:DRAFT("Your answers will not be saved."),discardConfirmCta:DRAFT("Leave"),discardKeepCta:DRAFT("Keep going"),noPetsTitle:DRAFT("No pets on this account"),loadFailedTitle:DRAFT("Could not load"),retryCta:DRAFT("Try again")}),emergency:/* @__PURE__ */Object.freeze({bannerTitle:DRAFT("This can’t wait for a scheduled visit."),keepBookingCta:DRAFT("I’ve handled this, continue booking"),lede:DRAFT("What you’re describing is the kind of thing vets want to see in person, now. Call one of these first."),ledeWithoutExits:DRAFT("What you’re describing is the kind of thing vets want to see in person, now."),exitPrimaryVetTitle:DRAFT("Call {petName}’s regular vet"),exitFindErTitle:DRAFT("Find an emergency vet near you"),startCallHint:DRAFT("Starts a phone call"),poisonControl:DRAFT("ASPCA Animal Poison Control"),poisonControlDetail:DRAFT("(888) 426-4435 · a fee may apply"),poisonControlTel:"tel:+18884264435"}),visit:/* @__PURE__ */Object.freeze({title:DRAFT("Your visit")}),loading:/* @__PURE__ */Object.freeze({pets:"Loading pets. Nothing to read yet.",clinicians:"Loading vets. Nothing to read yet.",slots:"Loading times. Nothing to read yet.",consult:"Loading your visit. Nothing to read yet.",progressTemplate:"Step {step} of {total}"})});function televetBookingCopyValues(node=TELEVET_BOOKING_COPY){return typeof node=="string"?[node]:typeof node!="object"||node===null?[]:Object.values(node).flatMap(v=>televetBookingCopyValues(v))}function isTelevetBookingCopyReady(){return televetBookingCopyValues().every(value=>value.trim().length>0&&!isPlaceholderCopy(value))}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
1
+ import{createContext,forwardRef,createElement,useMemo,useState,useRef,useEffect,useCallback,useReducer,useContext,useSyncExternalStore,Component}from"react";import{TextInput as TextInput$1,StyleSheet,View,Pressable,Linking,Animated,Alert,BackHandler,Image,ActivityIndicator,ScrollView,Modal,StatusBar,Text as Text$1}from"react-native";import{z}from"zod";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import*as callModule from"@everfur/sdk/televet/call";import{useSafeAreaInsets}from"react-native-safe-area-context";function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
2
+ 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 reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}function createTelevetBackChannel(){let handlers=[];return{register(handler){return handlers=[...handlers,handler],()=>{handlers=handlers.filter(h=>h!==handler)}},dispatch(){for(let handler of[...handlers].reverse())try{if(handler())return!0}catch{}return false}}}var TelevetBackChannelContext=createContext(null);function useTelevetBackChannel(handler,enabled=true){let channel=useContext(TelevetBackChannelContext),current=useRef(handler);current.current=handler,useEffect(()=>{if(!(channel===null||!enabled))return channel.register(()=>current.current())},[channel,enabled])}var EMERGENCY_ER_LINE="Go to the nearest emergency vet now.";var DRAFT=s=>s,PLACEHOLDER_MARKERS=["[PLACEHOLDER","[PLAN NAME]","[LINK]","[Last]","TODO","TBD"];function isPlaceholderCopy(value){return PLACEHOLDER_MARKERS.some(m=>value.toUpperCase().includes(m.toUpperCase()))}function fill(template,slots){let out=template;for(let[key,value]of Object.entries(slots))out=out.split(`{${key}}`).join(value);return out}var TELEVET_BOOKING_COPY=/* @__PURE__ */Object.freeze({stateBlockedTitle:DRAFT("Not available in this state yet"),noCliniciansTitle:DRAFT("No vets available right now"),noCliniciansBody:DRAFT("Nobody is free in your area at the moment. This changes through the day."),noCliniciansRetryCta:DRAFT("Check again"),noCliniciansRegionBody:DRAFT("Video visits have to be with a vet licensed in your state, and we don’t have one there yet."),yourVetTitle:DRAFT("Your vet"),licensedPillTemplate:DRAFT("Licensed in {state}"),reviewsLabel:DRAFT("reviews"),rescheduleFromTemplate:DRAFT("Moving your visit on {when}"),rescheduleFailed:DRAFT("That did not move. Your original time is unchanged."),rescheduleStepLabel:DRAFT("Reschedule"),rescheduleTitleTemplate:DRAFT("Pick a new time for {pet}"),rescheduleNowLabel:DRAFT("Now"),rescheduleMoveTemplate:DRAFT("Move to {when}"),rescheduleMoving:DRAFT("Moving…"),rescheduleKeepLabel:DRAFT("Keep the visit as it is"),keepExistingCta:DRAFT("Keep my current time"),bookingPausedTitle:DRAFT("Booking is not available right now."),slotsErrorTitle:DRAFT("Could not load times"),noSlotsTitle:DRAFT("No times available"),nextOpeningTemplate:DRAFT("Next opening across our vets: {when}"),seeOtherVetsCta:DRAFT("See other vets"),retryCta:DRAFT("Try again"),holdExpired:DRAFT("That time is no longer held. Pick another."),slotTaken:DRAFT("That time was just taken. Pick another."),reasonPlaceholder:DRAFT("What is going on with your pet?"),reasonTooLong:DRAFT("That is too long. Please shorten it."),shareRecordsOff:DRAFT("Share health records with this vet"),confirmNotEntitled:DRAFT("A Pro membership is needed to book a video visit."),confirmFailed:DRAFT("That did not book. Try again."),checkAvailabilityCta:DRAFT("Check availability"),stateInterest:/* @__PURE__ */Object.freeze({cta:DRAFT("Add me to the list"),submitting:DRAFT("Adding you to the list…"),joinedTitle:DRAFT("You are on the list"),joinedBody:DRAFT("We will let you know when this changes."),failed:DRAFT("That did not save. Try again.")}),media:/* @__PURE__ */Object.freeze({droppedTemplate:DRAFT("{n} attachment did not upload."),droppedPluralTemplate:DRAFT("{n} attachments did not upload."),refusedSizeTemplate:DRAFT("{n} attachment was too large to send."),refusedSizePluralTemplate:DRAFT("{n} attachments were too large to send."),refusedTypeTemplate:DRAFT("{n} attachment is a file type that cannot be sent."),refusedTypePluralTemplate:DRAFT("{n} attachments are file types that cannot be sent."),refusedUnreadableTemplate:DRAFT("{n} attachment could not be read."),refusedUnreadablePluralTemplate:DRAFT("{n} attachments could not be read.")}),navTitle:DRAFT("Book a visit"),petFallback:"your pet",whereTitleTemplate:DRAFT("Where will {pet} be during the visit?"),whereLeadTemplate:DRAFT("Pick where {pronoun} be for the call, not where you live. It decides what the vet can do."),wherePronounFallback:"they’ll",whereFormLabelTemplate:DRAFT("Where {pet} will be"),whereLegend:DRAFT("State"),wherePrescribeMetaTemplate:DRAFT("Video visit, and prescriptions if {pet} needs them"),whereWellnessMeta:DRAFT("Wellness visit: advice and a care plan, no prescriptions yet"),whereAnotherState:DRAFT("Another state"),whereWhichState:DRAFT("Which state?"),whereLicensedTemplate:DRAFT("{vet} is licensed in {state}, so a prescription can be part of {pet}’s plan."),whereAskEveryTime:DRAFT("We ask every time: state rules require it."),issuesTitleTemplate:DRAFT("What’s going on with {pet}?"),issuesHint:DRAFT("Pick as many as you like."),issuesFormLabel:DRAFT("What’s going on"),issuesLegend:DRAFT("Main issues"),issuesPickOne:DRAFT("Pick at least one. Not sure? Choose Something else."),otherIssue:DRAFT("Something else"),describeHeadingTemplate:DRAFT("Tell {vet} what you’re seeing"),describeFieldLabel:DRAFT("What you’re seeing"),emergencyCheck:/* @__PURE__ */Object.freeze({titleTemplate:DRAFT("Is {pet} doing any of these right now?"),lead:DRAFT("A scheduled video visit isn’t the right place for an emergency."),signs:/* @__PURE__ */Object.freeze([DRAFT("Trouble breathing, or blue, grey or very pale gums"),DRAFT("Collapsed, or can’t stand up"),DRAFT("A seizure"),DRAFT("Ate something toxic, like grapes, chocolate, xylitol or medicine"),DRAFT("A swollen, hard belly, or retching with nothing coming up"),DRAFT("Bleeding that won’t stop"),DRAFT("Straining to pee with nothing coming out")]),formLabel:DRAFT("Emergency check"),legend:DRAFT("Any of these now?"),noneCta:DRAFT("No, none of these"),someCta:DRAFT("Yes, at least one")}),timeHeading:DRAFT("Pick a time"),timeMorning:DRAFT("Morning"),timeAfternoon:DRAFT("Afternoon"),timeEvening:DRAFT("Evening"),timeLegendTemplate:DRAFT("Time on {day}"),dayLegend:DRAFT("Day"),reviewHeading:DRAFT("Does this look right?"),summaryWhere:DRAFT("Where"),changeCta:DRAFT("Change"),whereAttestTemplate:DRAFT("{pet} and I will be in {state} during the visit."),attestBoth:DRAFT("Check both boxes to book the visit."),bookedStepLabel:DRAFT("Booked"),bookedTitleTemplate:DRAFT("You’re booked with {vet}"),bookedLeadTemplate:DRAFT("{when}, for {pet}."),footnote:DRAFT("Video visits are with a licensed veterinarian. Prescriptions where allowed, starting with California. In an emergency, go to the nearest emergency animal hospital."),rescheduleNavTitle:DRAFT("Change your visit"),close:DRAFT("Close"),continueCta:DRAFT("Continue"),petSelectTitle:DRAFT("Who is this visit for?"),addPetCta:DRAFT("Add a pet"),addAnotherPetCta:DRAFT("Add another pet"),locationUnknownTitle:DRAFT("We need your location to find a vet"),locationUnknownBody:DRAFT("Turn on location for Everfur, then try again."),locationUnknownCta:DRAFT("Allow location"),locationBlockedTitle:DRAFT("Location is turned off"),locationBlockedBody:DRAFT("Everfur needs your location to match you with a vet in your area."),locationBlockedCta:DRAFT("Open Settings"),locationUnavailableTitle:DRAFT("We could not read your location"),locationUnavailableBody:DRAFT("Try again in a moment."),stateAttestTemplate:DRAFT("I confirm my pet and I are in {state} right now."),describeHeading:DRAFT("Tell the vet what you are seeing"),describeHelpLong:DRAFT("When it started, what’s changed, what you’ve tried. Anything helps."),addPhotoCta:DRAFT("Add photos or videos"),addPhotoMeta:DRAFT("Optional. A close-up in good light helps."),removePhotoLabel:DRAFT("Remove photo"),summaryPet:DRAFT("Pet"),summaryVet:DRAFT("Vet"),summaryWhen:DRAFT("When"),summaryLength:DRAFT("Length"),summaryReason:DRAFT("About"),summaryLengthTemplate:DRAFT("{n} minutes"),confirmCta:DRAFT("Book the visit"),confirmBusy:DRAFT("Booking…"),bookedTitle:DRAFT("You are booked."),addToCalendarCta:DRAFT("Add to calendar"),doneCta:DRAFT("Done"),booked:/* @__PURE__ */Object.freeze({remindPromise:DRAFT("We will notify you 30 minutes before."),summaryPromise:DRAFT("{pet}'s summary goes to the vet ahead of the call."),recordsPromiseTemplate:DRAFT("{pet}’s records and your notes go to {vet} ahead of the call."),recordsPhotoPromiseTemplate:DRAFT("{pet}’s records, your notes and the photo go to {vet} ahead of the call."),stepsLabel:DRAFT("What happens next"),joinPromise:DRAFT("Join right here in the app. No links to hunt for."),backToPet:DRAFT("Back to {pet}"),calendarAdded:DRAFT("Added to your calendar"),calendarFailedBody:DRAFT("That did not save to your calendar.")}),chrome:/* @__PURE__ */Object.freeze({closeHint:DRAFT("Closes without saving"),discardTitle:DRAFT("Leave without booking?"),discardBody:DRAFT("Your answers will not be saved."),discardConfirmCta:DRAFT("Leave"),discardKeepCta:DRAFT("Keep going"),noPetsTitle:DRAFT("No pets on this account"),loadFailedTitle:DRAFT("Could not load"),retryCta:DRAFT("Try again")}),emergency:/* @__PURE__ */Object.freeze({bannerTitle:DRAFT("This can’t wait for a scheduled visit."),keepBookingCta:DRAFT("I’ve handled this, continue booking"),lede:DRAFT("What you’re describing is the kind of thing vets want to see in person, now. Call one of these first."),ledeWithoutExits:DRAFT("What you’re describing is the kind of thing vets want to see in person, now."),exitPrimaryVetTitle:DRAFT("Call {petName}’s regular vet"),exitFindErTitle:DRAFT("Find an emergency vet near you"),exitGoToErTitle:EMERGENCY_ER_LINE,startCallHint:DRAFT("Starts a phone call"),poisonControl:DRAFT("ASPCA Animal Poison Control"),poisonControlDetail:DRAFT("(888) 426-4435 · a fee may apply"),poisonControlTel:"tel:+18884264435"}),visit:/* @__PURE__ */Object.freeze({title:DRAFT("Your visit")}),loading:/* @__PURE__ */Object.freeze({pets:"Loading pets. Nothing to read yet.",clinicians:"Loading vets. Nothing to read yet.",slots:"Loading times. Nothing to read yet.",consult:"Loading your visit. Nothing to read yet.",progressTemplate:"Step {step} of {total}"})});function televetBookingCopyValues(node=TELEVET_BOOKING_COPY){return typeof node=="string"?[node]:typeof node!="object"||node===null?[]:Object.values(node).flatMap(v=>televetBookingCopyValues(v))}function isTelevetBookingCopyReady(){return televetBookingCopyValues().every(value=>value.trim().length>0&&!isPlaceholderCopy(value))}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
3
3
  /* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
4
4
  /* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
5
5
  /* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
@@ -86,7 +86,7 @@ return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fiel
86
86
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
87
87
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
88
88
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
89
- /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row2=>row2.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",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",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"}),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 row2=BY_KEY.get(candidate+key);if(row2)return row2}}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",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"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.",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:"Something in that request was not right. Check the details and try again.",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,unknown:"Something went wrong. Please try again."});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 row2=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};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)),row2);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 ok(value,warning){/* @__PURE__ */
89
+ /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row2=>row2.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",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",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"}),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 row2=BY_KEY.get(candidate+key);if(row2)return row2}}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."});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 row2=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};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)),row2);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 ok(value,warning){/* @__PURE__ */
90
90
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
91
91
  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)}};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{return err(authRejectedError())}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{return err(authRejectedError())}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?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp2({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(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({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(
92
92
  /* @__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__ */
@@ -129,13 +129,14 @@ return Object.freeze({failure:"unavailable"});default:/* @__PURE__ */
129
129
  return Object.freeze({failure:"failed"})}}function useSlotHold(deps){let{draft:draft,hold:hold,dispatch:dispatch,setFailure:setFailure,refetchSlots:refetchSlots}=deps;return useCallback(slot=>{if(setFailure(null),holdsSlot(draft,slot.slotId,Date.now())){dispatch({type:"next"});return}hold.mutate(slot.slotId,{onSuccess:awarded=>{dispatch({type:"patch",patch:{slot:slot,holdExpiresAt:awarded.expiresAt,idempotencyKey:televetBookingKey(slot.slotId)}}),dispatch({type:"next"})},onError:error=>{let refused=televetHoldFailure(error);setFailure(refused.failure),refused.failure==="taken"&&refetchSlots()}})},[draft,hold,dispatch,setFailure,refetchSlots])}function televetTriageReadFrom(controller){let triage=controller?.triage;return!controller||!triage?null:async(reasonText,signal)=>{let res=await triage.call(controller,reasonText,signal);return res.ok?res.value:null}}function useEarlyTriage(read){let[open,setOpen]=useState(false),[checking,setChecking]=useState(false),[acknowledgedReason,setAcknowledgedReason]=useState(null),triaged=useRef(null),inFlight=useRef(null),live=useRef(true);useEffect(()=>(live.current=true,()=>{live.current=false,inFlight.current?.abort(),inFlight.current=null}),[]);let cancel=useCallback(()=>{inFlight.current?.abort(),inFlight.current=null,live.current&&setChecking(false)},[]),check=useCallback(async reasonText=>{if(inFlight.current!==null)return false;let reason=reasonText.trim();if(acknowledgedReason!==null&&acknowledgedReason===reason||!read)return true;let emergency=triaged.current!==null&&triaged.current.reason===reason?triaged.current.emergency:null;if(emergency===null){let controller=new AbortController;inFlight.current=controller,setChecking(true);try{let verdict=await read(reason,controller.signal);if(controller.signal.aborted||!live.current)return!1;verdict===null?emergency=!1:(emergency=verdict.isEmergency||verdict.fallback,triaged.current=/* @__PURE__ */Object.freeze({reason:reason,emergency:emergency}))}catch{if(controller.signal.aborted||!live.current)return false;emergency=false}finally{inFlight.current===controller&&(inFlight.current=null,live.current&&setChecking(false))}}return emergency===true?(setOpen(true),false):true},[acknowledgedReason,read]),acknowledge=useCallback(reasonText=>{setAcknowledgedReason(reasonText.trim()),setOpen(false)},[]),close=useCallback(()=>setOpen(false),[]),reset=useCallback(()=>{cancel(),triaged.current=null,setAcknowledgedReason(null),setOpen(false)},[cancel]),isAcknowledged=useCallback(reasonText=>acknowledgedReason!==null&&acknowledgedReason===reasonText.trim(),[acknowledgedReason]);return{open:open,checking:checking,check:check,acknowledge:acknowledge,close:close,cancel:cancel,reset:reset,isAcknowledged:isAcknowledged}}function normalizeStateCode(state){let code=state?.trim().toUpperCase()??"";return/^[A-Z]{2}$/.test(code)?code:null}function useStateInterest(state,write){let normalized=normalizeStateCode(state),[phases,setPhases]=useState(()=>/* @__PURE__ */Object.freeze({})),revision=useRef(0),lastKey=useRef(null),actionFor=useCallback(reason=>{if(!write||normalized===null)return null;let key=`${normalized}:${reason}`;lastKey.current!==null&&lastKey.current!==key&&(revision.current+=1),lastKey.current=key;let phase=phases[key]??"idle";return{joined:phase==="joined",pending:phase==="pending",failed:phase==="failed",onPress:()=>{if(phase==="pending"||phase==="joined")return;let mine=revision.current+=1;setPhases(prev=>/* @__PURE__ */Object.freeze({...prev,[key]:"pending"})),(async()=>{let joined=false;try{joined=await write(normalized,reason)}catch{joined=false}revision.current===mine&&setPhases(prev=>/* @__PURE__ */Object.freeze({...prev,[key]:joined?"joined":"failed"}))})()}}},[normalized,phases,write]);return useMemo(()=>({actionFor:actionFor}),[actionFor])}function televetEmptyRosterView(cause){/* @__PURE__ */
130
130
  return Object.freeze(cause==="dark"?{title:TELEVET_BOOKING_COPY.noCliniciansTitle,message:TELEVET_BOOKING_COPY.noCliniciansBody,retryLabel:TELEVET_BOOKING_COPY.noCliniciansRetryCta,interestReason:null}:{title:TELEVET_BOOKING_COPY.noCliniciansTitle,message:TELEVET_BOOKING_COPY.noCliniciansRegionBody,retryLabel:null,interestReason:"no_licensed_vet"})}function televetEmptyRosterCause(surfaceServed){return surfaceServed?"roster":"dark"}var MAX_FILENAME_LENGTH=120;function sanitizeFilename(input){if(!input)return"attachment";let stripped=input.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!stripped)return"attachment";if(stripped.length<=MAX_FILENAME_LENGTH)return stripped;let dotIndex=stripped.lastIndexOf(".");if(dotIndex===-1||dotIndex===stripped.length-1)return stripped.slice(0,MAX_FILENAME_LENGTH);let extension=stripped.slice(dotIndex);return extension.length>=MAX_FILENAME_LENGTH?stripped.slice(0,MAX_FILENAME_LENGTH):`${stripped.slice(0,dotIndex).slice(0,MAX_FILENAME_LENGTH-extension.length)}${extension}`}var ok2=value=>/* @__PURE__ */Object.freeze({ok:true,value:value}),err2=error=>/* @__PURE__ */Object.freeze({ok:false,error:error});function failure(code,retryable,filename,extra){/* @__PURE__ */
131
131
  return Object.freeze({code:code,retryable:retryable,filename:filename,...{}})}async function uploadAttachmentBytes(transport,policy,attachment,opts){let cancelled=()=>opts?.signal?.aborted===true;if(cancelled())return err2(failure("cancelled",true,attachment.filename));try{return await transport.postMultipart(policy,attachment.file,{...opts?.signal?{signal:opts.signal}:{},...opts?.onProgress?{onProgress:opts.onProgress}:{}}),ok2(void 0)}catch{return cancelled()?err2(failure("cancelled",true,attachment.filename)):err2(failure("server",true,attachment.filename))}}var NO_MEDIA_SHORTFALL=/* @__PURE__ */Object.freeze({failed:0,refused:/* @__PURE__ */Object.freeze({size:0,type:0,unreadable:0})});function isMediaShortfallEmpty(shortfall){let{failed:failed,refused:refused}=shortfall;return failed<=0&&refused.size<=0&&refused.type<=0&&refused.unreadable<=0}function televetMediaShortfallLines(shortfall){let count=n=>Number.isFinite(n)&&n>0?Math.floor(n):0,c=TELEVET_BOOKING_COPY.media;return[{n:count(shortfall.failed),one:c.droppedTemplate,many:c.droppedPluralTemplate},{n:count(shortfall.refused.size),one:c.refusedSizeTemplate,many:c.refusedSizePluralTemplate},{n:count(shortfall.refused.type),one:c.refusedTypeTemplate,many:c.refusedTypePluralTemplate},{n:count(shortfall.refused.unreadable),one:c.refusedUnreadableTemplate,many:c.refusedUnreadablePluralTemplate}].filter(line=>line.n>0).map(line=>fill(line.n===1?line.one:line.many,{n:String(line.n)}))}function mediaShortfallFromUnsentPicks(pickCount){let n=Number.isFinite(pickCount)&&pickCount>0?Math.floor(pickCount):0;return n===0?NO_MEDIA_SHORTFALL:/* @__PURE__ */Object.freeze({failed:n,refused:NO_MEDIA_SHORTFALL.refused})}function withUnsentPicks(shortfall,pickCount){let extra=mediaShortfallFromUnsentPicks(pickCount);return extra.failed===0?shortfall:/* @__PURE__ */Object.freeze({failed:shortfall.failed+extra.failed,refused:shortfall.refused})}var PRESIGN_MARGIN_MS=6e4;function validated(pick2){let contentType=televetAttachmentContentType(pick2.filename,pick2.mimeType);return contentType===null?null:{file:{uri:pick2.uri,name:pick2.filename,mimeType:contentType,sizeBytes:pick2.fileSize},filename:pick2.filename,contentType:contentType,sizeBytes:pick2.fileSize}}function fresh(state,now){if(state?.kind!=="ready")return null;let lifetime=state.policy.expires_in_seconds*1e3;return now-state.at<lifetime-PRESIGN_MARGIN_MS?state.policy:null}function useTelevetBookingMedia({media:media,controller:controller,transport:transport}){let[states,setStates]=useState(()=>/* @__PURE__ */new Map),[darkAnswered,setDarkAnswered]=useState(false),[sending,setSending]=useState(false),statesRef=useRef(states),mediaRef=useRef(media);mediaRef.current=media;let darkRef=useRef(false),sendingRef=useRef(false),alive=useRef(new AbortController);useEffect(()=>{let controllerForThisMount=new AbortController;return alive.current=controllerForThisMount,()=>controllerForThisMount.abort()},[]);let initiate=controller?.initiateAttachment?.bind(controller),dark=darkAnswered||initiate===void 0,put=useCallback((uri,next)=>{let map=new Map(statesRef.current);map.set(uri,next),statesRef.current=map,setStates(map)},[]),goDark=useCallback(()=>{darkRef.current=true,setDarkAnswered(true)},[]),presign=useCallback(async(pick2,file)=>{if(initiate===void 0)return"dark";let res=await initiate({filename:file.filename,contentType:file.contentType,fileSize:file.sizeBytes},alive.current.signal);if(alive.current.signal.aborted)return null;if(res.ok)return put(pick2.uri,{kind:"ready",policy:res.value,at:Date.now()}),res.value;let cause=televetAttachmentInitiateFailure(res.error);return cause==="dark"?"dark":(put(pick2.uri,cause==="failed"?{kind:"retry"}:{kind:"refused",cause:cause}),null)},[initiate,put]);useEffect(()=>{if(!dark)for(let pick2 of media){if(statesRef.current.has(pick2.uri))continue;let refusal=televetAttachmentRefusal(pick2),file=validated(pick2);if(refusal!==null||file===null){put(pick2.uri,{kind:"refused",cause:refusal??"type"});continue}put(pick2.uri,{kind:"checking"}),presign(pick2,file).then(answer=>{answer==="dark"&&goDark()})}},[media,dark,presign,put,goDark]);let send=useCallback(async()=>{if(darkRef.current||initiate===void 0||sendingRef.current)return[];sendingRef.current=true,setSending(true);let keys=[];try{for(let pick2 of mediaRef.current){let state=statesRef.current.get(pick2.uri);if(state?.kind==="sent"){keys.push(state.s3Key);continue}if(state?.kind==="refused")continue;let file=validated(pick2);if(file===null)continue;let policy=fresh(state,Date.now());if(policy===null){let answer=await presign(pick2,file);if(answer==="dark")return goDark(),[];if(answer===null){statesRef.current.get(pick2.uri)?.kind==="retry"&&put(pick2.uri,{kind:"failed"});continue}policy=answer}if(alive.current.signal.aborted)return[];let staged=await uploadAttachmentBytes(transport,policy,file,{signal:alive.current.signal});if(alive.current.signal.aborted)return[];staged.ok?(put(pick2.uri,{kind:"sent",s3Key:policy.s3_key}),keys.push(policy.s3_key)):put(pick2.uri,{kind:"failed"})}return keys}catch{return keys}finally{sendingRef.current=false,alive.current.signal.aborted||setSending(false)}},[initiate,presign,put,goDark,transport]),shortfall=useMemo(()=>{if(media.length===0)return NO_MEDIA_SHORTFALL;if(dark)return mediaShortfallFromUnsentPicks(media.length);let refused={size:0,type:0,unreadable:0},failed=0;for(let pick2 of media){let state=states.get(pick2.uri);state?.kind==="refused"?refused[state.cause]+=1:state?.kind==="failed"&&(failed+=1)}return failed===0&&refused.size+refused.type+refused.unreadable===0?NO_MEDIA_SHORTFALL:/* @__PURE__ */Object.freeze({failed:failed,refused:/* @__PURE__ */Object.freeze(refused)})},[media,dark,states]),sentKeys=useMemo(()=>media.flatMap(pick2=>{let state=states.get(pick2.uri);return state?.kind==="sent"?[{key:state.s3Key,pick:pick2}]:[]}),[media,states]),bookedShortfall=useCallback(consult=>{if(dark)return shortfall;let kept=new Set(consult.mediaRefs),dropped=sentKeys.filter(sent=>!kept.has(sent.key)).length;return dropped===0?shortfall:/* @__PURE__ */Object.freeze({failed:shortfall.failed+dropped,refused:shortfall.refused})},[dark,shortfall,sentKeys]),sentOnePhoto=useCallback(consult=>{if(dark||sentKeys.length!==1)return false;let[only]=sentKeys;return only===void 0||!consult.mediaRefs.includes(only.key)?false:(televetAttachmentContentType(only.pick.filename,only.pick.mimeType)??"").startsWith("image/")},[dark,sentKeys]),live=!dark&&[...states.values()].some(state=>state.kind==="ready"||state.kind==="sent");return useMemo(()=>({shortfall:shortfall,sending:sending,live:live,send:send,bookedShortfall:bookedShortfall,sentOnePhoto:sentOnePhoto}),[shortfall,sending,live,send,bookedShortfall,sentOnePhoto])}var FILE_FIELD="file",NOT_SENT="multipart upload failed";function postRnMultipart(post){let form;try{form=new FormData;for(let[name,value]of Object.entries(post.fields))form.append(name,value);form.append(FILE_FIELD,post.file)}catch{return Promise.reject(new Error(NOT_SENT))}return post.fetch!==void 0?postWithFetch(post.fetch,post.url,form,post.signal):postWithXhr(post.url,form,post.signal)}function stored(status){return status>=200&&status<300}function postWithXhr(url,form,signal){return new Promise((resolve,reject)=>{let Xhr=globalThis.XMLHttpRequest;if(typeof Xhr!="function"||signal?.aborted===true){reject(new Error(NOT_SENT));return}let onAbort=null,release2=()=>{onAbort!==null&&signal?.removeEventListener("abort",onAbort)},fail=()=>{release2(),reject(new Error(NOT_SENT))};try{let xhr=new Xhr;xhr.open("POST",url),xhr.withCredentials=!1,xhr.onload=()=>{release2(),resolve(stored(xhr.status))},xhr.onerror=fail,xhr.ontimeout=fail,xhr.onabort=fail,signal!==void 0&&(onAbort=()=>{try{xhr.abort()}finally{fail()}},signal.addEventListener("abort",onAbort,{once:!0})),xhr.send(form)}catch{fail()}})}function postWithFetch(send,url,form,signal){return Promise.resolve().then(()=>send(url,{method:"POST",body:form,credentials:"omit",...signal?{signal:signal}:{}})).then(res=>res.ok)}var NO_URI="chat attachment upload: the file handle has no uri",FAILED="chat attachment upload failed";function filePartOf(file){return{uri:file.uri,name:sanitizeFilename(file.name),type:file.mimeType}}function createRnChatAttachmentTransport(options={}){/* @__PURE__ */
132
- return Object.freeze({postMultipart(policy,file,opts){if(typeof file.uri!="string"||file.uri.length===0)return Promise.reject(new Error(NO_URI));let{signal:signal,onProgress:onProgress}=opts,failed=()=>Promise.reject(new Error(FAILED));return signal?.aborted===true?failed():postRnMultipart({url:policy.upload_url,fields:policy.upload_fields,file:filePartOf(file),signal:signal,fetch:options.fetch}).then(stored2=>{if(!stored2)return failed();onProgress?.(1)},failed)}})}var TELEVET_SIMULATOR_COPY=/* @__PURE__ */Object.freeze({title:"Vet test mode (sandbox tenants)",create:"Create a simulated visit for this pet",createLabel:"Create",visitTemplate:"Visit {visitRef}: {status}, scheduled {scheduledAt}.",eventsNote:"Raise one of the visit events that is not a status change, to see what a tap on it opens:",advance:/* @__PURE__ */Object.freeze({completed:"Complete it",cancelled:"Cancel it",no_show:"Mark no-show"}),events:/* @__PURE__ */Object.freeze({rescheduled:"Rescheduled",reminder:"Reminder (24h)",followup_sent:"Follow-up sent",message_received:"Vet replied",ended:"Ended"}),resultTemplate:"{label}: {result}.",errorTemplate:"{label}: {message}"});var VET_VISIT_SANDBOX_VISITS_PATH="/widget/v1/televet/sandbox/visits",PET_REF_MAX2=128,VISIT_REF_MAX=64,STATUSES=/* @__PURE__ */new Set(["booked","cancelled","completed","no_show"]),RESULTS=/* @__PURE__ */new Set(["applied","already_applied","not_applicable"]),EVENTS=/* @__PURE__ */new Set(["rescheduled","reminder","followup_sent","message_received","ended"]),REMINDER_STAGES=/* @__PURE__ */new Set(["24h","30m"]);function invalid4(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function textError(name,value,max){return typeof value!="string"||value.length===0?invalid4(`${name} is required and must be a non-empty string`):hasLoneSurrogate(value)?invalid4(`${name} contains an unpaired surrogate and cannot be encoded`):serverLength(value)>max?invalid4(`${name} is longer than ${max} characters`):null}function mapActionResult(wire){if(typeof wire!="object"||wire===null)return null;let{result:result,visit:visit}=wire;if(typeof result!="string"||!RESULTS.has(result)||typeof visit!="object"||visit===null)return null;let{visit_ref:visit_ref,pet_ref:pet_ref,status:status,scheduled_at:scheduled_at}=visit;return typeof visit_ref!="string"||visit_ref.length===0||typeof pet_ref!="string"||pet_ref.length===0||typeof status!="string"||!STATUSES.has(status)||typeof scheduled_at!="string"||scheduled_at.length===0?null:/* @__PURE__ */Object.freeze({result:result,visit:/* @__PURE__ */Object.freeze({visitRef:visit_ref,petRef:pet_ref,status:status,scheduledAt:scheduled_at})})}function createVetVisitSandboxController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),run=async(call,path,body)=>{let res=await funnel.send(call,{method:"POST",path:path,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let mapped=mapActionResult(res.value);return mapped===null?err(makeEverfurError("internalError",{retryable:false})):ok(mapped)};return{createVisit(petRef){let bad=textError("pet_ref",petRef,PET_REF_MAX2);return bad!==null?Promise.resolve(err(bad)):run("televet.sandbox.createVisit",VET_VISIT_SANDBOX_VISITS_PATH,{pet_ref:petRef})},advanceVisit(visitRef,to){let bad=textError("visit_ref",visitRef,VISIT_REF_MAX);if(bad!==null)return Promise.resolve(err(bad));if(typeof to!="string"||!STATUSES.has(to))return Promise.resolve(err(invalid4("to must be booked, cancelled, completed or no_show")));let path=`${VET_VISIT_SANDBOX_VISITS_PATH}/${encodeURIComponent(visitRef)}/advance`;return run("televet.sandbox.advanceVisit",path,{to:to})},simulateVisitEvent(visitRef,event,stage){let bad=textError("visit_ref",visitRef,VISIT_REF_MAX);if(bad!==null)return Promise.resolve(err(bad));if(typeof event!="string"||!EVENTS.has(event))return Promise.resolve(err(invalid4(`event must be one of ${[...EVENTS].join(", ")}`)));if(event==="reminder"){if(typeof stage!="string"||!REMINDER_STAGES.has(stage))return Promise.resolve(err(invalid4(`stage must be one of ${[...REMINDER_STAGES].join(", ")} for a reminder`)))}else if(stage!==void 0)return Promise.resolve(err(invalid4("stage is only for a reminder")));let path=`${VET_VISIT_SANDBOX_VISITS_PATH}/${encodeURIComponent(visitRef)}/simulate`;return run("televet.sandbox.simulateVisitEvent",path,stage===void 0?{event:event}:{event:event,stage:stage})}}}function useEverfurVetVisitSandbox(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();return useMemo(()=>{let{services:services}=runtime.registry;return createVetVisitSandboxController({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch])}function televetOpensSimulator(sandboxTenant,allowance){return!sandboxTenant||!allowance.enabled?false:allowance.data!==null&&allowance.data.active===false||televetReadIsDark({error:allowance.error??null})}var isSandbox=snapshot=>snapshot.livemode===false;function useTelevetSandboxTenant(){let store=useEverfurContext().runtime.entitlements,read=useCallback(()=>isSandbox(store.getSnapshot()),[store]);return useSyncExternalStore(store.subscribe,read,read)}function useTelevetSimulatorRoute(allowance,notEntitled){let simulate=televetOpensSimulator(useTelevetSandboxTenant(),allowance);return{simulate:simulate,fundingRefused:notEntitled&&!simulate}}function televetRosterReadsAllowed(sandboxTenant,allowance){return!sandboxTenant||!allowance.enabled?true:(allowance.data!==null||(allowance.error??null)!==null)&&!televetOpensSimulator(true,allowance)}function useTelevetRosterController(controller,allowance){return televetRosterReadsAllowed(useTelevetSandboxTenant(),allowance)?controller:null}function useTelevetVisitSimulator(petRef){let sandbox=useEverfurVetVisitSandbox(),[visit,setVisit]=useState(null),[line,setLine]=useState(null),[busy,setBusy]=useState(false),inFlight=useRef(false),alive=useRef(true);useEffect(()=>(alive.current=true,()=>{alive.current=false}),[]);let run=useCallback((label,send,keepVisit)=>{inFlight.current||(inFlight.current=true,setBusy(true),send().then(res=>{if(inFlight.current=false,!!alive.current){if(setBusy(false),!res.ok){setLine({tone:"danger",text:fill(TELEVET_SIMULATOR_COPY.errorTemplate,{label:label,message:res.error.displayMessage})});return}keepVisit&&setVisit(res.value.visit),setLine({tone:"ok",text:fill(TELEVET_SIMULATOR_COPY.resultTemplate,{label:label,result:res.value.result})})}}))},[]),create=useCallback(()=>{run(TELEVET_SIMULATOR_COPY.createLabel,()=>sandbox.createVisit(petRef),true)},[petRef,run,sandbox]),advance=useCallback(to=>{visit!==null&&run(TELEVET_SIMULATOR_COPY.advance[to],()=>sandbox.advanceVisit(visit.visitRef,to),true)},[run,sandbox,visit]),raise=useCallback(event=>{if(visit===null)return;let stage=event==="reminder"?"24h":void 0;run(TELEVET_SIMULATOR_COPY.events[event],()=>sandbox.simulateVisitEvent(visit.visitRef,event,stage),false)},[run,sandbox,visit]),visitLine=visit===null?null:fill(TELEVET_SIMULATOR_COPY.visitTemplate,{visitRef:visit.visitRef,status:visit.status,scheduledAt:visit.scheduledAt});return{visit:visit,visitLine:visitLine,line:line,busy:busy,create:create,advance:advance,raise:raise}}var TELEVET_SIMULATOR_MOVES=/* @__PURE__ */Object.freeze(["completed","cancelled","no_show"]),TELEVET_SIMULATOR_EVENTS=/* @__PURE__ */Object.freeze(["rescheduled","reminder","followup_sent","message_received","ended"]);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 WHITE="#FFFFFF",BLACK="#000000";function poleForGrounds(grounds){let worst=ink=>grounds.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,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(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 PINK_SOFT_ALPHA=.22,TINT_SOFT_ALPHA=.5,EVERFUR_PINK="#FFC3BC";function televetPlainLook(theme){let c=theme.color;return{ink:c.brandInk,text:c.text.primary,muted:c.text.muted,line:c.borderRingCream,mist:c.surfaceSubtle,surface:c.surface,pink:c.highlight,onPink:c.onHighlight,go:c.mark,alert:c.danger,alertWash:c.badgeBgCritical}}function televetLook(theme){let c=theme.color,everfurPink=parseColor(c.highlight)===EVERFUR_PINK,soft=withAlpha(c.highlight,everfurPink?PINK_SOFT_ALPHA:TINT_SOFT_ALPHA);return{...televetPlainLook(theme),pinkSoft:(soft===null?null:flattenOnto(soft,c.surface))??c.surface}}function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}var MIN_TOUCH_TARGET=44;function useBookingStyles(){let theme=useEverfurTheme();return useMemo(()=>makeBookingStyles(theme),[theme])}function TelevetButton({label:label,onPress:onPress,kind:kind="primary",disabled:disabled=false,loading:loading=false,fullWidth:fullWidth=true,accessibilityLabel:accessibilityLabel,testID:testID,style:style}){let styles2=useBookingStyles(),theme=useEverfurTheme(),blocked=disabled||loading;/* @__PURE__ */
132
+ return Object.freeze({postMultipart(policy,file,opts){if(typeof file.uri!="string"||file.uri.length===0)return Promise.reject(new Error(NO_URI));let{signal:signal,onProgress:onProgress}=opts,failed=()=>Promise.reject(new Error(FAILED));return signal?.aborted===true?failed():postRnMultipart({url:policy.upload_url,fields:policy.upload_fields,file:filePartOf(file),signal:signal,fetch:options.fetch}).then(stored2=>{if(!stored2)return failed();onProgress?.(1)},failed)}})}var TELEVET_SIMULATOR_COPY=/* @__PURE__ */Object.freeze({title:"Vet test mode (sandbox tenants)",create:"Create a simulated visit for this pet",createLabel:"Create",visitTemplate:"Visit {visitRef}: {status}, scheduled {scheduledAt}.",eventsNote:"Raise one of the visit events that is not a status change, to see what a tap on it opens:",advance:/* @__PURE__ */Object.freeze({completed:"Complete it",cancelled:"Cancel it",no_show:"Mark no-show"}),events:/* @__PURE__ */Object.freeze({rescheduled:"Rescheduled",reminder:"Reminder (24h)",followup_sent:"Follow-up sent",message_received:"Vet replied",ended:"Ended"}),resultTemplate:"{label}: {result}.",errorTemplate:"{label}: {message}"});var VET_VISIT_SANDBOX_VISITS_PATH="/widget/v1/televet/sandbox/visits",PET_REF_MAX2=128,VISIT_REF_MAX=64,STATUSES=/* @__PURE__ */new Set(["booked","cancelled","completed","no_show"]),RESULTS=/* @__PURE__ */new Set(["applied","already_applied","not_applicable"]),EVENTS=/* @__PURE__ */new Set(["rescheduled","reminder","followup_sent","message_received","ended"]),REMINDER_STAGES=/* @__PURE__ */new Set(["24h","30m"]);function invalid4(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function textError(name,value,max){return typeof value!="string"||value.length===0?invalid4(`${name} is required and must be a non-empty string`):hasLoneSurrogate(value)?invalid4(`${name} contains an unpaired surrogate and cannot be encoded`):serverLength(value)>max?invalid4(`${name} is longer than ${max} characters`):null}function mapActionResult(wire){if(typeof wire!="object"||wire===null)return null;let{result:result,visit:visit}=wire;if(typeof result!="string"||!RESULTS.has(result)||typeof visit!="object"||visit===null)return null;let{visit_ref:visit_ref,pet_ref:pet_ref,status:status,scheduled_at:scheduled_at}=visit;return typeof visit_ref!="string"||visit_ref.length===0||typeof pet_ref!="string"||pet_ref.length===0||typeof status!="string"||!STATUSES.has(status)||typeof scheduled_at!="string"||scheduled_at.length===0?null:/* @__PURE__ */Object.freeze({result:result,visit:/* @__PURE__ */Object.freeze({visitRef:visit_ref,petRef:pet_ref,status:status,scheduledAt:scheduled_at})})}function createVetVisitSandboxController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),run=async(call,path,body)=>{let res=await funnel.send(call,{method:"POST",path:path,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let mapped=mapActionResult(res.value);return mapped===null?err(makeEverfurError("internalError",{retryable:false})):ok(mapped)};return{createVisit(petRef){let bad=textError("pet_ref",petRef,PET_REF_MAX2);return bad!==null?Promise.resolve(err(bad)):run("televet.sandbox.createVisit",VET_VISIT_SANDBOX_VISITS_PATH,{pet_ref:petRef})},advanceVisit(visitRef,to){let bad=textError("visit_ref",visitRef,VISIT_REF_MAX);if(bad!==null)return Promise.resolve(err(bad));if(typeof to!="string"||!STATUSES.has(to))return Promise.resolve(err(invalid4("to must be booked, cancelled, completed or no_show")));let path=`${VET_VISIT_SANDBOX_VISITS_PATH}/${encodeURIComponent(visitRef)}/advance`;return run("televet.sandbox.advanceVisit",path,{to:to})},simulateVisitEvent(visitRef,event,stage){let bad=textError("visit_ref",visitRef,VISIT_REF_MAX);if(bad!==null)return Promise.resolve(err(bad));if(typeof event!="string"||!EVENTS.has(event))return Promise.resolve(err(invalid4(`event must be one of ${[...EVENTS].join(", ")}`)));if(event==="reminder"){if(typeof stage!="string"||!REMINDER_STAGES.has(stage))return Promise.resolve(err(invalid4(`stage must be one of ${[...REMINDER_STAGES].join(", ")} for a reminder`)))}else if(stage!==void 0)return Promise.resolve(err(invalid4("stage is only for a reminder")));let path=`${VET_VISIT_SANDBOX_VISITS_PATH}/${encodeURIComponent(visitRef)}/simulate`;return run("televet.sandbox.simulateVisitEvent",path,stage===void 0?{event:event}:{event:event,stage:stage})}}}function useEverfurVetVisitSandbox(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();return useMemo(()=>{let{services:services}=runtime.registry;return createVetVisitSandboxController({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch])}function televetOpensSimulator(sandboxTenant,allowance){return!sandboxTenant||!allowance.enabled?false:allowance.data!==null&&allowance.data.active===false||televetReadIsDark({error:allowance.error??null})}var isSandbox=snapshot=>snapshot.livemode===false;function useTelevetSandboxTenant(){let store=useEverfurContext().runtime.entitlements,read=useCallback(()=>isSandbox(store.getSnapshot()),[store]);return useSyncExternalStore(store.subscribe,read,read)}function useTelevetSimulatorRoute(allowance,notEntitled){let simulate=televetOpensSimulator(useTelevetSandboxTenant(),allowance);return{simulate:simulate,fundingRefused:notEntitled&&!simulate}}function televetRosterReadsAllowed(sandboxTenant,allowance){return!sandboxTenant||!allowance.enabled?true:(allowance.data!==null||(allowance.error??null)!==null)&&!televetOpensSimulator(true,allowance)}function useTelevetRosterController(controller,allowance){return televetRosterReadsAllowed(useTelevetSandboxTenant(),allowance)?controller:null}function useTelevetVisitSimulator(petRef){let sandbox=useEverfurVetVisitSandbox(),[visit,setVisit]=useState(null),[line,setLine]=useState(null),[busy,setBusy]=useState(false),inFlight=useRef(false),alive=useRef(true);useEffect(()=>(alive.current=true,()=>{alive.current=false}),[]);let run=useCallback((label,send,keepVisit)=>{inFlight.current||(inFlight.current=true,setBusy(true),send().then(res=>{if(inFlight.current=false,!!alive.current){if(setBusy(false),!res.ok){setLine({tone:"danger",text:fill(TELEVET_SIMULATOR_COPY.errorTemplate,{label:label,message:res.error.displayMessage})});return}keepVisit&&setVisit(res.value.visit),setLine({tone:"ok",text:fill(TELEVET_SIMULATOR_COPY.resultTemplate,{label:label,result:res.value.result})})}}))},[]),create=useCallback(()=>{run(TELEVET_SIMULATOR_COPY.createLabel,()=>sandbox.createVisit(petRef),true)},[petRef,run,sandbox]),advance=useCallback(to=>{visit!==null&&run(TELEVET_SIMULATOR_COPY.advance[to],()=>sandbox.advanceVisit(visit.visitRef,to),true)},[run,sandbox,visit]),raise=useCallback(event=>{if(visit===null)return;let stage=event==="reminder"?"24h":void 0;run(TELEVET_SIMULATOR_COPY.events[event],()=>sandbox.simulateVisitEvent(visit.visitRef,event,stage),false)},[run,sandbox,visit]),visitLine=visit===null?null:fill(TELEVET_SIMULATOR_COPY.visitTemplate,{visitRef:visit.visitRef,status:visit.status,scheduledAt:visit.scheduledAt});return{visit:visit,visitLine:visitLine,line:line,busy:busy,create:create,advance:advance,raise:raise}}var TELEVET_SIMULATOR_MOVES=/* @__PURE__ */Object.freeze(["completed","cancelled","no_show"]),TELEVET_SIMULATOR_EVENTS=/* @__PURE__ */Object.freeze(["rescheduled","reminder","followup_sent","message_received","ended"]);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 WHITE="#FFFFFF",BLACK="#000000";function poleForGrounds(grounds){let worst=ink=>grounds.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,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(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 PINK_SOFT_ALPHA=.22,TINT_SOFT_ALPHA=.5,EVERFUR_PINK="#FFC3BC";function televetPlainLook(theme){let c=theme.color;return{ink:c.brandInk,text:c.text.primary,muted:c.text.muted,line:c.borderRingCream,mist:c.surfaceSubtle,surface:c.surface,pink:c.highlight,onPink:c.onHighlight,go:c.mark,alert:c.danger,alertWash:c.badgeBgCritical}}function televetLook(theme){let c=theme.color,everfurPink=parseColor(c.highlight)===EVERFUR_PINK,soft=withAlpha(c.highlight,everfurPink?PINK_SOFT_ALPHA:TINT_SOFT_ALPHA);return{...televetPlainLook(theme),pinkSoft:(soft===null?null:flattenOnto(soft,c.surface))??c.surface}}function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function insetSlot(slot,corner){return slot===void 0||slot.borderRadius!==void 0||slot.backgroundColor===void 0&&slot.borderColor===void 0?slot:{...slot,borderRadius:corner}}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}var MIN_TOUCH_TARGET=44;function useBookingStyles(){let theme=useEverfurTheme();return useMemo(()=>makeBookingStyles(theme),[theme])}function TelevetButton({label:label,onPress:onPress,kind:kind="primary",disabled:disabled=false,loading:loading=false,fullWidth:fullWidth=true,accessibilityLabel:accessibilityLabel,testID:testID,style:style}){let styles2=useBookingStyles(),theme=useEverfurTheme(),blocked=disabled||loading;/* @__PURE__ */
133
133
  return jsxs(Pressable,{onPress:onPress,disabled:blocked,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??label,accessibilityState:{disabled:blocked,busy:loading},style:({pressed:pressed})=>[styles2.button,kind==="primary"?styles2.buttonPrimary:kind==="danger"?styles2.buttonDanger:kind==="quiet"?styles2.buttonQuiet:styles2.buttonSecondary,fullWidth?styles2.buttonFull:styles2.buttonAuto,blocked?styles2.buttonDisabled:null,pressed&&!theme.motion.reducedMotion?styles2.buttonPressed:null,style],testID:testID,children:[loading?/* @__PURE__ */jsx(ActivityIndicator,{size:"small",color:kind==="secondary"||kind==="quiet"?theme.color.brandInk:kind==="danger"?theme.color.onDanger:theme.color.onPrimary}):null,
134
134
  /* @__PURE__ */jsx(Text,{tier:"control",style:kind==="secondary"||kind==="quiet"?styles2.buttonSecondaryLabel:kind==="danger"?styles2.buttonDangerLabel:styles2.buttonPrimaryLabel,children:label})]})}function TelevetStateCard({title:title,message:message,actionLabel:actionLabel,onAction:onAction,testID:testID}){let styles2=useBookingStyles(),actionable=typeof actionLabel=="string"&&actionLabel.length>0&&typeof onAction=="function";/* @__PURE__ */
135
135
  return jsxs(View,{style:styles2.stateCard,testID:testID,children:[
136
136
  /* @__PURE__ */jsx(Text,{style:styles2.stateTitle,accessibilityRole:"header",children:title}),message?/* @__PURE__ */jsx(Text,{style:styles2.stateMessage,children:message}):null,actionable?/* @__PURE__ */jsx(TelevetButton,{label:actionLabel,onPress:onAction,kind:"secondary",fullWidth:false}):null]})}function TelevetSkeletonBlock({height:height,width:width="100%",testID:testID}){let styles2=useBookingStyles();/* @__PURE__ */
137
137
  return jsx(View,{style:[styles2.skeleton,{height:height,width:width}],testID:testID,accessibilityElementsHidden:true,importantForAccessibility:"no"})}function TelevetFailureLine({message:message,assertive:assertive=false,testID:testID,style:style}){let styles2=useBookingStyles();/* @__PURE__ */
138
- return jsx(Text,{style:[styles2.failure,style],accessibilityLiveRegion:assertive?"assertive":"polite",testID:testID,children:message})}function makeBookingStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,{size:size,lineHeight:lineHeight}=type,step=theme.slots.bookingStep,stepBox=step?.backgroundColor!==void 0||step?.borderColor!==void 0?{padding:space.lg,...slotBox(step,1)}:slotBox(step,1),cardText=slotText(theme.slots.card);return StyleSheet.create({screen:{flex:1,paddingHorizontal:space.xl,gap:space.md},stepFill:{flex:1,minHeight:0,gap:space.md},stepFillBox:{flex:1,minHeight:0,gap:space.md,...stepBox},list:{gap:space.sm},button:{minHeight:52,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,paddingHorizontal:20,paddingVertical:space.xs,borderRadius:radius.pill,borderWidth:1.5,borderColor:"transparent"},buttonFull:{alignSelf:"stretch"},buttonAuto:{alignSelf:"flex-start",minWidth:MIN_TOUCH_TARGET,minHeight:MIN_TOUCH_TARGET},buttonPrimary:{backgroundColor:color.primary,borderColor:color.primaryEdge},buttonSecondary:{borderColor:color.brandInk,backgroundColor:color.surface},buttonQuiet:{backgroundColor:"transparent",paddingHorizontal:space.sm},buttonDanger:{backgroundColor:color.danger,borderColor:color.danger},buttonDisabled:{opacity:.45},buttonPressed:{transform:[{scale:.97}]},buttonPrimaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.snug},buttonDangerLabel:{...face(theme,"bold"),color:color.onDanger,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.snug},buttonSecondaryLabel:{...face(theme,"bold"),color:color.brandInk,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.snug},stateCard:{minHeight:140,justifyContent:"center",gap:space.sm,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:color.brandBorder,...slotBox(theme.slots.card,1)},stateTitle:{...headingFace(theme,"medium"),color:color.brandInk,fontSize:size.subtitle,lineHeight:size.subtitle*lineHeight.snug,...cardText},stateMessage:{...face(theme,"regular"),color:color.text.metaCool,fontSize:size.body,lineHeight:size.body*lineHeight.normal,...cardText},skeleton:{borderRadius:radius.md,backgroundColor:color.skeleton},failure:{...face(theme,"regular"),color:color.danger,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal},stepTitle:{...headingFace(theme,"medium"),color:color.brandInk,fontSize:size.heading,lineHeight:size.heading*lineHeight.snug,letterSpacing:-.33},stepHelp:{...face(theme,"regular"),color:color.text.primary,fontSize:size.body,lineHeight:size.body*lineHeight.relaxed},divider:{height:1,backgroundColor:color.brandBorder},scrollRoot:{flex:1,minHeight:0,...stepBox},scrollBody:{flex:1},scrollFooter:{paddingTop:space.md,paddingBottom:space.lg}})}function TelevetEmergencyExits({petName:petName,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}){let theme=useEverfurTheme(),local=useMemo(()=>makeExitStyles(theme),[theme]),name=petName?.trim()??"",rows2=[];return onFindEmergencyVet&&rows2.push(
138
+ return jsx(Text,{style:[styles2.failure,style],accessibilityLiveRegion:assertive?"assertive":"polite",testID:testID,children:message})}function makeBookingStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,{size:size,lineHeight:lineHeight}=type,step=theme.slots.bookingStep,stepBox=step?.backgroundColor!==void 0||step?.borderColor!==void 0?{padding:space.lg,...slotBox(step,1)}:slotBox(step,1),cardText=slotText(theme.slots.card);return StyleSheet.create({screen:{flex:1,paddingHorizontal:space.xl,gap:space.md},stepFill:{flex:1,minHeight:0,gap:space.md},stepFillBox:{flex:1,minHeight:0,gap:space.md,...stepBox},list:{gap:space.sm},button:{minHeight:52,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,paddingHorizontal:20,paddingVertical:space.xs,borderRadius:radius.pill,borderWidth:1.5,borderColor:"transparent"},buttonFull:{alignSelf:"stretch"},buttonAuto:{alignSelf:"flex-start",minWidth:MIN_TOUCH_TARGET,minHeight:MIN_TOUCH_TARGET},buttonPrimary:{backgroundColor:color.primary,borderColor:color.primaryEdge},buttonSecondary:{borderColor:color.brandInk,backgroundColor:color.surface},buttonQuiet:{backgroundColor:"transparent",paddingHorizontal:space.sm},buttonDanger:{backgroundColor:color.danger,borderColor:color.danger},buttonDisabled:{opacity:.45},buttonPressed:{transform:[{scale:.97}]},buttonPrimaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.snug},buttonDangerLabel:{...face(theme,"bold"),color:color.onDanger,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.snug},buttonSecondaryLabel:{...face(theme,"bold"),color:color.brandInk,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.snug},stateCard:{minHeight:140,justifyContent:"center",gap:space.sm,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:color.brandBorder,...slotBox(theme.slots.card,1)},stateTitle:{...headingFace(theme,"medium"),color:color.brandInk,fontSize:size.subtitle,lineHeight:size.subtitle*lineHeight.snug,...cardText},stateMessage:{...face(theme,"regular"),color:color.text.metaCool,fontSize:size.body,lineHeight:size.body*lineHeight.normal,...cardText},skeleton:{borderRadius:radius.md,backgroundColor:color.skeleton},failure:{...face(theme,"regular"),color:color.danger,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal},stepTitle:{...headingFace(theme,"medium"),color:color.brandInk,fontSize:size.heading,lineHeight:size.heading*lineHeight.snug,letterSpacing:-.33},stepHelp:{...face(theme,"regular"),color:color.text.primary,fontSize:size.body,lineHeight:size.body*lineHeight.relaxed},divider:{height:1,backgroundColor:color.brandBorder},scrollRoot:{flex:1,minHeight:0,...stepBox},scrollBody:{flex:1},scrollFooter:{paddingTop:space.md,paddingBottom:space.lg}})}function TelevetEmergencyExits({petName:petName,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}){let theme=useEverfurTheme(),local=useMemo(()=>makeExitStyles(theme),[theme]),name=petName?.trim()??"",rows2=[];return onFindEmergencyVet||rows2.push(
139
+ /* @__PURE__ */jsx(View,{style:local.vetCard,testID:"televet-emergency-go-to-er",children:/* @__PURE__ */jsx(Text,{style:local.vetTitle,children:TELEVET_BOOKING_COPY.emergency.exitGoToErTitle})},"go-to-er")),onFindEmergencyVet&&rows2.push(
139
140
  /* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:TELEVET_BOOKING_COPY.emergency.exitFindErTitle,onPress:()=>{callHost(onFindEmergencyVet)},style:local.vetCard,testID:"televet-emergency-find-vet",children:/* @__PURE__ */jsx(View,{style:local.vetRow,children:/* @__PURE__ */jsx(Text,{tier:"control",style:local.vetTitle,children:TELEVET_BOOKING_COPY.emergency.exitFindErTitle})})},"find")),rows2.push(
140
141
  /* @__PURE__ */jsx(Pressable,{accessibilityRole:"link",accessibilityLabel:`${TELEVET_BOOKING_COPY.emergency.poisonControl}, ${TELEVET_BOOKING_COPY.emergency.poisonControlDetail}`,accessibilityHint:TELEVET_BOOKING_COPY.emergency.startCallHint,onPress:()=>{Linking.openURL(TELEVET_BOOKING_COPY.emergency.poisonControlTel).catch(()=>{})},style:local.vetCard,testID:"televet-emergency-poison-control",children:/* @__PURE__ */jsxs(View,{style:local.vetText,children:[
141
142
  /* @__PURE__ */jsx(Text,{tier:"control",style:local.vetTitle,children:TELEVET_BOOKING_COPY.emergency.poisonControl}),
@@ -175,7 +176,7 @@ return jsxs(View,{style:styles2.wrap,children:[
175
176
  /* @__PURE__ */jsxs(View,{style:styles2.center,accessibilityRole:"header",accessibilityLabel:`${title??TELEVET_BOOKING_COPY.navTitle}, ${label}`,children:[
176
177
  /* @__PURE__ */jsx(Text,{tier:"compact",style:styles2.stepLabel,testID:"televet-booking-progress-label",children:label}),
177
178
  /* @__PURE__ */jsx(View,{style:styles2.segments,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"televet-booking-rail",children:segments.map((name,index)=>/* @__PURE__ */jsx(View,{style:[styles2.segment,index<current?styles2.segmentDone:null]},name))})]}),
178
- /* @__PURE__ */jsx(Pressable,{onPress:confirmClose,accessibilityRole:"button",accessibilityLabel:TELEVET_BOOKING_COPY.close,accessibilityHint:TELEVET_BOOKING_COPY.chrome.closeHint,testID:"televet-booking-close",style:styles2.ring,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.close,accessibilityElementsHidden:true,importantForAccessibility:"no",children:CLOSE_GLYPH})})]})]})}var CLOSE_GLYPH="×",BACK_LABEL="Back",LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160;function makeStyles3(theme){let{space:space,type:type}=theme,look=televetLook(theme),header=theme.slots.header,ink=header?.textColor??look.ink;return StyleSheet.create({wrap:{...slotBox(header)},logoBar:{alignItems:"center",paddingTop:space.sm},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH},bar:{flexDirection:"row",alignItems:"center",gap:space.md,paddingVertical:space.sm,minHeight:60},ring:{width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,borderRadius:MIN_TOUCH_TARGET/2,borderWidth:1.5,borderColor:look.line,alignItems:"center",justifyContent:"center"},chevron:{width:10,height:10,marginLeft:4,borderLeftWidth:2,borderBottomWidth:2,borderColor:ink,transform:[{rotate:"45deg"}]},close:{...face(theme,"regular"),color:ink,fontSize:24,lineHeight:26},center:{flex:1,alignItems:"center",gap:6},stepLabel:{...face(theme,"monoBold"),color:ink,fontSize:12,lineHeight:16,letterSpacing:1.2,textTransform:"uppercase"},segments:{flexDirection:"row",gap:4,alignSelf:"stretch"},segment:{flex:1,height:4,borderRadius:2,backgroundColor:look.mist},segmentDone:{backgroundColor:look.go},title:{...headingFace(theme,"medium"),color:ink,fontSize:type.size.subtitle}})}function formatTelevetPetMetaLine(pet){let parts=[],breed=pet.breed?.trim();breed&&parts.push(breed);let years=wholeYears(pet.ageYears);years!==null&&parts.push(`${String(years)} year${years===1?"":"s"}`);let weight=pet.weightKg;return typeof weight=="number"&&Number.isFinite(weight)&&weight>0&&parts.push(`${String(Math.round(weight))} kg`),parts.join(" · ")}function wholeYears(ageYears){if(typeof ageYears!="number"||!Number.isFinite(ageYears))return null;let years=Math.floor(ageYears);return years>=0?years:null}function TelevetIntakeMedia({media:media,onChange:onChange,onPickMedia:onPickMedia,meta:meta}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles4(theme),[theme]),remaining=MEDIA_REFS_MAX-media.length,[busy,setBusy]=useState(false);if(!onPickMedia)return null;let pick2=async()=>{if(!(busy||remaining<=0)){setBusy(true);try{let outcome=await callHostAsync(onPickMedia,remaining);if(!outcome.ok||outcome.value===null||outcome.value.length===0)return;let existing=new Set(media.map(m=>m.uri)),fresh2=outcome.value.filter(p=>typeof p?.uri=="string"&&p.uri.length>0&&!existing.has(p.uri));if(fresh2.length===0)return;onChange([...media,...fresh2].slice(0,MEDIA_REFS_MAX))}finally{setBusy(false)}}};/* @__PURE__ */
179
+ /* @__PURE__ */jsx(Pressable,{onPress:confirmClose,accessibilityRole:"button",accessibilityLabel:TELEVET_BOOKING_COPY.close,accessibilityHint:TELEVET_BOOKING_COPY.chrome.closeHint,testID:"televet-booking-close",style:styles2.ring,children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles2.close,accessibilityElementsHidden:true,importantForAccessibility:"no",children:CLOSE_GLYPH})})]})]})}var CLOSE_GLYPH="×",BACK_LABEL="Back",LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160;function makeStyles3(theme){let{space:space,type:type}=theme,look=televetLook(theme),header=theme.slots.header,ink=header?.textColor??look.ink;return StyleSheet.create({wrap:{...slotBox(insetSlot(header,theme.radius.lg))},logoBar:{alignItems:"center",paddingTop:space.sm},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH},bar:{flexDirection:"row",alignItems:"center",gap:space.md,paddingVertical:space.sm,minHeight:60},ring:{width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,borderRadius:MIN_TOUCH_TARGET/2,borderWidth:1.5,borderColor:look.line,alignItems:"center",justifyContent:"center"},chevron:{width:10,height:10,marginLeft:4,borderLeftWidth:2,borderBottomWidth:2,borderColor:ink,transform:[{rotate:"45deg"}]},close:{...face(theme,"regular"),color:ink,fontSize:24,lineHeight:26},center:{flex:1,alignItems:"center",gap:6},stepLabel:{...face(theme,"monoBold"),color:ink,fontSize:12,lineHeight:16,letterSpacing:1.2,textTransform:"uppercase"},segments:{flexDirection:"row",gap:4,alignSelf:"stretch"},segment:{flex:1,height:4,borderRadius:2,backgroundColor:look.mist},segmentDone:{backgroundColor:look.go},title:{...headingFace(theme,"medium"),color:ink,fontSize:type.size.subtitle}})}function formatTelevetPetMetaLine(pet){let parts=[],breed=pet.breed?.trim();breed&&parts.push(breed);let years=wholeYears(pet.ageYears);years!==null&&parts.push(`${String(years)} year${years===1?"":"s"}`);let weight=pet.weightKg;return typeof weight=="number"&&Number.isFinite(weight)&&weight>0&&parts.push(`${String(Math.round(weight))} kg`),parts.join(" · ")}function wholeYears(ageYears){if(typeof ageYears!="number"||!Number.isFinite(ageYears))return null;let years=Math.floor(ageYears);return years>=0?years:null}function TelevetIntakeMedia({media:media,onChange:onChange,onPickMedia:onPickMedia,meta:meta}){let theme=useEverfurTheme(),styles2=useMemo(()=>makeStyles4(theme),[theme]),remaining=MEDIA_REFS_MAX-media.length,[busy,setBusy]=useState(false);if(!onPickMedia)return null;let pick2=async()=>{if(!(busy||remaining<=0)){setBusy(true);try{let outcome=await callHostAsync(onPickMedia,remaining);if(!outcome.ok||outcome.value===null||outcome.value.length===0)return;let existing=new Set(media.map(m=>m.uri)),fresh2=outcome.value.filter(p=>typeof p?.uri=="string"&&p.uri.length>0&&!existing.has(p.uri));if(fresh2.length===0)return;onChange([...media,...fresh2].slice(0,MEDIA_REFS_MAX))}finally{setBusy(false)}}};/* @__PURE__ */
179
180
  return jsxs(View,{children:[
180
181
  /* @__PURE__ */jsxs(View,{style:styles2.row,children:[media.map((m,i)=>/* @__PURE__ */jsxs(View,{style:styles2.thumb,children:[
181
182
  /* @__PURE__ */jsx(Image,{source:{uri:m.uri},style:styles2.thumbImage,resizeMode:"cover"}),m.mimeType?.startsWith("video/")?/* @__PURE__ */jsx(View,{style:styles2.videoBadge,testID:`televet-intake-media-video-${String(i)}`,children:/* @__PURE__ */jsx(Text,{tier:"badge",style:styles2.videoBadgeText,children:VIDEO_GLYPH})}):null,
@@ -268,7 +269,7 @@ return jsxs(TelevetStepFrame,{heading:fill(check.titleTemplate,{pet:petName??TEL
268
269
  /* @__PURE__ */jsx(TelevetClinicianOutcome,{state:clinicianState,cause:emptyRosterCause,locationStatus:locationStatus,...onRequestLocation?{onRequestLocation:onRequestLocation}:{},onRetry:()=>clinicians.refetch(),stateInterest:noLicensedVetInterest,...renderUnavailable?{renderUnavailable:renderUnavailable}:{}}):step==="clinician"?/* @__PURE__ */jsx(ClinicianStep,{clinicians:clinicians.data??[],isPending:clinicians.enabled&&clinicians.isPending,isError:clinicians.isError,error:clinicians.error,selectedId:draft.clinicianId,stateCode:draft.state,stateName:where.stateName,onRetry:()=>clinicians.refetch(),onSelect:clinicianId=>{dispatch({type:"patch",patch:{clinicianId:clinicianId}}),dispatch({type:"next"})}}):step==="reason"?/* @__PURE__ */jsx(ReasonStep,{value:reasonText,composed:composedReason,vetName:matchedClinician?.displayName??null,onChange:setReasonText,media:media,onChangeMedia:setMedia,mediaLive:sendMedia.live,...onPickMedia?{onPickMedia:onPickMedia}:{},checking:triage.checking,onNext:()=>{triage.check(composedReason).then(goOn=>{goOn&&dispatch({type:"next"})})}}):step==="pet"?
269
270
  /* @__PURE__ */jsx(PetStep,{pets:pets,isPending:roster.loading,isError:roster.error!==null,error:roster.error,onRetry:()=>{roster.refresh()},onAddPet:onAddPet,selectedId:draft.petId,onSelect:petId=>dispatch({type:"patch",patch:{petId:petId}}),onNext:()=>dispatch({type:"next"})}):step==="where"?/* @__PURE__ */jsx(WhereStep,{petName:petName,where:where,onNext:()=>dispatch({type:"next"})}):step==="issues"?/* @__PURE__ */jsx(IssuesStep,{petName:petName,chips:intake.issueChips,selected:intake.concernIds,onToggle:intake.toggleConcern,onNext:()=>dispatch({type:"next"})}):step==="emergency"?/* @__PURE__ */jsx(EmergencyStep,{petName:petName,answer:intake.emergencyAnswer,onAnswer:intake.setEmergencyAnswer,onNext:()=>dispatch({type:"next"}),onHandled:()=>{triage.acknowledge(composedReason),dispatch({type:"next"})},...primaryVet?{primaryVet:primaryVet}:{},onFindEmergencyVet:onFindEmergencyVet}):
270
271
  /* @__PURE__ */jsx(View,{style:local.marker,testID:`televet-booking-step-${step}`})]}):/* @__PURE__ */jsx(View,{style:[styles2.screen,style],testID:testID??"televet-booking",children:/* @__PURE__ */jsx(View,{style:styles2.stepFill,testID:"televet-booking-copy-unapproved",children:renderUnavailable?renderUnavailable():null})})}var TELEVET_CLOCK_TICK_MS=2e4;function useNowMs(enabled=true,tickMs=TELEVET_CLOCK_TICK_MS){let[now,setNow]=useState(()=>Date.now());return useEffect(()=>{if(!enabled)return;setNow(Date.now());let id=setInterval(()=>setNow(Date.now()),tickMs);return()=>clearInterval(id)},[enabled,tickMs]),now}function answeredBehindSwitch(error){return error.httpStatus!==void 0&&!isVetMessagesDark(error)}function useVetThreads(controller,revision=0){let read=controller?.listVetThreads,enabled=read!==void 0,[state,setState]=useState(()=>({availability:enabled?"pending":"dark",threads:[],isPending:enabled,error:null})),[nonce,setNonce]=useState(0);useEffect(()=>{if(!controller||!read){setState({availability:"dark",threads:[],isPending:false,error:null});return}let abort=new AbortController,live=true;return setState(prev=>({...prev,isPending:true})),read.call(controller,abort.signal).then(settled=>{live&&(settled.ok?setState({availability:"lit",threads:settled.value,isPending:false,error:null}):isVetMessagesDark(settled.error)?setState({availability:"dark",threads:[],isPending:false,error:null}):setState(prev=>({availability:answeredBehindSwitch(settled.error)?"lit":prev.availability,threads:prev.threads,isPending:false,error:settled.error})))},()=>{live&&setState(prev=>({...prev,isPending:false}))}),()=>{live=false,abort.abort()}},[controller,read,revision,nonce]);let refetch=useCallback(()=>setNonce(n=>n+1),[]);return useMemo(()=>({...state,refetch:refetch}),[state,refetch])}function useVetThread(controller,petRef,options={}){let now=options.now??Date.now,list=controller?.listVetMessages,[messages,setMessages]=useState([]),[status,setStatus]=useState("loading"),[hasOlder,setHasOlder]=useState(false),[loadingOlder,setLoadingOlder]=useState(false),[vetFirst,setVetFirst]=useState(options.ownerCanStart===false),[sending,setSending]=useState(false),[sendFailure,setSendFailure]=useState(null),[sentCount,setSentCount]=useState(0),[nonce,setNonce]=useState(0),live=useRef(true),busy=useRef(false),olderBusy=useRef(false),nowRef=useRef(now);nowRef.current=now,useEffect(()=>(live.current=true,()=>{live.current=false}),[]),useEffect(()=>{options.ownerCanStart===false&&setVetFirst(true)},[options.ownerCanStart]),useEffect(()=>{if(setMessages([]),setHasOlder(false),!controller||!list){setStatus("ready");return}setStatus("loading");let abort=new AbortController,current=true;return list.call(controller,petRef,{},abort.signal).then(settled=>{if(current){if(!settled.ok){setStatus("error");return}setMessages([...settled.value].reverse()),setHasOlder(settled.value.length>=VET_MESSAGE_PAGE_DEFAULT),setStatus("ready")}},()=>{current&&setStatus("error")}),()=>{current=false,abort.abort()}},[controller,list,petRef,nonce]);let receiptSent=useRef(null);useEffect(()=>{let mark=controller?.markVetThreadRead;status!=="ready"||!controller||!mark||receiptSent.current===petRef||(receiptSent.current=petRef,mark.call(controller,petRef,new Date(nowRef.current()).toISOString()).catch(()=>{}))},[status,controller,petRef]);let loadOlder=useCallback(()=>{let oldest=messages[0];if(!controller||!list||!hasOlder||oldest===void 0||olderBusy.current)return;olderBusy.current=true,setLoadingOlder(true);let abort=new AbortController;list.call(controller,petRef,{before:oldest.createdAt},abort.signal).then(settled=>{if(olderBusy.current=false,!live.current||(setLoadingOlder(false),!settled.ok))return;let seen=new Set(messages.map(m=>m.messageId)),older=[...settled.value].reverse().filter(m=>!seen.has(m.messageId));setMessages(currentMessages=>[...older,...currentMessages]),setHasOlder(settled.value.length>=VET_MESSAGE_PAGE_DEFAULT)},()=>{olderBusy.current=false,live.current&&setLoadingOlder(false)})},[controller,list,petRef,hasOlder,messages]),send=useCallback(async content=>{let write=controller?.sendVetMessage;if(!controller||!write||busy.current||content.trim().length===0)return false;busy.current=true,setSending(true),setSendFailure(null);let landed=false;try{let settled=await write.call(controller,petRef,content);if(!live.current)return settled.ok;settled.ok?(landed=!0,setMessages(currentMessages=>[...currentMessages,settled.value]),setSentCount(n=>n+1)):isVetThreadVetFirst(settled.error)?(setVetFirst(!0),setSendFailure("vetWritesFirst")):setSendFailure("notSent")}catch{live.current&&setSendFailure("notSent")}finally{busy.current=false,live.current&&setSending(false)}return landed},[controller,petRef]),retry=useCallback(()=>setNonce(n=>n+1),[]),canWrite=controller?.sendVetMessage!==void 0&&!vetFirst;return useMemo(()=>({status:status,messages:messages,hasOlder:hasOlder,loadingOlder:loadingOlder,loadOlder:loadOlder,canWrite:canWrite,sending:sending,sendFailure:sendFailure,sentCount:sentCount,send:send,retry:retry}),[status,messages,hasOlder,loadingOlder,loadOlder,canWrite,sending,sendFailure,sentCount,send,retry])}function useVisitSummary(controller,consultId){let read=controller?.visitSummary,[state,setState]=useState(()=>({status:read?"loading":"absent",summary:null})),[nonce,setNonce]=useState(0);useEffect(()=>{if(!controller||!read){setState({status:"absent",summary:null});return}setState({status:"loading",summary:null});let abort=new AbortController,current=true;return read.call(controller,consultId,abort.signal).then(settled=>{current&&(settled.ok?setState({status:"ready",summary:settled.value}):setState({status:isVetMessagesDark(settled.error)?"pending":"error",summary:null}))},()=>{current&&setState({status:"error",summary:null})}),()=>{current=false,abort.abort()}},[controller,read,consultId,nonce]);let retry=useCallback(()=>setNonce(n=>n+1),[]);return useMemo(()=>({...state,retry:retry}),[state,retry])}function vetThreadPetRef(pets,petId){return petId?pets.find(p=>p.petRef===petId||p.petId===petId)?.petRef??null:null}var VET_NAME_FALLBACK="your vet",PET_NAME_FALLBACK="your pet",VET_MESSAGES_COPY=/* @__PURE__ */Object.freeze({messagesTitle:"Messages",newPillNative:"New",newPillWeb:"New reply",previewOwnerTemplate:"You: {text}",previewVetTemplateWeb:"{vet}: {text}",threadMetaTemplateNative:"With {vet}",threadLogTemplate:"Messages with {vet}",composerLabelTemplateNative:"Message {vet}",composerLabelWeb:"Message",composerPlaceholderTemplate:"Message {vet}…",send:"Send",composerNoteTemplate:"{vet} usually replies within a day. Emergency? Call a vet.",sent:"Sent",bookVisitWeb:"Book a visit",empty:"No messages yet",loading:"Loading",loadFailed:"Could not load",retry:"Try again",notSent:"Not sent",vetWritesFirst:"Your vet will write first. You can reply once they do.",attachmentsTemplate:"{n} attached",runningLateTemplate:"Running late? Message {vet}",sawTitleTemplate:"What {vet} saw",summaryLabel:"Summary",fromVetTemplate:"From {vet}",planTitleTemplate:"{pet}’s plan",wordForWord:"Word for word",fromThisVisitTitle:"From this visit",messageVetTemplate:"Message {vet}",bookFollowUp:"Book a follow-up",summaryFootnoteTemplate:"A summary of your video visit, written by {vet}. In an emergency, go to the nearest emergency animal hospital.",summaryPending:"Summary on its way"});function fillVetCopy(template,slots){let out=template;for(let[key,value]of Object.entries(slots))out=out.split(`{${key}}`).join(value);return out}function sentenceCase(line){return line.length===0?line:line.charAt(0).toUpperCase()+line.slice(1)}function vetNameOr(name){let trimmed=name?.trim()??"";return trimmed.length>0?trimmed:VET_NAME_FALLBACK}function petNameOr(name){let trimmed=name?.trim()??"";return trimmed.length>0?trimmed:PET_NAME_FALLBACK}function formatThreadDay(iso){let date2=new Date(iso);return Number.isNaN(date2.getTime())?"":date2.toLocaleDateString(void 0,{month:"short",day:"numeric"})}var TELEVET_VISITS_COPY_NATIVE=/* @__PURE__ */Object.freeze({pastTitle:"Past video visits",upcomingTitle:"Next video visit",bookedPill:"Booked",visitTitleTemplate:"{pet} with {vet}",minutesTemplate:"{n} minutes",emptyTitle:"No visits yet",bookCta:"Find a time",bookCardTitle:"Book a video visit",bookAnotherTitle:"Book another visit",bookCardSubtitle:"Get help for your pet from home.",loadErrorTitle:"Could not load your visits",retryCta:"Try again",statusCompleted:"Completed",statusCancelled:"Cancelled",statusMissed:"Missed",manageCta:"Manage",getReadyCta:"Get ready",joinCta:"Join the visit",joinDisabledReason:"You can join closer to the time.",joinOverReason:"This visit has ended.",vetUnassigned:"Your vet",rescheduleCta:"Reschedule",cancelCta:"Cancel",cancelConfirmTitleTemplate:"Cancel {pet}’s visit?",cancelConfirmTitle:"Cancel this visit?",cancelConfirmBody:"You can book another one afterwards.",cancelConfirmCta:"Cancel the visit",cancelKeepCta:"Keep the visit",cancelWhyTitle:"What changed?",cancelWhyOptional:"Optional",cancelWhyBetterTemplate:"{pet} is better",cancelWhyTime:"The time doesn’t work",cancelWhyRegularVet:"We’ll see our regular vet",cancelWhyOther:"Something else",cancelWhyTimeHint:"Another time might be easier.",cancelMoveInstead:"Move the visit instead",summaryWhen:"When",summaryVet:"Vet",summaryAbout:"About",cancelFailedTitle:"Could not cancel",cancelReason:"Cancelled by the pet parent in the app.",cancelPolicyErrorTitle:"Could not load what you need to agree to",phaseCancelled:"This visit was cancelled",phaseCancelledBody:"You can book another visit when you are ready.",notFoundTitle:"Not found",notFoundBody:"This visit is no longer available.",staleTitle:"Could not load your visits",staleRetry:"Try again"});function televetVisitStatusNative(status){switch(status){case"completed":return TELEVET_VISITS_COPY_NATIVE.statusCompleted;case"cancelled_owner":case"cancelled_ops":return TELEVET_VISITS_COPY_NATIVE.statusCancelled;case"no_show_owner":case"no_show_vet":return TELEVET_VISITS_COPY_NATIVE.statusMissed;default:return null}}function TelevetVisitBackRow({onBack:onBack,testID:testID}){let styles2=useVisitStyles();/* @__PURE__ */
271
- return jsx(View,{style:styles2.navRow,children:/* @__PURE__ */jsx(Pressable,{onPress:onBack,accessibilityRole:"button",accessibilityLabel:BACK_LABEL,testID:testID,style:styles2.backTap,children:/* @__PURE__ */jsx(View,{style:styles2.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})})})}function useVisitStyles(){let theme=useEverfurTheme();return useMemo(()=>makeVisitStyles(theme),[theme])}function makeVisitStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,{size:size,lineHeight:lineHeight}=type,look=televetLook(theme),header=theme.slots.header,card=theme.slots.card,cardText=slotText(card);return StyleSheet.create({screen:{flex:1,paddingHorizontal:space.xl},body:{gap:space.lg,paddingBottom:space.xl},navRow:{paddingVertical:space.sm,flexDirection:"row",...slotBox(header)},backTap:{width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,borderRadius:MIN_TOUCH_TARGET/2,borderWidth:1.5,borderColor:look.line,alignItems:"center",justifyContent:"center"},chevron:{width:10,height:10,marginLeft:space.xs,borderLeftWidth:2,borderBottomWidth:2,borderColor:header?.textColor??look.ink,transform:[{rotate:"45deg"}]},title:{...headingFace(theme,"bold"),color:look.ink,fontSize:size.subtitle,lineHeight:size.subtitle*lineHeight.snug},list:{gap:0},card:{gap:14,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:look.line,backgroundColor:look.surface,...slotBox(card,1)},cardHead:{flexDirection:"row",alignItems:"center",gap:space.sm},pill:{marginLeft:"auto",height:24,paddingHorizontal:10,borderRadius:radius.pill,backgroundColor:look.pink,justifyContent:"center"},pillLine:{backgroundColor:look.surface,borderWidth:1.5,borderColor:look.line},pillText:{...face(theme,"monoBold"),color:look.onPink,fontSize:11,letterSpacing:.9,textTransform:"uppercase"},pillLineText:{color:look.muted},visit:{flexDirection:"row",alignItems:"flex-start",gap:space.lg},dateTile:{width:56,paddingVertical:space.sm,borderRadius:14,backgroundColor:look.pinkSoft,alignItems:"center",gap:2},dateTileSmall:{...face(theme,"monoBold"),color:look.ink,fontSize:11,letterSpacing:.9,textTransform:"uppercase"},dateTileDay:{...face(theme,"medium"),color:look.ink,fontSize:size.heading,lineHeight:size.heading*lineHeight.tight},visitMain:{flex:1,gap:2},visitTitle:{...headingFace(theme,"bold"),color:look.ink,fontSize:size.body,lineHeight:size.body*lineHeight.snug,...cardText},visitLine:{...face(theme,"regular"),color:look.text,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.normal,...cardText},row:{gap:2,paddingVertical:space.md,borderTopWidth:1,borderTopColor:look.line},rowFirst:{borderTopWidth:0,paddingTop:0},rowHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},when:{flex:1,...face(theme,"bold"),color:look.ink,fontSize:size.body,lineHeight:size.body*lineHeight.snug,...cardText},status:{...face(theme,"monoBold"),color:look.muted,fontSize:11,letterSpacing:.9,textTransform:"uppercase",...cardText},meta:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal,...cardText},bookCard:{gap:space.md,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:look.line,backgroundColor:look.surface,...slotBox(card,1)},bookTitle:{...headingFace(theme,"bold"),color:look.ink,fontSize:size.subtitle,lineHeight:size.subtitle*lineHeight.snug,...cardText},bookSubtitle:{...face(theme,"regular"),color:look.muted,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.normal,...cardText},footnote:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,lineHeight:size.caption*lineHeight.relaxed,textAlign:"center"},visitCard:{gap:space.md,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:look.line,backgroundColor:look.surface,...slotBox(card,1)},visitWhen:{...headingFace(theme,"medium"),color:look.ink,fontSize:size.heading,lineHeight:size.heading*lineHeight.snug,...cardText},visitWho:{...face(theme,"bold"),color:look.ink,fontSize:size.body,lineHeight:size.body*lineHeight.snug,...cardText},visitMeta:{...face(theme,"regular"),color:look.text,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.normal,...cardText},reason:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal,...cardText},terms:{padding:space.md,borderRadius:radius.sm,backgroundColor:look.mist,...face(theme,"regular"),color:look.text,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal},noticeTitle:{...headingFace(theme,"medium"),color:look.ink,fontSize:size.heading,lineHeight:size.heading*lineHeight.snug},noticeBody:{...face(theme,"regular"),color:look.muted,fontSize:size.body,lineHeight:size.body*lineHeight.normal},receipt:{gap:space.xs,padding:space.md,borderRadius:radius.sm,backgroundColor:look.mist},stack:{gap:space.sm},whyHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:space.sm},whyTitle:{...face(theme,"bold"),color:look.ink,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.snug},whyNote:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal},hint:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:space.sm,paddingVertical:space.sm,paddingHorizontal:space.lg,borderRadius:radius.sm,backgroundColor:look.mist},muted:{...face(theme,"regular"),color:color.text.primary,fontSize:size.bodyTight}})}function makeVetThreadStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,{size:size,lineHeight:lineHeight}=type,look=televetLook(theme),bubble={...face(theme,"regular"),maxWidth:"85%",paddingVertical:10,paddingHorizontal:14,borderRadius:18,fontSize:size.body,lineHeight:size.body*lineHeight.normal};return StyleSheet.create({head:{gap:2},screenTitle:{...headingFace(theme,"medium"),color:look.ink,fontSize:size.heading,lineHeight:size.heading*lineHeight.snug},meta:{...face(theme,"regular"),color:look.muted,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.normal},log:{gap:space.sm,paddingBottom:space.md},day:{alignSelf:"center",...face(theme,"monoBold"),color:look.muted,fontSize:11,letterSpacing:.9,textTransform:"uppercase",paddingTop:space.sm},item:{gap:4,alignItems:"flex-start"},itemMine:{alignItems:"flex-end"},whoRow:{flexDirection:"row",alignItems:"baseline",gap:space.sm},who:{...face(theme,"bold"),color:look.ink,fontSize:size.bodyTight},time:{...face(theme,"regular"),color:look.muted,fontSize:size.caption},bubbleMine:{...bubble,backgroundColor:color.bubbleUser,color:color.onPrimary,borderBottomRightRadius:6},bubbleVet:{...bubble,backgroundColor:color.bubbleVet,color:color.onBubbleVet,borderBottomLeftRadius:6},system:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,textAlign:"center",alignSelf:"center"},attachments:{...face(theme,"regular"),color:look.muted,fontSize:size.caption},composer:{flexDirection:"row",alignItems:"flex-end",gap:space.sm,padding:space.sm,borderRadius:radius.lg,borderWidth:1.5,borderColor:look.line,backgroundColor:look.surface,...slotBox(theme.slots.input,1.5)},field:{flex:1,minHeight:MIN_TOUCH_TARGET,paddingHorizontal:space.sm,paddingVertical:10,...face(theme,"regular"),color:look.text,fontSize:size.body,...slotText(theme.slots.input)},send:{minWidth:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,paddingHorizontal:space.md,borderRadius:MIN_TOUCH_TARGET/2,backgroundColor:color.primary,alignItems:"center",justifyContent:"center"},sendDisabled:{opacity:.5},sendLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.bodyTight},note:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal},failure:{...face(theme,"bold"),color:look.alert,fontSize:size.caption},label:{...face(theme,"monoBold"),color:look.muted,fontSize:11,letterSpacing:.9,textTransform:"uppercase"},body:{...face(theme,"regular"),color:look.text,fontSize:size.body,lineHeight:size.body*lineHeight.normal},planItem:{flexDirection:"row",gap:space.md,alignItems:"flex-start"},planNumber:{...face(theme,"monoBold"),color:look.ink,fontSize:12,letterSpacing:.9,paddingTop:3},planText:{flex:1,...face(theme,"regular"),color:look.text,fontSize:size.body,lineHeight:size.body*lineHeight.normal},rowPress:{flexDirection:"row",alignItems:"center",gap:space.md,minHeight:MIN_TOUCH_TARGET},rowMain:{flex:1,gap:2},rowEnd:{alignItems:"flex-end",gap:4},preview:{...face(theme,"regular"),color:look.muted,fontSize:size.caption},link:{minHeight:MIN_TOUCH_TARGET,justifyContent:"center",alignSelf:"flex-start"},linkText:{...face(theme,"bold"),color:color.linkInk,fontSize:size.bodyTight,textDecorationLine:"underline"}})}function useVetThreadStyles(){let theme=useEverfurTheme();return useMemo(()=>makeVetThreadStyles(theme),[theme])}function TelevetConsultScreen({consult:opened,controller:injected,onJoin:onJoin,onReschedule:onReschedule,onCancelled:onCancelled,onBack:onBack,revision:revision=0,onMessageVet:onMessageVet,nowMs:nowMs,style:style}){let styles2=useVisitStyles(),lateStyles=useVetThreadStyles(),controller=useTelevetBookingController(injected),[localRevision,setLocalRevision]=useState(0),read=useTelevetConsult(opened.consultId,controller,revision+localRevision),policy=useTelevetCancellationPolicy(controller),cancel=useTelevetCancelConsult(opened.consultId,controller),{pets:pets}=useEverfurPets(),threads=useVetThreads(controller),[confirming,setConfirming]=useState(false),[why,setWhy]=useState(null),[cancelFailed,setCancelFailed]=useState(false),[receipt,setReceipt]=useState(null),notFound=read.isError&&read.error?.httpStatus===404,consult=notFound?null:read.data??opened,terminal=consult!==null&&TERMINAL_CONSULT_STATUSES.has(consult.status),ticked=useNowMs(!terminal),readiness=televetJoinReadiness(consult,nowMs??ticked),petName=consult===null?null:nameOf(pets,consult.petId),terms=policy.data?.summary.trim()||null,confirmCancel=useCallback(()=>{terms&&(setCancelFailed(false),cancel.mutate(why??TELEVET_VISITS_COPY_NATIVE.cancelReason,{onSuccess:settled=>{setConfirming(false),setReceipt(settled),setLocalRevision(n=>n+1),onCancelled?.(settled)},onError:()=>setCancelFailed(true)}))},[terms,cancel,onCancelled,why]);if(consult===null)/* @__PURE__ */
272
+ return jsx(View,{style:styles2.navRow,children:/* @__PURE__ */jsx(Pressable,{onPress:onBack,accessibilityRole:"button",accessibilityLabel:BACK_LABEL,testID:testID,style:styles2.backTap,children:/* @__PURE__ */jsx(View,{style:styles2.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})})})}function useVisitStyles(){let theme=useEverfurTheme();return useMemo(()=>makeVisitStyles(theme),[theme])}function makeVisitStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,{size:size,lineHeight:lineHeight}=type,look=televetLook(theme),header=theme.slots.header,card=theme.slots.card,cardText=slotText(card);return StyleSheet.create({screen:{flex:1,paddingHorizontal:space.xl},body:{gap:space.lg,paddingBottom:space.xl},navRow:{paddingVertical:space.sm,flexDirection:"row",...slotBox(insetSlot(header,radius.lg))},backTap:{width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,borderRadius:MIN_TOUCH_TARGET/2,borderWidth:1.5,borderColor:look.line,alignItems:"center",justifyContent:"center"},chevron:{width:10,height:10,marginLeft:space.xs,borderLeftWidth:2,borderBottomWidth:2,borderColor:header?.textColor??look.ink,transform:[{rotate:"45deg"}]},title:{...headingFace(theme,"bold"),color:look.ink,fontSize:size.subtitle,lineHeight:size.subtitle*lineHeight.snug},list:{gap:0},card:{gap:14,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:look.line,backgroundColor:look.surface,...slotBox(card,1)},cardHead:{flexDirection:"row",alignItems:"center",gap:space.sm},pill:{marginLeft:"auto",height:24,paddingHorizontal:10,borderRadius:radius.pill,backgroundColor:look.pink,justifyContent:"center"},pillLine:{backgroundColor:look.surface,borderWidth:1.5,borderColor:look.line},pillText:{...face(theme,"monoBold"),color:look.onPink,fontSize:11,letterSpacing:.9,textTransform:"uppercase"},pillLineText:{color:look.muted},visit:{flexDirection:"row",alignItems:"flex-start",gap:space.lg},dateTile:{width:56,paddingVertical:space.sm,borderRadius:14,backgroundColor:look.pinkSoft,alignItems:"center",gap:2},dateTileSmall:{...face(theme,"monoBold"),color:look.ink,fontSize:11,letterSpacing:.9,textTransform:"uppercase"},dateTileDay:{...face(theme,"medium"),color:look.ink,fontSize:size.heading,lineHeight:size.heading*lineHeight.tight},visitMain:{flex:1,gap:2},visitTitle:{...headingFace(theme,"bold"),color:look.ink,fontSize:size.body,lineHeight:size.body*lineHeight.snug,...cardText},visitLine:{...face(theme,"regular"),color:look.text,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.normal,...cardText},row:{gap:2,paddingVertical:space.md,borderTopWidth:1,borderTopColor:look.line},rowFirst:{borderTopWidth:0,paddingTop:0},rowHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},when:{flex:1,...face(theme,"bold"),color:look.ink,fontSize:size.body,lineHeight:size.body*lineHeight.snug,...cardText},status:{...face(theme,"monoBold"),color:look.muted,fontSize:11,letterSpacing:.9,textTransform:"uppercase",...cardText},meta:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal,...cardText},bookCard:{gap:space.md,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:look.line,backgroundColor:look.surface,...slotBox(card,1)},bookTitle:{...headingFace(theme,"bold"),color:look.ink,fontSize:size.subtitle,lineHeight:size.subtitle*lineHeight.snug,...cardText},bookSubtitle:{...face(theme,"regular"),color:look.muted,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.normal,...cardText},footnote:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,lineHeight:size.caption*lineHeight.relaxed,textAlign:"center"},visitCard:{gap:space.md,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:look.line,backgroundColor:look.surface,...slotBox(card,1)},visitWhen:{...headingFace(theme,"medium"),color:look.ink,fontSize:size.heading,lineHeight:size.heading*lineHeight.snug,...cardText},visitWho:{...face(theme,"bold"),color:look.ink,fontSize:size.body,lineHeight:size.body*lineHeight.snug,...cardText},visitMeta:{...face(theme,"regular"),color:look.text,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.normal,...cardText},reason:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal,...cardText},terms:{padding:space.md,borderRadius:radius.sm,backgroundColor:look.mist,...face(theme,"regular"),color:look.text,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal},noticeTitle:{...headingFace(theme,"medium"),color:look.ink,fontSize:size.heading,lineHeight:size.heading*lineHeight.snug},noticeBody:{...face(theme,"regular"),color:look.muted,fontSize:size.body,lineHeight:size.body*lineHeight.normal},receipt:{gap:space.xs,padding:space.md,borderRadius:radius.sm,backgroundColor:look.mist},stack:{gap:space.sm},whyHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:space.sm},whyTitle:{...face(theme,"bold"),color:look.ink,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.snug},whyNote:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal},hint:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:space.sm,paddingVertical:space.sm,paddingHorizontal:space.lg,borderRadius:radius.sm,backgroundColor:look.mist},muted:{...face(theme,"regular"),color:color.text.primary,fontSize:size.bodyTight}})}function makeVetThreadStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,{size:size,lineHeight:lineHeight}=type,look=televetLook(theme),bubble={...face(theme,"regular"),maxWidth:"85%",paddingVertical:10,paddingHorizontal:14,borderRadius:18,fontSize:size.body,lineHeight:size.body*lineHeight.normal};return StyleSheet.create({head:{gap:2},screenTitle:{...headingFace(theme,"medium"),color:look.ink,fontSize:size.heading,lineHeight:size.heading*lineHeight.snug},meta:{...face(theme,"regular"),color:look.muted,fontSize:size.bodyTight,lineHeight:size.bodyTight*lineHeight.normal},log:{gap:space.sm,paddingBottom:space.md},day:{alignSelf:"center",...face(theme,"monoBold"),color:look.muted,fontSize:11,letterSpacing:.9,textTransform:"uppercase",paddingTop:space.sm},item:{gap:4,alignItems:"flex-start"},itemMine:{alignItems:"flex-end"},whoRow:{flexDirection:"row",alignItems:"baseline",gap:space.sm},who:{...face(theme,"bold"),color:look.ink,fontSize:size.bodyTight},time:{...face(theme,"regular"),color:look.muted,fontSize:size.caption},bubbleMine:{...bubble,backgroundColor:color.bubbleUser,color:color.onPrimary,borderBottomRightRadius:6},bubbleVet:{...bubble,backgroundColor:color.bubbleVet,color:color.onBubbleVet,borderBottomLeftRadius:6},system:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,textAlign:"center",alignSelf:"center"},attachments:{...face(theme,"regular"),color:look.muted,fontSize:size.caption},composer:{flexDirection:"row",alignItems:"flex-end",gap:space.sm,padding:space.sm,borderRadius:radius.lg,borderWidth:1.5,borderColor:look.line,backgroundColor:look.surface,...slotBox(theme.slots.input,1.5)},field:{flex:1,minHeight:MIN_TOUCH_TARGET,paddingHorizontal:space.sm,paddingVertical:10,...face(theme,"regular"),color:look.text,fontSize:size.body,...slotText(theme.slots.input)},send:{minWidth:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,paddingHorizontal:space.md,borderRadius:MIN_TOUCH_TARGET/2,backgroundColor:color.primary,alignItems:"center",justifyContent:"center"},sendDisabled:{opacity:.5},sendLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.bodyTight},note:{...face(theme,"regular"),color:look.muted,fontSize:size.caption,lineHeight:size.caption*lineHeight.normal},failure:{...face(theme,"bold"),color:look.alert,fontSize:size.caption},label:{...face(theme,"monoBold"),color:look.muted,fontSize:11,letterSpacing:.9,textTransform:"uppercase"},body:{...face(theme,"regular"),color:look.text,fontSize:size.body,lineHeight:size.body*lineHeight.normal},planItem:{flexDirection:"row",gap:space.md,alignItems:"flex-start"},planNumber:{...face(theme,"monoBold"),color:look.ink,fontSize:12,letterSpacing:.9,paddingTop:3},planText:{flex:1,...face(theme,"regular"),color:look.text,fontSize:size.body,lineHeight:size.body*lineHeight.normal},rowPress:{flexDirection:"row",alignItems:"center",gap:space.md,minHeight:MIN_TOUCH_TARGET},rowMain:{flex:1,gap:2},rowEnd:{alignItems:"flex-end",gap:4},preview:{...face(theme,"regular"),color:look.muted,fontSize:size.caption},link:{minHeight:MIN_TOUCH_TARGET,justifyContent:"center",alignSelf:"flex-start"},linkText:{...face(theme,"bold"),color:color.linkInk,fontSize:size.bodyTight,textDecorationLine:"underline"}})}function useVetThreadStyles(){let theme=useEverfurTheme();return useMemo(()=>makeVetThreadStyles(theme),[theme])}function TelevetConsultScreen({consult:opened,controller:injected,onJoin:onJoin,onReschedule:onReschedule,onCancelled:onCancelled,onBack:onBack,revision:revision=0,onMessageVet:onMessageVet,nowMs:nowMs,style:style}){let styles2=useVisitStyles(),lateStyles=useVetThreadStyles(),controller=useTelevetBookingController(injected),[localRevision,setLocalRevision]=useState(0),read=useTelevetConsult(opened.consultId,controller,revision+localRevision),policy=useTelevetCancellationPolicy(controller),cancel=useTelevetCancelConsult(opened.consultId,controller),{pets:pets}=useEverfurPets(),threads=useVetThreads(controller),[confirming,setConfirming]=useState(false),[why,setWhy]=useState(null),[cancelFailed,setCancelFailed]=useState(false),[receipt,setReceipt]=useState(null),notFound=read.isError&&read.error?.httpStatus===404,consult=notFound?null:read.data??opened,terminal=consult!==null&&TERMINAL_CONSULT_STATUSES.has(consult.status),ticked=useNowMs(!terminal),readiness=televetJoinReadiness(consult,nowMs??ticked),petName=consult===null?null:nameOf(pets,consult.petId),terms=policy.data?.summary.trim()||null,confirmCancel=useCallback(()=>{terms&&(setCancelFailed(false),cancel.mutate(why??TELEVET_VISITS_COPY_NATIVE.cancelReason,{onSuccess:settled=>{setConfirming(false),setReceipt(settled),setLocalRevision(n=>n+1),onCancelled?.(settled)},onError:()=>setCancelFailed(true)}))},[terms,cancel,onCancelled,why]);if(consult===null)/* @__PURE__ */
272
273
  return jsxs(View,{style:[styles2.screen,style],testID:"televet-consult-missing",children:[
273
274
  /* @__PURE__ */jsx(TelevetVisitBackRow,{onBack:onBack,testID:"televet-consult-back"}),
274
275
  /* @__PURE__ */jsx(TelevetStateCard,{title:TELEVET_VISITS_COPY_NATIVE.notFoundTitle,message:TELEVET_VISITS_COPY_NATIVE.notFoundBody})]});let status=consult.status,isCancelled=status==="cancelled_owner"||status==="cancelled_ops",canJoin=status==="scheduled"||status==="in_progress",canManage=canManageTelevetVisit(status)&&receipt===null,vet=consult.clinicianName??TELEVET_VISITS_COPY_NATIVE.vetUnassigned,meta=[petName,consult.reasonText].filter(Boolean).join(" · "),latePetRef=threads.availability==="lit"?vetThreadPetRef(pets,consult.petId):null,lateListed=latePetRef===null?void 0:threads.threads.find(t=>t.petRef===latePetRef),lateTarget=latePetRef===null?null:{petRef:latePetRef,petName:petName,vetName:consult.clinicianName,...lateListed?{ownerCanStart:lateListed.ownerCanStart}:{}};/* @__PURE__ */
@@ -290,7 +291,7 @@ return jsxs(View,{style:[styles2.screen,style],testID:"televet-consult",children
290
291
  /* @__PURE__ */jsx(TelevetChoiceRow,{title:answer.label,selected:why===answer.label,onPress:()=>setWhy(why===answer.label?null:answer.label),testID:`televet-consult-cancel-why-${answer.id}`}),answer.id==="time"&&why===answer.label?/* @__PURE__ */jsxs(View,{style:styles2.hint,testID:"televet-consult-cancel-time-hint",children:[
291
292
  /* @__PURE__ */jsx(Text,{style:styles2.muted,children:TELEVET_VISITS_COPY_NATIVE.cancelWhyTimeHint}),onReschedule?/* @__PURE__ */jsx(TelevetButton,{label:TELEVET_VISITS_COPY_NATIVE.cancelMoveInstead,kind:"quiet",fullWidth:false,onPress:()=>onReschedule(consult),testID:"televet-consult-cancel-move"}):null]}):null]},answer.id))}),cancelFailed?/* @__PURE__ */jsx(TelevetFailureLine,{message:TELEVET_VISITS_COPY_NATIVE.cancelFailedTitle,testID:"televet-consult-cancel-failed"}):null,
292
293
  /* @__PURE__ */jsx(TelevetButton,{label:TELEVET_VISITS_COPY_NATIVE.cancelConfirmCta,kind:"danger",loading:cancel.isPending,onPress:confirmCancel,testID:"televet-consult-cancel-yes"}),
293
- /* @__PURE__ */jsx(TelevetButton,{label:TELEVET_VISITS_COPY_NATIVE.cancelKeepCta,kind:"secondary",disabled:cancel.isPending,onPress:()=>{setConfirming(false),setCancelFailed(false)},testID:"televet-consult-cancel-keep"})]}):/* @__PURE__ */jsx(TelevetButton,{label:TELEVET_VISITS_COPY_NATIVE.cancelCta,kind:"secondary",disabled:!terms,onPress:()=>{setCancelFailed(false),setConfirming(true)},testID:"televet-consult-cancel"})]}):null,read.isError&&!notFound?/* @__PURE__ */jsx(TelevetStateCard,{title:TELEVET_VISITS_COPY_NATIVE.staleTitle,actionLabel:TELEVET_VISITS_COPY_NATIVE.staleRetry,onAction:()=>read.refetch(),testID:"televet-consult-stale"}):null]})]})}var VET_CALL_COPY=/* @__PURE__ */Object.freeze({muteCta:"Mute",unmuteCta:"Unmute",cameraOffCta:"Camera off",cameraOnCta:"Camera on",leaveCta:"Leave",switchCameraCta:"Switch camera",speakerOffCta:"Speaker off",speakerOnCta:"Speaker on",lobbyTitleNoName:"Your vet is joining",lobbySubtitle:"Usually under a minute",lobbyPrepLabel:"WHILE YOU WAIT",lobbyPrepNoPet:"Have your pet nearby and somewhere well lit.",lobbyTitle:clinicianName=>{let name=clinicianName?.trim()??"";return name.length>0?`${name} is joining`:VET_CALL_COPY.lobbyTitleNoName},lobbyPrep:petName=>{let pet=petName?.trim()??"";return pet.length>0?`Have ${pet} nearby and somewhere well lit.`:VET_CALL_COPY.lobbyPrepNoPet},lobbyDuration:minutes=>`${minutes} minutes`,waitingRoomLabel:"Waiting room",leaveWaitingRoomLabel:"Leave the waiting room",lobbyTipsTitle:clinicianName=>{let name=clinicianName?.trim()??"";return name.length>0?`Before ${name} joins`:VET_CALL_COPY.lobbyPrepLabel},lobbyTipSpot:"Find a bright, quiet spot.",joinFailedReason:"That did not open. Try again.",recordingNoticeTitle:"This consultation is recorded.",recordingNoticeCta:"Continue to the call",recordingNoticeDecline:"Not now",selfCameraOffLabel:"Your camera is off"});function televetJoinRefusalNativeCopy(refusal){switch(refusal){case"too_early":return"You can join closer to the time.";case"too_late":return"This visit has ended.";case"room_not_ready":return"The room is still being set up. Try again in a moment.";case"not_joinable":return"This visit is no longer open.";case"unavailable":return"No way to join this visit yet.";default:return"That did not open. Try again."}}var TELEVET_JOIN_UNAVAILABLE_NATIVE="No way to join this visit yet.";function televetJoinIsRetryable(refusal){return refusal==="room_not_ready"||refusal==="unknown"}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 isEverfurDailyRegistered(){return televetGlobal().dailyRegistered}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}var JOINING=/* @__PURE__ */Object.freeze({status:"joining"});function useTelevetJoin(consultId,controller){let[attempt,setAttempt]=useState(0),[state,setState]=useState(JOINING),inflight=useRef(null);useEffect(()=>{let join=controller?.joinConsult;if(controller===null||join===void 0){setState(/* @__PURE__ */Object.freeze({status:"refused",refusal:"unavailable",reason:null}));return}let key=`${consultId}#${String(attempt)}`,entry=inflight.current;if(entry===null||entry.key!==key){let promise;try{promise=join.call(controller,consultId)}catch(cause){promise=Promise.reject(cause)}entry={key:key,promise:promise},inflight.current=entry}let live=true;return setState(JOINING),entry.promise.then(res=>{live&&(res.ok?setState(/* @__PURE__ */Object.freeze({status:"ready",credential:res.value})):setState(/* @__PURE__ */Object.freeze({status:"refused",refusal:vetCallJoinRefusal(res.error),reason:vetCallJoinReason(res.error)})))},()=>{live&&setState(/* @__PURE__ */Object.freeze({status:"refused",refusal:"unknown",reason:null}))}),()=>{live=false}},[consultId,controller,attempt]);let retry=useCallback(()=>setAttempt(n=>n+1),[]);return{state:state,retry:retry}}var SLOT2=/* @__PURE__ */Symbol.for("@everfur/sdk/televet/recording-notice-receipt");function receipts(){let realm=globalThis;return realm[SLOT2]??=/* @__PURE__ */new Map}function markRecordingNoticeAccepted(roomUrl){let rooms=receipts();rooms.set(roomUrl,(rooms.get(roomUrl)??0)+1)}function clearRecordingNoticeAccepted(roomUrl){let rooms=receipts(),count=rooms.get(roomUrl)??0;count<=1?rooms.delete(roomUrl):rooms.set(roomUrl,count-1)}var TelevetModalLayoutContext=createContext(null);function useTelevetModalFullBleed(fullBleed){let layout=useContext(TelevetModalLayoutContext);useEffect(()=>{if(!(layout===null||!fullBleed))return layout.setFullBleed(true),()=>{layout.setFullBleed(false)}},[layout,fullBleed])}var loadCall=memoizeTelevetLoader(()=>import("@everfur/sdk/televet/call"));function TelevetJoinScreen({consultId:consultId,...screen}){let styles2=useBookingStyles(),canHostCall=useCanHostCall();return canHostCall===null?/* @__PURE__ */jsx(View,{style:[styles2.screen,screen.style],testID:"televet-join-checking"}):/* @__PURE__ */jsx(TelevetJoinGate,{consultId:consultId,...screen,canHostCall:canHostCall},consultId)}function TelevetJoinGate({canHostCall:canHostCall,onLeave:onLeave,style:style,...room}){let[accepted,setAccepted]=useState(false);useJoinBackPress(()=>(onLeave(),true),!accepted);let leaveRoom=useCallback(()=>{setAccepted(false),onLeave()},[onLeave]);return canHostCall?accepted?/* @__PURE__ */jsx(TelevetJoinRoom,{...room,onLeave:leaveRoom,style:style}):/* @__PURE__ */jsx(TelevetRecordingNotice,{onContinue:()=>setAccepted(true),onLeave:onLeave,style:style}):/* @__PURE__ */jsx(TelevetJoinUnavailable,{onLeave:onLeave,style:style})}function TelevetJoinRoom({consultId:consultId,controller:injected,clinicianName:clinicianName,petName:petName,onLeave:onLeave,style:style}){let styles2=useBookingStyles(),controller=useTelevetBookingController(injected),{state:state,retry:retry}=useTelevetJoin(consultId,controller),[call,setCall]=useState(null),[callFailed,setCallFailed]=useState(false),ready=state.status==="ready";useEffect(()=>{if(!ready||call!==null)return;let live=true;return loadCall().then(loaded=>{live&&setCall(()=>loaded)},()=>{live&&setCallFailed(true)}),()=>{live=false}},[ready,call]);let roomUrl=state.status==="ready"?state.credential.roomUrl:null,[receiptFor,setReceiptFor]=useState(null);useEffect(()=>{if(roomUrl!==null)return markRecordingNoticeAccepted(roomUrl),setReceiptFor(roomUrl),()=>{clearRecordingNoticeAccepted(roomUrl)}},[roomUrl]);let inCall=ready&&call!==null&&!callFailed;useJoinBackPress(()=>(inCall||onLeave(),true),true);let credential=state.status==="ready"?state.credential:null;if(useTelevetModalFullBleed(inCall&&credential!==null&&call.isUsableRoomCredential(credential.roomUrl,credential.token)&&call.loadEverfurDaily().available),state.status==="refused"||callFailed){let refusal=state.status==="refused"?state.refusal:"unavailable";/* @__PURE__ */
294
+ /* @__PURE__ */jsx(TelevetButton,{label:TELEVET_VISITS_COPY_NATIVE.cancelKeepCta,kind:"secondary",disabled:cancel.isPending,onPress:()=>{setConfirming(false),setCancelFailed(false)},testID:"televet-consult-cancel-keep"})]}):/* @__PURE__ */jsx(TelevetButton,{label:TELEVET_VISITS_COPY_NATIVE.cancelCta,kind:"secondary",disabled:!terms,onPress:()=>{setCancelFailed(false),setConfirming(true)},testID:"televet-consult-cancel"})]}):null,read.isError&&!notFound?/* @__PURE__ */jsx(TelevetStateCard,{title:TELEVET_VISITS_COPY_NATIVE.staleTitle,actionLabel:TELEVET_VISITS_COPY_NATIVE.staleRetry,onAction:()=>read.refetch(),testID:"televet-consult-stale"}):null]})]})}var VET_CALL_COPY=/* @__PURE__ */Object.freeze({muteCta:"Mute",unmuteCta:"Unmute",cameraOffCta:"Camera off",cameraOnCta:"Camera on",leaveCta:"Leave",switchCameraCta:"Switch camera",speakerOffCta:"Speaker off",speakerOnCta:"Speaker on",lobbyTitleNoName:"Your vet is joining",lobbySubtitle:"",lobbyPrepLabel:"While you wait",lobbyPrepNoPet:"Have your pet nearby and somewhere well lit.",lobbyTitle:clinicianName=>{let name=clinicianName?.trim()??"";return name.length>0?`${name} is joining`:VET_CALL_COPY.lobbyTitleNoName},lobbyPrep:petName=>{let pet=petName?.trim()??"";return pet.length>0?`Have ${pet} nearby and somewhere well lit.`:VET_CALL_COPY.lobbyPrepNoPet},lobbyDuration:minutes=>`${minutes} minutes`,waitingRoomLabel:"Waiting room",leaveWaitingRoomLabel:"Leave the waiting room",lobbyTipsTitle:clinicianName=>{let name=clinicianName?.trim()??"";return name.length>0?`Before ${name} joins`:VET_CALL_COPY.lobbyPrepLabel},lobbyTipSpot:"Find a bright, quiet spot.",joinFailedReason:"That did not open. Try again.",recordingNoticeTitle:"This consultation is recorded.",recordingNoticeCta:"Continue to the call",recordingNoticeDecline:"Not now",selfCameraOffLabel:"Your camera is off"});function televetJoinRefusalNativeCopy(refusal){switch(refusal){case"too_early":return"You can join closer to the time.";case"too_late":return"This visit has ended.";case"room_not_ready":return"The room is still being set up. Try again in a moment.";case"not_joinable":return"This visit is no longer open.";case"unavailable":return"No way to join this visit yet.";default:return"That did not open. Try again."}}var TELEVET_JOIN_UNAVAILABLE_NATIVE="No way to join this visit yet.";function televetJoinIsRetryable(refusal){return refusal==="room_not_ready"||refusal==="unknown"}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 isEverfurDailyRegistered(){return televetGlobal().dailyRegistered}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}var JOINING=/* @__PURE__ */Object.freeze({status:"joining"});function useTelevetJoin(consultId,controller){let[attempt,setAttempt]=useState(0),[state,setState]=useState(JOINING),inflight=useRef(null);useEffect(()=>{let join=controller?.joinConsult;if(controller===null||join===void 0){setState(/* @__PURE__ */Object.freeze({status:"refused",refusal:"unavailable",reason:null}));return}let key=`${consultId}#${String(attempt)}`,entry=inflight.current;if(entry===null||entry.key!==key){let promise;try{promise=join.call(controller,consultId)}catch(cause){promise=Promise.reject(cause)}entry={key:key,promise:promise},inflight.current=entry}let live=true;return setState(JOINING),entry.promise.then(res=>{live&&(res.ok?setState(/* @__PURE__ */Object.freeze({status:"ready",credential:res.value})):setState(/* @__PURE__ */Object.freeze({status:"refused",refusal:vetCallJoinRefusal(res.error),reason:vetCallJoinReason(res.error)})))},()=>{live&&setState(/* @__PURE__ */Object.freeze({status:"refused",refusal:"unknown",reason:null}))}),()=>{live=false}},[consultId,controller,attempt]);let retry=useCallback(()=>setAttempt(n=>n+1),[]);return{state:state,retry:retry}}var SLOT2=/* @__PURE__ */Symbol.for("@everfur/sdk/televet/recording-notice-receipt");function receipts(){let realm=globalThis;return realm[SLOT2]??=/* @__PURE__ */new Map}function markRecordingNoticeAccepted(roomUrl){let rooms=receipts();rooms.set(roomUrl,(rooms.get(roomUrl)??0)+1)}function clearRecordingNoticeAccepted(roomUrl){let rooms=receipts(),count=rooms.get(roomUrl)??0;count<=1?rooms.delete(roomUrl):rooms.set(roomUrl,count-1)}var TelevetModalLayoutContext=createContext(null);function useTelevetModalFullBleed(fullBleed){let layout=useContext(TelevetModalLayoutContext);useEffect(()=>{if(!(layout===null||!fullBleed))return layout.setFullBleed(true),()=>{layout.setFullBleed(false)}},[layout,fullBleed])}var loadCall=memoizeTelevetLoader(()=>Promise.resolve(callModule));function TelevetJoinScreen({consultId:consultId,...screen}){let styles2=useBookingStyles(),canHostCall=useCanHostCall();return canHostCall===null?/* @__PURE__ */jsx(View,{style:[styles2.screen,screen.style],testID:"televet-join-checking"}):/* @__PURE__ */jsx(TelevetJoinGate,{consultId:consultId,...screen,canHostCall:canHostCall},consultId)}function TelevetJoinGate({canHostCall:canHostCall,onLeave:onLeave,style:style,...room}){let[accepted,setAccepted]=useState(false);useJoinBackPress(()=>(onLeave(),true),!accepted);let leaveRoom=useCallback(()=>{setAccepted(false),onLeave()},[onLeave]);return canHostCall?accepted?/* @__PURE__ */jsx(TelevetJoinRoom,{...room,onLeave:leaveRoom,style:style}):/* @__PURE__ */jsx(TelevetRecordingNotice,{onContinue:()=>setAccepted(true),onLeave:onLeave,style:style}):/* @__PURE__ */jsx(TelevetJoinUnavailable,{onLeave:onLeave,style:style})}function TelevetJoinRoom({consultId:consultId,controller:injected,clinicianName:clinicianName,petName:petName,onLeave:onLeave,style:style}){let styles2=useBookingStyles(),controller=useTelevetBookingController(injected),{state:state,retry:retry}=useTelevetJoin(consultId,controller),[call,setCall]=useState(null),[callFailed,setCallFailed]=useState(false),ready=state.status==="ready";useEffect(()=>{if(!ready||call!==null)return;let live=true;return loadCall().then(loaded=>{live&&setCall(()=>loaded)},()=>{live&&setCallFailed(true)}),()=>{live=false}},[ready,call]);let roomUrl=state.status==="ready"?state.credential.roomUrl:null,[receiptFor,setReceiptFor]=useState(null);useEffect(()=>{if(roomUrl!==null)return markRecordingNoticeAccepted(roomUrl),setReceiptFor(roomUrl),()=>{clearRecordingNoticeAccepted(roomUrl)}},[roomUrl]);let inCall=ready&&call!==null&&!callFailed;useJoinBackPress(()=>(inCall||onLeave(),true),true);let credential=state.status==="ready"?state.credential:null;if(useTelevetModalFullBleed(inCall&&credential!==null&&call.isUsableRoomCredential(credential.roomUrl,credential.token)&&call.loadEverfurDaily().available),state.status==="refused"||callFailed){let refusal=state.status==="refused"?state.refusal:"unavailable";/* @__PURE__ */
294
295
  return jsxs(View,{style:[styles2.screen,styles2.stepFill,style],testID:"televet-join-refused",children:[
295
296
  /* @__PURE__ */jsx(TelevetFailureLine,{message:televetJoinRefusalNativeCopy(refusal),testID:"televet-join-refused-message"}),televetJoinIsRetryable(refusal)&&state.status==="refused"?/* @__PURE__ */jsx(TelevetButton,{label:TELEVET_BOOKING_COPY.retryCta,kind:"primary",onPress:retry,testID:"televet-join-retry"}):null,
296
297
  /* @__PURE__ */jsx(TelevetButton,{label:VET_CALL_COPY.leaveCta,kind:"secondary",onPress:onLeave,testID:"televet-join-leave"})]})}if(state.status==="joining"||call===null||receiptFor!==state.credential.roomUrl)/* @__PURE__ */
@@ -1,4 +1,4 @@
1
- "use strict";var react=require("react"),reactNative=require("react-native"),reactNativeSafeAreaContext=require("react-native-safe-area-context"),jsxRuntime=require("react/jsx-runtime");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]]}}var noopTelemetry=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});function isSafeRoomUrl(url){try{return new URL(url.trim()).protocol==="https:"}catch{return false}}function isUsableRoomCredential(roomUrl,token){return isSafeRoomUrl(roomUrl)&&token.trim().length>0}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}var VET_CALL_CONSULT_MINUTES=10,VET_CALL_COPY=/* @__PURE__ */Object.freeze({muteCta:"Mute",unmuteCta:"Unmute",cameraOffCta:"Camera off",cameraOnCta:"Camera on",leaveCta:"Leave",switchCameraCta:"Switch camera",speakerOffCta:"Speaker off",speakerOnCta:"Speaker on",lobbyTitleNoName:"Your vet is joining",lobbySubtitle:"Usually under a minute",lobbyPrepLabel:"WHILE YOU WAIT",lobbyPrepNoPet:"Have your pet nearby and somewhere well lit.",lobbyTitle:clinicianName=>{let name=clinicianName?.trim()??"";return name.length>0?`${name} is joining`:VET_CALL_COPY.lobbyTitleNoName},lobbyPrep:petName=>{let pet=petName?.trim()??"";return pet.length>0?`Have ${pet} nearby and somewhere well lit.`:VET_CALL_COPY.lobbyPrepNoPet},lobbyDuration:minutes=>`${minutes} minutes`,waitingRoomLabel:"Waiting room",leaveWaitingRoomLabel:"Leave the waiting room",lobbyTipsTitle:clinicianName=>{let name=clinicianName?.trim()??"";return name.length>0?`Before ${name} joins`:VET_CALL_COPY.lobbyPrepLabel},lobbyTipSpot:"Find a bright, quiet spot.",joinFailedReason:"That did not open. Try again.",recordingNoticeTitle:"This consultation is recorded.",recordingNoticeCta:"Continue to the call",recordingNoticeDecline:"Not now",selfCameraOffLabel:"Your camera is off"});function formatElapsed(ms){let total=Math.max(0,Math.floor(ms/1e3)),seconds=String(total%60).padStart(2,"0"),minutes=Math.floor(total%3600/60),hours=Math.floor(total/3600);return hours>0?`${hours}:${String(minutes).padStart(2,"0")}:${seconds}`:`${minutes}:${seconds}`}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"};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]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});function optionalModule(name,load,validate){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`):validate&&!validate(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__ */
1
+ "use strict";var react=require("react"),reactNative=require("react-native"),reactNativeSafeAreaContext=require("react-native-safe-area-context"),jsxRuntime=require("react/jsx-runtime");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]]}}var noopTelemetry=/* @__PURE__ */Object.freeze({track(){},trackExpectedFailure(){}});function isSafeRoomUrl(url){try{return new URL(url.trim()).protocol==="https:"}catch{return false}}function isUsableRoomCredential(roomUrl,token){return isSafeRoomUrl(roomUrl)&&token.trim().length>0}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}var VET_CALL_CONSULT_MINUTES=10,VET_CALL_COPY=/* @__PURE__ */Object.freeze({muteCta:"Mute",unmuteCta:"Unmute",cameraOffCta:"Camera off",cameraOnCta:"Camera on",leaveCta:"Leave",switchCameraCta:"Switch camera",speakerOffCta:"Speaker off",speakerOnCta:"Speaker on",lobbyTitleNoName:"Your vet is joining",lobbySubtitle:"",lobbyPrepLabel:"While you wait",lobbyPrepNoPet:"Have your pet nearby and somewhere well lit.",lobbyTitle:clinicianName=>{let name=clinicianName?.trim()??"";return name.length>0?`${name} is joining`:VET_CALL_COPY.lobbyTitleNoName},lobbyPrep:petName=>{let pet=petName?.trim()??"";return pet.length>0?`Have ${pet} nearby and somewhere well lit.`:VET_CALL_COPY.lobbyPrepNoPet},lobbyDuration:minutes=>`${minutes} minutes`,waitingRoomLabel:"Waiting room",leaveWaitingRoomLabel:"Leave the waiting room",lobbyTipsTitle:clinicianName=>{let name=clinicianName?.trim()??"";return name.length>0?`Before ${name} joins`:VET_CALL_COPY.lobbyPrepLabel},lobbyTipSpot:"Find a bright, quiet spot.",joinFailedReason:"That did not open. Try again.",recordingNoticeTitle:"This consultation is recorded.",recordingNoticeCta:"Continue to the call",recordingNoticeDecline:"Not now",selfCameraOffLabel:"Your camera is off"});function formatElapsed(ms){let total=Math.max(0,Math.floor(ms/1e3)),seconds=String(total%60).padStart(2,"0"),minutes=Math.floor(total%3600/60),hours=Math.floor(total/3600);return hours>0?`${hours}:${String(minutes).padStart(2,"0")}:${seconds}`:`${minutes}:${seconds}`}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"};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]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});function optionalModule(name,load,validate){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`):validate&&!validate(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__ */
2
2
  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=/* @__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 markEverfurDailyRegistered(registered){televetGlobal().dailyRegistered=registered}var EVERFUR_DAILY_SETUP=`[everfur] The in-app vet call needs the Daily native modules, which this app has not registered. Install @daily-co/react-native-daily-js, @daily-co/react-native-webrtc and (Expo) @daily-co/config-plugin-rn-daily-js, rebuild the native app (a JS-only OTA cannot add a native module), and call registerEverfurDaily(() => require('@daily-co/react-native-daily-js')) once in your app entry. ON EXPO GO THIS CANNOT BE FIXED BY INSTALLING: Expo Go runs a fixed set of native modules and cannot load Daily at any version, so you need a development build (expo prebuild, then run the native app) before the in-app call works at all. Until then the in-app visit tells the member the call cannot be joined; <VetVisitButton prefer="redirect" /> is the explicit way to the hosted visit in the browser, which needs no native module.`,DAILY_PEER="@daily-co/react-native-daily-js",NOT_REGISTERED=`optional peer '${DAILY_PEER}' has no registered loader`,WRONG_SHAPE=`optional peer '${DAILY_PEER}' is present but failed its shape check`;function isRecordLike(candidate){return typeof candidate=="object"&&candidate!==null}function isDailyBox(candidate){return isRecordLike(candidate)&&"box"in candidate}function normalizeDailyModule(candidate){let inner=candidate.default,fallback=isRecordLike(inner)||typeof inner=="function"?inner:{},owner=typeof candidate.createCallObject=="function"?candidate:fallback,factory=owner.createCallObject,merged={createCallObject:typeof factory=="function"?factory.bind(owner):factory,DailyMediaView:candidate.DailyMediaView??fallback.DailyMediaView};return isEverfurDailyModule(merged)?merged:null}function isEverfurDailyModule(candidate){if(!isRecordLike(candidate)||typeof candidate.createCallObject!="function")return false;let view=candidate.DailyMediaView;return typeof view=="function"||typeof view=="object"&&view!==null}var loader=null,memo=null;function unavailable(reason){/* @__PURE__ */
3
3
  return Object.freeze({available:false,module:null,reason:reason})}function registerEverfurDaily(next){loader=next,memo=null,markEverfurDailyRegistered(next!==null)}function loadEverfurDaily(){if(memo!==null)return memo;let load=loader;if(load===null)return memo=unavailable(NOT_REGISTERED),memo;let raw=optionalModule(DAILY_PEER,()=>({box:load()}),isDailyBox);if(!raw.available)return memo=unavailable(raw.reason),memo;let inner=raw.module.box;if(!isRecordLike(inner))return memo=unavailable(WRONG_SHAPE),memo;let normalized=normalizeDailyModule(inner);return memo=normalized===null?unavailable(WRONG_SHAPE):/* @__PURE__ */Object.freeze({available:true,module:normalized}),memo}function CallControl({label:label,glyph:glyph,onPress:onPress,testID:testID,muted:muted=false,style:style}){/* @__PURE__ */
4
4
  return jsxRuntime.jsx(reactNative.Pressable,{onPress:onPress,testID:testID,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:muted},style:style,children:glyph})}function GlyphBox({children:children,testID:testID}){/* @__PURE__ */
@@ -34,9 +34,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,{paddingTop:insets.t
34
34
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.avatar,{width:avatarSize,height:avatarSize,borderRadius:avatarSize/2}],testID:"everfur-vet-lobby-avatar",accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
35
35
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.avatarGlyphHead}),
36
36
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.avatarGlyphBody})]}),
37
- /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{accessibilityLiveRegion:"polite",accessible:true,children:[
38
- /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"heading",style:styles.title,testID:"everfur-vet-lobby-title",children:VET_CALL_COPY.lobbyTitle(clinicianName)}),
39
- /* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.subtitle,testID:"everfur-vet-lobby-subtitle",children:VET_CALL_COPY.lobbySubtitle})]}),
37
+ /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityLiveRegion:"polite",accessible:true,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"heading",style:styles.title,testID:"everfur-vet-lobby-title",children:VET_CALL_COPY.lobbyTitle(clinicianName)})}),
40
38
  /* @__PURE__ */jsxRuntime.jsx(WaitingDots,{reducedMotion:theme.motion.reducedMotion,styles:styles})]}),
41
39
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.prepCard,testID:"everfur-vet-lobby-prep",children:[
42
40
  /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.prepLabel,children:VET_CALL_COPY.lobbyTipsTitle(clinicianName)}),[VET_CALL_COPY.lobbyTipSpot,VET_CALL_COPY.lobbyPrep(petName)].map((tip,i)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.tip,children:[
@@ -45,7 +43,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,{paddingTop:insets.t
45
43
  /* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.controls,children:[
46
44
  /* @__PURE__ */jsxRuntime.jsx(LobbyControl,{label:micOn?VET_CALL_COPY.muteCta:VET_CALL_COPY.unmuteCta,glyph:/* @__PURE__ */jsxRuntime.jsx(MicGlyph,{color:theme.color.text.onBrand,off:!micOn}),active:micOn,onPress:onToggleMic,testID:"everfur-vet-lobby-mic",styles:styles}),
47
45
  /* @__PURE__ */jsxRuntime.jsx(LobbyControl,{label:cameraOn?VET_CALL_COPY.cameraOffCta:VET_CALL_COPY.cameraOnCta,glyph:/* @__PURE__ */jsxRuntime.jsx(CameraGlyph,{color:theme.color.text.onBrand,off:!cameraOn}),active:cameraOn,onPress:onToggleCamera,testID:"everfur-vet-lobby-camera",styles:styles}),cameraOn&&onSwitchCamera?/* @__PURE__ */jsxRuntime.jsx(LobbyControl,{label:VET_CALL_COPY.switchCameraCta,glyph:/* @__PURE__ */jsxRuntime.jsx(SwitchCameraGlyph,{color:theme.color.text.onBrand}),active:true,onPress:onSwitchCamera,testID:"everfur-vet-lobby-switch-camera",styles:styles}):null]}),
48
- /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.duration,testID:"everfur-vet-lobby-duration",children:VET_CALL_COPY.lobbyDuration(soldMinutes(consultMinutes))})]})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return reactNative.StyleSheet.create({root:{flex:1,backgroundColor:color.brand,paddingHorizontal:space.lg},topRow:{flexDirection:"row",alignItems:"center",gap:space.md},tip:{flexDirection:"row",gap:space.md,alignItems:"flex-start",paddingTop:space.sm},tipNumber:{...face(theme,"monoBold"),color:ON_BRAND.textSecondary,fontSize:13,width:24,paddingTop:4},leaveHit:{minHeight:MIN_TOUCH_TARGET,justifyContent:"center",paddingVertical:space.xs,paddingRight:space.md},leaveLabel:{...face(theme,"medium"),color:color.text.onBrand,fontSize:type.size.body},center:{flex:1,alignItems:"center",justifyContent:"center"},avatar:{alignItems:"center",justifyContent:"center",borderWidth:2,borderColor:color.success,backgroundColor:ON_BRAND.surface,marginBottom:space.lg,overflow:"hidden"},avatarGlyphHead:{width:34,height:34,borderRadius:17,borderWidth:2,borderColor:ON_BRAND.glyph,marginBottom:6},avatarGlyphBody:{width:66,height:33,borderTopLeftRadius:33,borderTopRightRadius:33,borderWidth:2,borderBottomWidth:0,borderColor:ON_BRAND.glyph},title:{...face(theme,"bold"),color:color.text.onBrand,fontSize:type.size.heading,lineHeight:Math.round(type.size.heading*type.lineHeight.snug),textAlign:"center",paddingHorizontal:space.sm},subtitle:{...face(theme,"regular"),color:ON_BRAND.textSecondary,fontSize:type.size.body,textAlign:"center",marginTop:space.xs},dotRow:{flexDirection:"row",gap:space.xs,marginTop:space.lg},dot:{width:8,height:8,borderRadius:4,backgroundColor:color.success},prepCard:{borderRadius:radius.lg,borderWidth:1,borderColor:ON_BRAND.hairline,backgroundColor:ON_BRAND.surface,padding:space.lg,marginBottom:space.lg},prepLabel:{...face(theme,"monoBold"),color:color.accent,fontSize:type.size.micro,letterSpacing:1.2,textTransform:"uppercase"},prepBody:{...face(theme,"regular"),color:color.text.onBrand,fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.relaxed)},controls:{flexDirection:"row",justifyContent:"center",gap:space.lg,marginBottom:space.lg},control:{minWidth:64,minHeight:48,paddingHorizontal:space.md,alignItems:"center",justifyContent:"center",borderRadius:radius.pill,backgroundColor:ON_BRAND.surfaceRaised},controlOff:{backgroundColor:ON_BRAND.surfaceActive},duration:{...face(theme,"medium"),color:ON_BRAND.textTertiary,fontSize:type.size.micro,letterSpacing:1.6,textAlign:"center"}})}var LEAVE_SETTLE_MS=5e3;function settleWithin(work,ms){return new Promise(resolve=>{let timer=setTimeout(resolve,ms);work.catch(()=>{}).then(()=>{clearTimeout(timer),resolve()})})}function useLeaveOnce(onLeave,teardown){let onLeaveRef=react.useRef(onLeave);react.useEffect(()=>{onLeaveRef.current=onLeave});let liveRef=react.useRef(false);react.useEffect(()=>(liveRef.current=true,()=>{liveRef.current=false}),[]);let reportedRef=react.useRef(false),reportLeft=react.useCallback(()=>{reportedRef.current||!liveRef.current||(reportedRef.current=true,onLeaveRef.current())},[]),leavingRef=react.useRef(false),leave=react.useCallback(()=>{leavingRef.current||(leavingRef.current=true,settleWithin(teardown(),LEAVE_SETTLE_MS).then(reportLeft))},[teardown,reportLeft]);return{reportLeft:reportLeft,leave:leave,leaving:leavingRef}}var SLOT2=/* @__PURE__ */Symbol.for("@everfur/sdk/televet/recording-notice-receipt");function receipts(){let realm=globalThis;return realm[SLOT2]??=/* @__PURE__ */new Map}function hasRecordingNoticeAccepted(roomUrl){return(receipts().get(roomUrl)??0)>0}function useSpeakerRoute(callRef){let[speakerOn,setSpeakerOn]=react.useState(true),route=react.useRef(true),toggleSpeaker=react.useCallback(()=>{let call=callRef.current;if(!call?.setNativeInCallAudioMode)return;let next=!route.current;route.current=next,setSpeakerOn(next),call.setNativeInCallAudioMode(next?"video":"voice")},[callRef]);return{speakerOn:speakerOn,toggleSpeaker:toggleSpeaker}}function asTrack(track){return track??null}function hasVideo(participant){return!!participant?.videoTrack}function PersonMark({styles:styles}){/* @__PURE__ */
46
+ /* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.duration,testID:"everfur-vet-lobby-duration",children:VET_CALL_COPY.lobbyDuration(soldMinutes(consultMinutes))})]})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return reactNative.StyleSheet.create({root:{flex:1,backgroundColor:color.brand,paddingHorizontal:space.lg},topRow:{flexDirection:"row",alignItems:"center",gap:space.md},tip:{flexDirection:"row",gap:space.md,alignItems:"flex-start",paddingTop:space.sm},tipNumber:{...face(theme,"monoBold"),color:ON_BRAND.textSecondary,fontSize:13,width:24,paddingTop:4},leaveHit:{minHeight:MIN_TOUCH_TARGET,justifyContent:"center",paddingVertical:space.xs,paddingRight:space.md},leaveLabel:{...face(theme,"medium"),color:color.text.onBrand,fontSize:type.size.body},center:{flex:1,alignItems:"center",justifyContent:"center"},avatar:{alignItems:"center",justifyContent:"center",borderWidth:2,borderColor:color.success,backgroundColor:ON_BRAND.surface,marginBottom:space.lg,overflow:"hidden"},avatarGlyphHead:{width:34,height:34,borderRadius:17,borderWidth:2,borderColor:ON_BRAND.glyph,marginBottom:6},avatarGlyphBody:{width:66,height:33,borderTopLeftRadius:33,borderTopRightRadius:33,borderWidth:2,borderBottomWidth:0,borderColor:ON_BRAND.glyph},title:{...face(theme,"bold"),color:color.text.onBrand,fontSize:type.size.heading,lineHeight:Math.round(type.size.heading*type.lineHeight.snug),textAlign:"center",paddingHorizontal:space.sm},dotRow:{flexDirection:"row",gap:space.xs,marginTop:space.lg},dot:{width:8,height:8,borderRadius:4,backgroundColor:color.success},prepCard:{borderRadius:radius.lg,borderWidth:1,borderColor:ON_BRAND.hairline,backgroundColor:ON_BRAND.surface,padding:space.lg,marginBottom:space.lg},prepLabel:{...face(theme,"monoBold"),color:color.accent,fontSize:type.size.micro,letterSpacing:1.2,textTransform:"uppercase"},prepBody:{...face(theme,"regular"),color:color.text.onBrand,fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.relaxed)},controls:{flexDirection:"row",justifyContent:"center",gap:space.lg,marginBottom:space.lg},control:{minWidth:64,minHeight:48,paddingHorizontal:space.md,alignItems:"center",justifyContent:"center",borderRadius:radius.pill,backgroundColor:ON_BRAND.surfaceRaised},controlOff:{backgroundColor:ON_BRAND.surfaceActive},duration:{...face(theme,"medium"),color:ON_BRAND.textTertiary,fontSize:type.size.micro,letterSpacing:1.6,textAlign:"center"}})}var LEAVE_SETTLE_MS=5e3;function settleWithin(work,ms){return new Promise(resolve=>{let timer=setTimeout(resolve,ms);work.catch(()=>{}).then(()=>{clearTimeout(timer),resolve()})})}function useLeaveOnce(onLeave,teardown){let onLeaveRef=react.useRef(onLeave);react.useEffect(()=>{onLeaveRef.current=onLeave});let liveRef=react.useRef(false);react.useEffect(()=>(liveRef.current=true,()=>{liveRef.current=false}),[]);let reportedRef=react.useRef(false),reportLeft=react.useCallback(()=>{reportedRef.current||!liveRef.current||(reportedRef.current=true,onLeaveRef.current())},[]),leavingRef=react.useRef(false),leave=react.useCallback(()=>{leavingRef.current||(leavingRef.current=true,settleWithin(teardown(),LEAVE_SETTLE_MS).then(reportLeft))},[teardown,reportLeft]);return{reportLeft:reportLeft,leave:leave,leaving:leavingRef}}var SLOT2=/* @__PURE__ */Symbol.for("@everfur/sdk/televet/recording-notice-receipt");function receipts(){let realm=globalThis;return realm[SLOT2]??=/* @__PURE__ */new Map}function hasRecordingNoticeAccepted(roomUrl){return(receipts().get(roomUrl)??0)>0}function useSpeakerRoute(callRef){let[speakerOn,setSpeakerOn]=react.useState(true),route=react.useRef(true),toggleSpeaker=react.useCallback(()=>{let call=callRef.current;if(!call?.setNativeInCallAudioMode)return;let next=!route.current;route.current=next,setSpeakerOn(next),call.setNativeInCallAudioMode(next?"video":"voice")},[callRef]);return{speakerOn:speakerOn,toggleSpeaker:toggleSpeaker}}function asTrack(track){return track??null}function hasVideo(participant){return!!participant?.videoTrack}function PersonMark({styles:styles}){/* @__PURE__ */
49
47
  return jsxRuntime.jsxs(reactNative.View,{style:styles.remoteOffAvatar,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
50
48
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.remoteOffHead}),
51
49
  /* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.remoteOffBody})]})}function EverfurVetCall(props){/* @__PURE__ */
@@ -2,9 +2,9 @@ import { ComponentType, ReactNode } from 'react';
2
2
  import { StyleProp, ViewStyle } from 'react-native';
3
3
  import { T as TelemetryPort } from '../../TelemetryPort-BDNr00hu.cjs';
4
4
  import { O as OptionalModule } from '../../optionalModule-DbJmsq5f.cjs';
5
- export { V as VetCallPhase, i as isSafeRoomUrl, a as isUsableRoomCredential } from '../../callRoom-DfZTWFXh.cjs';
6
- export { V as VET_CALL_CONSULT_MINUTES, a as VET_CALL_COPY } from '../../callCopy-DHjem0R-.cjs';
7
- import '../../EverfurError-pEXDbUJ1.cjs';
5
+ export { V as VetCallPhase, i as isSafeRoomUrl, a as isUsableRoomCredential } from '../../callRoom-BhIdadyV.cjs';
6
+ export { V as VET_CALL_CONSULT_MINUTES, a as VET_CALL_COPY } from '../../callCopy-Bw6oZT54.cjs';
7
+ import '../../EverfurError-DeBqRpQV.cjs';
8
8
 
9
9
  /**
10
10
  * A participant's media track. Daily types this `MediaStreamTrack | false | null`: `false` means the track
@@ -2,9 +2,9 @@ import { ComponentType, ReactNode } from 'react';
2
2
  import { StyleProp, ViewStyle } from 'react-native';
3
3
  import { T as TelemetryPort } from '../../TelemetryPort-BDNr00hu.js';
4
4
  import { O as OptionalModule } from '../../optionalModule-DbJmsq5f.js';
5
- export { V as VetCallPhase, i as isSafeRoomUrl, a as isUsableRoomCredential } from '../../callRoom-B1qq_D-4.js';
6
- export { V as VET_CALL_CONSULT_MINUTES, a as VET_CALL_COPY } from '../../callCopy-DHjem0R-.js';
7
- import '../../EverfurError-pEXDbUJ1.js';
5
+ export { V as VetCallPhase, i as isSafeRoomUrl, a as isUsableRoomCredential } from '../../callRoom-B92eH_ij.js';
6
+ export { V as VET_CALL_CONSULT_MINUTES, a as VET_CALL_COPY } from '../../callCopy-Bw6oZT54.js';
7
+ import '../../EverfurError-DeBqRpQV.js';
8
8
 
9
9
  /**
10
10
  * A participant's media track. Daily types this `MediaStreamTrack | false | null`: `false` means the track