@everfur/sdk 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +11 -10
  3. package/dist/{Chat.d-Dts8u_1a.d.cts → Chat.d-aycmX1CA.d.cts} +12 -4
  4. package/dist/{Chat.d-DUNTfzqC.d.ts → Chat.d-puminpyi.d.ts} +12 -4
  5. package/dist/{DepthViews.d-CubkMPbU.d.ts → DepthViews.d-BdvFZgPs.d.cts} +1 -1
  6. package/dist/{DepthViews.d-Ce2Zhnrb.d.ts → DepthViews.d-DIvxzLDf.d.ts} +1 -1
  7. package/dist/{DepthViews.d-BMU2jFPw.d.cts → DepthViews.d-Dy0Zl-s-.d.ts} +1 -1
  8. package/dist/{DepthViews.d-BIp599lz.d.cts → DepthViews.d-wLNkzk9f.d.cts} +1 -1
  9. package/dist/RecordsPage.d-9Ank15PT.d.ts +93 -0
  10. package/dist/RecordsPage.d-DMKU0IKc.d.cts +93 -0
  11. package/dist/animations/index.d.cts +5 -5
  12. package/dist/animations/index.d.ts +5 -5
  13. package/dist/{attachments.d-D1yhJjcZ.d.ts → attachments.d--sIsfk6e.d.ts} +2 -2
  14. package/dist/{attachments.d-Bp2qbHxn.d.cts → attachments.d-DNUCiyy5.d.cts} +6 -24
  15. package/dist/{attachments.d-DisnvB9R.d.cts → attachments.d-ZEpTUeWN.d.cts} +2 -2
  16. package/dist/{attachments.d-Djy9z_0Z.d.ts → attachments.d-rp3xs-Q3.d.ts} +6 -24
  17. package/dist/{bookingCopy.d-BJF6gd1A.d.ts → bookingCopy.d-D0uIIFAJ.d.ts} +2 -2
  18. package/dist/{bookingCopy.d-BlBmhAJc.d.cts → bookingCopy.d-DUrmVcLs.d.cts} +2 -2
  19. package/dist/{branding.d-DI8S400y.d.cts → branding.d-CTXTUg_8.d.cts} +1 -1
  20. package/dist/{branding.d-OIGLbQeM.d.ts → branding.d-DxJSoFce.d.ts} +1 -1
  21. package/dist/{casesRepository.d-CT2LTicS.d.cts → casesRepository.d-DCnix2pT.d.cts} +1 -1
  22. package/dist/{casesRepository.d-UsWOz9bv.d.ts → casesRepository.d-DbirgbyH.d.ts} +1 -1
  23. package/dist/chat/index.cjs +43 -41
  24. package/dist/chat/index.d.cts +26 -13
  25. package/dist/chat/index.d.ts +26 -13
  26. package/dist/chat/index.js +43 -41
  27. package/dist/client/index.cjs +2 -2
  28. package/dist/client/index.d.cts +10 -10
  29. package/dist/client/index.d.ts +10 -10
  30. package/dist/client/index.js +2 -2
  31. package/dist/clinicBatch.d-Ccmrngcu.d.cts +71 -0
  32. package/dist/clinicBatch.d-D9Ci7IpP.d.ts +71 -0
  33. package/dist/clinicModels.d-BXgKZqDb.d.cts +68 -0
  34. package/dist/clinicModels.d-CaS64-P-.d.ts +68 -0
  35. package/dist/clinicRequestProps.d-1dCtouGA.d.cts +65 -0
  36. package/dist/clinicRequestProps.d-CjsMg_OD.d.ts +65 -0
  37. package/dist/{config.d-BR3DT9ho.d.cts → config.d-DJ4mvf_w.d.cts} +1 -1
  38. package/dist/{config.d-Dy6igYlH.d.ts → config.d-MX7IKP2f.d.ts} +1 -1
  39. package/dist/consent/index.d.cts +5 -5
  40. package/dist/consent/index.d.ts +5 -5
  41. package/dist/{context.d-QcCgguzA.d.ts → context.d-BdnBe8Oe.d.ts} +7 -7
  42. package/dist/{context.d-Cwks0p3C.d.cts → context.d-C6MJsMpN.d.cts} +7 -7
  43. package/dist/{copy.d-CiMn2IIt.d.ts → copy.d-BIfQOoDB.d.ts} +2 -2
  44. package/dist/{copy.d-DLJTyRfT.d.cts → copy.d-C_u7shha.d.cts} +2 -2
  45. package/dist/core/index.cjs +3 -3
  46. package/dist/core/index.d.cts +20 -18
  47. package/dist/core/index.d.ts +20 -18
  48. package/dist/core/index.js +3 -3
  49. package/dist/{depth.d-OSALbYM7.d.ts → depth.d-COFxYWLU.d.ts} +6 -133
  50. package/dist/{depth.d-CjPGVPDL.d.cts → depth.d-D2e5WZuE.d.cts} +6 -133
  51. package/dist/{entitlementRepository.d-CVQa1DA1.d.cts → entitlementRepository.d-BP15dFbe.d.cts} +4 -4
  52. package/dist/{entitlementRepository.d-Cf3LbTwD.d.ts → entitlementRepository.d-DLuxnGi5.d.ts} +4 -4
  53. package/dist/{features.d-fNsGcg0R.d.ts → features.d-DrQxTw3-.d.cts} +1 -1
  54. package/dist/{features.d-fNsGcg0R.d.cts → features.d-DrQxTw3-.d.ts} +1 -1
  55. package/dist/{focus.d-DMg2ngHI.d.ts → focus.d-C0Tr0oVJ.d.ts} +109 -348
  56. package/dist/{focus.d-az9cqUz3.d.cts → focus.d-jQWp0hdK.d.cts} +109 -348
  57. package/dist/health-plan/index.cjs +165 -151
  58. package/dist/health-plan/index.d.cts +53 -11
  59. package/dist/health-plan/index.d.ts +53 -11
  60. package/dist/health-plan/index.js +169 -155
  61. package/dist/{idempotency.d-D461_DPD.d.cts → idempotency.d-DXb1BN2A.d.ts} +151 -6
  62. package/dist/{idempotency.d-WpXx9zQo.d.ts → idempotency.d-HF6fyRt2.d.cts} +151 -6
  63. package/dist/{identity.d-DzTijonw.d.ts → identity.d-BePPZ7Uv.d.ts} +1 -1
  64. package/dist/{identity.d-60LeJt_s.d.cts → identity.d-CJfnWOdH.d.cts} +1 -1
  65. package/dist/index.cjs +46 -44
  66. package/dist/index.d.cts +19 -18
  67. package/dist/index.d.ts +19 -18
  68. package/dist/index.js +46 -44
  69. package/dist/introEvents.d-BkGDT_kG.d.cts +175 -0
  70. package/dist/introEvents.d-DHlMvmC7.d.ts +175 -0
  71. package/dist/introEvents.d-dS3fJCH1.d.cts +5 -0
  72. package/dist/introEvents.d-dS3fJCH1.d.ts +5 -0
  73. package/dist/{models.d-BnLm3VAA.d.cts → models.d-BSqvbTE1.d.cts} +8 -1
  74. package/dist/{models.d-BagXhafD.d.ts → models.d-DOwnr8fi.d.ts} +8 -1
  75. package/dist/notifications/index.d.cts +4 -4
  76. package/dist/notifications/index.d.ts +4 -4
  77. package/dist/{optInView.d-CEyHR6PK.d.cts → optInView.d-0iI5JoAf.d.cts} +119 -3
  78. package/dist/{optInView.d-acKpV8V2.d.ts → optInView.d-s-w4aGN3.d.ts} +119 -3
  79. package/dist/{parse.d-C8CXyS58.d.ts → parse.d-COt1qVA6.d.ts} +1 -1
  80. package/dist/{parse.d-tEzufgJX.d.cts → parse.d-EmsgOUMQ.d.cts} +1 -1
  81. package/dist/{pets.d-C_53_fzo.d.ts → pets.d-BFT_b53y.d.ts} +1 -1
  82. package/dist/{pets.d-NbJvP_kh.d.cts → pets.d-nNAVnw7f.d.cts} +1 -1
  83. package/dist/{petsRepository.d-lp1BHRqM.d.cts → petsRepository.d-B2TpRE7r.d.cts} +1 -1
  84. package/dist/{petsRepository.d-BuGHymNx.d.ts → petsRepository.d-RGwSZcYl.d.ts} +1 -1
  85. package/dist/planSignals.d-BDbp2e-k.d.cts +126 -0
  86. package/dist/planSignals.d-DSnxKoWe.d.ts +126 -0
  87. package/dist/{ports.d-COIyN624.d.ts → ports.d-D2n4HRUy.d.ts} +4 -4
  88. package/dist/{ports.d-CEROoqnA.d.cts → ports.d-DBA_gsq5.d.cts} +4 -4
  89. package/dist/{presentation.d-DMbdad7G.d.cts → presentation.d-vy8kTGfR.d.cts} +6 -0
  90. package/dist/{presentation.d-DMbdad7G.d.ts → presentation.d-vy8kTGfR.d.ts} +6 -0
  91. package/dist/quickPrompts.d-NM_81Jc1.d.cts +19 -0
  92. package/dist/quickPrompts.d-NM_81Jc1.d.ts +19 -0
  93. package/dist/records/depth/index.d.cts +13 -9
  94. package/dist/records/depth/index.d.ts +13 -9
  95. package/dist/records/index.cjs +252 -138
  96. package/dist/records/index.d.cts +88 -23
  97. package/dist/records/index.d.ts +88 -23
  98. package/dist/records/index.js +253 -139
  99. package/dist/{requestFunnel.d-CXUMPw1K.d.ts → requestFunnel.d-D9edIEjZ.d.ts} +2 -2
  100. package/dist/{requestFunnel.d-DWQQpjFR.d.cts → requestFunnel.d-RZex94XX.d.cts} +2 -2
  101. package/dist/{resolve.d-jI8FmBj3.d.cts → resolve.d-CoQWUy1Y.d.cts} +1 -1
  102. package/dist/{resolve.d-jI8FmBj3.d.ts → resolve.d-CoQWUy1Y.d.ts} +1 -1
  103. package/dist/{runtimeTypes.d-4yFNNuYR.d.ts → runtimeTypes.d-BYq38b17.d.ts} +6 -6
  104. package/dist/{runtimeTypes.d-D6N_fhxx.d.cts → runtimeTypes.d-LkwZaF7z.d.cts} +6 -6
  105. package/dist/{useRecordsDepth.d-DFcCfiXm.d.ts → screenProps.d-BVzRzowC.d.ts} +5 -91
  106. package/dist/{useRecordsDepth.d-sAq2Qkhr.d.cts → screenProps.d-CQ0qZJkr.d.cts} +5 -91
  107. package/dist/server/events/index.cjs +1 -1
  108. package/dist/server/events/index.d.cts +2 -2
  109. package/dist/server/events/index.d.ts +2 -2
  110. package/dist/server/events/index.js +1 -1
  111. package/dist/server/index.cjs +1 -1
  112. package/dist/server/index.d.cts +3 -3
  113. package/dist/server/index.d.ts +3 -3
  114. package/dist/server/index.js +1 -1
  115. package/dist/{sheetSeam.d-Cviqk89n.d.ts → sheetSeam.d-B09jf4YC.d.ts} +8 -4
  116. package/dist/{sheetSeam.d-DCS3LW8g.d.cts → sheetSeam.d-BBuEIVsa.d.cts} +8 -4
  117. package/dist/shop/index.cjs +224 -58
  118. package/dist/shop/index.d.cts +23 -5
  119. package/dist/shop/index.d.ts +23 -5
  120. package/dist/shop/index.js +225 -59
  121. package/dist/tabs/index.cjs +195 -0
  122. package/dist/tabs/index.d.cts +174 -0
  123. package/dist/tabs/index.d.ts +174 -0
  124. package/dist/tabs/index.js +195 -0
  125. package/dist/tabsModel.d-BfIQg6yS.d.cts +31 -0
  126. package/dist/tabsModel.d-BfIQg6yS.d.ts +31 -0
  127. package/dist/televet/booking/index.d.cts +6 -6
  128. package/dist/televet/booking/index.d.ts +6 -6
  129. package/dist/testing/index.cjs +1 -1
  130. package/dist/testing/index.d.cts +1 -1
  131. package/dist/testing/index.d.ts +1 -1
  132. package/dist/testing/index.js +1 -1
  133. package/dist/testing/rn/index.cjs +1 -1
  134. package/dist/testing/rn/index.d.cts +11 -11
  135. package/dist/testing/rn/index.d.ts +11 -11
  136. package/dist/testing/rn/index.js +1 -1
  137. package/dist/testing/web/index.d.cts +12 -12
  138. package/dist/testing/web/index.d.ts +12 -12
  139. package/dist/texting/index.cjs +40 -5
  140. package/dist/texting/index.d.cts +40 -7
  141. package/dist/texting/index.d.ts +40 -7
  142. package/dist/texting/index.js +40 -5
  143. package/dist/threadOptions.d-9r4Csa7k.d.cts +458 -0
  144. package/dist/threadOptions.d-B6GA09aM.d.ts +458 -0
  145. package/dist/{timelineRows.d-CU5GvvLk.d.ts → timelineRows.d-Bes8ip2v.d.ts} +1 -1
  146. package/dist/{timelineRows.d-BNxgzYRW.d.cts → timelineRows.d-BvM2A7_G.d.cts} +1 -1
  147. package/dist/{typeStyle.d-C1HBRAI3.d.ts → typeStyle.d-Co5KF0up.d.ts} +1 -1
  148. package/dist/{typeStyle.d-Bl8pzbBy.d.cts → typeStyle.d-xIZj02Ru.d.cts} +1 -1
  149. package/dist/useIntroSeen.d-CTWFUthO.d.cts +35 -0
  150. package/dist/useIntroSeen.d-CTWFUthO.d.ts +35 -0
  151. package/dist/usePresentation.d-BGz32Vlm.d.ts +285 -0
  152. package/dist/usePresentation.d-DYTF_ZGf.d.cts +285 -0
  153. package/dist/{useRecords.d-Cb-36SF5.d.cts → useRecords.d-BYNX01El.d.cts} +2 -2
  154. package/dist/{useRecords.d-aQTzQZoV.d.ts → useRecords.d-DWk61a4c.d.ts} +2 -2
  155. package/dist/useRecordsDepth.d--LLA_4ga.d.cts +32 -0
  156. package/dist/useRecordsDepth.d-BQRL0Hez.d.ts +32 -0
  157. package/dist/{view.d-Dps5C8-s.d.cts → view.d-0yBjLTV3.d.cts} +6 -4
  158. package/dist/{view.d-C-SNpDJX.d.ts → view.d-DqbCADFa.d.ts} +6 -4
  159. package/dist/web/consent/index.d.cts +5 -5
  160. package/dist/web/consent/index.d.ts +5 -5
  161. package/dist/web/health-plan/index.cjs +50 -43
  162. package/dist/web/health-plan/index.d.cts +46 -192
  163. package/dist/web/health-plan/index.d.ts +46 -192
  164. package/dist/web/health-plan/index.js +65 -58
  165. package/dist/web/index.cjs +61 -45
  166. package/dist/web/index.d.cts +165 -25
  167. package/dist/web/index.d.ts +165 -25
  168. package/dist/web/index.js +62 -46
  169. package/dist/web/intro/index.cjs +167 -0
  170. package/dist/web/intro/index.d.cts +79 -0
  171. package/dist/web/intro/index.d.ts +79 -0
  172. package/dist/web/intro/index.js +167 -0
  173. package/dist/web/notifications/index.d.cts +3 -3
  174. package/dist/web/notifications/index.d.ts +3 -3
  175. package/dist/web/records/depth/index.d.cts +13 -9
  176. package/dist/web/records/depth/index.d.ts +13 -9
  177. package/dist/web/records/index.cjs +7 -7
  178. package/dist/web/records/index.d.cts +21 -82
  179. package/dist/web/records/index.d.ts +21 -82
  180. package/dist/web/records/index.js +7 -7
  181. package/dist/web/records-sheet/index.cjs +181 -127
  182. package/dist/web/records-sheet/index.d.cts +18 -16
  183. package/dist/web/records-sheet/index.d.ts +18 -16
  184. package/dist/web/records-sheet/index.js +181 -127
  185. package/dist/web/shop/index.cjs +191 -76
  186. package/dist/web/shop/index.d.cts +21 -4
  187. package/dist/web/shop/index.d.ts +21 -4
  188. package/dist/web/shop/index.js +191 -76
  189. package/dist/web/televet/booking/index.d.cts +6 -6
  190. package/dist/web/televet/booking/index.d.ts +6 -6
  191. package/dist/web/texting/index.cjs +36 -5
  192. package/dist/web/texting/index.d.cts +40 -7
  193. package/dist/web/texting/index.d.ts +40 -7
  194. package/dist/web/texting/index.js +36 -5
  195. package/package.json +35 -4
  196. package/tabs/package.json +8 -0
  197. package/web/intro/native-blocked.cjs +12 -0
  198. package/web/intro/package.json +8 -0
  199. package/dist/threadOptions.d-B1pTMmDF.d.cts +0 -260
  200. package/dist/threadOptions.d-B1pTMmDF.d.ts +0 -260
  201. package/dist/usePresentation.d-D6qsFzBz.d.cts +0 -9
  202. package/dist/usePresentation.d-DuGQe_Do.d.ts +0 -9
