@everfur/sdk 1.6.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/dist/{Chat.d-B4GybUU4.d.ts → Chat.d-BIr_4AJt.d.ts} +1 -1
  2. package/dist/{Chat.d-DPM2ncxi.d.cts → Chat.d-BhevtXn9.d.cts} +1 -1
  3. package/dist/{DepthViews.d-BGspxovy.d.cts → DepthViews.d-C8KdfzwR.d.cts} +1 -1
  4. package/dist/{DepthViews.d-BaLh7Lsi.d.cts → DepthViews.d-DWQ-J208.d.cts} +1 -1
  5. package/dist/{DepthViews.d-BIHVrf9r.d.ts → DepthViews.d-DYVUq4Xk.d.ts} +1 -1
  6. package/dist/{DepthViews.d-CEVk9poG.d.ts → DepthViews.d-oKr9R0Ql.d.ts} +1 -1
  7. package/dist/{IntakeMedia.d-CwSkSLNM.d.ts → IntakeMedia.d-B-ZZK6vd.d.ts} +1 -1
  8. package/dist/{IntakeMedia.d-LRXO38_z.d.cts → IntakeMedia.d-CuVkzIsO.d.cts} +1 -1
  9. package/dist/{IntakeMedia.d-DmaeGU6T.d.cts → IntakeMedia.d-CyF6NPHx.d.cts} +1 -1
  10. package/dist/{IntakeMedia.d-Dyb9R8b0.d.ts → IntakeMedia.d-vU8g9OM5.d.ts} +1 -1
  11. package/dist/{RecordsPage.d-D10RIgdc.d.ts → RecordsPage.d-DU8Nswzh.d.ts} +1 -1
  12. package/dist/{RecordsPage.d-DbhYNSbq.d.cts → RecordsPage.d-DzPhqMHW.d.cts} +1 -1
  13. package/dist/animations/index.d.cts +3 -3
  14. package/dist/animations/index.d.ts +3 -3
  15. package/dist/{attachments.d-CF4lLuGK.d.cts → attachments.d-0nOPDIng.d.cts} +1 -1
  16. package/dist/{attachments.d-BlukNfIf.d.ts → attachments.d-BlyI-RCY.d.ts} +1 -1
  17. package/dist/{bookingCopy.d-Bn8bdo89.d.ts → bookingCopy.d-ClL8OxBS.d.ts} +3 -3
  18. package/dist/{bookingCopy.d-Dg7bPM-U.d.cts → bookingCopy.d-DUVqhF5f.d.cts} +3 -3
  19. package/dist/{branding.d-XrZYClN4.d.ts → branding.d-D0LV3aFE.d.ts} +1 -1
  20. package/dist/{branding.d-CqDLKj1U.d.cts → branding.d-DzSPLZKl.d.cts} +1 -1
  21. package/dist/{casesRepository.d-CVuKTkJo.d.cts → casesRepository.d-DnanKXJ1.d.cts} +1 -1
  22. package/dist/{casesRepository.d-Dn1fK1b2.d.ts → casesRepository.d-_4QucKVC.d.ts} +1 -1
  23. package/dist/chat/index.cjs +239 -238
  24. package/dist/chat/index.d.cts +11 -11
  25. package/dist/chat/index.d.ts +11 -11
  26. package/dist/chat/index.js +241 -240
  27. package/dist/chat/lite/index.cjs +239 -238
  28. package/dist/chat/lite/index.d.cts +11 -11
  29. package/dist/chat/lite/index.d.ts +11 -11
  30. package/dist/chat/lite/index.js +239 -238
  31. package/dist/{chatHandoffToken.d-zdp23Ukr.d.ts → chatHandoffToken.d-BoZGGbIB.d.ts} +5 -5
  32. package/dist/{chatHandoffToken.d-Cap2z62P.d.cts → chatHandoffToken.d-DhhGdLNH.d.cts} +5 -5
  33. package/dist/{checkin.d-CuIUahcd.d.cts → checkin.d-DB-HlK7r.d.cts} +9 -4
  34. package/dist/{checkin.d-BoZXWjxX.d.ts → checkin.d-DogrR06X.d.ts} +9 -4
  35. package/dist/{chunk-ZSCVH4UW.js → chunk-6E3J6IVM.js} +16 -16
  36. package/dist/{chunk-CQUKIPRU.js → chunk-J5ZUBY3S.js} +1 -1
  37. package/dist/{chunk-RF4N4WUN.js → chunk-LPHBCDJP.js} +18 -18
  38. package/dist/{chunk-DBQYQLJT.js → chunk-ULQDOC75.js} +1 -1
  39. package/dist/client/index.cjs +28 -27
  40. package/dist/client/index.d.cts +13 -13
  41. package/dist/client/index.d.ts +13 -13
  42. package/dist/client/index.js +25 -24
  43. package/dist/{clinicBatch.d-C0xx5L4j.d.cts → clinicBatch.d-BvPF6vXS.d.cts} +2 -2
  44. package/dist/{clinicBatch.d-DNi4UURs.d.ts → clinicBatch.d-CF0GIvpx.d.ts} +2 -2
  45. package/dist/{config.d-B7Z-KTGq.d.ts → config.d-Bc41Ax6M.d.ts} +5 -1
  46. package/dist/{config.d-ClAI2RZ6.d.cts → config.d-Bn6GEGfl.d.cts} +5 -1
  47. package/dist/consent/index.d.cts +5 -5
  48. package/dist/consent/index.d.ts +5 -5
  49. package/dist/{context.d-D7zX6Q0J.d.ts → context.d-0QfLaI3W.d.ts} +5 -5
  50. package/dist/{context.d-guaLkx5t.d.cts → context.d-CyQpedoU.d.cts} +5 -5
  51. package/dist/{copy.d--F5A9cXK.d.cts → copy.d-B55PpLxr.d.cts} +2 -2
  52. package/dist/{copy.d-DmxuFJFe.d.ts → copy.d-B8wIE6cH.d.ts} +2 -2
  53. package/dist/core/index.cjs +32 -31
  54. package/dist/core/index.d.cts +16 -16
  55. package/dist/core/index.d.ts +16 -16
  56. package/dist/core/index.js +32 -31
  57. package/dist/{depth.d-CgzYE6_n.d.ts → depth.d-CrtZXnLy.d.ts} +2 -2
  58. package/dist/{depth.d-DLaP0o8Y.d.cts → depth.d-Cxz6VisZ.d.cts} +2 -2
  59. package/dist/{entitlementRepository.d-CkUTlVAb.d.ts → entitlementRepository.d-BaZTIe1B.d.ts} +3 -3
  60. package/dist/{entitlementRepository.d-DVTp-BB9.d.cts → entitlementRepository.d-YeNG2TKI.d.cts} +3 -3
  61. package/dist/{focus.d-u-HYvim0.d.ts → focus.d-520VEHKB.d.ts} +1 -1
  62. package/dist/{focus.d-CLTjm6In.d.cts → focus.d-DoempN1I.d.cts} +1 -1
  63. package/dist/health-plan/index.cjs +236 -235
  64. package/dist/health-plan/index.d.cts +15 -15
  65. package/dist/health-plan/index.d.ts +15 -15
  66. package/dist/health-plan/index.js +236 -235
  67. package/dist/{healthPlanRepository.d-CwRXeoM7.d.ts → healthPlanRepository.d-BHu9LO0r.d.ts} +2 -2
  68. package/dist/{healthPlanRepository.d-B22kjrYa.d.cts → healthPlanRepository.d-tUR1f_5s.d.cts} +2 -2
  69. package/dist/{idempotency.d-DrxKLPPe.d.cts → idempotency.d-CcFLvzYW.d.cts} +1 -1
  70. package/dist/{idempotency.d-CbB07p64.d.ts → idempotency.d-CvqKG3Uq.d.ts} +1 -1
  71. package/dist/{identity.d-D4VtpqRr.d.ts → identity.d-Bex_XJZx.d.ts} +1 -1
  72. package/dist/{identity.d-DDpXOtas.d.cts → identity.d-Dm0Buvn8.d.cts} +1 -1
  73. package/dist/{inbox.d-B2JXK0uI.d.ts → inbox.d-9ajb0oiJ.d.ts} +1 -1
  74. package/dist/{inbox.d-CwA1ogzV.d.cts → inbox.d-CGCYOZIq.d.cts} +1 -1
  75. package/dist/index.cjs +362 -361
  76. package/dist/index.d.cts +17 -17
  77. package/dist/index.d.ts +17 -17
  78. package/dist/index.js +253 -252
  79. package/dist/{introEvents.d-DW3gLljE.d.ts → introEvents.d-CuVaufTy.d.ts} +1 -1
  80. package/dist/{introEvents.d-B7acmGwf.d.cts → introEvents.d-DU6feqx4.d.cts} +1 -1
  81. package/dist/{layout.d-C8y_ki1V.d.ts → layout.d-BQ5IVS-m.d.ts} +1 -1
  82. package/dist/{layout.d-DfaFM_lp.d.cts → layout.d-CSPr33BP.d.cts} +1 -1
  83. package/dist/notifications/inbox/index.d.cts +6 -6
  84. package/dist/notifications/inbox/index.d.ts +6 -6
  85. package/dist/notifications/index.d.cts +7 -7
  86. package/dist/notifications/index.d.ts +7 -7
  87. package/dist/{optInView.d-Cps7aLQN.d.ts → optInView.d-DpGXnpGw.d.ts} +21 -3
  88. package/dist/{optInView.d-ChJyJMBA.d.cts → optInView.d-dLjrI3co.d.cts} +21 -3
  89. package/dist/{pets.d-BpLObpfM.d.ts → pets.d-CHdSIoBf.d.ts} +1 -1
  90. package/dist/{pets.d-DXhzTNuI.d.cts → pets.d-jnhrJhqm.d.cts} +1 -1
  91. package/dist/{petsRepository.d-ai_tZ3lu.d.cts → petsRepository.d-BeKRiNao.d.cts} +1 -1
  92. package/dist/{petsRepository.d-_QfM7F6T.d.ts → petsRepository.d-BjwB1vku.d.ts} +1 -1
  93. package/dist/{presentation.d-BkIvMtIl.d.cts → presentation.d-Br3TnwA6.d.cts} +17 -1
  94. package/dist/{presentation.d-BkIvMtIl.d.ts → presentation.d-Br3TnwA6.d.ts} +17 -1
  95. package/dist/records/depth/index.d.cts +9 -9
  96. package/dist/records/depth/index.d.ts +9 -9
  97. package/dist/records/index.cjs +237 -228
  98. package/dist/records/index.d.cts +39 -12
  99. package/dist/records/index.d.ts +39 -12
  100. package/dist/records/index.js +155 -146
  101. package/dist/{requestFunnel.d-DKBPTpsy.d.ts → requestFunnel.d-C_NMgz9R.d.ts} +2 -2
  102. package/dist/{requestFunnel.d-BwZDfWVD.d.cts → requestFunnel.d-DoJWLySc.d.cts} +2 -2
  103. package/dist/{route.d-QBCoO62z.d.cts → route.d-BW2abFVK.d.cts} +2 -2
  104. package/dist/{route.d-B3u14HJT.d.ts → route.d-Olr_gXaa.d.ts} +2 -2
  105. package/dist/{runtimeTypes.d-hjN6xvxm.d.ts → runtimeTypes.d-Bp2VW6YE.d.ts} +6 -6
  106. package/dist/{runtimeTypes.d-BSxuUCOX.d.cts → runtimeTypes.d-StvJY45N.d.cts} +6 -6
  107. package/dist/{screenProps.d-fHBKArt_.d.ts → screenProps.d-BTLSji0N.d.ts} +1 -1
  108. package/dist/{screenProps.d-6xmE1C-V.d.cts → screenProps.d-B_5Bh7aQ.d.cts} +1 -1
  109. package/dist/server/events/index.cjs +2 -2
  110. package/dist/server/events/index.d.cts +19 -5
  111. package/dist/server/events/index.d.ts +19 -5
  112. package/dist/server/events/index.js +2 -2
  113. package/dist/server/index.cjs +1 -1
  114. package/dist/server/index.d.cts +3 -3
  115. package/dist/server/index.d.ts +3 -3
  116. package/dist/server/index.js +1 -1
  117. package/dist/shop/index.d.cts +3 -3
  118. package/dist/shop/index.d.ts +3 -3
  119. package/dist/slots/index.cjs +200 -199
  120. package/dist/slots/index.d.cts +5 -5
  121. package/dist/slots/index.d.ts +5 -5
  122. package/dist/slots/index.js +200 -199
  123. package/dist/tabs/index.cjs +200 -190
  124. package/dist/tabs/index.d.cts +68 -11
  125. package/dist/tabs/index.d.ts +68 -11
  126. package/dist/tabs/index.js +201 -191
  127. package/dist/tabs-bar/index.cjs +247 -0
  128. package/dist/tabs-bar/index.d.cts +10 -0
  129. package/dist/tabs-bar/index.d.ts +10 -0
  130. package/dist/tabs-bar/index.js +247 -0
  131. package/dist/{tabsModel.d-D9GWPFrL.d.ts → tabsModel.d-B4MSQB57.d.cts} +5 -2
  132. package/dist/{tabsModel.d-D9GWPFrL.d.cts → tabsModel.d-C8pd-DP3.d.ts} +5 -2
  133. package/dist/televet/booking/index.cjs +147 -145
  134. package/dist/televet/booking/index.d.cts +10 -10
  135. package/dist/televet/booking/index.d.ts +10 -10
  136. package/dist/televet/booking/index.js +163 -161
  137. package/dist/televet/call/index.cjs +52 -52
  138. package/dist/televet/call/index.d.cts +5 -0
  139. package/dist/televet/call/index.d.ts +5 -0
  140. package/dist/televet/call/index.js +25 -25
  141. package/dist/televet/index.d.cts +3 -3
  142. package/dist/televet/index.d.ts +3 -3
  143. package/dist/{televetGlobal.d-gZrXPaLl.d.cts → televetGlobal.d-B_I_fy7O.d.cts} +9 -0
  144. package/dist/{televetGlobal.d-DkJkV55Y.d.ts → televetGlobal.d-DN7o45WJ.d.ts} +9 -0
  145. package/dist/testing/index.cjs +3 -3
  146. package/dist/testing/index.d.cts +1 -1
  147. package/dist/testing/index.d.ts +1 -1
  148. package/dist/testing/index.js +3 -3
  149. package/dist/testing/rn/index.d.cts +9 -9
  150. package/dist/testing/rn/index.d.ts +9 -9
  151. package/dist/testing/web/index.d.cts +9 -9
  152. package/dist/testing/web/index.d.ts +9 -9
  153. package/dist/texting/index.cjs +32 -27
  154. package/dist/texting/index.d.cts +5 -5
  155. package/dist/texting/index.d.ts +5 -5
  156. package/dist/texting/index.js +52 -47
  157. package/dist/{threadOptions.d-NSlFx-Lp.d.ts → threadOptions.d-D_3hk79R.d.ts} +5 -5
  158. package/dist/{threadOptions.d-Dc57dm7h.d.cts → threadOptions.d-D_GU6lp9.d.cts} +5 -5
  159. package/dist/{timelineRows.d-CthNM5hV.d.ts → timelineRows.d-BbVuARtc.d.ts} +1 -1
  160. package/dist/{timelineRows.d-7w8NsNi4.d.cts → timelineRows.d-BiLAAbYl.d.cts} +1 -1
  161. package/dist/{typeStyle.d-8mcLhtbH.d.ts → typeStyle.d-DSk99BuZ.d.ts} +1 -1
  162. package/dist/{typeStyle.d-CLrQZW-r.d.cts → typeStyle.d-DqR6mWCF.d.cts} +1 -1
  163. package/dist/{useHealthPlanSubscription.d-CV7M21HS.d.ts → useHealthPlanSubscription.d-CpE6l1VW.d.ts} +3 -3
  164. package/dist/{useHealthPlanSubscription.d-SA9-SuKe.d.cts → useHealthPlanSubscription.d-DRiWDJXq.d.cts} +3 -3
  165. package/dist/{useInboxUnread.d-0DrQPn7J.d.ts → useInboxUnread.d-BV7PkWDH.d.ts} +1 -1
  166. package/dist/{useInboxUnread.d-CRcOTkmu.d.cts → useInboxUnread.d-CElyXBkY.d.cts} +1 -1
  167. package/dist/{usePresentation.d-BJzFicRQ.d.cts → usePresentation.d-BcazazQH.d.cts} +3 -3
  168. package/dist/{usePresentation.d-DgSGIWS-.d.ts → usePresentation.d-CMOypLlH.d.ts} +3 -3
  169. package/dist/{useRecordsDepth.d-ZX2rhcUx.d.ts → useRecordsDepth.d-Bka4KQhq.d.ts} +1 -1
  170. package/dist/{useRecordsDepth.d-C9W45gwS.d.cts → useRecordsDepth.d-TgmpxKdX.d.cts} +1 -1
  171. package/dist/{useUnread.d-4SbFChbd.d.ts → useUnread.d-CGqaP-dB.d.ts} +27 -5
  172. package/dist/{useUnread.d-B0YhhR_D.d.cts → useUnread.d-DVVnYNPU.d.cts} +27 -5
  173. package/dist/{view.d-3lxzyJlL.d.cts → view.d-CwruYhQy.d.cts} +3 -3
  174. package/dist/{view.d-DRiYNQJ8.d.ts → view.d-DamH8TQF.d.ts} +3 -3
  175. package/dist/web/consent/index.d.cts +5 -5
  176. package/dist/web/consent/index.d.ts +5 -5
  177. package/dist/web/health-plan/index.cjs +9 -8
  178. package/dist/web/health-plan/index.d.cts +16 -16
  179. package/dist/web/health-plan/index.d.ts +16 -16
  180. package/dist/web/health-plan/index.js +49 -48
  181. package/dist/web/inbox/index.d.cts +7 -7
  182. package/dist/web/inbox/index.d.ts +7 -7
  183. package/dist/web/index.cjs +185 -184
  184. package/dist/web/index.d.cts +32 -32
  185. package/dist/web/index.d.ts +32 -32
  186. package/dist/web/index.js +179 -178
  187. package/dist/web/intro/index.d.cts +7 -7
  188. package/dist/web/intro/index.d.ts +7 -7
  189. package/dist/web/notifications/index.d.cts +6 -6
  190. package/dist/web/notifications/index.d.ts +6 -6
  191. package/dist/web/records/depth/index.d.cts +9 -9
  192. package/dist/web/records/depth/index.d.ts +9 -9
  193. package/dist/web/records/index.d.cts +11 -11
  194. package/dist/web/records/index.d.ts +11 -11
  195. package/dist/web/records-sheet/index.cjs +111 -110
  196. package/dist/web/records-sheet/index.js +111 -110
  197. package/dist/web/shop/index.cjs +1 -1
  198. package/dist/web/shop/index.d.cts +3 -3
  199. package/dist/web/shop/index.d.ts +3 -3
  200. package/dist/web/shop/index.js +1 -1
  201. package/dist/web/televet/booking/index.cjs +3 -3
  202. package/dist/web/televet/booking/index.d.cts +10 -10
  203. package/dist/web/televet/booking/index.d.ts +10 -10
  204. package/dist/web/televet/booking/index.js +69 -69
  205. package/dist/web/televet/call/index.cjs +1 -1
  206. package/dist/web/televet/call/index.js +1 -1
  207. package/dist/web/televet/index.d.cts +3 -3
  208. package/dist/web/televet/index.d.ts +3 -3
  209. package/dist/web/texting/index.cjs +34 -29
  210. package/dist/web/texting/index.d.cts +5 -5
  211. package/dist/web/texting/index.d.ts +5 -5
  212. package/dist/web/texting/index.js +45 -40
  213. package/dist/web/ui/index.cjs +1 -1
  214. package/dist/web/ui/index.js +41 -41
  215. package/package.json +16 -1
  216. package/tabs-bar/package.json +8 -0
@@ -600,4 +600,4 @@ return t.jsx(PlacedRoute,{orderIds:e.orderIds},e.orderIds.join(","));case"addres
600
600
  return t.jsx(LiveAddress,{...e.then?{then:e.then}:{}});case"card":/* @__PURE__ */
601
601
  return t.jsx(LiveCard,{handoff:r,...e.then?{then:e.then}:{}},a);case"buy":/* @__PURE__ */
602
602
  return t.jsx(LiveBuy,{route:e});case"consent":/* @__PURE__ */
