@everfur/sdk 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/dist/{Chat.d-BHovj6Ku.d.ts → Chat.d-CoGJrK3t.d.ts} +1 -1
- package/dist/{Chat.d-BO-XtVYe.d.cts → Chat.d-JDtlG_EW.d.cts} +1 -1
- package/dist/{DepthViews.d-DKoZgF8l.d.ts → DepthViews.d-CNQn-eEr.d.ts} +1 -1
- package/dist/{DepthViews.d-CBUunxP1.d.ts → DepthViews.d-D31VlFKU.d.ts} +1 -1
- package/dist/{DepthViews.d-BwIkdmWZ.d.cts → DepthViews.d-XTv4s3ru.d.cts} +1 -1
- package/dist/{DepthViews.d-Bx85LeiP.d.cts → DepthViews.d-zxM_xbP9.d.cts} +1 -1
- package/dist/{RecordsPage.d-DRFp2LXH.d.cts → RecordsPage.d-CSZHrtWJ.d.cts} +11 -5
- package/dist/{RecordsPage.d-CsvBhU0f.d.ts → RecordsPage.d-D_y-ZB3S.d.ts} +11 -5
- package/dist/animations/index.d.cts +3 -3
- package/dist/animations/index.d.ts +3 -3
- package/dist/{attachments.d-DWUsHPf9.d.cts → attachments.d-D74wbmQU.d.cts} +1 -1
- package/dist/{attachments.d-DOZjCdkb.d.ts → attachments.d-Dm6NUJTR.d.ts} +1 -1
- package/dist/{bookingCopy.d-BlMWlvgv.d.ts → bookingCopy.d-DMmLKY5Q.d.ts} +2 -2
- package/dist/{bookingCopy.d-tvO7y6MK.d.cts → bookingCopy.d-iaYDPvPd.d.cts} +2 -2
- package/dist/{casesRepository.d-C7qbrOL-.d.ts → casesRepository.d-CCJJQXnl.d.ts} +1 -1
- package/dist/{casesRepository.d-sSo6oakf.d.cts → casesRepository.d-G2dahIKO.d.cts} +1 -1
- package/dist/chat/index.d.cts +10 -10
- package/dist/chat/index.d.ts +10 -10
- package/dist/chat/lite/index.d.cts +10 -10
- package/dist/chat/lite/index.d.ts +10 -10
- package/dist/{chatHandoffToken.d-C4tEyuCT.d.ts → chatHandoffToken.d-DVv9tl8h.d.ts} +5 -5
- package/dist/{chatHandoffToken.d-D6GUoBvs.d.cts → chatHandoffToken.d-xmnHrTA5.d.cts} +5 -5
- package/dist/{chatTypes.d-CSyw9em_.d.cts → chatTypes.d-CQC7GTdE.d.cts} +4 -4
- package/dist/{chatTypes.d-BI4vidgu.d.ts → chatTypes.d-hS1AilYl.d.ts} +4 -4
- package/dist/chunk-2NA7TPUA.js +5 -0
- package/dist/chunk-IJU5TV5N.js +12 -0
- package/dist/chunk-TFX6WMDN.js +30 -0
- package/dist/chunk-WZNPR5TY.js +34 -0
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +6 -6
- package/dist/client/index.d.ts +6 -6
- package/dist/client/index.js +1 -1
- package/dist/{clinicBatch.d-BxA_uGBb.d.cts → clinicBatch.d-4PFwKJfw.d.cts} +3 -3
- package/dist/{clinicBatch.d-T5oSAhY-.d.ts → clinicBatch.d-BpP2NBb3.d.ts} +3 -3
- package/dist/{clinicRequestProps.d-CjsMg_OD.d.ts → clinicRequestProps.d-BuMuGoVZ.d.ts} +1 -1
- package/dist/{clinicRequestProps.d-1dCtouGA.d.cts → clinicRequestProps.d-DjzUdDFx.d.cts} +1 -1
- package/dist/{config.d-N5Xzy53V.d.ts → config.d-D9igq-vT.d.ts} +1 -1
- package/dist/{config.d-jCmrhM4a.d.cts → config.d-cX5E6DAw.d.cts} +1 -1
- package/dist/consent/index.cjs +1 -1
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/consent/index.js +1 -1
- package/dist/{context.d-l4HkFJI8.d.cts → context.d-BrRRNw9I.d.cts} +4 -4
- package/dist/{context.d-BJEpEERH.d.ts → context.d-hPfsEsNf.d.ts} +4 -4
- package/dist/{copy.d-hFRaovog.d.ts → copy.d-CDlirTR4.d.ts} +2 -2
- package/dist/{copy.d-hS49oJ4w.d.cts → copy.d-DWjSkbrZ.d.cts} +2 -2
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.d.cts +14 -14
- package/dist/core/index.d.ts +14 -14
- package/dist/core/index.js +1 -1
- package/dist/{depth.d-C99_xup2.d.ts → depth.d-CfBorxcQ.d.ts} +3 -3
- package/dist/{depth.d-BYwddMNU.d.cts → depth.d-KkrGx98U.d.cts} +3 -3
- package/dist/{entitlementRepository.d-CiU_QIPL.d.cts → entitlementRepository.d-BvnWpcQH.d.cts} +2 -2
- package/dist/{entitlementRepository.d-qZAlET7C.d.ts → entitlementRepository.d-DpQrIgW6.d.ts} +2 -2
- package/dist/{focus.d-RJMXplJc.d.cts → focus.d-9loikWy8.d.cts} +2 -2
- package/dist/{focus.d-CG6KhDBK.d.ts → focus.d-CYwVLDvR.d.ts} +2 -2
- package/dist/health-plan/index.cjs +53 -37
- package/dist/health-plan/index.d.cts +10 -10
- package/dist/health-plan/index.d.ts +10 -10
- package/dist/health-plan/index.js +54 -38
- package/dist/{idempotency.d-DJyOZDPb.d.cts → idempotency.d-CVKkUhY4.d.cts} +1 -1
- package/dist/{idempotency.d-D-ZWpO9p.d.ts → idempotency.d-DGQ_xML5.d.ts} +1 -1
- package/dist/{identity.d-CA7mW59I.d.cts → identity.d-Bnl5Z0MM.d.cts} +1 -1
- package/dist/{identity.d-DIOnFzXL.d.ts → identity.d-DR5YwO6E.d.ts} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +13 -13
- package/dist/index.d.ts +13 -13
- package/dist/index.js +1 -1
- package/dist/{introEvents.d-BjqfFgE1.d.ts → introEvents.d-D_yL7lnE.d.ts} +1 -1
- package/dist/{introEvents.d-7wNDMhEF.d.cts → introEvents.d-JmPqEqMQ.d.cts} +1 -1
- package/dist/{models.d-BSqvbTE1.d.cts → models.d-BN53M9sU.d.cts} +52 -1
- package/dist/{models.d-DOwnr8fi.d.ts → models.d-Bhq9p6Wa.d.ts} +52 -1
- package/dist/notifications/inbox/index.d.cts +4 -4
- package/dist/notifications/inbox/index.d.ts +4 -4
- package/dist/notifications/index.d.cts +7 -7
- package/dist/notifications/index.d.ts +7 -7
- package/dist/{optInView.d-BQhHPleh.d.cts → optInView.d-BizcW_QG.d.cts} +2 -2
- package/dist/{optInView.d-B5v4cDDW.d.ts → optInView.d-CZvKlq-o.d.ts} +2 -2
- package/dist/{pets.d-DRqMaP8A.d.cts → pets.d-C4CWxQPh.d.cts} +1 -1
- package/dist/{pets.d-DVrOb-Bj.d.ts → pets.d-uCzgFbGi.d.ts} +1 -1
- package/dist/{petsRepository.d-tZADfKA1.d.cts → petsRepository.d-DOcVv9bd.d.cts} +1 -1
- package/dist/{petsRepository.d-CpYWRWFq.d.ts → petsRepository.d-DRW7NkKm.d.ts} +1 -1
- package/dist/records/depth/index.cjs +1 -1
- package/dist/records/depth/index.d.cts +11 -11
- package/dist/records/depth/index.d.ts +11 -11
- package/dist/records/depth/index.js +1 -1
- package/dist/records/index.cjs +16 -14
- package/dist/records/index.d.cts +47 -17
- package/dist/records/index.d.ts +47 -17
- package/dist/records/index.js +16 -14
- package/dist/{requestFunnel.d-B8OVGh0p.d.ts → requestFunnel.d-BYLycQMI.d.ts} +2 -2
- package/dist/{requestFunnel.d-C4abgvt9.d.cts → requestFunnel.d-CQ0O8fMG.d.cts} +2 -2
- package/dist/{route.d-BAZqGLfl.d.ts → route.d-DFJ0gXj8.d.ts} +2 -2
- package/dist/{route.d-CTf8h9vS.d.cts → route.d-q9yndhFy.d.cts} +2 -2
- package/dist/{runtimeTypes.d-DbaQKGLv.d.cts → runtimeTypes.d-3LRuzxr7.d.cts} +4 -4
- package/dist/{runtimeTypes.d-DrIz5e6L.d.ts → runtimeTypes.d-BJHYj2MI.d.ts} +4 -4
- package/dist/{screenProps.d-Di3wYGCn.d.cts → screenProps.d-DfAmuKkr.d.cts} +2 -2
- package/dist/{screenProps.d-BP8LAZWn.d.ts → screenProps.d-tVzlXGaN.d.ts} +2 -2
- package/dist/server/events/index.cjs +1 -1
- package/dist/server/events/index.d.cts +2 -2
- package/dist/server/events/index.d.ts +2 -2
- package/dist/server/events/index.js +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +3 -3
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +1 -1
- package/dist/{sheetSeam.d-BBuEIVsa.d.cts → sheetSeam.d-B9iQqG_I.d.cts} +2 -2
- package/dist/{sheetSeam.d-B09jf4YC.d.ts → sheetSeam.d-CtuKILqp.d.ts} +2 -2
- package/dist/shop/index.cjs +187 -145
- package/dist/shop/index.d.cts +3 -3
- package/dist/shop/index.d.ts +3 -3
- package/dist/shop/index.js +188 -146
- package/dist/tabs/index.cjs +1 -1
- package/dist/tabs/index.d.cts +8 -8
- package/dist/tabs/index.d.ts +8 -8
- package/dist/tabs/index.js +1 -1
- package/dist/televet/booking/index.d.cts +6 -6
- package/dist/televet/booking/index.d.ts +6 -6
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/rn/index.d.cts +8 -8
- package/dist/testing/rn/index.d.ts +8 -8
- package/dist/testing/web/index.d.cts +9 -9
- package/dist/testing/web/index.d.ts +9 -9
- package/dist/texting/index.d.cts +5 -5
- package/dist/texting/index.d.ts +5 -5
- package/dist/{threadOptions.d-Cwmyu8pc.d.ts → threadOptions.d-DfH26dy7.d.ts} +2 -2
- package/dist/{threadOptions.d-REwBuXAY.d.cts → threadOptions.d-I6G3BdlP.d.cts} +2 -2
- package/dist/{timelineRows.d-CTlGQTB0.d.ts → timelineRows.d-CugnCOfZ.d.ts} +1 -1
- package/dist/{timelineRows.d-CongJG58.d.cts → timelineRows.d-uSfr2IP3.d.cts} +1 -1
- package/dist/{types.d-d3RdaeAA.d.cts → types.d-BOKzNuuF.d.cts} +87 -85
- package/dist/{types.d-d3RdaeAA.d.ts → types.d-BOKzNuuF.d.ts} +87 -85
- package/dist/ui/index.cjs +98 -46
- package/dist/ui/index.d.cts +4 -3
- package/dist/ui/index.d.ts +4 -3
- package/dist/ui/index.js +98 -46
- package/dist/{useHealthPlanSubscription.d-BSo5kFT9.d.ts → useHealthPlanSubscription.d-CVVQIFpG.d.ts} +2 -2
- package/dist/{useHealthPlanSubscription.d-Br7GKHTt.d.cts → useHealthPlanSubscription.d-DylPMm_m.d.cts} +2 -2
- package/dist/{useInboxUnread.d-Blxu00eY.d.ts → useInboxUnread.d-DDoSII8D.d.ts} +1 -1
- package/dist/{useInboxUnread.d-pi6FNnK-.d.cts → useInboxUnread.d-Dq3CCAa3.d.cts} +1 -1
- package/dist/{usePresentation.d-yd9Gh4GB.d.ts → usePresentation.d-CDNK4MDY.d.ts} +2 -2
- package/dist/{usePresentation.d-C6ci1s3j.d.cts → usePresentation.d-CrobH0d_.d.cts} +2 -2
- package/dist/{useRecords.d-BYNX01El.d.cts → useRecords.d-BMSW4aRD.d.cts} +46 -3
- package/dist/{useRecords.d-DWk61a4c.d.ts → useRecords.d-Cv1nhZrv.d.ts} +46 -3
- package/dist/{useRecordsDepth.d-C5snbNxR.d.ts → useRecordsDepth.d-BvBYIPii.d.ts} +1 -1
- package/dist/{useRecordsDepth.d-BIDVPfx7.d.cts → useRecordsDepth.d-Cd5Vyb7D.d.cts} +1 -1
- package/dist/{useUnread.d-CORommFJ.d.cts → useUnread.d-B4Yqcteg.d.cts} +3 -3
- package/dist/{useUnread.d-w0dKMnx7.d.ts → useUnread.d-ElAEfgl1.d.ts} +3 -3
- package/dist/{view.d-CK2UN4qn.d.ts → view.d-2RWoY9kd.d.ts} +5 -5
- package/dist/{view.d-DUhKppyl.d.cts → view.d-utmOR2ee.d.cts} +5 -5
- package/dist/web/consent/index.cjs +1 -1
- package/dist/web/consent/index.d.cts +5 -5
- package/dist/web/consent/index.d.ts +5 -5
- package/dist/web/consent/index.js +1 -1
- package/dist/web/health-plan/index.cjs +43 -16
- package/dist/web/health-plan/index.d.cts +12 -12
- package/dist/web/health-plan/index.d.ts +12 -12
- package/dist/web/health-plan/index.js +32 -27
- package/dist/web/health-plan/styles.css +160 -1
- package/dist/web/inbox/index.cjs +1 -1
- package/dist/web/inbox/index.d.cts +5 -5
- package/dist/web/inbox/index.d.ts +5 -5
- package/dist/web/inbox/index.js +1 -1
- package/dist/web/index.cjs +1 -1
- package/dist/web/index.d.cts +27 -27
- package/dist/web/index.d.ts +27 -27
- package/dist/web/index.js +1 -1
- package/dist/web/intro/index.cjs +1 -1
- package/dist/web/intro/index.d.cts +8 -8
- package/dist/web/intro/index.d.ts +8 -8
- package/dist/web/intro/index.js +1 -1
- package/dist/web/notifications/index.d.cts +6 -6
- package/dist/web/notifications/index.d.ts +6 -6
- package/dist/web/records/depth/index.cjs +1 -1
- package/dist/web/records/depth/index.d.cts +11 -11
- package/dist/web/records/depth/index.d.ts +11 -11
- package/dist/web/records/depth/index.js +1 -1
- package/dist/web/records/index.cjs +15 -13
- package/dist/web/records/index.d.cts +43 -19
- package/dist/web/records/index.d.ts +43 -19
- package/dist/web/records/index.js +15 -13
- package/dist/web/records-sheet/index.cjs +1 -1
- package/dist/web/records-sheet/index.d.cts +4 -4
- package/dist/web/records-sheet/index.d.ts +4 -4
- package/dist/web/records-sheet/index.js +1 -1
- package/dist/web/shop/index.cjs +110 -88
- package/dist/web/shop/index.d.cts +3 -3
- package/dist/web/shop/index.d.ts +3 -3
- package/dist/web/shop/index.js +67 -81
- package/dist/web/televet/booking/index.d.cts +6 -6
- package/dist/web/televet/booking/index.d.ts +6 -6
- package/dist/web/texting/index.d.cts +5 -5
- package/dist/web/texting/index.d.ts +5 -5
- package/dist/web/ui/index.cjs +96 -57
- package/dist/web/ui/index.d.cts +4 -3
- package/dist/web/ui/index.d.ts +4 -3
- package/dist/web/ui/index.js +41 -46
- package/dist/web/ui/styles.css +481 -1
- package/package.json +5 -5
- package/dist/chunk-Y3Q4GW47.js +0 -31
package/dist/web/inbox/index.cjs
CHANGED
|
@@ -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-
|
|
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-
|
|
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-Dq3CCAa3.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-Dq3CCAa3.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-
|
|
13
|
-
export { I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-
|
|
12
|
+
import { A as AuthContext } from '../../identity.d-Bnl5Z0MM.cjs';
|
|
13
|
+
export { I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-Bnl5Z0MM.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-
|
|
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-cX5E6DAw.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-
|
|
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-
|
|
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-DDoSII8D.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-DDoSII8D.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-
|
|
13
|
-
export { I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-
|
|
12
|
+
import { A as AuthContext } from '../../identity.d-DR5YwO6E.js';
|
|
13
|
+
export { I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-DR5YwO6E.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-
|
|
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-D9igq-vT.js';
|
|
16
16
|
export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode } from '../../EverfurError.d-8NHtlgzA.js';
|
|
17
17
|
|
|
18
18
|
interface EverfurInboxProps {
|
package/dist/web/inbox/index.js
CHANGED
|
@@ -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};
|
package/dist/web/index.cjs
CHANGED
|
@@ -10,7 +10,7 @@ return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversati
|
|
|
10
10
|
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:fields.serverRequestId??null})}function analysisStartedFrame(requestId,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
11
11
|
return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
|
|
12
12
|
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:fields.resultId,analysisType:fields.analysisType,modelVersion:fields.modelVersion,confidence:fields.confidence,detections:/* @__PURE__ */Object.freeze([...fields.detections]),interpretation:fields.interpretation,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function unknownFrame(raw,lastEventId,serverRequestId=null){/* @__PURE__ */
|
|
13
|
-
return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function 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 createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}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}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}function createFallbackUtf8Decoder(){let pending3=[];return{decode(input,options){let stream=options?.stream===true,bytes=pending3.length>0?pending3.slice():[];if(input!==void 0)for(let i2=0;i2<input.length;i2+=1)bytes.push(input[i2]);pending3=[];let out="",i=0;for(;i<bytes.length;){let b0=bytes[i];if(b0<128){out+=String.fromCharCode(b0),i+=1;continue}let need,lower=128,upper=191,cp;if(b0>=194&&b0<=223)need=1,cp=b0&31;else if(b0>=224&&b0<=239)need=2,cp=b0&15,b0===224&&(lower=160),b0===237&&(upper=159);else if(b0>=240&&b0<=244)need=3,cp=b0&7,b0===240&&(lower=144),b0===244&&(upper=143);else{out+="�",i+=1;continue}let j=1,valid=true;for(;j<=need&&!(i+j>=bytes.length);){let b=bytes[i+j],lo=j===1?lower:128,hi=j===1?upper:191;if(b<lo||b>hi){valid=false;break}cp=cp<<6|b&63,j+=1}if(!valid){out+="�",i+=j;continue}if(j<=need){stream?pending3=bytes.slice(i):out+="�";break}out+=String.fromCodePoint(cp),i+=need+1}return out}}}function createUtf8Decoder(){let Native=globalThis.TextDecoder;return typeof Native=="function"?new Native("utf-8"):createFallbackUtf8Decoder()}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string(),/* @__PURE__ */zod.z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=createUtf8Decoder(),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function parseUrl(raw,base2){let Url=globalThis.URL;if(typeof Url=="function"){let url;try{url=base2===void 0?new Url(raw):new Url(raw,base2)}catch{return null}try{if(url.protocol)return url}catch{}}return parseByPattern(raw)}var WHOLE_URL=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,REWRITTEN_BY_STANDARD_PARSER=/[\s\u0000-\u001f\u007f\\]/,DEFAULT_PORTS={"http:":"80","https:":"443"};function parseByPattern(raw,base2){let input=raw.trim();let match=REWRITTEN_BY_STANDARD_PARSER.test(input)?null:WHOLE_URL.exec(input);if(match===null)return null;let[,scheme="",username="",password="",host2="",portText="",path="",query="",fragment=""]=match,protocol=`${scheme.toLowerCase()}:`,portNumber=Number(portText);if(portNumber>65535)return null;let port=portText===""||String(portNumber)===DEFAULT_PORTS[protocol]?"":String(portNumber),special=DEFAULT_PORTS[protocol]!==void 0,hostPort=host2.toLowerCase()+(port&&`:${port}`),pathname=path||(special?"/":""),credentials=username||password?`${username}${password&&`:${password}`}@`:"";return{href:`${protocol}//${credentials}${hostPort}${pathname}${query}${fragment}`,protocol:protocol,username:username,password:password,hostname:host2.toLowerCase(),port:port,origin:special?`${protocol}//${hostPort}`:"null",pathname:pathname,search:query==="?"?"":query,hash:fragment==="#"?"":fragment}}var SDK_VERSION="0.19.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
13
|
+
return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function 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 createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}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}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}function createFallbackUtf8Decoder(){let pending3=[];return{decode(input,options){let stream=options?.stream===true,bytes=pending3.length>0?pending3.slice():[];if(input!==void 0)for(let i2=0;i2<input.length;i2+=1)bytes.push(input[i2]);pending3=[];let out="",i=0;for(;i<bytes.length;){let b0=bytes[i];if(b0<128){out+=String.fromCharCode(b0),i+=1;continue}let need,lower=128,upper=191,cp;if(b0>=194&&b0<=223)need=1,cp=b0&31;else if(b0>=224&&b0<=239)need=2,cp=b0&15,b0===224&&(lower=160),b0===237&&(upper=159);else if(b0>=240&&b0<=244)need=3,cp=b0&7,b0===240&&(lower=144),b0===244&&(upper=143);else{out+="�",i+=1;continue}let j=1,valid=true;for(;j<=need&&!(i+j>=bytes.length);){let b=bytes[i+j],lo=j===1?lower:128,hi=j===1?upper:191;if(b<lo||b>hi){valid=false;break}cp=cp<<6|b&63,j+=1}if(!valid){out+="�",i+=j;continue}if(j<=need){stream?pending3=bytes.slice(i):out+="�";break}out+=String.fromCodePoint(cp),i+=need+1}return out}}}function createUtf8Decoder(){let Native=globalThis.TextDecoder;return typeof Native=="function"?new Native("utf-8"):createFallbackUtf8Decoder()}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string(),/* @__PURE__ */zod.z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=createUtf8Decoder(),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function parseUrl(raw,base2){let Url=globalThis.URL;if(typeof Url=="function"){let url;try{url=base2===void 0?new Url(raw):new Url(raw,base2)}catch{return null}try{if(url.protocol)return url}catch{}}return parseByPattern(raw)}var WHOLE_URL=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,REWRITTEN_BY_STANDARD_PARSER=/[\s\u0000-\u001f\u007f\\]/,DEFAULT_PORTS={"http:":"80","https:":"443"};function parseByPattern(raw,base2){let input=raw.trim();let match=REWRITTEN_BY_STANDARD_PARSER.test(input)?null:WHOLE_URL.exec(input);if(match===null)return null;let[,scheme="",username="",password="",host2="",portText="",path="",query="",fragment=""]=match,protocol=`${scheme.toLowerCase()}:`,portNumber=Number(portText);if(portNumber>65535)return null;let port=portText===""||String(portNumber)===DEFAULT_PORTS[protocol]?"":String(portNumber),special=DEFAULT_PORTS[protocol]!==void 0,hostPort=host2.toLowerCase()+(port&&`:${port}`),pathname=path||(special?"/":""),credentials=username||password?`${username}${password&&`:${password}`}@`:"";return{href:`${protocol}//${credentials}${hostPort}${pathname}${query}${fragment}`,protocol:protocol,username:username,password:password,hostname:host2.toLowerCase(),port:port,origin:special?`${protocol}//${hostPort}`:"null",pathname:pathname,search:query==="?"?"":query,hash:fragment==="#"?"":fragment}}var SDK_VERSION="0.21.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
14
14
|
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function checkPublishableKey(raw){let publishableKey=typeof raw=="string"?raw.trim():"";return publishableKey.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(publishableKey)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}function tryResolveClientConfig(config,options){let keyFailure=checkPublishableKey(config?.publishableKey);if(keyFailure!==null)/* @__PURE__ */
|
|
15
15
|
return Object.freeze({ok:false,failure:keyFailure});let publishableKey=config.publishableKey.trim(),baseUrl=tryResolveApiBaseUrl(config.apiBaseUrl);if(!baseUrl.ok)return baseUrl;let contractVersion=config.contractVersion?.trim()||DEFAULT_CONTRACT_VERSION;/* @__PURE__ */
|
|
16
16
|
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:publishableKey,apiBaseUrl:baseUrl.value,contractVersion:contractVersion,sdkVersion:SDK_VERSION,platform:options?.platform??SDK_PLATFORM,debug:config.debug===true})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host2){return host2.length===0||host2.includes("@")?false:host2.startsWith("[")&&host2.endsWith("]")?true:!host2.includes(":")}function canEchoOrigin(rawTrimmed,host2){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host2)}function safeOrigin(scheme,host2){return`${scheme}://${host2}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host2=hostOf(match[2]);if(host2.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host2)?`: ${safeOrigin(scheme,host2)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host2)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
|
package/dist/web/index.d.cts
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
1
1
|
/*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
|
|
2
2
|
import { ReactNode, CSSProperties } from 'react';
|
|
3
|
-
import { E as EverfurProviderProps } from '../context.d-
|
|
4
|
-
export { a as EverfurConfig, b as EverfurHandle, c as EverfurUser, U as UseEverfurPetProfileState, u as useCapability, d as useEverfur, e as useEverfurPetProfile, f as useEverfurTheme } from '../context.d-
|
|
3
|
+
import { E as EverfurProviderProps } from '../context.d-BrRRNw9I.cjs';
|
|
4
|
+
export { a as EverfurConfig, b as EverfurHandle, c as EverfurUser, U as UseEverfurPetProfileState, u as useCapability, d as useEverfur, e as useEverfurPetProfile, f as useEverfurTheme } from '../context.d-BrRRNw9I.cjs';
|
|
5
5
|
import { C as CapabilityName, a as CapabilityDecision } from '../resolve.d-BTC3b6FW.cjs';
|
|
6
6
|
export { b as CapabilityDisabled, D as DisabledLevel } from '../resolve.d-BTC3b6FW.cjs';
|
|
7
|
-
import { U as UrgencyDisplayLevel, E as EverfurChatDraftStore, b as ChatFollowUpPolicy, i as UseEverfurUnreadOptions, d as EverfurUnreadState } from '../chatHandoffToken.d-
|
|
8
|
-
export { C as ChatFeedbackReason, a as ChatFeedbackReasonOption, c as ChatSentiment, e as UseChatAttachmentsOptions, f as UseChatAttachmentsState, g as UseEverfurChatState, h as UseEverfurPetsState, j as chatHandoffTokenFromUrl, u as useChatAttachments, k as useEverfurChat, l as useEverfurPets } from '../chatHandoffToken.d-
|
|
7
|
+
import { U as UrgencyDisplayLevel, E as EverfurChatDraftStore, b as ChatFollowUpPolicy, i as UseEverfurUnreadOptions, d as EverfurUnreadState } from '../chatHandoffToken.d-xmnHrTA5.cjs';
|
|
8
|
+
export { C as ChatFeedbackReason, a as ChatFeedbackReasonOption, c as ChatSentiment, e as UseChatAttachmentsOptions, f as UseChatAttachmentsState, g as UseEverfurChatState, h as UseEverfurPetsState, j as chatHandoffTokenFromUrl, u as useChatAttachments, k as useEverfurChat, l as useEverfurPets } from '../chatHandoffToken.d-xmnHrTA5.cjs';
|
|
9
9
|
import { P as PetRef, C as ConversationId } from '../ids.d-B2GAAifq.cjs';
|
|
10
10
|
export { B as Brand, a as ClientId, b as ResponseId, U as UserRef, _ as __brand, c as conversationId, p as petRef, u as userRef } from '../ids.d-B2GAAifq.cjs';
|
|
11
|
-
import { a as ChatCheckinTarget } from '../chatTypes.d-
|
|
12
|
-
export { C as ChatCheckin, b as ChatConversation, c as ChatConversationListOptions, d as ChatConversationPage, e as ChatFeedbackReceipt, f as ChatFeedbackType, g as ChatHistoryOptions, j as ChatMessage, h as ChatMessagePage, k as ChatMessageRole, l as ChatMessageSender, i as ChatRefreshOptions, m as ChatStatus, n as Citation, S as SendOptions } from '../chatTypes.d-
|
|
11
|
+
import { a as ChatCheckinTarget } from '../chatTypes.d-CQC7GTdE.cjs';
|
|
12
|
+
export { C as ChatCheckin, b as ChatConversation, c as ChatConversationListOptions, d as ChatConversationPage, e as ChatFeedbackReceipt, f as ChatFeedbackType, g as ChatHistoryOptions, j as ChatMessage, h as ChatMessagePage, k as ChatMessageRole, l as ChatMessageSender, i as ChatRefreshOptions, m as ChatStatus, n as Citation, S as SendOptions } from '../chatTypes.d-CQC7GTdE.cjs';
|
|
13
13
|
import { i as EverfurPresentationInput } from '../presentation.d-Bs8xQ4gD.cjs';
|
|
14
14
|
export { D as DEFAULT_PRESENTATION, 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, l as EverfurPresentationField, j as EverfurSafetyDisclaimerPlacement, p as parsePresentation, r as resolvePresentation } from '../presentation.d-Bs8xQ4gD.cjs';
|
|
15
|
-
import { P as PetProfileInput } from '../petsRepository.d-
|
|
16
|
-
export { a as PetProfilePatch, R as RegisteredPet, W as WidgetPet, b as WidgetPetProfile } from '../petsRepository.d-
|
|
15
|
+
import { P as PetProfileInput } from '../petsRepository.d-DOcVv9bd.cjs';
|
|
16
|
+
export { a as PetProfilePatch, R as RegisteredPet, W as WidgetPet, b as WidgetPetProfile } from '../petsRepository.d-DOcVv9bd.cjs';
|
|
17
17
|
import { L as LifecyclePort } from '../LifecyclePort.d-Cr1p33a7.cjs';
|
|
18
18
|
import { E as EverfurStarterPrompt } from '../quickPrompts.d-NM_81Jc1.cjs';
|
|
19
|
-
import { E as EverfurChatEmptyState, a as EverfurChatHistoryBar, b as EverfurChatOpeningCard, c as EverfurChatAnswerCards, d as EverfurChatTopCard, e as EverfurChatHistorySheet, f as EverfurHealthPlanProps } from '../threadOptions.d-
|
|
20
|
-
export { g as EverfurChatAnswerCard, h as EverfurChatAnswerContext, i as EverfurChatFollowUpAction } from '../threadOptions.d-
|
|
21
|
-
import { e as HealthPlanTopCardResults } from '../usePresentation.d-
|
|
22
|
-
export { u as useEverfurPresentation } from '../usePresentation.d-
|
|
19
|
+
import { E as EverfurChatEmptyState, a as EverfurChatHistoryBar, b as EverfurChatOpeningCard, c as EverfurChatAnswerCards, d as EverfurChatTopCard, e as EverfurChatHistorySheet, f as EverfurHealthPlanProps } from '../threadOptions.d-I6G3BdlP.cjs';
|
|
20
|
+
export { g as EverfurChatAnswerCard, h as EverfurChatAnswerContext, i as EverfurChatFollowUpAction } from '../threadOptions.d-I6G3BdlP.cjs';
|
|
21
|
+
import { e as HealthPlanTopCardResults } from '../usePresentation.d-CrobH0d_.cjs';
|
|
22
|
+
export { u as useEverfurPresentation } from '../usePresentation.d-CrobH0d_.cjs';
|
|
23
23
|
import { E as EverfurChatEmptyHeaderContext } from '../threadOptions.d-CW51PyVd.cjs';
|
|
24
24
|
export { c as EverfurChatTopCardRow } from '../threadOptions.d-CW51PyVd.cjs';
|
|
25
|
-
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-
|
|
26
|
-
export { C as CheckinAnswer, a as CheckinOutcome, W as WatchCase } from '../casesRepository.d-
|
|
25
|
+
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-cX5E6DAw.cjs';
|
|
26
|
+
export { C as CheckinAnswer, a as CheckinOutcome, W as WatchCase } from '../casesRepository.d-G2dahIKO.cjs';
|
|
27
27
|
export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode, c as categoryFor, i as isRetryableCode, u as userFacingError } from '../EverfurError.d-8NHtlgzA.cjs';
|
|
28
28
|
export { E as EverfurUnread, P as PresignedPolicy, U as UploadPort } from '../unreadStore.d-w5x6lEpR.cjs';
|
|
29
|
-
export { A as AttachmentError, a as AttachmentErrorCode, b as AttachmentOutcome, c as AttachmentQueue, d as AttachmentState, e as AttachmentStatus } from '../attachments.d-
|
|
29
|
+
export { A as AttachmentError, a as AttachmentErrorCode, b as AttachmentOutcome, c as AttachmentQueue, d as AttachmentState, e as AttachmentStatus } from '../attachments.d-D74wbmQU.cjs';
|
|
30
30
|
import { U as UploadTransport, F as FileHandle } from '../ports.d-BX4f4UsB.cjs';
|
|
31
31
|
export { b as FilePort, a as UploadPolicyWire } from '../ports.d-BX4f4UsB.cjs';
|
|
32
|
-
import { C as CaptureRecordsSignature } from '../clinicRequestProps.d-
|
|
33
|
-
import { E as EverfurRecordsPageProps } from '../RecordsPage.d-
|
|
34
|
-
import { E as EverfurIntroCopy, a as EverfurIntroBlank, b as EverfurRecordsRequested, d as EverfurRecordsLanded } from '../introEvents.d-
|
|
32
|
+
import { C as CaptureRecordsSignature } from '../clinicRequestProps.d-DjzUdDFx.cjs';
|
|
33
|
+
import { E as EverfurRecordsPageProps } from '../RecordsPage.d-CSZHrtWJ.cjs';
|
|
34
|
+
import { E as EverfurIntroCopy, a as EverfurIntroBlank, b as EverfurRecordsRequested, d as EverfurRecordsLanded } from '../introEvents.d-JmPqEqMQ.cjs';
|
|
35
35
|
import { E as EverfurTabId, a as EverfurTabsCopy } from '../tabsModel.d-D9GWPFrL.cjs';
|
|
36
36
|
export { b as EVERFUR_TABS_COPY } from '../tabsModel.d-D9GWPFrL.cjs';
|
|
37
37
|
export { E as EVERFUR_RECORDS_LANDED_EVENT, a as EVERFUR_RECORDS_REQUESTED_EVENT } from '../introEvents.d-dS3fJCH1.cjs';
|
|
38
38
|
import { K as KvPort } from '../cacheEpoch.d-DknKn3S0.cjs';
|
|
39
39
|
export { I as ImageCachePort } from '../cacheEpoch.d-DknKn3S0.cjs';
|
|
40
|
-
export { E as EverfurClientEvent, a as EverfurEventHandler, L as LogLevel, b as LogRecord, c as LogSink, P as PrepareOptions, d as PrepareResult, e as PrepareStatus, S as SecureStorePort } from '../runtimeTypes.d-
|
|
40
|
+
export { E as EverfurClientEvent, a as EverfurEventHandler, L as LogLevel, b as LogRecord, c as LogSink, P as PrepareOptions, d as PrepareResult, e as PrepareStatus, S as SecureStorePort } from '../runtimeTypes.d-3LRuzxr7.cjs';
|
|
41
41
|
export { T as TelemetryPort } from '../TelemetryPort.d-BDNr00hu.cjs';
|
|
42
42
|
export { E as ErrorPolicyPort } from '../ErrorPolicyPort.d-DirW9hgO.cjs';
|
|
43
43
|
export { C as CameraPort, a as CaptureOptions, M as MediaSource } from '../CameraPort.d-Cv31Pz7g.cjs';
|
|
44
44
|
export { a as EverfurConfigError, E as EverfurResult, b as EverfurThrownError, i as isErr, c as isOk, u as unwrap } from '../EverfurResult.d-BFH-3s6E.cjs';
|
|
45
|
-
export { M as MintedToken, T as TokenProvider } from '../identity.d-
|
|
45
|
+
export { M as MintedToken, T as TokenProvider } from '../identity.d-Bnl5Z0MM.cjs';
|
|
46
46
|
export { E as EverfurFaceStyle, a as EverfurThemeAdjustment, f as face, h as headingFace, p as previewTheme, t as themeAdjustments } from '../typeStyle.d-Ckdh_S-t.cjs';
|
|
47
47
|
import { E as EverfurThemeInput } from '../branding.d-BFauULV6.cjs';
|
|
48
48
|
export { A as APPEARANCE_PRESETS, a as APPEARANCE_PRESET_NAMES, b as APPEARANCE_SIZE_RANGES, c as EverfurAppearance, d as EverfurAppearanceFont, e as EverfurAppearancePreset, f as EverfurAppearanceRules, g as EverfurAppearanceVariables, h as EverfurThemeFontFaceKey, i as EverfurThemeFontUrlsInput, j as EverfurThemeFontsInput, k as EverfurThemeSlotInput, l as EverfurThemeSlotsInput, m as expandAppearance } from '../branding.d-BFauULV6.cjs';
|
|
@@ -50,16 +50,16 @@ import { d as EverfurFontWeight, m as EverfurTheme, a as EverfurFontFaceKey } fr
|
|
|
50
50
|
export { E as EverfurColorTokens, b as EverfurFontFamilies, c as EverfurFontSource, e as EverfurLetterSpacingTokens, f as EverfurLineHeightTokens, g as EverfurMotionDurationTokens, h as EverfurMotionTokens, i as EverfurRadiusTokens, j as EverfurSpaceTokens, k as EverfurSpringToken, l as EverfurTextColorTokens, n as EverfurThemeMeta, o as EverfurThemeSlot, p as EverfurThemeSlotKey, q as EverfurThemeSlotName, r as EverfurThemeSlots, s as EverfurTypeSizeTokens, t as EverfurTypeTokens, u as EverfurWeightTokens, T as THEME_SLOT_KEYS, v as THEME_SLOT_KEYS_BY_SLOT, w as THEME_SLOT_NAMES, x as themeSlotKeysFor } from '../tokens.d-BUVqme2D.cjs';
|
|
51
51
|
export { b as PetActivityLevel, c as PetAllergy, d as PetAllergySeverity, e as PetBirthDatePrecision, f as PetCondition, a as PetHealthProfile, P as PetHealthProfileInput, g as PetIndoorOutdoor, h as PetMedication, i as PetSex } from '../profile.d-CSs1wlXT.cjs';
|
|
52
52
|
export { C as CanonicalPetSpecies, c as canonicalPetSpecies } from '../species.d-BXAIMh7I.cjs';
|
|
53
|
-
import '../requestFunnel.d-
|
|
54
|
-
import '../focus.d-
|
|
55
|
-
import '../models.d-
|
|
53
|
+
import '../requestFunnel.d-CQ0O8fMG.cjs';
|
|
54
|
+
import '../focus.d-9loikWy8.cjs';
|
|
55
|
+
import '../models.d-BN53M9sU.cjs';
|
|
56
56
|
import '../clinicModels.d-BXgKZqDb.cjs';
|
|
57
|
-
import '../useRecords.d-
|
|
57
|
+
import '../useRecords.d-BMSW4aRD.cjs';
|
|
58
58
|
import '../features.d-DrQxTw3-.cjs';
|
|
59
|
-
import '../screenProps.d-
|
|
60
|
-
import '../clinicBatch.d-
|
|
59
|
+
import '../screenProps.d-DfAmuKkr.cjs';
|
|
60
|
+
import '../clinicBatch.d-4PFwKJfw.cjs';
|
|
61
61
|
import '../recordsAsk.d-C5CGSi3j.cjs';
|
|
62
|
-
import '../sheetSeam.d-
|
|
62
|
+
import '../sheetSeam.d-B9iQqG_I.cjs';
|
|
63
63
|
|
|
64
64
|
/**
|
|
65
65
|
* Wrap the tree ONCE, high. Mounting constructs the runtime (transport, identity, registry,
|