@@ -1,16 +1,16 @@
1
1
  import { ReactNode } from 'react';
2
2
  import { StyleProp, ViewStyle } from 'react-native';
3
- import { C as CapabilityDecision } from '../resolve.d-jI8FmBj3.cjs';
3
+ import { a as CapabilityDecision } from '../resolve.d-CoQWUy1Y.cjs';
4
4
  import { E as EverfurError } from '../EverfurError.d-8NHtlgzA.cjs';
5
5
  export { a as EverfurErrorCategory, b as EverfurErrorCode } from '../EverfurError.d-8NHtlgzA.cjs';
6
- import { E as EverfurTextingViewStatus, T as TextingCopy, a as TextingBrandCopy } from '../optInView.d-CEyHR6PK.cjs';
7
- export { C as COPY_PLACEHOLDER_PREFIX, b as EVERFUR_TEXTING_STATUSES, c as EverfurTextingChallenge, d as EverfurTextingIdentity, e as EverfurTextingInputProblem, f as EverfurTextingProfile, g as EverfurTextingReason, h as EverfurTextingState, i as EverfurTextingStatus, j as EverfurTextingVerificationInput, k as TEXTING_BRAND_COPY, l as TEXTING_CODE_PATTERN, m as TEXTING_COPY, n as TEXTING_COPY_PLACEHOLDERS, o as TEXTING_UI_CODE_LENGTH, p as TextingAction, q as TextingCodeRefusal, r as TextingController, s as TextingPhase, t as TextingRepository, u as TextingRepositoryDeps, v as TextingRuntime, w as TextingSnapshot, x as createTextingRepository, y as createTextingRepositoryOver, z as formatTextingPhone, A as isE164, B as parseTextingProfile, D as textingErrorText, F as textingIdentityFromWire, G as textingInputProblemText, H as textingOptedOutBody, I as textingReasonOf, J as textingSupportText, K as toTextingE164, L as useEverfurTexting, M as useEverfurTextingProfile, N as useEverfurTextingRepository, O as validateTextingCode, P as validateTextingEnroll } from '../optInView.d-CEyHR6PK.cjs';
8
- export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../identity.d-60LeJt_s.cjs';
9
- export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../config.d-BR3DT9ho.cjs';
6
+ import { E as EverfurTextingViewStatus, T as TextingCopy, a as TextingBrandCopy, b as TextingAsk } from '../optInView.d-0iI5JoAf.cjs';
7
+ export { C as COPY_PLACEHOLDER_PREFIX, c as EVERFUR_TEXTING_STATUSES, d as EverfurTextingChallenge, e as EverfurTextingIdentity, f as EverfurTextingInputProblem, g as EverfurTextingProfile, h as EverfurTextingReason, i as EverfurTextingState, j as EverfurTextingStatus, k as EverfurTextingVerificationInput, l as TEXTING_ASK_MAX_ASKS, m as TEXTING_ASK_SCHEDULE_KEY, n as TEXTING_ASK_SNOOZE_MS, o as TEXTING_BRAND_COPY, p as TEXTING_CODE_PATTERN, q as TEXTING_COPY, r as TEXTING_COPY_PLACEHOLDERS, s as TEXTING_UI_CODE_LENGTH, t as TextingAction, u as TextingAskDue, v as TextingAskDueInput, w as TextingAskEntry, x as TextingAskIdentity, y as TextingAskOptions, z as TextingAskScheduleRead, A as TextingAskStage, B as TextingAskThreadMessage, D as TextingAskThreadState, F as TextingCodeRefusal, G as TextingController, H as TextingPhase, I as TextingRepository, J as TextingRepositoryDeps, K as TextingRuntime, L as TextingSnapshot, M as createTextingRepository, N as createTextingRepositoryOver, O as formatTextingPhone, P as isE164, Q as isTextingAskEligible, R as parseTextingProfile, S as resolveTextingAskDue, U as textingAskThreadReady, V as textingErrorText, W as textingIdentityFromWire, X as textingInputProblemText, Y as textingOptedOutBody, Z as textingReasonOf, _ as textingSupportText, $ as toTextingE164, a0 as useEverfurTexting, a1 as useEverfurTextingProfile, a2 as useEverfurTextingRepository, a3 as useTextingAsk, a4 as validateTextingCode, a5 as validateTextingEnroll } from '../optInView.d-0iI5JoAf.cjs';
8
+ export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../identity.d-CJfnWOdH.cjs';
9
+ export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../config.d-DJ4mvf_w.cjs';
10
10
  export { B as Brand, C as ConversationId, P as PetRef, R as RecordsRequestId, U as UserRef, _ as __brand } from '../ids.d-B2GAAifq.cjs';
11
11
  export { E as EverfurResult } from '../EverfurResult.d-BFH-3s6E.cjs';
12
12
  export { E as ErrorPolicyPort } from '../ErrorPolicyPort.d-DirW9hgO.cjs';
13
- import '../requestFunnel.d-DWQQpjFR.cjs';
13
+ import '../requestFunnel.d-RZex94XX.cjs';
14
14
 