603
- return t.jsx(LiveConsent,{route:e})}}var ro="1.6.1";var ao=/* @__PURE__ */Object.freeze({k1:"X4wc1hwVONs4I9Vmclo9ExrfPZlH8-tgY7NmzxuA5lI"});function no(e,t){let i=Object.keys(t).sort().map(e=>`${e}=${t[e]}`).join(",");return`v${1}|${e}|${i}`}var so=no(ro,ao);var oo=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeRenderer@${so}`),lo=globalThis;function co(t,i){let r=lo[oo];return r===void 0?e.createElement(t.bundled,i):r(t,i)}var uo={part:"shop",name:"EverfurShop",bundled:EverfurShop,hostSubpaths:{"@everfur/sdk/web/shop/orders-v2":()=>import("@everfur/sdk/web/shop/orders-v2")}};function EverfurShop2(e){return co(uo,e)}function po(e,t){let i=globalThis.URL;if(typeof i=="function"){let r;try{r=t===void 0?new i(e):new i(e,t)}catch{return null}try{if(r.protocol)return r}catch{}}return go(e)}var fo=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,mo=/[\s\u0000-\u001f\u007f\\]/,ho={"http:":"80","https:":"443"};function go(e,t){let i=e.trim();let r=mo.test(i)?null:fo.exec(i);if(r===null)return null;let[,a="",n="",s="",o="",l="",c="",d="",u=""]=r,p=`${a.toLowerCase()}:`,f=Number(l);if(f>65535)return null;let m=l===""||String(f)===ho[p]?"":String(f),h=ho[p]!==void 0,g=o.toLowerCase()+(m&&`:${m}`),b=c||(h?"/":""),x=n||s?`${n}${s&&`:${s}`}@`:"";return{href:`${p}//${x}${g}${b}${d}${u}`,protocol:p,username:n,password:s,hostname:o.toLowerCase(),port:m,origin:h?`${p}//${g}`:"null",pathname:b,search:d==="?"?"":d,hash:u==="#"?"":u}}var bo=class _OmsWireError extends Error{constructor(e){super(`OMS answer could not be read: ${e}`);this.field=e;this.name="OmsWireError",Object.setPrototypeOf(this,_OmsWireError.prototype)}};function xo(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new bo(t);return e}function vo(e,t){if(e==null)return[];if(!Array.isArray(e))throw new bo(t);return e}function yo(e,t,i=t){let r=e[t];if(typeof r!="string"||r.length===0)throw new bo(i);return r}function wo(e,t){let i=e[t];return typeof i=="string"&&i.length>0?i:null}function ko(e,t,i=t){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))throw new bo(i);return Math.trunc(r)}function _o(e,t){let i=e[t];return typeof i=="number"&&Number.isFinite(i)?Math.trunc(i):null}function jo(e,t){return e[t]===true}function No(e){if(!e||typeof e!="object")return null;let t=e.pet_id;return typeof t=="string"&&t.length>0?t:null}var zo=["each","gram","milliliter"],$o=["ground","two_day","next_day"];function Co(e){let t=e.pack_unit;return typeof t=="string"&&zo.includes(t)?t:null}function So(e){return typeof e=="string"&&$o.includes(e)?e:null}function Io(e,t){let i=wo(e,t);return i&&po(i)?.protocol==="https:"?i:null}function To(e,t){let i=e[t];return typeof i=="number"&&Number.isFinite(i)?i:null}function Fo(e,t){let i=wo(e,t);return i&&/^\d{4}-\d{2}-\d{2}$/.test(i)?i:null}function Po(e,t){let i=e[t];return typeof i=="boolean"?i:null}var Lo=["pharmacy","everfur_box"];function Ao(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,i=_o(t,"units_left"),r=wo(t,"unit_label"),a=To(t,"daily_units"),n=Fo(t,"runs_out_on");return i===null||i<0||!r||a===null||a<=0||!n?null:{unitsLeft:i,unitLabel:r,dailyUnits:a,runsOutOn:n,refillArrivesOn:Fo(t,"refill_arrives_on")}}function Eo(e){if(e===null||typeof e!="object"||Array.isArray(e))return[];let t=e,i=wo(t,"key");return i?[{key:i,doneAt:wo(t,"done_at")}]:[]}function Oo(e){let t=xo(e,"shop-config"),i=t.delivery&&typeof t.delivery=="object"?t.delivery:null,r=wo(t,"stripe_publishable_key");return{recurringTermsVersion:wo(t,"recurring_terms_version"),recurringTermsUrl:Io(t,"recurring_terms_url"),stripePublishableKey:r&&/^pk_(test|live)_[A-Za-z0-9]+$/.test(r)?r:null,delivery:i?{firstFill:So(i.first_fill),refill:So(i.refill)}:null,rxContactMissing:Array.isArray(t.rx_contact_missing)?t.rx_contact_missing.filter(e=>typeof e=="string"):null,freeShippingThresholdCents:_o(t,"free_shipping_threshold_cents"),firstRxDiscountCents:_o(t,"first_rx_discount_cents")}}function Bo(e){let t=xo(e,"offer"),i=t.pack_quantity;return{offerId:yo(t,"offer_id"),sku:wo(t,"sku")??"",title:yo(t,"title"),fulfillmentType:wo(t,"fulfillment_type")??"physical",requiresRx:jo(t,"requires_rx"),compounded:jo(t,"compounded"),packQuantity:typeof i=="string"&&/^\d+(\.\d+)?$/.test(i)?i:null,packUnit:Co(t),price:_o(t,"price"),imageUrl:Io(t,"image_url")}}function Mo(e){let t=xo(e,"offers");return{offers:vo(t.offers,"offers").map(Bo),nextCursor:wo(t,"next_cursor")}}function Ho(e){let t=xo(e,"quote");return{lines:vo(t.lines,"lines").map(e=>{let t=xo(e,"line");return{offerId:yo(t,"offer_id"),quantity:ko(t,"quantity"),petId:No(t.pet),unitPrice:ko(t,"unit_price"),discount:_o(t,"discount")??0,tax:_o(t,"tax")??0,whenFilledDiscountCents:_o(t,"when_filled_discount_cents"),isRx:Po(t,"is_rx"),chargedWhenFilled:Po(t,"charged_when_filled")}}),shipping:ko(t,"shipping"),tax:_o(t,"tax")??0,total:ko(t,"total"),expiresAt:yo(t,"expires_at"),whenFilledDiscountCents:_o(t,"when_filled_discount_cents"),dueTodayCents:_o(t,"due_today_cents"),dueWhenFilledCents:_o(t,"due_when_filled_cents"),shipsOn:Fo(t,"ships_on"),arrivesOn:Fo(t,"arrives_on")}}function qo(e){let t=xo(e,"checkout");return{checkoutId:yo(t,"checkout_id"),state:wo(t,"state")??"draft",orderIds:vo(t.order_ids,"order_ids").filter(e=>typeof e=="string"),createdAt:wo(t,"created_at")??"",total:ko(t,"total"),shipping:_o(t,"shipping")??0,tax:_o(t,"tax")??0}}function Do(e){let t=xo(e,"confirmation");return{checkoutId:yo(t,"checkout_id"),resale:vo(t.resale,"resale").map(e=>{let t=xo(e,"resale"),i=yo(t,"outcome");if(i!=="confirmed"&&i!=="action_required")throw new bo("resale.outcome");let r=wo(t,"payer_action");if(i==="action_required"&&!r)throw new bo("resale.payer_action");return{outcome:i,orderId:yo(t,"order_id"),payerAction:i==="confirmed"?null:r}})}}function Ro(e){let t=xo(e,"order"),i=t.reference&&typeof t.reference=="object"?t.reference:null;return{orderId:yo(t,"order_id"),referenceNumber:i?wo(i,"number"):null,status:yo(t,"status"),total:ko(t,"total"),placedAt:wo(t,"placed_at"),itemCount:_o(t,"item_count"),items:Array.isArray(t.items)?t.items.flatMap(Wo):null,fulfiller:Lo.includes(wo(t,"fulfiller")??"")?t.fulfiller:null,arrivesBy:Fo(t,"arrives_by"),steps:Array.isArray(t.steps)?t.steps.flatMap(Eo):null,currentStep:wo(t,"current_step"),statusLineKey:wo(t,"status_line_key"),prescriberName:wo(t,"prescriber_name")}}function Wo(e){if(e===null||typeof e!="object"||Array.isArray(e))return[];let t=e,i=wo(t,"offer_id"),r=wo(t,"title"),a=_o(t,"quantity");return i&&r&&a!==null?[{offerId:i,title:r,quantity:a,imageUrl:Io(t,"image_url")}]:[]}function Uo(e){if(e===null||typeof e!="object"||Array.isArray(e))return[];let t=e,i=wo(t,"key");return i?[{key:i,done:t.done===true,at:wo(t,"at")}]:[]}function Vo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;try{return Yo(e)}catch{return null}}function Go(e){let t=xo(e,"orders");return{orders:vo(t.orders,"orders").map(Ro),nextCursor:wo(t,"next_cursor")}}function Ko(e){let t=xo(e,"line"),i=t.pack_quantity;return{lineId:yo(t,"line_id"),offerId:yo(t,"offer_id"),sku:wo(t,"sku")??"",title:yo(t,"title"),requiresRx:jo(t,"requires_rx"),compounded:jo(t,"compounded"),packQuantity:typeof i=="string"&&/^\d+(\.\d+)?$/.test(i)?i:null,packUnit:Co(t),quantity:ko(t,"quantity"),unitPrice:ko(t,"unit_price"),discount:_o(t,"discount")??0,tax:_o(t,"tax")??0,fulfillmentType:wo(t,"fulfillment_type")??"physical",petId:No(t.pet),imageUrl:Io(t,"image_url")}}function Yo(e){let t=xo(e,"tracking");return{carrier:wo(t,"carrier"),trackingNumber:wo(t,"tracking_number"),status:yo(t,"status"),occurredAt:wo(t,"occurred_at"),trackingUrl:Io(t,"tracking_url"),deliveryBy:wo(t,"delivery_by")}}function Xo(e){let t=xo(e,"shipment");return{shipmentId:yo(t,"shipment_id"),state:yo(t,"state"),lines:vo(t.lines,"shipment.lines").map(e=>{let t=xo(e,"shipment.line");return{lineId:yo(t,"line_id"),quantity:ko(t,"quantity")}}),tracking:vo(t.tracking,"tracking").map(Yo)}}function Qo(e){let t=xo(e,"order");return{summary:Ro(t.summary),lines:vo(t.lines,"lines").map(Ko),shipping:_o(t,"shipping")??0,shippingTax:_o(t,"shipping_tax")??0,shipments:vo(t.shipments,"shipments").map(Xo),canCancel:jo(t,"can_cancel"),canReturn:jo(t,"can_return"),canPay:jo(t,"can_pay"),paymentStatus:wo(t,"payment_status"),refunds:vo(t.refunds,"refunds").map(e=>{let t=xo(e,"refund");return{refundId:yo(t,"refund_id"),amount:ko(t,"amount"),state:yo(t,"state")}}),returnIds:vo(t.return_ids,"return_ids").filter(e=>typeof e=="string"),subtotal:_o(t,"subtotal"),discount:_o(t,"discount"),tax:_o(t,"tax"),arrivesBy:wo(t,"arrives_by"),tracking:Vo(t.tracking),steps:Array.isArray(t.steps)?t.steps.flatMap(Uo):null,paymentMethodId:wo(t,"payment_method_id")}}function Zo(e){let t=xo(e,"cancel");return{outcome:yo(t,"outcome"),refunded:_o(t,"refunded"),reasonCode:wo(t,"reason_code")}}function Jo(e){let t=xo(e,"pay"),i=yo(t,"outcome");if(i!=="authorized"&&i!=="action_required")throw new bo("pay.outcome");let r=wo(t,"payer_action");if(i==="action_required"&&!r)throw new bo("pay.payer_action");return{outcome:i,orderId:yo(t,"order_id"),payerAction:i==="authorized"?null:r}}function el(e){let t=xo(e,"return");return{returnId:yo(t,"return_id"),orderId:yo(t,"order_id"),lines:vo(t.lines,"return.lines").map(e=>{let t=xo(e,"return.line");return{lineId:yo(t,"line_id"),quantity:ko(t,"quantity"),reasonCode:yo(t,"reason_code")}}),state:yo(t,"state"),rma:wo(t,"rma"),labelUrl:Io(t,"label_url")}}function tl(e){let t=xo(e,"case");return{caseId:yo(t,"case_id"),orderId:yo(t,"order_id"),reasonCode:yo(t,"reason_code"),message:typeof t.message=="string"?t.message:"",openedAt:yo(t,"opened_at"),closedAt:wo(t,"closed_at")}}function il(e){return vo(xo(e,"cases").cases,"cases").map(tl)}function rl(e){return vo(xo(e,"prescriptions").prescriptions,"prescriptions").map(e=>{let t=xo(e,"prescription");return{rxId:yo(t,"rx_id"),petId:yo(t,"pet_id"),drug:wo(t,"drug")??"",strength:wo(t,"strength"),form:wo(t,"form"),status:yo(t,"status"),offerId:wo(t,"offer_id"),packCount:_o(t,"pack_count"),fillsUsed:_o(t,"fills_used"),fillsTotal:_o(t,"fills_total"),expiresOn:wo(t,"expires_on"),nextFillOn:wo(t,"next_fill_on"),supply:Ao(t.supply),prescriberName:wo(t,"prescriber_name"),refillsTotal:_o(t,"refills_total"),refillsLeft:_o(t,"refills_left")}})}function al(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,i=wo(t,"line1"),r=wo(t,"city"),a=wo(t,"postal_code"),n=wo(t,"country");return!i||!r||!a||!n?null:{recipientName:wo(t,"recipient_name"),line1:i,line2:wo(t,"line2"),city:r,region:wo(t,"region")??"",postalCode:a,country:n}}function nl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,i=wo(t,"brand"),r=wo(t,"last4");return i&&r?{brand:i,last4:r}:null}function sl(e){let t=xo(e,"receipt"),i=t.reference&&typeof t.reference=="object"?t.reference:null;return{orderId:yo(t,"order_id"),referenceNumber:i?wo(i,"number"):null,placedAt:yo(t,"placed_at"),lines:vo(t.lines,"receipt.lines").map(e=>{let t=xo(e,"receipt.line");return{title:yo(t,"title","receipt.line.title"),quantity:ko(t,"quantity","receipt.line.quantity"),unitPrice:ko(t,"unit_price","receipt.line.unit_price"),discount:ko(t,"discount","receipt.line.discount"),tax:ko(t,"tax","receipt.line.tax"),total:ko(t,"total","receipt.line.total")}}),subtotal:ko(t,"subtotal"),shipping:ko(t,"shipping"),tax:ko(t,"tax"),discounts:ko(t,"discounts"),total:ko(t,"total"),paidAt:wo(t,"paid_at"),card:nl(t.card),shipTo:al(t.ship_to)}}function ol(e){let t=xo(e,"address");return{ref:yo(t,"ref"),label:wo(t,"label")??"",isDefault:jo(t,"is_default"),isComplete:jo(t,"is_complete")}}function ll(e){return vo(xo(e,"addresses").addresses,"addresses").map(ol)}function cl(e){let t=xo(e,"address"),i=xo(t.address,"address.address"),r={recipientName:wo(i,"recipient_name"),line1:yo(i,"line1","address.line1"),line2:wo(i,"line2"),city:yo(i,"city","address.city"),region:wo(i,"region")??"",postalCode:yo(i,"postal_code","address.postal_code"),country:yo(i,"country","address.country")};return{...ol(t),address:r}}function dl(e){return vo(xo(e,"payment_methods").payment_methods,"payment_methods").map(e=>{let t=xo(e,"payment_method");return{paymentMethodId:yo(t,"payment_method_id"),brand:wo(t,"brand")??"",last4:wo(t,"last4")??"",wallet:wo(t,"wallet")}})}function ul(e){let t=xo(e,"setup");return{setupId:yo(t,"setup_id"),payerAction:yo(t,"payer_action")}}function pl(e){let t=xo(e,"card_setup");return{url:yo(t,"url")}}function fl(e){let t=xo(e,"card_action");return{url:yo(t,"url"),expiresAt:yo(t,"expires_at")}}function ml(e){let t=xo(e,"plan");return{planId:yo(t,"plan_id"),lines:vo(t.lines,"plan.lines").map(e=>{let t=xo(e,"plan.line");return{offerId:yo(t,"offer_id"),quantity:ko(t,"quantity"),petId:No(t.pet)}}),cadenceDays:ko(t,"cadence_days"),destination:wo(t,"destination"),paymentMethodId:wo(t,"payment_method_id"),discountBps:_o(t,"discount_bps")??0,nextRun:wo(t,"next_run"),state:yo(t,"state"),stopReason:wo(t,"stop_reason"),priceCentsPerCycle:_o(t,"price_cents_per_cycle"),chargedWhenFilled:Po(t,"charged_when_filled"),nextShipOn:Fo(t,"next_ship_on"),skippedCycleOn:Fo(t,"skipped_cycle_on"),prescriberName:wo(t,"prescriber_name"),refillsLeft:_o(t,"refills_left"),refillsTotal:_o(t,"refills_total"),autoDiscountPct:_o(t,"auto_discount_pct"),changeOptions:gl(t.change_options),skipWarning:hl(t.skip_warning)}}function hl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,i=wo(t,"key");if(i!=="last_dose"&&i!=="bottle_gap")return null;let r=t.values!==null&&typeof t.values=="object"&&!Array.isArray(t.values)?t.values:{},a=wo(r,"unit_label")?.trim();return{key:i,values:{unitLabel:a||null,doseOn:Fo(r,"dose_on"),noneFor:Fo(r,"none_for"),lastsTo:Fo(r,"lasts_to"),weeks:_o(r,"weeks")}}}function gl(e){if(!Array.isArray(e))return null;let t=e.flatMap(e=>{if(e===null||typeof e!="object"||Array.isArray(e))return[];let t=e,i=wo(t,"offer_id"),r=wo(t,"title"),a=_o(t,"quantity"),n=_o(t,"price_cents_per_cycle"),s=Array.isArray(t.cadence_days)?t.cadence_days.filter(e=>Number.isInteger(e)&&e>0):[];if(!i||!r||a===null||a<1||n===null||s.length===0)return[];let o=t.pack_quantity;return[{offerId:i,title:r,size:wo(t,"size"),packQuantity:typeof o=="string"&&/^\d+(\.\d+)?$/.test(o)?o:null,packUnit:Co(t),unitLabel:wo(t,"unit_label"),quantity:a,priceCentsPerCycle:n,cadenceDays:s,current:t.current===true}]});return t.length>0?t:null}function bl(e){return vo(xo(e,"buy_again").items,"items").flatMap(e=>{if(e===null||typeof e!="object"||Array.isArray(e))return[];let t=e,i=wo(t,"offer_id"),r=wo(t,"title");return!i||!r?[]:[{offerId:i,title:r,imageUrl:Io(t,"image_url"),priceCents:_o(t,"price_cents"),lastOrderedOn:Fo(t,"last_ordered_on"),isRx:Po(t,"is_rx")??false,likelyOut:Po(t,"likely_out")??false}]})}function xl(e){let t=xo(e,"plans");return{plans:vo(t.plans,"plans").map(ml),nextCursor:wo(t,"next_cursor")}}function vl(e){let t={offer_id:e.offerId,quantity:e.quantity};return e.petId&&(t.pet={namespace:"consumer",pet_id:e.petId}),e.rxId&&(t.rx_id=e.rxId),e.plan&&(t.plan=e.plan),t}function yl(e){let t=e.address;return{label:e.label,make_default:e.makeDefault===true,address:{recipient_name:t.recipientName,line1:t.line1,line2:t.line2,city:t.city,region:t.region,postal_code:t.postalCode,country:t.country}}}function wl(e){let t=xo(e,"cycle"),i=t.review&&typeof t.review=="object"&&!Array.isArray(t.review)?t.review:null,r=e=>i&&i[e]!==void 0&&i[e]!==null?i[e]:t[e];return{planId:yo(t,"plan_id"),reviewId:wo(t,"review_id")??(i?wo(i,"review_id"):null),cycle:ko(t,"cycle"),state:i?wo(i,"state")??wo(t,"state"):wo(t,"state"),lines:vo(r("lines"),"cycle.lines").map(e=>{let t=xo(e,"cycle.line");return{offerId:yo(t,"offer_id"),quantity:ko(t,"quantity"),petId:No(t.pet)}}),shipsOn:i?wo(i,"ships_on")??wo(t,"ships_on"):wo(t,"ships_on"),approveBy:i?wo(i,"approve_by")??wo(t,"approve_by"):wo(t,"approve_by"),quoteLines:vo(t.quote&&typeof t.quote=="object"?t.quote.lines:null,"cycle.quote.lines").map(e=>{let t=xo(e,"cycle.quote.line");return{offerId:yo(t,"offer_id"),quantity:ko(t,"quantity"),petId:No(t.pet),unitPrice:ko(t,"unit_price"),discount:_o(t,"discount")??0,tax:_o(t,"tax")??0}})}}function kl(e){let t=xo(e,"cycle-draft");return{checkoutId:yo(t,"checkout_id"),shipping:_o(t,"shipping")??0,tax:_o(t,"tax")??0,total:ko(t,"total"),expiresAt:wo(t,"expires_at")}}var _l="/api/v1/oms",jl=3e4,Nl=/^[A-Za-z0-9_]+$/,zl=/^[a-z][a-z0-9_]{0,63}$/;function $l(e){let t=po(e);if(t===null)throw new N("invalid-argument","createOmsClient: baseUrl is not a URL");let i=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(i&&t.protocol==="http:"))throw new N("invalid-argument","createOmsClient: baseUrl must be https");if(t.username||t.password||t.search||t.hash)throw new N("invalid-argument","createOmsClient: baseUrl must be a bare origin or path");return t.origin+t.pathname.replace(/\/+$/,"")}function Cl(e){return encodeURIComponent(e)}function Sl(e){return typeof e=="string"&&e.length>0&&e.length<=256}function createOmsClient(e){let t=$l(e.baseUrl)+(e.path??_l).replace(/\/+$/,""),i=e.fetch??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0);if(!i)throw new N("missing-peer-dependency","createOmsClient: no fetch available; pass config.fetch");if(!e.auth||e.auth.kind!=="everfur_consumer"||typeof e.auth.getToken!="function")throw new N("invalid-argument",'createOmsClient: auth must be { kind: "everfur_consumer", getToken }');let r=e.auth.getToken,a=e.channel??"web",n=e.timeoutMs??jl;async function s(){try{let e=await r();return typeof e=="string"&&e.length>0?e:null}catch{return null}}async function o(e){let r=await s();if(!r)return $({kind:"signedOut"});let a=t+e.path;if(e.query){let t=Object.entries(e.query).filter(([,e])=>e!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");t&&(a+=`?${t}`)}let o={accept:"application/json",authorization:`Bearer ${r}`},l={method:e.method,headers:o};e.body!==void 0&&(o["content-type"]="application/json",l.body=JSON.stringify(e.body));let c=typeof AbortController=="function"?new AbortController:null;c&&(l.signal=c.signal);let d=false,u=setTimeout(()=>{d=true,c?.abort()},n),p;try{p=await i(a,l)}catch{return clearTimeout(u),$({kind:d?"timeout":"network"})}try{let t=p.headers.get("x-request-id")??void 0,i=t?{requestId:t}:{};if(p.status<200||p.status>=300){let e=p.status===402||p.status===409||p.status===422?await p.json().catch(()=>null):null;return $(F(p.status,e,{...i,retryAfter:p.headers.get("retry-after")}))}if(e.read===null||p.status===204)return z(void 0);let r;try{r=await p.json()}catch{return $({kind:"badResponse",...i})}try{return z(e.read(r))}catch{return $({kind:"badResponse",...i})}}catch{return $({kind:d?"timeout":"network"})}finally{clearTimeout(u)}}let l=()=>Promise.resolve($({kind:"invalidRequest"}));function c(e,t){return Sl(e)?t(Cl(e)):l()}let d=e=>e.map(vl);return{shopConfig:()=>o({method:"GET",path:"/shop-config",read:Oo}),offers:(e={})=>o({method:"GET",path:"/catalog/offers",query:{text:e.text,requires_rx:e.requiresRx,cursor:e.cursor,limit:e.limit},read:Mo}),offer:e=>c(e,e=>o({method:"GET",path:`/catalog/offers/${e}`,read:Bo})),prescriptions:()=>o({method:"GET",path:"/prescriptions",read:rl}),addresses:()=>o({method:"GET",path:"/addresses",read:ll}),address:e=>c(e,e=>o({method:"GET",path:`/addresses/${e}`,read:cl})),addAddress:e=>o({method:"POST",path:"/addresses",body:yl(e),read:ol}),updateAddress:(e,t)=>c(e,e=>o({method:"PUT",path:`/addresses/${e}`,body:yl(t),read:ol})),removeAddress:e=>c(e,e=>o({method:"DELETE",path:`/addresses/${e}`,read:null})),makeDefaultAddress:e=>c(e,e=>o({method:"POST",path:`/addresses/${e}/default`,read:ol})),paymentMethods:()=>o({method:"GET",path:"/payment-methods",read:dl}),setupPaymentMethod:()=>o({method:"POST",path:"/payment-methods/setup",read:ul}),startCardSetupSession:e=>o({method:"POST",path:"/payment-methods/setup-session",body:{idempotency_key:e.idempotencyKey,return_url:e.returnUrl},read:pl}),removePaymentMethod:e=>Nl.test(e)?o({method:"DELETE",path:`/payment-methods/${e}`,read:null}):l(),quote:e=>o({method:"POST",path:"/cart/quote",body:{lines:d(e.lines),ship_to:e.shipTo,promo_code:e.promoCode??null},read:Ho}),createCheckout:e=>o({method:"POST",path:"/checkouts",body:{idempotency_key:e.idempotencyKey,channel:a,lines:d(e.lines),ship_to:e.shipTo,receipt_email:e.receiptEmail??null,promo_code:e.promoCode??null},read:qo}),confirmCheckout:(e,t)=>Nl.test(t.paymentMethodId)&&Number.isInteger(t.expectedTotal)?c(e,e=>o({method:"POST",path:`/checkouts/${e}/confirm`,body:{idempotency_key:t.idempotencyKey,expected_total:t.expectedTotal,payment_method_id:t.paymentMethodId},read:Do})):l(),orders:(e={})=>e.since!==void 0&&!/^\d{4}-\d{2}-\d{2}$/.test(e.since)?l():o({method:"GET",path:"/orders",query:{cursor:e.cursor,limit:e.limit,reference:e.reference,since:e.since},read:Go}),order:e=>c(e,e=>o({method:"GET",path:`/orders/${e}`,read:Qo})),cancelOrder:(e,t)=>zl.test(t.reasonCode)?c(e,e=>o({method:"POST",path:`/orders/${e}/cancel`,body:{idempotency_key:t.idempotencyKey,reason_code:t.reasonCode},read:Zo})):l(),payOrder:(e,t)=>{if(t.paymentMethodId!==void 0&&!Nl.test(t.paymentMethodId))return l();let i={idempotency_key:t.idempotencyKey};return t.paymentMethodId&&(i.payment_method_id=t.paymentMethodId),c(e,e=>o({method:"POST",path:`/orders/${e}/pay`,body:i,read:Jo}))},cardActionLink:(e,t)=>c(e,e=>o({method:"POST",path:`/orders/${e}/card-action-link`,body:{return_url:t.returnUrl},read:fl})),receipt:e=>c(e,e=>o({method:"GET",path:`/orders/${e}/receipt`,read:sl})),requestReturn:(e,t)=>t.lines.every(e=>zl.test(e.reasonCode))?c(e,e=>o({method:"POST",path:`/orders/${e}/returns`,body:{idempotency_key:t.idempotencyKey,lines:t.lines.map(e=>({line_id:e.lineId,quantity:e.quantity,reason_code:e.reasonCode}))},read:el})):l(),getReturn:e=>c(e,e=>o({method:"GET",path:`/returns/${e}`,read:el})),cancelReturn:e=>c(e,e=>o({method:"POST",path:`/returns/${e}/cancel`,read:el})),openCase:(e,t)=>zl.test(t.reasonCode)&&t.message.length<=4e3?c(e,e=>o({method:"POST",path:`/orders/${e}/cases`,body:{idempotency_key:t.idempotencyKey,reason_code:t.reasonCode,message:t.message},read:tl})):l(),orderCases:e=>c(e,e=>o({method:"GET",path:`/orders/${e}/cases`,read:il})),plans:(e={})=>o({method:"GET",path:"/subscriptions",query:{cursor:e.cursor,limit:e.limit},read:xl}),buyAgain:()=>o({method:"GET",path:"/buy-again",read:bl}),createPlan:e=>Nl.test(e.paymentMethodId)?o({method:"POST",path:"/subscriptions",body:{idempotency_key:e.idempotencyKey,cadence_days:e.cadenceDays,destination:e.destination,payment_method_id:e.paymentMethodId,consent_terms_version:e.consentTermsVersion,lines:d(e.lines)},read:ml}):l(),updatePlan:(e,t)=>{if(t.paymentMethodId!==void 0&&!Nl.test(t.paymentMethodId))return l();let i={idempotency_key:t.idempotencyKey};if(t.lines&&(i.lines=d(t.lines)),t.cadenceDays!==void 0&&(i.cadence_days=t.cadenceDays),t.offerId!==void 0){if(!Sl(t.offerId)||t.cadenceDays===void 0||t.lines)return l();i.offer_id=t.offerId}return t.destination!==void 0&&(i.destination=t.destination),t.paymentMethodId!==void 0&&(i.payment_method_id=t.paymentMethodId),c(e,e=>o({method:"PATCH",path:`/subscriptions/${e}`,body:i,read:ml}))},planAction:(e,t)=>c(e,e=>o({method:"POST",path:`/subscriptions/${e}/actions`,body:{idempotency_key:t.idempotencyKey,operation:t.operation},read:ml})),cancelPlan:e=>c(e,e=>o({method:"POST",path:`/subscriptions/${e}/cancel`,read:ml})),cycleReview:e=>c(e,e=>o({method:"GET",path:`/subscriptions/${e}/cycle`,read:wl})),editCycle:(e,t,i)=>Number.isInteger(t)&&t>0?c(e,e=>o({method:"PUT",path:`/subscriptions/${e}/cycles/${t}/lines`,body:{idempotency_key:i.idempotencyKey,lines:d(i.lines)},read:wl})):l(),draftCycle:(e,t)=>Number.isInteger(t)&&t>0?c(e,e=>o({method:"POST",path:`/subscriptions/${e}/cycles/${t}/draft`,read:kl})):l(),approveCycle:(e,t,i)=>Number.isInteger(t)&&t>0&&Number.isInteger(i.expectedTotal)?c(e,e=>o({method:"POST",path:`/subscriptions/${e}/cycles/${t}/approve`,body:{idempotency_key:i.idempotencyKey,checkout_id:i.checkoutId,expected_total:i.expectedTotal},read:Do})):l(),skipCycle:(e,t,i)=>Number.isInteger(t)&&t>0?c(e,e=>o({method:"POST",path:`/subscriptions/${e}/cycles/${t}/skip`,body:{idempotency_key:i.idempotencyKey},read:ml})):l()}}var Il=/* @__PURE__ */new Set(["card_error","validation_error"]);function Tl(e){if(!e.error)return{ok:true};let{type:t,message:i}=e.error;return{ok:false,message:typeof t=="string"&&Il.has(t)&&typeof i=="string"&&i.length<=300?i:null}}function createStripeJsPayments(e,t={}){return{async confirmCardSetup(i){try{let r=t.returnUrl?{return_url:t.returnUrl}:void 0;return Tl(await e.confirmSetup({clientSecret:i,...t.elementsFor?{elements:t.elementsFor(i)}:{},...r?{confirmParams:r}:{},redirect:"if_required"}))}catch{return{ok:false,message:null}}},async handleNextAction(t){try{return Tl(await e.handleNextAction({clientSecret:t}))}catch{return{ok:false,message:null}}}}}exports.EverfurShop=EverfurShop2;exports.SHOP_COPY=Y;exports.SHOP_COPY_PLACEHOLDERS=X;exports.SHOP_ORDERS_V2_COPY=Us;exports.SHOP_V3_COPY=ee;exports.SHOP_V3_COPY_PLACEHOLDERS=te;exports.UNAVAILABLE_PACKAGE_SOURCE=Z;exports.createOmsClient=createOmsClient;exports.createOmsPackageSource=createOmsPackageSource;exports.createStripeJsPayments=createStripeJsPayments;exports.isOmsRefusal=isOmsRefusal;exports.isOmsRetryable=isOmsRetryable;exports.isOmsUnavailable=isOmsUnavailable;exports.newIdempotencyKey=newIdempotencyKey;exports.shopCopy=shopCopy;exports.shopOrdersV2Copy=shopOrdersV2Copy;exports.shopV3Copy=shopV3Copy;
603
+ return t.jsx(LiveConsent,{route:e})}}var ro="1.7.0";var ao=/* @__PURE__ */Object.freeze({k1:"X4wc1hwVONs4I9Vmclo9ExrfPZlH8-tgY7NmzxuA5lI"});function no(e,t){let i=Object.keys(t).sort().map(e=>`${e}=${t[e]}`).join(",");return`v${1}|${e}|${i}`}var so=no(ro,ao);var oo=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeRenderer@${so}`),lo=globalThis;function co(t,i){let r=lo[oo];return r===void 0?e.createElement(t.bundled,i):r(t,i)}var uo={part:"shop",name:"EverfurShop",bundled:EverfurShop,hostSubpaths:{"@everfur/sdk/web/shop/orders-v2":()=>import("@everfur/sdk/web/shop/orders-v2")}};function EverfurShop2(e){return co(uo,e)}function po(e,t){let i=globalThis.URL;if(typeof i=="function"){let r;try{r=t===void 0?new i(e):new i(e,t)}catch{return null}try{if(r.protocol)return r}catch{}}return go(e)}var fo=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,mo=/[\s\u0000-\u001f\u007f\\]/,ho={"http:":"80","https:":"443"};function go(e,t){let i=e.trim();let r=mo.test(i)?null:fo.exec(i);if(r===null)return null;let[,a="",n="",s="",o="",l="",c="",d="",u=""]=r,p=`${a.toLowerCase()}:`,f=Number(l);if(f>65535)return null;let m=l===""||String(f)===ho[p]?"":String(f),h=ho[p]!==void 0,g=o.toLowerCase()+(m&&`:${m}`),b=c||(h?"/":""),x=n||s?`${n}${s&&`:${s}`}@`:"";return{href:`${p}//${x}${g}${b}${d}${u}`,protocol:p,username:n,password:s,hostname:o.toLowerCase(),port:m,origin:h?`${p}//${g}`:"null",pathname:b,search:d==="?"?"":d,hash:u==="#"?"":u}}var bo=class _OmsWireError extends Error{constructor(e){super(`OMS answer could not be read: ${e}`);this.field=e;this.name="OmsWireError",Object.setPrototypeOf(this,_OmsWireError.prototype)}};function xo(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new bo(t);return e}function vo(e,t){if(e==null)return[];if(!Array.isArray(e))throw new bo(t);return e}function yo(e,t,i=t){let r=e[t];if(typeof r!="string"||r.length===0)throw new bo(i);return r}function wo(e,t){let i=e[t];return typeof i=="string"&&i.length>0?i:null}function ko(e,t,i=t){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))throw new bo(i);return Math.trunc(r)}function _o(e,t){let i=e[t];return typeof i=="number"&&Number.isFinite(i)?Math.trunc(i):null}function jo(e,t){return e[t]===true}function No(e){if(!e||typeof e!="object")return null;let t=e.pet_id;return typeof t=="string"&&t.length>0?t:null}var zo=["each","gram","milliliter"],$o=["ground","two_day","next_day"];function Co(e){let t=e.pack_unit;return typeof t=="string"&&zo.includes(t)?t:null}function So(e){return typeof e=="string"&&$o.includes(e)?e:null}function Io(e,t){let i=wo(e,t);return i&&po(i)?.protocol==="https:"?i:null}function To(e,t){let i=e[t];return typeof i=="number"&&Number.isFinite(i)?i:null}function Fo(e,t){let i=wo(e,t);return i&&/^\d{4}-\d{2}-\d{2}$/.test(i)?i:null}function Po(e,t){let i=e[t];return typeof i=="boolean"?i:null}var Lo=["pharmacy","everfur_box"];function Ao(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,i=_o(t,"units_left"),r=wo(t,"unit_label"),a=To(t,"daily_units"),n=Fo(t,"runs_out_on");return i===null||i<0||!r||a===null||a<=0||!n?null:{unitsLeft:i,unitLabel:r,dailyUnits:a,runsOutOn:n,refillArrivesOn:Fo(t,"refill_arrives_on")}}function Eo(e){if(e===null||typeof e!="object"||Array.isArray(e))return[];let t=e,i=wo(t,"key");return i?[{key:i,doneAt:wo(t,"done_at")}]:[]}function Oo(e){let t=xo(e,"shop-config"),i=t.delivery&&typeof t.delivery=="object"?t.delivery:null,r=wo(t,"stripe_publishable_key");return{recurringTermsVersion:wo(t,"recurring_terms_version"),recurringTermsUrl:Io(t,"recurring_terms_url"),stripePublishableKey:r&&/^pk_(test|live)_[A-Za-z0-9]+$/.test(r)?r:null,delivery:i?{firstFill:So(i.first_fill),refill:So(i.refill)}:null,rxContactMissing:Array.isArray(t.rx_contact_missing)?t.rx_contact_missing.filter(e=>typeof e=="string"):null,freeShippingThresholdCents:_o(t,"free_shipping_threshold_cents"),firstRxDiscountCents:_o(t,"first_rx_discount_cents")}}function Bo(e){let t=xo(e,"offer"),i=t.pack_quantity;return{offerId:yo(t,"offer_id"),sku:wo(t,"sku")??"",title:yo(t,"title"),fulfillmentType:wo(t,"fulfillment_type")??"physical",requiresRx:jo(t,"requires_rx"),compounded:jo(t,"compounded"),packQuantity:typeof i=="string"&&/^\d+(\.\d+)?$/.test(i)?i:null,packUnit:Co(t),price:_o(t,"price"),imageUrl:Io(t,"image_url")}}function Mo(e){let t=xo(e,"offers");return{offers:vo(t.offers,"offers").map(Bo),nextCursor:wo(t,"next_cursor")}}function Ho(e){let t=xo(e,"quote");return{lines:vo(t.lines,"lines").map(e=>{let t=xo(e,"line");return{offerId:yo(t,"offer_id"),quantity:ko(t,"quantity"),petId:No(t.pet),unitPrice:ko(t,"unit_price"),discount:_o(t,"discount")??0,tax:_o(t,"tax")??0,whenFilledDiscountCents:_o(t,"when_filled_discount_cents"),isRx:Po(t,"is_rx"),chargedWhenFilled:Po(t,"charged_when_filled")}}),shipping:ko(t,"shipping"),tax:_o(t,"tax")??0,total:ko(t,"total"),expiresAt:yo(t,"expires_at"),whenFilledDiscountCents:_o(t,"when_filled_discount_cents"),dueTodayCents:_o(t,"due_today_cents"),dueWhenFilledCents:_o(t,"due_when_filled_cents"),shipsOn:Fo(t,"ships_on"),arrivesOn:Fo(t,"arrives_on")}}function qo(e){let t=xo(e,"checkout");return{checkoutId:yo(t,"checkout_id"),state:wo(t,"state")??"draft",orderIds:vo(t.order_ids,"order_ids").filter(e=>typeof e=="string"),createdAt:wo(t,"created_at")??"",total:ko(t,"total"),shipping:_o(t,"shipping")??0,tax:_o(t,"tax")??0}}function Do(e){let t=xo(e,"confirmation");return{checkoutId:yo(t,"checkout_id"),resale:vo(t.resale,"resale").map(e=>{let t=xo(e,"resale"),i=yo(t,"outcome");if(i!=="confirmed"&&i!=="action_required")throw new bo("resale.outcome");let r=wo(t,"payer_action");if(i==="action_required"&&!r)throw new bo("resale.payer_action");return{outcome:i,orderId:yo(t,"order_id"),payerAction:i==="confirmed"?null:r}})}}function Ro(e){let t=xo(e,"order"),i=t.reference&&typeof t.reference=="object"?t.reference:null;return{orderId:yo(t,"order_id"),referenceNumber:i?wo(i,"number"):null,status:yo(t,"status"),total:ko(t,"total"),placedAt:wo(t,"placed_at"),itemCount:_o(t,"item_count"),items:Array.isArray(t.items)?t.items.flatMap(Wo):null,fulfiller:Lo.includes(wo(t,"fulfiller")??"")?t.fulfiller:null,arrivesBy:Fo(t,"arrives_by"),steps:Array.isArray(t.steps)?t.steps.flatMap(Eo):null,currentStep:wo(t,"current_step"),statusLineKey:wo(t,"status_line_key"),prescriberName:wo(t,"prescriber_name")}}function Wo(e){if(e===null||typeof e!="object"||Array.isArray(e))return[];let t=e,i=wo(t,"offer_id"),r=wo(t,"title"),a=_o(t,"quantity");return i&&r&&a!==null?[{offerId:i,title:r,quantity:a,imageUrl:Io(t,"image_url")}]:[]}function Uo(e){if(e===null||typeof e!="object"||Array.isArray(e))return[];let t=e,i=wo(t,"key");return i?[{key:i,done:t.done===true,at:wo(t,"at")}]:[]}function Vo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;try{return Yo(e)}catch{return null}}function Go(e){let t=xo(e,"orders");return{orders:vo(t.orders,"orders").map(Ro),nextCursor:wo(t,"next_cursor")}}function Ko(e){let t=xo(e,"line"),i=t.pack_quantity;return{lineId:yo(t,"line_id"),offerId:yo(t,"offer_id"),sku:wo(t,"sku")??"",title:yo(t,"title"),requiresRx:jo(t,"requires_rx"),compounded:jo(t,"compounded"),packQuantity:typeof i=="string"&&/^\d+(\.\d+)?$/.test(i)?i:null,packUnit:Co(t),quantity:ko(t,"quantity"),unitPrice:ko(t,"unit_price"),discount:_o(t,"discount")??0,tax:_o(t,"tax")??0,fulfillmentType:wo(t,"fulfillment_type")??"physical",petId:No(t.pet),imageUrl:Io(t,"image_url")}}function Yo(e){let t=xo(e,"tracking");return{carrier:wo(t,"carrier"),trackingNumber:wo(t,"tracking_number"),status:yo(t,"status"),occurredAt:wo(t,"occurred_at"),trackingUrl:Io(t,"tracking_url"),deliveryBy:wo(t,"delivery_by")}}function Xo(e){let t=xo(e,"shipment");return{shipmentId:yo(t,"shipment_id"),state:yo(t,"state"),lines:vo(t.lines,"shipment.lines").map(e=>{let t=xo(e,"shipment.line");return{lineId:yo(t,"line_id"),quantity:ko(t,"quantity")}}),tracking:vo(t.tracking,"tracking").map(Yo)}}function Qo(e){let t=xo(e,"order");return{summary:Ro(t.summary),lines:vo(t.lines,"lines").map(Ko),shipping:_o(t,"shipping")??0,shippingTax:_o(t,"shipping_tax")??0,shipments:vo(t.shipments,"shipments").map(Xo),canCancel:jo(t,"can_cancel"),canReturn:jo(t,"can_return"),canPay:jo(t,"can_pay"),paymentStatus:wo(t,"payment_status"),refunds:vo(t.refunds,"refunds").map(e=>{let t=xo(e,"refund");return{refundId:yo(t,"refund_id"),amount:ko(t,"amount"),state:yo(t,"state")}}),returnIds:vo(t.return_ids,"return_ids").filter(e=>typeof e=="string"),subtotal:_o(t,"subtotal"),discount:_o(t,"discount"),tax:_o(t,"tax"),arrivesBy:wo(t,"arrives_by"),tracking:Vo(t.tracking),steps:Array.isArray(t.steps)?t.steps.flatMap(Uo):null,paymentMethodId:wo(t,"payment_method_id")}}function Zo(e){let t=xo(e,"cancel");return{outcome:yo(t,"outcome"),refunded:_o(t,"refunded"),reasonCode:wo(t,"reason_code")}}function Jo(e){let t=xo(e,"pay"),i=yo(t,"outcome");if(i!=="authorized"&&i!=="action_required")throw new bo("pay.outcome");let r=wo(t,"payer_action");if(i==="action_required"&&!r)throw new bo("pay.payer_action");return{outcome:i,orderId:yo(t,"order_id"),payerAction:i==="authorized"?null:r}}function el(e){let t=xo(e,"return");return{returnId:yo(t,"return_id"),orderId:yo(t,"order_id"),lines:vo(t.lines,"return.lines").map(e=>{let t=xo(e,"return.line");return{lineId:yo(t,"line_id"),quantity:ko(t,"quantity"),reasonCode:yo(t,"reason_code")}}),state:yo(t,"state"),rma:wo(t,"rma"),labelUrl:Io(t,"label_url")}}function tl(e){let t=xo(e,"case");return{caseId:yo(t,"case_id"),orderId:yo(t,"order_id"),reasonCode:yo(t,"reason_code"),message:typeof t.message=="string"?t.message:"",openedAt:yo(t,"opened_at"),closedAt:wo(t,"closed_at")}}function il(e){return vo(xo(e,"cases").cases,"cases").map(tl)}function rl(e){return vo(xo(e,"prescriptions").prescriptions,"prescriptions").map(e=>{let t=xo(e,"prescription");return{rxId:yo(t,"rx_id"),petId:yo(t,"pet_id"),drug:wo(t,"drug")??"",strength:wo(t,"strength"),form:wo(t,"form"),status:yo(t,"status"),offerId:wo(t,"offer_id"),packCount:_o(t,"pack_count"),fillsUsed:_o(t,"fills_used"),fillsTotal:_o(t,"fills_total"),expiresOn:wo(t,"expires_on"),nextFillOn:wo(t,"next_fill_on"),supply:Ao(t.supply),prescriberName:wo(t,"prescriber_name"),refillsTotal:_o(t,"refills_total"),refillsLeft:_o(t,"refills_left")}})}function al(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,i=wo(t,"line1"),r=wo(t,"city"),a=wo(t,"postal_code"),n=wo(t,"country");return!i||!r||!a||!n?null:{recipientName:wo(t,"recipient_name"),line1:i,line2:wo(t,"line2"),city:r,region:wo(t,"region")??"",postalCode:a,country:n}}function nl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,i=wo(t,"brand"),r=wo(t,"last4");return i&&r?{brand:i,last4:r}:null}function sl(e){let t=xo(e,"receipt"),i=t.reference&&typeof t.reference=="object"?t.reference:null;return{orderId:yo(t,"order_id"),referenceNumber:i?wo(i,"number"):null,placedAt:yo(t,"placed_at"),lines:vo(t.lines,"receipt.lines").map(e=>{let t=xo(e,"receipt.line");return{title:yo(t,"title","receipt.line.title"),quantity:ko(t,"quantity","receipt.line.quantity"),unitPrice:ko(t,"unit_price","receipt.line.unit_price"),discount:ko(t,"discount","receipt.line.discount"),tax:ko(t,"tax","receipt.line.tax"),total:ko(t,"total","receipt.line.total")}}),subtotal:ko(t,"subtotal"),shipping:ko(t,"shipping"),tax:ko(t,"tax"),discounts:ko(t,"discounts"),total:ko(t,"total"),paidAt:wo(t,"paid_at"),card:nl(t.card),shipTo:al(t.ship_to)}}function ol(e){let t=xo(e,"address");return{ref:yo(t,"ref"),label:wo(t,"label")??"",isDefault:jo(t,"is_default"),isComplete:jo(t,"is_complete")}}function ll(e){return vo(xo(e,"addresses").addresses,"addresses").map(ol)}function cl(e){let t=xo(e,"address"),i=xo(t.address,"address.address"),r={recipientName:wo(i,"recipient_name"),line1:yo(i,"line1","address.line1"),line2:wo(i,"line2"),city:yo(i,"city","address.city"),region:wo(i,"region")??"",postalCode:yo(i,"postal_code","address.postal_code"),country:yo(i,"country","address.country")};return{...ol(t),address:r}}function dl(e){return vo(xo(e,"payment_methods").payment_methods,"payment_methods").map(e=>{let t=xo(e,"payment_method");return{paymentMethodId:yo(t,"payment_method_id"),brand:wo(t,"brand")??"",last4:wo(t,"last4")??"",wallet:wo(t,"wallet")}})}function ul(e){let t=xo(e,"setup");return{setupId:yo(t,"setup_id"),payerAction:yo(t,"payer_action")}}function pl(e){let t=xo(e,"card_setup");return{url:yo(t,"url")}}function fl(e){let t=xo(e,"card_action");return{url:yo(t,"url"),expiresAt:yo(t,"expires_at")}}function ml(e){let t=xo(e,"plan");return{planId:yo(t,"plan_id"),lines:vo(t.lines,"plan.lines").map(e=>{let t=xo(e,"plan.line");return{offerId:yo(t,"offer_id"),quantity:ko(t,"quantity"),petId:No(t.pet)}}),cadenceDays:ko(t,"cadence_days"),destination:wo(t,"destination"),paymentMethodId:wo(t,"payment_method_id"),discountBps:_o(t,"discount_bps")??0,nextRun:wo(t,"next_run"),state:yo(t,"state"),stopReason:wo(t,"stop_reason"),priceCentsPerCycle:_o(t,"price_cents_per_cycle"),chargedWhenFilled:Po(t,"charged_when_filled"),nextShipOn:Fo(t,"next_ship_on"),skippedCycleOn:Fo(t,"skipped_cycle_on"),prescriberName:wo(t,"prescriber_name"),refillsLeft:_o(t,"refills_left"),refillsTotal:_o(t,"refills_total"),autoDiscountPct:_o(t,"auto_discount_pct"),changeOptions:gl(t.change_options),skipWarning:hl(t.skip_warning)}}function hl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,i=wo(t,"key");if(i!=="last_dose"&&i!=="bottle_gap")return null;let r=t.values!==null&&typeof t.values=="object"&&!Array.isArray(t.values)?t.values:{},a=wo(r,"unit_label")?.trim();return{key:i,values:{unitLabel:a||null,doseOn:Fo(r,"dose_on"),noneFor:Fo(r,"none_for"),lastsTo:Fo(r,"lasts_to"),weeks:_o(r,"weeks")}}}function gl(e){if(!Array.isArray(e))return null;let t=e.flatMap(e=>{if(e===null||typeof e!="object"||Array.isArray(e))return[];let t=e,i=wo(t,"offer_id"),r=wo(t,"title"),a=_o(t,"quantity"),n=_o(t,"price_cents_per_cycle"),s=Array.isArray(t.cadence_days)?t.cadence_days.filter(e=>Number.isInteger(e)&&e>0):[];if(!i||!r||a===null||a<1||n===null||s.length===0)return[];let o=t.pack_quantity;return[{offerId:i,title:r,size:wo(t,"size"),packQuantity:typeof o=="string"&&/^\d+(\.\d+)?$/.test(o)?o:null,packUnit:Co(t),unitLabel:wo(t,"unit_label"),quantity:a,priceCentsPerCycle:n,cadenceDays:s,current:t.current===true}]});return t.length>0?t:null}function bl(e){return vo(xo(e,"buy_again").items,"items").flatMap(e=>{if(e===null||typeof e!="object"||Array.isArray(e))return[];let t=e,i=wo(t,"offer_id"),r=wo(t,"title");return!i||!r?[]:[{offerId:i,title:r,imageUrl:Io(t,"image_url"),priceCents:_o(t,"price_cents"),lastOrderedOn:Fo(t,"last_ordered_on"),isRx:Po(t,"is_rx")??false,likelyOut:Po(t,"likely_out")??false}]})}function xl(e){let t=xo(e,"plans");return{plans:vo(t.plans,"plans").map(ml),nextCursor:wo(t,"next_cursor")}}function vl(e){let t={offer_id:e.offerId,quantity:e.quantity};return e.petId&&(t.pet={namespace:"consumer",pet_id:e.petId}),e.rxId&&(t.rx_id=e.rxId),e.plan&&(t.plan=e.plan),t}function yl(e){let t=e.address;return{label:e.label,make_default:e.makeDefault===true,address:{recipient_name:t.recipientName,line1:t.line1,line2:t.line2,city:t.city,region:t.region,postal_code:t.postalCode,country:t.country}}}function wl(e){let t=xo(e,"cycle"),i=t.review&&typeof t.review=="object"&&!Array.isArray(t.review)?t.review:null,r=e=>i&&i[e]!==void 0&&i[e]!==null?i[e]:t[e];return{planId:yo(t,"plan_id"),reviewId:wo(t,"review_id")??(i?wo(i,"review_id"):null),cycle:ko(t,"cycle"),state:i?wo(i,"state")??wo(t,"state"):wo(t,"state"),lines:vo(r("lines"),"cycle.lines").map(e=>{let t=xo(e,"cycle.line");return{offerId:yo(t,"offer_id"),quantity:ko(t,"quantity"),petId:No(t.pet)}}),shipsOn:i?wo(i,"ships_on")??wo(t,"ships_on"):wo(t,"ships_on"),approveBy:i?wo(i,"approve_by")??wo(t,"approve_by"):wo(t,"approve_by"),quoteLines:vo(t.quote&&typeof t.quote=="object"?t.quote.lines:null,"cycle.quote.lines").map(e=>{let t=xo(e,"cycle.quote.line");return{offerId:yo(t,"offer_id"),quantity:ko(t,"quantity"),petId:No(t.pet),unitPrice:ko(t,"unit_price"),discount:_o(t,"discount")??0,tax:_o(t,"tax")??0}})}}function kl(e){let t=xo(e,"cycle-draft");return{checkoutId:yo(t,"checkout_id"),shipping:_o(t,"shipping")??0,tax:_o(t,"tax")??0,total:ko(t,"total"),expiresAt:wo(t,"expires_at")}}var _l="/api/v1/oms",jl=3e4,Nl=/^[A-Za-z0-9_]+$/,zl=/^[a-z][a-z0-9_]{0,63}$/;function $l(e){let t=po(e);if(t===null)throw new N("invalid-argument","createOmsClient: baseUrl is not a URL");let i=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(i&&t.protocol==="http:"))throw new N("invalid-argument","createOmsClient: baseUrl must be https");if(t.username||t.password||t.search||t.hash)throw new N("invalid-argument","createOmsClient: baseUrl must be a bare origin or path");return t.origin+t.pathname.replace(/\/+$/,"")}function Cl(e){return encodeURIComponent(e)}function Sl(e){return typeof e=="string"&&e.length>0&&e.length<=256}function createOmsClient(e){let t=$l(e.baseUrl)+(e.path??_l).replace(/\/+$/,""),i=e.fetch??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0);if(!i)throw new N("missing-peer-dependency","createOmsClient: no fetch available; pass config.fetch");if(!e.auth||e.auth.kind!=="everfur_consumer"||typeof e.auth.getToken!="function")throw new N("invalid-argument",'createOmsClient: auth must be { kind: "everfur_consumer", getToken }');let r=e.auth.getToken,a=e.channel??"web",n=e.timeoutMs??jl;async function s(){try{let e=await r();return typeof e=="string"&&e.length>0?e:null}catch{return null}}async function o(e){let r=await s();if(!r)return $({kind:"signedOut"});let a=t+e.path;if(e.query){let t=Object.entries(e.query).filter(([,e])=>e!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`).join("&");t&&(a+=`?${t}`)}let o={accept:"application/json",authorization:`Bearer ${r}`},l={method:e.method,headers:o};e.body!==void 0&&(o["content-type"]="application/json",l.body=JSON.stringify(e.body));let c=typeof AbortController=="function"?new AbortController:null;c&&(l.signal=c.signal);let d=false,u=setTimeout(()=>{d=true,c?.abort()},n),p;try{p=await i(a,l)}catch{return clearTimeout(u),$({kind:d?"timeout":"network"})}try{let t=p.headers.get("x-request-id")??void 0,i=t?{requestId:t}:{};if(p.status<200||p.status>=300){let e=p.status===402||p.status===409||p.status===422?await p.json().catch(()=>null):null;return $(F(p.status,e,{...i,retryAfter:p.headers.get("retry-after")}))}if(e.read===null||p.status===204)return z(void 0);let r;try{r=await p.json()}catch{return $({kind:"badResponse",...i})}try{return z(e.read(r))}catch{return $({kind:"badResponse",...i})}}catch{return $({kind:d?"timeout":"network"})}finally{clearTimeout(u)}}let l=()=>Promise.resolve($({kind:"invalidRequest"}));function c(e,t){return Sl(e)?t(Cl(e)):l()}let d=e=>e.map(vl);return{shopConfig:()=>o({method:"GET",path:"/shop-config",read:Oo}),offers:(e={})=>o({method:"GET",path:"/catalog/offers",query:{text:e.text,requires_rx:e.requiresRx,cursor:e.cursor,limit:e.limit},read:Mo}),offer:e=>c(e,e=>o({method:"GET",path:`/catalog/offers/${e}`,read:Bo})),prescriptions:()=>o({method:"GET",path:"/prescriptions",read:rl}),addresses:()=>o({method:"GET",path:"/addresses",read:ll}),address:e=>c(e,e=>o({method:"GET",path:`/addresses/${e}`,read:cl})),addAddress:e=>o({method:"POST",path:"/addresses",body:yl(e),read:ol}),updateAddress:(e,t)=>c(e,e=>o({method:"PUT",path:`/addresses/${e}`,body:yl(t),read:ol})),removeAddress:e=>c(e,e=>o({method:"DELETE",path:`/addresses/${e}`,read:null})),makeDefaultAddress:e=>c(e,e=>o({method:"POST",path:`/addresses/${e}/default`,read:ol})),paymentMethods:()=>o({method:"GET",path:"/payment-methods",read:dl}),setupPaymentMethod:()=>o({method:"POST",path:"/payment-methods/setup",read:ul}),startCardSetupSession:e=>o({method:"POST",path:"/payment-methods/setup-session",body:{idempotency_key:e.idempotencyKey,return_url:e.returnUrl},read:pl}),removePaymentMethod:e=>Nl.test(e)?o({method:"DELETE",path:`/payment-methods/${e}`,read:null}):l(),quote:e=>o({method:"POST",path:"/cart/quote",body:{lines:d(e.lines),ship_to:e.shipTo,promo_code:e.promoCode??null},read:Ho}),createCheckout:e=>o({method:"POST",path:"/checkouts",body:{idempotency_key:e.idempotencyKey,channel:a,lines:d(e.lines),ship_to:e.shipTo,receipt_email:e.receiptEmail??null,promo_code:e.promoCode??null},read:qo}),confirmCheckout:(e,t)=>Nl.test(t.paymentMethodId)&&Number.isInteger(t.expectedTotal)?c(e,e=>o({method:"POST",path:`/checkouts/${e}/confirm`,body:{idempotency_key:t.idempotencyKey,expected_total:t.expectedTotal,payment_method_id:t.paymentMethodId},read:Do})):l(),orders:(e={})=>e.since!==void 0&&!/^\d{4}-\d{2}-\d{2}$/.test(e.since)?l():o({method:"GET",path:"/orders",query:{cursor:e.cursor,limit:e.limit,reference:e.reference,since:e.since},read:Go}),order:e=>c(e,e=>o({method:"GET",path:`/orders/${e}`,read:Qo})),cancelOrder:(e,t)=>zl.test(t.reasonCode)?c(e,e=>o({method:"POST",path:`/orders/${e}/cancel`,body:{idempotency_key:t.idempotencyKey,reason_code:t.reasonCode},read:Zo})):l(),payOrder:(e,t)=>{if(t.paymentMethodId!==void 0&&!Nl.test(t.paymentMethodId))return l();let i={idempotency_key:t.idempotencyKey};return t.paymentMethodId&&(i.payment_method_id=t.paymentMethodId),c(e,e=>o({method:"POST",path:`/orders/${e}/pay`,body:i,read:Jo}))},cardActionLink:(e,t)=>c(e,e=>o({method:"POST",path:`/orders/${e}/card-action-link`,body:{return_url:t.returnUrl},read:fl})),receipt:e=>c(e,e=>o({method:"GET",path:`/orders/${e}/receipt`,read:sl})),requestReturn:(e,t)=>t.lines.every(e=>zl.test(e.reasonCode))?c(e,e=>o({method:"POST",path:`/orders/${e}/returns`,body:{idempotency_key:t.idempotencyKey,lines:t.lines.map(e=>({line_id:e.lineId,quantity:e.quantity,reason_code:e.reasonCode}))},read:el})):l(),getReturn:e=>c(e,e=>o({method:"GET",path:`/returns/${e}`,read:el})),cancelReturn:e=>c(e,e=>o({method:"POST",path:`/returns/${e}/cancel`,read:el})),openCase:(e,t)=>zl.test(t.reasonCode)&&t.message.length<=4e3?c(e,e=>o({method:"POST",path:`/orders/${e}/cases`,body:{idempotency_key:t.idempotencyKey,reason_code:t.reasonCode,message:t.message},read:tl})):l(),orderCases:e=>c(e,e=>o({method:"GET",path:`/orders/${e}/cases`,read:il})),plans:(e={})=>o({method:"GET",path:"/subscriptions",query:{cursor:e.cursor,limit:e.limit},read:xl}),buyAgain:()=>o({method:"GET",path:"/buy-again",read:bl}),createPlan:e=>Nl.test(e.paymentMethodId)?o({method:"POST",path:"/subscriptions",body:{idempotency_key:e.idempotencyKey,cadence_days:e.cadenceDays,destination:e.destination,payment_method_id:e.paymentMethodId,consent_terms_version:e.consentTermsVersion,lines:d(e.lines)},read:ml}):l(),updatePlan:(e,t)=>{if(t.paymentMethodId!==void 0&&!Nl.test(t.paymentMethodId))return l();let i={idempotency_key:t.idempotencyKey};if(t.lines&&(i.lines=d(t.lines)),t.cadenceDays!==void 0&&(i.cadence_days=t.cadenceDays),t.offerId!==void 0){if(!Sl(t.offerId)||t.cadenceDays===void 0||t.lines)return l();i.offer_id=t.offerId}return t.destination!==void 0&&(i.destination=t.destination),t.paymentMethodId!==void 0&&(i.payment_method_id=t.paymentMethodId),c(e,e=>o({method:"PATCH",path:`/subscriptions/${e}`,body:i,read:ml}))},planAction:(e,t)=>c(e,e=>o({method:"POST",path:`/subscriptions/${e}/actions`,body:{idempotency_key:t.idempotencyKey,operation:t.operation},read:ml})),cancelPlan:e=>c(e,e=>o({method:"POST",path:`/subscriptions/${e}/cancel`,read:ml})),cycleReview:e=>c(e,e=>o({method:"GET",path:`/subscriptions/${e}/cycle`,read:wl})),editCycle:(e,t,i)=>Number.isInteger(t)&&t>0?c(e,e=>o({method:"PUT",path:`/subscriptions/${e}/cycles/${t}/lines`,body:{idempotency_key:i.idempotencyKey,lines:d(i.lines)},read:wl})):l(),draftCycle:(e,t)=>Number.isInteger(t)&&t>0?c(e,e=>o({method:"POST",path:`/subscriptions/${e}/cycles/${t}/draft`,read:kl})):l(),approveCycle:(e,t,i)=>Number.isInteger(t)&&t>0&&Number.isInteger(i.expectedTotal)?c(e,e=>o({method:"POST",path:`/subscriptions/${e}/cycles/${t}/approve`,body:{idempotency_key:i.idempotencyKey,checkout_id:i.checkoutId,expected_total:i.expectedTotal},read:Do})):l(),skipCycle:(e,t,i)=>Number.isInteger(t)&&t>0?c(e,e=>o({method:"POST",path:`/subscriptions/${e}/cycles/${t}/skip`,body:{idempotency_key:i.idempotencyKey},read:ml})):l()}}var Il=/* @__PURE__ */new Set(["card_error","validation_error"]);function Tl(e){if(!e.error)return{ok:true};let{type:t,message:i}=e.error;return{ok:false,message:typeof t=="string"&&Il.has(t)&&typeof i=="string"&&i.length<=300?i:null}}function createStripeJsPayments(e,t={}){return{async confirmCardSetup(i){try{let r=t.returnUrl?{return_url:t.returnUrl}:void 0;return Tl(await e.confirmSetup({clientSecret:i,...t.elementsFor?{elements:t.elementsFor(i)}:{},...r?{confirmParams:r}:{},redirect:"if_required"}))}catch{return{ok:false,message:null}}},async handleNextAction(t){try{return Tl(await e.handleNextAction({clientSecret:t}))}catch{return{ok:false,message:null}}}}}exports.EverfurShop=EverfurShop2;exports.SHOP_COPY=Y;exports.SHOP_COPY_PLACEHOLDERS=X;exports.SHOP_ORDERS_V2_COPY=Us;exports.SHOP_V3_COPY=ee;exports.SHOP_V3_COPY_PLACEHOLDERS=te;exports.UNAVAILABLE_PACKAGE_SOURCE=Z;exports.createOmsClient=createOmsClient;exports.createOmsPackageSource=createOmsPackageSource;exports.createStripeJsPayments=createStripeJsPayments;exports.isOmsRefusal=isOmsRefusal;exports.isOmsRetryable=isOmsRetryable;exports.isOmsUnavailable=isOmsUnavailable;exports.newIdempotencyKey=newIdempotencyKey;exports.shopCopy=shopCopy;exports.shopOrdersV2Copy=shopOrdersV2Copy;exports.shopV3Copy=shopV3Copy;
@@ -1,9 +1,9 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
2
  import { ReactNode } from 'react';
