@everfur/sdk 0.19.0 → 0.20.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 (178) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/{Chat.d-BHovj6Ku.d.ts → Chat.d-D61LLPJh.d.ts} +1 -1
  3. package/dist/{Chat.d-BO-XtVYe.d.cts → Chat.d-IpxKa9gS.d.cts} +1 -1
  4. package/dist/{DepthViews.d-DKoZgF8l.d.ts → DepthViews.d-C8EsR8Gq.d.ts} +1 -1
  5. package/dist/{DepthViews.d-BwIkdmWZ.d.cts → DepthViews.d-CDIL4mPa.d.cts} +1 -1
  6. package/dist/{DepthViews.d-Bx85LeiP.d.cts → DepthViews.d-Q1nqdH8n.d.cts} +1 -1
  7. package/dist/{DepthViews.d-CBUunxP1.d.ts → DepthViews.d-w2o4Nf7r.d.ts} +1 -1
  8. package/dist/{RecordsPage.d-DRFp2LXH.d.cts → RecordsPage.d-BSjZOHu8.d.cts} +11 -5
  9. package/dist/{RecordsPage.d-CsvBhU0f.d.ts → RecordsPage.d-DqhM_rCr.d.ts} +11 -5
  10. package/dist/animations/index.d.cts +3 -3
  11. package/dist/animations/index.d.ts +3 -3
  12. package/dist/{attachments.d-DWUsHPf9.d.cts → attachments.d-BviU_Tja.d.cts} +1 -1
  13. package/dist/{attachments.d-DOZjCdkb.d.ts → attachments.d-DZVfHHnY.d.ts} +1 -1
  14. package/dist/{bookingCopy.d-BlMWlvgv.d.ts → bookingCopy.d-5V3erfXD.d.ts} +2 -2
  15. package/dist/{bookingCopy.d-tvO7y6MK.d.cts → bookingCopy.d-DlzUPsFE.d.cts} +2 -2
  16. package/dist/{casesRepository.d-sSo6oakf.d.cts → casesRepository.d-7Us2O-z8.d.cts} +1 -1
  17. package/dist/{casesRepository.d-C7qbrOL-.d.ts → casesRepository.d-Dqg-KbpA.d.ts} +1 -1
  18. package/dist/chat/index.d.cts +10 -10
  19. package/dist/chat/index.d.ts +10 -10
  20. package/dist/chat/lite/index.d.cts +10 -10
  21. package/dist/chat/lite/index.d.ts +10 -10
  22. package/dist/{chatHandoffToken.d-D6GUoBvs.d.cts → chatHandoffToken.d-B9pjkEfl.d.cts} +5 -5
  23. package/dist/{chatHandoffToken.d-C4tEyuCT.d.ts → chatHandoffToken.d-TYcD8NIi.d.ts} +5 -5
  24. package/dist/{chatTypes.d-BI4vidgu.d.ts → chatTypes.d-DPALEQoW.d.ts} +4 -4
  25. package/dist/{chatTypes.d-CSyw9em_.d.cts → chatTypes.d-RnQ5R4zP.d.cts} +4 -4
  26. package/dist/client/index.cjs +1 -1
  27. package/dist/client/index.d.cts +6 -6
  28. package/dist/client/index.d.ts +6 -6
  29. package/dist/client/index.js +1 -1
  30. package/dist/{clinicBatch.d-BxA_uGBb.d.cts → clinicBatch.d-C6MzLj3X.d.cts} +3 -3
  31. package/dist/{clinicBatch.d-T5oSAhY-.d.ts → clinicBatch.d-t9hkown2.d.ts} +3 -3
  32. package/dist/{clinicRequestProps.d-CjsMg_OD.d.ts → clinicRequestProps.d-BuMuGoVZ.d.ts} +1 -1
  33. package/dist/{clinicRequestProps.d-1dCtouGA.d.cts → clinicRequestProps.d-DjzUdDFx.d.cts} +1 -1
  34. package/dist/{config.d-N5Xzy53V.d.ts → config.d-BnZkxI5a.d.ts} +1 -1
  35. package/dist/{config.d-jCmrhM4a.d.cts → config.d-DoC-XaJ0.d.cts} +1 -1
  36. package/dist/consent/index.cjs +1 -1
  37. package/dist/consent/index.d.cts +5 -5
  38. package/dist/consent/index.d.ts +5 -5
  39. package/dist/consent/index.js +1 -1
  40. package/dist/{context.d-l4HkFJI8.d.cts → context.d-BAh7C7T4.d.cts} +4 -4
  41. package/dist/{context.d-BJEpEERH.d.ts → context.d-z2zIjKEb.d.ts} +4 -4
  42. package/dist/{copy.d-hS49oJ4w.d.cts → copy.d-BkX6G-Ws.d.cts} +2 -2
  43. package/dist/{copy.d-hFRaovog.d.ts → copy.d-DLxgHsZZ.d.ts} +2 -2
  44. package/dist/core/index.cjs +1 -1
  45. package/dist/core/index.d.cts +14 -14
  46. package/dist/core/index.d.ts +14 -14
  47. package/dist/core/index.js +1 -1
  48. package/dist/{depth.d-BYwddMNU.d.cts → depth.d-aXddCjyh.d.cts} +3 -3
  49. package/dist/{depth.d-C99_xup2.d.ts → depth.d-z2FlzY3x.d.ts} +3 -3
  50. package/dist/{entitlementRepository.d-CiU_QIPL.d.cts → entitlementRepository.d-CDCF8eFx.d.cts} +2 -2
  51. package/dist/{entitlementRepository.d-qZAlET7C.d.ts → entitlementRepository.d-Cgmy4Opa.d.ts} +2 -2
  52. package/dist/{focus.d-CG6KhDBK.d.ts → focus.d-C2fd_5MW.d.ts} +2 -2
  53. package/dist/{focus.d-RJMXplJc.d.cts → focus.d-q_sXGhLn.d.cts} +2 -2
  54. package/dist/health-plan/index.d.cts +10 -10
  55. package/dist/health-plan/index.d.ts +10 -10
  56. package/dist/{idempotency.d-DJyOZDPb.d.cts → idempotency.d-Bqdyv_yn.d.cts} +1 -1
  57. package/dist/{idempotency.d-D-ZWpO9p.d.ts → idempotency.d-DlAPAxD5.d.ts} +1 -1
  58. package/dist/{identity.d-DIOnFzXL.d.ts → identity.d-BWZiaByn.d.ts} +1 -1
  59. package/dist/{identity.d-CA7mW59I.d.cts → identity.d-CooKscNj.d.cts} +1 -1
  60. package/dist/index.cjs +1 -1
  61. package/dist/index.d.cts +13 -13
  62. package/dist/index.d.ts +13 -13
  63. package/dist/index.js +1 -1
  64. package/dist/{introEvents.d-7wNDMhEF.d.cts → introEvents.d-C8bDDiK6.d.cts} +1 -1
  65. package/dist/{introEvents.d-BjqfFgE1.d.ts → introEvents.d-baVM016i.d.ts} +1 -1
  66. package/dist/{models.d-BSqvbTE1.d.cts → models.d-BN53M9sU.d.cts} +52 -1
  67. package/dist/{models.d-DOwnr8fi.d.ts → models.d-Bhq9p6Wa.d.ts} +52 -1
  68. package/dist/notifications/inbox/index.d.cts +4 -4
  69. package/dist/notifications/inbox/index.d.ts +4 -4
  70. package/dist/notifications/index.d.cts +7 -7
  71. package/dist/notifications/index.d.ts +7 -7
  72. package/dist/{optInView.d-B5v4cDDW.d.ts → optInView.d-C04aX0Hs.d.ts} +2 -2
  73. package/dist/{optInView.d-BQhHPleh.d.cts → optInView.d-D_D7fs6C.d.cts} +2 -2
  74. package/dist/{pets.d-DVrOb-Bj.d.ts → pets.d-CkFNO-x-.d.ts} +1 -1
  75. package/dist/{pets.d-DRqMaP8A.d.cts → pets.d-oJ2OIY22.d.cts} +1 -1
  76. package/dist/{petsRepository.d-CpYWRWFq.d.ts → petsRepository.d-CKCi6rtp.d.ts} +1 -1
  77. package/dist/{petsRepository.d-tZADfKA1.d.cts → petsRepository.d-VWMyIeIJ.d.cts} +1 -1
  78. package/dist/records/depth/index.cjs +1 -1
  79. package/dist/records/depth/index.d.cts +11 -11
  80. package/dist/records/depth/index.d.ts +11 -11
  81. package/dist/records/depth/index.js +1 -1
  82. package/dist/records/index.cjs +16 -14
  83. package/dist/records/index.d.cts +47 -17
  84. package/dist/records/index.d.ts +47 -17
  85. package/dist/records/index.js +16 -14
  86. package/dist/{requestFunnel.d-C4abgvt9.d.cts → requestFunnel.d-By0-I8Cp.d.cts} +2 -2
  87. package/dist/{requestFunnel.d-B8OVGh0p.d.ts → requestFunnel.d-DVCytzTE.d.ts} +2 -2
  88. package/dist/{route.d-BAZqGLfl.d.ts → route.d-Ay-lRct1.d.ts} +2 -2
  89. package/dist/{route.d-CTf8h9vS.d.cts → route.d-DQDX6QFn.d.cts} +2 -2
  90. package/dist/{runtimeTypes.d-DrIz5e6L.d.ts → runtimeTypes.d-C49Cgb9c.d.ts} +4 -4
  91. package/dist/{runtimeTypes.d-DbaQKGLv.d.cts → runtimeTypes.d-DUVNpR6g.d.cts} +4 -4
  92. package/dist/{screenProps.d-BP8LAZWn.d.ts → screenProps.d-B_arD3Lh.d.ts} +2 -2
  93. package/dist/{screenProps.d-Di3wYGCn.d.cts → screenProps.d-BgxlmfG5.d.cts} +2 -2
  94. package/dist/server/events/index.cjs +1 -1
  95. package/dist/server/events/index.d.cts +2 -2
  96. package/dist/server/events/index.d.ts +2 -2
  97. package/dist/server/events/index.js +1 -1
  98. package/dist/server/index.cjs +1 -1
  99. package/dist/server/index.d.cts +3 -3
  100. package/dist/server/index.d.ts +3 -3
  101. package/dist/server/index.js +1 -1
  102. package/dist/{sheetSeam.d-BBuEIVsa.d.cts → sheetSeam.d-B9iQqG_I.d.cts} +2 -2
  103. package/dist/{sheetSeam.d-B09jf4YC.d.ts → sheetSeam.d-CtuKILqp.d.ts} +2 -2
  104. package/dist/shop/index.d.cts +3 -3
  105. package/dist/shop/index.d.ts +3 -3
  106. package/dist/tabs/index.cjs +1 -1
  107. package/dist/tabs/index.d.cts +8 -8
  108. package/dist/tabs/index.d.ts +8 -8
  109. package/dist/tabs/index.js +1 -1
  110. package/dist/televet/booking/index.d.cts +6 -6
  111. package/dist/televet/booking/index.d.ts +6 -6
  112. package/dist/testing/index.cjs +1 -1
  113. package/dist/testing/index.d.cts +1 -1
  114. package/dist/testing/index.d.ts +1 -1
  115. package/dist/testing/index.js +1 -1
  116. package/dist/testing/rn/index.d.cts +8 -8
  117. package/dist/testing/rn/index.d.ts +8 -8
  118. package/dist/testing/web/index.d.cts +9 -9
  119. package/dist/testing/web/index.d.ts +9 -9
  120. package/dist/texting/index.d.cts +5 -5
  121. package/dist/texting/index.d.ts +5 -5
  122. package/dist/{threadOptions.d-Cwmyu8pc.d.ts → threadOptions.d-Cbhjjb9_.d.ts} +2 -2
  123. package/dist/{threadOptions.d-REwBuXAY.d.cts → threadOptions.d-pZXzsd2d.d.cts} +2 -2
  124. package/dist/{timelineRows.d-CTlGQTB0.d.ts → timelineRows.d-BHxMeZzl.d.ts} +1 -1
  125. package/dist/{timelineRows.d-CongJG58.d.cts → timelineRows.d-DlMs82N1.d.cts} +1 -1
  126. package/dist/{useHealthPlanSubscription.d-BSo5kFT9.d.ts → useHealthPlanSubscription.d-BoC7H85G.d.ts} +2 -2
  127. package/dist/{useHealthPlanSubscription.d-Br7GKHTt.d.cts → useHealthPlanSubscription.d-CZn06-lu.d.cts} +2 -2
  128. package/dist/{useInboxUnread.d-pi6FNnK-.d.cts → useInboxUnread.d-DW0dpWdv.d.cts} +1 -1
  129. package/dist/{useInboxUnread.d-Blxu00eY.d.ts → useInboxUnread.d-vYpOXVRv.d.ts} +1 -1
  130. package/dist/{usePresentation.d-yd9Gh4GB.d.ts → usePresentation.d-CgvwGb2A.d.ts} +2 -2
  131. package/dist/{usePresentation.d-C6ci1s3j.d.cts → usePresentation.d-CyCEJ6nj.d.cts} +2 -2
  132. package/dist/{useRecords.d-BYNX01El.d.cts → useRecords.d-BMSW4aRD.d.cts} +46 -3
  133. package/dist/{useRecords.d-DWk61a4c.d.ts → useRecords.d-Cv1nhZrv.d.ts} +46 -3
  134. package/dist/{useRecordsDepth.d-C5snbNxR.d.ts → useRecordsDepth.d-CbXhWbx7.d.ts} +1 -1
  135. package/dist/{useRecordsDepth.d-BIDVPfx7.d.cts → useRecordsDepth.d-CcbL98FD.d.cts} +1 -1
  136. package/dist/{useUnread.d-w0dKMnx7.d.ts → useUnread.d-BsZKbLp9.d.ts} +3 -3
  137. package/dist/{useUnread.d-CORommFJ.d.cts → useUnread.d-CfF2Cx-q.d.cts} +3 -3
  138. package/dist/{view.d-DUhKppyl.d.cts → view.d-CF3AP3T7.d.cts} +5 -5
  139. package/dist/{view.d-CK2UN4qn.d.ts → view.d-DdyOf0T0.d.ts} +5 -5
  140. package/dist/web/consent/index.cjs +1 -1
  141. package/dist/web/consent/index.d.cts +5 -5
  142. package/dist/web/consent/index.d.ts +5 -5
  143. package/dist/web/consent/index.js +1 -1
  144. package/dist/web/health-plan/index.d.cts +12 -12
  145. package/dist/web/health-plan/index.d.ts +12 -12
  146. package/dist/web/inbox/index.cjs +1 -1
  147. package/dist/web/inbox/index.d.cts +5 -5
  148. package/dist/web/inbox/index.d.ts +5 -5
  149. package/dist/web/inbox/index.js +1 -1
  150. package/dist/web/index.cjs +1 -1
  151. package/dist/web/index.d.cts +27 -27
  152. package/dist/web/index.d.ts +27 -27
  153. package/dist/web/index.js +1 -1
  154. package/dist/web/intro/index.cjs +1 -1
  155. package/dist/web/intro/index.d.cts +8 -8
  156. package/dist/web/intro/index.d.ts +8 -8
  157. package/dist/web/intro/index.js +1 -1
  158. package/dist/web/notifications/index.d.cts +6 -6
  159. package/dist/web/notifications/index.d.ts +6 -6
  160. package/dist/web/records/depth/index.cjs +1 -1
  161. package/dist/web/records/depth/index.d.cts +11 -11
  162. package/dist/web/records/depth/index.d.ts +11 -11
  163. package/dist/web/records/depth/index.js +1 -1
  164. package/dist/web/records/index.cjs +15 -13
  165. package/dist/web/records/index.d.cts +43 -19
  166. package/dist/web/records/index.d.ts +43 -19
  167. package/dist/web/records/index.js +15 -13
  168. package/dist/web/records-sheet/index.cjs +1 -1
  169. package/dist/web/records-sheet/index.d.cts +4 -4
  170. package/dist/web/records-sheet/index.d.ts +4 -4
  171. package/dist/web/records-sheet/index.js +1 -1
  172. package/dist/web/shop/index.d.cts +3 -3
  173. package/dist/web/shop/index.d.ts +3 -3
  174. package/dist/web/televet/booking/index.d.cts +6 -6
  175. package/dist/web/televet/booking/index.d.ts +6 -6
  176. package/dist/web/texting/index.d.cts +5 -5
  177. package/dist/web/texting/index.d.ts +5 -5
  178. package/package.json +1 -1