15
15
  interface EverfurTextingOptInProps {
16
16
  /** Called when the member's step changes (for example to `verified` or `optedOut`). A throw is swallowed. */
@@ -33,4 +33,37 @@ interface EverfurTextingOptInProps {
33
33
  /** The texting opt-in in a React Native app. Mount it under the `EverfurProvider` from "@everfur/sdk". */
34
34
  declare function EverfurTextingOptIn(props: EverfurTextingOptInProps): ReactNode;
35
35
 
36
- export { EverfurError, EverfurTextingOptIn, type EverfurTextingOptInProps, EverfurTextingViewStatus, TextingBrandCopy, TextingCopy };
36
+ /** How a showing ended: the member verified a number, or answered "Not now" (or closed the pop-up). */
37
+ type EverfurTextingPromptOutcome = 'verified' | 'dismissed';
38
+ interface EverfurTextingPromptProps {
39
+ /** Called once when a showing ends. A throw is swallowed. */
40
+ readonly onResolved?: (outcome: EverfurTextingPromptOutcome) => void;
41
+ }
42
+ /** The app-open texting pop-up in a React Native app. Renders nothing unless the ask is due for this member. */
43
+ declare function EverfurTextingPrompt({ onResolved }: EverfurTextingPromptProps): ReactNode;
44
+
45
+ interface ChatTextingAskControllerProps {
46
+ /** The chat's `chatTextingAsk` presentation setting. */
47
+ readonly enabled: boolean;
48
+ /** The thread has an answer on screen and nothing in flight. */
49
+ readonly ready: boolean;
50
+ /** Called with the ask's state whenever it changes. */
51
+ readonly onAsk: (ask: TextingAsk) => void;
52
+ }
53
+ /** Runs the ask for the chat and reports it; draws nothing. `EverfurChat` mounts it itself. */
54
+ declare function ChatTextingAskController({ enabled, ready, onAsk }: ChatTextingAskControllerProps): ReactNode;
55
+ /** The words the chat's thread draws for the ask: the line, its two chips and the closing line. */
56
+ interface TextingAskLines {
57
+ readonly line: string;
58
+ readonly accept: string;
59
+ readonly dismiss: string;
60
+ readonly verified: string;
61
+ }
62
+ declare function textingAskLines(ask: Pick<TextingAsk, 'brand'>): TextingAskLines;
63
+ interface ChatTextingAskComposerProps {
64
+ readonly ask: TextingAsk;
65
+ }
66
+ /** The number entry in the chat composer's place, while the ask is `enrolling`. */
67
+ declare function ChatTextingAskComposer({ ask }: ChatTextingAskComposerProps): ReactNode;
68
+
69
+ export { ChatTextingAskComposer, type ChatTextingAskComposerProps, ChatTextingAskController, type ChatTextingAskControllerProps, EverfurError, EverfurTextingOptIn, type EverfurTextingOptInProps, EverfurTextingPrompt, type EverfurTextingPromptOutcome, type EverfurTextingPromptProps, EverfurTextingViewStatus, TextingAsk, type TextingAskLines, TextingBrandCopy, TextingCopy, textingAskLines };
@@ -1,16 +1,16 @@
1
1
  import { ReactNode } from 'react';
2
2
  import { StyleProp, ViewStyle } from 'react-native';
3
- import { C as CapabilityDecision } from '../resolve.d-jI8FmBj3.js';
3
+ import { a as CapabilityDecision } from '../resolve.d-CoQWUy1Y.js';
4
4
  import { E as EverfurError } from '../EverfurError.d-8NHtlgzA.js';
5
5
  export { a as EverfurErrorCategory, b as EverfurErrorCode } from '../EverfurError.d-8NHtlgzA.js';
6
- import { E as EverfurTextingViewStatus, T as TextingCopy, a as TextingBrandCopy } from '../optInView.d-acKpV8V2.js';
7
- export { C as COPY_PLACEHOLDER_PREFIX, b as EVERFUR_TEXTING_STATUSES, c as EverfurTextingChallenge, d as EverfurTextingIdentity, e as EverfurTextingInputProblem, f as EverfurTextingProfile, g as EverfurTextingReason, h as EverfurTextingState, i as EverfurTextingStatus, j as EverfurTextingVerificationInput, k as TEXTING_BRAND_COPY, l as TEXTING_CODE_PATTERN, m as TEXTING_COPY, n as TEXTING_COPY_PLACEHOLDERS, o as TEXTING_UI_CODE_LENGTH, p as TextingAction, q as TextingCodeRefusal, r as TextingController, s as TextingPhase, t as TextingRepository, u as TextingRepositoryDeps, v as TextingRuntime, w as TextingSnapshot, x as createTextingRepository, y as createTextingRepositoryOver, z as formatTextingPhone, A as isE164, B as parseTextingProfile, D as textingErrorText, F as textingIdentityFromWire, G as textingInputProblemText, H as textingOptedOutBody, I as textingReasonOf, J as textingSupportText, K as toTextingE164, L as useEverfurTexting, M as useEverfurTextingProfile, N as useEverfurTextingRepository, O as validateTextingCode, P as validateTextingEnroll } from '../optInView.d-acKpV8V2.js';
8
- export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../identity.d-DzTijonw.js';
9
- export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../config.d-Dy6igYlH.js';
6
+ import { E as EverfurTextingViewStatus, T as TextingCopy, a as TextingBrandCopy, b as TextingAsk } from '../optInView.d-s-w4aGN3.js';
7
+ export { C as COPY_PLACEHOLDER_PREFIX, c as EVERFUR_TEXTING_STATUSES, d as EverfurTextingChallenge, e as EverfurTextingIdentity, f as EverfurTextingInputProblem, g as EverfurTextingProfile, h as EverfurTextingReason, i as EverfurTextingState, j as EverfurTextingStatus, k as EverfurTextingVerificationInput, l as TEXTING_ASK_MAX_ASKS, m as TEXTING_ASK_SCHEDULE_KEY, n as TEXTING_ASK_SNOOZE_MS, o as TEXTING_BRAND_COPY, p as TEXTING_CODE_PATTERN, q as TEXTING_COPY, r as TEXTING_COPY_PLACEHOLDERS, s as TEXTING_UI_CODE_LENGTH, t as TextingAction, u as TextingAskDue, v as TextingAskDueInput, w as TextingAskEntry, x as TextingAskIdentity, y as TextingAskOptions, z as TextingAskScheduleRead, A as TextingAskStage, B as TextingAskThreadMessage, D as TextingAskThreadState, F as TextingCodeRefusal, G as TextingController, H as TextingPhase, I as TextingRepository, J as TextingRepositoryDeps, K as TextingRuntime, L as TextingSnapshot, M as createTextingRepository, N as createTextingRepositoryOver, O as formatTextingPhone, P as isE164, Q as isTextingAskEligible, R as parseTextingProfile, S as resolveTextingAskDue, U as textingAskThreadReady, V as textingErrorText, W as textingIdentityFromWire, X as textingInputProblemText, Y as textingOptedOutBody, Z as textingReasonOf, _ as textingSupportText, $ as toTextingE164, a0 as useEverfurTexting, a1 as useEverfurTextingProfile, a2 as useEverfurTextingRepository, a3 as useTextingAsk, a4 as validateTextingCode, a5 as validateTextingEnroll } from '../optInView.d-s-w4aGN3.js';
8
+ export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../identity.d-BePPZ7Uv.js';
9
+ export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../config.d-MX7IKP2f.js';
10
10
  export { B as Brand, C as ConversationId, P as PetRef, R as RecordsRequestId, U as UserRef, _ as __brand } from '../ids.d-B2GAAifq.js';
11
11
  export { E as EverfurResult } from '../EverfurResult.d-D_-254ZY.js';
12
12
  export { E as ErrorPolicyPort } from '../ErrorPolicyPort.d-68yrE3BE.js';
13
- import '../requestFunnel.d-CXUMPw1K.js';
13
+ import '../requestFunnel.d-D9edIEjZ.js';
14
14
 
15
15
  interface EverfurTextingOptInProps {
16
16
  /** Called when the member's step changes (for example to `verified` or `optedOut`). A throw is swallowed. */
@@ -33,4 +33,37 @@ interface EverfurTextingOptInProps {
33
33
  /** The texting opt-in in a React Native app. Mount it under the `EverfurProvider` from "@everfur/sdk". */
34
34
  declare function EverfurTextingOptIn(props: EverfurTextingOptInProps): ReactNode;
35
35
 
36
- export { EverfurError, EverfurTextingOptIn, type EverfurTextingOptInProps, EverfurTextingViewStatus, TextingBrandCopy, TextingCopy };
36
+ /** How a showing ended: the member verified a number, or answered "Not now" (or closed the pop-up). */
37
+ type EverfurTextingPromptOutcome = 'verified' | 'dismissed';
38
+ interface EverfurTextingPromptProps {
39
+ /** Called once when a showing ends. A throw is swallowed. */
40
+ readonly onResolved?: (outcome: EverfurTextingPromptOutcome) => void;
41
+ }
42
+ /** The app-open texting pop-up in a React Native app. Renders nothing unless the ask is due for this member. */
43
+ declare function EverfurTextingPrompt({ onResolved }: EverfurTextingPromptProps): ReactNode;
44
+
45
+ interface ChatTextingAskControllerProps {
46
+ /** The chat's `chatTextingAsk` presentation setting. */
47
+ readonly enabled: boolean;
48
+ /** The thread has an answer on screen and nothing in flight. */
49
+ readonly ready: boolean;
50
+ /** Called with the ask's state whenever it changes. */
51
+ readonly onAsk: (ask: TextingAsk) => void;
52
+ }
53
+ /** Runs the ask for the chat and reports it; draws nothing. `EverfurChat` mounts it itself. */
54
+ declare function ChatTextingAskController({ enabled, ready, onAsk }: ChatTextingAskControllerProps): ReactNode;
55
+ /** The words the chat's thread draws for the ask: the line, its two chips and the closing line. */
56
+ interface TextingAskLines {
57
+ readonly line: string;
58
+ readonly accept: string;
59
+ readonly dismiss: string;
60
+ readonly verified: string;
61
+ }
62
+ declare function textingAskLines(ask: Pick<TextingAsk, 'brand'>): TextingAskLines;
63
+ interface ChatTextingAskComposerProps {
64
+ readonly ask: TextingAsk;
65
+ }
66
+ /** The number entry in the chat composer's place, while the ask is `enrolling`. */
67
+ declare function ChatTextingAskComposer({ ask }: ChatTextingAskComposerProps): ReactNode;
68
+
69
+ export { ChatTextingAskComposer, type ChatTextingAskComposerProps, ChatTextingAskController, type ChatTextingAskControllerProps, EverfurError, EverfurTextingOptIn, type EverfurTextingOptInProps, EverfurTextingPrompt, type EverfurTextingPromptOutcome, type EverfurTextingPromptProps, EverfurTextingViewStatus, TextingAsk, type TextingAskLines, TextingBrandCopy, TextingCopy, textingAskLines };
@@ -1,4 +1,4 @@
1
- import{createContext,forwardRef,createElement,useMemo,useEffect,useSyncExternalStore,useCallback,useState,useContext,useRef,Component}from"react";import{TextInput as TextInput$1,View,ActivityIndicator,Pressable,StyleSheet,Text as Text$1}from"react-native";import{jsxs,jsx,Fragment}from"react/jsx-runtime";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 FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function 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 HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
1
+ import{createContext,forwardRef,createElement,useMemo,useRef,useEffect,useSyncExternalStore,useCallback,useState,useContext,Component}from"react";import{TextInput as TextInput$1,View,ActivityIndicator,Pressable,StyleSheet,Modal,Text as Text$1}from"react-native";import{jsxs,jsx,Fragment}from"react/jsx-runtime";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 FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base=face(theme,fallback);return base.fontWeight===void 0||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}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 HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state2){return Object.is(props.resetKey,state2.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
2
2
  /* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
3
3
  /* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
4
4
  /* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
@@ -99,10 +99,10 @@ return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fiel
99
99
  return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str(o.ref),name:name,dose:str(o.dose),frequency:str(o.frequency),startDate:str(o.start_date),endDate:str(o.end_date),notes:str(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
100
100
  return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str(o.food_brand),foodType:str(o.food_type),microchipId:str(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),conditionName:conditionName,diagnosedDate:str(row.diagnosed_date),notes:str(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid("pet_ref must be a string");if(petRef.trim().length===0)return invalid("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid("profile must be an object");let checks=[checkString("pet_ref",petRef,PET_REF_MAX)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str2=v=>typeof v=="string"?v:null,num=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
101
101
  return Object.freeze({petRef:str2(o.pet_ref)??petRef,name:str2(o.name),species:str2(o.species),breed:str2(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef=str2(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str2(o.pet_id),petRef:petRef,name:str2(o.name),species:str2(o.species),breed:str2(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str2(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
102
- return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid3=validate(petRef,profile);if(invalid3!==null)return err(invalid3);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base,signal:opts.signal}:base);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}var COPY_PLACEHOLDER_PREFIX="[copy needed: ",TEXTING_COPY=/* @__PURE__ */Object.freeze({loading:"Loading",retry:"Try again",signedOut:"Sign in required",phoneLabel:"Mobile number",phoneHint:"We'll text a 6-digit code to confirm it's you.",phoneInvalid:"That doesn't look like a valid number. Check it and the country, then try again.",consentRequired:"Please agree to receive SMS messages to continue.",sendCode:"Send code",sendingCode:"Sending code",codeTitle:"Enter your code",codeSentTo:"We texted a 6-digit code to",codeLabel:"6-digit code",codeInvalidFormat:"Enter all 6 digits of the code.",confirmCode:"Verify",confirmingCode:"Verifying",verificationInvalid:"That code is no longer valid. Request a new one.",codeExpired:"This code has expired. Request a new one.",requestNewCode:"Request a new code",noResendsLeft:"You've requested the maximum number of codes. Please try again later or contact support.",changeNumber:"Use a different number",defaultPetLabel:"Default pet for SMS",noPetSelected:"Choose a pet",savePet:"Save",savingPet:"Saving",petSaved:"Saved",petIneligible:"That pet can't be selected anymore. Please choose another.",optedOutTitle:"SMS paused",verifiedTitle:"SMS Chat is on",disable:"Turn off SMS Chat",disabling:"Turning off",disableConfirmTitle:"Turn off SMS Chat?",disableConfirmBody:"We'll stop texting this number. You can turn it back on anytime.",disableConfirm:"Turn off",disableCancel:"Keep it on",unavailableTitle:"SMS Chat isn't available yet",unavailableBody:"We're still setting it up. Check back soon.",phoneAlreadyLinked:"This number is already linked to another Everfur account. Contact support and we'll move it for you.",providerFailed:"We couldn't send the text. Please try again.",genericFailure:"That didn't go through. Please try again.",supportReference:"Support reference:",phoneCountryNotAllowed:"That doesn't look like a valid number. Check it and the country, then try again.",verificationBusy:"SMS Chat is temporarily unavailable. Please try again in a few minutes.",helpContactLabel:"Help:",reenroll:"Turn on SMS Chat",optedOutByMemberBody:"We'll stop texting this number. You can turn it back on anytime.",codeWrong:"That code didn't work. Check it and try again."}),TEXTING_BRAND_COPY=/* @__PURE__ */Object.freeze({introTitle:brand=>`Chat with ${brand} by text`,introBody:brand=>`Ask ${brand} about your pet by text, the same way you'd message a friend. We'll text you back.`,statusActive:brand=>`You can text ${brand} anytime from this number.`,optedOutBody:brand=>`You texted STOP, so we won't message you. Text START to ${brand} to turn SMS Chat back on.`}),TEXTING_COPY_PLACEHOLDERS=/* @__PURE__ */Object.freeze(Object.keys(TEXTING_COPY).filter(key=>TEXTING_COPY[key].startsWith(COPY_PLACEHOLDER_PREFIX)));function resolveTextingCopy(overrides){if(overrides==null||typeof overrides!="object")return TEXTING_COPY;let out={...TEXTING_COPY};for(let key of Object.keys(TEXTING_COPY)){let value=overrides[key];typeof value=="string"&&value.trim().length>0&&(out[key]=value)}/* @__PURE__ */
103
- return Object.freeze(out)}function resolveTextingBrandCopy(overrides){if(overrides==null||typeof overrides!="object")return TEXTING_BRAND_COPY;let out={...TEXTING_BRAND_COPY};for(let key of Object.keys(TEXTING_BRAND_COPY)){let host=overrides[key];if(typeof host!="function")continue;let fallback=TEXTING_BRAND_COPY[key];out[key]=brand=>{try{let text3=host(brand);return typeof text3=="string"&&text3.trim().length>0?text3:fallback(brand)}catch{return fallback(brand)}}}/* @__PURE__ */
102
+ return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid3=validate(petRef,profile);if(invalid3!==null)return err(invalid3);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base,signal:opts.signal}:base);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state2,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state2.repository===repository?state2:{pets:[],loading:true,error:null},generation=useRef(0),load2=useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);useEffect(()=>(load2(),()=>{generation.current+=1}),[load2]),useEffect(()=>subscribePetsChanged(runtime,()=>{load2()}),[runtime,load2]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load2}),[current.pets,current.loading,current.error,activePet,load2])}var COPY_PLACEHOLDER_PREFIX="[copy needed: ",TEXTING_COPY=/* @__PURE__ */Object.freeze({loading:"Loading",retry:"Try again",signedOut:"Sign in required",close:"Close",phoneLabel:"Mobile number",phoneHint:"We'll text a 6-digit code to confirm it's you.",phoneInvalid:"That doesn't look like a valid number. Check it and the country, then try again.",consentRequired:"Please agree to receive SMS messages to continue.",sendCode:"Send code",sendingCode:"Sending code",codeTitle:"Enter your code",codeSentTo:"We texted a 6-digit code to",codeLabel:"6-digit code",codeInvalidFormat:"Enter all 6 digits of the code.",confirmCode:"Verify",confirmingCode:"Verifying",verificationInvalid:"That code is no longer valid. Request a new one.",codeExpired:"This code has expired. Request a new one.",requestNewCode:"Request a new code",noResendsLeft:"You've requested the maximum number of codes. Please try again later or contact support.",changeNumber:"Use a different number",defaultPetLabel:"Default pet for SMS",noPetSelected:"Choose a pet",savePet:"Save",savingPet:"Saving",petSaved:"Saved",petIneligible:"That pet can't be selected anymore. Please choose another.",optedOutTitle:"SMS paused",verifiedTitle:"SMS Chat is on",disable:"Turn off SMS Chat",disabling:"Turning off",disableConfirmTitle:"Turn off SMS Chat?",disableConfirmBody:"We'll stop texting this number. You can turn it back on anytime.",disableConfirm:"Turn off",disableCancel:"Keep it on",unavailableTitle:"SMS Chat isn't available yet",unavailableBody:"We're still setting it up. Check back soon.",phoneAlreadyLinked:"This number is already linked to another Everfur account. Contact support and we'll move it for you.",providerFailed:"We couldn't send the text. Please try again.",genericFailure:"That didn't go through. Please try again.",supportReference:"Support reference:",promptBody:"Ask questions about your pet by text message, anytime. No app needed.",promptAccept:"Turn on SMS Chat",promptDismiss:"Not now",phoneCountryNotAllowed:"That doesn't look like a valid number. Check it and the country, then try again.",verificationBusy:"SMS Chat is temporarily unavailable. Please try again in a few minutes.",helpContactLabel:"Help:",reenroll:"Turn on SMS Chat",optedOutByMemberBody:"We'll stop texting this number. You can turn it back on anytime.",codeWrong:"That code didn't work. Check it and try again."}),TEXTING_BRAND_COPY=/* @__PURE__ */Object.freeze({introTitle:brand=>`Chat with ${brand} by text`,introBody:brand=>`Ask ${brand} about your pet by text, the same way you'd message a friend. We'll text you back.`,statusActive:brand=>`You can text ${brand} anytime from this number.`,optedOutBody:brand=>`You texted STOP, so we won't message you. Text START to ${brand} to turn SMS Chat back on.`,promptTitle:brand=>`Ask ${brand} by text, for every pet`,chatAskLine:brand=>`Want answers by text too? Add your mobile number and you can text ${brand} about your pet anytime.`,chatAskVerified:brand=>`Verified. You're all set to text ${brand}.`}),TEXTING_COPY_PLACEHOLDERS=/* @__PURE__ */Object.freeze(Object.keys(TEXTING_COPY).filter(key=>TEXTING_COPY[key].startsWith(COPY_PLACEHOLDER_PREFIX)));function resolveTextingCopy(overrides){if(overrides==null||typeof overrides!="object")return TEXTING_COPY;let out={...TEXTING_COPY};for(let key of Object.keys(TEXTING_COPY)){let value=overrides[key];typeof value=="string"&&value.trim().length>0&&(out[key]=value)}/* @__PURE__ */
103
+ return Object.freeze(out)}function resolveTextingBrandCopy(overrides){if(overrides==null||typeof overrides!="object")return TEXTING_BRAND_COPY;let out={...TEXTING_BRAND_COPY};for(let key of Object.keys(TEXTING_BRAND_COPY)){let host2=overrides[key];if(typeof host2!="function")continue;let fallback=TEXTING_BRAND_COPY[key];out[key]=brand=>{try{let text3=host2(brand);return typeof text3=="string"&&text3.trim().length>0?text3:fallback(brand)}catch{return fallback(brand)}}}/* @__PURE__ */
104
104
  return Object.freeze(out)}var TextingCopyContext=createContext({copy:TEXTING_COPY,brandCopy:TEXTING_BRAND_COPY});function useTextingCopy(){return useContext(TextingCopyContext)}function wireCodeOf2(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}function foldWireReason(error,table){let wire=wireCodeOf2(error);if(wire===null)return error;let fold=table[wire];return fold===void 0?error:makeEverfurError(fold.code,{retryable:fold.retryable,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},wireCode:wire,reasonCode:wire,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}function foldWireOrReason(error,table){let folded=foldWireReason(error,table);if(folded!==error||wireCodeOf2(error)!==null)return folded;let reason=error.reasonCode;if(typeof reason!="string")return error;let fold=table[reason];return fold===void 0?error:makeEverfurError(fold.code,{retryable:fold.retryable,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},wireCode:reason,reasonCode:reason,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}function text2(value,max=4e3){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length>0&&trimmed.length<=max?trimmed:null}function parseTextingProfile(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let o=raw,brandName=text2(o.brand_name,120),consentText=text2(o.consent_text),consentVersion=text2(o.consent_version,64);return brandName===null||consentText===null||consentVersion===null?null:/* @__PURE__ */Object.freeze({brandName:brandName,consentText:consentText,consentVersion:consentVersion,helpContact:text2(o.help_contact,320),isLive:o.status_is_live===true})}function toTextingE164(input){if(typeof input!="string"||input.length>40)return null;let trimmed=input.trim();if(!/^\+?[\d\s().-]+$/.test(trimmed))return null;let digits=trimmed.replace(/\D/g,"");if(trimmed.startsWith("+")&&!digits.startsWith("1"))return null;let national=digits.length===11&&digits.startsWith("1")?digits.slice(1):digits;return national.length!==10||!/^[2-9]\d{2}[2-9]\d{6}$/.test(national)?null:`+1${national}`}function isE164(value){return typeof value=="string"&&/^\+[1-9]\d{7,14}$/.test(value)}var IDENTITY_PATH="/widget/v1/me/sms-identity",VERIFY_PATH=`${IDENTITY_PATH}/verification`,CONFIRM_PATH=`${VERIFY_PATH}/confirm`,PET_PATH=`${IDENTITY_PATH}/selected-pet`,EVERFUR_TEXTING_STATUSES=/* @__PURE__ */Object.freeze(["none","pending","verified","opted_out"]),TEXTING_CODE_PATTERN=/^\d{4,8}$/,TEXTING_REASONS=/* @__PURE__ */Object.freeze({sms_not_live:{code:"accessDenied",retryable:false},consent_version_mismatch:{code:"conflict",retryable:false},pet_not_found:{code:"resourceNotFound",retryable:false},pet_species_unsupported:{code:"validationFailed",retryable:false},phone_country_not_allowed:{code:"accessDenied",retryable:false},verification_tenant_limit:{code:"rateLimited",retryable:false},verification_phone_limit:{code:"rateLimited",retryable:false},SMS_NOT_LIVE:{code:"accessDenied",retryable:false},SMS_CHAT_VERIFICATION_INVALID:{code:"validationFailed",retryable:false},SMS_CHAT_PHONE_ALREADY_LINKED:{code:"conflict",retryable:false},SMS_CHAT_PET_INELIGIBLE:{code:"validationFailed",retryable:false},SMS_CHAT_IDENTITY_NOT_FOUND:{code:"resourceNotFound",retryable:false}}),REASON_BY_WIRE=/* @__PURE__ */Object.freeze({sms_not_live:"not_live",SMS_NOT_LIVE:"not_live",session_required:"session_required",consent_version_mismatch:"consent_changed",pet_not_found:"pet_ineligible",pet_species_unsupported:"pet_ineligible",phone_country_not_allowed:"country_not_allowed",verification_phone_limit:"phone_code_limit",verification_tenant_limit:"tenant_code_limit",SMS_CHAT_VERIFICATION_INVALID:"code_invalid",SMS_CHAT_PHONE_ALREADY_LINKED:"phone_linked",SMS_CHAT_PET_INELIGIBLE:"pet_ineligible",SMS_CHAT_IDENTITY_NOT_FOUND:"no_identity"});function textingReasonOf(error){if(error==null)return null;let code=error.reasonCode??wireCodeOf2(error);return typeof code=="string"?REASON_BY_WIRE[code]??null:null}function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function malformed(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the documented shape`})}var str3=value=>typeof value=="string"&&value.length>0?value:null;function statusOf(value){return typeof value=="string"&&EVERFUR_TEXTING_STATUSES.includes(value)?value:"none"}function textingIdentityFromWire(raw){if(raw===null||typeof raw!="object")return null;let o=raw;return typeof o.status!="string"?null:/* @__PURE__ */Object.freeze({status:statusOf(o.status),phoneMasked:str3(o.phone_masked),consentVersion:str3(o.consent_version),selectedPetRef:str3(o.selected_pet_ref)})}function challengeFromWire(raw){if(raw===null||typeof raw!="object")return null;let o=raw,challengeId=str3(o.challenge_id);if(challengeId===null)return null;let attempts=o.attempts_remaining,attemptsRemaining=typeof attempts=="number"&&Number.isInteger(attempts)&&attempts>=0?attempts:null;/* @__PURE__ */
105
- return Object.freeze({challengeId:challengeId,expiresAt:str3(o.expires_at),attemptsRemaining:attemptsRemaining})}function isEmptyBody(value){return value==null||value===""?true:typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0}var OPTED_OUT=/* @__PURE__ */Object.freeze({status:"opted_out",phoneMasked:null,consentVersion:null,selectedPetRef:null});function createTextingRepository(runtime){let over=()=>{let{services:services}=runtime.registry;return createTextingRepositoryOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed(verb)));return{read:opts=>runtime.isDisposed?gone("read"):over().read(opts),startVerification:input=>runtime.isDisposed?gone("startVerification"):over().startVerification(input),confirmVerification:(id,code)=>runtime.isDisposed?gone("confirmVerification"):over().confirmVerification(id,code),selectPet:petRef=>runtime.isDisposed?gone("selectPet"):over().selectPet(petRef),optOut:()=>runtime.isDisposed?gone("optOut"):over().optOut()}}function createTextingRepositoryOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),fold=error=>foldWireOrReason(error,TEXTING_REASONS),identityCall=async(call,req,opts,emptyIs)=>{let res=await funnel.send(call,req,opts);if(!res.ok)return err(fold(res.error));let identity=textingIdentityFromWire(res.value);return identity!==null?ok(identity):emptyIs!==void 0&&isEmptyBody(res.value)?ok(emptyIs):err(malformed(call))};return{read(opts){let req=opts?.signal?{method:"GET",path:IDENTITY_PATH,signal:opts.signal}:{method:"GET",path:IDENTITY_PATH};return identityCall("texting.read",req)},async startVerification(input){if(typeof input!="object"||input===null||!isE164(input.phoneE164))return err(invalid2("phoneE164 must be an E.164 number"));if(typeof input.consentVersion!="string"||input.consentVersion.length===0||input.consentVersion.length>64)return err(invalid2("consentVersion must be the tenant profile consent version (1..64 characters)"));let res=await funnel.send("texting.verification.start",{method:"POST",path:VERIFY_PATH,body:{phone_e164:input.phoneE164,consent_version:input.consentVersion}},{maxAttempts:1});if(!res.ok)return err(fold(res.error));let challenge=challengeFromWire(res.value);return challenge===null?err(malformed("texting.verification.start")):ok(challenge)},async confirmVerification(challengeId,code){return typeof challengeId!="string"||challengeId.length===0?err(invalid2("challengeId is required")):typeof code!="string"||!TEXTING_CODE_PATTERN.test(code)?err(invalid2("code must be the digits that were texted")):identityCall("texting.verification.confirm",{method:"POST",path:CONFIRM_PATH,body:{challenge_id:challengeId,code:code}},{maxAttempts:1})},async selectPet(petRef){return typeof petRef!="string"||petRef.length===0||petRef.length>128?err(invalid2("petRef must be 1..128 characters")):identityCall("texting.pet.select",{method:"PUT",path:PET_PATH,body:{pet_ref:petRef}})},optOut(){return identityCall("texting.optOut",{method:"DELETE",path:IDENTITY_PATH},void 0,OPTED_OUT)}}}function textingErrorText(error,action,codeRefusal=null,copy=TEXTING_COPY){switch(textingReasonOf(error)){case"code_invalid":return codeRefusal==="wrong"?copy.codeWrong:codeRefusal==="expired"?copy.codeExpired:copy.verificationInvalid;case"phone_linked":return copy.phoneAlreadyLinked;case"pet_ineligible":return copy.petIneligible;case"not_live":return copy.unavailableBody;case"session_required":return copy.signedOut;case"country_not_allowed":return copy.phoneCountryNotAllowed;case"phone_code_limit":return copy.noResendsLeft;case"tenant_code_limit":return copy.verificationBusy;default:return action==="start"?copy.providerFailed:copy.genericFailure}}function textingSupportText(error,copy=TEXTING_COPY){return typeof error.requestId=="string"&&error.requestId.length>0?`${copy.supportReference} ${error.requestId}`:null}function textingInputProblemText(problem,copy=TEXTING_COPY){return copy[problem]}function textingOptedOutBody(identity,brand,copy=TEXTING_COPY,brandCopy=TEXTING_BRAND_COPY){return identity!==null&&identity.phoneMasked!==null?brandCopy.optedOutBody(brand):copy.optedOutByMemberBody}function formatTextingPhone(e164){if(e164===null)return"";let match=/^\+1(\d{3})(\d{3})(\d{4})$/.exec(e164);return match===null?e164:`(${match[1]}) ${match[2]}-${match[3]}`}var INITIAL=/* @__PURE__ */Object.freeze({phase:"loading",identity:null,challenge:null,phoneE164:null,error:null,failedAction:null,codeRefusal:null,savingPet:false,resending:false});function phaseFor(identity){return identity.status==="verified"?"verified":identity.status==="opted_out"?"optedOut":"enroll"}var TextingController=class{constructor(repository,now=Date.now){this.repository=repository;this.now=now;this.snapshot=INITIAL;this.listeners=/* @__PURE__ */new Set;this.generation=0;this.consentVersion=null;this.disposed=false;this.subscribe=listener=>(this.listeners.add(listener),()=>{this.listeners.delete(listener)});this.getSnapshot=()=>this.snapshot}set(next){if(!this.disposed){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,codeRefusal:null,resending:false,...next});for(let listener of this.listeners)listener()}}async load(){let gen=++this.generation;this.set({phase:"loading",error:null,failedAction:null});let result=await this.repository.read();if(gen===this.generation){if(!result.ok){this.set({phase:"failed",error:result.error,failedAction:"read"});return}this.set({phase:phaseFor(result.value),identity:result.value,challenge:null,error:null,failedAction:null})}}async start(phoneE164,consentVersion){let from=this.snapshot.phase;if(from!=="enroll"&&from!=="code"&&from!=="optedOut")return false;let gen=++this.generation;this.consentVersion=consentVersion,this.set({phase:"requesting",phoneE164:phoneE164,error:null,failedAction:null,resending:from==="code"});let result=await this.repository.startVerification({phoneE164:phoneE164,consentVersion:consentVersion});return gen!==this.generation?false:result.ok?(this.set({phase:"code",challenge:result.value,error:null,failedAction:null}),true):(this.set({phase:from==="code"?"code":"enroll",error:result.error,failedAction:"start"}),false)}resend(){let{phoneE164:phoneE164}=this.snapshot;return phoneE164===null||this.consentVersion===null?Promise.resolve(false):this.start(phoneE164,this.consentVersion)}async confirm(code){let{challenge:challenge}=this.snapshot;if(this.snapshot.phase!=="code"||challenge===null)return false;let gen=++this.generation;this.set({phase:"confirming",error:null,failedAction:null});let result=await this.repository.confirmVerification(challenge.challengeId,code);if(gen!==this.generation)return false;if(!result.ok){if(textingReasonOf(result.error)!=="code_invalid")return this.set({phase:"code",error:result.error,failedAction:"confirm"}),false;let left=challenge.attemptsRemaining===null?null:Math.max(0,challenge.attemptsRemaining-1),expiresAt=challenge.expiresAt===null?Number.NaN:Date.parse(challenge.expiresAt),codeRefusal=null;return Number.isFinite(expiresAt)&&this.now()>=expiresAt?codeRefusal="expired":left===0?codeRefusal="spent":left!==null&&Number.isFinite(expiresAt)&&(codeRefusal="wrong"),this.set({phase:"code",challenge:/* @__PURE__ */Object.freeze({...challenge,attemptsRemaining:left}),error:result.error,failedAction:"confirm",codeRefusal:codeRefusal}),false}return this.set({phase:phaseFor(result.value),identity:result.value,challenge:null,error:null,failedAction:null}),true}changeNumber(){this.generation+=1,this.set({phase:"enroll",challenge:null,error:null,failedAction:null})}reenroll(){this.snapshot.phase==="optedOut"&&(this.generation+=1,this.set({phase:"enroll",challenge:null,error:null,failedAction:null}))}async selectPet(petRef){if(this.snapshot.phase!=="verified"||this.snapshot.savingPet)return false;let gen=this.generation;this.set({savingPet:true,error:null,failedAction:null});let result=await this.repository.selectPet(petRef);return gen!==this.generation?false:result.ok?(this.set({savingPet:false,identity:result.value,phase:phaseFor(result.value)}),true):(this.set({savingPet:false,error:result.error,failedAction:"selectPet"}),false)}async optOut(){if(this.snapshot.phase!=="verified")return false;let gen=++this.generation;this.set({phase:"optingOut",error:null,failedAction:null});let result=await this.repository.optOut();return gen!==this.generation?false:result.ok?(this.set({phase:"optedOut",identity:result.value,error:null,failedAction:null}),true):(this.set({phase:"verified",error:result.error,failedAction:"optOut"}),false)}dispose(){this.generation+=1,this.disposed=true,this.listeners.clear()}};function useScopedController(create,deps){let[controller,setController]=useState(create),adopted=useRef(false);return useEffect(()=>{let current=controller;return adopted.current&&(current=create(),setController(current)),adopted.current=true,()=>current.dispose()},deps),controller}function validateTextingEnroll(phone,consented){return toTextingE164(phone)===null?"phoneInvalid":consented?null:"consentRequired"}var TEXTING_UI_CODE_LENGTH=6;function validateTextingCode(code){return new RegExp(`^\\d{${TEXTING_UI_CODE_LENGTH}}$`).test(code.trim())?null:"codeInvalidFormat"}var NO_SUBSCRIPTION=()=>()=>{};function useRawTextingProfile(){let{runtime:runtime}=useEverfurContext(),source=runtime.entitlements??null,subscribe=useCallback(listener=>source===null?NO_SUBSCRIPTION():source.subscribe(listener),[source]),read=useCallback(()=>source===null?void 0:source.getSnapshot().smsProfilePublic,[source]);return useSyncExternalStore(subscribe,read,read)}function useEverfurTextingProfile(){let raw=useRawTextingProfile();return useMemo(()=>parseTextingProfile(raw),[raw])}function useEverfurTextingRepository(){let{runtime:runtime}=useEverfurContext();return useMemo(()=>createTextingRepository(runtime),[runtime])}function useEverfurTexting(){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useEverfurTextingRepository(),profile=useEverfurTextingProfile(),controller=useScopedController(()=>new TextingController(repository),[repository,userRef,scopeEpoch]);useEffect(()=>{userRef!==null&&controller.load()},[controller,userRef]);let snapshot=useSyncExternalStore(controller.subscribe,controller.getSnapshot,controller.getSnapshot),start=useCallback(async phone=>{let e164=toTextingE164(phone);return e164===null||profile===null||userRef===null?false:controller.start(e164,profile.consentVersion)},[controller,profile,userRef]),confirm=useCallback(code=>validateTextingCode(code)===null?controller.confirm(code.trim()):Promise.resolve(false),[controller]),status;return userRef===null?status="signedOut":profile===null?status="unavailable":status=snapshot.phase,useMemo(()=>({status:status,profile:profile,snapshot:snapshot,start:start,resend:()=>controller.resend(),confirm:confirm,changeNumber:()=>controller.changeNumber(),reenroll:()=>controller.reenroll(),selectPet:petRef=>controller.selectPet(petRef),optOut:()=>controller.optOut(),refresh:()=>controller.load()}),[status,profile,snapshot,start,confirm,controller])}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]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return createElement(Text$1,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...props,...ref===null?{}:{ref:ref}})});var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
105
+ return Object.freeze({challengeId:challengeId,expiresAt:str3(o.expires_at),attemptsRemaining:attemptsRemaining})}function isEmptyBody(value){return value==null||value===""?true:typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0}var OPTED_OUT=/* @__PURE__ */Object.freeze({status:"opted_out",phoneMasked:null,consentVersion:null,selectedPetRef:null});function createTextingRepository(runtime){let over=()=>{let{services:services}=runtime.registry;return createTextingRepositoryOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed(verb)));return{read:opts=>runtime.isDisposed?gone("read"):over().read(opts),startVerification:input=>runtime.isDisposed?gone("startVerification"):over().startVerification(input),confirmVerification:(id,code)=>runtime.isDisposed?gone("confirmVerification"):over().confirmVerification(id,code),selectPet:petRef=>runtime.isDisposed?gone("selectPet"):over().selectPet(petRef),optOut:()=>runtime.isDisposed?gone("optOut"):over().optOut()}}function createTextingRepositoryOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),fold=error=>foldWireOrReason(error,TEXTING_REASONS),identityCall=async(call,req,opts,emptyIs)=>{let res=await funnel.send(call,req,opts);if(!res.ok)return err(fold(res.error));let identity=textingIdentityFromWire(res.value);return identity!==null?ok(identity):emptyIs!==void 0&&isEmptyBody(res.value)?ok(emptyIs):err(malformed(call))};return{read(opts){let req=opts?.signal?{method:"GET",path:IDENTITY_PATH,signal:opts.signal}:{method:"GET",path:IDENTITY_PATH};return identityCall("texting.read",req)},async startVerification(input){if(typeof input!="object"||input===null||!isE164(input.phoneE164))return err(invalid2("phoneE164 must be an E.164 number"));if(typeof input.consentVersion!="string"||input.consentVersion.length===0||input.consentVersion.length>64)return err(invalid2("consentVersion must be the tenant profile consent version (1..64 characters)"));let res=await funnel.send("texting.verification.start",{method:"POST",path:VERIFY_PATH,body:{phone_e164:input.phoneE164,consent_version:input.consentVersion}},{maxAttempts:1});if(!res.ok)return err(fold(res.error));let challenge=challengeFromWire(res.value);return challenge===null?err(malformed("texting.verification.start")):ok(challenge)},async confirmVerification(challengeId,code){return typeof challengeId!="string"||challengeId.length===0?err(invalid2("challengeId is required")):typeof code!="string"||!TEXTING_CODE_PATTERN.test(code)?err(invalid2("code must be the digits that were texted")):identityCall("texting.verification.confirm",{method:"POST",path:CONFIRM_PATH,body:{challenge_id:challengeId,code:code}},{maxAttempts:1})},async selectPet(petRef){return typeof petRef!="string"||petRef.length===0||petRef.length>128?err(invalid2("petRef must be 1..128 characters")):identityCall("texting.pet.select",{method:"PUT",path:PET_PATH,body:{pet_ref:petRef}})},optOut(){return identityCall("texting.optOut",{method:"DELETE",path:IDENTITY_PATH},void 0,OPTED_OUT)}}}function textingErrorText(error,action,codeRefusal=null,copy=TEXTING_COPY){switch(textingReasonOf(error)){case"code_invalid":return codeRefusal==="wrong"?copy.codeWrong:codeRefusal==="expired"?copy.codeExpired:copy.verificationInvalid;case"phone_linked":return copy.phoneAlreadyLinked;case"pet_ineligible":return copy.petIneligible;case"not_live":return copy.unavailableBody;case"session_required":return copy.signedOut;case"country_not_allowed":return copy.phoneCountryNotAllowed;case"phone_code_limit":return copy.noResendsLeft;case"tenant_code_limit":return copy.verificationBusy;default:return action==="start"?copy.providerFailed:copy.genericFailure}}function textingSupportText(error,copy=TEXTING_COPY){return typeof error.requestId=="string"&&error.requestId.length>0?`${copy.supportReference} ${error.requestId}`:null}function textingInputProblemText(problem,copy=TEXTING_COPY){return copy[problem]}function textingOptedOutBody(identity,brand,copy=TEXTING_COPY,brandCopy=TEXTING_BRAND_COPY){return identity!==null&&identity.phoneMasked!==null?brandCopy.optedOutBody(brand):copy.optedOutByMemberBody}function formatTextingPhone(e164){if(e164===null)return"";let match=/^\+1(\d{3})(\d{3})(\d{4})$/.exec(e164);return match===null?e164:`(${match[1]}) ${match[2]}-${match[3]}`}var INITIAL=/* @__PURE__ */Object.freeze({phase:"loading",identity:null,challenge:null,phoneE164:null,error:null,failedAction:null,codeRefusal:null,savingPet:false,resending:false});function phaseFor(identity){return identity.status==="verified"?"verified":identity.status==="opted_out"?"optedOut":"enroll"}var TextingController=class{constructor(repository,now=Date.now){this.repository=repository;this.now=now;this.snapshot=INITIAL;this.listeners=/* @__PURE__ */new Set;this.generation=0;this.consentVersion=null;this.disposed=false;this.subscribe=listener=>(this.listeners.add(listener),()=>{this.listeners.delete(listener)});this.getSnapshot=()=>this.snapshot}set(next){if(!this.disposed){this.snapshot=/* @__PURE__ */Object.freeze({...this.snapshot,codeRefusal:null,resending:false,...next});for(let listener of this.listeners)listener()}}async load(){let gen=++this.generation;this.set({phase:"loading",error:null,failedAction:null});let result=await this.repository.read();if(gen===this.generation){if(!result.ok){this.set({phase:"failed",error:result.error,failedAction:"read"});return}this.set({phase:phaseFor(result.value),identity:result.value,challenge:null,error:null,failedAction:null})}}async start(phoneE164,consentVersion){let from=this.snapshot.phase;if(from!=="enroll"&&from!=="code"&&from!=="optedOut")return false;let gen=++this.generation;this.consentVersion=consentVersion,this.set({phase:"requesting",phoneE164:phoneE164,error:null,failedAction:null,resending:from==="code"});let result=await this.repository.startVerification({phoneE164:phoneE164,consentVersion:consentVersion});return gen!==this.generation?false:result.ok?(this.set({phase:"code",challenge:result.value,error:null,failedAction:null}),true):(this.set({phase:from==="code"?"code":"enroll",error:result.error,failedAction:"start"}),false)}resend(){let{phoneE164:phoneE164}=this.snapshot;return phoneE164===null||this.consentVersion===null?Promise.resolve(false):this.start(phoneE164,this.consentVersion)}async confirm(code){let{challenge:challenge}=this.snapshot;if(this.snapshot.phase!=="code"||challenge===null)return false;let gen=++this.generation;this.set({phase:"confirming",error:null,failedAction:null});let result=await this.repository.confirmVerification(challenge.challengeId,code);if(gen!==this.generation)return false;if(!result.ok){if(textingReasonOf(result.error)!=="code_invalid")return this.set({phase:"code",error:result.error,failedAction:"confirm"}),false;let left=challenge.attemptsRemaining===null?null:Math.max(0,challenge.attemptsRemaining-1),expiresAt=challenge.expiresAt===null?Number.NaN:Date.parse(challenge.expiresAt),codeRefusal=null;return Number.isFinite(expiresAt)&&this.now()>=expiresAt?codeRefusal="expired":left===0?codeRefusal="spent":left!==null&&Number.isFinite(expiresAt)&&(codeRefusal="wrong"),this.set({phase:"code",challenge:/* @__PURE__ */Object.freeze({...challenge,attemptsRemaining:left}),error:result.error,failedAction:"confirm",codeRefusal:codeRefusal}),false}return this.set({phase:phaseFor(result.value),identity:result.value,challenge:null,error:null,failedAction:null}),true}changeNumber(){this.generation+=1,this.set({phase:"enroll",challenge:null,error:null,failedAction:null})}reenroll(){this.snapshot.phase==="optedOut"&&(this.generation+=1,this.set({phase:"enroll",challenge:null,error:null,failedAction:null}))}async selectPet(petRef){if(this.snapshot.phase!=="verified"||this.snapshot.savingPet)return false;let gen=this.generation;this.set({savingPet:true,error:null,failedAction:null});let result=await this.repository.selectPet(petRef);return gen!==this.generation?false:result.ok?(this.set({savingPet:false,identity:result.value,phase:phaseFor(result.value)}),true):(this.set({savingPet:false,error:result.error,failedAction:"selectPet"}),false)}async optOut(){if(this.snapshot.phase!=="verified")return false;let gen=++this.generation;this.set({phase:"optingOut",error:null,failedAction:null});let result=await this.repository.optOut();return gen!==this.generation?false:result.ok?(this.set({phase:"optedOut",identity:result.value,error:null,failedAction:null}),true):(this.set({phase:"verified",error:result.error,failedAction:"optOut"}),false)}dispose(){this.generation+=1,this.disposed=true,this.listeners.clear()}};function useScopedController(create,deps){let[controller,setController]=useState(create),adopted=useRef(false);return useEffect(()=>{let current=controller;return adopted.current&&(current=create(),setController(current)),adopted.current=true,()=>current.dispose()},deps),controller}function validateTextingEnroll(phone,consented){return toTextingE164(phone)===null?"phoneInvalid":consented?null:"consentRequired"}var TEXTING_UI_CODE_LENGTH=6;function validateTextingCode(code){return new RegExp(`^\\d{${TEXTING_UI_CODE_LENGTH}}$`).test(code.trim())?null:"codeInvalidFormat"}var NO_SUBSCRIPTION=()=>()=>{};function useRawTextingProfile(){let{runtime:runtime}=useEverfurContext(),source=runtime.entitlements??null,subscribe2=useCallback(listener=>source===null?NO_SUBSCRIPTION():source.subscribe(listener),[source]),read=useCallback(()=>source===null?void 0:source.getSnapshot().smsProfilePublic,[source]);return useSyncExternalStore(subscribe2,read,read)}function useEverfurTextingProfile(){let raw=useRawTextingProfile();return useMemo(()=>parseTextingProfile(raw),[raw])}function useEverfurTextingRepository(){let{runtime:runtime}=useEverfurContext();return useMemo(()=>createTextingRepository(runtime),[runtime])}function useEverfurTexting(){return useTextingState(true)}function useTextingState(read){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useEverfurTextingRepository(),profile=useEverfurTextingProfile(),controller=useScopedController(()=>new TextingController(repository),[repository,userRef,scopeEpoch]),loadedFor=useRef(null);useEffect(()=>{userRef===null||!read||loadedFor.current===controller||(loadedFor.current=controller,controller.load())},[controller,userRef,read]);let snapshot=useSyncExternalStore(controller.subscribe,controller.getSnapshot,controller.getSnapshot),start=useCallback(async phone=>{let e164=toTextingE164(phone);return e164===null||profile===null||userRef===null?false:controller.start(e164,profile.consentVersion)},[controller,profile,userRef]),confirm=useCallback(code=>validateTextingCode(code)===null?controller.confirm(code.trim()):Promise.resolve(false),[controller]),status;return userRef===null?status="signedOut":profile===null?status="unavailable":status=snapshot.phase,useMemo(()=>({status:status,profile:profile,snapshot:snapshot,start:start,resend:()=>controller.resend(),confirm:confirm,changeNumber:()=>controller.changeNumber(),reenroll:()=>controller.reenroll(),selectPet:petRef=>controller.selectPet(petRef),optOut:()=>controller.optOut(),refresh:()=>controller.load()}),[status,profile,snapshot,start,confirm,controller])}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]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return createElement(Text$1,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...props,...ref===null?{}:{ref:ref}})});var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
106
106
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
107
107
  return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
108
108
  return jsx(View,{style:[styles.offstate,style],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${capability}`,children:/* @__PURE__ */jsx(View,{style:styles.skeletonBar})})}function OffState({decision:decision,style:style}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
@@ -155,4 +155,39 @@ return jsxs(View,{style:styles.petRow,children:[
155
155
  /* @__PURE__ */jsx(View,{style:styles.chips,accessibilityRole:"radiogroup",accessibilityLabel:copy.defaultPetLabel,children:pets.map(pet=>{let picked=pet.petRef===value;/* @__PURE__ */
156
156
  return jsx(Pressable,{onPress:()=>onChoose(pet.petRef),disabled:saving,accessibilityRole:"radio",accessibilityState:{checked:picked,disabled:saving},accessibilityLabel:pet.name??pet.petRef,style:[styles.chip,picked?styles.chipPicked:null],children:/* @__PURE__ */jsx(Text,{tier:"compact",style:[styles.chipLabel,picked?styles.chipLabelPicked:null],children:pet.name??pet.petRef})},pet.petRef)})}),
157
157
  /* @__PURE__ */jsxs(View,{style:styles.links,children:[
158
- /* @__PURE__ */jsx(Button,{label:saving?copy.savingPet:copy.savePet,kind:"secondary",busy:saving,disabled:!changed,styles:styles,onPress:()=>{value!==null&&onSave(value)},testID:"texting-pet-save"}),saved&&!changed?/* @__PURE__ */jsx(Text,{style:styles.footnote,children:copy.petSaved}):null]})]})}function makeStyles2(theme){let{color:color,radius:radius,space:space,type:type,slots:slots}=theme,text3=(size,ink,weight)=>({...face(theme,weight),fontSize:size,lineHeight:Math.round(size*type.lineHeight.snug),color:ink}),cardInk=slots.card?.textColor;return StyleSheet.create({card:{gap:space.md,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,...slotBox(slots.card,1)},title:text3(type.size.subtitle,cardInk??color.text.primary,"bold"),subtitle:text3(type.size.body,cardInk??color.text.primary,"bold"),body:text3(type.size.body,cardInk??color.text.secondary,"regular"),footnote:text3(type.size.caption,color.text.muted,"regular"),phone:text3(type.size.body,cardInk??color.text.primary,"bold"),label:text3(type.size.caption,cardInk??color.text.primary,"bold"),input:{minHeight:44,paddingHorizontal:space.md,borderRadius:radius.md,borderWidth:1,borderColor:color.controlEdge,backgroundColor:color.surface,...text3(type.size.body,color.text.primary,"regular"),...slotBox(slots.input,1),...slotText(slots.input)},consentRow:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,minHeight:44},box:{width:24,height:24,borderRadius:radius.xs,borderWidth:2,borderColor:color.controlEdge,alignItems:"center",justifyContent:"center",backgroundColor:color.surface},boxChecked:{backgroundColor:color.brand,borderColor:color.brandInk},tick:{...text3(type.size.caption,color.text.onBrand,"bold")},consentText:{flex:1,...text3(type.size.caption,cardInk??color.text.secondary,"regular")},primary:{minHeight:44,paddingHorizontal:space.lg,borderRadius:radius.pill,alignItems:"center",justifyContent:"center",backgroundColor:color.brand,...slotBox(slots.primaryButton)},primaryLabel:{...text3(type.size.body,color.text.onBrand,"bold"),...slotText(slots.primaryButton)},secondary:{minHeight:44,paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1,borderColor:color.brandBorder,alignItems:"center",justifyContent:"center",backgroundColor:color.surface},secondaryLabel:text3(type.size.caption,color.brandInk,"bold"),link:{minHeight:44,justifyContent:"center",alignSelf:"flex-start"},linkLabel:{...text3(type.size.caption,color.linkInk,"bold"),...slotText(slots.link)},dimmed:{opacity:.5},links:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:space.md},notice:{gap:space.xs},noticeText:text3(type.size.caption,color.errorRed,"regular"),confirm:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceSubtle},petRow:{gap:space.xs},chips:{flexDirection:"row",flexWrap:"wrap",gap:space.sm},chip:{minHeight:44,paddingHorizontal:space.md,borderRadius:radius.pill,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,justifyContent:"center",...slotBox(slots.chip,1)},chipPicked:{backgroundColor:color.brandSoft,borderColor:color.brandInk},chipLabel:{...text3(type.size.caption,color.text.primary,"regular"),...slotText(slots.chip)},chipLabelPicked:{...face(theme,"bold"),color:color.brandInk}})}export{COPY_PLACEHOLDER_PREFIX,EVERFUR_TEXTING_STATUSES,EverfurTextingOptIn,TEXTING_BRAND_COPY,TEXTING_CODE_PATTERN,TEXTING_COPY,TEXTING_COPY_PLACEHOLDERS,TEXTING_UI_CODE_LENGTH,TextingController,createTextingRepository,createTextingRepositoryOver,formatTextingPhone,isE164,parseTextingProfile,textingErrorText,textingIdentityFromWire,textingInputProblemText,textingOptedOutBody,textingReasonOf,textingSupportText,toTextingE164,useEverfurTexting,useEverfurTextingProfile,useEverfurTextingRepository,validateTextingCode,validateTextingEnroll};
158
+ /* @__PURE__ */jsx(Button,{label:saving?copy.savingPet:copy.savePet,kind:"secondary",busy:saving,disabled:!changed,styles:styles,onPress:()=>{value!==null&&onSave(value)},testID:"texting-pet-save"}),saved&&!changed?/* @__PURE__ */jsx(Text,{style:styles.footnote,children:copy.petSaved}):null]})]})}function makeStyles2(theme){let{color:color,radius:radius,space:space,type:type,slots:slots}=theme,text3=(size,ink,weight)=>({...face(theme,weight),fontSize:size,lineHeight:Math.round(size*type.lineHeight.snug),color:ink}),cardInk=slots.card?.textColor;return StyleSheet.create({card:{gap:space.md,padding:space.lg,borderRadius:radius.lg,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,...slotBox(slots.card,1)},title:text3(type.size.subtitle,cardInk??color.text.primary,"bold"),subtitle:text3(type.size.body,cardInk??color.text.primary,"bold"),body:text3(type.size.body,cardInk??color.text.secondary,"regular"),footnote:text3(type.size.caption,color.text.muted,"regular"),phone:text3(type.size.body,cardInk??color.text.primary,"bold"),label:text3(type.size.caption,cardInk??color.text.primary,"bold"),input:{minHeight:44,paddingHorizontal:space.md,borderRadius:radius.md,borderWidth:1,borderColor:color.controlEdge,backgroundColor:color.surface,...text3(type.size.body,color.text.primary,"regular"),...slotBox(slots.input,1),...slotText(slots.input)},consentRow:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,minHeight:44},box:{width:24,height:24,borderRadius:radius.xs,borderWidth:2,borderColor:color.controlEdge,alignItems:"center",justifyContent:"center",backgroundColor:color.surface},boxChecked:{backgroundColor:color.brand,borderColor:color.brandInk},tick:{...text3(type.size.caption,color.text.onBrand,"bold")},consentText:{flex:1,...text3(type.size.caption,cardInk??color.text.secondary,"regular")},primary:{minHeight:44,paddingHorizontal:space.lg,borderRadius:radius.pill,alignItems:"center",justifyContent:"center",backgroundColor:color.brand,...slotBox(slots.primaryButton)},primaryLabel:{...text3(type.size.body,color.text.onBrand,"bold"),...slotText(slots.primaryButton)},secondary:{minHeight:44,paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1,borderColor:color.brandBorder,alignItems:"center",justifyContent:"center",backgroundColor:color.surface},secondaryLabel:text3(type.size.caption,color.brandInk,"bold"),link:{minHeight:44,justifyContent:"center",alignSelf:"flex-start"},linkLabel:{...text3(type.size.caption,color.linkInk,"bold"),...slotText(slots.link)},dimmed:{opacity:.5},links:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:space.md},notice:{gap:space.xs},noticeText:text3(type.size.caption,color.errorRed,"regular"),confirm:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceSubtle},petRow:{gap:space.xs},chips:{flexDirection:"row",flexWrap:"wrap",gap:space.sm},chip:{minHeight:44,paddingHorizontal:space.md,borderRadius:radius.pill,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,justifyContent:"center",...slotBox(slots.chip,1)},chipPicked:{backgroundColor:color.brandSoft,borderColor:color.brandInk},chipLabel:{...text3(type.size.caption,color.text.primary,"regular"),...slotText(slots.chip)},chipLabelPicked:{...face(theme,"bold"),color:color.brandInk}})}var INTRO_OPEN_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#IntroOpen@v1"),host=globalThis;function isIntroOpenState(value){if(typeof value!="object"||value===null)return false;let v=value;return v.holds instanceof Set&&v.listeners instanceof Set}var stored=host[INTRO_OPEN_SYMBOL],fresh=()=>({holds:/* @__PURE__ */new Set,listeners:/* @__PURE__ */new Set}),state=isIntroOpenState(stored)?stored:host[INTRO_OPEN_SYMBOL]=fresh();function isIntroOpen(){return state.holds.size>0}function subscribe(listener){return state.listeners.add(listener),()=>{state.listeners.delete(listener)}}function useIntroOpen(){return useSyncExternalStore(subscribe,isIntroOpen,isIntroOpen)}function resolveTextingAskDue(input){let readEnabled=input.enabled&&input.capabilityGranted&&input.hasProfile&&input.signedIn&&input.scheduleEligible&&!input.offeredThisSession,due=readEnabled&&input.identity==="none"&&input.surfaceReady;return{readEnabled:readEnabled,due:due}}var URGENT_LEVELS=/* @__PURE__ */new Set(["emergency","schedule_soon"]);function textingAskThreadReady(chat){if(chat.isBootstrapping===true||chat.isLoadingHistory===true||chat.isStreaming===true||chat.status==="error"||chat.stopped===true)return false;let last=chat.messages[chat.messages.length-1];return last===void 0||last.role!=="assistant"||last.pending===true||last.checkin!==void 0||last.text.trim().length===0?false:!(typeof last.urgencyLevel=="string"&&URGENT_LEVELS.has(last.urgencyLevel))}var IN_MEMORY_KVS=/* @__PURE__ */new WeakSet;function isInMemoryKv(kv){return IN_MEMORY_KVS.has(kv)}var TEXTING_ASK_SCHEDULE_KEY="everfur.texting.askSchedule.v1",TEXTING_ASK_SNOOZE_MS=2880*60*1e3,TEXTING_ASK_MAX_ASKS=3,EMPTY_TEXTING_ASK_ENTRY=/* @__PURE__ */Object.freeze({askCount:0,nextAskAt:null,completed:false});function isTextingAskEligible(read,now){if(read.status!=="ok")return false;let{entry:entry}=read;return entry.completed||entry.askCount>=TEXTING_ASK_MAX_ASKS?false:entry.nextAskAt===null||now>=entry.nextAskAt}function applyTextingAsk(entry,now){return{askCount:Math.min(entry.askCount+1,TEXTING_ASK_MAX_ASKS),nextAskAt:now+TEXTING_ASK_SNOOZE_MS,completed:entry.completed}}function applyTextingAskSnooze(entry,now){return{...entry,nextAskAt:now+TEXTING_ASK_SNOOZE_MS}}function applyTextingAskCompleted(entry){return{...entry,completed:true}}function nextTextingAskNumber(entry){return entry.askCount<=0?1:entry.askCount===1?2:3}function entryOf(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let o=raw,{askCount:askCount,nextAskAt:nextAskAt,completed:completed}=o;return typeof askCount!="number"||!Number.isInteger(askCount)||askCount<0||nextAskAt!==null&&(typeof nextAskAt!="number"||!Number.isFinite(nextAskAt))||typeof completed!="boolean"?null:{askCount:Math.min(askCount,TEXTING_ASK_MAX_ASKS),nextAskAt:nextAskAt,completed:completed}}function parseTextingAskMap(raw){let value;try{value=JSON.parse(raw)}catch{return null}if(value===null||typeof value!="object"||Array.isArray(value))return null;let out={};for(let[key,item]of Object.entries(value)){let entry=entryOf(item);if(entry===null)return null;out[key]=entry}return out}var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/texting/ask-schedule@v1");function shared(){let host2=globalThis,state2=host2[SLOT];return state2===void 0&&(state2={sessions:/* @__PURE__ */new Map,sessionListeners:/* @__PURE__ */new Set,listeners:/* @__PURE__ */new Set,writeChain:Promise.resolve()},host2[SLOT]=state2),state2.sessionListeners===void 0&&(state2.sessionListeners=/* @__PURE__ */new Set),state2}async function load(kv){if(isInMemoryKv(kv))return{status:"unreadable"};let raw;try{raw=await kv.getItem(TEXTING_ASK_SCHEDULE_KEY)}catch{return{status:"unreadable"}}if(raw===null)try{return await kv.setItem(TEXTING_ASK_SCHEDULE_KEY,"{}"),await kv.getItem(TEXTING_ASK_SCHEDULE_KEY)===null?{status:"unreadable"}:{status:"ok",map:{}}}catch{return{status:"unreadable"}}let map=parseTextingAskMap(raw);if(map!==null)return{status:"ok",map:map};try{await kv.removeItem(TEXTING_ASK_SCHEDULE_KEY)}catch{}return{status:"unreadable"}}function subscribeTextingAskSchedule(listener){let{listeners:listeners2}=shared();return listeners2.add(listener),()=>{listeners2.delete(listener)}}function update(kv,userRef,change){let state2=shared(),run=async()=>{let loaded=await load(kv);if(loaded.status!=="ok")return;let current=loaded.map[userRef]??EMPTY_TEXTING_ASK_ENTRY;try{await kv.setItem(TEXTING_ASK_SCHEDULE_KEY,JSON.stringify({...loaded.map,[userRef]:change(current)}))}catch{return}for(let listener of[...state2.listeners])listener()},next=state2.writeChain.then(run,run);return state2.writeChain=next.catch(()=>{}),next}async function readTextingAskSchedule(kv,userRef){let loaded=await load(kv);return loaded.status!=="ok"?{status:"unreadable"}:{status:"ok",entry:loaded.map[userRef]??EMPTY_TEXTING_ASK_ENTRY}}function recordTextingAsk(kv,userRef,now=Date.now()){return update(kv,userRef,entry=>applyTextingAsk(entry,now))}function snoozeTextingAsk(kv,userRef,now=Date.now()){return update(kv,userRef,entry=>applyTextingAskSnooze(entry,now))}function markTextingAskCompleted(kv,userRef){return update(kv,userRef,applyTextingAskCompleted)}function textingAskSession(userRef){return shared().sessions.get(userRef)??null}function setTextingAskSession(userRef,entry){let state2=shared();state2.sessions.set(userRef,entry);for(let listener of[...state2.sessionListeners])listener()}function subscribeTextingAskSessions(listener){let{sessionListeners:sessionListeners}=shared();return sessionListeners.add(listener),()=>{sessionListeners.delete(listener)}}var NO_SNAPSHOT=()=>null;function useTextingGranted(){let{runtime:runtime}=useEverfurContext(),source=runtime.entitlements??null,subscribe2=useCallback(listener=>source===null?()=>{}:source.subscribe(listener),[source]),read=source===null?NO_SNAPSHOT:source.getSnapshot,snapshot=useSyncExternalStore(subscribe2,read,read);return useMemo(()=>snapshot!==null&&decideCapability("texting",snapshot.decisions,{isPending:snapshot.isPending}).enabled,[snapshot])}var IDLE=/* @__PURE__ */Object.freeze({status:"idle"});function useAskSchedule(userRef){let{runtime:runtime}=useEverfurContext(),kv=runtime.registry.services.kv,[state2,setState]=useState({user:null,value:IDLE});return useEffect(()=>{if(userRef===null)return;let live=true,read=()=>{readTextingAskSchedule(kv,userRef).then(value=>{live&&setState({user:userRef,value:{status:"ready",read:value}})})};read();let unsubscribe=subscribeTextingAskSchedule(read);return()=>{live=false,unsubscribe()}},[kv,userRef]),state2.user===userRef?state2.value:IDLE}function identityOf(texting){switch(texting.status){case"enroll":case"requesting":case"code":case"confirming":return"none";case"verified":case"optingOut":case"optedOut":return"exists";default:return"unknown"}}function useTextingAsk(options={}){let enabled=options.enabled!==false,ready=options.ready!==false,surface=options.surface??"prompt",{runtime:runtime,userRef:userRef}=useEverfurContext(),kv=runtime.registry.services.kv,granted=useTextingGranted(),schedule=useAskSchedule(enabled&&userRef!==null?userRef:null),readSession=useCallback(()=>userRef===null?null:textingAskSession(userRef),[userRef]),current=useSyncExternalStore(subscribeTextingAskSessions,readSession,readSession),update2=useCallback(entry=>{userRef!==null&&setTextingAskSession(userRef,entry)},[userRef]),mine=current!==null&&current.surface===surface,handedOff=current!==null&&current.fromPrompt===true,stage=mine?current.stage==="handoff"?"hidden":current.stage:surface==="prompt"&&handedOff?"dismissed":"hidden",now=Date.now(),scheduleEligible=schedule.status==="ready"&&isTextingAskEligible(schedule.read,now),[readFor,setReadFor]=useState(null),texting=useTextingState(userRef!==null&&readFor===userRef||stage!=="hidden"||mine),identity=identityOf(texting),{readEnabled:readEnabled,due:due}=resolveTextingAskDue({enabled:enabled,capabilityGranted:granted,hasProfile:texting.profile!==null,signedIn:userRef!==null,scheduleEligible:scheduleEligible,offeredThisSession:current!==null,identity:identity,surfaceReady:ready});useEffect(()=>{readEnabled&&userRef!==null&&setReadFor(userRef)},[readEnabled,userRef]);let askNumber=current?.askNumber??(schedule.status==="ready"&&schedule.read.status==="ok"?nextTextingAskNumber(schedule.read.entry):1);useEffect(()=>{!due||userRef===null||textingAskSession(userRef)!==null||update2({surface:surface,stage:"offered",answered:false,askNumber:askNumber})},[due,userRef,update2,askNumber,surface]),useEffect(()=>{!mine||current.stage!=="handoff"||enabled&&ready&&granted&&texting.profile!==null&&identity==="none"&&update2({...current,stage:"offered"})},[mine,current,enabled,ready,granted,texting.profile,identity,update2]);let completed=schedule.status==="ready"&&schedule.read.status==="ok"&&schedule.read.entry.completed;useEffect(()=>{userRef===null||identity!=="exists"||completed||schedule.status!=="ready"||markTextingAskCompleted(kv,userRef)},[identity,completed,schedule.status,kv,userRef]),useEffect(()=>{mine&&current.stage==="enrolling"&&texting.status==="verified"&&update2({...current,stage:"verified"})},[mine,current,texting.status,update2]);let answer=useCallback(entry=>userRef===null||entry.answered?entry:(recordTextingAsk(kv,userRef),{...entry,answered:true}),[kv,userRef]),accept=useCallback(()=>{mine&&current.stage==="offered"&&update2({...current,stage:"enrolling"})},[mine,current,update2]),close=useCallback(()=>{mine&&current.stage==="enrolling"&&update2({...current,stage:"offered"})},[mine,current,update2]),dismiss=useCallback(()=>{if(!(!mine||current.stage!=="offered"&&current.stage!=="enrolling")){if(surface==="prompt"){update2({...answer(current),surface:"chat",stage:"handoff",fromPrompt:true});return}current.fromPrompt===true&&current.answered&&userRef!==null&&snoozeTextingAsk(kv,userRef),update2({...answer(current),stage:"dismissed"})}},[mine,current,surface,update2,answer,kv,userRef]),{start:startCode}=texting,start=useCallback(async phone=>!mine||current.stage!=="enrolling"?false:(current.answered||update2(answer(current)),startCode(phone)),[mine,current,update2,answer,startCode]),brand=texting.profile?.brandName??"";return useMemo(()=>({stage:userRef===null?"hidden":stage,brand:brand,askNumber:askNumber,texting:texting,accept:accept,dismiss:dismiss,close:close,start:start}),[userRef,stage,brand,askNumber,texting,accept,dismiss,close,start])}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});function ChatTextingAskController({enabled:enabled,ready:ready,onAsk:onAsk}){let ask=useTextingAsk({enabled:enabled,ready:ready,surface:"chat"});return useEffect(()=>{callHost(onAsk,ask)},[ask,onAsk]),null}function textingAskLines(ask){return{line:TEXTING_BRAND_COPY.chatAskLine(ask.brand),accept:TEXTING_COPY.promptAccept,dismiss:TEXTING_COPY.promptDismiss,verified:TEXTING_BRAND_COPY.chatAskVerified(ask.brand)}}function ChatTextingAskComposer({ask:ask}){let theme=useEverfurTheme(),styles=useMemo(()=>makeAskStyles(theme),[theme]);/* @__PURE__ */
159
+ return jsx(AskEntry,{ask:ask,styles:styles})}function AskEntry({ask:ask,styles:styles}){let{texting:texting}=ask,{status:status,profile:profile,snapshot:snapshot}=texting,[phone,setPhone]=useState(""),[consented,setConsented]=useState(false),[code,setCode]=useState(""),[problem,setProblem]=useState(null),onNumber=status==="enroll"||status==="requesting"&&!snapshot.resending,onCode=status==="code"||status==="confirming"||status==="requesting";useEffect(()=>{setProblem(null)},[status]);let close=/* @__PURE__ */jsxs(Pressable,{onPress:ask.close,accessibilityRole:"button",accessibilityLabel:TEXTING_COPY.close,hitSlop:8,style:styles.close,testID:"texting-ask-close",children:[
160
+ /* @__PURE__ */jsx(View,{style:[styles.closeBar,styles.closeBarA]}),
161
+ /* @__PURE__ */jsx(View,{style:[styles.closeBar,styles.closeBarB]})]}),refusal=snapshot.error===null?null:/* @__PURE__ */jsxs(View,{style:styles.notice,accessibilityRole:"alert",children:[
162
+ /* @__PURE__ */jsx(Text,{style:styles.noticeText,children:textingErrorText(snapshot.error,snapshot.failedAction,snapshot.codeRefusal)}),textingSupportText(snapshot.error)===null?null:/* @__PURE__ */jsx(Text,{style:styles.footnote,children:textingSupportText(snapshot.error)})]}),inputProblem=problem===null?null:/* @__PURE__ */jsx(Text,{style:styles.noticeText,accessibilityRole:"alert",children:textingInputProblemText(problem)});if(profile===null)return null;if(status==="loading"||status==="failed"||status==="signedOut"||status==="unavailable")/* @__PURE__ */
163
+ return jsx(View,{style:styles.root,testID:"texting-ask-entry",accessibilityState:{busy:status==="loading"},children:/* @__PURE__ */jsxs(View,{style:styles.head,children:[
164
+ /* @__PURE__ */jsx(View,{style:styles.headBody,children:status==="failed"?refusal:null}),close]})});if(onNumber){let busy=status==="requesting",submit=()=>{let found=validateTextingEnroll(phone,consented);setProblem(found),found===null&&ask.start(phone)};/* @__PURE__ */
165
+ return jsxs(View,{style:styles.root,testID:"texting-ask-phone",children:[
166
+ /* @__PURE__ */jsxs(View,{style:styles.head,children:[
167
+ /* @__PURE__ */jsxs(View,{style:styles.headBody,children:[
168
+ /* @__PURE__ */jsxs(Pressable,{onPress:()=>setConsented(!consented),disabled:busy,accessibilityRole:"checkbox",accessibilityState:{checked:consented,disabled:busy},accessibilityLabel:profile.consentText,style:styles.consentRow,testID:"texting-ask-consent",children:[
169
+ /* @__PURE__ */jsx(View,{style:[styles.box,consented?styles.boxChecked:null],accessibilityElementsHidden:true,importantForAccessibility:"no",children:consented?/* @__PURE__ */jsx(Text,{style:styles.tick,children:"✓"}):null}),
170
+ /* @__PURE__ */jsx(Text,{style:styles.consentText,children:profile.consentText})]}),profile.helpContact===null?null:/* @__PURE__ */jsxs(Text,{style:styles.footnote,children:[TEXTING_COPY.helpContactLabel," ",profile.helpContact]})]}),close]}),inputProblem,refusal,
171
+ /* @__PURE__ */jsxs(View,{style:styles.pill,children:[
172
+ /* @__PURE__ */jsx(TextInput,{value:phone,onChangeText:setPhone,editable:!busy,autoFocus:true,keyboardType:"phone-pad",textContentType:"telephoneNumber",autoComplete:"tel",accessibilityLabel:TEXTING_COPY.phoneLabel,placeholder:TEXTING_COPY.phoneLabel,onSubmitEditing:submit,style:styles.field,testID:"texting-ask-phone-input"}),
173
+ /* @__PURE__ */jsx(Pressable,{onPress:submit,disabled:busy,accessibilityRole:"button",accessibilityLabel:busy?TEXTING_COPY.sendingCode:TEXTING_COPY.sendCode,accessibilityState:{disabled:busy,busy:busy},style:[styles.primary,busy?styles.dimmed:null],testID:"texting-ask-send",children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles.primaryLabel,children:busy?TEXTING_COPY.sendingCode:TEXTING_COPY.sendCode})})]})]})}if(onCode){let confirming=status==="confirming",resending=status==="requesting",busy=confirming||resending,submit=()=>{let found=validateTextingCode(code);setProblem(found),found===null&&texting.confirm(code)};/* @__PURE__ */
174
+ return jsxs(View,{style:styles.root,testID:"texting-ask-code",children:[
175
+ /* @__PURE__ */jsxs(View,{style:styles.head,children:[
176
+ /* @__PURE__ */jsxs(View,{style:styles.headBody,children:[
177
+ /* @__PURE__ */jsxs(Text,{style:styles.body,children:[TEXTING_COPY.codeSentTo," ",formatTextingPhone(snapshot.phoneE164)]}),
178
+ /* @__PURE__ */jsxs(View,{style:styles.links,children:[
179
+ /* @__PURE__ */jsx(Pressable,{onPress:()=>{setCode(""),texting.resend()},disabled:busy,accessibilityRole:"button",accessibilityState:{disabled:busy,busy:resending},style:[styles.link,busy?styles.dimmed:null],children:/* @__PURE__ */jsx(Text,{style:styles.linkLabel,children:TEXTING_COPY.requestNewCode})}),
180
+ /* @__PURE__ */jsx(Pressable,{onPress:()=>{setCode(""),texting.changeNumber()},disabled:busy,accessibilityRole:"button",accessibilityState:{disabled:busy},style:[styles.link,busy?styles.dimmed:null],children:/* @__PURE__ */jsx(Text,{style:styles.linkLabel,children:TEXTING_COPY.changeNumber})})]})]}),close]}),inputProblem,refusal,
181
+ /* @__PURE__ */jsxs(View,{style:styles.pill,children:[
182
+ /* @__PURE__ */jsx(TextInput,{value:code,onChangeText:value=>setCode(value.replace(/\D/g,"")),editable:!busy,autoFocus:true,keyboardType:"number-pad",textContentType:"oneTimeCode",autoComplete:"sms-otp",maxLength:6,accessibilityLabel:TEXTING_COPY.codeLabel,placeholder:TEXTING_COPY.codeLabel,onSubmitEditing:submit,style:[styles.field,styles.digits],testID:"texting-ask-code-input"}),
183
+ /* @__PURE__ */jsx(Pressable,{onPress:submit,disabled:busy,accessibilityRole:"button",accessibilityLabel:confirming?TEXTING_COPY.confirmingCode:TEXTING_COPY.confirmCode,accessibilityState:{disabled:busy,busy:confirming},style:[styles.primary,busy?styles.dimmed:null],testID:"texting-ask-confirm",children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles.primaryLabel,children:confirming?TEXTING_COPY.confirmingCode:TEXTING_COPY.confirmCode})})]})]})}return null}function makeAskStyles(theme){let{color:color,radius:radius,space:space,type:type,slots:slots}=theme,text3=(size,ink,weight)=>({...face(theme,weight),fontSize:size,lineHeight:Math.round(size*type.lineHeight.snug),color:ink});return StyleSheet.create({root:{gap:space.sm,width:"100%"},head:{flexDirection:"row",alignItems:"flex-start",gap:space.sm},headBody:{flex:1,minWidth:0,gap:space.xs},consentRow:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,minHeight:44},box:{width:24,height:24,borderRadius:radius.xs,borderWidth:2,borderColor:color.controlEdge,alignItems:"center",justifyContent:"center",backgroundColor:color.surface},boxChecked:{backgroundColor:color.brand,borderColor:color.brandInk},tick:text3(type.size.caption,color.text.onBrand,"bold"),consentText:{flex:1,...text3(type.size.caption,color.text.secondary,"regular")},body:text3(type.size.body,color.text.primary,"regular"),footnote:text3(type.size.caption,color.text.muted,"regular"),pill:{flexDirection:"row",alignItems:"center",gap:space.xs,minHeight:50,paddingVertical:space.xs,paddingLeft:space.md,paddingRight:space.xs,borderRadius:radius.pill,borderWidth:1.5,borderColor:color.controlEdge,backgroundColor:color.surface,...slotBox(slots.input,1)},field:{flex:1,minWidth:0,minHeight:44,padding:0,...text3(type.size.body,color.text.primary,"regular"),...slotText(slots.input)},digits:{fontVariant:["tabular-nums"]},primary:{minHeight:40,paddingHorizontal:space.md,borderRadius:radius.pill,alignItems:"center",justifyContent:"center",backgroundColor:color.brand,...slotBox(slots.primaryButton)},primaryLabel:{...text3(type.size.body,color.text.onBrand,"bold"),...slotText(slots.primaryButton)},dimmed:{opacity:.5},close:{width:44,height:44,alignItems:"center",justifyContent:"center"},closeBar:{position:"absolute",width:18,height:2,borderRadius:1,backgroundColor:color.text.muted},closeBarA:{transform:[{rotate:"45deg"}]},closeBarB:{transform:[{rotate:"-45deg"}]},links:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:space.md},link:{minHeight:44,justifyContent:"center"},linkLabel:{...text3(type.size.caption,color.linkInk,"bold"),...slotText(slots.link)},notice:{gap:space.xs},noticeText:text3(type.size.caption,color.errorRed,"regular")})}var OPEN=/* @__PURE__ */new Set(["offered","enrolling"]);function EverfurTextingPrompt({onResolved:onResolved}){let introOpen=useIntroOpen(),ask=useTextingAsk({surface:"prompt",ready:!introOpen}),theme=useEverfurTheme(),styles=useMemo(()=>makePromptStyles(theme),[theme]),entryStyles=useMemo(()=>makeAskStyles(theme),[theme]),shown=useRef(false),[resolved,setResolved]=useState(false);OPEN.has(ask.stage)&&(shown.current=true);let open=shown.current&&(OPEN.has(ask.stage)||ask.stage==="verified")&&!resolved&&!introOpen,finish=()=>{resolved||(ask.stage==="verified"?(setResolved(true),callHost(onResolved,"verified")):ask.dismiss())};if(useEffect(()=>{shown.current&&ask.stage==="dismissed"&&!resolved&&(setResolved(true),callHost(onResolved,"dismissed"))},[ask.stage,onResolved,resolved]),!open)return null;let title=ask.stage==="verified"?TEXTING_COPY.verifiedTitle:TEXTING_BRAND_COPY.promptTitle(ask.brand);/* @__PURE__ */
184
+ return jsx(Modal,{transparent:true,visible:true,animationType:theme.motion.reducedMotion?"none":"fade",onRequestClose:finish,children:/* @__PURE__ */jsxs(View,{style:styles.backdrop,children:[
185
+ /* @__PURE__ */jsx(Pressable,{style:ABSOLUTE_FILL,accessibilityRole:"button",accessibilityLabel:TEXTING_COPY.close,onPress:finish}),
186
+ /* @__PURE__ */jsxs(View,{style:styles.sheet,accessibilityViewIsModal:true,testID:"everfur-texting-prompt",children:[
187
+ /* @__PURE__ */jsx(Text,{style:styles.title,accessibilityRole:"header",children:title}),ask.stage==="offered"?/* @__PURE__ */jsxs(Fragment,{children:[
188
+ /* @__PURE__ */jsx(Text,{style:styles.body,children:TEXTING_COPY.promptBody}),
189
+ /* @__PURE__ */jsxs(View,{style:styles.actions,children:[
190
+ /* @__PURE__ */jsx(Pressable,{onPress:ask.accept,accessibilityRole:"button",accessibilityLabel:TEXTING_COPY.promptAccept,style:styles.primary,testID:"texting-prompt-accept",children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles.primaryLabel,children:TEXTING_COPY.promptAccept})}),
191
+ /* @__PURE__ */jsx(Pressable,{onPress:ask.dismiss,accessibilityRole:"button",accessibilityLabel:TEXTING_COPY.promptDismiss,style:styles.secondary,testID:"texting-prompt-dismiss",children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles.secondaryLabel,children:TEXTING_COPY.promptDismiss})})]})]}):null,ask.stage==="enrolling"?/* @__PURE__ */jsx(AskEntry,{ask:ask,styles:entryStyles}):null,ask.stage==="verified"?/* @__PURE__ */jsxs(Fragment,{children:[
192
+ /* @__PURE__ */jsx(Text,{style:styles.body,children:TEXTING_BRAND_COPY.chatAskVerified(ask.brand)}),
193
+ /* @__PURE__ */jsx(View,{style:styles.actions,children:/* @__PURE__ */jsx(Pressable,{onPress:finish,accessibilityRole:"button",accessibilityLabel:TEXTING_COPY.close,style:styles.secondary,testID:"texting-prompt-close",children:/* @__PURE__ */jsx(Text,{tier:"control",style:styles.secondaryLabel,children:TEXTING_COPY.close})})})]}):null]})]})})}function makePromptStyles(theme){let{color:color,radius:radius,space:space,type:type,slots:slots}=theme,dialogText=slotText(slots.dialog),text3=(size,ink,weight)=>({...face(theme,weight),fontSize:size,lineHeight:Math.round(size*type.lineHeight.normal),color:ink}),button={minHeight:48,paddingHorizontal:space.lg,borderRadius:radius.pill,alignItems:"center",justifyContent:"center"};return StyleSheet.create({backdrop:{flex:1,justifyContent:"center",paddingHorizontal:space.lg,backgroundColor:"rgba(0,0,0,0.4)"},sheet:{width:"100%",maxWidth:480,alignSelf:"center",backgroundColor:color.surface,borderRadius:radius.xl,paddingHorizontal:space.lg,paddingTop:space.xl,paddingBottom:space.lg,maxHeight:"88%",gap:space.md,...slotBox(slots.dialog)},title:{...text3(type.size.heading,color.text.primary,"bold"),...headingFace(theme,"bold"),textAlign:"center",...dialogText},body:{...text3(type.size.body,color.text.secondary,"regular"),textAlign:"center",...dialogText},actions:{gap:space.xs},primary:{...button,backgroundColor:color.brand,...slotBox(slots.primaryButton)},primaryLabel:{...text3(type.size.body,color.text.onBrand,"bold"),...slotText(slots.primaryButton)},secondary:button,secondaryLabel:text3(type.size.body,color.text.muted,"bold")})}export{COPY_PLACEHOLDER_PREFIX,ChatTextingAskComposer,ChatTextingAskController,EVERFUR_TEXTING_STATUSES,EverfurTextingOptIn,EverfurTextingPrompt,TEXTING_ASK_MAX_ASKS,TEXTING_ASK_SCHEDULE_KEY,TEXTING_ASK_SNOOZE_MS,TEXTING_BRAND_COPY,TEXTING_CODE_PATTERN,TEXTING_COPY,TEXTING_COPY_PLACEHOLDERS,TEXTING_UI_CODE_LENGTH,TextingController,createTextingRepository,createTextingRepositoryOver,formatTextingPhone,isE164,isTextingAskEligible,parseTextingProfile,resolveTextingAskDue,textingAskLines,textingAskThreadReady,textingErrorText,textingIdentityFromWire,textingInputProblemText,textingOptedOutBody,textingReasonOf,textingSupportText,toTextingE164,useEverfurTexting,useEverfurTextingProfile,useEverfurTextingRepository,useTextingAsk,validateTextingCode,validateTextingEnroll};