3
- import { O as OmsClient, S as ShopPet, a as ShopPaymentsPort, b as ShopPackageSource, c as ShopCopy, d as ShopV3Copy, e as ShopRoute, f as ShopCardHandoff, g as ShopCardReturn, h as ShopProfileName, i as ShopOrdersV2Copy } from '../../idempotency.d-DrxKLPPe.cjs';
4
- export { j as OmsClientConfig, k as OmsConsumerAuth, l as OmsGetToken, m as SHOP_COPY, n as SHOP_COPY_PLACEHOLDERS, o as SHOP_ORDERS_V2_COPY, p as SHOP_V3_COPY, q as SHOP_V3_COPY_PLACEHOLDERS, r as ShopPackage, s as ShopPackageLine, t as ShopPaymentStepResult, u as ShopTabName, v as StripeJsErrorLike, w as StripeJsLike, x as StripeJsPaymentsOptions, U as UNAVAILABLE_PACKAGE_SOURCE, y as createOmsClient, z as createOmsPackageSource, A as createStripeJsPayments, B as newIdempotencyKey, C as shopCopy, D as shopOrdersV2Copy, E as shopV3Copy } from '../../idempotency.d-DrxKLPPe.cjs';
3
+ import { O as OmsClient, S as ShopPet, a as ShopPaymentsPort, b as ShopPackageSource, c as ShopCopy, d as ShopV3Copy, e as ShopRoute, f as ShopCardHandoff, g as ShopCardReturn, h as ShopProfileName, i as ShopOrdersV2Copy } from '../../idempotency.d-CcFLvzYW.cjs';
4
+ export { j as OmsClientConfig, k as OmsConsumerAuth, l as OmsGetToken, m as SHOP_COPY, n as SHOP_COPY_PLACEHOLDERS, o as SHOP_ORDERS_V2_COPY, p as SHOP_V3_COPY, q as SHOP_V3_COPY_PLACEHOLDERS, r as ShopPackage, s as ShopPackageLine, t as ShopPaymentStepResult, u as ShopTabName, v as StripeJsErrorLike, w as StripeJsLike, x as StripeJsPaymentsOptions, U as UNAVAILABLE_PACKAGE_SOURCE, y as createOmsClient, z as createOmsPackageSource, A as createStripeJsPayments, B as newIdempotencyKey, C as shopCopy, D as shopOrdersV2Copy, E as shopV3Copy } from '../../idempotency.d-CcFLvzYW.cjs';
5
5
  export { o as OmsAddress, a as OmsBuyAgainItem, p as OmsCartLine, q as OmsCents, j as OmsError, r as OmsOffer, b as OmsOrder, c as OmsOrderSummary, f as OmsPlan, s as OmsPlanChangeOption, t as OmsPlanOperation, m as OmsPlanSkipWarning, u as OmsPlanSkipWarningKey, n as OmsPrescription, g as OmsQuote, v as OmsQuoteLine, h as OmsReceipt, w as OmsReceiptCard, x as OmsReceiptLine, y as OmsResult, i as OmsShopConfig, z as OmsSupply, A as isOmsRefusal, B as isOmsRetryable, C as isOmsUnavailable } from '../../omsErrors.d-VF5tnr20.cjs';