@@ -5,7 +5,7 @@ return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
5
5
  return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function errorFrame(fields){/* @__PURE__ */
6
6
  return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled2;try{settled2=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled2=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled2.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled2;let error=settled2.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
7
7
  /* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
8
- return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}var CONSENT_PATH="/widget/v1/consent",EVERFUR_CONSENT_SCOPES=/* @__PURE__ */Object.freeze(["transcript_exposure","partner_context"]),RECORDS_CONTENT_SCOPE="records_content",CONSENT_VERSION_MAX=64,SCOPES=new Set(EVERFUR_CONSENT_SCOPES);function isEverfurConsentScope(value){return typeof value=="string"&&SCOPES.has(value)}function invalid(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function validateScope(scope){return isEverfurConsentScope(scope)?null:invalid(scope===RECORDS_CONTENT_SCOPE?`'${RECORDS_CONTENT_SCOPE}' is not recorded here: the records release a member grants and revokes is PUT and DELETE /widget/v1/records/pets/{pet_ref}/consent, which the records surface wires and which also kills the pet's live share links on a revoke. A row on the scoped ledger would not gate any read.`:`scope must be one of ${EVERFUR_CONSENT_SCOPES.join(", ")}`)}function validateDecision(decision){if(typeof decision!="object"||decision===null)return invalid("write needs a decision object");let{scope:scope,granted:granted,consentVersion:consentVersion}=decision,badScope=validateScope(scope);return badScope!==null?badScope:typeof granted!="boolean"?invalid("granted must be true to grant or false to withdraw"):consentVersion!==void 0&&(typeof consentVersion!="string"||consentVersion.length===0||consentVersion.length>CONSENT_VERSION_MAX)?invalid(`consentVersion must be 1..${CONSENT_VERSION_MAX} characters`):null}var str=value=>typeof value=="string"&&value.length>0?value:null;function verdictFromWire(raw,scope){if(typeof raw!="object"||raw===null)return null;let o=raw;return typeof o.granted!="boolean"||typeof o.has_decision!="boolean"?null:/* @__PURE__ */Object.freeze({scope:scope,granted:o.granted,hasDecision:o.has_decision,consentVersion:str(o.consent_version),actor:str(o.actor),recordedAt:str(o.recorded_at)})}function malformed(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response carried no granted/has_decision pair`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function createConsentRepository(runtime){let over=()=>{let{services:services}=runtime.registry;return createConsentRepositoryOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})};return{read:(scope,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("read"))):over().read(scope,opts),write:(decision,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("write"))):over().write(decision,opts)}}function createConsentRepositoryOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),withSignal=(req,signal)=>signal?{...req,signal:signal}:req;return{async read(scope,opts){let bad=validateScope(scope);if(bad!==null)return err(bad);let res=await funnel.send("consent.read",withSignal({method:"GET",path:CONSENT_PATH,query:{scope:scope}},opts?.signal));if(!res.ok)return err(res.error);let verdict=verdictFromWire(res.value,scope);return verdict===null?err(malformed("consent.read")):ok(verdict)},async write(decision,opts){let bad=validateDecision(decision);if(bad!==null)return err(bad);let body={scope:decision.scope,granted:decision.granted};decision.consentVersion!==void 0&&(body.consent_version=decision.consentVersion);let res=await funnel.send("consent.write",withSignal({method:"PUT",path:CONSENT_PATH,body:body},opts?.signal));if(!res.ok)return err(res.error);let verdict=verdictFromWire(res.value,decision.scope);return verdict===null?err(malformed("consent.write")):ok(verdict)}}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function blank(scope,error){/* @__PURE__ */
8
+ return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}var CONSENT_PATH="/widget/v1/consent",EVERFUR_CONSENT_SCOPES=/* @__PURE__ */Object.freeze(["transcript_exposure","partner_context"]),RECORDS_CONTENT_SCOPE="records_content",CONSENT_VERSION_MAX=64,SCOPES=new Set(EVERFUR_CONSENT_SCOPES);function isEverfurConsentScope(value){return typeof value=="string"&&SCOPES.has(value)}function invalid(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function validateScope(scope){return isEverfurConsentScope(scope)?null:invalid(scope===RECORDS_CONTENT_SCOPE?`'${RECORDS_CONTENT_SCOPE}' is not recorded here: the records release a member grants and revokes is PUT and DELETE /widget/v1/records/consent (all pets) or /widget/v1/records/pets/{pet_ref}/consent (one pet), which the records surface wires and which also kills the pet's live share links on a revoke. A row on the scoped ledger would not gate any read.`:`scope must be one of ${EVERFUR_CONSENT_SCOPES.join(", ")}`)}function validateDecision(decision){if(typeof decision!="object"||decision===null)return invalid("write needs a decision object");let{scope:scope,granted:granted,consentVersion:consentVersion}=decision,badScope=validateScope(scope);return badScope!==null?badScope:typeof granted!="boolean"?invalid("granted must be true to grant or false to withdraw"):consentVersion!==void 0&&(typeof consentVersion!="string"||consentVersion.length===0||consentVersion.length>CONSENT_VERSION_MAX)?invalid(`consentVersion must be 1..${CONSENT_VERSION_MAX} characters`):null}var str=value=>typeof value=="string"&&value.length>0?value:null;function verdictFromWire(raw,scope){if(typeof raw!="object"||raw===null)return null;let o=raw;return typeof o.granted!="boolean"||typeof o.has_decision!="boolean"?null:/* @__PURE__ */Object.freeze({scope:scope,granted:o.granted,hasDecision:o.has_decision,consentVersion:str(o.consent_version),actor:str(o.actor),recordedAt:str(o.recorded_at)})}function malformed(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response carried no granted/has_decision pair`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function createConsentRepository(runtime){let over=()=>{let{services:services}=runtime.registry;return createConsentRepositoryOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})};return{read:(scope,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("read"))):over().read(scope,opts),write:(decision,opts)=>runtime.isDisposed?Promise.resolve(err(disposed("write"))):over().write(decision,opts)}}function createConsentRepositoryOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),withSignal=(req,signal)=>signal?{...req,signal:signal}:req;return{async read(scope,opts){let bad=validateScope(scope);if(bad!==null)return err(bad);let res=await funnel.send("consent.read",withSignal({method:"GET",path:CONSENT_PATH,query:{scope:scope}},opts?.signal));if(!res.ok)return err(res.error);let verdict=verdictFromWire(res.value,scope);return verdict===null?err(malformed("consent.read")):ok(verdict)},async write(decision,opts){let bad=validateDecision(decision);if(bad!==null)return err(bad);let body={scope:decision.scope,granted:decision.granted};decision.consentVersion!==void 0&&(body.consent_version=decision.consentVersion);let res=await funnel.send("consent.write",withSignal({method:"PUT",path:CONSENT_PATH,body:body},opts?.signal));if(!res.ok)return err(res.error);let verdict=verdictFromWire(res.value,decision.scope);return verdict===null?err(malformed("consent.write")):ok(verdict)}}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function blank(scope,error){/* @__PURE__ */
9
9
  return Object.freeze({scope:scope,granted:false,hasDecision:false,consentVersion:null,recordedAt:null,loaded:false,saving:false,error:error})}function settled(verdict){/* @__PURE__ */
10
10
  return Object.freeze({scope:verdict.scope,granted:verdict.granted,hasDecision:verdict.hasDecision,consentVersion:verdict.consentVersion,recordedAt:verdict.recordedAt,loaded:true,saving:false,error:null})}function noMember(){return makeEverfurError("sessionRequired",{retryable:false,wireMessage:"a consent decision is authored by the member; sign a user in on the provider first"})}function useEverfurConsentRepository(){let{runtime:runtime}=useEverfurContext();return useMemo(()=>createConsentRepository(runtime),[runtime])}function useEverfurConsent(options){let{userRef:userRef}=useEverfurContext(),repository=useEverfurConsentRepository(),requestedKey=(options?.scopes??[]).filter(isEverfurConsentScope).join(","),requested=useMemo(()=>{let named=requestedKey.length===0?[]:requestedKey.split(",");return named.length===0?EVERFUR_CONSENT_SCOPES:/* @__PURE__ */Object.freeze(named)},[requestedKey]),[status,setStatus]=useState(userRef===null?"signed_out":"loading"),[scopes,setScopes]=useState([]),[error,setError]=useState(null),generation=useRef(0),readAll=useCallback(async()=>{if(userRef===null){generation.current+=1,setStatus("signed_out"),setScopes([]),setError(null);return}let gen=generation.current+=1;setStatus("loading"),setError(null);let results=await Promise.all(requested.map(scope=>repository.read(scope)));if(gen!==generation.current)return;let next=results.map((result,index)=>{let scope=requested[index];return result.ok?settled(result.value):blank(scope,result.error)}),firstFailure=results.find(result=>!result.ok),everyFailed=results.every(result=>!result.ok);setScopes(/* @__PURE__ */Object.freeze(next)),setStatus(everyFailed?"failed":"ready"),setError(everyFailed&&firstFailure!==void 0&&!firstFailure.ok?firstFailure.error:null)},[repository,requested,userRef]);useEffect(()=>{readAll()},[readAll]);let setConsent=useCallback(async(scope,granted)=>{if(userRef===null)return err(noMember());let gen=generation.current,previous=null;setScopes(current=>{let index=current.findIndex(entry=>entry.scope===scope),before=index===-1?blank(scope,null):current[index];previous=before;let optimistic=/* @__PURE__ */Object.freeze({...before,granted:granted,hasDecision:true,saving:true,error:null});if(index===-1)/* @__PURE__ */return Object.freeze([...current,optimistic]);let next=[...current];return next[index]=optimistic,/* @__PURE__ */Object.freeze(next)});let result=await repository.write({scope:scope,granted:granted});return gen!==generation.current||setScopes(current=>{let index=current.findIndex(entry=>entry.scope===scope);if(index===-1)return current;let next=[...current];return next[index]=result.ok?settled(result.value):/* @__PURE__ */Object.freeze({...previous??blank(scope,null),saving:false,error:result.error}),/* @__PURE__ */Object.freeze(next)}),result},[repository,userRef]);return useMemo(()=>({status:status,scopes:scopes,error:error,setConsent:setConsent,refresh:readAll}),[status,scopes,error,setConsent,readAll])}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"};deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function EverfurConsentToggle(props){let{scope:scope,onChange:onChange,renderNotice:renderNotice,style:style,className:className}=guardHostProps(props,["onChange"]),theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]),consent=useEverfurConsent({scopes:[scope]}),view=consentRowView(consent,scope),copy=CONSENT_SCOPE_COPY[scope],[attempt,setAttempt]=useState(null),decide=useCallback(async granted=>{setAttempt(granted);let result=await consent.setConsent(scope,granted);result.ok&&(setAttempt(null),onChange?.(result.value.granted))},[consent,onChange,scope]),notice=(error,onRetry)=>/* @__PURE__ */jsxs("div",{style:styles.notice,children:[
11
11
  /* @__PURE__ */jsx(HostRender,{resetKey:error,render:()=>renderNotice?renderNotice(error):/* @__PURE__ */jsx("p",{style:styles.noticeText,children:error.displayMessage}),fallback:/* @__PURE__ */jsx("p",{style:styles.noticeText,children:error.displayMessage})}),
@@ -1,17 +1,17 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
- import { H as HealthPlanFocusProps, d as EverfurChatTopCard } from '../../threadOptions.d-REwBuXAY.cjs';
3
- export { j as EverfurHealthPlan, f as EverfurHealthPlanProps, k as HealthPlanCheckoutLine, l as HealthPlanFocusLayer, m as HealthPlanFocusOptions, n as HealthPlanFocusOverlay, o as HealthPlanFocusOverlayControls, p as HealthPlanProductPageOptions, q as HealthPlanTodayOptions } from '../../threadOptions.d-REwBuXAY.cjs';
2
+ import { H as HealthPlanFocusProps, d as EverfurChatTopCard } from '../../threadOptions.d-pZXzsd2d.cjs';
3
+ export { j as EverfurHealthPlan, f as EverfurHealthPlanProps, k as HealthPlanCheckoutLine, l as HealthPlanFocusLayer, m as HealthPlanFocusOptions, n as HealthPlanFocusOverlay, o as HealthPlanFocusOverlayControls, p as HealthPlanProductPageOptions, q as HealthPlanTodayOptions } from '../../threadOptions.d-pZXzsd2d.cjs';
4
4
  import { ReactNode, CSSProperties, Ref } from 'react';
5
5
  import { E as EverfurError } from '../../EverfurError.d-8NHtlgzA.cjs';
6
6
  export { a as EverfurErrorCategory, b as EverfurErrorCode } from '../../EverfurError.d-8NHtlgzA.cjs';
7
- import { b as HealthPlanItem, u as HealthPlanTodayIcon, d as HealthPlanFocusCopy, f as HealthPlanFocusIcon, e as HealthPlanFocusClassNames, v as HealthPlanFocusPart, t as HealthPlanPagePet, H as HealthPlanPage } from '../../focus.d-RJMXplJc.cjs';
8
- export { w as HEALTH_PLAN_FOCUS_COPY, x as HEALTH_PLAN_REASON_KINDS, p as HealthPlan, y as HealthPlanCartCheckoutRequest, z as HealthPlanCheckoutItem, l as HealthPlanCheckoutProvider, A as HealthPlanCheckoutRefusal, B as HealthPlanCheckoutRequest, C as HealthPlanCheckoutSession, D as HealthPlanCheckoutState, E as HealthPlanCheckoutStatus, c as HealthPlanFocusDesign, n as HealthPlanFocusExtra, F as HealthPlanFocusLearnCard, m as HealthPlanFocusPrices, G as HealthPlanFocusReasonRow, I as HealthPlanFocusReport, J as HealthPlanFocusReview, K as HealthPlanFocusSign, L as HealthPlanFocusStep, o as HealthPlanFocusWait, M as HealthPlanItemDetail, N as HealthPlanItemDose, O as HealthPlanItemReview, P as HealthPlanOneBoxOffer, h as HealthPlanOneBoxOrder, Q as HealthPlanOneBoxOrderPage, R as HealthPlanOneBoxOrderPageOptions, S as HealthPlanOrderStatus, T as HealthPlanOrderTracking, U as HealthPlanOrderTrackingStatus, j as HealthPlanPageRepository, a as HealthPlanPetWords, V as HealthPlanPurchase, W as HealthPlanReason, s as HealthPlanReasonKind, q as HealthPlanRepository, X as HealthPlanRepositoryDeps, Y as HealthPlanRuntime, k as HealthPlanShopOrder, g as HealthPlanSubscription, r as HealthPlanSubscriptionQuote, Z as HealthPlanSubscriptionRenewal, i as HealthPlanSubscriptionRepository, _ as HealthPlanSubscriptionStatus, $ as HealthPlanSubscriptionStep, a0 as HealthPlanSubscriptionSupply, a1 as HealthPlanTrackStep, a2 as createHealthPlanPageRepository, a3 as createHealthPlanPageRepositoryOver, a4 as createHealthPlanRepository, a5 as createHealthPlanRepositoryOver, a6 as createHealthPlanSubscriptionRepository, a7 as createHealthPlanSubscriptionRepositoryOver, a8 as formatHealthPlanDay, a9 as healthPlanCheckoutRefusal, aa as healthPlanCheckoutSessionFromWire, ab as healthPlanCheckoutStateFromWire, ac as healthPlanFocusCopyFor, ad as healthPlanFocusDesignFromWire, ae as healthPlanFromWire, af as healthPlanOneBoxOrderFromWire, ag as healthPlanOneBoxOrderPageFromWire, ah as healthPlanOrderTrackingFromWire, ai as healthPlanPageFromWire, aj as healthPlanPetWords, ak as healthPlanSubscriptionFromWire, al as healthPlanSubscriptionQuoteFromWire, am as isHealthPlanSubscriptionUnavailable } from '../../focus.d-RJMXplJc.cjs';
9
- import { f as HealthPlanCardOptions, g as HealthPlanImageVariant, h as HealthPlanReasonVariant, a as HealthPlanPriceFormat, d as HealthPlanCart$1, i as HealthPlanTopCardCopy, e as HealthPlanTopCardResults } from '../../usePresentation.d-C6ci1s3j.cjs';
10
- export { E as EverfurHealthPlanOptions, j as EverfurHealthPlanState, k as EverfurHealthPlanStatus, l as HEALTH_PLAN_COPY, m as HEALTH_PLAN_COPY_PLACEHOLDERS, n as HEALTH_PLAN_LAYOUT_DEFAULTS, o as HEALTH_PLAN_REASON_LABELS, p as HEALTH_PLAN_TEMPLATES, q as HEALTH_PLAN_TOP_CARD_COPY, r as HealthPlanAddButtonSize, s as HealthPlanAddedVariant, H as HealthPlanBlanksFacts, t as HealthPlanBlanksPhase, v as HealthPlanCardShadow, w as HealthPlanCartBarPlacement, x as HealthPlanCartBarVisibility, y as HealthPlanCategoryVariant, c as HealthPlanEmptyCopy, z as HealthPlanFontWeight, A as HealthPlanHeaderContext, b as HealthPlanLayoutProps, B as HealthPlanPageContext, C as HealthPlanShadow, D as HealthPlanTopCardFocus, F as HealthPlanTopCardPet, G as formatHealthPlanPrice, I as formatHealthPlanPriceWith, J as healthPlanBlanksFacts, K as healthPlanCart, L as healthPlanNextShotsAt, M as healthPlanRecordsWeightKg, N as isHealthPlanSessionRequired, O as showHealthPlanCartBar, P as useEverfurHealthPlan, Q as useEverfurHealthPlanRepository, u as useEverfurPresentation } from '../../usePresentation.d-C6ci1s3j.cjs';
11
- import { H as HealthPlanAskRowData, a as HealthPlanBylineData, b as HealthPlanCheckupData, c as HealthPlanExtrasData, d as HealthPlanFineData, e as HealthPlanFocusCardData, f as HealthPlanHeaderData, g as HealthPlanJumpStripData, h as HealthPlanNoPickData, i as HealthPlanOtherItemsData, j as HealthPlanSignsData, k as HealthPlanTipsData, l as HealthPlanToastData, m as HealthPlanToolbarData, n as HealthPlanVetQuoteData, o as HealthPlanWaitCardData, p as HealthPlanBuyButtonData, q as HealthPlanBuyOptionsData, r as HealthPlanDoseCardData, s as HealthPlanIngredientsData, t as HealthPlanProductPickData, u as HealthPlanProofData, v as HealthPlanReviewsData, w as HealthPlanSubscribedBoxData, x as HealthPlanTrustRowData, y as HealthPlanWhyItFitsData, z as HealthPlanCartCheckoutData, A as HealthPlanCheckoutSheetData, B as HealthPlanManageSheetData, C as HealthPlanWeightSheetData, D as HealthPlanCartScreenData, E as HealthPlanOrderData, F as HealthPlanOrdersData, G as HealthPlanPlacedData, I as HealthPlanStartedData } from '../../useHealthPlanSubscription.d-Br7GKHTt.cjs';
12
- export { J as HealthPlanBuyMode, K as HealthPlanCartDock, L as HealthPlanCartHandlers, M as HealthPlanCartScope, N as HealthPlanCartScopeProps, O as HealthPlanController, P as HealthPlanExtraRow, Q as HealthPlanFactRow, R as HealthPlanFocusContent, S as HealthPlanIconLabel, T as HealthPlanNextRow, U as HealthPlanNoVetListener, V as HealthPlanOtherItemRow, W as HealthPlanPageOptions, X as HealthPlanPagePhase, Y as HealthPlanPageState, Z as HealthPlanPhase, _ as HealthPlanRecordsLandedListener, $ as HealthPlanRecordsLandedSource, a0 as HealthPlanShopLineView, a1 as HealthPlanShopOrderView, a2 as HealthPlanSnapshot, a3 as HealthPlanSubscriptionOptions, a4 as HealthPlanSubscriptionPhase, a5 as HealthPlanSubscriptionState, a6 as HealthPlanVet, a7 as healthPlanNoVet, a8 as notifyHealthPlanRecordsLanded, a9 as onHealthPlanNoVet, aa as onHealthPlanRecordsLanded, ab as setHealthPlanNoVet, ac as useHealthPlanCartDock, ad as useHealthPlanPage, ae as useHealthPlanPageRepository, af as useHealthPlanSubscription, ag as useHealthPlanSubscriptionRepository } from '../../useHealthPlanSubscription.d-Br7GKHTt.cjs';
13
- export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-CA7mW59I.cjs';
14
- export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config.d-jCmrhM4a.cjs';
7
+ import { b as HealthPlanItem, u as HealthPlanTodayIcon, d as HealthPlanFocusCopy, f as HealthPlanFocusIcon, e as HealthPlanFocusClassNames, v as HealthPlanFocusPart, t as HealthPlanPagePet, H as HealthPlanPage } from '../../focus.d-q_sXGhLn.cjs';
8
+ export { w as HEALTH_PLAN_FOCUS_COPY, x as HEALTH_PLAN_REASON_KINDS, p as HealthPlan, y as HealthPlanCartCheckoutRequest, z as HealthPlanCheckoutItem, l as HealthPlanCheckoutProvider, A as HealthPlanCheckoutRefusal, B as HealthPlanCheckoutRequest, C as HealthPlanCheckoutSession, D as HealthPlanCheckoutState, E as HealthPlanCheckoutStatus, c as HealthPlanFocusDesign, n as HealthPlanFocusExtra, F as HealthPlanFocusLearnCard, m as HealthPlanFocusPrices, G as HealthPlanFocusReasonRow, I as HealthPlanFocusReport, J as HealthPlanFocusReview, K as HealthPlanFocusSign, L as HealthPlanFocusStep, o as HealthPlanFocusWait, M as HealthPlanItemDetail, N as HealthPlanItemDose, O as HealthPlanItemReview, P as HealthPlanOneBoxOffer, h as HealthPlanOneBoxOrder, Q as HealthPlanOneBoxOrderPage, R as HealthPlanOneBoxOrderPageOptions, S as HealthPlanOrderStatus, T as HealthPlanOrderTracking, U as HealthPlanOrderTrackingStatus, j as HealthPlanPageRepository, a as HealthPlanPetWords, V as HealthPlanPurchase, W as HealthPlanReason, s as HealthPlanReasonKind, q as HealthPlanRepository, X as HealthPlanRepositoryDeps, Y as HealthPlanRuntime, k as HealthPlanShopOrder, g as HealthPlanSubscription, r as HealthPlanSubscriptionQuote, Z as HealthPlanSubscriptionRenewal, i as HealthPlanSubscriptionRepository, _ as HealthPlanSubscriptionStatus, $ as HealthPlanSubscriptionStep, a0 as HealthPlanSubscriptionSupply, a1 as HealthPlanTrackStep, a2 as createHealthPlanPageRepository, a3 as createHealthPlanPageRepositoryOver, a4 as createHealthPlanRepository, a5 as createHealthPlanRepositoryOver, a6 as createHealthPlanSubscriptionRepository, a7 as createHealthPlanSubscriptionRepositoryOver, a8 as formatHealthPlanDay, a9 as healthPlanCheckoutRefusal, aa as healthPlanCheckoutSessionFromWire, ab as healthPlanCheckoutStateFromWire, ac as healthPlanFocusCopyFor, ad as healthPlanFocusDesignFromWire, ae as healthPlanFromWire, af as healthPlanOneBoxOrderFromWire, ag as healthPlanOneBoxOrderPageFromWire, ah as healthPlanOrderTrackingFromWire, ai as healthPlanPageFromWire, aj as healthPlanPetWords, ak as healthPlanSubscriptionFromWire, al as healthPlanSubscriptionQuoteFromWire, am as isHealthPlanSubscriptionUnavailable } from '../../focus.d-q_sXGhLn.cjs';
9
+ import { f as HealthPlanCardOptions, g as HealthPlanImageVariant, h as HealthPlanReasonVariant, a as HealthPlanPriceFormat, d as HealthPlanCart$1, i as HealthPlanTopCardCopy, e as HealthPlanTopCardResults } from '../../usePresentation.d-CyCEJ6nj.cjs';
10
+ export { E as EverfurHealthPlanOptions, j as EverfurHealthPlanState, k as EverfurHealthPlanStatus, l as HEALTH_PLAN_COPY, m as HEALTH_PLAN_COPY_PLACEHOLDERS, n as HEALTH_PLAN_LAYOUT_DEFAULTS, o as HEALTH_PLAN_REASON_LABELS, p as HEALTH_PLAN_TEMPLATES, q as HEALTH_PLAN_TOP_CARD_COPY, r as HealthPlanAddButtonSize, s as HealthPlanAddedVariant, H as HealthPlanBlanksFacts, t as HealthPlanBlanksPhase, v as HealthPlanCardShadow, w as HealthPlanCartBarPlacement, x as HealthPlanCartBarVisibility, y as HealthPlanCategoryVariant, c as HealthPlanEmptyCopy, z as HealthPlanFontWeight, A as HealthPlanHeaderContext, b as HealthPlanLayoutProps, B as HealthPlanPageContext, C as HealthPlanShadow, D as HealthPlanTopCardFocus, F as HealthPlanTopCardPet, G as formatHealthPlanPrice, I as formatHealthPlanPriceWith, J as healthPlanBlanksFacts, K as healthPlanCart, L as healthPlanNextShotsAt, M as healthPlanRecordsWeightKg, N as isHealthPlanSessionRequired, O as showHealthPlanCartBar, P as useEverfurHealthPlan, Q as useEverfurHealthPlanRepository, u as useEverfurPresentation } from '../../usePresentation.d-CyCEJ6nj.cjs';
11
+ import { H as HealthPlanAskRowData, a as HealthPlanBylineData, b as HealthPlanCheckupData, c as HealthPlanExtrasData, d as HealthPlanFineData, e as HealthPlanFocusCardData, f as HealthPlanHeaderData, g as HealthPlanJumpStripData, h as HealthPlanNoPickData, i as HealthPlanOtherItemsData, j as HealthPlanSignsData, k as HealthPlanTipsData, l as HealthPlanToastData, m as HealthPlanToolbarData, n as HealthPlanVetQuoteData, o as HealthPlanWaitCardData, p as HealthPlanBuyButtonData, q as HealthPlanBuyOptionsData, r as HealthPlanDoseCardData, s as HealthPlanIngredientsData, t as HealthPlanProductPickData, u as HealthPlanProofData, v as HealthPlanReviewsData, w as HealthPlanSubscribedBoxData, x as HealthPlanTrustRowData, y as HealthPlanWhyItFitsData, z as HealthPlanCartCheckoutData, A as HealthPlanCheckoutSheetData, B as HealthPlanManageSheetData, C as HealthPlanWeightSheetData, D as HealthPlanCartScreenData, E as HealthPlanOrderData, F as HealthPlanOrdersData, G as HealthPlanPlacedData, I as HealthPlanStartedData } from '../../useHealthPlanSubscription.d-CZn06-lu.cjs';
12
+ export { J as HealthPlanBuyMode, K as HealthPlanCartDock, L as HealthPlanCartHandlers, M as HealthPlanCartScope, N as HealthPlanCartScopeProps, O as HealthPlanController, P as HealthPlanExtraRow, Q as HealthPlanFactRow, R as HealthPlanFocusContent, S as HealthPlanIconLabel, T as HealthPlanNextRow, U as HealthPlanNoVetListener, V as HealthPlanOtherItemRow, W as HealthPlanPageOptions, X as HealthPlanPagePhase, Y as HealthPlanPageState, Z as HealthPlanPhase, _ as HealthPlanRecordsLandedListener, $ as HealthPlanRecordsLandedSource, a0 as HealthPlanShopLineView, a1 as HealthPlanShopOrderView, a2 as HealthPlanSnapshot, a3 as HealthPlanSubscriptionOptions, a4 as HealthPlanSubscriptionPhase, a5 as HealthPlanSubscriptionState, a6 as HealthPlanVet, a7 as healthPlanNoVet, a8 as notifyHealthPlanRecordsLanded, a9 as onHealthPlanNoVet, aa as onHealthPlanRecordsLanded, ab as setHealthPlanNoVet, ac as useHealthPlanCartDock, ad as useHealthPlanPage, ae as useHealthPlanPageRepository, af as useHealthPlanSubscription, ag as useHealthPlanSubscriptionRepository } from '../../useHealthPlanSubscription.d-CZn06-lu.cjs';
13
+ export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-CooKscNj.cjs';
14
+ export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config.d-DoC-XaJ0.cjs';
15
15
  import { P as PetRef } from '../../ids.d-B2GAAifq.cjs';
16
16
  export { B as Brand, C as ConversationId, R as RecordsRequestId, U as UserRef, _ as __brand } from '../../ids.d-B2GAAifq.cjs';
17
17
  export { E as EverfurResult } from '../../EverfurResult.d-BFH-3s6E.cjs';
@@ -20,8 +20,8 @@ export { L as LifecyclePort } from '../../LifecyclePort.d-Cr1p33a7.cjs';
20
20
  export { E as EverfurChatAnswerStyle, a as EverfurChatComposerPlaceholder, b as EverfurChatComposerStyle, c as EverfurChatHistoryBarSetting, d as EverfurChatHistoryStyle, e as EverfurChatSendButtonSetting, f as EverfurChatTopCardSetting, g as EverfurHealthPlanLayout, h as EverfurPresentation, i as EverfurPresentationInput, j as EverfurSafetyDisclaimerPlacement } from '../../presentation.d-Bs8xQ4gD.cjs';
21
21
  export { c as EverfurChatTopCardRow } from '../../threadOptions.d-CW51PyVd.cjs';
22
22
  import '../../resolve.d-BTC3b6FW.cjs';
23
- import '../../requestFunnel.d-C4abgvt9.cjs';
24
- import '../../models.d-BSqvbTE1.cjs';
23
+ import '../../requestFunnel.d-By0-I8Cp.cjs';
24
+ import '../../models.d-BN53M9sU.cjs';
25
25
 
26
26
  /**
27
27
  * The focus layout over one plan item. `EverfurHealthPlan` mounts it; a partner can mount it over the hook too. It is
@@ -1,17 +1,17 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
- import { H as HealthPlanFocusProps, d as EverfurChatTopCard } from '../../threadOptions.d-Cwmyu8pc.js';
3
- export { j as EverfurHealthPlan, f as EverfurHealthPlanProps, k as HealthPlanCheckoutLine, l as HealthPlanFocusLayer, m as HealthPlanFocusOptions, n as HealthPlanFocusOverlay, o as HealthPlanFocusOverlayControls, p as HealthPlanProductPageOptions, q as HealthPlanTodayOptions } from '../../threadOptions.d-Cwmyu8pc.js';
2
+ import { H as HealthPlanFocusProps, d as EverfurChatTopCard } from '../../threadOptions.d-Cbhjjb9_.js';
3
+ export { j as EverfurHealthPlan, f as EverfurHealthPlanProps, k as HealthPlanCheckoutLine, l as HealthPlanFocusLayer, m as HealthPlanFocusOptions, n as HealthPlanFocusOverlay, o as HealthPlanFocusOverlayControls, p as HealthPlanProductPageOptions, q as HealthPlanTodayOptions } from '../../threadOptions.d-Cbhjjb9_.js';
4
4
  import { ReactNode, CSSProperties, Ref } from 'react';
5
5
  import { E as EverfurError } from '../../EverfurError.d-8NHtlgzA.js';
6
6
  export { a as EverfurErrorCategory, b as EverfurErrorCode } from '../../EverfurError.d-8NHtlgzA.js';
7
- import { b as HealthPlanItem, u as HealthPlanTodayIcon, d as HealthPlanFocusCopy, f as HealthPlanFocusIcon, e as HealthPlanFocusClassNames, v as HealthPlanFocusPart, t as HealthPlanPagePet, H as HealthPlanPage } from '../../focus.d-CG6KhDBK.js';
8
- export { w as HEALTH_PLAN_FOCUS_COPY, x as HEALTH_PLAN_REASON_KINDS, p as HealthPlan, y as HealthPlanCartCheckoutRequest, z as HealthPlanCheckoutItem, l as HealthPlanCheckoutProvider, A as HealthPlanCheckoutRefusal, B as HealthPlanCheckoutRequest, C as HealthPlanCheckoutSession, D as HealthPlanCheckoutState, E as HealthPlanCheckoutStatus, c as HealthPlanFocusDesign, n as HealthPlanFocusExtra, F as HealthPlanFocusLearnCard, m as HealthPlanFocusPrices, G as HealthPlanFocusReasonRow, I as HealthPlanFocusReport, J as HealthPlanFocusReview, K as HealthPlanFocusSign, L as HealthPlanFocusStep, o as HealthPlanFocusWait, M as HealthPlanItemDetail, N as HealthPlanItemDose, O as HealthPlanItemReview, P as HealthPlanOneBoxOffer, h as HealthPlanOneBoxOrder, Q as HealthPlanOneBoxOrderPage, R as HealthPlanOneBoxOrderPageOptions, S as HealthPlanOrderStatus, T as HealthPlanOrderTracking, U as HealthPlanOrderTrackingStatus, j as HealthPlanPageRepository, a as HealthPlanPetWords, V as HealthPlanPurchase, W as HealthPlanReason, s as HealthPlanReasonKind, q as HealthPlanRepository, X as HealthPlanRepositoryDeps, Y as HealthPlanRuntime, k as HealthPlanShopOrder, g as HealthPlanSubscription, r as HealthPlanSubscriptionQuote, Z as HealthPlanSubscriptionRenewal, i as HealthPlanSubscriptionRepository, _ as HealthPlanSubscriptionStatus, $ as HealthPlanSubscriptionStep, a0 as HealthPlanSubscriptionSupply, a1 as HealthPlanTrackStep, a2 as createHealthPlanPageRepository, a3 as createHealthPlanPageRepositoryOver, a4 as createHealthPlanRepository, a5 as createHealthPlanRepositoryOver, a6 as createHealthPlanSubscriptionRepository, a7 as createHealthPlanSubscriptionRepositoryOver, a8 as formatHealthPlanDay, a9 as healthPlanCheckoutRefusal, aa as healthPlanCheckoutSessionFromWire, ab as healthPlanCheckoutStateFromWire, ac as healthPlanFocusCopyFor, ad as healthPlanFocusDesignFromWire, ae as healthPlanFromWire, af as healthPlanOneBoxOrderFromWire, ag as healthPlanOneBoxOrderPageFromWire, ah as healthPlanOrderTrackingFromWire, ai as healthPlanPageFromWire, aj as healthPlanPetWords, ak as healthPlanSubscriptionFromWire, al as healthPlanSubscriptionQuoteFromWire, am as isHealthPlanSubscriptionUnavailable } from '../../focus.d-CG6KhDBK.js';
9
- import { f as HealthPlanCardOptions, g as HealthPlanImageVariant, h as HealthPlanReasonVariant, a as HealthPlanPriceFormat, d as HealthPlanCart$1, i as HealthPlanTopCardCopy, e as HealthPlanTopCardResults } from '../../usePresentation.d-yd9Gh4GB.js';
10
- export { E as EverfurHealthPlanOptions, j as EverfurHealthPlanState, k as EverfurHealthPlanStatus, l as HEALTH_PLAN_COPY, m as HEALTH_PLAN_COPY_PLACEHOLDERS, n as HEALTH_PLAN_LAYOUT_DEFAULTS, o as HEALTH_PLAN_REASON_LABELS, p as HEALTH_PLAN_TEMPLATES, q as HEALTH_PLAN_TOP_CARD_COPY, r as HealthPlanAddButtonSize, s as HealthPlanAddedVariant, H as HealthPlanBlanksFacts, t as HealthPlanBlanksPhase, v as HealthPlanCardShadow, w as HealthPlanCartBarPlacement, x as HealthPlanCartBarVisibility, y as HealthPlanCategoryVariant, c as HealthPlanEmptyCopy, z as HealthPlanFontWeight, A as HealthPlanHeaderContext, b as HealthPlanLayoutProps, B as HealthPlanPageContext, C as HealthPlanShadow, D as HealthPlanTopCardFocus, F as HealthPlanTopCardPet, G as formatHealthPlanPrice, I as formatHealthPlanPriceWith, J as healthPlanBlanksFacts, K as healthPlanCart, L as healthPlanNextShotsAt, M as healthPlanRecordsWeightKg, N as isHealthPlanSessionRequired, O as showHealthPlanCartBar, P as useEverfurHealthPlan, Q as useEverfurHealthPlanRepository, u as useEverfurPresentation } from '../../usePresentation.d-yd9Gh4GB.js';
11
- import { H as HealthPlanAskRowData, a as HealthPlanBylineData, b as HealthPlanCheckupData, c as HealthPlanExtrasData, d as HealthPlanFineData, e as HealthPlanFocusCardData, f as HealthPlanHeaderData, g as HealthPlanJumpStripData, h as HealthPlanNoPickData, i as HealthPlanOtherItemsData, j as HealthPlanSignsData, k as HealthPlanTipsData, l as HealthPlanToastData, m as HealthPlanToolbarData, n as HealthPlanVetQuoteData, o as HealthPlanWaitCardData, p as HealthPlanBuyButtonData, q as HealthPlanBuyOptionsData, r as HealthPlanDoseCardData, s as HealthPlanIngredientsData, t as HealthPlanProductPickData, u as HealthPlanProofData, v as HealthPlanReviewsData, w as HealthPlanSubscribedBoxData, x as HealthPlanTrustRowData, y as HealthPlanWhyItFitsData, z as HealthPlanCartCheckoutData, A as HealthPlanCheckoutSheetData, B as HealthPlanManageSheetData, C as HealthPlanWeightSheetData, D as HealthPlanCartScreenData, E as HealthPlanOrderData, F as HealthPlanOrdersData, G as HealthPlanPlacedData, I as HealthPlanStartedData } from '../../useHealthPlanSubscription.d-BSo5kFT9.js';
12
- export { J as HealthPlanBuyMode, K as HealthPlanCartDock, L as HealthPlanCartHandlers, M as HealthPlanCartScope, N as HealthPlanCartScopeProps, O as HealthPlanController, P as HealthPlanExtraRow, Q as HealthPlanFactRow, R as HealthPlanFocusContent, S as HealthPlanIconLabel, T as HealthPlanNextRow, U as HealthPlanNoVetListener, V as HealthPlanOtherItemRow, W as HealthPlanPageOptions, X as HealthPlanPagePhase, Y as HealthPlanPageState, Z as HealthPlanPhase, _ as HealthPlanRecordsLandedListener, $ as HealthPlanRecordsLandedSource, a0 as HealthPlanShopLineView, a1 as HealthPlanShopOrderView, a2 as HealthPlanSnapshot, a3 as HealthPlanSubscriptionOptions, a4 as HealthPlanSubscriptionPhase, a5 as HealthPlanSubscriptionState, a6 as HealthPlanVet, a7 as healthPlanNoVet, a8 as notifyHealthPlanRecordsLanded, a9 as onHealthPlanNoVet, aa as onHealthPlanRecordsLanded, ab as setHealthPlanNoVet, ac as useHealthPlanCartDock, ad as useHealthPlanPage, ae as useHealthPlanPageRepository, af as useHealthPlanSubscription, ag as useHealthPlanSubscriptionRepository } from '../../useHealthPlanSubscription.d-BSo5kFT9.js';
13
- export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-DIOnFzXL.js';
14
- export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config.d-N5Xzy53V.js';
7
+ import { b as HealthPlanItem, u as HealthPlanTodayIcon, d as HealthPlanFocusCopy, f as HealthPlanFocusIcon, e as HealthPlanFocusClassNames, v as HealthPlanFocusPart, t as HealthPlanPagePet, H as HealthPlanPage } from '../../focus.d-C2fd_5MW.js';
8
+ export { w as HEALTH_PLAN_FOCUS_COPY, x as HEALTH_PLAN_REASON_KINDS, p as HealthPlan, y as HealthPlanCartCheckoutRequest, z as HealthPlanCheckoutItem, l as HealthPlanCheckoutProvider, A as HealthPlanCheckoutRefusal, B as HealthPlanCheckoutRequest, C as HealthPlanCheckoutSession, D as HealthPlanCheckoutState, E as HealthPlanCheckoutStatus, c as HealthPlanFocusDesign, n as HealthPlanFocusExtra, F as HealthPlanFocusLearnCard, m as HealthPlanFocusPrices, G as HealthPlanFocusReasonRow, I as HealthPlanFocusReport, J as HealthPlanFocusReview, K as HealthPlanFocusSign, L as HealthPlanFocusStep, o as HealthPlanFocusWait, M as HealthPlanItemDetail, N as HealthPlanItemDose, O as HealthPlanItemReview, P as HealthPlanOneBoxOffer, h as HealthPlanOneBoxOrder, Q as HealthPlanOneBoxOrderPage, R as HealthPlanOneBoxOrderPageOptions, S as HealthPlanOrderStatus, T as HealthPlanOrderTracking, U as HealthPlanOrderTrackingStatus, j as HealthPlanPageRepository, a as HealthPlanPetWords, V as HealthPlanPurchase, W as HealthPlanReason, s as HealthPlanReasonKind, q as HealthPlanRepository, X as HealthPlanRepositoryDeps, Y as HealthPlanRuntime, k as HealthPlanShopOrder, g as HealthPlanSubscription, r as HealthPlanSubscriptionQuote, Z as HealthPlanSubscriptionRenewal, i as HealthPlanSubscriptionRepository, _ as HealthPlanSubscriptionStatus, $ as HealthPlanSubscriptionStep, a0 as HealthPlanSubscriptionSupply, a1 as HealthPlanTrackStep, a2 as createHealthPlanPageRepository, a3 as createHealthPlanPageRepositoryOver, a4 as createHealthPlanRepository, a5 as createHealthPlanRepositoryOver, a6 as createHealthPlanSubscriptionRepository, a7 as createHealthPlanSubscriptionRepositoryOver, a8 as formatHealthPlanDay, a9 as healthPlanCheckoutRefusal, aa as healthPlanCheckoutSessionFromWire, ab as healthPlanCheckoutStateFromWire, ac as healthPlanFocusCopyFor, ad as healthPlanFocusDesignFromWire, ae as healthPlanFromWire, af as healthPlanOneBoxOrderFromWire, ag as healthPlanOneBoxOrderPageFromWire, ah as healthPlanOrderTrackingFromWire, ai as healthPlanPageFromWire, aj as healthPlanPetWords, ak as healthPlanSubscriptionFromWire, al as healthPlanSubscriptionQuoteFromWire, am as isHealthPlanSubscriptionUnavailable } from '../../focus.d-C2fd_5MW.js';
9
+ import { f as HealthPlanCardOptions, g as HealthPlanImageVariant, h as HealthPlanReasonVariant, a as HealthPlanPriceFormat, d as HealthPlanCart$1, i as HealthPlanTopCardCopy, e as HealthPlanTopCardResults } from '../../usePresentation.d-CgvwGb2A.js';
10
+ export { E as EverfurHealthPlanOptions, j as EverfurHealthPlanState, k as EverfurHealthPlanStatus, l as HEALTH_PLAN_COPY, m as HEALTH_PLAN_COPY_PLACEHOLDERS, n as HEALTH_PLAN_LAYOUT_DEFAULTS, o as HEALTH_PLAN_REASON_LABELS, p as HEALTH_PLAN_TEMPLATES, q as HEALTH_PLAN_TOP_CARD_COPY, r as HealthPlanAddButtonSize, s as HealthPlanAddedVariant, H as HealthPlanBlanksFacts, t as HealthPlanBlanksPhase, v as HealthPlanCardShadow, w as HealthPlanCartBarPlacement, x as HealthPlanCartBarVisibility, y as HealthPlanCategoryVariant, c as HealthPlanEmptyCopy, z as HealthPlanFontWeight, A as HealthPlanHeaderContext, b as HealthPlanLayoutProps, B as HealthPlanPageContext, C as HealthPlanShadow, D as HealthPlanTopCardFocus, F as HealthPlanTopCardPet, G as formatHealthPlanPrice, I as formatHealthPlanPriceWith, J as healthPlanBlanksFacts, K as healthPlanCart, L as healthPlanNextShotsAt, M as healthPlanRecordsWeightKg, N as isHealthPlanSessionRequired, O as showHealthPlanCartBar, P as useEverfurHealthPlan, Q as useEverfurHealthPlanRepository, u as useEverfurPresentation } from '../../usePresentation.d-CgvwGb2A.js';
11
+ import { H as HealthPlanAskRowData, a as HealthPlanBylineData, b as HealthPlanCheckupData, c as HealthPlanExtrasData, d as HealthPlanFineData, e as HealthPlanFocusCardData, f as HealthPlanHeaderData, g as HealthPlanJumpStripData, h as HealthPlanNoPickData, i as HealthPlanOtherItemsData, j as HealthPlanSignsData, k as HealthPlanTipsData, l as HealthPlanToastData, m as HealthPlanToolbarData, n as HealthPlanVetQuoteData, o as HealthPlanWaitCardData, p as HealthPlanBuyButtonData, q as HealthPlanBuyOptionsData, r as HealthPlanDoseCardData, s as HealthPlanIngredientsData, t as HealthPlanProductPickData, u as HealthPlanProofData, v as HealthPlanReviewsData, w as HealthPlanSubscribedBoxData, x as HealthPlanTrustRowData, y as HealthPlanWhyItFitsData, z as HealthPlanCartCheckoutData, A as HealthPlanCheckoutSheetData, B as HealthPlanManageSheetData, C as HealthPlanWeightSheetData, D as HealthPlanCartScreenData, E as HealthPlanOrderData, F as HealthPlanOrdersData, G as HealthPlanPlacedData, I as HealthPlanStartedData } from '../../useHealthPlanSubscription.d-BoC7H85G.js';
12
+ export { J as HealthPlanBuyMode, K as HealthPlanCartDock, L as HealthPlanCartHandlers, M as HealthPlanCartScope, N as HealthPlanCartScopeProps, O as HealthPlanController, P as HealthPlanExtraRow, Q as HealthPlanFactRow, R as HealthPlanFocusContent, S as HealthPlanIconLabel, T as HealthPlanNextRow, U as HealthPlanNoVetListener, V as HealthPlanOtherItemRow, W as HealthPlanPageOptions, X as HealthPlanPagePhase, Y as HealthPlanPageState, Z as HealthPlanPhase, _ as HealthPlanRecordsLandedListener, $ as HealthPlanRecordsLandedSource, a0 as HealthPlanShopLineView, a1 as HealthPlanShopOrderView, a2 as HealthPlanSnapshot, a3 as HealthPlanSubscriptionOptions, a4 as HealthPlanSubscriptionPhase, a5 as HealthPlanSubscriptionState, a6 as HealthPlanVet, a7 as healthPlanNoVet, a8 as notifyHealthPlanRecordsLanded, a9 as onHealthPlanNoVet, aa as onHealthPlanRecordsLanded, ab as setHealthPlanNoVet, ac as useHealthPlanCartDock, ad as useHealthPlanPage, ae as useHealthPlanPageRepository, af as useHealthPlanSubscription, ag as useHealthPlanSubscriptionRepository } from '../../useHealthPlanSubscription.d-BoC7H85G.js';
13
+ export { A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-BWZiaByn.js';
14
+ export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config.d-BnZkxI5a.js';
15
15
  import { P as PetRef } from '../../ids.d-B2GAAifq.js';
16
16
  export { B as Brand, C as ConversationId, R as RecordsRequestId, U as UserRef, _ as __brand } from '../../ids.d-B2GAAifq.js';
17
17
  export { E as EverfurResult } from '../../EverfurResult.d-D_-254ZY.js';
@@ -20,8 +20,8 @@ export { L as LifecyclePort } from '../../LifecyclePort.d-Cr1p33a7.js';
20
20
  export { E as EverfurChatAnswerStyle, a as EverfurChatComposerPlaceholder, b as EverfurChatComposerStyle, c as EverfurChatHistoryBarSetting, d as EverfurChatHistoryStyle, e as EverfurChatSendButtonSetting, f as EverfurChatTopCardSetting, g as EverfurHealthPlanLayout, h as EverfurPresentation, i as EverfurPresentationInput, j as EverfurSafetyDisclaimerPlacement } from '../../presentation.d-Bs8xQ4gD.js';
21
21
  export { c as EverfurChatTopCardRow } from '../../threadOptions.d-CW51PyVd.js';
22
22
  import '../../resolve.d-BTC3b6FW.js';
23
- import '../../requestFunnel.d-B8OVGh0p.js';
24
- import '../../models.d-DOwnr8fi.js';
23
+ import '../../requestFunnel.d-DVCytzTE.js';
24
+ import '../../models.d-Bhq9p6Wa.js';
25
25
 
26
26
  /**
27
27
  * The focus layout over one plan item. `EverfurHealthPlan` mounts it; a partner can mount it over the hook too. It is
@@ -46,4 +46,4 @@ return jsxRuntime.jsxs("button",{type:"button","aria-label":row.label,"data-ever
46
46
  /* @__PURE__ */jsxRuntime.jsxs("article",{style:styles.detail,children:[
47
47
  /* @__PURE__ */jsxRuntime.jsx(Heading,{style:styles.heading,children:detailTitle(detail.item,copy)}),
48
48
  /* @__PURE__ */jsxRuntime.jsx(DetailTime,{item:detail.item,now:now,copy:copy,styles:styles}),detail.item.body.length>0?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.detailBody,children:detail.item.body}):null]})]})}function detailTitle(item,copy){return item.title.trim().length>0?item.title:copy.rowFallbackTitle}function DetailTime({item:item,now:now,copy:copy,styles:styles}){let time=formatInboxTime(item.createdAt,now,copy.now);return time===null?null:/* @__PURE__ */jsxRuntime.jsxs("p",{style:styles.time,children:[
49
- /* @__PURE__ */jsxRuntime.jsx("time",{dateTime:item.createdAt,children:time}),inboxTimeTakesAgo(time)?/* @__PURE__ */jsxRuntime.jsx("span",{style:VISUALLY_HIDDEN,children:` ${copy.timeAgoSuffix}`}):null]})}function makeInboxStyles(theme){let{color:color,radius:radius,space:space,type:type,slots:slots2}=theme,lineHeight=(size,ratio)=>`${Math.round(size*ratio)}px`,button={minHeight:48,padding:`0 ${space.lg}px`,borderRadius:radius.pill,cursor:"pointer",...faceCss(theme,"bold"),fontSize:type.size.body},row={boxSizing:"border-box",display:"flex",alignItems:"flex-start",gap:space.sm,width:"100%",minHeight:48,margin:0,padding:`${space.md}px ${space.lg}px`,border:"none",borderRadius:radius.md,backgroundColor:"transparent",color:color.text.primary,textAlign:"start",cursor:"pointer",...faceCss(theme,"regular")},dot={flex:"none",width:8,height:8,marginTop:Math.round((type.size.body*type.lineHeight.normal-8)/2),borderRadius:radius.pill},title={flex:1,minWidth:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.snug),color:color.text.primary,overflowWrap:"anywhere"},bar={display:"block",height:type.size.body,borderRadius:radius.xs,backgroundColor:color.skeleton};return{root:{...SURFACE_ROOT_RESET,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.md,width:"100%",padding:space.lg,borderRadius:radius.lg,backgroundColor:color.surface,color:color.text.primary,...faceCss(theme,"regular"),...slotCss(slots2.card)},heading:{margin:0,...headingFaceCss(theme,"bold"),fontSize:type.size.heading,lineHeight:lineHeight(type.size.heading,type.lineHeight.snug),color:color.text.primary},list:{display:"flex",flexDirection:"column",gap:space.xs,margin:0,padding:0,listStyle:"none"},item:{margin:0,padding:0},row:row,rowUnread:{...row,backgroundColor:color.brandSofter},dot:{...dot,backgroundColor:color.brand},dotRead:{...dot,backgroundColor:"transparent"},rowText:{display:"flex",flexDirection:"column",gap:space.xs,flex:1,minWidth:0},rowTop:{display:"flex",alignItems:"baseline",gap:space.sm},rowTitle:{...title,...faceCss(theme,"medium")},rowTitleUnread:{...title,...faceCss(theme,"bold")},rowBody:{fontSize:type.size.bodyTight,lineHeight:lineHeight(type.size.bodyTight,type.lineHeight.normal),color:color.text.secondary,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",overflowWrap:"anywhere"},time:{flex:"none",margin:0,fontSize:type.size.caption,lineHeight:lineHeight(type.size.caption,type.lineHeight.normal),color:color.text.timestamp},state:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm,padding:`${space.xl}px ${space.lg}px`,textAlign:"center"},stateTitle:{margin:0,...faceCss(theme,"bold"),fontSize:type.size.subtitle,lineHeight:lineHeight(type.size.subtitle,type.lineHeight.snug),color:color.text.primary},stateBody:{margin:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.normal),color:color.text.secondary},primary:{...button,marginTop:space.xs,border:"none",backgroundColor:color.brand,color:color.text.onBrand,...slotCss(slots2.primaryButton)},secondary:{...button,alignSelf:"center",border:`1px solid ${color.brandBorder}`,backgroundColor:"transparent",color:color.brandInk},back:{...button,alignSelf:"flex-start",padding:`0 ${space.sm}px`,border:"none",backgroundColor:"transparent",color:color.brandInk,...slotCss(slots2.link)},detail:{display:"flex",flexDirection:"column",gap:space.sm},detailBody:{margin:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.relaxed),color:color.text.primary,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},skeletonRow:{display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.md}px ${space.lg}px`},skeletonTitle:{...bar,width:"60%"},skeletonBody:{...bar,width:"90%",height:type.size.bodyTight}}}var INBOX_UNREAD_REFRESH_KEY="everfur-inbox-unread";function useInboxUnreadState(lifecycle){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),store=react.useMemo(()=>userRef===null?null:inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),[runtime,userRef,scopeEpoch]),subscribe=react.useCallback(listener=>store===null?()=>{}:store.subscribe(listener),[store]),read=react.useCallback(()=>store===null?null:store.get(),[store]),unreadCount=react.useSyncExternalStore(subscribe,read,read),refresh=react.useCallback(()=>store===null?Promise.resolve():store.refresh(),[store]);return react.useEffect(()=>{refresh()},[refresh]),useChatLifecycle(store===null?void 0:lifecycle,{conversationId:store===null?null:INBOX_UNREAD_REFRESH_KEY,isTurnInFlight:false,refresh:refresh}),react.useMemo(()=>({unreadCount:unreadCount,refresh:refresh}),[unreadCount,refresh])}function useEverfurInboxUnread(options={}){let{lifecycle:lifecycle}=options,port=react.useMemo(()=>lifecycle===void 0?createInboxBrowserLifecycle():lifecycle??void 0,[lifecycle]);return useInboxUnreadState(port)}var BASE="/widget/v1/notifications/web-push",URL_MAX=2048,KEY_MAX=256,TIMEZONE_MAX=64,LOCALE_MAX=35,BASE64URL=/^[A-Za-z0-9_-]+={0,2}$/,SUBSCRIPTION_ID=/^wps_[A-Za-z0-9_-]{1,64}$/,LOCAL_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]);function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed2(call){return makeEverfurError("internalError",{retryable:false,wireMessage:`${call}: the response was not the documented shape`})}function disposed2(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function hintsRefused(error){return error.httpStatus===400&&error.code==="validationFailed"}function withoutHints(body){let rest={...body};return delete rest.timezone,delete rest.locale,rest}function webPushUrl(value){if(typeof value!="string"||value.length===0||value.length>URL_MAX)return null;let url;try{url=new URL(value)}catch{return null}return url.protocol==="https:"||url.protocol==="http:"&&LOCAL_HOSTS.has(url.hostname)?url.href:null}function key(value){return typeof value=="string"&&value.length>0&&value.length<=KEY_MAX&&BASE64URL.test(value)}function bounded(value,max){return typeof value=="string"&&value.length>0&&value.length<=max?value:null}function validate(input){if(typeof input!="object"||input===null)return invalid2("subscribe needs an input object");let{endpoint:endpoint,keys:keys,openUrl:openUrl,timezone:timezone,locale:locale}=input,endpointHref=webPushUrl(endpoint);if(endpointHref===null||!endpointHref.startsWith("https:"))return invalid2("endpoint must be the https endpoint of a push subscription");if(typeof keys!="object"||keys===null||!key(keys.p256dh)||!key(keys.auth))return invalid2("keys must carry the subscription p256dh and auth keys (base64url)");let open=webPushUrl(openUrl);return open===null?invalid2("openUrl must be an https URL of your page"):{body:{endpoint:endpointHref,keys:{p256dh:keys.p256dh,auth:keys.auth},open_url:open,timezone:bounded(timezone,TIMEZONE_MAX),locale:bounded(locale,LOCALE_MAX)}}}function createWebPushClient(runtime){let over=()=>{let{services:services}=runtime.registry;return createWebPushClientOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed2(verb)));return{config:opts=>runtime.isDisposed?gone("config"):over().config(opts),subscribe:input=>runtime.isDisposed?gone("subscribe"):over().subscribe(input),unsubscribe:id=>runtime.isDisposed?gone("unsubscribe"):over().unsubscribe(id)}}function createWebPushClientOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async config(opts){let res=await funnel.send("webPush.config",{method:"GET",path:`${BASE}/config`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return res;let vapid=res.value?.vapid_public_key;return key(vapid)?ok(/* @__PURE__ */Object.freeze({vapidPublicKey:vapid})):err(malformed2("webPush.config"))},async subscribe(input){let checked=validate(input);if(!("body"in checked))return err(checked);let send=body=>funnel.send("webPush.subscribe",{method:"POST",path:`${BASE}/subscriptions`,body:body}),res=await send(checked.body);if(!res.ok&&hintsRefused(res.error)&&(checked.body.timezone!==null||checked.body.locale!==null)&&(res=await send(withoutHints(checked.body))),!res.ok)return res;let id=res.value?.subscription_id;return typeof id=="string"&&SUBSCRIPTION_ID.test(id)?ok(/* @__PURE__ */Object.freeze({subscriptionId:id})):err(malformed2("webPush.subscribe"))},async unsubscribe(subscriptionId){if(typeof subscriptionId!="string"||!SUBSCRIPTION_ID.test(subscriptionId))return err(invalid2("subscriptionId must be a web push subscription id (wps_...)"));let res=await funnel.send("webPush.unsubscribe",{method:"DELETE",path:`${BASE}/subscriptions/${subscriptionId}`});return res.ok?ok(void 0):err(res.error)}}}var LOGOUT_HOOK_BUDGET_MS=3e3;function wireCodeOf2(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}var DEFAULT_SERVICE_WORKER_PATH="/everfur-sw.js",SCOPE_DIRECTORY="everfur-push/",STORE_KEY="everfur.webPush.v1";function applicationServerKeyFromBase64Url(key2){let padded=key2.replace(/=+$/,"").replace(/-/g,"+").replace(/_/g,"/"),base64=padded+"=".repeat((4-padded.length%4)%4),binary=atob(base64),bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index+=1)bytes[index]=binary.charCodeAt(index);return bytes}function ownerTag(userRef){let hash=2166136261;for(let index=0;index<userRef.length;index+=1)hash^=userRef.charCodeAt(index),hash=Math.imul(hash,16777619)>>>0;return hash.toString(16).padStart(8,"0")}function webPushScope(serviceWorkerPath,scope){if(scope!==void 0)return scope;let path=serviceWorkerPath.split("?")[0]??serviceWorkerPath;return`${path.slice(0,path.lastIndexOf("/")+1)}${SCOPE_DIRECTORY}`}function pageOnly(url){return url.split(/[?#]/)[0]??url}function localStore(){let storage=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}};return{read(){try{let raw=storage()?.getItem(STORE_KEY);if(raw==null)return null;let parsed=JSON.parse(raw),owner=parsed?.owner,subscriptionId=parsed?.subscriptionId,endpoint=parsed?.endpoint;return typeof owner!="string"||typeof subscriptionId!="string"||typeof endpoint!="string"?null:{owner:owner,subscriptionId:subscriptionId,endpoint:endpoint}}catch{return null}},write(entry){try{storage()?.setItem(STORE_KEY,JSON.stringify(entry))}catch{}},clear(){try{storage()?.removeItem(STORE_KEY)}catch{}}}}function browserWebPush(){try{let g=globalThis,container=g.navigator?.serviceWorker,notification=g.Notification;if(container===void 0||notification===void 0||g.PushManager===void 0||g.isSecureContext===!1)return null;let asRegistration=value=>typeof value=="object"&&value!==null&&"pushManager"in value?value:null;return{permission:()=>notification.permission,requestPermission:()=>notification.requestPermission(),async register(path,scope){let registration=asRegistration(await container.register(path,{scope:scope}));return registration!==null&&await waitForActive(registration),registration},async existing(scope){return asRegistration(await container.getRegistration(scope))},pageUrl:()=>g.location?.href??"",timeZone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{return null}},locale:()=>typeof g.navigator?.language=="string"&&g.navigator.language.length>0?g.navigator.language:null}}catch{return null}}function waitForActive(registration){let reg=registration,worker=reg.active?null:reg.installing??reg.waiting??null;return worker===null?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,1e4);worker.addEventListener("statechange",()=>{(worker.state==="activated"||worker.state==="redundant")&&(clearTimeout(timer),resolve())})})}var WEB_PUSH_UNAVAILABLE="web_push_unavailable",OUTCOME_BY_PERMISSION=/* @__PURE__ */Object.freeze({default:"dismissed",denied:"denied"});function createWebPushController(deps){let{client:client}=deps,browser=deps.browser===void 0?browserWebPush():deps.browser,store=deps.store??localStore(),owner=ownerTag(deps.userRef),path=deps.options?.serviceWorkerPath??DEFAULT_SERVICE_WORKER_PATH,scope=webPushScope(path,deps.options?.scope),available=null,openUrl=()=>{let page=browser?.pageUrl()??"",open=webPushUrl(deps.options?.openUrl??pageOnly(page));return open===null?null:originOf(open)===originOf(page)?open:(warnOnce(`Everfur web push: openUrl ${originOf(open)??""} is not this page's origin (${originOf(page)??"unknown"}). The service worker opens only its own origin; pass an openUrl on this origin.`),null)},notOffered=error=>error.httpStatus===404?(available=false,true):wireCodeOf2(error)!==WEB_PUSH_UNAVAILABLE?false:(error.raw?.retryable!==true&&(available=false),true),currentSubscription=async()=>{if(browser===null)return null;let registration=await browser.existing(scope).catch(()=>null);return registration===null?null:registration.pushManager.getSubscription().catch(()=>null)},dropForeign=async subscription=>{subscription!==null&&await subscription.unsubscribe().catch(()=>false),store.clear()},register=async subscription=>{let json=subscription.toJSON(),p256dh=json.keys?.p256dh,auth=json.keys?.auth,endpoint=json.endpoint??subscription.endpoint,open=openUrl();if(typeof p256dh!="string"||typeof auth!="string"||typeof endpoint!="string"||open===null||browser===null)return"failed";let res=await client.subscribe({endpoint:endpoint,keys:{p256dh:p256dh,auth:auth},openUrl:open,timezone:browser.timeZone(),locale:browser.locale()});return res.ok?(store.write({owner:owner,subscriptionId:res.value.subscriptionId,endpoint:endpoint}),"ok"):notOffered(res.error)?"unavailable":"failed"},probe=async()=>{if(available!==null)return available;let res=await client.config();if(res.ok)available=true;else if(notOffered(res.error))return false;return available??true};return{async state(){try{if(browser===null)return"unsupported";let permission=browser.permission();if(permission==="denied")return"denied";if(!await probe())return"unavailable";if(permission==="default")return"ask";let subscription=await currentSubscription(),stored=store.read();return subscription!==null&&stored!==null&&stored.owner===owner&&stored.endpoint===subscription.endpoint?"on":"off"}catch{return browser===null?"unsupported":"off"}},async enable(){if(browser===null)return"unsupported";if(available===false)return"unavailable";if(openUrl()===null)return"failed";try{let permission=browser.permission()==="granted"?"granted":await browser.requestPermission();if(permission!=="granted")return OUTCOME_BY_PERMISSION[permission];let registration=await browser.register(path,scope);if(registration===null)return"failed";let config=await client.config();if(!config.ok)return notOffered(config.error)?"unavailable":"failed";available=!0;let existing=await registration.pushManager.getSubscription().catch(()=>null),stored=store.read(),subscription=existing;existing!==null&&(stored===null||stored.owner!==owner)&&(await dropForeign(existing),subscription=null),subscription??=await registration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:applicationServerKeyFromBase64Url(config.value.vapidPublicKey)});let outcome=await register(subscription);return outcome==="ok"?"on":outcome}catch{return"failed"}},async disable(){try{let subscription=await currentSubscription(),stored=store.read();if(stored!==null&&stored.owner===owner){let res=await client.unsubscribe(stored.subscriptionId);if(!res.ok&&res.error.httpStatus!==404)return!1}return subscription!==null&&await subscription.unsubscribe(),store.clear(),!0}catch{return false}},async sync(){try{if(browser===null||browser.permission()!=="granted")return"skipped";let subscription=await currentSubscription(),stored=store.read();if(subscription===null)return stored!==null&&(stored.owner===owner&&client.unsubscribe(stored.subscriptionId),store.clear()),"skipped";if(stored===null||stored.owner!==owner)return await dropForeign(subscription),"reset";let outcome=await register(subscription);return outcome==="ok"?"synced":outcome}catch{return"failed"}},async endForSignOut(signOutClient){try{let stored=store.read(),subscription=await currentSubscription();stored!==null&&stored.owner===owner&&await signOutClient.unsubscribe(stored.subscriptionId),subscription!==null&&await subscription.unsubscribe()}catch{}finally{store.clear()}}}}function originOf(url){try{return new URL(url).origin}catch{return null}}var warned=false;function warnOnce(message){if(warned)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}function useEverfurWebPush(options={}){let{runtime:runtime,userRef:userRef}=useEverfurContext(),{serviceWorkerPath:serviceWorkerPath,scope:scope,openUrl:openUrl}=options,settings=react.useMemo(()=>({...serviceWorkerPath===void 0?{}:{serviceWorkerPath:serviceWorkerPath},...scope===void 0?{}:{scope:scope},...openUrl===void 0?{}:{openUrl:openUrl}}),[serviceWorkerPath,scope,openUrl]),controller=react.useMemo(()=>userRef===null?null:createWebPushController({client:createWebPushClient(runtime),userRef:userRef,options:settings}),[runtime,userRef,settings]),[status,setStatus]=react.useState(controller===null?"signed_out":"checking"),[busy,setBusy]=react.useState(false),current=react.useRef(controller);current.current=controller,react.useEffect(()=>{if(controller===null){setStatus("signed_out");return}let live=true;return setStatus("checking"),(async()=>{await controller.sync();let next=await controller.state();live&&setStatus(next)})(),()=>{live=false}},[controller]),react.useEffect(()=>runtime.onBeforeLogout(async({userRef:leaving,auth:auth})=>{let funnel=createRequestFunnel({auth:auth,maxAttempts:1,unaryTimeoutMs:LOGOUT_HOOK_BUDGET_MS,...runtime.registry.services.errorPolicy?{errorPolicy:runtime.registry.services.errorPolicy}:{}});await createWebPushController({client:createWebPushClient(runtime),userRef:leaving,options:settings}).endForSignOut(createWebPushClientOver({auth:auth,funnel:funnel}))}),[runtime,settings]);let enable=react.useCallback(()=>{let mine=current.current;return mine===null?Promise.resolve("failed"):(setBusy(true),mine.enable().then(async outcome=>{let next=await mine.state();return current.current===mine&&(setStatus(next),setBusy(false)),outcome}))},[]),disable=react.useCallback(async()=>{let mine=current.current;if(mine===null)return false;setBusy(true);let done=await mine.disable(),next=await mine.state();return current.current===mine&&(setStatus(next),setBusy(false)),done},[]);return react.useMemo(()=>({status:status,busy:busy,enable:enable,disable:disable}),[status,busy,enable,disable])}function tapTarget(ref){return ref.route==null||ref.eventId===null?null:parseEverfurNotification({v:1,event_id:ref.eventId,event_type:ref.route.event_type,target:ref.route.target})?.target??null}var addressTap=null,ADDRESS_TAPS=/* @__PURE__ */new WeakSet;function takeAddressTap(){let taken=takeNotificationOpenFrom(typeof window>"u"?void 0:window);return taken!==null&&(addressTap=taken,ADDRESS_TAPS.add(taken)),taken}function takeEverfurNotificationEventId(){return takeAddressTap()?.eventId??null}function takeEverfurNotificationOpen(){return takeAddressTap()}function firstTap(given){if(given===void 0)return takeAddressTap()??addressTap;if(given===null||typeof given=="string")return addressTap!==null&&addressTap.eventId===given?addressTap:given===null?null:{eventId:given,itemId:null};let tap=notificationOpenOf(given);return tap!==null&&addressTap!==null&&addressTap.eventId===tap.eventId&&addressTap.itemId===tap.itemId?addressTap:tap}function useEverfurNotificationOpen(options){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=useEverfurInboxClient(),onOpen=react.useRef(options.onOpen);onOpen.current=options.onOpen;let pending=react.useRef(null);if(pending.current===null){let first=firstTap(options.eventId);pending.current=first===null?[]:[first]}let queue=pending,flush=react.useRef(()=>{});react.useEffect(()=>onNotificationMessage(ref=>{queue.current.push(ref),flush.current()}),[]),react.useEffect(()=>{if(userRef===null)return;let live=true,started=/* @__PURE__ */new Set,unread=inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),controller=createInboxController({client:client,onUnreadCount:count2=>unread.report(count2)}),run=()=>{for(let ref of queue.current)started.has(ref)||(started.add(ref),controller.open({...ref.itemId===null?{}:{itemId:ref.itemId},...ref.eventId===null?{}:{eventId:ref.eventId}}).then(res=>{let at2=queue.current.indexOf(ref);if(!live||at2<0)return;if(queue.current.splice(at2,1),ref===addressTap)addressTap=null;else if(ADDRESS_TAPS.has(ref))return;let inbox=res.ok?res.value:null;callHost(onOpen.current,{eventId:ref.eventId,itemId:ref.itemId,inbox:inbox,target:inbox===null?tapTarget(ref):null})}))};return flush.current=run,run(),()=>{live=false,flush.current=()=>{},controller.dispose()}},[client,userRef,runtime,scopeEpoch])}exports.EverfurInbox=EverfurInbox;exports.createInboxClient=createInboxClient;exports.createWebPushClient=createWebPushClient;exports.takeEverfurNotificationEventId=takeEverfurNotificationEventId;exports.takeEverfurNotificationOpen=takeEverfurNotificationOpen;exports.useEverfurInbox=useEverfurInbox;exports.useEverfurInboxClient=useEverfurInboxClient;exports.useEverfurInboxUnread=useEverfurInboxUnread;exports.useEverfurNotificationOpen=useEverfurNotificationOpen;exports.useEverfurWebPush=useEverfurWebPush;
49
+ /* @__PURE__ */jsxRuntime.jsx("time",{dateTime:item.createdAt,children:time}),inboxTimeTakesAgo(time)?/* @__PURE__ */jsxRuntime.jsx("span",{style:VISUALLY_HIDDEN,children:` ${copy.timeAgoSuffix}`}):null]})}function makeInboxStyles(theme){let{color:color,radius:radius,space:space,type:type,slots:slots2}=theme,lineHeight=(size,ratio)=>`${Math.round(size*ratio)}px`,button={minHeight:48,padding:`0 ${space.lg}px`,borderRadius:radius.pill,cursor:"pointer",...faceCss(theme,"bold"),fontSize:type.size.body},row={boxSizing:"border-box",display:"flex",alignItems:"flex-start",gap:space.sm,width:"100%",minHeight:48,margin:0,padding:`${space.md}px ${space.lg}px`,border:"none",borderRadius:radius.md,backgroundColor:"transparent",color:color.text.primary,textAlign:"start",cursor:"pointer",...faceCss(theme,"regular")},dot={flex:"none",width:8,height:8,marginTop:Math.round((type.size.body*type.lineHeight.normal-8)/2),borderRadius:radius.pill},title={flex:1,minWidth:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.snug),color:color.text.primary,overflowWrap:"anywhere"},bar={display:"block",height:type.size.body,borderRadius:radius.xs,backgroundColor:color.skeleton};return{root:{...SURFACE_ROOT_RESET,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.md,width:"100%",padding:space.lg,borderRadius:radius.lg,backgroundColor:color.surface,color:color.text.primary,...faceCss(theme,"regular"),...slotCss(slots2.card)},heading:{margin:0,...headingFaceCss(theme,"bold"),fontSize:type.size.heading,lineHeight:lineHeight(type.size.heading,type.lineHeight.snug),color:color.text.primary},list:{display:"flex",flexDirection:"column",gap:space.xs,margin:0,padding:0,listStyle:"none"},item:{margin:0,padding:0},row:row,rowUnread:{...row,backgroundColor:color.brandSofter},dot:{...dot,backgroundColor:color.brand},dotRead:{...dot,backgroundColor:"transparent"},rowText:{display:"flex",flexDirection:"column",gap:space.xs,flex:1,minWidth:0},rowTop:{display:"flex",alignItems:"baseline",gap:space.sm},rowTitle:{...title,...faceCss(theme,"medium")},rowTitleUnread:{...title,...faceCss(theme,"bold")},rowBody:{fontSize:type.size.bodyTight,lineHeight:lineHeight(type.size.bodyTight,type.lineHeight.normal),color:color.text.secondary,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",overflowWrap:"anywhere"},time:{flex:"none",margin:0,fontSize:type.size.caption,lineHeight:lineHeight(type.size.caption,type.lineHeight.normal),color:color.text.timestamp},state:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm,padding:`${space.xl}px ${space.lg}px`,textAlign:"center"},stateTitle:{margin:0,...faceCss(theme,"bold"),fontSize:type.size.subtitle,lineHeight:lineHeight(type.size.subtitle,type.lineHeight.snug),color:color.text.primary},stateBody:{margin:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.normal),color:color.text.secondary},primary:{...button,marginTop:space.xs,border:"none",backgroundColor:color.brand,color:color.text.onBrand,...slotCss(slots2.primaryButton)},secondary:{...button,alignSelf:"center",border:`1px solid ${color.brandBorder}`,backgroundColor:"transparent",color:color.brandInk},back:{...button,alignSelf:"flex-start",padding:`0 ${space.sm}px`,border:"none",backgroundColor:"transparent",color:color.brandInk,...slotCss(slots2.link)},detail:{display:"flex",flexDirection:"column",gap:space.sm},detailBody:{margin:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.relaxed),color:color.text.primary,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},skeletonRow:{display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.md}px ${space.lg}px`},skeletonTitle:{...bar,width:"60%"},skeletonBody:{...bar,width:"90%",height:type.size.bodyTight}}}var INBOX_UNREAD_REFRESH_KEY="everfur-inbox-unread";function useInboxUnreadState(lifecycle){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),store=react.useMemo(()=>userRef===null?null:inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),[runtime,userRef,scopeEpoch]),subscribe=react.useCallback(listener=>store===null?()=>{}:store.subscribe(listener),[store]),read=react.useCallback(()=>store===null?null:store.get(),[store]),unreadCount=react.useSyncExternalStore(subscribe,read,read),refresh=react.useCallback(()=>store===null?Promise.resolve():store.refresh(),[store]);return react.useEffect(()=>{refresh()},[refresh]),useChatLifecycle(store===null?void 0:lifecycle,{conversationId:store===null?null:INBOX_UNREAD_REFRESH_KEY,isTurnInFlight:false,refresh:refresh}),react.useMemo(()=>({unreadCount:unreadCount,refresh:refresh}),[unreadCount,refresh])}function useEverfurInboxUnread(options={}){let{lifecycle:lifecycle}=options,port=react.useMemo(()=>lifecycle===void 0?createInboxBrowserLifecycle():lifecycle??void 0,[lifecycle]);return useInboxUnreadState(port)}var BASE="/widget/v1/notifications/web-push",URL_MAX=2048,KEY_MAX=256,TIMEZONE_MAX=64,LOCALE_MAX=35,BASE64URL=/^[A-Za-z0-9_-]+={0,2}$/,SUBSCRIPTION_ID=/^wps_[A-Za-z0-9_-]{1,64}$/,LOCAL_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]);function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed2(call){return makeEverfurError("internalError",{retryable:false,wireMessage:`${call}: the response was not the documented shape`})}function disposed2(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function hintsRefused(error){return error.httpStatus===400&&error.code==="validationFailed"}function withoutHints(body){let rest={...body};return delete rest.timezone,delete rest.locale,rest}function webPushUrl(value){if(typeof value!="string"||value.length===0||value.length>URL_MAX)return null;let url;try{url=new URL(value)}catch{return null}return url.protocol==="https:"||url.protocol==="http:"&&LOCAL_HOSTS.has(url.hostname)?url.href:null}function key(value){return typeof value=="string"&&value.length>0&&value.length<=KEY_MAX&&BASE64URL.test(value)}function bounded(value,max){return typeof value=="string"&&value.length>0&&value.length<=max?value:null}function validate(input){if(typeof input!="object"||input===null)return invalid2("subscribe needs an input object");let{endpoint:endpoint,keys:keys,openUrl:openUrl,timezone:timezone,locale:locale}=input,endpointHref=webPushUrl(endpoint);if(endpointHref===null||!endpointHref.startsWith("https:"))return invalid2("endpoint must be the https endpoint of a push subscription");if(typeof keys!="object"||keys===null||!key(keys.p256dh)||!key(keys.auth))return invalid2("keys must carry the subscription p256dh and auth keys (base64url)");let open=webPushUrl(openUrl);return open===null?invalid2("openUrl must be an https URL of your page"):{body:{endpoint:endpointHref,keys:{p256dh:keys.p256dh,auth:keys.auth},open_url:open,timezone:bounded(timezone,TIMEZONE_MAX),locale:bounded(locale,LOCALE_MAX)}}}function createWebPushClient(runtime){let over=()=>{let{services:services}=runtime.registry;return createWebPushClientOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed2(verb)));return{config:opts=>runtime.isDisposed?gone("config"):over().config(opts),subscribe:input=>runtime.isDisposed?gone("subscribe"):over().subscribe(input),unsubscribe:id=>runtime.isDisposed?gone("unsubscribe"):over().unsubscribe(id)}}function createWebPushClientOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async config(opts){let res=await funnel.send("webPush.config",{method:"GET",path:`${BASE}/config`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return res;let vapid=res.value?.vapid_public_key;return key(vapid)?ok(/* @__PURE__ */Object.freeze({vapidPublicKey:vapid})):err(malformed2("webPush.config"))},async subscribe(input){let checked=validate(input);if(!("body"in checked))return err(checked);let send=body=>funnel.send("webPush.subscribe",{method:"POST",path:`${BASE}/subscriptions`,body:body}),res=await send(checked.body);if(!res.ok&&hintsRefused(res.error)&&(checked.body.timezone!==null||checked.body.locale!==null)&&(res=await send(withoutHints(checked.body))),!res.ok)return res;let id=res.value?.subscription_id;return typeof id=="string"&&SUBSCRIPTION_ID.test(id)?ok(/* @__PURE__ */Object.freeze({subscriptionId:id})):err(malformed2("webPush.subscribe"))},async unsubscribe(subscriptionId){if(typeof subscriptionId!="string"||!SUBSCRIPTION_ID.test(subscriptionId))return err(invalid2("subscriptionId must be a web push subscription id (wps_...)"));let res=await funnel.send("webPush.unsubscribe",{method:"DELETE",path:`${BASE}/subscriptions/${subscriptionId}`});return res.ok?ok(void 0):err(res.error)}}}var LOGOUT_HOOK_BUDGET_MS=3e3;function wireCodeOf2(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}var DEFAULT_SERVICE_WORKER_PATH="/everfur-sw.js",SCOPE_DIRECTORY="everfur-push/",STORE_KEY="everfur.webPush.v1";function applicationServerKeyFromBase64Url(key2){let padded=key2.replace(/=+$/,"").replace(/-/g,"+").replace(/_/g,"/"),base64=padded+"=".repeat((4-padded.length%4)%4),binary=atob(base64),bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index+=1)bytes[index]=binary.charCodeAt(index);return bytes}function ownerTag(userRef){let hash=2166136261;for(let index=0;index<userRef.length;index+=1)hash^=userRef.charCodeAt(index),hash=Math.imul(hash,16777619)>>>0;return hash.toString(16).padStart(8,"0")}function webPushScope(serviceWorkerPath,scope){if(scope!==void 0)return scope;let path=serviceWorkerPath.split("?")[0]??serviceWorkerPath;return`${path.slice(0,path.lastIndexOf("/")+1)}${SCOPE_DIRECTORY}`}function pageOnly(url){return url.split(/[?#]/)[0]??url}function localStore(){let storage=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}};return{read(){try{let raw=storage()?.getItem(STORE_KEY);if(raw==null)return null;let parsed=JSON.parse(raw),owner=parsed?.owner,subscriptionId=parsed?.subscriptionId,endpoint=parsed?.endpoint;return typeof owner!="string"||typeof subscriptionId!="string"||typeof endpoint!="string"?null:{owner:owner,subscriptionId:subscriptionId,endpoint:endpoint}}catch{return null}},write(entry){try{storage()?.setItem(STORE_KEY,JSON.stringify(entry))}catch{}},clear(){try{storage()?.removeItem(STORE_KEY)}catch{}}}}function browserWebPush(){try{let g=globalThis,container=g.navigator?.serviceWorker,notification=g.Notification;if(container===void 0||notification===void 0||g.PushManager===void 0||g.isSecureContext===!1)return null;let asRegistration=value=>typeof value=="object"&&value!==null&&"pushManager"in value?value:null;return{permission:()=>notification.permission,requestPermission:()=>notification.requestPermission(),async register(path,scope){let registration=asRegistration(await container.register(path,{scope:scope}));return registration!==null&&await waitForActive(registration),registration},async existing(scope){return asRegistration(await container.getRegistration(scope))},pageUrl:()=>g.location?.href??"",timeZone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{return null}},locale:()=>typeof g.navigator?.language=="string"&&g.navigator.language.length>0?g.navigator.language:null}}catch{return null}}function waitForActive(registration){let reg=registration,worker=reg.active?null:reg.installing??reg.waiting??null;return worker===null?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,1e4);worker.addEventListener("statechange",()=>{(worker.state==="activated"||worker.state==="redundant")&&(clearTimeout(timer),resolve())})})}var WEB_PUSH_UNAVAILABLE="web_push_unavailable",OUTCOME_BY_PERMISSION=/* @__PURE__ */Object.freeze({default:"dismissed",denied:"denied"});function createWebPushController(deps){let{client:client}=deps,browser=deps.browser===void 0?browserWebPush():deps.browser,store=deps.store??localStore(),owner=ownerTag(deps.userRef),path=deps.options?.serviceWorkerPath??DEFAULT_SERVICE_WORKER_PATH,scope=webPushScope(path,deps.options?.scope),available=null,openUrl=()=>{let page=browser?.pageUrl()??"",open=webPushUrl(deps.options?.openUrl??pageOnly(page));return open===null?null:originOf(open)===originOf(page)?open:(warnOnce(`Everfur web push: openUrl ${originOf(open)??""} is not this page's origin (${originOf(page)??"unknown"}). The service worker opens only its own origin; pass an openUrl on this origin.`),null)},notOffered=error=>error.httpStatus===404?(available=false,true):wireCodeOf2(error)!==WEB_PUSH_UNAVAILABLE?false:(error.raw?.retryable!==true&&(available=false),true),currentSubscription=async()=>{if(browser===null)return null;let registration=await browser.existing(scope).catch(()=>null);return registration===null?null:registration.pushManager.getSubscription().catch(()=>null)},dropForeign=async subscription=>{subscription!==null&&await subscription.unsubscribe().catch(()=>false),store.clear()},register=async subscription=>{let json=subscription.toJSON(),p256dh=json.keys?.p256dh,auth=json.keys?.auth,endpoint=json.endpoint??subscription.endpoint,open=openUrl();if(typeof p256dh!="string"||typeof auth!="string"||typeof endpoint!="string"||open===null||browser===null)return"failed";let res=await client.subscribe({endpoint:endpoint,keys:{p256dh:p256dh,auth:auth},openUrl:open,timezone:browser.timeZone(),locale:browser.locale()});return res.ok?(store.write({owner:owner,subscriptionId:res.value.subscriptionId,endpoint:endpoint}),"ok"):notOffered(res.error)?"unavailable":"failed"},probe=async()=>{if(available!==null)return available;let res=await client.config();if(res.ok)available=true;else if(notOffered(res.error))return false;return available??true};return{async state(){try{if(browser===null)return"unsupported";let permission=browser.permission();if(permission==="denied")return"denied";if(!await probe())return"unavailable";if(permission==="default")return"ask";let subscription=await currentSubscription(),stored=store.read();return subscription!==null&&stored!==null&&stored.owner===owner&&stored.endpoint===subscription.endpoint?"on":"off"}catch{return browser===null?"unsupported":"off"}},async enable(){if(browser===null)return"unsupported";if(available===false)return"unavailable";if(openUrl()===null)return"failed";try{let permission=browser.permission()==="granted"?"granted":await browser.requestPermission();if(permission!=="granted")return OUTCOME_BY_PERMISSION[permission];let registration=await browser.register(path,scope);if(registration===null)return"failed";let config=await client.config();if(!config.ok)return notOffered(config.error)?"unavailable":"failed";available=!0;let existing=await registration.pushManager.getSubscription().catch(()=>null),stored=store.read(),subscription=existing;existing!==null&&(stored===null||stored.owner!==owner)&&(await dropForeign(existing),subscription=null),subscription??=await registration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:applicationServerKeyFromBase64Url(config.value.vapidPublicKey)});let outcome=await register(subscription);return outcome==="ok"?"on":outcome}catch{return"failed"}},async disable(){try{let subscription=await currentSubscription(),stored=store.read();if(stored!==null&&stored.owner===owner){let res=await client.unsubscribe(stored.subscriptionId);if(!res.ok&&res.error.httpStatus!==404)return!1}return subscription!==null&&await subscription.unsubscribe(),store.clear(),!0}catch{return false}},async sync(){try{if(browser===null||browser.permission()!=="granted")return"skipped";let subscription=await currentSubscription(),stored=store.read();if(subscription===null)return stored!==null&&(stored.owner===owner&&client.unsubscribe(stored.subscriptionId),store.clear()),"skipped";if(stored===null||stored.owner!==owner)return await dropForeign(subscription),"reset";let outcome=await register(subscription);return outcome==="ok"?"synced":outcome}catch{return"failed"}},async endForSignOut(signOutClient){try{let stored=store.read(),subscription=await currentSubscription();stored!==null&&stored.owner===owner&&await signOutClient.unsubscribe(stored.subscriptionId),subscription!==null&&await subscription.unsubscribe()}catch{}finally{store.clear()}}}}function originOf(url){try{return new URL(url).origin}catch{return null}}var warned=false;function warnOnce(message){if(warned)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}var signOutSettings=/* @__PURE__ */new WeakMap;function useEverfurWebPush(options={}){let{runtime:runtime,userRef:userRef}=useEverfurContext(),{serviceWorkerPath:serviceWorkerPath,scope:scope,openUrl:openUrl}=options,settings=react.useMemo(()=>({...serviceWorkerPath===void 0?{}:{serviceWorkerPath:serviceWorkerPath},...scope===void 0?{}:{scope:scope},...openUrl===void 0?{}:{openUrl:openUrl}}),[serviceWorkerPath,scope,openUrl]),controller=react.useMemo(()=>userRef===null?null:createWebPushController({client:createWebPushClient(runtime),userRef:userRef,options:settings}),[runtime,userRef,settings]),[status,setStatus]=react.useState(controller===null?"signed_out":"checking"),[busy,setBusy]=react.useState(false),current=react.useRef(controller);current.current=controller,react.useEffect(()=>{if(controller===null){setStatus("signed_out");return}let live=true;return setStatus("checking"),(async()=>{await controller.sync();let next=await controller.state();live&&setStatus(next)})(),()=>{live=false}},[controller]),react.useEffect(()=>{signOutSettings.has(runtime)||runtime.onBeforeLogout(async({userRef:leaving,auth:auth})=>{let funnel=createRequestFunnel({auth:auth,maxAttempts:1,unaryTimeoutMs:LOGOUT_HOOK_BUDGET_MS,...runtime.registry.services.errorPolicy?{errorPolicy:runtime.registry.services.errorPolicy}:{}}),leavingClient=createWebPushClientOver({auth:auth,funnel:funnel});await createWebPushController({client:leavingClient,userRef:leaving,options:signOutSettings.get(runtime)}).endForSignOut(leavingClient)}),signOutSettings.set(runtime,settings)},[runtime,settings]);let enable=react.useCallback(()=>{let mine=current.current;return mine===null?Promise.resolve("failed"):(setBusy(true),mine.enable().then(async outcome=>{let next=await mine.state();return current.current===mine&&(setStatus(next),setBusy(false)),outcome}))},[]),disable=react.useCallback(async()=>{let mine=current.current;if(mine===null)return false;setBusy(true);let done=await mine.disable(),next=await mine.state();return current.current===mine&&(setStatus(next),setBusy(false)),done},[]);return react.useMemo(()=>({status:status,busy:busy,enable:enable,disable:disable}),[status,busy,enable,disable])}function tapTarget(ref){return ref.route==null||ref.eventId===null?null:parseEverfurNotification({v:1,event_id:ref.eventId,event_type:ref.route.event_type,target:ref.route.target})?.target??null}var addressTap=null,ADDRESS_TAPS=/* @__PURE__ */new WeakSet;function takeAddressTap(){let taken=takeNotificationOpenFrom(typeof window>"u"?void 0:window);return taken!==null&&(addressTap=taken,ADDRESS_TAPS.add(taken)),taken}function takeEverfurNotificationEventId(){return takeAddressTap()?.eventId??null}function takeEverfurNotificationOpen(){return takeAddressTap()}function firstTap(given){if(given===void 0)return takeAddressTap()??addressTap;if(given===null||typeof given=="string")return addressTap!==null&&addressTap.eventId===given?addressTap:given===null?null:{eventId:given,itemId:null};let tap=notificationOpenOf(given);return tap!==null&&addressTap!==null&&addressTap.eventId===tap.eventId&&addressTap.itemId===tap.itemId?addressTap:tap}function useEverfurNotificationOpen(options){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=useEverfurInboxClient(),onOpen=react.useRef(options.onOpen);onOpen.current=options.onOpen;let pending=react.useRef(null);if(pending.current===null){let first=firstTap(options.eventId);pending.current=first===null?[]:[first]}let queue=pending,flush=react.useRef(()=>{});react.useEffect(()=>onNotificationMessage(ref=>{queue.current.push(ref),flush.current()}),[]),react.useEffect(()=>{if(userRef===null)return;let live=true,started=/* @__PURE__ */new Set,unread=inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),controller=createInboxController({client:client,onUnreadCount:count2=>unread.report(count2)}),run=()=>{for(let ref of queue.current)started.has(ref)||(started.add(ref),controller.open({...ref.itemId===null?{}:{itemId:ref.itemId},...ref.eventId===null?{}:{eventId:ref.eventId}}).then(res=>{let at2=queue.current.indexOf(ref);if(!live||at2<0)return;if(queue.current.splice(at2,1),ref===addressTap)addressTap=null;else if(ADDRESS_TAPS.has(ref))return;let inbox=res.ok?res.value:null;callHost(onOpen.current,{eventId:ref.eventId,itemId:ref.itemId,inbox:inbox,target:inbox===null?tapTarget(ref):null})}))};return flush.current=run,run(),()=>{live=false,flush.current=()=>{},controller.dispose()}},[client,userRef,runtime,scopeEpoch])}exports.EverfurInbox=EverfurInbox;exports.createInboxClient=createInboxClient;exports.createWebPushClient=createWebPushClient;exports.takeEverfurNotificationEventId=takeEverfurNotificationEventId;exports.takeEverfurNotificationOpen=takeEverfurNotificationOpen;exports.useEverfurInbox=useEverfurInbox;exports.useEverfurInboxClient=useEverfurInboxClient;exports.useEverfurInboxUnread=useEverfurInboxUnread;exports.useEverfurNotificationOpen=useEverfurNotificationOpen;exports.useEverfurWebPush=useEverfurWebPush;
@@ -3,16 +3,16 @@ import { CSSProperties, ReactNode } from 'react';
3
3
  import { P as PetRef, U as UserRef } from '../../ids.d-B2GAAifq.cjs';
4
4
  export { B as Brand, C as ConversationId, R as RecordsRequestId, _ as __brand } from '../../ids.d-B2GAAifq.cjs';
5
5
  import { L as LifecyclePort } from '../../LifecyclePort.d-Cr1p33a7.cjs';
6
- import { E as EverfurInboxOpenHandler, a as EverfurInboxCopy, U as UseEverfurInboxOptions, b as EverfurInboxState, c as UseEverfurInboxUnreadOptions, d as EverfurInboxUnread, g as EverfurInboxOpen } from '../../useInboxUnread.d-pi6FNnK-.cjs';
7
- export { e as EverfurInboxClient, f as EverfurInboxItem, h as EverfurInboxPage, i as EverfurInboxQuery, j as EverfurInboxSnapshot, k as EverfurInboxStatus, l as EverfurInboxTarget, I as InboxRuntime, m as createInboxClient, u as useEverfurInboxClient } from '../../useInboxUnread.d-pi6FNnK-.cjs';
6
+ import { E as EverfurInboxOpenHandler, a as EverfurInboxCopy, U as UseEverfurInboxOptions, b as EverfurInboxState, c as UseEverfurInboxUnreadOptions, d as EverfurInboxUnread, g as EverfurInboxOpen } from '../../useInboxUnread.d-DW0dpWdv.cjs';
7
+ export { e as EverfurInboxClient, f as EverfurInboxItem, h as EverfurInboxPage, i as EverfurInboxQuery, j as EverfurInboxSnapshot, k as EverfurInboxStatus, l as EverfurInboxTarget, I as InboxRuntime, m as createInboxClient, u as useEverfurInboxClient } from '../../useInboxUnread.d-DW0dpWdv.cjs';
8
8
  import { g as EverfurNotificationTarget } from '../../parse.d-DYsx1Q2V.cjs';
9
9
  export { d as EverfurNotification, f as EverfurNotificationEventType, h as EverfurNotificationTargetKind } from '../../parse.d-DYsx1Q2V.cjs';
10
10
  import { E as EverfurResult } from '../../EverfurResult.d-BFH-3s6E.cjs';
11
11
  import { E as ErrorPolicyPort } from '../../ErrorPolicyPort.d-DirW9hgO.cjs';
12
- import { A as AuthContext } from '../../identity.d-CA7mW59I.cjs';
13
- export { I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-CA7mW59I.cjs';
12
+ import { A as AuthContext } from '../../identity.d-CooKscNj.cjs';
13
+ export { I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-CooKscNj.cjs';
14
14
  export { V as VetVisitIntent } from '../../visitIntent.d-D7_yVp1I.cjs';
15
- export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config.d-jCmrhM4a.cjs';
15
+ export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config.d-DoC-XaJ0.cjs';
16
16
  export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode } from '../../EverfurError.d-8NHtlgzA.cjs';
17
17
 
18
18
  interface EverfurInboxProps {
@@ -3,16 +3,16 @@ import { CSSProperties, ReactNode } from 'react';
3
3
  import { P as PetRef, U as UserRef } from '../../ids.d-B2GAAifq.js';
4
4
  export { B as Brand, C as ConversationId, R as RecordsRequestId, _ as __brand } from '../../ids.d-B2GAAifq.js';
5
5
  import { L as LifecyclePort } from '../../LifecyclePort.d-Cr1p33a7.js';
6
- import { E as EverfurInboxOpenHandler, a as EverfurInboxCopy, U as UseEverfurInboxOptions, b as EverfurInboxState, c as UseEverfurInboxUnreadOptions, d as EverfurInboxUnread, g as EverfurInboxOpen } from '../../useInboxUnread.d-Blxu00eY.js';
7
- export { e as EverfurInboxClient, f as EverfurInboxItem, h as EverfurInboxPage, i as EverfurInboxQuery, j as EverfurInboxSnapshot, k as EverfurInboxStatus, l as EverfurInboxTarget, I as InboxRuntime, m as createInboxClient, u as useEverfurInboxClient } from '../../useInboxUnread.d-Blxu00eY.js';
6
+ import { E as EverfurInboxOpenHandler, a as EverfurInboxCopy, U as UseEverfurInboxOptions, b as EverfurInboxState, c as UseEverfurInboxUnreadOptions, d as EverfurInboxUnread, g as EverfurInboxOpen } from '../../useInboxUnread.d-vYpOXVRv.js';
7
+ export { e as EverfurInboxClient, f as EverfurInboxItem, h as EverfurInboxPage, i as EverfurInboxQuery, j as EverfurInboxSnapshot, k as EverfurInboxStatus, l as EverfurInboxTarget, I as InboxRuntime, m as createInboxClient, u as useEverfurInboxClient } from '../../useInboxUnread.d-vYpOXVRv.js';
8
8
  import { g as EverfurNotificationTarget } from '../../parse.d-Do0sdAgm.js';
9
9
  export { d as EverfurNotification, f as EverfurNotificationEventType, h as EverfurNotificationTargetKind } from '../../parse.d-Do0sdAgm.js';
10
10
  import { E as EverfurResult } from '../../EverfurResult.d-D_-254ZY.js';
11
11
  import { E as ErrorPolicyPort } from '../../ErrorPolicyPort.d-68yrE3BE.js';
12
- import { A as AuthContext } from '../../identity.d-DIOnFzXL.js';
13
- export { I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-DIOnFzXL.js';
12
+ import { A as AuthContext } from '../../identity.d-BWZiaByn.js';
13
+ export { I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-BWZiaByn.js';
14
14
  export { V as VetVisitIntent } from '../../visitIntent.d-D7_yVp1I.js';
15
- export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config.d-N5Xzy53V.js';
15
+ export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, D as DeltaFrame, c as DoneFrame, E as ErrorFrame, d as EverfurRequest, e as EverfurRequestBase, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, i as UrgencyLevel } from '../../config.d-BnZkxI5a.js';
16
16
  export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode } from '../../EverfurError.d-8NHtlgzA.js';
17
17
 
18
18
  interface EverfurInboxProps {
@@ -46,4 +46,4 @@ return jsxs("button",{type:"button","aria-label":row.label,"data-everfur-inbox-r
46
46
  /* @__PURE__ */jsxs("article",{style:styles.detail,children:[
47
47
  /* @__PURE__ */jsx(Heading,{style:styles.heading,children:detailTitle(detail.item,copy)}),
48
48
  /* @__PURE__ */jsx(DetailTime,{item:detail.item,now:now,copy:copy,styles:styles}),detail.item.body.length>0?/* @__PURE__ */jsx("p",{style:styles.detailBody,children:detail.item.body}):null]})]})}function detailTitle(item,copy){return item.title.trim().length>0?item.title:copy.rowFallbackTitle}function DetailTime({item:item,now:now,copy:copy,styles:styles}){let time=formatInboxTime(item.createdAt,now,copy.now);return time===null?null:/* @__PURE__ */jsxs("p",{style:styles.time,children:[
49
- /* @__PURE__ */jsx("time",{dateTime:item.createdAt,children:time}),inboxTimeTakesAgo(time)?/* @__PURE__ */jsx("span",{style:VISUALLY_HIDDEN,children:` ${copy.timeAgoSuffix}`}):null]})}function makeInboxStyles(theme){let{color:color,radius:radius,space:space,type:type,slots:slots2}=theme,lineHeight=(size,ratio)=>`${Math.round(size*ratio)}px`,button={minHeight:48,padding:`0 ${space.lg}px`,borderRadius:radius.pill,cursor:"pointer",...faceCss(theme,"bold"),fontSize:type.size.body},row={boxSizing:"border-box",display:"flex",alignItems:"flex-start",gap:space.sm,width:"100%",minHeight:48,margin:0,padding:`${space.md}px ${space.lg}px`,border:"none",borderRadius:radius.md,backgroundColor:"transparent",color:color.text.primary,textAlign:"start",cursor:"pointer",...faceCss(theme,"regular")},dot={flex:"none",width:8,height:8,marginTop:Math.round((type.size.body*type.lineHeight.normal-8)/2),borderRadius:radius.pill},title={flex:1,minWidth:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.snug),color:color.text.primary,overflowWrap:"anywhere"},bar={display:"block",height:type.size.body,borderRadius:radius.xs,backgroundColor:color.skeleton};return{root:{...SURFACE_ROOT_RESET,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.md,width:"100%",padding:space.lg,borderRadius:radius.lg,backgroundColor:color.surface,color:color.text.primary,...faceCss(theme,"regular"),...slotCss(slots2.card)},heading:{margin:0,...headingFaceCss(theme,"bold"),fontSize:type.size.heading,lineHeight:lineHeight(type.size.heading,type.lineHeight.snug),color:color.text.primary},list:{display:"flex",flexDirection:"column",gap:space.xs,margin:0,padding:0,listStyle:"none"},item:{margin:0,padding:0},row:row,rowUnread:{...row,backgroundColor:color.brandSofter},dot:{...dot,backgroundColor:color.brand},dotRead:{...dot,backgroundColor:"transparent"},rowText:{display:"flex",flexDirection:"column",gap:space.xs,flex:1,minWidth:0},rowTop:{display:"flex",alignItems:"baseline",gap:space.sm},rowTitle:{...title,...faceCss(theme,"medium")},rowTitleUnread:{...title,...faceCss(theme,"bold")},rowBody:{fontSize:type.size.bodyTight,lineHeight:lineHeight(type.size.bodyTight,type.lineHeight.normal),color:color.text.secondary,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",overflowWrap:"anywhere"},time:{flex:"none",margin:0,fontSize:type.size.caption,lineHeight:lineHeight(type.size.caption,type.lineHeight.normal),color:color.text.timestamp},state:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm,padding:`${space.xl}px ${space.lg}px`,textAlign:"center"},stateTitle:{margin:0,...faceCss(theme,"bold"),fontSize:type.size.subtitle,lineHeight:lineHeight(type.size.subtitle,type.lineHeight.snug),color:color.text.primary},stateBody:{margin:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.normal),color:color.text.secondary},primary:{...button,marginTop:space.xs,border:"none",backgroundColor:color.brand,color:color.text.onBrand,...slotCss(slots2.primaryButton)},secondary:{...button,alignSelf:"center",border:`1px solid ${color.brandBorder}`,backgroundColor:"transparent",color:color.brandInk},back:{...button,alignSelf:"flex-start",padding:`0 ${space.sm}px`,border:"none",backgroundColor:"transparent",color:color.brandInk,...slotCss(slots2.link)},detail:{display:"flex",flexDirection:"column",gap:space.sm},detailBody:{margin:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.relaxed),color:color.text.primary,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},skeletonRow:{display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.md}px ${space.lg}px`},skeletonTitle:{...bar,width:"60%"},skeletonBody:{...bar,width:"90%",height:type.size.bodyTight}}}var INBOX_UNREAD_REFRESH_KEY="everfur-inbox-unread";function useInboxUnreadState(lifecycle){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),store=useMemo(()=>userRef===null?null:inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),[runtime,userRef,scopeEpoch]),subscribe=useCallback(listener=>store===null?()=>{}:store.subscribe(listener),[store]),read=useCallback(()=>store===null?null:store.get(),[store]),unreadCount=useSyncExternalStore(subscribe,read,read),refresh=useCallback(()=>store===null?Promise.resolve():store.refresh(),[store]);return useEffect(()=>{refresh()},[refresh]),useChatLifecycle(store===null?void 0:lifecycle,{conversationId:store===null?null:INBOX_UNREAD_REFRESH_KEY,isTurnInFlight:false,refresh:refresh}),useMemo(()=>({unreadCount:unreadCount,refresh:refresh}),[unreadCount,refresh])}function useEverfurInboxUnread(options={}){let{lifecycle:lifecycle}=options,port=useMemo(()=>lifecycle===void 0?createInboxBrowserLifecycle():lifecycle??void 0,[lifecycle]);return useInboxUnreadState(port)}var BASE="/widget/v1/notifications/web-push",URL_MAX=2048,KEY_MAX=256,TIMEZONE_MAX=64,LOCALE_MAX=35,BASE64URL=/^[A-Za-z0-9_-]+={0,2}$/,SUBSCRIPTION_ID=/^wps_[A-Za-z0-9_-]{1,64}$/,LOCAL_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]);function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed2(call){return makeEverfurError("internalError",{retryable:false,wireMessage:`${call}: the response was not the documented shape`})}function disposed2(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function hintsRefused(error){return error.httpStatus===400&&error.code==="validationFailed"}function withoutHints(body){let rest={...body};return delete rest.timezone,delete rest.locale,rest}function webPushUrl(value){if(typeof value!="string"||value.length===0||value.length>URL_MAX)return null;let url;try{url=new URL(value)}catch{return null}return url.protocol==="https:"||url.protocol==="http:"&&LOCAL_HOSTS.has(url.hostname)?url.href:null}function key(value){return typeof value=="string"&&value.length>0&&value.length<=KEY_MAX&&BASE64URL.test(value)}function bounded(value,max){return typeof value=="string"&&value.length>0&&value.length<=max?value:null}function validate(input){if(typeof input!="object"||input===null)return invalid2("subscribe needs an input object");let{endpoint:endpoint,keys:keys,openUrl:openUrl,timezone:timezone,locale:locale}=input,endpointHref=webPushUrl(endpoint);if(endpointHref===null||!endpointHref.startsWith("https:"))return invalid2("endpoint must be the https endpoint of a push subscription");if(typeof keys!="object"||keys===null||!key(keys.p256dh)||!key(keys.auth))return invalid2("keys must carry the subscription p256dh and auth keys (base64url)");let open=webPushUrl(openUrl);return open===null?invalid2("openUrl must be an https URL of your page"):{body:{endpoint:endpointHref,keys:{p256dh:keys.p256dh,auth:keys.auth},open_url:open,timezone:bounded(timezone,TIMEZONE_MAX),locale:bounded(locale,LOCALE_MAX)}}}function createWebPushClient(runtime){let over=()=>{let{services:services}=runtime.registry;return createWebPushClientOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed2(verb)));return{config:opts=>runtime.isDisposed?gone("config"):over().config(opts),subscribe:input=>runtime.isDisposed?gone("subscribe"):over().subscribe(input),unsubscribe:id=>runtime.isDisposed?gone("unsubscribe"):over().unsubscribe(id)}}function createWebPushClientOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async config(opts){let res=await funnel.send("webPush.config",{method:"GET",path:`${BASE}/config`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return res;let vapid=res.value?.vapid_public_key;return key(vapid)?ok(/* @__PURE__ */Object.freeze({vapidPublicKey:vapid})):err(malformed2("webPush.config"))},async subscribe(input){let checked=validate(input);if(!("body"in checked))return err(checked);let send=body=>funnel.send("webPush.subscribe",{method:"POST",path:`${BASE}/subscriptions`,body:body}),res=await send(checked.body);if(!res.ok&&hintsRefused(res.error)&&(checked.body.timezone!==null||checked.body.locale!==null)&&(res=await send(withoutHints(checked.body))),!res.ok)return res;let id=res.value?.subscription_id;return typeof id=="string"&&SUBSCRIPTION_ID.test(id)?ok(/* @__PURE__ */Object.freeze({subscriptionId:id})):err(malformed2("webPush.subscribe"))},async unsubscribe(subscriptionId){if(typeof subscriptionId!="string"||!SUBSCRIPTION_ID.test(subscriptionId))return err(invalid2("subscriptionId must be a web push subscription id (wps_...)"));let res=await funnel.send("webPush.unsubscribe",{method:"DELETE",path:`${BASE}/subscriptions/${subscriptionId}`});return res.ok?ok(void 0):err(res.error)}}}var LOGOUT_HOOK_BUDGET_MS=3e3;function wireCodeOf2(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}var DEFAULT_SERVICE_WORKER_PATH="/everfur-sw.js",SCOPE_DIRECTORY="everfur-push/",STORE_KEY="everfur.webPush.v1";function applicationServerKeyFromBase64Url(key2){let padded=key2.replace(/=+$/,"").replace(/-/g,"+").replace(/_/g,"/"),base64=padded+"=".repeat((4-padded.length%4)%4),binary=atob(base64),bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index+=1)bytes[index]=binary.charCodeAt(index);return bytes}function ownerTag(userRef){let hash=2166136261;for(let index=0;index<userRef.length;index+=1)hash^=userRef.charCodeAt(index),hash=Math.imul(hash,16777619)>>>0;return hash.toString(16).padStart(8,"0")}function webPushScope(serviceWorkerPath,scope){if(scope!==void 0)return scope;let path=serviceWorkerPath.split("?")[0]??serviceWorkerPath;return`${path.slice(0,path.lastIndexOf("/")+1)}${SCOPE_DIRECTORY}`}function pageOnly(url){return url.split(/[?#]/)[0]??url}function localStore(){let storage=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}};return{read(){try{let raw=storage()?.getItem(STORE_KEY);if(raw==null)return null;let parsed=JSON.parse(raw),owner=parsed?.owner,subscriptionId=parsed?.subscriptionId,endpoint=parsed?.endpoint;return typeof owner!="string"||typeof subscriptionId!="string"||typeof endpoint!="string"?null:{owner:owner,subscriptionId:subscriptionId,endpoint:endpoint}}catch{return null}},write(entry){try{storage()?.setItem(STORE_KEY,JSON.stringify(entry))}catch{}},clear(){try{storage()?.removeItem(STORE_KEY)}catch{}}}}function browserWebPush(){try{let g=globalThis,container=g.navigator?.serviceWorker,notification=g.Notification;if(container===void 0||notification===void 0||g.PushManager===void 0||g.isSecureContext===!1)return null;let asRegistration=value=>typeof value=="object"&&value!==null&&"pushManager"in value?value:null;return{permission:()=>notification.permission,requestPermission:()=>notification.requestPermission(),async register(path,scope){let registration=asRegistration(await container.register(path,{scope:scope}));return registration!==null&&await waitForActive(registration),registration},async existing(scope){return asRegistration(await container.getRegistration(scope))},pageUrl:()=>g.location?.href??"",timeZone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{return null}},locale:()=>typeof g.navigator?.language=="string"&&g.navigator.language.length>0?g.navigator.language:null}}catch{return null}}function waitForActive(registration){let reg=registration,worker=reg.active?null:reg.installing??reg.waiting??null;return worker===null?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,1e4);worker.addEventListener("statechange",()=>{(worker.state==="activated"||worker.state==="redundant")&&(clearTimeout(timer),resolve())})})}var WEB_PUSH_UNAVAILABLE="web_push_unavailable",OUTCOME_BY_PERMISSION=/* @__PURE__ */Object.freeze({default:"dismissed",denied:"denied"});function createWebPushController(deps){let{client:client}=deps,browser=deps.browser===void 0?browserWebPush():deps.browser,store=deps.store??localStore(),owner=ownerTag(deps.userRef),path=deps.options?.serviceWorkerPath??DEFAULT_SERVICE_WORKER_PATH,scope=webPushScope(path,deps.options?.scope),available=null,openUrl=()=>{let page=browser?.pageUrl()??"",open=webPushUrl(deps.options?.openUrl??pageOnly(page));return open===null?null:originOf(open)===originOf(page)?open:(warnOnce(`Everfur web push: openUrl ${originOf(open)??""} is not this page's origin (${originOf(page)??"unknown"}). The service worker opens only its own origin; pass an openUrl on this origin.`),null)},notOffered=error=>error.httpStatus===404?(available=false,true):wireCodeOf2(error)!==WEB_PUSH_UNAVAILABLE?false:(error.raw?.retryable!==true&&(available=false),true),currentSubscription=async()=>{if(browser===null)return null;let registration=await browser.existing(scope).catch(()=>null);return registration===null?null:registration.pushManager.getSubscription().catch(()=>null)},dropForeign=async subscription=>{subscription!==null&&await subscription.unsubscribe().catch(()=>false),store.clear()},register=async subscription=>{let json=subscription.toJSON(),p256dh=json.keys?.p256dh,auth=json.keys?.auth,endpoint=json.endpoint??subscription.endpoint,open=openUrl();if(typeof p256dh!="string"||typeof auth!="string"||typeof endpoint!="string"||open===null||browser===null)return"failed";let res=await client.subscribe({endpoint:endpoint,keys:{p256dh:p256dh,auth:auth},openUrl:open,timezone:browser.timeZone(),locale:browser.locale()});return res.ok?(store.write({owner:owner,subscriptionId:res.value.subscriptionId,endpoint:endpoint}),"ok"):notOffered(res.error)?"unavailable":"failed"},probe=async()=>{if(available!==null)return available;let res=await client.config();if(res.ok)available=true;else if(notOffered(res.error))return false;return available??true};return{async state(){try{if(browser===null)return"unsupported";let permission=browser.permission();if(permission==="denied")return"denied";if(!await probe())return"unavailable";if(permission==="default")return"ask";let subscription=await currentSubscription(),stored=store.read();return subscription!==null&&stored!==null&&stored.owner===owner&&stored.endpoint===subscription.endpoint?"on":"off"}catch{return browser===null?"unsupported":"off"}},async enable(){if(browser===null)return"unsupported";if(available===false)return"unavailable";if(openUrl()===null)return"failed";try{let permission=browser.permission()==="granted"?"granted":await browser.requestPermission();if(permission!=="granted")return OUTCOME_BY_PERMISSION[permission];let registration=await browser.register(path,scope);if(registration===null)return"failed";let config=await client.config();if(!config.ok)return notOffered(config.error)?"unavailable":"failed";available=!0;let existing=await registration.pushManager.getSubscription().catch(()=>null),stored=store.read(),subscription=existing;existing!==null&&(stored===null||stored.owner!==owner)&&(await dropForeign(existing),subscription=null),subscription??=await registration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:applicationServerKeyFromBase64Url(config.value.vapidPublicKey)});let outcome=await register(subscription);return outcome==="ok"?"on":outcome}catch{return"failed"}},async disable(){try{let subscription=await currentSubscription(),stored=store.read();if(stored!==null&&stored.owner===owner){let res=await client.unsubscribe(stored.subscriptionId);if(!res.ok&&res.error.httpStatus!==404)return!1}return subscription!==null&&await subscription.unsubscribe(),store.clear(),!0}catch{return false}},async sync(){try{if(browser===null||browser.permission()!=="granted")return"skipped";let subscription=await currentSubscription(),stored=store.read();if(subscription===null)return stored!==null&&(stored.owner===owner&&client.unsubscribe(stored.subscriptionId),store.clear()),"skipped";if(stored===null||stored.owner!==owner)return await dropForeign(subscription),"reset";let outcome=await register(subscription);return outcome==="ok"?"synced":outcome}catch{return"failed"}},async endForSignOut(signOutClient){try{let stored=store.read(),subscription=await currentSubscription();stored!==null&&stored.owner===owner&&await signOutClient.unsubscribe(stored.subscriptionId),subscription!==null&&await subscription.unsubscribe()}catch{}finally{store.clear()}}}}function originOf(url){try{return new URL(url).origin}catch{return null}}var warned=false;function warnOnce(message){if(warned)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}function useEverfurWebPush(options={}){let{runtime:runtime,userRef:userRef}=useEverfurContext(),{serviceWorkerPath:serviceWorkerPath,scope:scope,openUrl:openUrl}=options,settings=useMemo(()=>({...serviceWorkerPath===void 0?{}:{serviceWorkerPath:serviceWorkerPath},...scope===void 0?{}:{scope:scope},...openUrl===void 0?{}:{openUrl:openUrl}}),[serviceWorkerPath,scope,openUrl]),controller=useMemo(()=>userRef===null?null:createWebPushController({client:createWebPushClient(runtime),userRef:userRef,options:settings}),[runtime,userRef,settings]),[status,setStatus]=useState(controller===null?"signed_out":"checking"),[busy,setBusy]=useState(false),current=useRef(controller);current.current=controller,useEffect(()=>{if(controller===null){setStatus("signed_out");return}let live=true;return setStatus("checking"),(async()=>{await controller.sync();let next=await controller.state();live&&setStatus(next)})(),()=>{live=false}},[controller]),useEffect(()=>runtime.onBeforeLogout(async({userRef:leaving,auth:auth})=>{let funnel=createRequestFunnel({auth:auth,maxAttempts:1,unaryTimeoutMs:LOGOUT_HOOK_BUDGET_MS,...runtime.registry.services.errorPolicy?{errorPolicy:runtime.registry.services.errorPolicy}:{}});await createWebPushController({client:createWebPushClient(runtime),userRef:leaving,options:settings}).endForSignOut(createWebPushClientOver({auth:auth,funnel:funnel}))}),[runtime,settings]);let enable=useCallback(()=>{let mine=current.current;return mine===null?Promise.resolve("failed"):(setBusy(true),mine.enable().then(async outcome=>{let next=await mine.state();return current.current===mine&&(setStatus(next),setBusy(false)),outcome}))},[]),disable=useCallback(async()=>{let mine=current.current;if(mine===null)return false;setBusy(true);let done=await mine.disable(),next=await mine.state();return current.current===mine&&(setStatus(next),setBusy(false)),done},[]);return useMemo(()=>({status:status,busy:busy,enable:enable,disable:disable}),[status,busy,enable,disable])}function tapTarget(ref){return ref.route==null||ref.eventId===null?null:parseEverfurNotification({v:1,event_id:ref.eventId,event_type:ref.route.event_type,target:ref.route.target})?.target??null}var addressTap=null,ADDRESS_TAPS=/* @__PURE__ */new WeakSet;function takeAddressTap(){let taken=takeNotificationOpenFrom(typeof window>"u"?void 0:window);return taken!==null&&(addressTap=taken,ADDRESS_TAPS.add(taken)),taken}function takeEverfurNotificationEventId(){return takeAddressTap()?.eventId??null}function takeEverfurNotificationOpen(){return takeAddressTap()}function firstTap(given){if(given===void 0)return takeAddressTap()??addressTap;if(given===null||typeof given=="string")return addressTap!==null&&addressTap.eventId===given?addressTap:given===null?null:{eventId:given,itemId:null};let tap=notificationOpenOf(given);return tap!==null&&addressTap!==null&&addressTap.eventId===tap.eventId&&addressTap.itemId===tap.itemId?addressTap:tap}function useEverfurNotificationOpen(options){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=useEverfurInboxClient(),onOpen=useRef(options.onOpen);onOpen.current=options.onOpen;let pending=useRef(null);if(pending.current===null){let first=firstTap(options.eventId);pending.current=first===null?[]:[first]}let queue=pending,flush=useRef(()=>{});useEffect(()=>onNotificationMessage(ref=>{queue.current.push(ref),flush.current()}),[]),useEffect(()=>{if(userRef===null)return;let live=true,started=/* @__PURE__ */new Set,unread=inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),controller=createInboxController({client:client,onUnreadCount:count2=>unread.report(count2)}),run=()=>{for(let ref of queue.current)started.has(ref)||(started.add(ref),controller.open({...ref.itemId===null?{}:{itemId:ref.itemId},...ref.eventId===null?{}:{eventId:ref.eventId}}).then(res=>{let at2=queue.current.indexOf(ref);if(!live||at2<0)return;if(queue.current.splice(at2,1),ref===addressTap)addressTap=null;else if(ADDRESS_TAPS.has(ref))return;let inbox=res.ok?res.value:null;callHost(onOpen.current,{eventId:ref.eventId,itemId:ref.itemId,inbox:inbox,target:inbox===null?tapTarget(ref):null})}))};return flush.current=run,run(),()=>{live=false,flush.current=()=>{},controller.dispose()}},[client,userRef,runtime,scopeEpoch])}export{EverfurInbox,createInboxClient,createWebPushClient,takeEverfurNotificationEventId,takeEverfurNotificationOpen,useEverfurInbox,useEverfurInboxClient,useEverfurInboxUnread,useEverfurNotificationOpen,useEverfurWebPush};
49
+ /* @__PURE__ */jsx("time",{dateTime:item.createdAt,children:time}),inboxTimeTakesAgo(time)?/* @__PURE__ */jsx("span",{style:VISUALLY_HIDDEN,children:` ${copy.timeAgoSuffix}`}):null]})}function makeInboxStyles(theme){let{color:color,radius:radius,space:space,type:type,slots:slots2}=theme,lineHeight=(size,ratio)=>`${Math.round(size*ratio)}px`,button={minHeight:48,padding:`0 ${space.lg}px`,borderRadius:radius.pill,cursor:"pointer",...faceCss(theme,"bold"),fontSize:type.size.body},row={boxSizing:"border-box",display:"flex",alignItems:"flex-start",gap:space.sm,width:"100%",minHeight:48,margin:0,padding:`${space.md}px ${space.lg}px`,border:"none",borderRadius:radius.md,backgroundColor:"transparent",color:color.text.primary,textAlign:"start",cursor:"pointer",...faceCss(theme,"regular")},dot={flex:"none",width:8,height:8,marginTop:Math.round((type.size.body*type.lineHeight.normal-8)/2),borderRadius:radius.pill},title={flex:1,minWidth:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.snug),color:color.text.primary,overflowWrap:"anywhere"},bar={display:"block",height:type.size.body,borderRadius:radius.xs,backgroundColor:color.skeleton};return{root:{...SURFACE_ROOT_RESET,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.md,width:"100%",padding:space.lg,borderRadius:radius.lg,backgroundColor:color.surface,color:color.text.primary,...faceCss(theme,"regular"),...slotCss(slots2.card)},heading:{margin:0,...headingFaceCss(theme,"bold"),fontSize:type.size.heading,lineHeight:lineHeight(type.size.heading,type.lineHeight.snug),color:color.text.primary},list:{display:"flex",flexDirection:"column",gap:space.xs,margin:0,padding:0,listStyle:"none"},item:{margin:0,padding:0},row:row,rowUnread:{...row,backgroundColor:color.brandSofter},dot:{...dot,backgroundColor:color.brand},dotRead:{...dot,backgroundColor:"transparent"},rowText:{display:"flex",flexDirection:"column",gap:space.xs,flex:1,minWidth:0},rowTop:{display:"flex",alignItems:"baseline",gap:space.sm},rowTitle:{...title,...faceCss(theme,"medium")},rowTitleUnread:{...title,...faceCss(theme,"bold")},rowBody:{fontSize:type.size.bodyTight,lineHeight:lineHeight(type.size.bodyTight,type.lineHeight.normal),color:color.text.secondary,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",overflowWrap:"anywhere"},time:{flex:"none",margin:0,fontSize:type.size.caption,lineHeight:lineHeight(type.size.caption,type.lineHeight.normal),color:color.text.timestamp},state:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm,padding:`${space.xl}px ${space.lg}px`,textAlign:"center"},stateTitle:{margin:0,...faceCss(theme,"bold"),fontSize:type.size.subtitle,lineHeight:lineHeight(type.size.subtitle,type.lineHeight.snug),color:color.text.primary},stateBody:{margin:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.normal),color:color.text.secondary},primary:{...button,marginTop:space.xs,border:"none",backgroundColor:color.brand,color:color.text.onBrand,...slotCss(slots2.primaryButton)},secondary:{...button,alignSelf:"center",border:`1px solid ${color.brandBorder}`,backgroundColor:"transparent",color:color.brandInk},back:{...button,alignSelf:"flex-start",padding:`0 ${space.sm}px`,border:"none",backgroundColor:"transparent",color:color.brandInk,...slotCss(slots2.link)},detail:{display:"flex",flexDirection:"column",gap:space.sm},detailBody:{margin:0,fontSize:type.size.body,lineHeight:lineHeight(type.size.body,type.lineHeight.relaxed),color:color.text.primary,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},skeletonRow:{display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.md}px ${space.lg}px`},skeletonTitle:{...bar,width:"60%"},skeletonBody:{...bar,width:"90%",height:type.size.bodyTight}}}var INBOX_UNREAD_REFRESH_KEY="everfur-inbox-unread";function useInboxUnreadState(lifecycle){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),store=useMemo(()=>userRef===null?null:inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),[runtime,userRef,scopeEpoch]),subscribe=useCallback(listener=>store===null?()=>{}:store.subscribe(listener),[store]),read=useCallback(()=>store===null?null:store.get(),[store]),unreadCount=useSyncExternalStore(subscribe,read,read),refresh=useCallback(()=>store===null?Promise.resolve():store.refresh(),[store]);return useEffect(()=>{refresh()},[refresh]),useChatLifecycle(store===null?void 0:lifecycle,{conversationId:store===null?null:INBOX_UNREAD_REFRESH_KEY,isTurnInFlight:false,refresh:refresh}),useMemo(()=>({unreadCount:unreadCount,refresh:refresh}),[unreadCount,refresh])}function useEverfurInboxUnread(options={}){let{lifecycle:lifecycle}=options,port=useMemo(()=>lifecycle===void 0?createInboxBrowserLifecycle():lifecycle??void 0,[lifecycle]);return useInboxUnreadState(port)}var BASE="/widget/v1/notifications/web-push",URL_MAX=2048,KEY_MAX=256,TIMEZONE_MAX=64,LOCALE_MAX=35,BASE64URL=/^[A-Za-z0-9_-]+={0,2}$/,SUBSCRIPTION_ID=/^wps_[A-Za-z0-9_-]{1,64}$/,LOCAL_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]);function invalid2(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed2(call){return makeEverfurError("internalError",{retryable:false,wireMessage:`${call}: the response was not the documented shape`})}function disposed2(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}function hintsRefused(error){return error.httpStatus===400&&error.code==="validationFailed"}function withoutHints(body){let rest={...body};return delete rest.timezone,delete rest.locale,rest}function webPushUrl(value){if(typeof value!="string"||value.length===0||value.length>URL_MAX)return null;let url;try{url=new URL(value)}catch{return null}return url.protocol==="https:"||url.protocol==="http:"&&LOCAL_HOSTS.has(url.hostname)?url.href:null}function key(value){return typeof value=="string"&&value.length>0&&value.length<=KEY_MAX&&BASE64URL.test(value)}function bounded(value,max){return typeof value=="string"&&value.length>0&&value.length<=max?value:null}function validate(input){if(typeof input!="object"||input===null)return invalid2("subscribe needs an input object");let{endpoint:endpoint,keys:keys,openUrl:openUrl,timezone:timezone,locale:locale}=input,endpointHref=webPushUrl(endpoint);if(endpointHref===null||!endpointHref.startsWith("https:"))return invalid2("endpoint must be the https endpoint of a push subscription");if(typeof keys!="object"||keys===null||!key(keys.p256dh)||!key(keys.auth))return invalid2("keys must carry the subscription p256dh and auth keys (base64url)");let open=webPushUrl(openUrl);return open===null?invalid2("openUrl must be an https URL of your page"):{body:{endpoint:endpointHref,keys:{p256dh:keys.p256dh,auth:keys.auth},open_url:open,timezone:bounded(timezone,TIMEZONE_MAX),locale:bounded(locale,LOCALE_MAX)}}}function createWebPushClient(runtime){let over=()=>{let{services:services}=runtime.registry;return createWebPushClientOver({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},gone=verb=>Promise.resolve(err(disposed2(verb)));return{config:opts=>runtime.isDisposed?gone("config"):over().config(opts),subscribe:input=>runtime.isDisposed?gone("subscribe"):over().subscribe(input),unsubscribe:id=>runtime.isDisposed?gone("unsubscribe"):over().unsubscribe(id)}}function createWebPushClientOver(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async config(opts){let res=await funnel.send("webPush.config",{method:"GET",path:`${BASE}/config`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return res;let vapid=res.value?.vapid_public_key;return key(vapid)?ok(/* @__PURE__ */Object.freeze({vapidPublicKey:vapid})):err(malformed2("webPush.config"))},async subscribe(input){let checked=validate(input);if(!("body"in checked))return err(checked);let send=body=>funnel.send("webPush.subscribe",{method:"POST",path:`${BASE}/subscriptions`,body:body}),res=await send(checked.body);if(!res.ok&&hintsRefused(res.error)&&(checked.body.timezone!==null||checked.body.locale!==null)&&(res=await send(withoutHints(checked.body))),!res.ok)return res;let id=res.value?.subscription_id;return typeof id=="string"&&SUBSCRIPTION_ID.test(id)?ok(/* @__PURE__ */Object.freeze({subscriptionId:id})):err(malformed2("webPush.subscribe"))},async unsubscribe(subscriptionId){if(typeof subscriptionId!="string"||!SUBSCRIPTION_ID.test(subscriptionId))return err(invalid2("subscriptionId must be a web push subscription id (wps_...)"));let res=await funnel.send("webPush.unsubscribe",{method:"DELETE",path:`${BASE}/subscriptions/${subscriptionId}`});return res.ok?ok(void 0):err(res.error)}}}var LOGOUT_HOOK_BUDGET_MS=3e3;function wireCodeOf2(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}var DEFAULT_SERVICE_WORKER_PATH="/everfur-sw.js",SCOPE_DIRECTORY="everfur-push/",STORE_KEY="everfur.webPush.v1";function applicationServerKeyFromBase64Url(key2){let padded=key2.replace(/=+$/,"").replace(/-/g,"+").replace(/_/g,"/"),base64=padded+"=".repeat((4-padded.length%4)%4),binary=atob(base64),bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index+=1)bytes[index]=binary.charCodeAt(index);return bytes}function ownerTag(userRef){let hash=2166136261;for(let index=0;index<userRef.length;index+=1)hash^=userRef.charCodeAt(index),hash=Math.imul(hash,16777619)>>>0;return hash.toString(16).padStart(8,"0")}function webPushScope(serviceWorkerPath,scope){if(scope!==void 0)return scope;let path=serviceWorkerPath.split("?")[0]??serviceWorkerPath;return`${path.slice(0,path.lastIndexOf("/")+1)}${SCOPE_DIRECTORY}`}function pageOnly(url){return url.split(/[?#]/)[0]??url}function localStore(){let storage=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}};return{read(){try{let raw=storage()?.getItem(STORE_KEY);if(raw==null)return null;let parsed=JSON.parse(raw),owner=parsed?.owner,subscriptionId=parsed?.subscriptionId,endpoint=parsed?.endpoint;return typeof owner!="string"||typeof subscriptionId!="string"||typeof endpoint!="string"?null:{owner:owner,subscriptionId:subscriptionId,endpoint:endpoint}}catch{return null}},write(entry){try{storage()?.setItem(STORE_KEY,JSON.stringify(entry))}catch{}},clear(){try{storage()?.removeItem(STORE_KEY)}catch{}}}}function browserWebPush(){try{let g=globalThis,container=g.navigator?.serviceWorker,notification=g.Notification;if(container===void 0||notification===void 0||g.PushManager===void 0||g.isSecureContext===!1)return null;let asRegistration=value=>typeof value=="object"&&value!==null&&"pushManager"in value?value:null;return{permission:()=>notification.permission,requestPermission:()=>notification.requestPermission(),async register(path,scope){let registration=asRegistration(await container.register(path,{scope:scope}));return registration!==null&&await waitForActive(registration),registration},async existing(scope){return asRegistration(await container.getRegistration(scope))},pageUrl:()=>g.location?.href??"",timeZone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch{return null}},locale:()=>typeof g.navigator?.language=="string"&&g.navigator.language.length>0?g.navigator.language:null}}catch{return null}}function waitForActive(registration){let reg=registration,worker=reg.active?null:reg.installing??reg.waiting??null;return worker===null?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,1e4);worker.addEventListener("statechange",()=>{(worker.state==="activated"||worker.state==="redundant")&&(clearTimeout(timer),resolve())})})}var WEB_PUSH_UNAVAILABLE="web_push_unavailable",OUTCOME_BY_PERMISSION=/* @__PURE__ */Object.freeze({default:"dismissed",denied:"denied"});function createWebPushController(deps){let{client:client}=deps,browser=deps.browser===void 0?browserWebPush():deps.browser,store=deps.store??localStore(),owner=ownerTag(deps.userRef),path=deps.options?.serviceWorkerPath??DEFAULT_SERVICE_WORKER_PATH,scope=webPushScope(path,deps.options?.scope),available=null,openUrl=()=>{let page=browser?.pageUrl()??"",open=webPushUrl(deps.options?.openUrl??pageOnly(page));return open===null?null:originOf(open)===originOf(page)?open:(warnOnce(`Everfur web push: openUrl ${originOf(open)??""} is not this page's origin (${originOf(page)??"unknown"}). The service worker opens only its own origin; pass an openUrl on this origin.`),null)},notOffered=error=>error.httpStatus===404?(available=false,true):wireCodeOf2(error)!==WEB_PUSH_UNAVAILABLE?false:(error.raw?.retryable!==true&&(available=false),true),currentSubscription=async()=>{if(browser===null)return null;let registration=await browser.existing(scope).catch(()=>null);return registration===null?null:registration.pushManager.getSubscription().catch(()=>null)},dropForeign=async subscription=>{subscription!==null&&await subscription.unsubscribe().catch(()=>false),store.clear()},register=async subscription=>{let json=subscription.toJSON(),p256dh=json.keys?.p256dh,auth=json.keys?.auth,endpoint=json.endpoint??subscription.endpoint,open=openUrl();if(typeof p256dh!="string"||typeof auth!="string"||typeof endpoint!="string"||open===null||browser===null)return"failed";let res=await client.subscribe({endpoint:endpoint,keys:{p256dh:p256dh,auth:auth},openUrl:open,timezone:browser.timeZone(),locale:browser.locale()});return res.ok?(store.write({owner:owner,subscriptionId:res.value.subscriptionId,endpoint:endpoint}),"ok"):notOffered(res.error)?"unavailable":"failed"},probe=async()=>{if(available!==null)return available;let res=await client.config();if(res.ok)available=true;else if(notOffered(res.error))return false;return available??true};return{async state(){try{if(browser===null)return"unsupported";let permission=browser.permission();if(permission==="denied")return"denied";if(!await probe())return"unavailable";if(permission==="default")return"ask";let subscription=await currentSubscription(),stored=store.read();return subscription!==null&&stored!==null&&stored.owner===owner&&stored.endpoint===subscription.endpoint?"on":"off"}catch{return browser===null?"unsupported":"off"}},async enable(){if(browser===null)return"unsupported";if(available===false)return"unavailable";if(openUrl()===null)return"failed";try{let permission=browser.permission()==="granted"?"granted":await browser.requestPermission();if(permission!=="granted")return OUTCOME_BY_PERMISSION[permission];let registration=await browser.register(path,scope);if(registration===null)return"failed";let config=await client.config();if(!config.ok)return notOffered(config.error)?"unavailable":"failed";available=!0;let existing=await registration.pushManager.getSubscription().catch(()=>null),stored=store.read(),subscription=existing;existing!==null&&(stored===null||stored.owner!==owner)&&(await dropForeign(existing),subscription=null),subscription??=await registration.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:applicationServerKeyFromBase64Url(config.value.vapidPublicKey)});let outcome=await register(subscription);return outcome==="ok"?"on":outcome}catch{return"failed"}},async disable(){try{let subscription=await currentSubscription(),stored=store.read();if(stored!==null&&stored.owner===owner){let res=await client.unsubscribe(stored.subscriptionId);if(!res.ok&&res.error.httpStatus!==404)return!1}return subscription!==null&&await subscription.unsubscribe(),store.clear(),!0}catch{return false}},async sync(){try{if(browser===null||browser.permission()!=="granted")return"skipped";let subscription=await currentSubscription(),stored=store.read();if(subscription===null)return stored!==null&&(stored.owner===owner&&client.unsubscribe(stored.subscriptionId),store.clear()),"skipped";if(stored===null||stored.owner!==owner)return await dropForeign(subscription),"reset";let outcome=await register(subscription);return outcome==="ok"?"synced":outcome}catch{return"failed"}},async endForSignOut(signOutClient){try{let stored=store.read(),subscription=await currentSubscription();stored!==null&&stored.owner===owner&&await signOutClient.unsubscribe(stored.subscriptionId),subscription!==null&&await subscription.unsubscribe()}catch{}finally{store.clear()}}}}function originOf(url){try{return new URL(url).origin}catch{return null}}var warned=false;function warnOnce(message){if(warned)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}var signOutSettings=/* @__PURE__ */new WeakMap;function useEverfurWebPush(options={}){let{runtime:runtime,userRef:userRef}=useEverfurContext(),{serviceWorkerPath:serviceWorkerPath,scope:scope,openUrl:openUrl}=options,settings=useMemo(()=>({...serviceWorkerPath===void 0?{}:{serviceWorkerPath:serviceWorkerPath},...scope===void 0?{}:{scope:scope},...openUrl===void 0?{}:{openUrl:openUrl}}),[serviceWorkerPath,scope,openUrl]),controller=useMemo(()=>userRef===null?null:createWebPushController({client:createWebPushClient(runtime),userRef:userRef,options:settings}),[runtime,userRef,settings]),[status,setStatus]=useState(controller===null?"signed_out":"checking"),[busy,setBusy]=useState(false),current=useRef(controller);current.current=controller,useEffect(()=>{if(controller===null){setStatus("signed_out");return}let live=true;return setStatus("checking"),(async()=>{await controller.sync();let next=await controller.state();live&&setStatus(next)})(),()=>{live=false}},[controller]),useEffect(()=>{signOutSettings.has(runtime)||runtime.onBeforeLogout(async({userRef:leaving,auth:auth})=>{let funnel=createRequestFunnel({auth:auth,maxAttempts:1,unaryTimeoutMs:LOGOUT_HOOK_BUDGET_MS,...runtime.registry.services.errorPolicy?{errorPolicy:runtime.registry.services.errorPolicy}:{}}),leavingClient=createWebPushClientOver({auth:auth,funnel:funnel});await createWebPushController({client:leavingClient,userRef:leaving,options:signOutSettings.get(runtime)}).endForSignOut(leavingClient)}),signOutSettings.set(runtime,settings)},[runtime,settings]);let enable=useCallback(()=>{let mine=current.current;return mine===null?Promise.resolve("failed"):(setBusy(true),mine.enable().then(async outcome=>{let next=await mine.state();return current.current===mine&&(setStatus(next),setBusy(false)),outcome}))},[]),disable=useCallback(async()=>{let mine=current.current;if(mine===null)return false;setBusy(true);let done=await mine.disable(),next=await mine.state();return current.current===mine&&(setStatus(next),setBusy(false)),done},[]);return useMemo(()=>({status:status,busy:busy,enable:enable,disable:disable}),[status,busy,enable,disable])}function tapTarget(ref){return ref.route==null||ref.eventId===null?null:parseEverfurNotification({v:1,event_id:ref.eventId,event_type:ref.route.event_type,target:ref.route.target})?.target??null}var addressTap=null,ADDRESS_TAPS=/* @__PURE__ */new WeakSet;function takeAddressTap(){let taken=takeNotificationOpenFrom(typeof window>"u"?void 0:window);return taken!==null&&(addressTap=taken,ADDRESS_TAPS.add(taken)),taken}function takeEverfurNotificationEventId(){return takeAddressTap()?.eventId??null}function takeEverfurNotificationOpen(){return takeAddressTap()}function firstTap(given){if(given===void 0)return takeAddressTap()??addressTap;if(given===null||typeof given=="string")return addressTap!==null&&addressTap.eventId===given?addressTap:given===null?null:{eventId:given,itemId:null};let tap=notificationOpenOf(given);return tap!==null&&addressTap!==null&&addressTap.eventId===tap.eventId&&addressTap.itemId===tap.itemId?addressTap:tap}function useEverfurNotificationOpen(options){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=useEverfurInboxClient(),onOpen=useRef(options.onOpen);onOpen.current=options.onOpen;let pending=useRef(null);if(pending.current===null){let first=firstTap(options.eventId);pending.current=first===null?[]:[first]}let queue=pending,flush=useRef(()=>{});useEffect(()=>onNotificationMessage(ref=>{queue.current.push(ref),flush.current()}),[]),useEffect(()=>{if(userRef===null)return;let live=true,started=/* @__PURE__ */new Set,unread=inboxUnreadStoreFor(runtime,inboxUnreadScope(userRef,scopeEpoch)),controller=createInboxController({client:client,onUnreadCount:count2=>unread.report(count2)}),run=()=>{for(let ref of queue.current)started.has(ref)||(started.add(ref),controller.open({...ref.itemId===null?{}:{itemId:ref.itemId},...ref.eventId===null?{}:{eventId:ref.eventId}}).then(res=>{let at2=queue.current.indexOf(ref);if(!live||at2<0)return;if(queue.current.splice(at2,1),ref===addressTap)addressTap=null;else if(ADDRESS_TAPS.has(ref))return;let inbox=res.ok?res.value:null;callHost(onOpen.current,{eventId:ref.eventId,itemId:ref.itemId,inbox:inbox,target:inbox===null?tapTarget(ref):null})}))};return flush.current=run,run(),()=>{live=false,flush.current=()=>{},controller.dispose()}},[client,userRef,runtime,scopeEpoch])}export{EverfurInbox,createInboxClient,createWebPushClient,takeEverfurNotificationEventId,takeEverfurNotificationOpen,useEverfurInbox,useEverfurInboxClient,useEverfurInboxUnread,useEverfurNotificationOpen,useEverfurWebPush};