6
- import '../../config.d-ClAI2RZ6.cjs';
6
+ import '../../config.d-Bn6GEGfl.cjs';
7
7
  import '../../EverfurError.d-8NHtlgzA.cjs';
8
8
  import '../../EverfurResult.d-BFH-3s6E.cjs';
9
9
 
@@ -1,9 +1,9 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
2
  import { ReactNode } from 'react';
3
- import { O as OmsClient, S as ShopPet, a as ShopPaymentsPort, b as ShopPackageSource, c as ShopCopy, d as ShopV3Copy, e as ShopRoute, f as ShopCardHandoff, g as ShopCardReturn, h as ShopProfileName, i as ShopOrdersV2Copy } from '../../idempotency.d-CbB07p64.js';
4
- export { j as OmsClientConfig, k as OmsConsumerAuth, l as OmsGetToken, m as SHOP_COPY, n as SHOP_COPY_PLACEHOLDERS, o as SHOP_ORDERS_V2_COPY, p as SHOP_V3_COPY, q as SHOP_V3_COPY_PLACEHOLDERS, r as ShopPackage, s as ShopPackageLine, t as ShopPaymentStepResult, u as ShopTabName, v as StripeJsErrorLike, w as StripeJsLike, x as StripeJsPaymentsOptions, U as UNAVAILABLE_PACKAGE_SOURCE, y as createOmsClient, z as createOmsPackageSource, A as createStripeJsPayments, B as newIdempotencyKey, C as shopCopy, D as shopOrdersV2Copy, E as shopV3Copy } from '../../idempotency.d-CbB07p64.js';
3
+ import { O as OmsClient, S as ShopPet, a as ShopPaymentsPort, b as ShopPackageSource, c as ShopCopy, d as ShopV3Copy, e as ShopRoute, f as ShopCardHandoff, g as ShopCardReturn, h as ShopProfileName, i as ShopOrdersV2Copy } from '../../idempotency.d-CvqKG3Uq.js';
4
+ export { j as OmsClientConfig, k as OmsConsumerAuth, l as OmsGetToken, m as SHOP_COPY, n as SHOP_COPY_PLACEHOLDERS, o as SHOP_ORDERS_V2_COPY, p as SHOP_V3_COPY, q as SHOP_V3_COPY_PLACEHOLDERS, r as ShopPackage, s as ShopPackageLine, t as ShopPaymentStepResult, u as ShopTabName, v as StripeJsErrorLike, w as StripeJsLike, x as StripeJsPaymentsOptions, U as UNAVAILABLE_PACKAGE_SOURCE, y as createOmsClient, z as createOmsPackageSource, A as createStripeJsPayments, B as newIdempotencyKey, C as shopCopy, D as shopOrdersV2Copy, E as shopV3Copy } from '../../idempotency.d-CvqKG3Uq.js';
5
5
  export { o as OmsAddress, a as OmsBuyAgainItem, p as OmsCartLine, q as OmsCents, j as OmsError, r as OmsOffer, b as OmsOrder, c as OmsOrderSummary, f as OmsPlan, s as OmsPlanChangeOption, t as OmsPlanOperation, m as OmsPlanSkipWarning, u as OmsPlanSkipWarningKey, n as OmsPrescription, g as OmsQuote, v as OmsQuoteLine, h as OmsReceipt, w as OmsReceiptCard, x as OmsReceiptLine, y as OmsResult, i as OmsShopConfig, z as OmsSupply, A as isOmsRefusal, B as isOmsRetryable, C as isOmsUnavailable } from '../../omsErrors.d-VF5tnr20.js';
6
- import '../../config.d-B7Z-KTGq.js';
6
+ import '../../config.d-Bc41Ax6M.js';
7
7
  import '../../EverfurError.d-8NHtlgzA.js';
8
8
  import '../../EverfurResult.d-D_-254ZY.js';
9
9
 
@@ -1,6 +1,6 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
2
  "use client";
3
- import{UI_ICON_BOX as e,BlockScope as r,useBlockStyles as t,thumbnailCss as a,Thumbnail as i,cartLineCss as n,CartLine as l}from"../../chunk-ZSCVH4UW.js";import{EverfurConfigError as s,parseUrl as o,planTokens as d,PLAN_RULES as c,PLAN_CONTEXT as u,PLAN_BEFORE_CLASS as p}from"../../chunk-DBQYQLJT.js";import{registerIcons as h,renderRuntimePart as f,useEverfurTheme,LinkComponentProvider as m,v3Palette as v,everfurTheme as g,ThemeProvider as b,summaryListCss as y,SummaryList as k,iconCss as w,useEfdsPart as x,cx as _,dataOf as N,useTheme as I,useWebPressLayer as C,useLinkComponent as $,BlockIcon as S,Icon as P,SvgIcon as L,UI_ICON_CHEVRON as T,avatarSpec as A,initialsOf as M}from"../../chunk-CQUKIPRU.js";import{createContext,forwardRef as z,useMemo as O,useState as q,useRef as R,createElement as E,useEffect as B,useContext as j,useLayoutEffect as F,useCallback as U,useSyncExternalStore as V,useId as D,Fragment as W,Children as H,isValidElement as K}from"react";import{jsx as G,jsxs as Q,Fragment as Y}from"react/jsx-runtime";import{createPortal as Z}from"react-dom";var J=/* @__PURE__ */new WeakMap,X=[];function ee(e){let r=J.get(e);return r||(r={items:X,flash:null,storage:null,binding:null,lastKey:null,listeners:/* @__PURE__ */new Set},J.set(e,r)),r}function re(e,r){let t=ee(e);if(t.items=r,t.storage)try{t.storage.write(JSON.stringify(r))}catch{}for(let e of[...t.listeners])e()}function te(e){return Math.max(1,Math.min(5,Math.round(e)))}function ae(e){return`${e.offerId}|${e.petId??""}|${e.rxId??""}`}var ie=e=>typeof e=="string"&&e!=="";function ne(e){return typeof e=="string"&&/^https:\/\/[^\s]+$/i.test(e)?e:null}function le(e){if(!e)return X;let r;try{r=JSON.parse(e)}catch{return X}if(!Array.isArray(r))return X;let t=[];for(let e of r){if(!e||typeof e!="object")continue;let r=e;if(!ie(r.offerId)||typeof r.title!="string"||typeof r.quantity!="number"||!Number.isFinite(r.quantity))continue;let a=typeof r.unitPrice=="number"&&Number.isFinite(r.unitPrice)?r.unitPrice:null,i=ie(r.petId)?r.petId:void 0,n=ie(r.rxId)?r.rxId:void 0,l=ne(r.imageUrl),s={offerId:r.offerId,...i?{petId:i}:{},...n?{rxId:n}:{}},o=ae(s);t.some(e=>e.key===o)||t.push({...s,key:o,title:r.title,unitPrice:a,requiresRx:r.requiresRx===true,quantity:n?Math.max(1,Math.round(r.quantity)):te(r.quantity),...l?{imageUrl:l}:{}})}return t.length>0?t:X}function se(e,r){let t=ee(e);if(!(!r||t.storage)&&(t.storage=r,t.items.length===0)){let e=null;try{e=r.read()}catch{e=null}t.items=le(e)}}function oe(e){let r;try{r=globalThis.sessionStorage}catch{return null}if(!r||typeof r.getItem!="function"||typeof r.setItem!="function")return null;let t=r;return{read:()=>t.getItem(e),write:r=>t.setItem(e,r)}}function de(e){return ee(e).items}function ce(e,r){let t=ae(r),a=de(e),i=a.find(e=>e.key===t),n=r.rxId?Math.max(1,Math.round(r.quantity)):te((i?.quantity??0)+r.quantity),l={...r,key:t,quantity:n};return re(e,i?a.map(e=>e.key===t?l:e):[...a,l]),l}function ue(e,r,t){let a=de(e);re(e,a.map(e=>e.key===r&&!e.rxId?{...e,quantity:te(t)}:e))}function pe(e,r){let t=de(e),a=t.find(e=>e.key===r)??null;return a&&re(e,t.filter(e=>e.key!==r)),a}function he(e,r){let t=new Set(r),a=de(e);a.some(e=>t.has(e.key))&&re(e,a.filter(e=>!t.has(e.key)))}function fe(e,r){ee(e).flash=r}function me(e){let r=ee(e),t=r.flash;return r.flash=null,t}function ve(e){return e.map(e=>({offerId:e.offerId,quantity:e.quantity,...e.petId?{petId:e.petId}:{},...e.rxId?{rxId:e.rxId}:{}}))}function ge(e){let r=0;for(let t of e){if(t.unitPrice===null)return null;r+=t.unitPrice*t.quantity}return r}function be(e){return e.reduce((e,r)=>e+r.quantity,0)}function ye(e){let r=ee(e);return V(e=>(r.listeners.add(e),()=>{r.listeners.delete(e)}),()=>r.items,()=>r.items)}function ke(e){/* @__PURE__ */
3
+ import{UI_ICON_BOX as e,BlockScope as r,useBlockStyles as t,thumbnailCss as a,Thumbnail as i,cartLineCss as n,CartLine as l}from"../../chunk-6E3J6IVM.js";import{EverfurConfigError as s,parseUrl as o,planTokens as d,PLAN_RULES as c,PLAN_CONTEXT as u,PLAN_BEFORE_CLASS as p}from"../../chunk-ULQDOC75.js";import{registerIcons as h,renderRuntimePart as f,useEverfurTheme,LinkComponentProvider as m,v3Palette as v,everfurTheme as g,ThemeProvider as b,summaryListCss as y,SummaryList as k,iconCss as w,useEfdsPart as x,cx as _,dataOf as N,useTheme as I,useWebPressLayer as C,useLinkComponent as $,BlockIcon as S,Icon as P,SvgIcon as L,UI_ICON_CHEVRON as T,avatarSpec as A,initialsOf as M}from"../../chunk-J5ZUBY3S.js";import{createContext,forwardRef as z,useMemo as O,useState as q,useRef as R,createElement as E,useEffect as B,useContext as j,useLayoutEffect as F,useCallback as U,useSyncExternalStore as V,useId as D,Fragment as W,Children as H,isValidElement as K}from"react";import{jsx as G,jsxs as Q,Fragment as Y}from"react/jsx-runtime";import{createPortal as Z}from"react-dom";var J=/* @__PURE__ */new WeakMap,X=[];function ee(e){let r=J.get(e);return r||(r={items:X,flash:null,storage:null,binding:null,lastKey:null,listeners:/* @__PURE__ */new Set},J.set(e,r)),r}function re(e,r){let t=ee(e);if(t.items=r,t.storage)try{t.storage.write(JSON.stringify(r))}catch{}for(let e of[...t.listeners])e()}function te(e){return Math.max(1,Math.min(5,Math.round(e)))}function ae(e){return`${e.offerId}|${e.petId??""}|${e.rxId??""}`}var ie=e=>typeof e=="string"&&e!=="";function ne(e){return typeof e=="string"&&/^https:\/\/[^\s]+$/i.test(e)?e:null}function le(e){if(!e)return X;let r;try{r=JSON.parse(e)}catch{return X}if(!Array.isArray(r))return X;let t=[];for(let e of r){if(!e||typeof e!="object")continue;let r=e;if(!ie(r.offerId)||typeof r.title!="string"||typeof r.quantity!="number"||!Number.isFinite(r.quantity))continue;let a=typeof r.unitPrice=="number"&&Number.isFinite(r.unitPrice)?r.unitPrice:null,i=ie(r.petId)?r.petId:void 0,n=ie(r.rxId)?r.rxId:void 0,l=ne(r.imageUrl),s={offerId:r.offerId,...i?{petId:i}:{},...n?{rxId:n}:{}},o=ae(s);t.some(e=>e.key===o)||t.push({...s,key:o,title:r.title,unitPrice:a,requiresRx:r.requiresRx===true,quantity:n?Math.max(1,Math.round(r.quantity)):te(r.quantity),...l?{imageUrl:l}:{}})}return t.length>0?t:X}function se(e,r){let t=ee(e);if(!(!r||t.storage)&&(t.storage=r,t.items.length===0)){let e=null;try{e=r.read()}catch{e=null}t.items=le(e)}}function oe(e){let r;try{r=globalThis.sessionStorage}catch{return null}if(!r||typeof r.getItem!="function"||typeof r.setItem!="function")return null;let t=r;return{read:()=>t.getItem(e),write:r=>t.setItem(e,r)}}function de(e){return ee(e).items}function ce(e,r){let t=ae(r),a=de(e),i=a.find(e=>e.key===t),n=r.rxId?Math.max(1,Math.round(r.quantity)):te((i?.quantity??0)+r.quantity),l={...r,key:t,quantity:n};return re(e,i?a.map(e=>e.key===t?l:e):[...a,l]),l}function ue(e,r,t){let a=de(e);re(e,a.map(e=>e.key===r&&!e.rxId?{...e,quantity:te(t)}:e))}function pe(e,r){let t=de(e),a=t.find(e=>e.key===r)??null;return a&&re(e,t.filter(e=>e.key!==r)),a}function he(e,r){let t=new Set(r),a=de(e);a.some(e=>t.has(e.key))&&re(e,a.filter(e=>!t.has(e.key)))}function fe(e,r){ee(e).flash=r}function me(e){let r=ee(e),t=r.flash;return r.flash=null,t}function ve(e){return e.map(e=>({offerId:e.offerId,quantity:e.quantity,...e.petId?{petId:e.petId}:{},...e.rxId?{rxId:e.rxId}:{}}))}function ge(e){let r=0;for(let t of e){if(t.unitPrice===null)return null;r+=t.unitPrice*t.quantity}return r}function be(e){return e.reduce((e,r)=>e+r.quantity,0)}function ye(e){let r=ee(e);return V(e=>(r.listeners.add(e),()=>{r.listeners.delete(e)}),()=>r.items,()=>r.items)}function ke(e){/* @__PURE__ */
4
4
  return Object.freeze({ok:true,value:e})}function we(e){/* @__PURE__ */
5
5
  return Object.freeze({ok:false,error:/* @__PURE__ */Object.freeze(e)})}function isOmsRefusal(e,r){return e.kind==="refused"&&(r===void 0||e.reasonCode===r)}function isOmsUnavailable(e){return e.kind==="unavailable"}function isOmsRetryable(e){return e.kind==="network"||e.kind==="timeout"||e.kind==="serviceUnavailable"||e.kind==="refused"&&e.reasonCode==="order_state_conflict"}var xe=/^[a-z][a-z0-9_]{0,63}$/,_e=300;function Ne(e){if(typeof e!="string")return null;let r=e.replace(/[\u0000-\u001f\u007f]+/g," ").trim();return r.length===0||r.length>_e?null:r}function Ie(e){if(!e)return null;let r=Number(e);return Number.isFinite(r)&&r>=0?Math.min(Math.round(r),3600):null}function Ce(e,r,t){let a=t.requestId,i=a?{requestId:a}:{};if(e===404)return{kind:"unavailable",...i};if(e===401)return{kind:"signedOut"};if(e===402||e===409||e===422){let t=r&&typeof r=="object"?r:{},a=typeof t.reason_code=="string"&&xe.test(t.reason_code)?t.reason_code:null;return{kind:"refused",status:e,reasonCode:a,message:Ne(t.message),...i}}return e===400?{kind:"invalidRequest",...i}:e===429?{kind:"rateLimited",retryAfterSeconds:Ie(t.retryAfter??null),...i}:e===503?{kind:"serviceUnavailable",...i}:e===403?{kind:"unavailable",...i}:{kind:"serverError",status:e,...i}}function newIdempotencyKey(){let e=globalThis.crypto;if(e&&typeof e.randomUUID=="function")return e.randomUUID();if(e&&typeof e.getRandomValues=="function"){let r=e.getRandomValues(new Uint8Array(16));r[6]=r[6]&15|64,r[8]=r[8]&63|128;let t=Array.from(r,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}throw new s("missing-peer-dependency","No secure random source: cannot make an idempotency key")}var $e=3,Se=["client_name_missing"];function Pe(e){return!!e&&e.kind==="refused"&&!!e.reasonCode&&Se.includes(e.reasonCode)}var Le=class{constructor(e=newIdempotencyKey){this.make=e;this.keys=/* @__PURE__ */new Map}key(e){let r=this.keys.get(e);return r||(r=this.make(),this.keys.set(e,r)),r}next(e){let r=this.make();return this.keys.set(e,r),r}};async function Te(e,r,t,a={reconfirm:true}){let i=r.key("confirm"),n=[];for(let l=0;l<$e;l+=1){let s=await e(i);if(!s.ok)return{kind:"failed",error:s.error};n=s.value.resale.map(e=>e.orderId);let o=s.value.resale.filter(e=>e.outcome==="action_required"&&e.payerAction);if(o.length===0)return{kind:"confirmed",orderIds:n};if(!t)return{kind:"needsPayerAction",orderIds:n};if(l===0&&a.beforePayerAction)try{a.beforePayerAction(n)}catch{}for(let e of o){let r=await t.handleNextAction(e.payerAction,{orderId:e.orderId});if(!r.ok)return r.closed?{kind:"payerActionClosed",orderIds:n}:{kind:"payerActionFailed",orderIds:n,message:r.message}}if(!a.reconfirm)return{kind:"confirmed",orderIds:n};i=r.next("confirm")}return{kind:"needsPayerAction",orderIds:n}}function Ae(e){let r=e<0?"-":"",t=Math.abs(Math.round(e));return`${r}$${Math.floor(t/100).toLocaleString("en-US")}.${String(t%100).padStart(2,"0")}`}function Me(e){return`[copy:shop.${e}]`}var ze=["January","February","March","April","May","June","July","August","September","October","November","December"];function Oe(e){return`${e}’s`}function qe(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function Re(e){if(!e)return null;let r=new Date(/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e);return Number.isNaN(r.getTime())?null:r}function Ee(e,r={}){let t=Re(e);if(!t)return null;if(r.when&&t.getUTCFullYear()!==(r.now??/* @__PURE__ */new Date).getUTCFullYear())return t.toLocaleDateString("en-US",{timeZone:"UTC",month:"short",day:"numeric",year:"numeric"});let a=r.weekday===true||r.when===true;return t.toLocaleDateString("en-US",{timeZone:"UTC",...a?{weekday:"short"}:{},month:"short",day:"numeric"})}function formatWhen(e){let r=Re(e);if(!r)return null;let t=r.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}),a=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"});return`${t} · ${a}`}function Be(e){let r=Re(e);return r?ze[r.getUTCMonth()]:null}function je(e,r){return`${e?e.charAt(0).toUpperCase()+e.slice(1):""} ending ${r}`}var Fe="We can’t send this prescription to the pharmacy yet. Contact us.",Ue=["prescription_missing","prescription_reference_missing","prescription_unreadable","prescriptions_disagree","first_fill_mixed_with_refill","duplicate_prescription_line","prescription_in_flight","client_email_missing","client_phone_missing","client_phone_not_us","practice_email_missing","practice_phone_missing","practice_phone_not_us","patient_birth_date_missing","patient_weight_missing","weight_below_partner_unit","species_not_supported","sex_not_supported","refills_over_partner_limit","indications_missing","indication_not_mapped","compounding_missing","compounding_reason_not_mapped","compounding_unexplained","delivery_speed_unavailable","address_missing","address_not_deliverable"],Ve={tabsLabel:"Care",tabPackage:"Package",tabShop:"Shop",tabOrders:"Orders",tabPlan:"Plan",legal:"Prescription items need a valid prescription from a licensed vet, and are filled by a licensed partner pharmacy.",legalTracking:"Prescription items are filled by a licensed partner pharmacy.",loadFailed:e=>`We couldn’t load ${e}. Check your connection and try again.`,tryAgain:"Try again",actionFailed:"That didn’t go through. Try again.",saving:"Saving…",keepIt:"Keep it",close:"Close",thingPackage:Me("thing.package"),thingShop:Me("thing.shop"),thingProduct:Me("thing.product"),thingPlan:Me("thing.plan"),thingOrders:"your orders",thingOrder:"this order",packageTitle:e=>`${e} package`,packageSub:(e,r,t)=>{let a=[];return e.length>0&&a.push(`For ${qe(e)}.`),r&&t&&a.push(`Approve by ${r} and it arrives ${t}.`),a.length?a.join(" "):null},inThisPackage:"In this package",reviewBy:e=>`Review by ${e}`,forPet:e=>`For ${e}`,details:"Details",remove:"Remove",removed:"Removed.",total:"Total",items:"Items",shipping:"Shipping",tax:"Tax",free:"Free",approveAndShip:"Approve and ship",itemCount:e=>e===1?Me("package.item_count_one"):`${e} items`,withTotal:(e,r)=>`${e} · ${r}`,approveRegion:"Approve",packageDetailsRegion:"Package details",deliveryPaymentRegion:"Delivery and payment",questionsRegion:"Questions",approving:"Approving…",skipThisMonth:"Skip this month",chargedWhenShips:e=>`Charged to ${e} when it ships.`,rxCheckedFirst:"Prescriptions are checked with the vet who wrote them first.",delivery:"Delivery",arrives:e=>`Arrives ${e}`,change:"Change",outOfStock:"Out of stock",packageOutOfStock:"Out of stock right now, so it won’t ship this month.",packageEmpty:e=>`Nothing in ${Oe(e)} package yet. Add something from the shop, or skip this month.`,itemNoLongerSold:Me("package.item_no_longer_sold"),reviewClosed:Me("package.review_closed"),approvalInProgress:Me("package.approval_in_progress"),priceChanged:Me("package.price_changed"),cardStepFailed:Me("package.card_step_failed"),cardStepClosed:Me("package.card_step_closed"),noCardOnFile:Me("package.no_card_on_file"),shopTitle:"Shop",searchLabel:"Search the shop",searchPlaceholder:"Search the shop…",filtersLabel:"Filter",filterAll:"All",refillSoon:"Refill soon",prescribedFor:e=>`Prescribed for ${qe(e)}`,inMonthsPackage:e=>`In ${Oe(e)} package →`,forPets:e=>`For ${qe(e)}`,allProducts:Me("shop.all_products_title"),rx:"Rx",hasPrescription:e=>`${e} has a prescription`,needsPrescription:"Needs a prescription",noMatches:e=>`Nothing in the shop matches ‘${e}’.`,nothingHereYet:"Nothing here yet.",photoToCome:"Photo to come",backToShop:"Shop",howOften:"How often",everyMonthIn:e=>`Every month, in ${Oe(e)} package`,skipOrStop:"Skip or stop any month",justOnce:"Just once",shipsWith:e=>`Ships with ${Oe(e)} package`,justOnceShipsNow:Me("product.just_once_meta"),oneFewer:"One fewer",oneMore:"One more",quantity:"Quantity",addToPackage:e=>`Add to ${Oe(e)} package`,refillInPackage:e=>`Refill in ${Oe(e)} package`,buyNow:Me("product.buy_now"),startPlan:Me("product.start_plan"),adding:"Adding…",outOfStockNow:"Out of stock right now.",prescription:"Prescription",noPrescriptionFor:e=>`No prescription for ${e} on file.`,bookVideoVisit:"Book a video visit",refillsLeft:e=>`${e} ${e===1?"refill":"refills"} left`,rxBeingPrepared:"This prescription is being prepared. You can order it soon.",rxTooSoon:Me("rx.too_soon"),rxRenew:Me("rx.needs_renewal"),rxPick:Me("rx.pick_pet"),educational:"Educational, not a diagnosis.",planTitle:"Your plan",whatRepeats:"What repeats",repeatsLabel:e=>`${e} repeats`,cadenceMonths:e=>e===1?"Every month":`Every ${e} months`,cadenceDays:Me("plan.cadence_days"),repeatsEmpty:"Nothing repeats yet. Pick Every month when you add something, and it shows up here.",nextPackage:"Next package",reviewByLabel:"Review by",ships:"Ships",reviewMonthsPackage:e=>`Review ${Oe(e)} package →`,deliveryAndPayment:"Delivery and payment",shipTo:"Ship to",payWith:"Pay with",needABreak:"Need a break?",skipMonth:e=>`Skip ${e}`,skipMonthAsk:e=>`Skip ${e}?`,skipMonthBody:"Nothing ships this month.",pausePlan:"Pause the plan",pausePlanAsk:"Pause the plan?",pausePlanBody:"Nothing ships until you turn it back on.",declined:e=>e?`Declined. Update your card so ${Oe(e)} package can ship.`:"Declined.",resumePlan:Me("plan.resume"),stopReason:e=>Me(`plan.stop_reason.${e}`),consentTitle:Me("plan.consent_title"),consentBody:Me("plan.consent_body"),consentTermsLink:Me("plan.consent_terms_link"),consentAgree:Me("plan.consent_agree"),ordersTitle:"Orders",ordersSub:e=>`Packages and one-off orders for ${qe(e)}.`,allOrders:"All orders",placed:e=>`Placed ${e}`,ordersEmpty:"No orders yet. Your first package shows up here once you approve it.",paymentFailed:"Payment failed",backToCare:"Care",onItsWay:e=>`${e}, on its way`,shouldArrive:e=>`It should arrive ${e}.`,whereItStands:"Where it stands",stepApproved:"Approved",stepChecking:"Checking prescriptions…",stepFilled:"Filled by the pharmacy",stepShipped:"Shipped",stepDelivered:"Delivered",now:"Now",expected:e=>`Expected ${e}.`,inTheBox:"In the box",payment:"Payment",cancelOrder:Me("order.cancel"),payOrder:Me("order.pay"),trackPackage:Me("order.track"),orderStatus:{pending_placement:"Confirmed, sending to the pharmacy",placement_unknown:"Confirmed",placed:"With the pharmacy, in review",accepted:"Approved by the pharmacist",release_sent:"Approved, being prepared",release_unknown:"Approved, being prepared",released:"Being prepared",shipped:"Shipped",delivered:"Delivered",needs_support:"We’re looking into this order",rejected:Me("order.status.rejected"),cancelled:"Cancelled",pending_handoff:Me("order.status.pending_handoff")},addressTitle:Me("address.title"),addressLabel:Me("address.label"),addressRecipient:Me("address.recipient_name"),addressLine1:Me("address.line1"),addressLine2:Me("address.line2"),addressCity:Me("address.city"),addressRegion:Me("address.region"),addressPostal:Me("address.postal_code"),addressSave:Me("address.save"),addressNeeded:Me("address.needed"),cardTitle:Me("card.title"),cardBody:Me("card.body"),cardStart:Me("card.start"),cardUnavailable:Me("card.unavailable"),confirmTitle:Me("buy.confirm_title"),confirmPay:Me("buy.confirm_pay"),nameMissing:Me("checkout.name_missing"),addName:Me("checkout.add_name"),firstName:Me("checkout.first_name"),lastName:Me("checkout.last_name"),saveName:Me("checkout.save_name"),refusal:{operation_not_supported:"This action isn’t available for this order.",order_not_sellable:"We can’t ship this order as it is. Add items or contact us.",rx_being_prepared:"This prescription is being prepared. You can order it soon.",rx_not_dispensable:Fe,...Object.fromEntries(Ue.map(e=>[e,Fe])),order_state_conflict:"This order changed. Refresh and try again.",payment_method_in_use:"A subscription or an order uses this card."},rateLimited:Me("error.rate_limited")},De=(()=>{let e=/* @__PURE__ */new Set,r=t=>{if(typeof t=="string"){let r=/^\[copy:(shop\.[a-z0-9_.]+)\]$/.exec(t);r&&e.add(r[1])}else if(typeof t=="function")try{r(t("x","x","x"))}catch{}else if(t&&typeof t=="object")for(let e of Object.values(t))r(e)};return r(Ve),[...e].sort()})();function shopCopy(e){return e?{...Ve,...e}:Ve}function We(e,r){if(r.kind==="rateLimited")return e.rateLimited;if(r.kind==="refused"){if(Pe(r))return e.nameMissing;let t=r.reasonCode?e.refusal[r.reasonCode]:void 0;if(t)return t}return e.actionFailed}var He=/* @__PURE__ */Object.freeze({load:()=>Promise.resolve(we({kind:"unavailable"})),removeLine:()=>Promise.resolve(we({kind:"unavailable"})),skip:()=>Promise.resolve(we({kind:"unavailable"})),approve:()=>Promise.resolve({kind:"failed",error:{kind:"unavailable"}})});async function Ke(e,r){let t=[...new Set(r)],a=await Promise.all(t.map(r=>e.offer(r)));return new Map(t.map((e,r)=>[e,a[r].ok?a[r].value:null]))}function createOmsPackageSource(e){async function r(r,t){let a=await Ke(e,t.lines.map(e=>e.offerId)),i=t.lines.map(e=>({...e,offer:a.get(e.offerId)??null})),n=null;if(t.state==="open"&&i.length>0){let a=await e.draftCycle(r.planId,t.cycle);if(a.ok)n=a.value;else if(a.error.kind!=="refused")return we(a.error)}return ke({plan:r,review:t,lines:i,draft:n})}return{async load(){let t=await e.plans();if(!t.ok)return we(t.error);let a=t.value.plans.find(e=>e.state==="active")??t.value.plans.find(e=>e.state!=="cancelled");if(!a)return ke(null);let i=await e.cycleReview(a.planId);return i.ok?r(a,i.value):we(i.error)},async removeLine(t,a,i){let n=t.lines.filter((e,r)=>r!==a).map(e=>({offerId:e.offerId,quantity:e.quantity,...e.petId?{petId:e.petId}:{}})),l=await e.editCycle(t.plan.planId,t.review.cycle,{idempotencyKey:i.key(`remove:${a}`),lines:n});return l.ok?r(t.plan,l.value):we(l.error)},async skip(r,t){let a=await e.skipCycle(r.plan.planId,r.review.cycle,{idempotencyKey:t.key("skip")});return a.ok?ke(void 0):we(a.error)},approve(r,t,a){let i=r.draft;return i?Te(t=>e.approveCycle(r.plan.planId,r.review.cycle,{idempotencyKey:t,checkoutId:i.checkoutId,expectedTotal:i.total}),t,a,{reconfirm:false}):Promise.resolve({kind:"failed",error:{kind:"invalidRequest"}})}}}var Ge={cartTitle:"Cart",cartLabel:e=>e>0?`Cart, ${e} item${e>1?"s":""}`:"Cart, empty",cartEmptyTitle:"Your cart is empty",cartEmptyBody:null,addToCart:"Add to cart",viewCart:"View cart",addedToCart:e=>`${e} is in your cart.`,removedFromCart:e=>`${e} is out of your cart.`,quantityLabel:e=>`How many: ${e}`,fewer:"One fewer",more:"One more",remove:"Remove",subtotal:"Subtotal",shipping:"Shipping",tax:"Tax",free:"Free",total:"Total",checkoutCart:e=>`Checkout · ${e}`,checkoutKicker:"Checkout",itemQuantity:e=>`Qty ${e}`,shipsTo:"Ships to",payWith:"Pay with",placeOrder:e=>`Place order · ${e}`,chooseAddress:Me("checkout.choose_address"),chooseCard:Me("checkout.choose_card"),addAddress:Me("checkout.add_address"),addCard:Me("card.start"),makeDefault:Me("address.make_default"),editAddress:Me("address.edit"),noAddressYet:Me("address.needed"),noCardYet:Me("package.no_card_on_file"),placedHeader:"Order placed",placedTitle:"Order placed.",placedSteps:"What's coming",placedShips:"It ships.",placedArrives:"It arrives at home.",viewOrder:"View order",ordersTitle:"Orders",ordersEmptyTitle:"No orders yet",ordersEmptyBody:null,moreOrders:Me("orders.more"),subscriptionBox:"Subscription box",orderTitle:e=>e===null?"Order":`Order ${e}`,arrivesBy:e=>`Arrives by ${e}`,deliveredOn:e=>`Delivered ${e}`,expected:e=>`Expected ${e}`,orderSteps:["Ordered","Shipped","Out for delivery","Delivered"],tracking:"Tracking",trackOn:e=>`Track on ${e}`,inThisOrder:"In this order",orderItemLine:e=>`Qty ${e}`,buyAgain:"Buy again",orderHelp:"Get help with this order",paidWith:"Paid with",refund:Me("order.refund"),discount:Me("order.discount"),cancelAsk:Me("order.cancel_ask"),cancelBody:null,cancelRequested:Me("order.cancel_requested"),close:"Close",manageKicker:"Your subscription",manageTitle:e=>`Manage ${e}`,manage:"Manage",shipsEvery:"Ships every",daysChip:e=>`${e} days`,skipNext:"Skip the next box",cancelSubscription:"Cancel subscription",nextBox:e=>`Next box ${e}`,everyDays:e=>`Every ${e} days`,subscribedLine:(e,r)=>r===null?`Every ${e} days`:`Every ${e} days · next box ${r}`,skipped:"Skipped.",cancelSubscriptionAsk:Me("plan.cancel_ask"),cancelSubscriptionBody:Me("plan.cancel_body")},Qe=Object.values(Ge).filter(e=>typeof e=="string"&&e.startsWith("[copy:"));function shopV3Copy(e){if(!e)return Ge;let r={};for(let[t,a]of Object.entries(e))t in Ge&&a!==void 0&&(r[t]=a);return{...Ge,...r}}var Ye=createContext(null);function ShopProvider(e){let{client:r,pets:t,payments:a,packageSource:i,copy:n,v3Copy:l,saveProfileName:s,onProfileNameRequired:o,children:d}=e,c=R(s);c.current=s;let u=R(o);u.current=o;let p=!!s,h=!!o,f=O(()=>{let e=t??[],s=new Map(e.map(e=>[e.petId,e.name]));return{client:r,pets:e,petName:e=>e?s.get(e)??null:null,payments:a??null,packageSource:i??createOmsPackageSource(r),copy:shopCopy(n),v3:shopV3Copy(l),saveProfileName:p?e=>c.current?c.current(e):Promise.resolve(false):null,onProfileNameRequired:h?()=>u.current?.():null}},[r,t,a,i,n,l,p,h]);return E(Ye.Provider,{value:f},d)}function Ze(){let e=j(Ye);if(!e)throw new s("not-initialized","useShop: wrap the shop in <ShopProvider>");return e}function Je(e,r){let[t,a]=q({key:null,phase:"loading",value:null,error:null}),i=R(0),n=R(null),l=R(r);l.current=r;let s=U(r=>{let t=++i.current;if(e===null)return Promise.resolve();r||a({key:e,phase:"loading",value:null,error:null});let s=l.current().then(n=>{if(t!==i.current)return;if(n.ok){a({key:e,phase:"ready",value:n.value,error:null});return}let l={key:e,phase:n.error.kind==="unavailable"?"unavailable":"failed",value:null,error:n.error};r&&l.phase==="failed"?a(r=>r.key===e&&r.phase==="ready"?r:l):a(l)},()=>{});return n.current={epoch:t,done:s},s.then(()=>{n.current?.epoch===t&&(n.current=null)}),s},[e]);B(()=>(s(false),()=>{i.current+=1}),[s]);let o=U(()=>{s(false)},[s]),d=U(()=>{let e=n.current;return e&&e.epoch===i.current?e.done:s(true)},[s]);return t.key!==e?{phase:"loading",value:null,error:null,refresh:o,reread:d}:{phase:t.phase,value:t.value,error:t.error,refresh:o,reread:d}}function Xe(){let{client:e}=Ze();return Je("shop-config",()=>e.shopConfig())}function er(e={}){let{client:r}=Ze(),t=e.text?.trim()??"",a=`offers:${t}:${e.requiresRx??""}`;return Je(a,()=>r.offers({...t?{text:t}:{},...e.requiresRx!==void 0?{requiresRx:e.requiresRx}:{},limit:100}))}function rr(e){let{client:r}=Ze();return Je(e?`offer:${e}`:null,()=>r.offer(e))}function tr(){let{client:e}=Ze();return Je("prescriptions",()=>e.prescriptions())}function ar(){let{client:e}=Ze();return Je("addresses",()=>e.addresses())}function ir(e){let{client:r}=Ze();return Je(e?`address:${e}`:null,()=>r.address(e))}function nr(){let{client:e}=Ze();return Je("payment-methods",()=>e.paymentMethods())}function lr(e){let{client:r}=Ze();return Je(e?`order:${e}`:null,()=>r.order(e))}function sr(){let{client:e}=Ze();return Je("plans",()=>e.plans({limit:100}))}function or(){let{packageSource:e}=Ze();return Je("package",()=>e.load())}function dr(e){let[r,t]=q(false),[a,i]=q(null),n=R(null),l=R(false),s=R(e);s.current=e;let o=R(true);B(()=>(o.current=true,()=>{o.current=false}),[]);let d=U(async(...e)=>{if(l.current)return null;l.current=true,n.current??=new Le,t(true),i(null);try{let r=await s.current(n.current,...e);return r.ok?n.current=null:cr(r.error)||(n.current=null),o.current&&i(r.ok?null:r.error),r}finally{l.current=false,o.current&&t(false)}},[]),c=U(()=>{n.current=null,i(null)},[]);return{busy:r,error:a,run:d,reset:c}}function cr(e){return e.kind==="network"||e.kind==="timeout"||e.kind==="serviceUnavailable"||e.kind==="serverError"}function ur(e){let r=[];for(let t of e)t!==null&&!r.includes(t)&&r.push(t);return r}var pr=[[/\b(inject(ion|able)?|vial|syringe|pen)s?\b/i,"syringe"],[/\b(chew(able)?|soft ?chew|treat)s?\b/i,"bowl"],[/\b(shampoo|spray|ointment|cream|gel|lotion|topical|spot[- ]on|otic|ophthalmic|wipe|foam|mousse|collar)s?\b/i,"shield"],[/\b(solution|suspension|liquid|syrup|elixir|drops?|oral ?paste|paste)s?\b/i,"flask"],[/\b(tablet|caplet|capsule|tab|cap|pill)s?\b/i,"pill"]];function hr(e,r){for(let t of[e,r]){if(!t)continue;let e=pr.find(([e])=>e.test(t));if(e)return e[1]}return"pill"}function fr(e,r,t){return e?{tone:"pink",icon:hr(r,t)}:{tone:"yellow",icon:"leaf"}}var mr=[[pr[0][0],"injection"],[pr[1][0],"chew"],[pr[2][0],"topical"],[pr[3][0],"liquid"],[/\b(capsule|cap)s?\b/i,"capsule"],[/\b(tablet|caplet|tab|pill)s?\b/i,"tablet"]];function vr(e,r,t){if(!e)return null;for(let e of[r,t]){if(!e)continue;let r=mr.find(([r])=>r.test(e));if(r)return r[1]}return"unknown"}var gr={tablet:{tone:"pink",icon:"pill"},capsule:{tone:"sage",icon:"pill"},liquid:{tone:"base",icon:"flask"},injection:{tone:"base",icon:"syringe"},chew:{tone:"yellow",icon:"bowl"},topical:{tone:"sage",icon:"shield"},unknown:{tone:"pink",icon:"pill"}};function br(e){return e?gr[e]:{tone:"yellow",icon:"leaf"}}function yr(e){return`${e.line2?`${e.line1}, ${e.line2}`:e.line1}, ${e.city}, ${e.region?`${e.region} `:""}${e.postalCode}`}function kr(e){return{label:e.rx,tone:"rx"}}function wr(e){return e.fillsTotal!==null&&e.fillsUsed!==null?Math.max(0,e.fillsTotal-Math.max(e.fillsUsed,1)):null}function xr(e){let{pkg:r,copy:t,petName:a}=e,i=r.review,n=Be(i.shipsOn),l=ur(r.lines.map(e=>a(e.petId))),s=i.state==="open",o=new Map(i.quoteLines.map(e=>[`${e.offerId}:${e.petId??""}`,e])),d=r.lines.map((r,a)=>{let i=r.offer,n=o.get(`${r.offerId}:${r.petId??""}`),l=i?.requiresRx??false,d=[];return i||d.push({label:t.outOfStock,tone:"later"}),{petId:r.petId,view:{key:`${r.offerId}:${r.petId??""}:${a}`,name:i?.title??t.itemNoLongerSold,rx:l,meta:null,alert:i?null:t.packageOutOfStock,pills:d,price:n&&i?Ae(n.unitPrice*n.quantity-n.discount):null,...fr(l,i?.title),details:i?{label:t.details,to:{name:"product",offerId:i.offerId,...r.petId?{petId:r.petId}:{}}}:null,remove:s?{label:t.remove,busy:e.removing===a,disabled:e.removing!==null,onPress:()=>e.onRemove(a)}:null}}}),c=[];for(let e of d){let r=a(e.petId),i=r?t.forPet(r):null,n=c.find(e=>e.label===i);n?n.items.push(e.view):c.push({label:i,items:[e.view]})}let u=[],p=r.draft;p?(u.push({k:t.items,v:Ae(p.total-p.shipping-p.tax)}),u.push({k:t.shipping,v:p.shipping===0?t.free:Ae(p.shipping)}),u.push({k:t.tax,v:Ae(p.tax)}),u.push({k:t.total,v:Ae(p.total)})):i.quoteLines.length>0&&u.push({k:t.items,v:Ae(i.quoteLines.reduce((e,r)=>e+r.unitPrice*r.quantity-r.discount,0))});let h=e.card?je(e.card.brand,e.card.last4):null,f=r.lines.some(e=>e.offer?.requiresRx),m=h?[t.chargedWhenShips(h),f?t.rxCheckedFirst:null].filter(Boolean).join(" "):null,v=e.error;!v&&i.state==="approving"?v=t.approvalInProgress:!v&&i.state!=="open"&&i.state!==null?v=t.reviewClosed:!v&&s&&!e.card&&(v=t.noCardOnFile);let g=s&&p&&e.card?{label:t.approveAndShip,busyLabel:t.approving,busy:e.approving,disabled:e.approving||e.placed===true||e.removing!==null,onPress:e.onApprove}:null;return{title:n?t.packageTitle(n):t.tabPackage,sub:t.packageSub(l,Ee(i.approveBy,{weekday:true}),null),reviewPill:i.approveBy&&s?t.reviewBy(Ee(i.approveBy)):null,countPill:r.lines.length>0?t.itemCount(r.lines.length):null,fine:null,groups:r.lines.length>0?c:[],empty:r.lines.length===0?{line:n?t.packageEmpty(n):t.nothingHereYet,shop:{label:t.tabShop,to:{name:"shop"}},skip:null}:null,add:null,sum:u,approve:g,skip:s?{label:t.skipThisMonth,to:{name:"plan"}}:null,note:m,error:v,delivery:e.address?[{k:t.shipTo,v:yr(e.address),change:{label:t.change,to:{name:"address",then:{name:"package"}}}}]:[],legal:t.legal}}function _r(e,r){return r.filter(r=>r.status==="ready"&&r.offerId===e)}function Nr(e,r,t,a,i=null){let n=[],l=null,s=i,o;return e.requiresRx&&(n.push(kr(t)),o=_r(e.offerId,r).find(e=>a(e.petId)),s=o?.petId??i,l=o?t.hasPrescription(a(o.petId)):t.needsPrescription),{key:e.offerId,to:{name:"product",offerId:e.offerId,...s?{petId:s}:{}},name:e.title,meta:l,price:e.price!==null?Ae(e.price):null,pills:n,...fr(e.requiresRx,e.title,o?.form),form:vr(e.requiresRx,e.title,o?.form),imageUrl:e.imageUrl??null}}function Ir(e){return e.fillsUsed===null||e.fillsUsed===0}function Cr(e){let{copy:r}=e,t=t=>Nr(t,e.prescriptions,r,e.petName,e.petId??null),a=[],i=/* @__PURE__ */new Map;for(let r of[...e.offers,...e.prescribed??[]])i.set(r.offerId,r);let n=[],l=[],s=[];if(!e.searching){let r=e.prescriptions.filter(r=>r.status==="ready"&&r.offerId!==null&&e.petName(r.petId));for(let t of ur(r.map(e=>e.offerId))){let a=i.get(t);if(!a||!a.requiresRx)continue;let o=r.filter(e=>e.offerId===t);if(o.every(Ir)){n.push(a);for(let r of o)s.includes(e.petName(r.petId))||s.push(e.petName(r.petId))}else l.push(a)}}n.length>0&&a.push({key:"prescribed",title:r.prescribedFor(s),link:null,tiles:n.map(t)}),l.length>0&&a.push({key:"refill",title:r.refillSoon,link:e.packageMonth?{label:r.inMonthsPackage(e.packageMonth),to:{name:"package"}}:null,tiles:l.map(t)});let o=new Set([...n,...l].map(e=>e.offerId));return a.push({key:"all",title:e.petNames.length>0?r.forPets(e.petNames):r.allProducts,link:null,tiles:e.offers.filter(e=>!o.has(e.offerId)).map(t)}),a}function $r(e){let{copy:r,offer:t}=e,a=e.plansOn&&e.petName!==null,i=a?e.choice:"once",n=i==="monthly"?e.packageMonth?r.addToPackage(e.packageMonth):r.startPlan:r.buyNow,l=t.price!==null;return{back:{label:r.backToShop,to:{name:"shop"}},title:t.title,sub:null,price:l?Ae(t.price):null,priceUnit:null,...fr(false),form:null,imageUrl:t.imageUrl??null,source:null,stockLine:l?null:r.outOfStockNow,choices:a?[{value:"monthly",title:r.everyMonthIn(e.petName),meta:r.skipOrStop},{value:"once",title:r.justOnce,meta:r.justOnceShipsNow}]:null,choice:a?i:null,onChoice:r=>e.onChoice(r==="once"?"once":"monthly"),quantity:e.quantity,onQuantity:r=>e.onQuantity(Math.min(99,Math.max(1,r))),submit:l?{label:n,busyLabel:r.adding,busy:e.busy,disabled:e.busy,onPress:e.onSubmit}:{label:r.outOfStock,disabled:true,onPress:()=>{}},error:e.error,facts:null,cards:[],aside:null,legal:r.legal}}function Sr(e){let{copy:r,offer:t}=e,a=_r(t.offerId,e.prescriptions).filter(r=>e.petName(r.petId)),i=(e.petId?a.find(r=>r.petId===e.petId):void 0)??a[0]??null,n=t.price!==null,l=null,s=null,o=i?.form??null;if(i){let t=wr(i);l={name:r.hasPrescription(e.petName(i.petId)),meta:t!==null&&t>0?r.refillsLeft(t):null,directions:null},s=n?{label:e.packageMonth?r.refillInPackage(e.packageMonth):r.buyNow,busyLabel:r.adding,busy:e.busy,disabled:e.busy,onPress:()=>e.onSubmit(i)}:{label:r.outOfStock,disabled:true,onPress:()=>{}}}else{let a=e.prescriptions.filter(r=>r.offerId===t.offerId&&(r.status==="being_prepared"||r.status==="too_soon")&&e.petName(r.petId)),i=(e.petId?a.find(r=>r.petId===e.petId):void 0)??a[0]??null;if(i)l={name:r.hasPrescription(e.petName(i.petId)),meta:i.status==="being_prepared"?r.rxBeingPrepared:r.rxTooSoon,directions:null},s=null,o=i.form;else{let t=(e.petId?e.petName(e.petId):null)??e.firstPetName;l=t?{name:r.noPrescriptionFor(t),meta:null,directions:null}:null,s=e.bookVisitHref?{label:r.bookVideoVisit,href:e.bookVisitHref}:null}}return{back:{label:r.backToShop,to:{name:"shop"}},stepLabel:r.prescription,title:t.title,sub:null,price:n?Ae(t.price):null,priceUnit:null,...fr(true,t.title,o),form:vr(true,t.title,o),imageUrl:t.imageUrl??null,script:l,stockLine:n?null:r.outOfStockNow,submit:s,note:null,error:e.error,cards:[],aside:null,legal:r.legal}}function Pr(e,r){let t=Math.round(e/30.4);return t>=1&&Math.abs(e-t*30.4)<=2?r.cadenceMonths(t):r.cadenceDays}function Lr(e){let{copy:r}=e,t=e.plans.filter(e=>e.state!=="cancelled"),a=[];for(let i of t)i.lines.forEach((t,n)=>{let l=e.offers.get(t.offerId)??null,s=e.petName(t.petId),o=[l?.title??r.itemNoLongerSold,s].filter(Boolean).join(" · "),d=i.stopReason,c=d==="payment_declined"?r.declined(e.packageMonth):d&&d!=="customer"?r.stopReason(d):Pr(i.cadenceDays,r);a.push({key:`${i.planId}:${n}`,title:o,meta:c,alert:!!(d&&d!=="customer"),on:i.state==="active",busy:e.busyPlan===i.planId,onToggle:r=>e.onToggle(i,r),error:e.rowError&&e.rowError.planId===i.planId&&n===0?e.rowError.line:null})});let i=t.find(e=>e.state==="active")??null,n=[],l=Ee(e.reviewBy,{weekday:true});l&&n.push({k:r.reviewByLabel,v:l});let s=Ee(i?.nextRun??null,{weekday:true});s&&n.push({k:r.ships,v:s});let o=t.some(e=>e.stopReason==="payment_declined"),d=[];e.address&&d.push({k:r.shipTo,v:yr(e.address),change:{label:r.change,to:{name:"address",then:{name:"plan"}}}}),e.card&&d.push({k:r.payWith,v:je(e.card.brand,e.card.last4),alert:o?r.declined(e.packageMonth):null,change:{label:r.change,to:{name:"card",then:{name:"plan"}}}});let c=e.packageMonth??Be(i?.nextRun??null);return{sub:null,rows:a,emptyLine:a.length===0?r.repeatsEmpty:null,next:i&&n.length>0?{sum:n,link:e.packageMonth?{label:r.reviewMonthsPackage(e.packageMonth),to:{name:"package"}}:null}:null,delivery:d,breakCard:i?{skip:c?{label:r.skipMonth(c),ask:r.skipMonthAsk(c),body:r.skipMonthBody}:null,pause:{label:r.pausePlan,ask:r.pausePlanAsk,body:r.pausePlanBody},busy:e.breakBusy,error:e.breakError,onConfirm:e.onBreak}:null,legal:r.legal}}var Tr={pending_placement:1,placement_unknown:1,placed:1,accepted:2,release_sent:2,release_unknown:2,released:2,shipped:3,delivered:5};var Ar=createContext(null),Mr=Ar.Provider;function zr(){let e=j(Ar);if(!e)throw new s("not-initialized","shop screens render inside EverfurShop");return e}function Or(e){return e.phase==="ready"&&e.value?Be(e.value.review.shipsOn):null}function qr(e,r){return e.phase==="ready"&&e.value!==null?{phase:"ready",value:r(e.value)}:e.phase==="loading"?{phase:"loading"}:{phase:"failed",retry:e.refresh}}function Rr(e,r){return!e||e.length===0?null:(r?e.find(e=>e.paymentMethodId===r):void 0)??e[0]??null}function Er(e){let{client:r}=Ze(),t=[...new Set(e)].sort();return Je(`offers-by-id:${t.join(",")}`,async()=>{let e=await Promise.all(t.map(e=>r.offer(e)));return ke(new Map(t.map((r,t)=>[r,e[t].ok?e[t].value:null])))})}function Br(e,r){return r.kind==="confirmed"?null:r.kind==="needsPayerAction"?e.cardStepFailed:r.kind==="payerActionFailed"?r.message??e.cardStepFailed:r.kind==="payerActionClosed"?e.cardStepClosed:r.error.kind==="refused"&&r.error.reasonCode==="price_changed"?e.priceChanged:We(e,r.error)}var jr=/* @__PURE__ */new WeakMap;function Fr(e,r,t){let a=jr.get(e);a||(a=/* @__PURE__ */new Map,jr.set(e,a)),t?a.set(r,t):a.delete(r)}function Ur(e,r){return jr.get(e)?.get(r)??null}function Vr(e,r){jr.get(e)?.delete(r)}var Dr="\0card",Wr=/* @__PURE__ */new WeakSet;function Hr(e,r,t,a){if(!r||Wr.has(r))return false;let i=r.step==="card"?t.name==="card"?Dr:null:t.name==="order"?t.orderId:null;return i===null?false:(Wr.add(r),Fr(e,i,r.outcome==="closed"?a.cardStepClosed:r.outcome==="failed"?a.cardStepFailed:null),true)}function Kr(e){let{copy:r,petName:t,packageSource:a,payments:i,client:n}=Ze(),{tabs:l,pkg:s}=zr(),o=s.phase==="ready"?s.value?.plan??null:null,d=nr(),c=ir(o?.destination??null),[u,p]=q(null),[h,f]=q(null),[m,v]=q(false),[g,b]=q(false),y=dr((e,r,t)=>a.removeLine(r,t,e));if(s.phase==="ready"&&s.value===null)return{tabs:l,view:{phase:"failed",retry:s.refresh}};let k=qr(s,l=>xr({pkg:l,card:Rr(d.value,l.plan.paymentMethodId),address:c.value?.address??null,copy:r,petName:t,removing:u,approving:m,placed:g,error:h,onRemove:e=>{p(e),f(null),y.run(l,e).then(e=>{p(null),e&&e.ok?s.refresh():e&&f(We(r,e.error))})},onApprove:()=>{m||g||(v(true),f(null),(async()=>{let t=await Qr(a,l,i);v(false);let o=Br(r,t),d=t.kind!=="failed"?t.orderIds[0]:void 0;d?(b(true),Fr(n,d,o),e({name:"order",orderId:d})):(f(o),t.kind==="failed"&&t.error.kind==="refused"&&s.refresh())})())}}));return{tabs:l,view:k}}var Gr=/* @__PURE__ */new WeakMap;async function Qr(e,r,t){let a=Gr.get(r);a||(a=new Le,Gr.set(r,a));let i=await e.approve(r,a,t);return(i.kind!=="failed"||i.error.kind==="refused")&&Gr.delete(r),i}function Yr(e,r){let[t,a]=q(e);return B(()=>{let t=setTimeout(()=>a(e),r);return()=>clearTimeout(t)},[e,r]),t}function Zr(e){let{client:r,copy:t,petName:a,pets:i}=Ze(),{tabs:n,pkg:l}=zr(),[s,o]=q(e??""),d=Yr(s,250),c=er({text:d}),u=tr(),p=u.value??[],h=i.map(e=>e.name),f=Or(l),m=p.filter(e=>e.status==="ready"&&e.offerId!==null&&a(e.petId)).map(e=>e.offerId),v=Er(m),g=c.phase==="ready"?c.value??null:null,[b,y]=q(null),k=b&&g&&b.first===g?b:null,w=k?k.cursor:g?.nextCursor??null,x=R(false),_=U(()=>{if(!g||!w||x.current)return;x.current=true,y(e=>({first:g,offers:e&&e.first===g?e.offers:[],cursor:w,loading:true,failed:false}));let e=d.trim();r.offers({...e?{text:e}:{},cursor:w,limit:100}).then(e=>{x.current=false,y(r=>!r||r.first!==g?r:e.ok?{first:g,offers:[...r.offers,...e.value.offers],cursor:e.value.nextCursor,loading:false,failed:false}:{...r,loading:false,failed:true})})},[r,g,w,d]),N,I=u.phase==="loading"||m.length>0&&v.phase==="loading";if(g&&!I){let e=/* @__PURE__ */new Set,r=[];for(let t of[...g.offers,...k?.offers??[]])e.has(t.offerId)||(e.add(t.offerId),r.push(t));N={phase:"ready",value:Cr({offers:r,prescribed:[...v.value?.values()??[]].filter(e=>e!==null),prescriptions:p,copy:t,petName:a,petNames:h,packageMonth:f,searching:d.trim()!=="",petId:i.length===1?i[0].petId:null})}}else c.phase==="loading"||I?N={phase:"loading"}:c.phase==="unavailable"?N={phase:"ready",value:[]}:N={phase:"failed",retry:c.refresh};let C=N.phase==="ready"?N.value.reduce((e,r)=>e+r.tiles.length,0):1,$=N.phase==="ready"&&C===0?d.trim()?t.noMatches(d.trim()):t.nothingHereYet:null,S=g&&w?{onMore:_,loading:k?.loading??false,failed:k?.failed??false}:null;return{tabs:n,view:{sub:null,query:s,onQuery:o,filters:[],shelves:N,empty:$,legal:t.legal,more:S}}}function Jr(e,r,t,a){return{offerId:e.offerId,quantity:a?.packCount??r,...a?.petId??t?{petId:a?.petId??t}:{},...a?{rxId:a.rxId}:{}}}function Xr(e,r){return{name:e,offerId:r.offerId,quantity:r.quantity,...r.petId?{petId:r.petId}:{},...r.rxId?{rxId:r.rxId}:{}}}function et(e,r,t){let{copy:a,petName:i,pets:n,client:l}=Ze(),{config:s,pkg:o,bookVisitHref:d}=zr(),c=rr(e),u=tr(),[p,h]=q("monthly"),[f,m]=q(1),[v,g]=q(null),b=Or(o),y=sr(),k=(o.phase==="ready"?o.value?.plan??null:null)??y.value?.plans.find(e=>e.state==="active")??null,w=dr((e,r,t)=>l.updatePlan(r.planId,{idempotencyKey:e.key("add"),lines:[...r.lines.map(e=>({offerId:e.offerId,quantity:e.quantity,...e.petId?{petId:e.petId}:{}})),t]})),x=(e,r)=>{if(g(null),!r)return t(Xr("buy",e));if(!k)return t(Xr("consent",e));w.run(k,e).then(e=>{e&&e.ok?(o.refresh(),t({name:"package"})):e&&g(We(a,e.error))})};if(c.phase==="ready"&&c.value?.requiresRx){let e=c.value,t={offer:e,copy:a,petId:r??null,petName:i,firstPetName:n[0]?.name??null,packageMonth:b,error:v,bookVisitHref:d};return u.phase==="unavailable"?{kind:"rx",view:{phase:"ready",value:Sr({...t,prescriptions:[],busy:false,onSubmit:()=>{}})}}:{kind:"rx",view:qr(u,r=>Sr({...t,prescriptions:r,busy:w.busy,onSubmit:r=>x(Jr(e,1,null,r),k!==null)}))}}let _=(r?i(r):null)??n[0]?.name??null;return{kind:"product",view:qr(c,e=>$r({offer:e,copy:a,petName:_,packageMonth:b,plansOn:s.recurringTermsVersion!==null,choice:p,onChoice:h,quantity:f,onQuantity:m,busy:w.busy,error:v,onSubmit:()=>x(Jr(e,f,r??n[0]?.petId??null,null),p==="monthly"&&s.recurringTermsVersion!==null&&_!==null)}))}}function rt(){let{copy:e,petName:r,client:t}=Ze(),{tabs:a,pkg:i}=zr(),n=sr(),l=nr(),s=(n.value?.plans??[]).filter(e=>e.state!=="cancelled"),o=s.find(e=>e.state==="active")??s[0]??null,d=ir(o?.destination??null),c=Er(s.flatMap(e=>e.lines.map(e=>e.offerId))),[u,p]=q(null),[h,f]=q(null),[m,v]=q(null),g=dr((e,r,a)=>t.planAction(r.planId,{idempotencyKey:e.key(a?"resume":"pause"),operation:a?"resume":"pause"})),b=dr((e,r,a)=>t.planAction(r.planId,{idempotencyKey:e.key(a),operation:a})),y=Or(i);if(n.phase==="unavailable")return{tabs:a,view:{phase:"failed",retry:n.refresh}};let k=qr(n,()=>Lr({plans:s,offers:c.value??/* @__PURE__ */new Map,copy:e,petName:r,card:Rr(l.value,o?.paymentMethodId??null),address:d.value?.address??null,reviewBy:i.phase==="ready"?i.value?.review.approveBy??null:null,packageMonth:y,busyPlan:u,rowError:h,onToggle:(r,t)=>{p(r.planId),f(null),g.run(r,t).then(t=>{p(null),g.reset(),t&&t.ok?n.refresh():t&&f({planId:r.planId,line:We(e,t.error)})})},breakBusy:b.busy,breakError:m,onBreak:async r=>{if(!o)return false;v(null);let t=await b.run(o,r);return t&&t.ok?(b.reset(),n.refresh(),i.refresh(),true):(t&&v(We(e,t.error)),false)}}));return{tabs:a,view:k}}var tt=/* @__PURE__ */new WeakMap;function at(e){return tt.get(e)??null}function it(e){tt.delete(e)}function nt(e,r){let{copy:t,client:a}=Ze(),{pkg:i}=zr(),n=e??{name:"package"},l=R(null),s=dr(async(r,t)=>{let n=JSON.stringify(t),s=l.current?.sent===n?l.current.ref:null;if(s===null){let e=await a.addAddress(t);if(!e.ok)return we(e.error);s=e.value.ref,l.current={sent:n,ref:s}}if(e?.name==="package"||e?.name==="plan"){let t=await a.plans({limit:100});if(!t.ok)return we(t.error);let n=t.value.plans.filter(e=>e.state!=="cancelled"),l=e.name==="package"?n.find(e=>e.planId===(i.value?.plan.planId??null))??null:n.find(e=>e.state==="active")??n[0]??null,o=l?n.filter(e=>e.planId===l.planId||l.destination!==null&&e.destination===l.destination):[];for(let e of o){if(e.destination===s)continue;let t=await a.updatePlan(e.planId,{idempotencyKey:r.key(`destination:${e.planId}`),destination:s});if(!t.ok)return we(t.error)}}return ke(s)});return{back:{label:t.backToCare,to:n},busy:s.busy,error:s.error?We(t,s.error):null,onSave:t=>{s.run(t).then(t=>{!t||!t.ok||(e?.name==="package"||e?.name==="plan"?i.refresh():tt.set(a,t.value),r(n))})}}}function lt(e,r,t){let{copy:a,client:i,payments:n}=Ze(),{config:l}=zr(),s=e??{name:"plan"},[o,d]=q(()=>Ur(i,Dr));B(()=>Vr(i,Dr),[i]);let c=dr(async()=>{if(t){let e=await t();return e.ok?ke(true):(d(e.closed?a.cardStepClosed:e.message??a.cardStepFailed),ke(false))}let e=await i.setupPaymentMethod();if(!e.ok||!n)return e.ok?we({kind:"invalidRequest"}):we(e.error);let r=await n.confirmCardSetup(e.value.payerAction);return r.ok?ke(true):(d(r.closed?a.cardStepClosed:r.message??a.cardStepFailed),ke(false))}),u=t?true:n!==null&&l.stripePublishableKey!==null;return{back:{label:a.backToCare,to:s},error:o??(c.error?We(a,c.error):null),start:u?{label:a.cardStart,busyLabel:a.saving,busy:c.busy,disabled:c.busy,onPress:()=>{d(null),c.run().then(e=>{e&&e.ok&&e.value&&r(s)})}}:null}}function st(e){let{copy:r,saveProfileName:t,onProfileNameRequired:a}=Ze(),[i,n]=q(false),[l,s]=q(false),[o,d]=q(null),c=R(e);c.current=e;let u=R(false),p=R(true);return B(()=>(p.current=true,()=>{p.current=false}),[]),{view:i?{line:r.nameMissing,form:t?{firstLabel:r.firstName,lastLabel:r.lastName,saveLabel:r.saveName,busy:l,error:o,onSave:e=>{let a=e.firstName.trim(),i=e.lastName.trim();u.current||!a||!i||(u.current=true,s(true),d(null),t({firstName:a,lastName:i}).then(e=>e,()=>false).then(e=>{if(u.current=false,!!p.current){if(s(false),!e){d(r.actionFailed);return}n(false),c.current()}}))}}:null,handoff:!t&&a?{label:r.addName,onPress:a}:null}:null,raise:e=>Pe(e)?(d(null),n(true),true):false,clear:()=>n(false)}}function ot(){let e=ar(),r=nr(),t=e.value?.find(e=>e.isDefault&&e.isComplete)??e.value?.find(e=>e.isComplete)??null,a=Rr(r.value,null);return{addresses:e,cards:r,address:t,card:a}}function dt(e,r){return r.phase==="unavailable"?e.actionFailed:r.phase==="failed"&&r.error?We(e,r.error):null}function ct(e,r){let{copy:t,client:a,payments:i,petName:n}=Ze(),l=rr(e.offerId),{address:s,card:o}=ot(),d=O(()=>({offerId:e.offerId,quantity:e.quantity,...e.petId?{petId:e.petId}:{},...e.rxId?{rxId:e.rxId}:{}}),[e.offerId,e.quantity,e.petId,e.rxId]),c=Je(s?`quote:${s.ref}:${JSON.stringify(d)}`:null,()=>a.quote({lines:[d],shipTo:s.ref})),[u,p]=q(null),[h,f]=q(null),[m,v]=q(false),g=dr(async e=>{let r=await a.createCheckout({idempotencyKey:e.key("draft"),lines:[d],shipTo:s.ref});if(!r.ok)return we(r.error);if((u??c.value?.total??null)!==r.value.total)return p(r.value.total),we({kind:"refused",status:409,reasonCode:"price_changed",message:null});let t=await Te(e=>a.confirmCheckout(r.value.checkoutId,{idempotencyKey:e,expectedTotal:r.value.total,paymentMethodId:o.paymentMethodId}),e,i);return t.kind==="failed"?we(t.error):ke(t)}),b=[...s?[]:[{label:t.addressNeeded,to:{name:"address",then:e}}],...o?[]:[{label:t.cardTitle,to:{name:"card",then:e}}]],y=c.value,k=u??y?.total??null,w=R(()=>{}),x=st(()=>w.current()),_=()=>{m||(f(null),x.clear(),g.run().then(e=>{if(!e)return;let i=e.ok?e.value:{kind:"failed",error:e.error},n=i.kind!=="failed"?i.orderIds[0]:void 0;n?(v(true),Fr(a,n,Br(t,i)),r({name:"order",orderId:n})):i.kind==="failed"&&x.raise(i.error)||f(Br(t,i))}))};return w.current=_,{back:{label:t.backToShop,to:{name:"product",offerId:e.offerId}},title:t.confirmTitle,lines:l.value?[{key:d.offerId,name:l.value.title,meta:n(d.petId),price:l.value.price!==null?Ae(l.value.price*d.quantity):null,form:vr(l.value.requiresRx,l.value.title)}]:[],sum:y&&k!==null?[{k:t.shipping,v:y.shipping===0?t.free:Ae(y.shipping)},{k:t.tax,v:Ae(y.tax)},{k:t.total,v:Ae(k)}]:null,needs:b,pay:s&&o&&y?{label:t.confirmPay,busyLabel:t.saving,busy:g.busy,disabled:g.busy||m,onPress:_}:null,note:o?t.chargedWhenShips(je(o.brand,o.last4)):null,error:h??dt(t,c),nameStep:x.view}}function ut(e,r){let{copy:t,client:a}=Ze(),{config:i,pkg:n}=zr(),{address:l,card:s}=ot(),o=dr(r=>a.createPlan({idempotencyKey:r.key("create"),cadenceDays:30,destination:l.ref,paymentMethodId:s.paymentMethodId,consentTermsVersion:i.recurringTermsVersion,lines:[{offerId:e.offerId,quantity:e.quantity,...e.petId?{petId:e.petId}:{},...e.rxId?{rxId:e.rxId}:{}}]})),d=[...l?[]:[{label:t.addressNeeded,to:{name:"address",then:e}}],...s?[]:[{label:t.cardTitle,to:{name:"card",then:e}}]];return{back:{label:t.backToShop,to:{name:"product",offerId:e.offerId}},terms:i.recurringTermsUrl?{label:t.consentTermsLink,href:i.recurringTermsUrl}:null,needs:d,error:o.error?We(t,o.error):null,agree:l&&s&&i.recurringTermsVersion?{label:t.consentAgree,busyLabel:t.saving,busy:o.busy,disabled:o.busy,onPress:()=>{o.run().then(e=>{e&&e.ok&&(n.refresh(),r({name:"plan"}))})}}:null}}var pt=createContext({href:()=>"#",go:()=>{}}),ht=pt.Provider;function ft(){return j(pt)}function ShopLink({to:e,className:r,children:t,ariaCurrent:a,ariaLabel:i}){let n=ft(),l=r=>{r.defaultPrevented||r.button!==0||r.metaKey||r.ctrlKey||r.shiftKey||r.altKey||(r.preventDefault(),n.go(e))};/* @__PURE__ */
6
6
  return G("a",{className:r,href:n.href(e),onClick:l,"aria-current":a,"aria-label":i,children:t})}var mt=["AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY","AS","GU","MP","PR","VI","AA","AE","AP"],vt=/^\d{5}(-\d{4})?$/;function gt(e){return mt.includes(e.trim().toUpperCase())}function bt(e){return typeof e=="string"?e.length>0?e:null:e&&typeof e=="object"&&typeof e.uri=="string"&&e.uri.length>0?e.uri:null}function Face({name:e,src:r,tint:t,initials:a,alt:i,xs:n}){let l=bt(r),[s,o]=q(null);return l!==null&&s!==l?/* @__PURE__ */G("img",{src:l,alt:i,onError:()=>o(l),className:"efds-avatar__img"}):/* @__PURE__ */G("span",{"aria-hidden":"true",className:_("efds-avatar__initials",t!=="default"&&`efds-avatar__initials--${t}`,n&&"efds-avatar__initials--xs"),children:a??M(e)})}var yt=/* @__PURE__ */z(function({name:e,src:r,size:t="md",tint:a="default",initials:i,ring:n=false,dot:l=false,dotLabel:s,decorative:o=false,shape:d="circle",ringColor:c,testID:u,className:p,style:h,...f},m){x("avatar");let v=I(),g=A(v,t,a),b=l&&s?`${e}, ${s}`:e,y=bt(r),[k,w]=q(null),C=y!==null&&k!==y,$=typeof t=="string"?t:null,S=$===null||c?{...$===null?{width:g.side,height:g.side}:{},...c?{"--efds-avatar-ring":c}:{}}:void 0;/* @__PURE__ */
@@ -5,7 +5,7 @@ return Object.freeze(n)}function x(e,t){let n=f(e);return n===null?null:/* @__PU
5
5
  return Object.freeze({active:g(t?.active,false)})}var E=240;function R(e){let t=f(e);if(t===null)return null;let n=b(t.fee_cents);return n===null||n<0?null:/* @__PURE__ */Object.freeze({feeCents:n,currency:h(t.currency)??"usd",feeRecorded:g(t.fee_recorded,n>0),summary:m(t.summary)})}function P(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e)}catch{}}function D(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}function z(e,...t){if(typeof e=="function")try{let n=e(...t);return D(n)&&Promise.resolve(n).then(void 0,P),n}catch(e){P(e);return}}var F=/* @__PURE__ */new WeakMap;function A(e){if(typeof e!="function")return;let t=F.get(e);if(t!==void 0)return t;let n=(...t)=>{z(e,...t)};return F.set(e,n),n}function O(e,t){let n=null;for(let r of t){let t=e[r];typeof t=="function"&&(n??={...e},n[r]=A(t))}return n??e}function B(e,...t){let n;try{n=e(...t)}catch(e){return P(e),Promise.resolve({ok:false,error:e})}return Promise.resolve(n).then(e=>({ok:true,value:e}),e=>({ok:false,error:e}))}var L=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],N=/* @__PURE__ */Object.freeze(L.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(N.map(e=>e.wireCode));var M=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),$=/* @__PURE__ */Object.freeze(N.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:M[e.wireCode]}))),W=new Map($.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),H=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set($.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let n=e.trim().toUpperCase();if(n.length!==0)for(let e of[t??"http_envelope",...H]){let t=W.get(e+n);if(t)return t}}var V=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(e){return V[e]}function fromWire(e){let t=contractErrorFor(e);if(t)return t.normalized;let n=(e??"").trim().toUpperCase(),r=n.replace(/[^A-Z0-9]/g,"");if(r==="AUTHREJECTED")return"authRejected";if(n.startsWith("AUTH"))return"authExpired";switch(r){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var U=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return U.has(e)}var q=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||q.has(e)}var K=500,Y=8e3,G=4;function backoffDelayMs(e,t=Math.random){let n=Math.max(0,e),r=Math.min(K*2**n,Y);return Math.floor(t()*r)}var J="This feature isn't available on your account right now.",X="Something in that request was not right. Check the details and try again.",Q=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:J,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:X,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:J,runtimeDisposed:X,unknown:"Something went wrong. Please try again."}),Z="This session has ended. Please sign in again.",ee="linked_account_read_only";function te(e,t,n){return e==="conflict"&&n===ee?J:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?Z:userFacingError(e)}function userFacingError(e){return Q[e]}function ne(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:false,writable:false,configurable:false})}var re=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let n=contractErrorFor(t?.wireCode,t?.wireEnvelope),r=e==="conflict"&&t?.reasonCode===ee,l={code:e,category:categoryFor(e),retryable:t?.retryable??(r?false:isRetryableCode(e)),displayMessage:te(e,t?.wireCode,r?ee:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&re.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),n);return t?.wireMessage&&ne(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ne(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}function ok(e,t){/* @__PURE__ */
6
6
  return Object.freeze({ok:true,value:e})}function err(e){/* @__PURE__ */
7
7
  return Object.freeze({ok:false,error:e})}var le=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function assertNever(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}function errorFrame(e){/* @__PURE__ */
8
- return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:null,...e.freeCap?{freeCap:/* @__PURE__ */Object.freeze({...e.freeCap})}:{}})}var ie="x-everfur-anon-token",ae="anonTokenInvalid";async function oe(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function se(e,t){let n=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...n?{wireMessage:n}:{},...e!=null?{raw:e}:{}})}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[ie]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...de(e.headers),...authHeaders(t)}}}function de(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===ie||(t[n]=r)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let n=await oe(t),r=await t.transport.request(withAuthHeaders(e,ue(t,n)));if(r.ok||pe(r.error.raw)!==ae||t.anonIdentity===void 0||t.userRef!==null)return r;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===n?r:t.transport.request(withAuthHeaders(e,ue(t,l)))}let n;try{n=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(se(e))}let r=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:n,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(r.ok||r.error.httpStatus!==401)return r;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(se(e,{wireCode:pe(r.error.raw),requestId:r.error.requestId}))}let i=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!i.ok&&i.error.httpStatus===401?(t.identity.reportRejected?.(),err(ce(i.error))):i}function ue(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function ce(e){let t=e.raw,n=pe(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...n?{wireCode:n}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function pe(e){if(typeof e!="object"||e===null)return null;let t=e,n=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof n=="string"&&n.length>0?n:null}function fe(e,t){let n=globalThis.URL;if(typeof n=="function"){let r;try{r=t===void 0?new n(e):new n(e,t)}catch{return null}try{if(r.protocol)return r}catch{}}return be(e)}var he=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,me=/[\s\u0000-\u001f\u007f\\]/,ge={"http:":"80","https:":"443"};function be(e,t){let n=e.trim();let r=me.test(n)?null:he.exec(n);if(r===null)return null;let[,l="",i="",a="",o="",s="",d="",u="",c=""]=r,p=`${l.toLowerCase()}:`,f=Number(s);if(f>65535)return null;let h=s===""||String(f)===ge[p]?"":String(f),m=ge[p]!==void 0,g=o.toLowerCase()+(h&&`:${h}`),b=d||(m?"/":""),y=i||a?`${i}${a&&`:${a}`}@`:"";return{href:`${p}//${y}${g}${b}${u}${c}`,protocol:p,username:i,password:a,hostname:o.toLowerCase(),port:h,origin:m?`${p}//${g}`:"null",pathname:b,search:u==="?"?"":u,hash:c==="#"?"":c}}var ye="1.6.1";function networkError(e){return makeEverfurError("internalError",{retryable:true,wireMessage:ve(e)})}function ve(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var xe=3e4,ke=Y*2,we="idempotency-key",Te=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),Se=/* @__PURE__ */Object.freeze({onEvent(){}}),Ce=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function je(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}function createRequestFunnel(e){let t=e.observer??Se,n=e.timers??Ce,r=e.rng??Math.random,l=e.sleep??((e,t)=>We(e,n,t)),i=e.maxAttempts??G,a=e.unaryTimeoutMs??xe,o=e.newIdempotencyKey??Ie(),s=e=>{try{t.onEvent(e)}catch{}};async function d(t,d,u){let c=u?.maxAttempts,p=Math.max(1,c??i),f=u?.idempotent??Te.has(d.method),h=u?.idempotencyKey===void 0?null:je(u.idempotencyKey),m=f?h??o():null,g=_e(d,m),b=0;for(;;){let i=e=>/* @__PURE__ */Object.freeze({call:t,method:d.method,path:d.path,attempt:b,...m?{idempotencyKey:m}:{},...e});s(i({phase:"attempt"}));let o=Me(a,n),u=$e(o.signal,d.signal),f;try{f=await authedSend({...g,signal:u.signal},e.auth)}catch(e){f=err(networkError(e))}finally{u.dispose(),o.cancel()}if(f.ok)return s(i({phase:"settled",ok:true,reason:"ok"})),f;let h=f.error,y=Re(h,b,{maxAttempts:p,rng:r,now:n.now(),aborted:d.signal?.aborted===true,...c!==void 0?{perCallMaxAttempts:c}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),v={ok:false,code:h.code,reason:y.reason,...h.httpStatus!==void 0?{httpStatus:h.httpStatus}:{},...h.requestId!==void 0?{requestId:h.requestId}:{}};if(!y.retry)return s(i({phase:"settled",...v})),err(h);if(s(i({phase:"retry",...v,delayMs:y.delayMs})),await l(y.delayMs,d.signal),d.signal?.aborted===true)return s(i({phase:"settled",...v,reason:"aborted"})),err(h);b+=1}}async function u(t){return withAuthHeaders(t,await Ne(e.auth))}async function*c(t,n,r){s(
8
+ return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:null,...e.freeCap?{freeCap:/* @__PURE__ */Object.freeze({...e.freeCap})}:{}})}var ie="x-everfur-anon-token",ae="anonTokenInvalid";async function oe(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function se(e,t){let n=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...n?{wireMessage:n}:{},...e!=null?{raw:e}:{}})}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[ie]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...de(e.headers),...authHeaders(t)}}}function de(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===ie||(t[n]=r)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let n=await oe(t),r=await t.transport.request(withAuthHeaders(e,ue(t,n)));if(r.ok||pe(r.error.raw)!==ae||t.anonIdentity===void 0||t.userRef!==null)return r;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===n?r:t.transport.request(withAuthHeaders(e,ue(t,l)))}let n;try{n=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(se(e))}let r=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:n,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(r.ok||r.error.httpStatus!==401)return r;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(se(e,{wireCode:pe(r.error.raw),requestId:r.error.requestId}))}let i=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!i.ok&&i.error.httpStatus===401?(t.identity.reportRejected?.(),err(ce(i.error))):i}function ue(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function ce(e){let t=e.raw,n=pe(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...n?{wireCode:n}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function pe(e){if(typeof e!="object"||e===null)return null;let t=e,n=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof n=="string"&&n.length>0?n:null}function fe(e,t){let n=globalThis.URL;if(typeof n=="function"){let r;try{r=t===void 0?new n(e):new n(e,t)}catch{return null}try{if(r.protocol)return r}catch{}}return be(e)}var he=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,me=/[\s\u0000-\u001f\u007f\\]/,ge={"http:":"80","https:":"443"};function be(e,t){let n=e.trim();let r=me.test(n)?null:he.exec(n);if(r===null)return null;let[,l="",i="",a="",o="",s="",d="",u="",c=""]=r,p=`${l.toLowerCase()}:`,f=Number(s);if(f>65535)return null;let h=s===""||String(f)===ge[p]?"":String(f),m=ge[p]!==void 0,g=o.toLowerCase()+(h&&`:${h}`),b=d||(m?"/":""),y=i||a?`${i}${a&&`:${a}`}@`:"";return{href:`${p}//${y}${g}${b}${u}${c}`,protocol:p,username:i,password:a,hostname:o.toLowerCase(),port:h,origin:m?`${p}//${g}`:"null",pathname:b,search:u==="?"?"":u,hash:c==="#"?"":c}}var ye="1.7.0";function networkError(e){return makeEverfurError("internalError",{retryable:true,wireMessage:ve(e)})}function ve(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var xe=3e4,ke=Y*2,we="idempotency-key",Te=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),Se=/* @__PURE__ */Object.freeze({onEvent(){}}),Ce=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function je(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}function createRequestFunnel(e){let t=e.observer??Se,n=e.timers??Ce,r=e.rng??Math.random,l=e.sleep??((e,t)=>We(e,n,t)),i=e.maxAttempts??G,a=e.unaryTimeoutMs??xe,o=e.newIdempotencyKey??Ie(),s=e=>{try{t.onEvent(e)}catch{}};async function d(t,d,u){let c=u?.maxAttempts,p=Math.max(1,c??i),f=u?.idempotent??Te.has(d.method),h=u?.idempotencyKey===void 0?null:je(u.idempotencyKey),m=f?h??o():null,g=_e(d,m),b=0;for(;;){let i=e=>/* @__PURE__ */Object.freeze({call:t,method:d.method,path:d.path,attempt:b,...m?{idempotencyKey:m}:{},...e});s(i({phase:"attempt"}));let o=Me(a,n),u=$e(o.signal,d.signal),f;try{f=await authedSend({...g,signal:u.signal},e.auth)}catch(e){f=err(networkError(e))}finally{u.dispose(),o.cancel()}if(f.ok)return s(i({phase:"settled",ok:true,reason:"ok"})),f;let h=f.error,y=Re(h,b,{maxAttempts:p,rng:r,now:n.now(),aborted:d.signal?.aborted===true,...c!==void 0?{perCallMaxAttempts:c}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),v={ok:false,code:h.code,reason:y.reason,...h.httpStatus!==void 0?{httpStatus:h.httpStatus}:{},...h.requestId!==void 0?{requestId:h.requestId}:{}};if(!y.retry)return s(i({phase:"settled",...v})),err(h);if(s(i({phase:"retry",...v,delayMs:y.delayMs})),await l(y.delayMs,d.signal),d.signal?.aborted===true)return s(i({phase:"settled",...v,reason:"aborted"})),err(h);b+=1}}async function u(t){return withAuthHeaders(t,await Ne(e.auth))}async function*c(t,n,r){s(
9
9
  /* @__PURE__ */Object.freeze({call:t,phase:"stream.open",method:n.method,path:n.path,attempt:0}));try{yield*e.auth.transport.stream(n,r)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
10
10
  return Object.freeze({send:d,authorize:u,stream:c})}function _e(e,t){let n={};for(let[t,r]of Object.entries(e.headers??{}))t.toLowerCase()!==we&&(n[t]=r);return t!==null&&(n["Idempotency-Key"]=t),{...e,headers:n}}function Ie(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var Ee=10;function Re(e,t,n){if(n.aborted)return{retry:false,reason:"aborted"};let r=Pe(e);if(r==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(r!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let l=r==="burst"?"burst-throttle":"retryable-code";if((()=>{if(n.policy===void 0)return false;try{return!n.policy.shouldRetry(e.code,t)}catch{return false}})())return{retry:false,reason:"terminal-code"};let i=()=>{if(n.policy===void 0)return null;let t;try{t=n.policy.maxAttempts(e.code)}catch{return null}return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(Ee,Math.floor(t)))},a=n.perCallMaxAttempts??i()??n.maxAttempts;if(t+1>=a)return{retry:false,reason:"attempts-exhausted"};let o=De(e,n.now);return o!==null?o>ke?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:l,delayMs:o}:{retry:true,reason:l,delayMs:backoffDelayMs(t,n.rng)}}function Pe(e){let t=e.code==="unknown"?fromWire(Be(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}function De(e,t){let n=Fe(e.raw);if(n!==null){let e=n-t;return e>0?e:0}let r=ze(e.raw);return r===null?null:Math.round(r*1e3)}function ze(e){for(let t of Ae(e)){let e=t.retry_after_seconds;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e}return null}function Fe(e){for(let t of Ae(e)){let e=t.resets_at,n=Oe(e);if(n!==null)return n}return null}function Ae(e){if(!Le(e))return[];let t=[e];for(let n of["error","detail"]){let r=e[n];Le(r)&&t.push(r)}return t}function Oe(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}function Be(e){for(let t of Ae(e)){let e=t.code;if(typeof e=="string"&&e.length>0)return e}return null}function Le(e){return typeof e=="object"&&e!==null}async function Ne(e){if(e.mode==="anonymous"){let t=await oe(e);return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}return{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}function Me(e,t){let n=new AbortController,r=t.setTimeout(()=>n.abort(),e);return{signal:n.signal,cancel:()=>t.clearTimeout(r)}}function $e(e,t){let n=()=>{};if(!t)return{signal:e,dispose:n};let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),{signal:r.signal,dispose:n};let l=()=>r.abort();return e.addEventListener("abort",l,{once:true}),t.addEventListener("abort",l,{once:true}),{signal:r.signal,dispose:()=>{e.removeEventListener("abort",l),t.removeEventListener("abort",l)}}}function We(e,t,n){return e<=0||n?.aborted===true?Promise.resolve():new Promise(r=>{let l=t.setTimeout(()=>{n?.removeEventListener("abort",i),r()},e),i=()=>{t.clearTimeout(l),r()};n?.addEventListener("abort",i,{once:true})})}function He(e){for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1}else if(n>=56320&&n<=57343)return true}return false}function Ve(e){return[...e].length}var Ue=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Ue,t)?Ue[t]:null}var qe=50,Ke=128,Ye=120,Ge=120,Je=2e3,Xe=120,Qe=80,Ze=/* @__PURE__ */new Set(["male","female","unknown"]),et=/* @__PURE__ */new Set(["day","month","year"]),tt=/* @__PURE__ */new Set(["low","medium","high","athletic"]),nt=/* @__PURE__ */new Set(["indoor","outdoor","both"]),rt=/* @__PURE__ */new Set(["mild","moderate","severe"]),lt=/^(\d{4})-(\d{2})-(\d{2})$/,it=[["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"]],at=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...it,...at].map(([e])=>e));function ot(e){let t=lt.exec(e);if(t===null)return false;let[n,r,l]=[Number(t[1]),Number(t[2]),Number(t[3])],i=new Date(Date.UTC(n,r-1,l));return i.getUTCFullYear()===n&&i.getUTCMonth()===r-1&&i.getUTCDate()===l}var st=e=>(t,n)=>typeof n=="string"&&e.has(n)?null:`${t} must be one of ${[...e].join(", ")}`,dt=(e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,ut=(e,t)=>typeof t=="string"&&ot(t)?null:`${e} must be a real date written YYYY-MM-DD`,ct=(e,t={})=>(n,r)=>{if(typeof r!="string")return`${n} must be a string`;if(He(r))return`${n} contains an unpaired surrogate and cannot be encoded`;let l=t.trimmed?r.trim():r;if(t.required&&l.length===0)return`${n} is required and must not be blank`;let i=Ve(l);return i<=e?null:`${n} is ${i} characters; the server accepts at most ${e}`},pt={sex:st(Ze),spayedNeutered:dt,birthDate:ut,birthDatePrecision:st(et),activityLevel:st(tt),indoorOutdoor:st(nt),foodBrand:ct(Xe),foodType:ct(Xe),microchipId:ct(Qe)},ft=["ref","ref",false,ct(Ke,{required:true,trimmed:true})],ht=["notes","notes",false,ct(Je,{trimmed:true})],mt=[ft,["name","name",true,ct(Ye,{required:true,trimmed:true})],["dose","dose",false,ct(Ge,{trimmed:true})],["frequency","frequency",false,ct(Ge,{trimmed:true})],["startDate","start_date",false,ut],["endDate","end_date",false,ut],ht],gt={allergies:[ft,["allergen","allergen",true,ct(Ye,{required:true,trimmed:true})],["severity","severity",false,st(rt)],ht],medications:mt,supplements:mt,conditions:[ft,["conditionName","condition_name",true,ct(Ye,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,ut],ht]};function bt(e,t,n){let r=`${e}[${t}]`;if(typeof n!="object"||n===null||Array.isArray(n))return{error:`${r} must be an object`};let l=n,i={};for(let[t,n,a,o]of gt[e]){let e=l[t];if(e==null){if(a)return{error:`${r}.${t} is required`};e===null&&(i[n]=null);continue}let s=o(`${r}.${t}`,e);if(s!==null)return{error:s};i[n]=e}let a=i.start_date,o=i.end_date;return typeof a=="string"&&typeof o=="string"&&o<a?{error:`${r}.endDate must not be before startDate`}:{item:i}}function yt(e,t){if(!Array.isArray(t))return{error:`${e} must be an array (send [] to clear it)`};if(t.length>qe)return{error:`${e} has ${t.length} items; the server accepts at most ${qe}`};let n=[],r=/* @__PURE__ */new Set;for(let l=0;l<t.length;l+=1){let i=bt(e,l,t[l]);if("error"in i)return i;let a=i.item.ref;if(typeof a=="string"){let t=a.trim();if(r.has(t))return{error:`${e}: ref ${JSON.stringify(t)} is used twice; a ref names one item`};r.add(t)}n.push(i.item)}return{items:n}}function vt(e,t){let n=e,r={};for(let[e,t]of it){let l=n[e];if(l!==void 0){if(l!==null){let t=pt[e](e,l);if(t!==null)return{error:t}}r[t]=l}}let l=n.birthDate!==void 0,i=n.birthDatePrecision!==void 0;if(l!==i||l&&n.birthDate===null!=(n.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[e,t]of at){let l=n[e];if(l===void 0)continue;let i=yt(e,l);if("error"in i)return i;r[t]=i.items}return Object.keys(r).length>0&&t!==void 0&&canonicalPetSpecies(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:r}}var xt=e=>typeof e=="string"?e:null,kt=(e,t)=>typeof t=="string"&&e.has(t)?t:null,wt=e=>typeof e=="boolean"?e:null;function Tt(e,t){return Array.isArray(e)?/* @__PURE__ */Object.freeze(e.flatMap(e=>{if(typeof e!="object"||e===null||Array.isArray(e))return[];let n=t(e);return n===null?[]:[n]})):/* @__PURE__ */Object.freeze([])}function St(e){let t=xt(e.name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:xt(e.ref),name:t,dose:xt(e.dose),frequency:xt(e.frequency),startDate:xt(e.start_date),endDate:xt(e.end_date),notes:xt(e.notes)})}function Ct(e){let t=e.profile_version;/* @__PURE__ */
11
11
  return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:kt(Ze,e.sex),spayedNeutered:wt(e.spayed_neutered),birthDate:xt(e.birth_date),birthDatePrecision:kt(et,e.birth_date_precision),activityLevel:kt(tt,e.activity_level),indoorOutdoor:kt(nt,e.indoor_outdoor),foodBrand:xt(e.food_brand),foodType:xt(e.food_type),microchipId:xt(e.microchip_id),allergies:Tt(e.allergies,e=>{let t=xt(e.allergen);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:xt(e.ref),allergen:t,severity:kt(rt,e.severity),notes:xt(e.notes)})}),medications:Tt(e.medications,St),supplements:Tt(e.supplements,St),conditions:Tt(e.conditions,e=>{let t=xt(e.condition_name);return t===null||t.length===0?null:/* @__PURE__ */Object.freeze({ref:xt(e.ref),conditionName:t,diagnosedDate:xt(e.diagnosed_date),notes:xt(e.notes)})})})}var jt=100,_t=50,It=100,Et=50,Rt=500,Pt=128,Dt=6e4;function zt(e){return makeEverfurError("validationFailed",{retryable:false,wireMessage:e})}function Ft(e,t,n){if(typeof t!="string")return zt(`${e} must be a string`);let r=Ve(t);return r<=n?null:zt(`${e} is ${r} characters; the server accepts at most ${n}`)}function At(e,t,n){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=n?null:zt(`${e} must be a finite number between 0 and ${n}`)}function Ot(petRef,e){if(typeof petRef!="string")return zt("pet_ref must be a string");if(petRef.trim().length===0)return zt("pet_ref must not be blank");if(He(petRef))return zt("pet_ref contains an unpaired surrogate and cannot be encoded");if(e!=null&&typeof e!="object")return zt("profile must be an object");let t=[Ft("pet_ref",petRef,Pt)];return e?.name!==void 0&&t.push(Ft("name",e.name,jt)),e?.species!==void 0&&t.push(Ft("species",e.species,_t)),e?.breed!==void 0&&t.push(Ft("breed",e.breed,It)),e?.ageYears!==void 0&&t.push(At("age_years",e.ageYears,Et)),e?.weightKg!==void 0&&t.push(At("weight_kg",e.weightKg,Rt)),t.find(e=>e!==null)??null}function Bt(e,t){let n=vt(e,t);return"error"in n?{error:zt(n.error)}:n}function Lt(e){if(typeof e!="object"||e===null)return{error:zt("patch must be an object")};let t=e,n=[["name","name",e=>Ft("name",e,jt)],["species","species",e=>Ft("species",e,_t)],["breed","breed",e=>Ft("breed",e,It)],["ageYears","age_years",e=>At("age_years",e,Et)],["weightKg","weight_kg",e=>At("weight_kg",e,Rt)]],r={};for(let[e,l,i]of n){let n=t[e];if(n!==void 0){if(n!==null){let e=i(n);if(e!==null)return{error:e}}r[l]=n}}let l=Bt(t,t.species);return"error"in l?l:(Object.assign(r,l.body),Object.keys(r).length===0?{error:zt("patch must change at least one field")}:{body:r})}function Nt(e){if(e==null)return{body:{}};let t=Bt(e,e.species);return"error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}var Mt=e=>typeof e=="string"?e:null,$t=e=>typeof e=="number"&&Number.isFinite(e)?e:null;function Wt(e,petRef){let t=typeof e=="object"&&e!==null?e:{};/* @__PURE__ */
@@ -26,7 +26,7 @@ return Object.freeze({kind:"clinician_unavailable"});case"televet_membership_con
26
26
  return Object.freeze({kind:"not_entitled"});case"televet_registry_unavailable":/* @__PURE__ */
27
27
  return Object.freeze({kind:"failed"})}/* @__PURE__ */
28
28
  return Object.freeze({kind:"failed"})}function $n(t){let{draft:n,reasonText:r,book:l,stateAttested:i,termsAttested:o,cancellationPolicy:s,triage:d,goTo:u,releaseSlot:c,setFailure:p,setEmergency:f,setBookedConsult:h,onBooked:m,media:g}=t,b=e.useCallback(e=>{let t=n.idempotencyKey;if(!canConfirm(n,r)||!t||g?.sending)return;if(isHoldExpired(n,Date.now())){p("expired"),u("time");return}let b=e=>{let t=televetBookingRefusal(e);if(t.kind==="emergency"){f(t.categories);return}if(t.kind==="rate_limited"){p("rate_limited");return}p(t.kind==="not_entitled"?"not_entitled":t.kind==="slot_taken"?"taken":t.kind==="clinician_unavailable"?"clinician_unavailable":t.kind==="unavailable"?"unavailable":"failed"),t.kind==="slot_taken"&&(c(),u("time"))};p(null),f(null);let y=c=>l.mutate({pet_id:n.petId,clinician_id:n.clinicianId,slot_id:n.slot.slotId,state:n.state,reason_text:r.trim(),species:null,media_refs:c,emergency_acknowledged:e||d.isAcknowledged(r),share_health_records:n.shareHealthRecords,...attestation(i,o,s)},t,{onSuccess:e=>{if(!a(e)){b(Pn(e.status));return}h(e),u("booked"),m?.(e)},onError:e=>b(Fn(e))});if(!g){y([]);return}g.send().then(y,()=>y([]))},[n,r,l,i,o,s,d,u,c,p,f,h,m,g]),y=e.useCallback(()=>b(false),[b]);return{submitBooking:b,confirm:y}}var Wn=/* @__PURE__ */Object.freeze({idle:/* @__PURE__ */Object.freeze({title:"Find your pet’s clinic",body:"Search for the clinic that holds your pet’s records. We’ll request them on your behalf once you sign the authorization.",action:null}),no_requests:/* @__PURE__ */Object.freeze({title:"No record requests yet",body:"When you request records from a clinic, you’ll be able to track every step here.",action:null}),no_records:/* @__PURE__ */Object.freeze({title:"Nothing to show just yet",body:"Once your pet’s records arrive and our team reviews them, lab trends and visits will appear here.",action:null}),rate_limited:/* @__PURE__ */Object.freeze({title:"Slow down a moment",body:"You’ve made a lot of requests just now. You can try again shortly.",action:"Try again"}),service_unavailable:/* @__PURE__ */Object.freeze({title:"Records search is temporarily down",body:"We’re working on it. Please try again in a few minutes.",action:"Try again"}),error:/* @__PURE__ */Object.freeze({title:"Couldn’t reach Everfur",body:"Check your connection and try again.",action:"Try again"})}),Hn=60;var Vn=/* @__PURE__ */Object.freeze({title:Wn.rate_limited.title,body:Wn.rate_limited.body});function Un(e){return e!=null&&(e.code==="rateLimited"||e.httpStatus===429)}function qn(e,t){return De(e,t)??Hn*1e3}function Kn(t){let n=Un(t),[r,l]=e.useState(null);return e.useEffect(()=>{if(!n||t==null)return;let e=setTimeout(()=>l(t),qn(t,Date.now()));return()=>clearTimeout(e)},[t,n]),{rateLimited:n,waiting:n&&r!==t}}var Yn=3e4;function Gn(e={}){let t=e.now??Date.now,n=/* @__PURE__ */new Map,r=e=>e!==void 0&&e.settled!==null&&t()<e.keptUntil?e.settled:null,l=(e,t,r)=>{let l=t.promise;t.waiters+=1;let i=()=>{t.waiters-=1,t.waiters===0&&t.promise!==null&&(t.abort.abort(),n.get(e)===t&&n.delete(e))};return r.aborted?(i(),l):(r.addEventListener("abort",i,{once:true}),l.finally(()=>r.removeEventListener("abort",i)))},i=(e,r,l,i)=>{if(r.promise=null,n.get(e)!==r||r.abort.signal.aborted){n.get(e)===r&&n.delete(e);return}l.ok&&i>0?(r.settled=l,r.keptUntil=t()+i):!l.ok&&Un(l.error)?(r.settled=l,r.keptUntil=t()+qn(l.error,t())):n.delete(e)};/* @__PURE__ */
29
- return Object.freeze({read(e,t,a){let o=n.get(e);if(o?.promise)return l(e,o,a.signal);let s=r(o);if(s!==null&&(a.force!==true||!s.ok&&Un(s.error)))return Promise.resolve(s);let d={abort:new AbortController,promise:null,settled:null,keptUntil:0,waiters:0};return n.set(e,d),d.promise=t(d.abort.signal).then(t=>(i(e,d,t,a.freshMs),t),t=>{throw d.promise=null,n.get(e)===d&&n.delete(e),t}),l(e,d,a.signal)},peek(e){return r(n.get(e))},invalidate(e){for(let t of[...n.keys()])e.some(e=>t.startsWith(e))&&n.delete(t)}})}var Jn=/* @__PURE__ */new WeakMap;function Xn(e){let t=Jn.get(e);return t===void 0&&(t=Gn(),Jn.set(e,t)),t}var Qn=/* @__PURE__ */Object.freeze(["slots:","next-slot"]),Zn=/* @__PURE__ */Object.freeze(["consults:","consult:","slots:","next-slot"]);function er(e,t){Jn.get(e)?.invalidate(t)}function tr(e){return e.slot!==null&&e.holdExpiresAt!==null&&e.idempotencyKey!==null?e.slot.slotId:null}function nr({controller:t,draft:n,keep:r}){let l=tr(n),i=e.useRef({controller:t,keep:r});i.current={controller:t,keep:r};let a=e.useRef(null);e.useEffect(()=>{let e=a.current;a.current=l,e!==null&&e!==l&&rr(i.current,e)},[l]),e.useEffect(()=>()=>{let e=a.current;a.current=null,e!==null&&rr(i.current,e)},[])}function rr(e,t){if(e.keep)return;let n=e.controller,r=n?.releaseHold;n==null||r===void 0||r.call(n,t).catch(()=>{}).finally(()=>er(n,Qn))}function lr(e){if(e.httpStatus===409)/* @__PURE__ */return Object.freeze({failure:"taken"});switch(televetBookingRefusal(e).kind){case"slot_taken":/* @__PURE__ */
29
+ return Object.freeze({read(e,t,a){let o=n.get(e);if(o?.promise)return l(e,o,a.signal);let s=r(o);if(s!==null&&(a.force!==true||!s.ok&&Un(s.error)))return Promise.resolve(s);let d={abort:new AbortController,promise:null,settled:null,keptUntil:0,waiters:0};return n.set(e,d),d.promise=t(d.abort.signal).then(t=>(i(e,d,t,a.freshMs),t),t=>{throw d.promise=null,n.get(e)===d&&n.delete(e),t}),l(e,d,a.signal)},peek(e){return r(n.get(e))},invalidate(e){for(let t of[...n.keys()])e.some(e=>t.startsWith(e))&&n.delete(t)}})}var Jn=globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.televetReadCaches.v1")]??=/* @__PURE__ */new WeakMap;function Xn(e){let t=Jn.get(e);return t===void 0&&(t=Gn(),Jn.set(e,t)),t}var Qn=/* @__PURE__ */Object.freeze(["slots:","next-slot"]),Zn=/* @__PURE__ */Object.freeze(["consults:","consult:","slots:","next-slot"]);function er(e,t){Jn.get(e)?.invalidate(t)}function tr(e){return e.slot!==null&&e.holdExpiresAt!==null&&e.idempotencyKey!==null?e.slot.slotId:null}function nr({controller:t,draft:n,keep:r}){let l=tr(n),i=e.useRef({controller:t,keep:r});i.current={controller:t,keep:r};let a=e.useRef(null);e.useEffect(()=>{let e=a.current;a.current=l,e!==null&&e!==l&&rr(i.current,e)},[l]),e.useEffect(()=>()=>{let e=a.current;a.current=null,e!==null&&rr(i.current,e)},[])}function rr(e,t){if(e.keep)return;let n=e.controller,r=n?.releaseHold;n==null||r===void 0||r.call(n,t).catch(()=>{}).finally(()=>er(n,Qn))}function lr(e){if(e.httpStatus===409)/* @__PURE__ */return Object.freeze({failure:"taken"});switch(televetBookingRefusal(e).kind){case"slot_taken":/* @__PURE__ */
30
30
  return Object.freeze({failure:"taken"});case"rate_limited":/* @__PURE__ */
31
31
  return Object.freeze({failure:"rate_limited"});case"not_entitled":/* @__PURE__ */
32
32
  return Object.freeze({failure:"not_entitled"});case"unavailable":/* @__PURE__ */
@@ -38,7 +38,7 @@ return Object.freeze({messageId:e.message_id,petRef:e.pet_ref,role:e.role,conten
38
38
  return Object.freeze({drug:n,strength:Rr(t.data.strength),form:Rr(t.data.form),sig:Rr(t.data.sig),quantity:r==null?null:Rr(String(r)),refills:t.data.refills??null})}function Or(e){let t=Er.safeParse(e);if(!t.success)return null;let n=t.data;/* @__PURE__ */
39
39
  return Object.freeze({consultId:n.consult_id,findingsText:n.findings_text??"",nextStepsText:n.next_steps_text??"",medications:/* @__PURE__ */Object.freeze((n.medications??[]).map(Ar).filter(e=>e!==null)),productRefs:/* @__PURE__ */Object.freeze([...n.product_refs??[]]),actionItems:/* @__PURE__ */Object.freeze((n.action_items??[]).filter(e=>e.trim().length>0)),approvedAt:n.approved_at,approvedByName:Rr(n.approved_by_display_name),credentialsText:Rr(n.credentials_text)})}function isVetMessagesDark(e){return e.httpStatus===404}function isVetThreadVetFirst(e){return e.httpStatus===409}function Br(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function Lr(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function Nr(e){return e===void 0||!Number.isFinite(e)?wr:Math.min(Tr,Math.max(1,Math.trunc(e)))}function Mr(e){return e.trim().length>0&&!Number.isNaN(Date.parse(e))}function $r(e,t,n){try{e?.track(t,n)}catch{}}function Wr(e,t){return{async listVetThreads(t){let n=await e.send("televet.messages.threads",{method:"GET",path:xr,...t?{signal:t}:{}});if(!n.ok)return err(n.error);let r=Fr(n.value);return r===null?Lr("the vet thread list was unreadable"):ok(r)},async listVetMessages(petRef,t={},n){let r=petRef.trim();if(r.length===0)return Br("petRef is required");let l=t.before?.trim();if(l!==void 0&&l.length>0&&!Mr(l))return Br("before must be an ISO date-time");let i=await e.send("televet.messages.thread",{method:"GET",path:televetThreadMessagesCall(r),query:{...l?{before:l}:{},limit:Nr(t.limit)},...n?{signal:n}:{}});if(!i.ok)return err(i.error);let a=zr(i.value);return a===null?Lr("the vet thread page was unreadable"):ok(a)},async sendVetMessage(petRef,n){let r=petRef.trim();if(r.length===0)return Br("petRef is required");if(n.trim().length===0)return Br("content must not be blank");if(n.length>kr)return Br(`content must be at most ${kr} characters`);let l=await e.send("televet.messages.send",{method:"POST",path:televetThreadMessagesCall(r),body:{content:n}},{idempotent:false,maxAttempts:1});if(!l.ok)return $r(t,"televet.messages.send_failed",{status:l.error.httpStatus??null}),err(l.error);let i=Dr(l.value);return i===null?Lr("the sent message was unreadable"):ok(i)},async markVetThreadRead(petRef,t){let n=petRef.trim();if(n.length===0)return Br("petRef is required");if(!Mr(t))return Br("readAt must be an ISO date-time");let r=await e.send("televet.messages.read",{method:"PUT",path:televetThreadReadCall(n),body:{read_at:t}});return r.ok?ok(void 0):err(r.error)},async visitSummary(t,n){let r=t.trim();if(r.length===0)return Br("consultId is required");let l=await e.send("televet.messages.summary",{method:"GET",path:televetVisitSummaryCall(r),...n?{signal:n}:{}});if(!l.ok)return err(l.error);let i=Or(l.value);return i===null?Lr("the visit summary was unreadable"):ok(i)}}}var Hr="/widget/v1/televet",Vr=`${Hr}/state-policy`,Ur=`${Hr}/vets`,qr=`${Hr}/slots`,Kr=`${Hr}/slots/next`,Yr=`${Hr}/consults`,Gr=`${Hr}/entitlement`,Jr=`${Hr}/cancellation-policy`,Xr=`${Hr}/attachments/initiate`,Qr=`${Yr}/triage`;function televetHoldCall(e){return`${qr}/${encodeURIComponent(e)}/hold`}function televetRescheduleCall(e){return`${Yr}/${encodeURIComponent(e)}/reschedule`}function televetConsultCall(e){return`${Yr}/${encodeURIComponent(e)}`}function televetJoinCall(e){return`${televetConsultCall(e)}/join`}function televetCancelCall(e){return`${televetConsultCall(e)}/cancel`}var Zr=100;function el(e){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:e}))}function tl(e){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}function nl(e){return e.httpStatus===404}function rl(e,t,n){try{e?.track(t,n)}catch{}}function validateBookingBody(e){if(e.pet_id.trim().length===0)return"pet_id is required";if(e.clinician_id.trim().length===0)return"clinician_id is required";if(e.slot_id.trim().length===0)return"slot_id is required";if(!isWellFormedStateCode(e.state))return"state must be a two-letter US state code";let t=e.reason_text.trim();return t.length===0?"reason_text is required":t.length>c?`reason_text must be at most ${c} characters`:ll(e)}function ll(e){let t=e.state_attested===true,n=e.cancellation_policy_version?.trim()??"";return t!==n.length>0?"state_attested and cancellation_policy_version must be sent together or omitted together":n.length>u?`cancellation_policy_version must be at most ${u} characters`:null}function createTelevetBookingController(e){let t=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=e.telemetry;return{...Wr(t,n),async statePolicy(e,n){let r=e.trim();if(!isWellFormedStateCode(r))return el("state must be a two-letter US state code");let l=await t.send("televet.booking.state_policy",{method:"GET",path:`${Vr}/${encodeURIComponent(r)}`,...n?{signal:n}:{}});if(!l.ok)return err(l.error);let i=x(l.value,r);return i===null?tl("the state policy response was unreadable"):ok(i)},async entitlement(e){let n=await t.send("televet.booking.entitlement",{method:"GET",path:Gr,...e?{signal:e}:{}});return n.ok?ok(I(n.value)):err(n.error)},async cancellationPolicy(e){let n=await t.send("televet.booking.cancellation_policy",{method:"GET",path:Jr,...e?{signal:e}:{}});return n.ok?ok(k(n.value)):ok(null)},async clinicians(e,n){let r=e.trim();if(!isWellFormedStateCode(r))return el("state must be a two-letter US state code");let l=await t.send("televet.booking.clinicians",{method:"GET",path:Ur,query:{state:r},...n?{signal:n}:{}});return l.ok?ok(v(al(l.value,"vets"),w)):nl(l.error)?ok(/* @__PURE__ */Object.freeze([])):err(l.error)},async slots(e,n){let r=e.trim();if(r.length===0)return el("clinicianId is required");let l=await t.send("televet.booking.slots",{method:"GET",path:qr,query:{clinician_id:r},...n?{signal:n}:{}});return l.ok?ok(v(al(l.value,"slots"),S)):nl(l.error)?ok(/* @__PURE__ */Object.freeze([])):err(l.error)},async nextSlot(e){let n=await t.send("televet.booking.next_slot",{method:"GET",path:Kr,...e?{signal:e}:{}});return n.ok?ok(S(unwrap(n.value,"slot"))):ok(null)},async holdSlot(e){let r=e.trim();if(r.length===0)return el("slotId is required");let l=await t.send("televet.booking.hold",{method:"POST",path:televetHoldCall(r)},{idempotent:false,maxAttempts:1});if(!l.ok)return rl(n,"televet.booking.hold_failed",{status:l.error.httpStatus??null}),err(l.error);let i=j(l.value);return i===null?tl("the hold response carried no usable expiry"):ok(i)},async releaseHold(e){let n=e.trim();if(n.length===0)return el("slotId is required");let r=await t.send("televet.booking.release_hold",{method:"DELETE",path:televetHoldCall(n)},{idempotent:false,maxAttempts:1});return!r.ok&&r.error.httpStatus!==404?err(r.error):ok(void 0)},async book(e,r){let l=validateBookingBody(e);if(l!==null)return el(l);let i=r.trim();if(i.length===0)return el("idempotencyKey is required");let o=await t.send("televet.booking.book",{method:"POST",path:Yr,body:il(e)},{idempotent:true,idempotencyKey:i,maxAttempts:1});if(!o.ok)return rl(n,"televet.booking.book_failed",{status:o.error.httpStatus??null}),err(Fn(o.error));let s=_(o.value);return s===null?tl("the booking response was unreadable"):a(s)?ok(s):(rl(n,"televet.booking.book_failed",{status:null,consult_status:s.status}),err(Pn(s.status)))},async reschedule(e,r){let l=e.trim(),i=r.trim();if(l.length===0)return el("consultId is required");if(i.length===0)return el("slotId is required");let a=await t.send("televet.booking.reschedule",{method:"POST",path:televetRescheduleCall(l),body:{new_slot_id:i}},{idempotent:false,maxAttempts:1});if(!a.ok)return rl(n,"televet.booking.reschedule_failed",{status:a.error.httpStatus??null}),err(a.error);let o=_(a.value);return o===null?tl("the reschedule response was unreadable"):ok(o)},async triage(e,r){let l=e.trim();if(l.length===0)return ok(null);let i=await t.send("televet.booking.triage",{method:"POST",path:Qr,body:{reason_text:l},...r?{signal:r}:{}},{idempotent:false,maxAttempts:1});return i.ok?ok(C(i.value)):(rl(n,"televet.booking.triage_unavailable",{status:i.error.httpStatus??null}),ok(null))},async listConsults(e){let n=await t.send("televet.booking.consults",{method:"GET",path:Yr,query:{limit:String(Zr)},...e?{signal:e}:{}});return n.ok?ok(v(al(n.value,"consults"),_)):nl(n.error)?ok(/* @__PURE__ */Object.freeze([])):err(n.error)},async getConsult(e,n){let r=e.trim();if(r.length===0)return el("consultId is required");let l=await t.send("televet.booking.consult",{method:"GET",path:televetConsultCall(r),...n?{signal:n}:{}});if(!l.ok)return err(l.error);let i=_(l.value);return i===null?tl("the consult response was unreadable"):ok(i)},async joinConsult(e){let r=e.trim();if(r.length===0)return el("consultId is required");let l=await t.send("televet.booking.join",{method:"POST",path:televetJoinCall(r)},{idempotent:false,maxAttempts:1});if(!l.ok)return rl(n,"televet.booking.join_failed",{status:l.error.httpStatus??null}),err(l.error);let i=parseVetCallCredential(l.value);return i===null?tl("the join response carried no usable room credential"):ok(i)},async cancelConsult(e,r){let l=e.trim(),i=r.trim();if(l.length===0)return el("consultId is required");if(i.length===0)return el("reason is required");if(i.length>E)return el(`reason must be at most ${E} characters`);let a=await t.send("televet.booking.cancel",{method:"POST",path:televetCancelCall(l),body:{reason:i}},{idempotent:false,maxAttempts:1});if(!a.ok)return rl(n,"televet.booking.cancel_failed",{status:a.error.httpStatus??null}),err(a.error);let o=R(a.value);return o===null?tl("the cancel response was unreadable"):ok(o)},async initiateAttachment(e,n){let r=await t.send("televet.booking.attachment_initiate",{method:"POST",path:Xr,body:{filename:e.filename,content_type:e.contentType,file_size:e.fileSize},...n?{signal:n}:{}});if(!r.ok)return err(r.error);let l=pr(r.value);return l===null?tl("the attachment presign was unreadable"):ok(l)}}}function il(e){let t=e.cancellation_policy_version?.trim()??"",n=e.state_attested===true&&t.length>0;return{pet_id:e.pet_id,clinician_id:e.clinician_id,slot_id:e.slot_id,state:e.state,reason_text:e.reason_text.trim(),species:e.species,media_refs:[...e.media_refs],emergency_acknowledged:e.emergency_acknowledged,share_health_records:e.share_health_records,...n?{state_attested:true,cancellation_policy_version:t}:{}}}function al(e,t){if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null){let n=e,r=n[t]??n.items??n.data;if(Array.isArray(r))return r}return e}function unwrap(e,t){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e,r=n[t]??n.data;if(typeof r=="object"&&r!==null)return r}return e}var ol=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(e){return ol[e]}function decideCapability(e,t,n){let r=requires(e),l=/* @__PURE__ */new Map;for(let e of t)l.set(e.resource,e);if(n?.isPending===true&&r.some(e=>!l.has(e)))return ul({name:e,enabled:false,isPending:true,limits:{}});let i=sl(r,l);return r.filter(e=>l.get(e)?.granted!==true).length===0?ul({name:e,enabled:true,isPending:false,limits:i}):ul({name:e,enabled:false,isPending:false,limits:i,disabled:dl(r,l)})}function sl(e,t){let n={};for(let r of e){let e=t.get(r)?.limits;if(e)for(let[t,r]of Object.entries(e)){let e=n[t];n[t]=e===void 0?r:Math.min(e,r)}}return n}function dl(e,t){for(let n of e){let e=t.get(n)?.disabled;if(e)/* @__PURE__ */
40
40
  return Object.freeze({reason:e.reason,level:e.level,recoverable:e.recoverable})}/* @__PURE__ */
41
- return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function ul(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:/* @__PURE__ */Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),/* @__PURE__ */Object.freeze(t)}function useCapability(t){let{runtime:n}=Xt(),r=n.entitlements,l=e.useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return e.useMemo(()=>decideCapability(t,l.decisions,{isPending:l.isPending}),[t,l])}function useTelevetBookingController(t){let{runtime:n,userRef:userRef,scopeEpoch:r}=Xt();return e.useMemo(()=>t||(userRef===null?null:pl(n,`${userRef}\0${r}`,()=>{let{services:e}=n.registry;return createTelevetBookingController({auth:e.authFor(userRef),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})})),[n,userRef,r,t])}var cl=/* @__PURE__ */new WeakMap;function pl(e,t,n){let r=cl.get(e);if(r!==void 0&&r.scope===t)return r.controller;let l=n();return cl.set(e,{scope:t,controller:l}),l}function useTelevetBookingAvailable(){let{userRef:userRef}=Xt(),t=useCapability("televet");return e.useMemo(()=>({available:t.enabled&&userRef!==null,isPending:t.isPending}),[t.enabled,t.isPending,userRef])}function fl(t,n,r,l,i=Yn,a=false){let[o,s]=e.useState(()=>{let e=n&&r!==null&&l!==null&&!a?Xn(l).peek(t):null;return e!==null?e.ok?{key:t,data:e.value,isPending:false,error:null}:{key:t,data:null,isPending:false,error:e.error}:{key:t,data:null,isPending:n&&r!==null,error:null}}),[d,u]=e.useState(0),c=e.useRef(r);c.current=r;let p=e.useRef(l);p.current=l;let f=e.useRef(a);e.useEffect(()=>{let e=c.current;if(!n||e===null){s({key:t,data:null,isPending:false,error:null});return}let r=f.current;f.current=false;let l=p.current===null?null:Xn(p.current),a=r||l===null?null:l.peek(t);if(a!==null){s(a.ok?{key:t,data:a.value,isPending:false,error:null}:{key:t,data:null,isPending:false,error:a.error});return}let o=new AbortController,d=true;return s(e=>e.key===t?{...e,isPending:true,error:null}:{key:t,data:null,isPending:true,error:null}),(async()=>{let n;try{n=l===null?await e(o.signal):await l.read(t,e,{signal:o.signal,freshMs:i,force:r})}catch{d&&s({key:t,data:null,isPending:false,error:null});return}d&&(n.ok?s({key:t,data:n.value,isPending:false,error:null}):s({key:t,data:null,isPending:false,error:n.error}))})(),()=>{d=false,o.abort()}},[t,n,d]);let h=e.useCallback(()=>{f.current=true,u(e=>e+1)},[]),m=o.key===t;return e.useMemo(()=>({enabled:n,data:m?o.data:null,isPending:n&&(!m||o.isPending),isError:m&&o.error!==null,error:m?o.error:null,refetch:h}),[n,m,o.data,o.isPending,o.error,h])}function useTelevetStatePolicy(e,t){let n=e?.trim()??"",r=t?.statePolicy!==void 0&&isWellFormedStateCode(n),l=t?.statePolicy;return fl(`state-policy:${n}`,r,r&&l?e=>l.call(t,n,e):null,t)}function useTelevetBookingEntitlement(e){let t=e?.entitlement!==void 0,n=e?.entitlement;return fl("entitlement",t,t&&n?t=>n.call(e,t):null,e,0)}function useTelevetCancellationPolicy(e){let t=e?.cancellationPolicy!==void 0,n=e?.cancellationPolicy;return fl("cancellation-policy",t,t&&n?t=>n.call(e,t):null,e)}function useTelevetClinicians(e,t){let n=e?.trim()??"",r=t?.clinicians!==void 0&&isWellFormedStateCode(n),l=t?.clinicians;return fl(`clinicians:${n}`,r,r&&l?e=>l.call(t,n,e):null,t)}function useTelevetSlots(e,t){let n=e?.trim()??"",r=t!==null&&n.length>0;return fl(`slots:${n}`,r,r&&t?e=>t.slots(n,e):null,t)}function useTelevetNextSlot(e){let t=e?.nextSlot!==void 0,n=e?.nextSlot;return fl("next-slot",t,t&&n?t=>n.call(e,t):null,e)}function hl(t){let[n,r]=e.useState(null),l=e.useRef(true),i=e.useRef(false),a=e.useRef(t);a.current=t,e.useEffect(()=>(l.current=true,()=>{l.current=false}),[]);let o=e.useCallback((...e)=>{let t=a.current;if(t===null||i.current)return;let n=e[e.length-1],o=typeof n=="object"&&n!==null&&("onSuccess"in n||"onError"in n),s=o?n:void 0,d=o?e.slice(0,-1):e;i.current=true,r({variables:d[0]??null}),(async()=>{let e=null;try{e=await t(...d)}catch{e=null}i.current=false,l.current&&r(null),e!==null&&(e.ok?s?.onSuccess?.(e.value):s?.onError?.(e.error))})()},[]);return e.useMemo(()=>({isPending:n!==null,variables:n?.variables??null,mutate:o}),[n,o])}async function ml(e,t,n){let r=await n;return r.ok&&er(e,t),r}function useTelevetHoldSlot(e){return hl(e?t=>ml(e,Qn,e.holdSlot(t)):null)}function useTelevetBookConsult(e){return hl(e?(t,n)=>ml(e,Zn,e.book(t,n)):null)}function useTelevetRescheduleConsult(e,t){return hl(t&&e?n=>ml(t,Zn,t.reschedule(e,n)):null)}function gl(e,t=0,n){let r=e?.listConsults!==void 0,l=e?.listConsults;return fl(`consults:${t}`,r,r&&l?t=>l.call(e,t):null,e,Yn,n?.reread===true)}function bl(e){return e.error!==null&&e.error.httpStatus===404}function televetEmptyRosterView(e){/* @__PURE__ */
41
+ return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function ul(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:/* @__PURE__ */Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),/* @__PURE__ */Object.freeze(t)}function useCapability(t){let{runtime:n}=Xt(),r=n.entitlements,l=e.useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return e.useMemo(()=>decideCapability(t,l.decisions,{isPending:l.isPending}),[t,l])}function useTelevetBookingController(t){let{runtime:n,userRef:userRef,scopeEpoch:r}=Xt();return e.useMemo(()=>t||(userRef===null?null:pl(n,`${userRef}\0${r}`,()=>{let{services:e}=n.registry;return createTelevetBookingController({auth:e.authFor(userRef),telemetry:e.telemetry,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}})})),[n,userRef,r,t])}var cl=globalThis[/* @__PURE__ */Symbol.for("everfur.sdk.televetBookingControllers.v1")]??=/* @__PURE__ */new WeakMap;function pl(e,t,n){let r=cl.get(e);if(r!==void 0&&r.scope===t)return r.controller;let l=n();return cl.set(e,{scope:t,controller:l}),l}function useTelevetBookingAvailable(){let{userRef:userRef}=Xt(),t=useCapability("televet");return e.useMemo(()=>({available:t.enabled&&userRef!==null,isPending:t.isPending}),[t.enabled,t.isPending,userRef])}function fl(t,n,r,l,i=Yn,a=false){let[o,s]=e.useState(()=>{let e=n&&r!==null&&l!==null&&!a?Xn(l).peek(t):null;return e!==null?e.ok?{key:t,data:e.value,isPending:false,error:null}:{key:t,data:null,isPending:false,error:e.error}:{key:t,data:null,isPending:n&&r!==null,error:null}}),[d,u]=e.useState(0),c=e.useRef(r);c.current=r;let p=e.useRef(l);p.current=l;let f=e.useRef(a);e.useEffect(()=>{let e=c.current;if(!n||e===null){s({key:t,data:null,isPending:false,error:null});return}let r=f.current;f.current=false;let l=p.current===null?null:Xn(p.current),a=r||l===null?null:l.peek(t);if(a!==null){s(a.ok?{key:t,data:a.value,isPending:false,error:null}:{key:t,data:null,isPending:false,error:a.error});return}let o=new AbortController,d=true;return s(e=>e.key===t?{...e,isPending:true,error:null}:{key:t,data:null,isPending:true,error:null}),(async()=>{let n;try{n=l===null?await e(o.signal):await l.read(t,e,{signal:o.signal,freshMs:i,force:r})}catch{d&&s({key:t,data:null,isPending:false,error:null});return}d&&(n.ok?s({key:t,data:n.value,isPending:false,error:null}):s({key:t,data:null,isPending:false,error:n.error}))})(),()=>{d=false,o.abort()}},[t,n,d]);let h=e.useCallback(()=>{f.current=true,u(e=>e+1)},[]),m=o.key===t;return e.useMemo(()=>({enabled:n,data:m?o.data:null,isPending:n&&(!m||o.isPending),isError:m&&o.error!==null,error:m?o.error:null,refetch:h}),[n,m,o.data,o.isPending,o.error,h])}function useTelevetStatePolicy(e,t){let n=e?.trim()??"",r=t?.statePolicy!==void 0&&isWellFormedStateCode(n),l=t?.statePolicy;return fl(`state-policy:${n}`,r,r&&l?e=>l.call(t,n,e):null,t)}function useTelevetBookingEntitlement(e){let t=e?.entitlement!==void 0,n=e?.entitlement;return fl("entitlement",t,t&&n?t=>n.call(e,t):null,e,0)}function useTelevetCancellationPolicy(e){let t=e?.cancellationPolicy!==void 0,n=e?.cancellationPolicy;return fl("cancellation-policy",t,t&&n?t=>n.call(e,t):null,e)}function useTelevetClinicians(e,t){let n=e?.trim()??"",r=t?.clinicians!==void 0&&isWellFormedStateCode(n),l=t?.clinicians;return fl(`clinicians:${n}`,r,r&&l?e=>l.call(t,n,e):null,t)}function useTelevetSlots(e,t){let n=e?.trim()??"",r=t!==null&&n.length>0;return fl(`slots:${n}`,r,r&&t?e=>t.slots(n,e):null,t)}function useTelevetNextSlot(e){let t=e?.nextSlot!==void 0,n=e?.nextSlot;return fl("next-slot",t,t&&n?t=>n.call(e,t):null,e)}function hl(t){let[n,r]=e.useState(null),l=e.useRef(true),i=e.useRef(false),a=e.useRef(t);a.current=t,e.useEffect(()=>(l.current=true,()=>{l.current=false}),[]);let o=e.useCallback((...e)=>{let t=a.current;if(t===null||i.current)return;let n=e[e.length-1],o=typeof n=="object"&&n!==null&&("onSuccess"in n||"onError"in n),s=o?n:void 0,d=o?e.slice(0,-1):e;i.current=true,r({variables:d[0]??null}),(async()=>{let e=null;try{e=await t(...d)}catch{e=null}i.current=false,l.current&&r(null),e!==null&&(e.ok?s?.onSuccess?.(e.value):s?.onError?.(e.error))})()},[]);return e.useMemo(()=>({isPending:n!==null,variables:n?.variables??null,mutate:o}),[n,o])}async function ml(e,t,n){let r=await n;return r.ok&&er(e,t),r}function useTelevetHoldSlot(e){return hl(e?t=>ml(e,Qn,e.holdSlot(t)):null)}function useTelevetBookConsult(e){return hl(e?(t,n)=>ml(e,Zn,e.book(t,n)):null)}function useTelevetRescheduleConsult(e,t){return hl(t&&e?n=>ml(t,Zn,t.reschedule(e,n)):null)}function gl(e,t=0,n){let r=e?.listConsults!==void 0,l=e?.listConsults;return fl(`consults:${t}`,r,r&&l?t=>l.call(e,t):null,e,Yn,n?.reread===true)}function bl(e){return e.error!==null&&e.error.httpStatus===404}function televetEmptyRosterView(e){/* @__PURE__ */
42
42
  return Object.freeze(e==="dark"?{title:nn.noCliniciansTitle,message:nn.noCliniciansBody,retryLabel:nn.noCliniciansRetryCta,interestReason:null}:{title:nn.noCliniciansTitle,message:nn.noCliniciansRegionBody,retryLabel:null,interestReason:"no_licensed_vet"})}function televetEmptyRosterCause(e){return e?"roster":"dark"}var yl=e=>/* @__PURE__ */Object.freeze({ok:true,value:e}),vl=e=>/* @__PURE__ */Object.freeze({ok:false,error:e});function xl(e,t,n,r){/* @__PURE__ */
43
43
  return Object.freeze({code:e,retryable:t,filename:n,...{}})}async function uploadAttachmentBytes(e,t,n,r){let l=()=>r?.signal?.aborted===true;if(l())return vl(xl("cancelled",true,n.filename));try{return await e.postMultipart(t,n.file,{...r?.signal?{signal:r.signal}:{},...r?.onProgress?{onProgress:r.onProgress}:{}}),yl(void 0)}catch{return l()?vl(xl("cancelled",true,n.filename)):vl(xl("server",true,n.filename))}}var kl=/* @__PURE__ */Object.freeze({failed:0,refused:/* @__PURE__ */Object.freeze({size:0,type:0,unreadable:0})});function isMediaShortfallEmpty(e){let{failed:t,refused:n}=e;return t<=0&&n.size<=0&&n.type<=0&&n.unreadable<=0}function televetMediaShortfallLines(e){let t=e=>Number.isFinite(e)&&e>0?Math.floor(e):0,n=nn.media;return[{n:t(e.failed),one:n.droppedTemplate,many:n.droppedPluralTemplate},{n:t(e.refused.size),one:n.refusedSizeTemplate,many:n.refusedSizePluralTemplate},{n:t(e.refused.type),one:n.refusedTypeTemplate,many:n.refusedTypePluralTemplate},{n:t(e.refused.unreadable),one:n.refusedUnreadableTemplate,many:n.refusedUnreadablePluralTemplate}].filter(e=>e.n>0).map(e=>tn(e.n===1?e.one:e.many,{n:String(e.n)}))}function mediaShortfallFromUnsentPicks(e){let t=Number.isFinite(e)&&e>0?Math.floor(e):0;return t===0?kl:/* @__PURE__ */Object.freeze({failed:t,refused:kl.refused})}function withUnsentPicks(e,t){let n=mediaShortfallFromUnsentPicks(t);return n.failed===0?e:/* @__PURE__ */Object.freeze({failed:e.failed+n.failed,refused:e.refused})}var wl=6e4;function Tl(e){let t=ur(e.filename,e.mimeType);return t===null?null:{file:{uri:e.uri,name:e.filename,mimeType:t,sizeBytes:e.fileSize},filename:e.filename,contentType:t,sizeBytes:e.fileSize}}function Sl(e,t){if(e?.kind!=="ready")return null;let n=e.policy.expires_in_seconds*1e3;return t-e.at<n-wl?e.policy:null}function Cl({media:t,controller:n,transport:r}){let[l,i]=e.useState(()=>/* @__PURE__ */new Map),[a,o]=e.useState(false),[s,d]=e.useState(false),u=e.useRef(l),c=e.useRef(t);c.current=t;let p=e.useRef(false),f=e.useRef(false),h=e.useRef(new AbortController);e.useEffect(()=>{let e=new AbortController;return h.current=e,()=>e.abort()},[]);let m=n?.initiateAttachment?.bind(n),g=a||m===void 0,b=e.useCallback((e,t)=>{let n=new Map(u.current);n.set(e,t),u.current=n,i(n)},[]),y=e.useCallback(()=>{p.current=true,o(true)},[]),v=e.useCallback(async(e,t)=>{if(m===void 0)return"dark";let n=await m({filename:t.filename,contentType:t.contentType,fileSize:t.sizeBytes},h.current.signal);if(h.current.signal.aborted)return null;if(n.ok)return b(e.uri,{kind:"ready",policy:n.value,at:Date.now()}),n.value;let r=hr(n.error);return r==="dark"?"dark":(b(e.uri,r==="failed"?{kind:"retry"}:{kind:"refused",cause:r}),null)},[m,b]);e.useEffect(()=>{if(!g)for(let e of t){if(u.current.has(e.uri))continue;let t=cr(e),n=Tl(e);if(t!==null||n===null){b(e.uri,{kind:"refused",cause:t??"type"});continue}b(e.uri,{kind:"checking"}),v(e,n).then(e=>{e==="dark"&&y()})}},[t,g,v,b,y]);let x=e.useCallback(async()=>{if(p.current||m===void 0||f.current)return[];f.current=true,d(true);let e=[];try{for(let t of c.current){let n=u.current.get(t.uri);if(n?.kind==="sent"){e.push(n.s3Key);continue}if(n?.kind==="refused")continue;let l=Tl(t);if(l===null)continue;let i=Sl(n,Date.now());if(i===null){let e=await v(t,l);if(e==="dark")return y(),[];if(e===null){u.current.get(t.uri)?.kind==="retry"&&b(t.uri,{kind:"failed"});continue}i=e}if(h.current.signal.aborted)return[];let a=await uploadAttachmentBytes(r,i,l,{signal:h.current.signal});if(h.current.signal.aborted)return[];a.ok?(b(t.uri,{kind:"sent",s3Key:i.s3_key}),e.push(i.s3_key)):b(t.uri,{kind:"failed"})}return e}catch{return e}finally{f.current=false,h.current.signal.aborted||d(false)}},[m,v,b,y,r]),k=e.useMemo(()=>{if(t.length===0)return kl;if(g)return mediaShortfallFromUnsentPicks(t.length);let e={size:0,type:0,unreadable:0},n=0;for(let r of t){let t=l.get(r.uri);t?.kind==="refused"?e[t.cause]+=1:t?.kind==="failed"&&(n+=1)}return n===0&&e.size+e.type+e.unreadable===0?kl:/* @__PURE__ */Object.freeze({failed:n,refused:/* @__PURE__ */Object.freeze(e)})},[t,g,l]),w=e.useMemo(()=>t.flatMap(e=>{let t=l.get(e.uri);return t?.kind==="sent"?[{key:t.s3Key,pick:e}]:[]}),[t,l]),T=e.useCallback(e=>{if(g)return k;let t=new Set(e.mediaRefs),n=w.filter(e=>!t.has(e.key)).length;return n===0?k:/* @__PURE__ */Object.freeze({failed:k.failed+n,refused:k.refused})},[g,k,w]),S=e.useCallback(e=>{if(g||w.length!==1)return false;let[t]=w;return t===void 0||!e.mediaRefs.includes(t.key)?false:(ur(t.pick.filename,t.pick.mimeType)??"").startsWith("image/")},[g,w]),C=!g&&[...l.values()].some(e=>e.kind==="ready"||e.kind==="sent");return e.useMemo(()=>({shortfall:k,sending:s,live:C,send:x,bookedShortfall:T,sentOnePhoto:S}),[k,s,C,x,T,S])}var jl="file",_l="chat attachment upload: the file handle carries no bytes",Il="chat attachment upload failed";function createWebAttachmentTransport(e={}){let t=e.fetch??((e,t)=>fetch(e,t));/* @__PURE__ */
44
44
  return Object.freeze({postMultipart(e,n,r){let l=n.blob;if(l===void 0)return Promise.reject(new Error(_l));if(r.signal?.aborted===true)return Promise.reject(new Error(Il));let i=new FormData;for(let[t,n]of Object.entries(e.upload_fields))i.append(t,n);return i.append(jl,l,"image"),t(e.upload_url,{method:"POST",body:i,mode:"cors",credentials:"omit",...r.signal?{signal:r.signal}:{}}).then(e=>{if(!(e.status>=200&&e.status<300))return Promise.reject(new Error(Il));r.onProgress?.(1)},()=>Promise.reject(new Error(Il)))}})}var El="booking attachment upload: the picked file could not be read";function Rl(e={}){let t=e.fetch??((e,t)=>fetch(e,t)),n=createWebAttachmentTransport({fetch:t});/* @__PURE__ */