@everfur/sdk 1.5.3 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/chat-cards/package.json +8 -0
  2. package/dist/{Chat.d-BCfyvzX8.d.ts → Chat.d-B4GybUU4.d.ts} +1 -1
  3. package/dist/{Chat.d-Od44h51D.d.cts → Chat.d-DPM2ncxi.d.cts} +1 -1
  4. package/dist/chat/index.cjs +174 -174
  5. package/dist/chat/index.d.cts +4 -4
  6. package/dist/chat/index.d.ts +4 -4
  7. package/dist/chat/index.js +340 -340
  8. package/dist/chat/lite/index.cjs +174 -174
  9. package/dist/chat/lite/index.d.cts +4 -4
  10. package/dist/chat/lite/index.d.ts +4 -4
  11. package/dist/chat/lite/index.js +339 -339
  12. package/dist/chat-cards/index.cjs +18 -0
  13. package/dist/chat-cards/index.d.cts +15 -0
  14. package/dist/chat-cards/index.d.ts +15 -0
  15. package/dist/chat-cards/index.js +18 -0
  16. package/dist/{chatHandoffToken.d-BjfmIxXk.d.cts → chatHandoffToken.d-Cap2z62P.d.cts} +1 -1
  17. package/dist/{chatHandoffToken.d-CFiI6IMc.d.ts → chatHandoffToken.d-zdp23Ukr.d.ts} +1 -1
  18. package/dist/{checkin.d-CokpahFL.d.ts → checkin.d-BoZXWjxX.d.ts} +8 -0
  19. package/dist/{checkin.d-BP3ZWBfX.d.cts → checkin.d-CuIUahcd.d.cts} +8 -0
  20. package/dist/{chunk-CFEHTNKX.js → chunk-6AIEUA4V.js} +1 -1
  21. package/dist/{chunk-OU5RMGKD.js → chunk-BN7OAFBS.js} +18 -18
  22. package/dist/{chunk-ZGL2GEEI.js → chunk-IXHLESYC.js} +1 -1
  23. package/dist/{chunk-XGF2HYNN.js → chunk-LMIBOI3I.js} +16 -16
  24. package/dist/client/index.cjs +1 -1
  25. package/dist/client/index.d.cts +1 -1
  26. package/dist/client/index.d.ts +1 -1
  27. package/dist/client/index.js +1 -1
  28. package/dist/{context.d-DS1GXUEY.d.ts → context.d-D7zX6Q0J.d.ts} +1 -1
  29. package/dist/{context.d-Bj6-xYPA.d.cts → context.d-guaLkx5t.d.cts} +1 -1
  30. package/dist/core/index.cjs +2 -2
  31. package/dist/core/index.d.cts +4 -4
  32. package/dist/core/index.d.ts +4 -4
  33. package/dist/core/index.js +2 -2
  34. package/dist/index.cjs +354 -354
  35. package/dist/index.d.cts +7 -7
  36. package/dist/index.d.ts +7 -7
  37. package/dist/index.js +364 -364
  38. package/dist/notifications/index.d.cts +3 -3
  39. package/dist/notifications/index.d.ts +3 -3
  40. package/dist/records/index.cjs +1 -1
  41. package/dist/records/index.js +1 -1
  42. package/dist/{route.d-DtuKY5dM.d.ts → route.d-B3u14HJT.d.ts} +1 -1
  43. package/dist/{route.d-Nt-r-7IO.d.cts → route.d-QBCoO62z.d.cts} +1 -1
  44. package/dist/{runtimeTypes.d-CL4l7ta4.d.cts → runtimeTypes.d-BSxuUCOX.d.cts} +1 -1
  45. package/dist/{runtimeTypes.d-BzUig75K.d.ts → runtimeTypes.d-hjN6xvxm.d.ts} +1 -1
  46. package/dist/server/events/index.cjs +1 -1
  47. package/dist/server/events/index.js +1 -1
  48. package/dist/server/index.cjs +1 -1
  49. package/dist/server/index.js +1 -1
  50. package/dist/testing/rn/index.d.cts +2 -2
  51. package/dist/testing/rn/index.d.ts +2 -2
  52. package/dist/testing/web/index.d.cts +2 -2
  53. package/dist/testing/web/index.d.ts +2 -2
  54. package/dist/{useUnread.d-CedFK4k6.d.ts → useUnread.d-4SbFChbd.d.ts} +30 -3
  55. package/dist/{useUnread.d-DST1GMmL.d.cts → useUnread.d-B0YhhR_D.d.cts} +30 -3
  56. package/dist/web/health-plan/index.cjs +1 -1
  57. package/dist/web/health-plan/index.js +1 -1
  58. package/dist/web/index.cjs +3 -3
  59. package/dist/web/index.d.cts +7 -7
  60. package/dist/web/index.d.ts +7 -7
  61. package/dist/web/index.js +3 -3
  62. package/dist/web/notifications/index.d.cts +2 -2
  63. package/dist/web/notifications/index.d.ts +2 -2
  64. package/dist/web/records-sheet/index.cjs +1 -1
  65. package/dist/web/records-sheet/index.js +1 -1
  66. package/dist/web/shop/index.cjs +1 -1
  67. package/dist/web/shop/index.js +1 -1
  68. package/dist/web/televet/booking/index.cjs +1 -1
  69. package/dist/web/televet/booking/index.js +1 -1
  70. package/dist/web/televet/call/index.cjs +1 -1
  71. package/dist/web/televet/call/index.js +1 -1
  72. package/dist/web/ui/index.cjs +1 -1
  73. package/dist/web/ui/index.js +32 -32
  74. package/package.json +16 -1
package/dist/web/index.js CHANGED
@@ -11,7 +11,7 @@ return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryab
11
11
  return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}function analysisCompleteFrame(e,t=null){/* @__PURE__ */
12
12
  return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:/* @__PURE__ */Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}function unknownFrame(e,t,r=null){/* @__PURE__ */
13
13
  return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var B="/widget/v1/anon-identity",N="x-everfur-anon-token",L="anonTokenInvalid";function U(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let l=null,i=null,o=null,a=null,s=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,d=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs-2592e5),c=()=>l!==null&&(l.ttlMs===null||s(l.mintedAtMs)<l.ttlMs)?l.token:null,f=()=>i||(i=(async()=>{try{let i=null,a={method:"POST",path:B,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{i=e("date")}},s=await e.request(a),u=s.ok?s.value:null,d=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return d===null?(o=n(),c()):(l={token:d,mintedAtMs:n(),ttlMs:U(u?.expires_at,i)},o=null,d)}catch{return o=n(),c()}finally{i=null}})(),i);return{token(e){return e?.forceRefresh?i||(u(a,3e4)?Promise.resolve(l?.token??null):(a=n(),l=null,f())):d()||u(o,3e5)?Promise.resolve(c()):f()}}}async function H(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}var W="This feature isn't available on your account right now.",q="Something in that request was not right. Check the details and try again.",V=/* @__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:W,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:q,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:W,runtimeDisposed:q,unknown:"Something went wrong. Please try again."}),K="This session has ended. Please sign in again.",G="linked_account_read_only";function Y(e,t,r){return e==="conflict"&&r===G?W:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?K:userFacingError(e)}function userFacingError(e){return V[e]}function Q(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var Z=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===G,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:Y(e,t?.wireCode,n?G:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&Z.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let i=t?.retryAfterSeconds;if(typeof i=="number"&&Number.isFinite(i)&&i>=0&&(l.retryAfterSeconds=Math.round(i)),r);return t?.wireMessage&&Q(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Q(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}function X(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(e,t,r,n){let l=null,i=false,o=null,a=false,s=()=>o||(o=(async()=>{try{let e=await t(),n=typeof e=="string"?e:e?.token;if(typeof n!="string"||n.length===0)throw new C("invalid-argument","TokenProvider returned an empty token");return l=n,i=!1,r?.(typeof e=="string"?null:J(e.expiresAt)),n}finally{o=null}})(),o);return{userRef:e,async currentToken(e){if(a)throw new C("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(l=null),l!==null?l:s()},hasToken(){return!a&&l!==null},clear(){a=true,l=null},reportRejected(){a||i||(i=true,n?.())}}}function J(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[N]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...ee(e.headers),...authHeaders(t)}}}function ee(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===N||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await H(t),n=await t.transport.request(withAuthHeaders(e,te(t,r)));if(n.ok||ne(n.error.raw)!==L||t.anonIdentity===void 0||t.userRef!==null)return n;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===r?n:t.transport.request(withAuthHeaders(e,te(t,l)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(X(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(X(e,{wireCode:ne(n.error.raw),requestId:n.error.requestId}))}let i=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!i.ok&&i.error.httpStatus===401?(t.identity.reportRejected?.(),err(re(i.error))):i}function te(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function re(e){let t=e.raw,r=ne(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function ne(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var le="DAILY_QUOTA_EXCEEDED",ie=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function oe(e,t){if(!ie.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?le:e}var ae="free_cap_reached";function se(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function ue(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==ae&&n.code!==ae)return null;let l=se(n.limit),i=se(n.used);if(l===null||i===null)return null;let o=n.resets_at,a=n.emergency_guidance;/* @__PURE__ */
14
- return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function de(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:ue(t)}function ce(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let d=1,c=true;for(;d<=r&&!(o+d>=l.length);){let e=l[o+d],t=d===1?a:128,r=d===1?s:191;if(e<t||e>r){c=false;break}u=u<<6|e&63,d+=1}if(!c){i+="�",o+=d;continue}if(d<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function fe(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):ce()}var pe=`\n\n`,he=1048576,ge=/* @__PURE__ */m.record(/* @__PURE__ */m.string(),/* @__PURE__ */m.unknown()),me=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=fe(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(pe,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+pe.length),o=0;let r=be(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>he){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=be(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function be(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=ge.safeParse(l);return i.success?ye(i.data,r,t):null}function ye(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:ve(e.code)??"unknown",retryable:e.retryable===true,wireMessage:ve(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:ue(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:ve(e.conversation_id)??"",messageId:ve(e.message_id),title:ve(e.title),followUpQuestions:Ce(e.follow_up_questions),citations:_e(e.citations),citationStatus:ve(e.citation_status),urgencyLevel:ke(e.urgency_level),urgencyReason:ve(e.urgency_reason),urgencyProvided:xe(e),resultId:ve(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(ve(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=ve(e.delta)??ve(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(ve(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:ve(e.result_id),analysisType:ve(e.analysis_type),modelVersion:ve(e.model_version),confidence:we(e.confidence),detections:_e(e.detections),interpretation:ve(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function ve(e){return typeof e=="string"?e:null}function we(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ke(e){return typeof e=="string"&&me.includes(e)?e:null}function xe(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||ke(t)!==null}function Ce(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function Se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _e(e){return Array.isArray(e)?e.filter(Se):[]}var Re=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Ie(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return Pe(e)}var ze=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,Te=/[\s\u0000-\u001f\u007f\\]/,Oe={"http:":"80","https:":"443"};function Pe(e,t){let r=e.trim();let n=Te.test(r)?null:ze.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",d="",c=""]=n,f=`${l.toLowerCase()}:`,p=Number(s);if(p>65535)return null;let h=s===""||String(p)===Oe[f]?"":String(p),g=Oe[f]!==void 0,m=a.toLowerCase()+(h&&`:${h}`),b=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${m}${b}${d}${c}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:h,origin:g?`${f}//${m}`:"null",pathname:b,search:d==="?"?"":d,hash:c==="#"?"":c}}function Ee(e,t,r){return{...e,surface:t,requestId:r||null}}var Fe=64,je=/^[A-Za-z0-9._+() -]+$/;function Ae(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Fe?null:je.test(t)?t:null}var Me="1.5.3";var $e="react-native",De="2026-09-19",Be="EVERFUR_API_BASE_URL";function Ne(e,t){/* @__PURE__ */
14
+ return Object.freeze({limit:l,used:i,resetsAt:typeof o=="string"&&o.length>0?o:null,...typeof a=="string"&&a.trim().length>0?{emergencyGuidance:a}:{}})}function de(e){let t=e.raw;if(typeof t!="object"||t===null)return null;let r=t.freeCap;return typeof r=="object"&&r!==null?r:ue(t)}function ce(){let e=[];return{decode(t,r){let n=r?.stream===true,l=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)l.push(t[e]);e=[];let i="",o=0;for(;o<l.length;){let t=l[o];if(t<128){i+=String.fromCharCode(t),o+=1;continue}let r,a=128,s=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(a=160),t===237&&(s=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(a=144),t===244&&(s=143);else{i+="�",o+=1;continue}let d=1,c=true;for(;d<=r&&!(o+d>=l.length);){let e=l[o+d],t=d===1?a:128,r=d===1?s:191;if(e<t||e>r){c=false;break}u=u<<6|e&63,d+=1}if(!c){i+="�",o+=d;continue}if(d<=r){n?e=l.slice(o):i+="�";break}i+=String.fromCodePoint(u),o+=r+1}return i}}}function fe(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):ce()}var pe=`\n\n`,he=1048576,ge=/* @__PURE__ */m.record(/* @__PURE__ */m.string(),/* @__PURE__ */m.unknown()),me=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),l=fe(),i="",o=0,a=false;for await(let t of e){for(i+=l.decode(t,{stream:true});;){let e=i.indexOf(pe,o);if(e===-1)break;let t=i.slice(0,e);i=i.slice(e+pe.length),o=0;let r=be(t,n());if(r!==null&&(r.kind==="delta"&&(a=true),yield r,r.terminal))return}if(o=i.length>0?i.length-1:0,i.length>he){yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(i+=l.decode(),i.trim().length>0){let e=be(i,n());if(e!==null&&(e.kind==="delta"&&(a=true),yield e,e.terminal))return}yield errorFrame({code:a?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function be(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let l;try{l=JSON.parse(n.join(`\n`))}catch{return null}if(typeof l!="object"||l===null||Array.isArray(l))return null;let i=ge.safeParse(l);return i.success?ye(i.data,r,t):null}function ye(e,t,r){let n=e.type,l=e.event;if(n==="error"||"error"in e)return errorFrame({code:ve(e.code)??"unknown",retryable:e.retryable===true,wireMessage:ve(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:ue(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:ve(e.conversation_id)??"",messageId:ve(e.message_id),title:ve(e.title),followUpQuestions:Ce(e.follow_up_questions),citations:_e(e.citations),citationStatus:ve(e.citation_status),urgencyLevel:ke(e.urgency_level),urgencyReason:ve(e.urgency_reason),urgencyProvided:xe(e),resultId:ve(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(ve(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=ve(e.delta)??ve(e.token)??"";return deltaFrame(n,t,r)}return l==="analysis_started"?analysisStartedFrame(ve(e.request_id),t,r):l==="analysis_complete"?analysisCompleteFrame({resultId:ve(e.result_id),analysisType:ve(e.analysis_type),modelVersion:ve(e.model_version),confidence:we(e.confidence),detections:_e(e.detections),interpretation:ve(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function ve(e){return typeof e=="string"?e:null}function we(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ke(e){return typeof e=="string"&&me.includes(e)?e:null}function xe(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||ke(t)!==null}function Ce(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function Se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _e(e){return Array.isArray(e)?e.filter(Se):[]}var Re=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Ie(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return Pe(e)}var ze=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,Te=/[\s\u0000-\u001f\u007f\\]/,Oe={"http:":"80","https:":"443"};function Pe(e,t){let r=e.trim();let n=Te.test(r)?null:ze.exec(r);if(n===null)return null;let[,l="",i="",o="",a="",s="",u="",d="",c=""]=n,f=`${l.toLowerCase()}:`,p=Number(s);if(p>65535)return null;let h=s===""||String(p)===Oe[f]?"":String(p),g=Oe[f]!==void 0,m=a.toLowerCase()+(h&&`:${h}`),b=u||(g?"/":""),y=i||o?`${i}${o&&`:${o}`}@`:"";return{href:`${f}//${y}${m}${b}${d}${c}`,protocol:f,username:i,password:o,hostname:a.toLowerCase(),port:h,origin:g?`${f}//${m}`:"null",pathname:b,search:d==="?"?"":d,hash:c==="#"?"":c}}function Ee(e,t,r){return{...e,surface:t,requestId:r||null}}var Fe=64,je=/^[A-Za-z0-9._+() -]+$/;function Ae(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>Fe?null:je.test(t)?t:null}var Me="1.6.0";var $e="react-native",De="2026-09-19",Be="EVERFUR_API_BASE_URL";function Ne(e,t){/* @__PURE__ */
15
15
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:e,message:t})})}function checkPublishableKey(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{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(e,t){let r=checkPublishableKey(e?.publishableKey);if(r!==null)/* @__PURE__ */
16
16
  return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),l=tryResolveApiBaseUrl(e.apiBaseUrl);if(!l.ok)return l;let i=e.contractVersion?.trim()||De,o=Ae(e.appVersion);/* @__PURE__ */
17
17
  return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:l.value,contractVersion:i,sdkVersion:Me,platform:t?.platform??$e,debug:e.debug===true,...o!==null?{appVersion:o}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:Ke(Be);return r?qe(r):Ne("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Be}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function Le(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function Ue(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function He(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Ue(t)}function We(e,t){return`${e}://${t}`}function qe(e){let t=e.trim(),r=Re.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return Ne("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),l=Le(r[2]);if(l.length===0)return Ne("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let i=He(t,l)?`: ${We(n,l)}`:"";if(n!=="https"){if(!(n==="http"&&Ve(l)))return n==="http"?Ne("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${i}`):Ne("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${i}`)}let o=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
@@ -24,7 +24,7 @@ return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function ur(e){
24
24
  return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function dr(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),/* @__PURE__ */Object.freeze(r)}function cr(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,/* @__PURE__ */Object.freeze(r)}function fr(e){/* @__PURE__ */
25
25
  return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}function pr(e,t,r){return makeEverfurError(e,{retryable:t,...r?{wireMessage:r}:{}})}function hr(e){let t=fromWire(e.code);return makeEverfurError(t,{retryable:e.retryable||shouldRetry(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}function gr(e){return errorFrame({code:mr(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}function mr(e){switch(e){case"authExpired":return"AUTH_EXPIRED";case"authRejected":return"AuthorizationException";case"sessionRequired":return"session_required";case"accessDenied":return"ACCESS_DENIED";case"paymentRequired":return"TIER_UPGRADE_REQUIRED";case"quotaExceeded":return"QUOTA_EXCEEDED";case"rateLimited":return"RATE_LIMITED";case"validationFailed":return"ValidationException";case"sdkUpdateRequired":return"invalidRequest";case"conflict":return"ConflictException";case"idempotencyConflict":return"IDEMPOTENCY_CONFLICT";case"idempotencyInFlight":return"IDEMPOTENCY_KEY_IN_FLIGHT";case"conversationNotFound":return"CONVERSATION_NOT_FOUND";case"petNotFound":return"PET_NOT_FOUND";case"resourceNotFound":return"ResourceNotFoundException";case"streamTimeout":return"STREAM_TIMEOUT";case"mediaUploadFailed":return"MEDIA_UPLOAD_FAILED";case"moderationBlocked":return"MODERATION_BLOCKED";case"upstreamLlmTimeout":return"UPSTREAM_LLM_TIMEOUT";case"internalError":return"INTERNAL_ERROR";case"notImplemented":return"NotImplementedException";case"serviceUnavailable":return"ServiceUnavailableException";case"streamIncomplete":return"STREAM_INCOMPLETE";case"identitySignatureRequired":return"identitySignatureRequired";case"runtimeDisposed":return"runtimeDisposed";case"unknown":return"UNKNOWN";default:return assertNever(e)}}function br(e){let t=Array.isArray(e)?e:vr(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let e of t){if(!vr(e))continue;let t=wr(e.category)??wr(e.title)??"",n=kr(e.prompts??e.questions);t.length===0&&n.length===0||r.push(/* @__PURE__ */Object.freeze({category:t,prompts:/* @__PURE__ */Object.freeze(n)}))}/* @__PURE__ */
26
26
  return Object.freeze(r)}function yr(e){let t=/* @__PURE__ */new Set,r=[];for(let n of e)for(let e of n.prompts){let n=e.trim();n.length===0||t.has(n)||(t.add(n),r.push(n))}return r}function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wr(e){return typeof e=="string"?e:null}function kr(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(vr(r)){let e=wr(r.text)??wr(r.prompt)??wr(r.title);e!==null&&t.push(e)}return t}function xr(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Cr(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Sr(){return typeof Symbol=="function"?Symbol.asyncIterator:void 0}function _r(e){let t=e,r=Sr(),n=(r!==void 0?t[r]:void 0)??t["@@asyncIterator"];if(typeof n=="function")return n.call(e);let l=typeof Symbol=="function"?t[Symbol.iterator]:void 0;if(typeof l=="function"){let t=l.call(e);return{next:()=>Promise.resolve(t.next()),return:e=>Promise.resolve(t.return?.(e)??{done:true,value:void 0})}}return null}var Rr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*Ir(e,t,r,n){let l=_r(e);if(l===null){yield Tr();return}let i=Or(t.overallMs,n),o=Or(t.idleMs,n),a=Pr(r);try{for(;;){if(r.aborted)return;let e=l.next().then(e=>({tag:"next",value:e}),()=>({tag:"streamError"})),n=await Promise.race([e,o.promise.then(()=>({tag:"idle"})),i.promise.then(()=>({tag:"overall"})),a.then(()=>({tag:"abort"}))]);if(n.tag==="abort")return;if(n.tag==="streamError"){if(r.aborted)return;yield Tr();return}if(n.tag==="idle"||n.tag==="overall"){yield zr();return}let s=n.value;if(s.done||(o.reset(t.idleMs),yield s.value,s.value.terminal))return}}finally{o.cancel(),i.cancel(),Promise.resolve(l.return?.(void 0)).catch(()=>{})}}function zr(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function Tr(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function Or(e,t){let r=()=>{},n=new Promise(e=>{r=e}),l=t.setTimeout(()=>r(),e);return{promise:n,reset(e){t.clearTimeout(l),l=t.setTimeout(()=>r(),e)},cancel(){t.clearTimeout(l)}}}function Pr(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var Er=128,Fr=128,jr=/[\u0000-\u001F\u007F]/,Ar=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(e){let t=e,r=Wt(t);if(r===0||r>Fr)throw new C("invalid-argument",`petRef must be 1..${Fr} characters`);if(jr.test(t))throw new C("invalid-argument","petRef must be printable (no control characters)");return t}function userRef(e){let t=e,r=Wt(t);if(r===0||r>Er)throw new C("invalid-argument",`userRef must be 1..${Er} characters`);if(t.includes("@"))throw new C("invalid-argument","userRef must not contain '@'");if(jr.test(t))throw new C("invalid-argument","userRef must be printable (no control characters)");return t}function conversationId(e){if(!Ar.test(e))throw new C("invalid-argument","conversationId must be a UUID");return e}var Mr="checkin",$r=/^\d{4}-\d{2}-\d{2}$/,Dr="watching";function Br(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r!==void 0){if(r.role==="user")return null;if(r.role==="assistant"){if(r.checkin!==void 0)return r.checkin.answer!==null||isCheckinSettled(r.checkin)?null:r;if(typeof r.proactiveOriginRef=="string"&&r.proactiveOriginRef.length>0)return r}}}return null}function Nr(e){if(e===null||typeof e!="object")return null;let t=e,r=t.conversation_id,n=t.message_id,l=t.question,i=t.occasion_ref;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0||typeof l!="string"||l.trim().length===0)return null;let o=typeof i=="string"&&i.length>0?i:null,a=Ur(o),s=a===null?null:/* @__PURE__ */Object.freeze({caseId:a.caseId,answer:null,resolutionText:null,status:null}),u=typeof t.created_at=="string"?t.created_at:"",d=/* @__PURE__ */Object.freeze({id:n,role:"assistant",text:l,createdAt:u,...o===null?{}:{proactiveOriginRef:o},...s===null?{}:{checkin:s}});/* @__PURE__ */
27
- return Object.freeze({conversationId:r,message:d,checkin:s,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==Dr}function Lr(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}function Ur(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,l]=t;return r!==Mr||n===void 0||l===void 0||!Vt.test(n)||!$r.test(l)?null:{caseId:n,dueDay:l}}function Hr(e){return Ur(e)?.caseId??null}function Wr(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||Ht(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function qr(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Vr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Kr(e){return e==null||typeof e=="string"&&e.length>0&&!Ht(e)}function Gr(){return err(makeEverfurError("internalError",{retryable:false}))}function Yr(e){let t=Vr(e);if(!t||!Array.isArray(t.conversations)||!Kr(t.next_cursor))return Gr();let r=[];for(let e of t.conversations){let t=Vr(e);if(!t||typeof t.conversation_id!="string"||!qr(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return Gr();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return Gr();let l=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...l.length>0?{preview:l}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Qr(e){let t=Vr(e);if(!t||!Array.isArray(t.messages)||!Kr(t.next_cursor))return Gr();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=Vr(e);if(!t||typeof t.message_id!="string"||!qr(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return Gr();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(Zr(t,t.message_id,t.content,t.created_at));continue}let l=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,i=t.role==="assistant"?Hr(l):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:Jr(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:en(t.citations)}:{},...l!==null?{proactiveOriginRef:l}:{},...i!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:i,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Zr(e,t,r,n){let l=Vr(e.sender),i=Xr(l?.display_name)??Xr(e.sender_display_name),o=Xr(l?.specialty);/* @__PURE__ */
27
+ return Object.freeze({conversationId:r,message:d,checkin:s,occasionRef:o})}function isCheckinSettled(e){return e.status!=null&&e.status!==Dr}function Lr(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}function Ur(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,l]=t;return r!==Mr||n===void 0||l===void 0||!Vt.test(n)||!$r.test(l)?null:{caseId:n,dueDay:l}}function Hr(e){return Ur(e)?.caseId??null}function Wr(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||Ht(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function qr(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Vr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Kr(e){return e==null||typeof e=="string"&&e.length>0&&!Ht(e)}function Gr(){return err(makeEverfurError("internalError",{retryable:false}))}function Yr(e){let t=Vr(e);if(!t||!Array.isArray(t.conversations)||!Kr(t.next_cursor))return Gr();let r=[];for(let e of t.conversations){let t=Vr(e);if(!t||typeof t.conversation_id!="string"||!qr(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return Gr();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return Gr();let l=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...l.length>0?{preview:l}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Qr(e){let t=Vr(e);if(!t||!Array.isArray(t.messages)||!Kr(t.next_cursor))return Gr();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=Vr(e);if(!t||typeof t.message_id!="string"||!qr(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return Gr();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(Zr(t,t.message_id,t.content,t.created_at));continue}let l=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,i=t.role==="assistant"?Hr(l):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:Jr(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:en(t.citations)}:{},...l!==null?{proactiveOriginRef:l}:{},...i!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:i,answer:null,resolutionText:null,status:null})}:{},...t.a2ui?{a2ui:[t.a2ui]}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Zr(e,t,r,n){let l=Vr(e.sender),i=Xr(l?.display_name)??Xr(e.sender_display_name),o=Xr(l?.specialty);/* @__PURE__ */
28
28
  return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:i,specialty:o})})}function Xr(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!Ht(t)?t:null}function Jr(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function en(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
29
29
  return Object.freeze(e.flatMap(e=>{let r=Vr(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function tn(e,t,r){let n=new Set(e.map(e=>e.id)),l=e.filter(e=>r.has(e.id)),i=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=l.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){l.splice(r,1);continue}i.push(e)}return i}var rn=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),nn=4e3;var ln=4e3;function on(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:pr("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:pr("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function an(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:pr("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>ln?{reason:"too_long",error:pr("validationFailed",false,`message is ${r} characters; the server accepts at most ${ln}`)}:null}function sn(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*un(e){yield e}async function*dn(){}var cn=6e4,fn=18e4,pn=24,hn=512,gn=false;function createChatController(e){return new vn(e)}function mn(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function bn(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function yn(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var vn=class extends or{constructor(e){super(fr({status:"idle",messages:[],conversationId:e.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=Jt(this.funnel),this.telemetry=e.telemetry??S,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??$,this.timers=e.timers??Rr,this.rng=e.rng??Math.random,this.newId=e.newId??xr(),this.makeIdempotencyKey=e.makeIdempotencyKey??Cr(),this.budget={idleMs:e.budget?.idleMs??cn,overallMs:e.budget?.overallMs??fn}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=pr(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):un(gr(e))}let l=an(e)??on(n.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),r?(r.onError(l.error),()=>{}):un(gr(l.error));if(r)return this.driveWithHandlers(e,n,r);let i=this.beginTurn(e,n);return this.runTurn(i,n.signal)}askEverfur(e,t){if(this.disposed)return un(gr(pr("accessDenied",false)));let r=an(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),un(gr(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):dn()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,ar(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?ur(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(yr(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=Wr(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(pr("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(pr("accessDenied",false));if(!l.ok)return l;let i=Yr(l.value);if(i.ok){for(let e of i.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=i.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,i.value.conversations):this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return i}reportCheckinSkips(e){let t=[];e===null&&t.push("no_pet"),this.auth.userRef===null&&t.push("no_member");for(let e of t)this.reportCheckinSkip(e)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(e){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let t=this.epoch,r=e===null?"":`?pet_ref=${encodeURIComponent(String(e))}`,n=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${r}`},void 0,{maxAttempts:1});if(!this.alive(t)||this.disposed)return null;if(this.cardsInFlight=false,n.ok){this.cardsRoute="served";let e=n.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],r=[];for(let e of t){let t=Nr(e);t===null?this.reportCheckinSkip("card_unreadable"):r.push(this.withAnsweredCase(t))}return this.pendingCards=r,this.syncPendingCheckin(),null}if(n.error.category!=="notFound"&&n.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),bn(n.error)?n.error:null;if(n.error.category==="notFound"&&yn(n.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let l=Br(n.value.messages);l===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:l,checkin:l.checkin??null,occasionRef:l.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}mn(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(pr("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let r=e?.petRef??this.petRef,n=await this.listConversations({...r===null?{}:{petRef:r},limit:1});if(!n.ok)return err(n.error);let l=n.value.conversations[0];if(l===void 0)return ok(null);let i=await this.resumeConversation(l.id);return i.ok?ok(l.id):err(i.error)}async markRead(e){if(this.disposed)return err(pr("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(pr("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(pr("accessDenied",false));if(typeof e!="string"||e.trim().length===0||Ht(e))return err(pr("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!rn.includes(t))return err(pr("validationFailed",false,`feedback_type must be one of ${rn.join(", ")}`));let l=typeof r=="string"?r.trim():"";if([...l].length>nn)return err(pr("validationFailed",false,`notes is over ${nn} characters`));let i={feedback_type:t};l.length>0&&(i.notes=l);let o=this.epoch,a=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:i},n?.signal);if(!this.alive(o)||this.disposed)return err(pr("accessDenied",false));if(!a.ok)return err(a.error);let s=a.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof s=="string"?s:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(pr("accessDenied",false));let n=r?.petRef??this.petRef;if(n===null)return err(pr("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,i=await this.cases.checkin(n,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(l)||this.disposed)return err(pr("accessDenied",false));if(!i.ok)return i;let o=i.value.case.openedAt,a=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...o!==null?{openedAt:o}:{}}),s=t=>t.checkin?.caseId===e;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,checkin:a}):e)}),this.answeredCases.set(e,a);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:a}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!qr(e))return err(pr("validationFailed",false));let r=Wr(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(pr("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(pr("accessDenied",false)):l.ok?Qr(l.value):l}async resumeConversation(e){if(this.disposed)return err(pr("accessDenied",false));if(!qr(e))return err(pr("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(pr("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let t=this.petRef;if(t===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let r=await this.cases.list(t);if(!r.ok||e!==this.historyGeneration||this.disposed)return;let n=new Set(r.value.filter(e=>e.status===Dr).map(e=>e.caseId)),l=new Map(r.value.map(e=>[e.caseId,e])),i=false,o=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let r=l.get(t.caseId),o=t.openedAt??r?.openedAt??null,a=n.has(t.caseId),s=r!==void 0&&(!a||Lr({askCount:r.checkinAskCount,answerCount:r.checkinAnswerCount}))?r.lastResponse:null;/* @__PURE__ */
30
30
  return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:a?Dr:r?.status??"resolved",answer:t.answer??s,resolutionText:t.resolutionText??r?.resolutionText??null,...o!==null?{openedAt:o}:{}})})});i&&this.patch({messages:o})}async refreshActiveThread(e){if(this.disposed)return err(pr("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),l=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(pr("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=l===null?null:await l;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let i=await this.resumeConversation(r.id);return i.ok?ok(void 0):err(i.error)}let i=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(pr("accessDenied",false));if(!i.ok)return err(i.error);let o=tn(this.snapshot.messages,i.value.messages,this.localRowIds);if(o.length>0&&this.patch({messages:[...this.snapshot.messages,...o]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&bn(n.error))return err(n.error);let a=l===null?null:await l;return a!==null&&r===this.historyGeneration&&!this.disposed?err(a):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(pr("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(pr("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let l=new Set(this.snapshot.messages.map(e=>e.id)),i=n.value.messages.filter(e=>!l.has(e.id));return this.patch({messages:[...i,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield gr(t.error))}async primeConversation(e){if(this.disposed)return err(pr("accessDenied",false));let t=e?.petRef??null,r={petRef:t,settled:this.primeBounded(t)};this.unadoptedCreate=r;let n=await r.settled;return this.disposed?err(pr("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async primeBounded(e){let t=await this.headThreadWithUnread(e);return t.ok?t.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(t.value)).ok?ok(t.value):ok(this.snapshot.conversationId):t.error.code==="accessDenied"||t.error.httpStatus===403?ok(null):err(t.error)}async headThreadWithUnread(e){let t=await this.listConversationsWith({...e===null?{}:{petRef:e},limit:1},{maxAttempts:1});if(!t.ok)return err(t.error);let r=t.value.conversations[0];return r===void 0||r.unreadCount===null||r.unreadCount<=0?ok(null):ok(r.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(pr("accessDenied",false));let r=e?.petRef??null,n={petRef:r,settled:this.createConversationBounded(r)};this.unadoptedCreate=n;let l=await n.settled;return!this.alive(t)||this.disposed?err(pr("accessDenied",false)):(!l.ok&&this.unadoptedCreate===n&&(this.unadoptedCreate=null),l)}async createConversationBounded(e,t){let r={method:"POST",path:"/widget/v1/conversations",body:e?{pet_ref:e}:{}},n=await this.authedUnary("chat.createConversation",r,t,{maxAttempts:1});if(!n.ok)return err(n.error);let l=n.value?.conversation_id??n.value?.id;return typeof l!="string"||l.length===0?err(pr("internalError",true)):ok(l)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(pr("accessDenied",false));let r=e?.petRef??null;if(r!==null&&Ht(r))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let n=r!==null?`?pet_ref=${encodeURIComponent(r)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${n}`});return!this.alive(t)||this.disposed?err(pr("accessDenied",false)):l.ok?ok(br(l.value)):err(l.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,l=ir(n.signal,t.signal),i=this.beginTurn(e,t),o=this.runTurn(i,l),a=false,s=()=>{a||(a=true,n.abort(),this.handlerTeardowns.delete(s))};return this.handlerTeardowns.add(s),(async()=>{for await(let e of o){if(a)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!a&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(s)})(),s}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,ar(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,l=false,i=false,o=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,a=t?this.unadoptedCreate:null;if(a!==null&&(e.petRef===null||e.petRef===a.petRef)){let e=await a.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,gr(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let s=e.conversationIdOverride??this.snapshot.conversationId;if(s===null){let t=pr("internalError",!0);yield*this.emitTerminal(e,t,gr(t));return}this.clearAssistantInProgress(e);let u=new AbortController,d=ir(r.signal,u.signal),c=null,f=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,s))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,gr(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;f=t.headers?.[N]??null;let n=this.funnel.stream("chat.send",t,d);for await(let t of Ir(n,this.budget,d,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){c=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(c===null){if(this.snapshot.status==="complete")return;let t=pr("streamIncomplete",!0);yield*this.emitTerminal(e,t,gr(t));return}let p=fromWire(c.code);if(p==="authExpired"&&this.auth.mode==="personalized"&&!i){i=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(c);yield*this.emitTerminal(e,t,c);return}this.patch({reconnecting:!0});continue}if(!o&&f!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(c.code===L||p==="authExpired")){o=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==f){this.patch({reconnecting:!0});continue}}if(p==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(c);yield*this.emitTerminal(e,t,c);return}if(p==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,hr(c),c);return}if(canRecreateOnNotFound(p)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let h=c.retryable&&shouldRetry(p,!0);if(gn&&h&&n+1<this.errorPolicy.maxAttempts(p));yield*this.emitTerminal(e,hr(c),c);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?ur(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,sr(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=hn){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},pn)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?dr(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?cr(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?ur(e):e),cr(sr(r,"",this.stamp()),e)]}let l=yr([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=l.length>0?/* @__PURE__ */Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(e,t){if(t===null||this.disposed)return;let r=String(t);if(this.classifiedMessageIds.has(r))return;this.classifiedMessageIds.add(r);let n=this.epoch,l=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${e}/classify`});if(!i.ok||!this.alive(n)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==e)return;let o=sn(i.value?.urgency),a=typeof i.value?.reason=="string"?i.value.reason:null,s=e=>e.responseId===t;this.snapshot.messages.some(s)&&this.patch({messages:this.snapshot.messages.map(e=>s(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:o,urgencyReason:a,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?ur(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?pr("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,n=e.petRef??null,l=e.resumeConversationId??null,i=[],o=false,a=false,s=false,u=null,d=null,c=l?r.resumeConversation(l).then(e=>e.ok?ok(l):err(e.error)):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[p,h]=await Promise.all([c,f]),g=null;if(p.ok)g=p.value,p.value!==null&&i.push(p.value),p.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(p.value);else{let e=p.error;d=e,kn(e)?(a=true,u=e):(xn(e)&&(o=true),s=true)}let m=[];h.ok?m=h.value:b(h.error);function b(e){kn(e)?(a=true,u===null&&(u=e)):xn(e)&&(o=true)}let y=u!==null?u.displayMessage:null;/* @__PURE__ */
@@ -46,7 +46,7 @@ return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.creat
46
46
  return Object.freeze({track(t,r){try{e.track(t,r)}catch{}},trackExpectedFailure(r,n){try{e.trackExpectedFailure(r,t===void 0?n:fd(r,n,t))}catch{}}})}function fd(e,t,r){let n=e.indexOf("."),l=typeof t?.surface=="string"?t.surface:n>0?e.slice(0,n):"sdk",i=typeof t?.requestId=="string"?t.requestId:null;return{...Ee(r,l,i),...t}}function pd(e,t,r){if(e===void 0)return;let n=e.onExpectedFailure;return{shouldRetry:(t,r)=>e.shouldRetry(t,r),maxAttempts:t=>e.maxAttempts(t),...typeof n=="function"?{onExpectedFailure:(l,i)=>n.call(e,l,i??Ee(t,r,l.requestId))}:{}}}var hd=/* @__PURE__ */Object.freeze({"react-native":"If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.",web:`If the value is set in your environment, note that a browser bundle does not expose ${Be} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function gd(e,t,r=$e){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+hd[r])}function md(e){/* @__PURE__ */
47
47
  return Object.freeze({request(){return Promise.resolve(err(ud(e)))},stream(t,r){let n=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return async function*(){r.aborted||(yield n)}()}})}var bd=/* @__PURE__ */new WeakSet;function yd(){let e=/* @__PURE__ */new Map,t={async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r)},async removeItem(t){e.delete(t)},async keys(t){return[...e.keys()].filter(e=>e.startsWith(t))}};return bd.add(t),t}var vd=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(e,t){return new kd(e,t)}var wd=6e4,kd=class{constructor(e,t){this.sessionId=newSessionId();this.anonIdentity=null;this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.brandingCache=null;this.verdictLanded=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let r=e.config;if(r.secureStore!==void 0&&r.secureStore.isAvailable===true)throw new C("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 §5.3).");this.errorContext=/* @__PURE__ */Object.freeze({sdkVersion:Me,platform:t?.platform??$e,partnerKey:checkPublishableKey(r?.publishableKey)===null?r.publishableKey.trim():null,appVersion:Ae(r?.appVersion)}),this.telemetry=r.telemetry?cd(r.telemetry,this.errorContext):S,this.onEvent=typeof r.onEvent=="function"?r.onEvent:void 0;let n=typeof r?.publishableKey=="string"?r.publishableKey.trim():"",l=checkPublishableKey(r?.publishableKey),i=r.transport!==void 0,o,a=typeof r.apiBaseUrl=="string"&&r.apiBaseUrl.trim().length>0?r.apiBaseUrl.trim():null;if(l!==null)o=md(l);else if(r.transport!==void 0)o=r.transport;else{let e=dd(r,t?.platform);e.ok?(a=e.config.apiBaseUrl,o=createHttpTransport({config:e.config,...t?.eventSourceFactory?{eventSourceFactory:t.eventSourceFactory}:{}})):(l=e.failure,o=md(e.failure))}if(this.configFailure=l,this.publishableKey=l===null?n:"",this.mintScope=`${this.publishableKey}|${a??""}`,Zl(this,this.mintScope),this.transport=o,l!==null&&(gd(l,this.telemetry,t?.platform),this.emit({type:"error",code:ud(l).code,requestId:null,context:Ee(this.errorContext,"runtime",null)})),this.errorPolicy=pd(r.errorPolicy,this.errorContext,"runtime"),this.camera=r.camera??D,this.upload=r.upload??rr,this.uploadTransport=r.uploadTransport??Cn,this.imageCache=r.imageCache??vd,this.kv=r.storage??yd(),this.currentUser=e.user??null,this.identity=this.buildIdentity(e.user??null),this.activePet=e.activePet,this.store=l===null?Xu():Xu(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:e=>this.buildAuth(e),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:e=>this.acquireInternal("chat",xd(e),()=>this.buildChatController(e),Cd),releaseChat:e=>this.releaseInternal(e),peekChat:e=>this.entries.get(`${this.epoch}|chat|${xd(e)}`)?.controller??null,acquire:(e,t,r,n)=>this.acquireInternal(e,t,r,n),release:e=>this.releaseInternal(e)},this.entitlements=this.store,this.unread=Lu({read:e=>this.disposed||this.currentUser===null||this.configFailure!==null?null:Uu(this.buildAuth(this.currentUser.userRef),e,this.errorPolicy),emit:e=>this.emit(e)}),l===null){this.brandingCache=od(this.kv,this.mintScope);let e=this.epoch;this.brandingCache.restore(t=>{let r=this.store.getSnapshot();this.disposed||this.verdictLanded||this.epoch!==e||r.branding||this.store.set({...r,branding:t})})}this.sdkConfigHost=l===null?sd({kv:this.kv,scope:this.mintScope,funnel:()=>createRequestFunnel({auth:this.buildAuth(this.currentUser?.userRef??null)})}):void 0;let s=l===null&&(t?.startEntitlementPolling??!i);this.poller=l===null?this.buildPoller(t?.pollScheduler):null,s&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(e){if(e===null)return null;let t=ii(`${this.mintScope}|${e.userRef}`,e.getToken),r=createIdentityProvider(e.userRef,t,e=>this.armTokenRefresh(r,e),()=>{r===this.identity&&this.emit({type:"session_expired",userRef:e.userRef})});return r}armTokenRefresh(e,t){if(this.clearTokenRefresh(),t===null||this.disposed||e!==this.identity)return;let r=t-Date.now();if(r<=0)return;let n=Math.max(r-wd,r/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||e!==this.identity)&&e.currentToken({forceRefresh:true}).catch(()=>{})},n),this.refreshTimer.unref?.()}emit(e){let t=this.onEvent;if(t===void 0)return;let r=()=>{this.disposed||Kl(t,e)};typeof queueMicrotask=="function"?queueMicrotask(r):Promise.resolve().then(r)}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(e){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(e,t,r,n)=>{this.verdictLanded=true;let l=this.store.getSnapshot().branding??null,i=l!==null&&t!=null&&nd(l)===nd(t)?l:t;this.updateEntitlements({decisions:e,isPending:false,branding:i,...r===false?{livemode:r}:{},...n!==void 0?{smsProfilePublic:n}:{}}),this.brandingCache?.persist(i??null)},onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...e?{scheduler:e}:{}})}acquireInternal(e,t,r,n,l=false){let i=`${this.epoch}|${e}|${t}`,o=this.entries.get(i);if(o)return l||(o.warm?o.warm=false:o.refCount+=1),o.controller;let a=r();return this.entries.set(i,{controller:a,refCount:1,warm:l}),this.destroyers.set(a,n),a}releaseInternal(e){for(let[t,r]of this.entries)if(r.controller===e){r.refCount-=1,r.refCount<=0&&(this.runDestroyer(e),this.entries.delete(t));return}}runDestroyer(e){let t=this.destroyers.get(e);this.destroyers.delete(e),t&&t(e)}buildChatController(e){let t=createChatController({auth:this.buildAuth(e.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:pd(this.errorPolicy,this.errorContext,"chat")}:{},initialConversationId:e.conversationId,petRef:e.petRef,onConversationStarted:e=>this.emit({type:"conversation_started",conversationId:e}),unread:this.unread});return this.runBootstrap(t,e),t}runBootstrap(e,t){let r={};t.petRef!==null&&(r.petRef=t.petRef),t.conversationId!==null&&(r.resumeConversationId=t.conversationId);let n=bootstrapChat(r,{controller:e});return n.then(t=>e.adoptPrompts(t.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(e,n),n}buildAuth(e){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:e,sessionId:this.sessionId,anonIdentity:this.anonIdentity??=createAnonIdentityProvider(this.transport,this.publishableKey,this.sessionId)}}setUser(e){if(this.disposed)return;let t=e?.userRef??null,r=this.currentUser?.userRef??null;if(t===r){this.currentUser=e,e&&this.identity===null&&(this.identity=this.buildIdentity(e));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=e,this.identity=this.buildIdentity(e),this.rescopeAll()}async logout(){if(this.disposed)return;let e=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.anonIdentity=null,this.setUser(null),this.leavingSessionId=null,e&&this.rescopeAll();let t=this.pendingBeforeLogout;this.pendingBeforeLogout=null,t!==null&&await t,await Qu(this.kv,this.telemetry)}onBeforeLogout(e){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(e),()=>{this.beforeLogoutHooks.delete(e)})}beforeLogoutSettlement(){let e=this.currentUser,t=this.identity;return Gu({leaving:e,identity:t,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>Yu({leaving:e,identity:t,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(e,t){return this.withPets("registerPet",(r,n)=>Jl(Xl(this,n,e,t),()=>t===void 0?r.registerPet(e):r.registerPet(e,t)))}updatePet(e,t){return this.withPets("updatePet",r=>r.updatePet(e,t))}deletePet(e){return this.withPets("deletePet",t=>t.deletePet(e))}eraseUserData(){return this.withPets("eraseUserData",e=>e.eraseUserData())}async withPets(e,t){if(this.disposed)return err(Sd(e));let r=this.buildAuth(this.currentUser?.userRef??null),n=await t(createPetsRepository(r),r);return n.ok&&!this.disposed&&ni(this),n}prepare(e){let t=e?.petRef??null,r=`${this.epoch}|${this.currentUser?.userRef??""}|${t??""}`,n=this.prepared;if(n!==null&&n.key===r&&(n.result===null||n.result.status==="ready"))return n.promise;let l={key:r,result:null,promise:this.runPrepare(t).then(e=>(l.result=e,e))};return this.prepared=l,l.promise}async runPrepare(e){let t=Date.now(),r=this.configFailure,n=this.disposed?Sd("prepare"):r===null?null:ud(r),l=this.identity,[i,o,a]=await Promise.all([n?err(n):l===null?ok(void 0):l.currentToken().then(()=>ok(void 0),e=>(l.reportRejected?.(),err(X(e)))),n?err(n):this.primeEntitlements(),e===null?void 0:n?err(n):this.primeChat(e)]),s=i.ok?o.ok&&(a?.ok??true)?"ready":"partial":"failed",u=Date.now()-t;try{this.telemetry.track("sdk.prepare.timing",{durationMs:u,status:s})}catch{}if(s==="ready")this.emit({type:"ready"});else if(s==="failed"&&!i.ok&&r===null&&!this.disposed){let e=i.error.requestId??null;this.emit({type:"error",code:i.error.code,requestId:e,context:Ee(this.errorContext,"runtime",e)})}/* @__PURE__ */
48
48
  return Object.freeze({status:s,durationMs:u,session:i,entitlements:o,...a?{chat:a}:{}})}async primeEntitlements(){let e=await(this.poller?.prime());return e?e.kind==="failed"?err(e.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(e){let t={userRef:this.currentUser?.userRef??null,petRef:e,conversationId:null},r=this.acquireInternal("chat",xd(t),()=>this.buildChatController(t),Cd,true),n=await this.bootstraps.get(r);return n?.cause&&r.getSnapshot().conversationId===null&&(n=await this.runBootstrap(r,t)),n?.cause?err(n.cause):ok(void 0)}setActivePet(e){if(this.disposed)return;let t=e??null;t!==this.activePet&&(this.activePet=t,this.rescopeAll({keepBranding:true}))}updateEntitlements(e){this.disposed||this.configFailure===null&&this.store.set(e)}open(e){this.telemetry.track("sdk.open",{capability:e})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.sdkConfigHost!==void 0&&(this.sdkConfigHost.disposed=true,this.sdkConfigHost.store?.dispose(),this.sdkConfigHost.store=null,this.sdkConfigHost.branding.set(null)),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(e){this.epoch+=1,this.disposeAllControllers(),this.unread.reset(),this.store.reset(e),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let e of this.entries.values())this.runDestroyer(e.controller);this.entries.clear(),this.destroyers.clear()}};function xd(e){return`${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}function Cd(e){e.dispose()}function Sd(e){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}function _d(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function Rd(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function Id(e){return e.ok?e:err(Rd(e.error))}function zd(e){return{send:async(...t)=>Id(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var Td=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),Od=globalThis,Pd=Od[Td]??(Od[Td]=createContext(null));Pd.displayName??="EverfurContext";function Ed(){let e=t(Pd);if(e===null)throw new C("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}function useEverfur(){return Ed().handle}var Fd=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),jd=globalThis,Ad=jd[Fd]??(jd[Fd]=createContext(ko));Ad.displayName??="EverfurThemeContext";function useEverfurTheme(){return t(Ad)}var Md=()=>()=>{},$d=()=>null;function Dd(e,t){return n(t?.subscribe??Md,t?.get??$d,t?.get??$d)??e}function EverfurThemeProviderCore(e){let{runtime:t}=Ed(),i=t.entitlements,o=n(i.subscribe,i.getSnapshot,i.getSnapshot),s=e.seams.useColorScheme(),u=e.seams.useReducedMotion(),d=e.seams.useTextScale(),c=e.seams.useHighContrast(),f=e.seams.scaleTypeSizes,p=e.seams.typeProfile,h=e.seams.platformMonoFamily?.(),g=e.seams.isFontRegistered,m=e.clientTheme?Bd(e.clientTheme):"",b=l(()=>e.clientTheme?parseClientBranding(e.clientTheme):null,[m]),y=Dd(o.branding??null,t.sdkConfigHost?.branding),v=l(()=>resolveTheme({branding:y,clientOverride:b,colorScheme:s,reducedMotion:u,textScale:d,scaleTypeSizes:f,highContrast:c,...p===void 0?{}:{typeProfile:p},...h===void 0?{}:{platformMonoFamily:h},...g===void 0?{}:{isFontRegistered:g}}),[y,b,s,u,d,f,p,c,h,g]);e.seams.useResolvedTheme?.(v);let w=e.seams.isDevelopment;return a(()=>{w===void 0||!Nd(w)||qo(themeAdjustments({branding:y,clientOverride:b,colorScheme:s}))},[w,y,b,s]),r(Ad.Provider,{value:v},e.children)}function Bd(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}function Nd(e){try{return e()===!0}catch{return false}}function EverfurProviderCore(e){let{config:t,user:n,activePet:i,theme:s,warmUp:d,children:f,seams:p}=e,h=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,g=o(null),m=o(null),b=o(t?.onEvent);b.current=t?.onEvent;let y=o(e=>{b.current?.(e)}),[v,w]=c(e=>e+1,0),k=o(null),x=o(void 0),C=n?.userRef??null;x.current!==C&&(x.current!==void 0&&(k.current=null),x.current=C);let S=k.current!==null?k.current.user:n??null,_=o(null),R=o(void 0),I=i??null;R.current!==I&&(R.current!==void 0&&(_.current=null),R.current=I);let z=_.current!==null?_.current.pet:i??null;(g.current===null||g.current.key!==h||g.current.runtime.isDisposed)&&(g.current!==null&&!g.current.runtime.isDisposed&&(m.current=g.current.runtime),g.current={key:h,runtime:createEverfurRuntime({config:Ld(p.withDefaults?p.withDefaults(t):t,y.current),user:S,activePet:z,theme:s??null},{platform:p.platform,...p.eventSourceFactory?{eventSourceFactory:p.eventSourceFactory}:{}})});let T=g.current.runtime,O=o(null);a(()=>{let e=g.current?.runtime;e===void 0||!e.isDisposed||O.current!==e&&(O.current=e,w())}),a(()=>{let e=m.current;e!==null&&(m.current=null,e.dispose())});let P=S?.userRef??null;u(()=>{T.setUser(S)},[T,P]),u(()=>{T.setActivePet(z)},[T,z]);let E=o(null);a(()=>(E.current===T&&(E.current=null),()=>{E.current=T,Ud(()=>{E.current===T&&(E.current=null,T.dispose())})}),[T]),a(()=>{d==="onMount"&&T.prepare(z===null?{}:{petRef:z})},[T,d,P,z]);let F=l(()=>({setUser:e=>{k.current={user:e},T.setUser(e),w()},setActivePet:e=>{_.current={pet:e},T.setActivePet(e),w()},open:e=>T.open(e),prepare:e=>T.prepare(e),registerPet:(e,t)=>T.registerPet(e,t),updatePet:(e,t)=>T.updatePet(e,t),deletePet:e=>T.deletePet(e),eraseUserData:()=>T.eraseUserData(),logout:()=>{k.current={user:null};let e=T.logout();return w(),e}}),[T,w]),j=l(()=>({runtime:T,handle:F,userRef:P,activePet:z,scopeEpoch:T.scopeEpoch,publishableKey:Hd(t)}),[T,F,P,z,v,h]),A=r(EverfurThemeProviderCore,{clientTheme:s??null,seams:p.theme,children:f});return r(Pd.Provider,{value:j},p.wrap?p.wrap(A):A)}function Ld(e,t){return typeof e!="object"||e===null?e:{...e,onEvent:t}}function Ud(e){if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function Hd(e){return typeof e?.publishableKey=="string"?e.publishableKey.trim():""}var Wd="everfur:";function qd(){try{if(typeof window>"u")return null;let e=window.localStorage;return e&&typeof e.getItem=="function"?e:null}catch{return null}}function createLocalStorageKv(){return{async getItem(e){try{return qd()?.getItem(Wd+e)??null}catch{return null}},async setItem(e,t){try{qd()?.setItem(Wd+e,t)}catch{}},async removeItem(e){try{qd()?.removeItem(Wd+e)}catch{}},async keys(e){try{let t=qd();if(t===null)return[];let r=[],n=Wd+e;for(let e=0;e<t.length;e+=1){let l=t.key(e);l!==null&&l.startsWith(n)&&r.push(l.slice(Wd.length))}/* @__PURE__ */
49
- return Object.freeze(r)}catch{return[]}}}}var Vd="https://sdk.everfur.com",Kd=/* @__PURE__ */Object.freeze({k1:"X4wc1hwVONs4I9Vmclo9ExrfPZlH8-tgY7NmzxuA5lI"}),Gd=/* @__PURE__ */Object.freeze(["health-plan","health-plan-today","shop","shop-orders-v2","ui","televet-booking","televet-call"]),Yd=/* @__PURE__ */Object.freeze({"@everfur/sdk/web/health-plan":"health-plan","@everfur/sdk/web/health-plan/today":"health-plan-today","@everfur/sdk/web/shop":"shop","@everfur/sdk/web/shop/orders-v2":"shop-orders-v2","@everfur/sdk/web/ui":"ui","@everfur/sdk/web/televet/booking":"televet-booking","@everfur/sdk/web/televet/call":"televet-call"}),Qd=1794995274e3,Zd=3e3,Xd=8e3,Jd=256*1024,ec=4*1024*1024,tc="web_runtime.fallback";var rc=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBridge@v${1}`);function nc(){let e=globalThis,t=e[rc];if(t!==void 0)return t;let r={major:1,host:null,defined:/* @__PURE__ */new Map,waiters:/* @__PURE__ */new Map,importSubpath:null};return e[rc]=r,r}function lc(e){if(typeof e!="string")return null;let t=/^(\d+)\./.exec(e);return t===null?null:Number(t[1])}function ic(e){let t=lc(e.React?.version);if(t===null||typeof e.React.createElement!="function")return null;let r=nc();return r.host===null?(r.host={...e,reactMajor:t},{reactMajor:t}):r.host.React.createElement===e.React.createElement&&r.host.reactMajor===t?{reactMajor:t}:null}function oc(){return nc().host}var ac=(e,t)=>`${e}@${t}`;function sc(e,t){return nc().defined.get(ac(e,t))??null}function uc(e,t,r){let n=nc(),l=n.ran??=/* @__PURE__ */new Map,i=ac(e,t),o=l.get(i);return o===void 0?n.defined.has(i)?false:(l.set(i,r),true):o===r}function dc(e,t,r){let n=sc(e,t);if(n!==null)return Promise.resolve(n);let l=nc(),i=ac(e,t);return new Promise(e=>{let t=l.waiters.get(i)??/* @__PURE__ */new Set;l.waiters.set(i,t);let n=r=>{clearTimeout(a),t.delete(o),e(r)},o=e=>n(e),a=setTimeout(()=>n(null),r);t.add(o)})}function cc(e){nc().importSubpath=e}function fc(e,t){let r=Object.keys(t).sort().map(e=>`${e}=${t[e]}`).join(",");return`v${1}|${e}|${r}`}var pc=fc(Me,Kd);var hc=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBundledOnly@v${1}`),gc=globalThis,mc=()=>gc[hc]===true,bc=()=>{gc[hc]=true};var yc=/^\d{1,4}\.\d{1,5}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,64})?$/,vc=/^[a-z0-9][a-z0-9.-]{0,80}\.js$/,wc=/^sha384-[A-Za-z0-9+/]{64}$/,kc=/^[0-9a-f]{32}$/,xc=/^[A-Za-z0-9_-]+$/,Cc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Sc(e){if(typeof e!="string"||e.length===0||!xc.test(e))return null;let t=e.replace(/-/g,"+").replace(/_/g,"/");try{let e=atob(t+"=".repeat((4-t.length%4)%4)),r=new Uint8Array(e.length);for(let t=0;t<e.length;t+=1)r[t]=e.charCodeAt(t);return r}catch{return null}}var _c=/^\d{4}(-\d\d){2}T\d\d(:\d\d){2}(\.\d{1,3})?Z$/,Rc=14*864e5;function Ic(e){if(typeof e!="string"||!_c.test(e))return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function zc(e){if(!Cc(e)||!Array.isArray(e.react)||!Cc(e.parts))return null;let t=e.react.filter(e=>Number.isInteger(e)&&e>0);if(t.length===0||t.length!==e.react.length)return null;let r={};for(let[t,n]of Object.entries(e.parts))if(Gd.includes(t)){if(!Cc(n)||typeof n.path!="string"||typeof n.integrity!="string"||!vc.test(n.path)||!wc.test(n.integrity))return null;r[t]={path:n.path,integrity:n.integrity}}return{react:t,parts:r}}function Tc(e){if(!Cc(e)||e.schema!==1||!Number.isInteger(e.major))return null;let t=Ic(e.issuedAt),r=Ic(e.expiresAt);if(t===null||r===null||typeof e.stable!="string"||!yc.test(e.stable)||r<=t||r-t>Rc||!Cc(e.versions))return null;let n={};for(let[t,r]of Object.entries(e.versions)){let e=zc(r);if(!yc.test(t)||e===null)return null;n[t]=e}let l=null;if(e.canary!==void 0&&e.canary!==null){let t=e.canary;if(!Cc(t)||typeof t.version!="string"||!yc.test(t.version)||typeof t.percent!="number"||!Number.isFinite(t.percent)||t.percent<0||t.percent>100)return null;l={version:t.version,percent:t.percent}}let i={};if(e.pins!==void 0){if(!Cc(e.pins))return null;for(let[t,r]of Object.entries(e.pins)){if(!kc.test(t)||typeof r!="string"||!yc.test(r))return null;i[t]=r}}let o=[];if(e.revoked!==void 0){if(!Array.isArray(e.revoked)||!e.revoked.every(e=>typeof e=="string"&&yc.test(e)))return null;o=e.revoked}return{schema:1,major:e.major,issuedAt:t,expiresAt:r,stable:e.stable,canary:l,pins:i,revoked:o,versions:n}}async function Oc(e,t,r,n,l=Qd){if(!Cc(e)||e.v!==1||typeof e.keyId!="string")return{ok:false,reason:"manifest-shape"};let i=Sc(e.payload),o=Sc(e.signature);if(i===null||o===null||o.length!==64)return{ok:false,reason:"manifest-shape"};let a=Object.prototype.hasOwnProperty.call(t,e.keyId)?Sc(t[e.keyId]):null;if(a===null||a.length!==32)return{ok:false,reason:"signature-key"};let s;try{let e=await r.subtle.importKey("raw",a,{name:"Ed25519"},!1,["verify"]);s=await r.subtle.verify({name:"Ed25519"},e,o,i)}catch{return{ok:false,reason:"signature-unsupported"}}if(!s)return{ok:false,reason:"signature-invalid"};let u;try{u=JSON.parse((new TextDecoder).decode(i))}catch{return{ok:false,reason:"manifest-shape"}}let d=Tc(u);return d===null?{ok:false,reason:"manifest-shape"}:d.major!==1?{ok:false,reason:"manifest-major"}:n>=d.expiresAt?{ok:false,reason:"manifest-expired"}:d.issuedAt<l?{ok:false,reason:"manifest-stale"}:{ok:true,manifest:d}}function Pc(e,t){let[r="",n]=e.split(/-(.*)/s,2),[l="",i]=t.split(/-(.*)/s,2),o=r.split(".").map(Number),a=l.split(".").map(Number);for(let e=0;e<3;e+=1){let t=(o[e]??0)-(a[e]??0);if(t!==0)return t<0?-1:1}if(n===i)return 0;if(n===void 0)return 1;if(i===void 0)return-1;let s=n.split("."),u=i.split(".");for(let e=0;;e+=1){let t=s[e],r=u[e];if(t===r)continue;if(t===void 0||r===void 0)return t===void 0?-1:1;let n=/^\d+$/.test(t),l=/^\d+$/.test(r);return n!==l?n?-1:1:(n?Number(t)<Number(r):t<r)?-1:1}}function Ec(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0}function Fc(e,t){return Ec(`${e??"-"}:${t}`)%100}async function jc(e,t){try{let r=await t.subtle.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,"0")).join("").slice(0,32)}catch{return null}}function Ac(e,t){let r=t.tenantKey===null?void 0:e.pins[t.tenantKey],n,l;if(r!==void 0?(n=r,l="pin"):e.canary!==null&&Fc(t.tenantKey,t.sessionBucket)<e.canary.percent?(n=e.canary.version,l="canary"):(n=e.stable,l="stable"),e.revoked.includes(n))return{use:"bundled",reason:"revoked"};if(l!=="pin"&&Pc(n,t.bundledVersion)<0&&!e.revoked.includes(t.bundledVersion))return{use:"bundled",reason:"bundled-newer"};let i=e.versions[n];return i===void 0?{use:"bundled",reason:"version-missing"}:{use:"remote",version:n,entry:i,reason:l}}var Mc=/^manifest-(fetch|timeout)$/,$c="everfur:web-runtime:unreachable",Dc=10*6e4;function Bc(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function Nc(e,t,r,n,l="default"){let i=typeof AbortController=="function"?new AbortController:null,o=null,a=()=>{},s=new Promise(e=>{a=e}),u=setTimeout(()=>{a("timeout"),i?.abort(),o?.()},r),d=e=>Promise.race([e,s]);try{let r=await d(e(t,{mode:"cors",credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",cache:l,...i?{signal:i.signal}:{}}));if(r==="timeout")return{ok:!1,why:"timeout"};if(!r.ok)return{ok:!1,why:"http"};let a=Number(r.headers.get("content-length")??Number.NaN),s=r.body?.getReader()??null;if(o=()=>{s!==null&&s.cancel().catch(()=>{})},Number.isFinite(a)&&a>n)return o(),{ok:!1,why:"too-large"};if(s===null){let e=await d(r.arrayBuffer());return e==="timeout"?{ok:!1,why:"timeout"}:e.byteLength>n?{ok:!1,why:"too-large"}:{ok:!0,bytes:new Uint8Array(e)}}let u=[],c=0;for(;;){let e=await d(s.read());if(e==="timeout")return{ok:!1,why:"timeout"};if(e.done)break;if(c+=e.value.byteLength,c>n)return o(),{ok:!1,why:"too-large"};u.push(e.value)}let f=new Uint8Array(c),p=0;for(let e of u)f.set(e,p),p+=e.byteLength;return{ok:!0,bytes:f}}catch{return{ok:false,why:i?.signal.aborted?"timeout":"error"}}finally{clearTimeout(u)}}function Lc(e){let t=e.hasDom&&Object.keys(e.keys).length>0&&e.fetch!==null&&e.crypto!==null,r=e.manifestTimeoutMs??Zd,n=e.partTimeoutMs??Xd,l=e.manifestMaxBytes??Jd,i=e.partMaxBytes??ec,o=`${e.origin}/web-runtime`,a=null,s=/* @__PURE__ */new Map,u=/* @__PURE__ */new Map,d=/* @__PURE__ */new Map,c=/* @__PURE__ */new Map,f=null,p=null;async function h(){let t=await Nc(e.fetch,`${o}/${1}/manifest.json`,r,l,"no-store");if(!t.ok){let r=t.why==="timeout"?"manifest-timeout":t.why==="too-large"?"manifest-too-large":"manifest-fetch";if(t.why==="error"||t.why==="timeout")try{e.unreachable?.()?.setItem($c,`${e.now()+Dc}|${r}`)}catch{}return{ok:false,reason:r}}let n;try{n=JSON.parse((new TextDecoder).decode(t.bytes))}catch{return{ok:false,reason:"manifest-shape"}}return Oc(n,e.keys,e.crypto,e.now(),e.minIssuedAt??Qd)}function g(t){let r=t??"",n=s.get(r);if(n)return n;let l=(async()=>{a??=h();let r=await a;if(!r.ok)return{ok:false,reason:r.reason};let n=t===null?null:await jc(t,e.crypto),l=Ac(r.manifest,{tenantKey:n,sessionBucket:e.sessionBucket(),bundledVersion:e.bundledVersion});return l.use==="remote"?{ok:true,choice:l}:{ok:false,reason:l.reason}})();return s.set(r,l),l}async function m(t,r){if(await Promise.resolve(),mc())return{ok:false,reason:"disabled",version:null};let l=oc();if(l===null)return{ok:false,reason:"react-unregistered",version:null};let a=await g(r);if(!a.ok)return{ok:false,reason:a.reason,version:null};let{version:s,entry:u}=a.choice;if(!u.react.includes(l.reactMajor))return{ok:false,reason:"react-mismatch",version:s};let d=u.parts[t];if(d===void 0)return{ok:false,reason:"part-missing",version:s};if(!uc(t,s,d.integrity))return{ok:false,reason:"part-integrity",version:s};let c=sc(t,s);if(c!==null)return{ok:true,namespace:c,version:s};let f=`${o}/${s}/${d.path}`;if(mc())return{ok:false,reason:"disabled",version:s};let h=await Nc(e.fetch,f,n,i);if(!h.ok)return{ok:false,reason:h.why==="timeout"?"part-timeout":h.why==="too-large"?"part-too-large":"part-fetch",version:s};let m=h.bytes,b;try{b=`sha384-${Bc(new Uint8Array(await e.crypto.subtle.digest("SHA-384",m)))}`}catch{return{ok:false,reason:"part-integrity",version:s}}if(b!==d.integrity)return{ok:false,reason:"part-integrity",version:s};if(mc())return{ok:false,reason:"disabled",version:s};let y=e.createBlobUrl?.(m)??null,v="error";if(y!==null&&(v=await e.runScript(y,d.integrity,"blob",p),e.revokeBlobUrl(y)),v==="error"&&(v=await e.runScript(f,d.integrity,"cdn",p)),v==="error")return{ok:false,reason:"part-load",version:s};let w=await dc(t,s,50);return w===null?{ok:false,reason:"part-load",version:s}:{ok:true,namespace:w,version:s}}let b=t?null:e.hasDom?"disabled":"server";try{let[t,r]=(e.unreachable?.()?.getItem($c)??"").split("|");Number(t)>e.now()&&Mc.test(String(r))&&(b??=r)}catch{}function y(e,t){if(b!==null)return Promise.resolve({ok:false,reason:b,version:null});f??=t;let r=`${t??""}|${e}`,n=u.get(r);if(n)return n;let l=m(e,t).then(e=>e,()=>({ok:false,reason:"part-load",version:null}));return l.then(e=>d.set(r,e)),u.set(r,l),l}return t&&cc(e=>{let t=Object.prototype.hasOwnProperty.call(Yd,e)?Yd[e]:void 0,r=()=>{let t=c.get(e);return t?t():Promise.reject(new TypeError(`${e} is not available to the Everfur web runtime`))};return t===void 0?r():y(t,f).then(e=>e.ok?e.namespace:r())}),{enabled:t,peek:(e,t)=>b!==null?{ok:false,reason:b,version:null}:d.get(`${t??""}|${e}`)??null,load:y,registerHostSubpaths:e=>{for(let[t,r]of Object.entries(e))c.has(t)||c.set(t,r)},setCspNonce:e=>{p=e===null||e===""?null:e}}}var Uc="everfur:web-runtime:bucket",Hc=null;function Wc(){try{let e=globalThis.sessionStorage?.getItem(Uc);if(e)return e}catch{}Hc??=Math.floor(Math.random()*4294967296).toString(16);try{globalThis.sessionStorage?.setItem(Uc,Hc)}catch{}return Hc}function qc(e){return(t,r,n,l)=>new Promise(i=>{let o;try{o=e.createElement("script"),o.type="module",n==="cdn"&&(o.integrity=r,o.crossOrigin="anonymous"),l!==null&&(o.nonce=l),o.addEventListener("load",()=>{o.remove(),i("load")}),o.addEventListener("error",()=>{o.remove(),i("error")}),o.src=t,(e.head??e.documentElement).appendChild(o)}catch{i("error")}})}function Vc(){let e=typeof document>"u"?null:document,t=globalThis.crypto;return{origin:Vd,keys:Kd,bundledVersion:Me,fetch:typeof fetch=="function"?fetch.bind(globalThis):null,crypto:t?.subtle?t:null,hasDom:e!==null&&typeof window<"u",runScript:e===null?()=>Promise.resolve("error"):qc(e),createBlobUrl:typeof Blob=="function"&&typeof URL.createObjectURL=="function"?e=>{try{return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}catch{return null}}:null,revokeBlobUrl:e=>{try{URL.revokeObjectURL(e)}catch{}},now:()=>Date.now(),sessionBucket:Wc,unreachable:()=>globalThis.sessionStorage}}var Kc=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeLoader@${pc}`);function Gc(){let e=globalThis;return e[Kc]??=Lc(Vc())}var Yc=/* @__PURE__ */new Set(["disabled","server","bundled-newer"]),Qc=/* @__PURE__ */new Set;function Zc(e,t,r,n){if(Yc.has(r))return;let l=`${t}|${r}`;if(!Qc.has(l)){Qc.add(l);try{e?.trackExpectedFailure(tc,{part:t,reason:r,version:n,bundled:Me})}catch{}}}var Xc=/* @__PURE__ */new Set,Jc=class extends g{constructor(){super(...arguments);this.state={failed:false}}static getDerivedStateFromError(){return{failed:true}}componentDidCatch(){this.props.onError()}render(){return this.state.failed?this.props.fallback():this.props.children}},ef=/* @__PURE__ */new Map;function tf(e,t,r){let n=`${t??""}|${e.part}|${e.name}`,l=ef.get(n);return l===void 0&&(l=h(async()=>{let n=await Gc().load(e.part,t),l=n.ok?n.namespace[e.name]:void 0;return n.ok&&typeof l!="function"&&(typeof l!="object"||l===null)?(Zc(r.current,e.part,"part-missing",n.version),{default:e.bundled}):(n.ok||Zc(r.current,e.part,n.reason,n.version),{default:n.ok?l:e.bundled})}),ef.set(n,l)),l}var rf=()=>()=>{},nf=()=>false,lf=()=>true;function RuntimeSurface({spec:l,props:s}){let u=t(Pd),c=mc(),f=u?.publishableKey?u.publishableKey:null,p=o(null);p.current=u?.runtime.registry?.services?.telemetry??null;let h=n(rf,nf,lf),g=o(null),[,m]=i(0),y=c?null:Gc();if(l.hostSubpaths!==void 0&&y?.enabled&&y.registerHostSubpaths(l.hostSubpaths),h)g.current=l.wait==="bundled"&&y!==null?"hydrate":"bundled";else if(g.current===null)if(!y?.enabled||Xc.has(l.part))g.current="bundled";else if(ic({React:e,ReactDOM:b})===null)Zc(p.current,l.part,"react-mismatch",null),g.current="bundled";else{let e=y.peek(l.part,f);g.current=e===null?"suspense":e.ok?"direct":"bundled"}let v=g.current,w=h||v!=="hydrate"?null:y?.peek(l.part,f)??null,k=!h&&v==="hydrate"&&w===null&&y?.enabled===true&&!Xc.has(l.part);a(()=>{if(!k||y===null)return;if(ic({React:e,ReactDOM:b})===null){Zc(p.current,l.part,"react-mismatch",null);return}let t=true;return y.load(l.part,f).then(e=>{e.ok||Zc(p.current,l.part,e.reason,e.version),t&&m(e=>e+1)}),()=>{t=false}},[k,y,l.part,f]);let x=()=>r(l.bundled,s),C=e=>r(Jc,{fallback:x,onError:()=>{Xc.add(l.part),Zc(p.current,l.part,"render",null)},children:e});if(h||v==="bundled")return x();if(v==="hydrate"||v==="direct"){let e=w??y?.peek(l.part,f),t=e?.ok?e.namespace[l.name]:void 0;return t===void 0||Xc.has(l.part)?x():C(r(t,s))}let S=tf(l,f,p),_=l.wait==="bundled"?x():r("div",{"data-everfur-runtime":"loading","aria-busy":true});return C(r(d,{fallback:_},r(S,s)))}var of=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeRenderer@${pc}`),af=globalThis;function sf(e,t=false){e===null?delete af[of]:(t||af[of]===void 0)&&(af[of]=e)}var uf=RuntimeSurface,df=(e,t)=>r(uf,{spec:e,props:t});function cf(e){if(sf(df),e!==void 0&&e!==""){let t=Gc();t.enabled&&t.setCspNonce(e)}}var ff=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[ff[t]]}}function pf(e,t){let{scale:r,scaleCaps:n}=e.type,l=n[t];return l>0?Math.min(r,l):r}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[ff[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function hf(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var gf=/* @__PURE__ */new Map,mf=/* @__PURE__ */new Set,bf=typeof document>"u"?a:u;function yf(e){return e.cssSrc!==void 0?`css\n${e.cssSrc}`:`file\n${e.family}\n${e.src??""}\n${e.weight??"400"}\n${e.style??"normal"}`}function vf(e,t){if(!t)return;let r=e.cssSrc??e.src??"",n=`[everfur] A font in appearance.fonts did not load: "${e.family}" from ${r}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(e.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!mf.has(n)){mf.add(n);try{globalThis.console?.warn?.(n)}catch{}}}function wf(e){let t=document.getElementsByTagName("link");for(let r=0;r<t.length;r+=1){let n=t[r];if(n.rel==="stylesheet"&&n.getAttribute("href")===e)return n}return null}function kf(e){return wf(e)!==null?Promise.resolve(true):new Promise(t=>{let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-everfur-font",""),r.addEventListener("load",()=>t(true)),r.addEventListener("error",()=>t(false)),document.head.appendChild(r)})}function xf(e){let t=document.fonts;return new FontFace(e.family,`url("${e.src}")`,{display:"swap",weight:e.weight??"400",style:e.style??"normal"}).load().then(e=>(t.add(e),true)).catch(()=>false)}function Cf(e,t=false){let r=yf(e),n=gf.get(r);if(n===void 0){n=Promise.resolve(false);try{if(typeof document<"u"){let t=e.cssSrc===void 0?null:ls(e.cssSrc),r=e.src===void 0?null:ls(e.src);t!==null?n=kf(t):r!==null&&(n=xf({...e,src:r}))}}catch{n=Promise.resolve(false)}let l=n.then(r=>(r||vf(e,t),r));gf.set(r,l),n=l}return n}function Sf(e,t){let r=e.type.fontSources;bf(()=>{if(r.length===0)return;let e=false;try{e=t()}catch{}for(let t of r)Cf(t,e)},[r,t])}var _f=/* @__PURE__ */new RegExp(`^${La}\\/fonts\\/[\\w./-]+\\.woff2$`);function Rf(e){return _f.test(e)&&!e.includes("..")}var If=/* @__PURE__ */new Map;function zf(e,t,r="400"){let n=e.trim(),l=`${n}\n${t}\n${r}`,i=If.get(l);if(i===void 0){if(i=Promise.resolve(false),t!==null&&n!==""&&n!=="System"&&Rf(t))try{let e=document.fonts;i=new FontFace(n,`url("${t}") format("woff2")`,{display:"swap",weight:r}).load().then(t=>(e.add(t),!0)).catch(()=>!1)}catch{}If.set(l,i)}return i}var Tf=["regular","medium","bold","mono","monoMedium","monoBold"];function Of(e){let{families:t,fontUrls:r,weight:n,namedFaces:l}=e.type;a(()=>{for(let e of Tf){let i=r[e];i!=null&&zf(t[e],i,l[e]?n.regular:n[ff[e]])}},[t,r,n,l]),Sf(e,hf)}function Pf(e){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(e)??null}catch{return null}}function Ef(e){return t=>{let r=Pf(e);return r===null||typeof r.addEventListener!="function"?()=>{}:(r.addEventListener("change",t),()=>r.removeEventListener?.("change",t))}}var Ff="(prefers-color-scheme: dark)",jf="(prefers-color-scheme: light)",Af="(prefers-reduced-motion: reduce)",Mf="(prefers-contrast: more)",$f=Ef(Ff),Df=Ef(Af),Bf=Ef(Mf);function Nf(){let e=Pf(Ff);return e===null?null:e.matches?"dark":Pf(jf)?.matches?"light":null}function Lf(){return Pf(Af)?.matches===true}function Uf(){return Pf(Mf)?.matches===true}var Hf=16,Wf=false;var qf=null;function Vf(e){return Number.parseFloat(window.getComputedStyle(e).fontSize)}function Kf(){let e=document.body??document.documentElement,t=document.createElement("span");t.setAttribute("aria-hidden","true"),t.style.setProperty("position","absolute","important"),t.style.setProperty("visibility","hidden","important"),t.style.setProperty("font-size","medium","important"),e.appendChild(t);try{return Vf(t)}finally{t.remove()}}function Gf(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let e=Wf?Vf(document.documentElement):Kf();return Number.isFinite(e)&&e>0?e/Hf:1}catch{return 1}}function Yf(){return qf===null&&(qf=Gf()),qf}function Qf(e){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let t=()=>{qf=null,e()};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)}function Zf(){return n($f,Nf,()=>null)}function Xf(){return n(Df,Lf,()=>false)}function Jf(){return n(Bf,Uf,()=>false)}function ep(){return n(Qf,Yf,()=>1)}var tp=/* @__PURE__ */Object.freeze({useColorScheme:Zf,useReducedMotion:Xf,useTextScale:ep,useHighContrast:Jf,scaleTypeSizes:true,useResolvedTheme:Of,isDevelopment:hf});function rp(e){return e.storage===void 0?{...e,storage:createLocalStorageKv()}:e}var np=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:rp,theme:tp});function EverfurProvider(e){let{cspNonce:t,webRuntime:n,...l}=e;return n!==void 0&&n!=="updates"&&bc(),mc()||cf(t),r(EverfurProviderCore,{...l,seams:np})}function useCapability(e){let{runtime:t}=Ed(),r=t.entitlements,i=n(r.subscribe,r.getSnapshot,r.getSnapshot);return l(()=>decideCapability(e,i.decisions,{isPending:i.isPending}),[e,i])}function lp(e){let{runtime:t}=Ed(),r=t.entitlements,l=s(e=>r===void 0?()=>{}:r.subscribe(e),[r]),i=s(()=>{if(r===void 0)return false;let t=r.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[r,e]);return n(l,i,i)}var ip=class extends g{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:t,resetKey:n}){return r(ip,{fallback:t,resetKey:n,children:r(RenderHost,{render:e})})}function op(e,t,r){return Math.round(r*pf(e,t)*10)/10}var ap='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',sp="System";function up(e){let t=e.trim();return t.length===0||t===sp?ap:`${cp(t)}, ${ap}`}function dp(e){let t=e.trim();return t.length===0||t==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${cp(t)}, ui-monospace, Menlo, Consolas, monospace`}function cp(e){return`"${e.replace(/[\\"]/g,"\\$&")}"`}function faceCss(e,t){let r=e.type,n=r.families[t];return{fontFamily:t==="mono"||t==="monoMedium"||t==="monoBold"?dp(n):up(n),fontWeight:r.namedFaces[t]?r.weight.regular:r.weight[ff[t]]}}function headingFaceCss(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type,l=faceCss(e,t);return r===null&&n===null?l:r!==null?{fontFamily:up(r),fontWeight:n??e.type.weight[ff[t]]}:e.type.namedFaces[t]||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}var fp=/* @__PURE__ */Object.freeze({textAlign:"start"});var pp=48;function hp(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:t,children:r,renderDisabled:n,renderPending:i,style:o,className:a}=e,s=useCapability(t),u=l(()=>hp(s),[s]);switch(u){case"enabled":return r;case"pending":return i?/* @__PURE__ */v(HostRender,{render:i,fallback:/* @__PURE__ */v(PendingSkeleton,{capability:t,style:o,className:a})}):/* @__PURE__ */v(PendingSkeleton,{capability:t,style:o,className:a});case"disabled":return n?/* @__PURE__ */v(HostRender,{render:()=>n(s),fallback:/* @__PURE__ */v(OffState,{decision:s,style:o,className:a}),resetKey:s}):/* @__PURE__ */v(OffState,{decision:s,style:o,className:a});default:return assertNever(u)}}function PendingSkeleton({capability:e,style:t,className:r}){let n=useEverfurTheme(),i=l(()=>gp(n),[n]);/* @__PURE__ */
49
+ return Object.freeze(r)}catch{return[]}}}}var Vd="https://sdk.everfur.com",Kd=/* @__PURE__ */Object.freeze({k1:"X4wc1hwVONs4I9Vmclo9ExrfPZlH8-tgY7NmzxuA5lI"}),Gd=/* @__PURE__ */Object.freeze(["health-plan","health-plan-today","shop","shop-orders-v2","ui","televet-booking","televet-call"]),Yd=/* @__PURE__ */Object.freeze({"@everfur/sdk/web/health-plan":"health-plan","@everfur/sdk/web/health-plan/today":"health-plan-today","@everfur/sdk/web/shop":"shop","@everfur/sdk/web/shop/orders-v2":"shop-orders-v2","@everfur/sdk/web/ui":"ui","@everfur/sdk/web/televet/booking":"televet-booking","@everfur/sdk/web/televet/call":"televet-call"}),Qd=1795021773e3,Zd=3e3,Xd=8e3,Jd=256*1024,ec=4*1024*1024,tc="web_runtime.fallback";var rc=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBridge@v${1}`);function nc(){let e=globalThis,t=e[rc];if(t!==void 0)return t;let r={major:1,host:null,defined:/* @__PURE__ */new Map,waiters:/* @__PURE__ */new Map,importSubpath:null};return e[rc]=r,r}function lc(e){if(typeof e!="string")return null;let t=/^(\d+)\./.exec(e);return t===null?null:Number(t[1])}function ic(e){let t=lc(e.React?.version);if(t===null||typeof e.React.createElement!="function")return null;let r=nc();return r.host===null?(r.host={...e,reactMajor:t},{reactMajor:t}):r.host.React.createElement===e.React.createElement&&r.host.reactMajor===t?{reactMajor:t}:null}function oc(){return nc().host}var ac=(e,t)=>`${e}@${t}`;function sc(e,t){return nc().defined.get(ac(e,t))??null}function uc(e,t,r){let n=nc(),l=n.ran??=/* @__PURE__ */new Map,i=ac(e,t),o=l.get(i);return o===void 0?n.defined.has(i)?false:(l.set(i,r),true):o===r}function dc(e,t,r){let n=sc(e,t);if(n!==null)return Promise.resolve(n);let l=nc(),i=ac(e,t);return new Promise(e=>{let t=l.waiters.get(i)??/* @__PURE__ */new Set;l.waiters.set(i,t);let n=r=>{clearTimeout(a),t.delete(o),e(r)},o=e=>n(e),a=setTimeout(()=>n(null),r);t.add(o)})}function cc(e){nc().importSubpath=e}function fc(e,t){let r=Object.keys(t).sort().map(e=>`${e}=${t[e]}`).join(",");return`v${1}|${e}|${r}`}var pc=fc(Me,Kd);var hc=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeBundledOnly@v${1}`),gc=globalThis,mc=()=>gc[hc]===true,bc=()=>{gc[hc]=true};var yc=/^\d{1,4}\.\d{1,5}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,64})?$/,vc=/^[a-z0-9][a-z0-9.-]{0,80}\.js$/,wc=/^sha384-[A-Za-z0-9+/]{64}$/,kc=/^[0-9a-f]{32}$/,xc=/^[A-Za-z0-9_-]+$/,Cc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Sc(e){if(typeof e!="string"||e.length===0||!xc.test(e))return null;let t=e.replace(/-/g,"+").replace(/_/g,"/");try{let e=atob(t+"=".repeat((4-t.length%4)%4)),r=new Uint8Array(e.length);for(let t=0;t<e.length;t+=1)r[t]=e.charCodeAt(t);return r}catch{return null}}var _c=/^\d{4}(-\d\d){2}T\d\d(:\d\d){2}(\.\d{1,3})?Z$/,Rc=14*864e5;function Ic(e){if(typeof e!="string"||!_c.test(e))return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function zc(e){if(!Cc(e)||!Array.isArray(e.react)||!Cc(e.parts))return null;let t=e.react.filter(e=>Number.isInteger(e)&&e>0);if(t.length===0||t.length!==e.react.length)return null;let r={};for(let[t,n]of Object.entries(e.parts))if(Gd.includes(t)){if(!Cc(n)||typeof n.path!="string"||typeof n.integrity!="string"||!vc.test(n.path)||!wc.test(n.integrity))return null;r[t]={path:n.path,integrity:n.integrity}}return{react:t,parts:r}}function Tc(e){if(!Cc(e)||e.schema!==1||!Number.isInteger(e.major))return null;let t=Ic(e.issuedAt),r=Ic(e.expiresAt);if(t===null||r===null||typeof e.stable!="string"||!yc.test(e.stable)||r<=t||r-t>Rc||!Cc(e.versions))return null;let n={};for(let[t,r]of Object.entries(e.versions)){let e=zc(r);if(!yc.test(t)||e===null)return null;n[t]=e}let l=null;if(e.canary!==void 0&&e.canary!==null){let t=e.canary;if(!Cc(t)||typeof t.version!="string"||!yc.test(t.version)||typeof t.percent!="number"||!Number.isFinite(t.percent)||t.percent<0||t.percent>100)return null;l={version:t.version,percent:t.percent}}let i={};if(e.pins!==void 0){if(!Cc(e.pins))return null;for(let[t,r]of Object.entries(e.pins)){if(!kc.test(t)||typeof r!="string"||!yc.test(r))return null;i[t]=r}}let o=[];if(e.revoked!==void 0){if(!Array.isArray(e.revoked)||!e.revoked.every(e=>typeof e=="string"&&yc.test(e)))return null;o=e.revoked}return{schema:1,major:e.major,issuedAt:t,expiresAt:r,stable:e.stable,canary:l,pins:i,revoked:o,versions:n}}async function Oc(e,t,r,n,l=Qd){if(!Cc(e)||e.v!==1||typeof e.keyId!="string")return{ok:false,reason:"manifest-shape"};let i=Sc(e.payload),o=Sc(e.signature);if(i===null||o===null||o.length!==64)return{ok:false,reason:"manifest-shape"};let a=Object.prototype.hasOwnProperty.call(t,e.keyId)?Sc(t[e.keyId]):null;if(a===null||a.length!==32)return{ok:false,reason:"signature-key"};let s;try{let e=await r.subtle.importKey("raw",a,{name:"Ed25519"},!1,["verify"]);s=await r.subtle.verify({name:"Ed25519"},e,o,i)}catch{return{ok:false,reason:"signature-unsupported"}}if(!s)return{ok:false,reason:"signature-invalid"};let u;try{u=JSON.parse((new TextDecoder).decode(i))}catch{return{ok:false,reason:"manifest-shape"}}let d=Tc(u);return d===null?{ok:false,reason:"manifest-shape"}:d.major!==1?{ok:false,reason:"manifest-major"}:n>=d.expiresAt?{ok:false,reason:"manifest-expired"}:d.issuedAt<l?{ok:false,reason:"manifest-stale"}:{ok:true,manifest:d}}function Pc(e,t){let[r="",n]=e.split(/-(.*)/s,2),[l="",i]=t.split(/-(.*)/s,2),o=r.split(".").map(Number),a=l.split(".").map(Number);for(let e=0;e<3;e+=1){let t=(o[e]??0)-(a[e]??0);if(t!==0)return t<0?-1:1}if(n===i)return 0;if(n===void 0)return 1;if(i===void 0)return-1;let s=n.split("."),u=i.split(".");for(let e=0;;e+=1){let t=s[e],r=u[e];if(t===r)continue;if(t===void 0||r===void 0)return t===void 0?-1:1;let n=/^\d+$/.test(t),l=/^\d+$/.test(r);return n!==l?n?-1:1:(n?Number(t)<Number(r):t<r)?-1:1}}function Ec(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0}function Fc(e,t){return Ec(`${e??"-"}:${t}`)%100}async function jc(e,t){try{let r=await t.subtle.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,"0")).join("").slice(0,32)}catch{return null}}function Ac(e,t){let r=t.tenantKey===null?void 0:e.pins[t.tenantKey],n,l;if(r!==void 0?(n=r,l="pin"):e.canary!==null&&Fc(t.tenantKey,t.sessionBucket)<e.canary.percent?(n=e.canary.version,l="canary"):(n=e.stable,l="stable"),e.revoked.includes(n))return{use:"bundled",reason:"revoked"};if(l!=="pin"&&Pc(n,t.bundledVersion)<0&&!e.revoked.includes(t.bundledVersion))return{use:"bundled",reason:"bundled-newer"};let i=e.versions[n];return i===void 0?{use:"bundled",reason:"version-missing"}:{use:"remote",version:n,entry:i,reason:l}}var Mc=/^manifest-(fetch|timeout)$/,$c="everfur:web-runtime:unreachable",Dc=10*6e4;function Bc(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function Nc(e,t,r,n,l="default"){let i=typeof AbortController=="function"?new AbortController:null,o=null,a=()=>{},s=new Promise(e=>{a=e}),u=setTimeout(()=>{a("timeout"),i?.abort(),o?.()},r),d=e=>Promise.race([e,s]);try{let r=await d(e(t,{mode:"cors",credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",cache:l,...i?{signal:i.signal}:{}}));if(r==="timeout")return{ok:!1,why:"timeout"};if(!r.ok)return{ok:!1,why:"http"};let a=Number(r.headers.get("content-length")??Number.NaN),s=r.body?.getReader()??null;if(o=()=>{s!==null&&s.cancel().catch(()=>{})},Number.isFinite(a)&&a>n)return o(),{ok:!1,why:"too-large"};if(s===null){let e=await d(r.arrayBuffer());return e==="timeout"?{ok:!1,why:"timeout"}:e.byteLength>n?{ok:!1,why:"too-large"}:{ok:!0,bytes:new Uint8Array(e)}}let u=[],c=0;for(;;){let e=await d(s.read());if(e==="timeout")return{ok:!1,why:"timeout"};if(e.done)break;if(c+=e.value.byteLength,c>n)return o(),{ok:!1,why:"too-large"};u.push(e.value)}let f=new Uint8Array(c),p=0;for(let e of u)f.set(e,p),p+=e.byteLength;return{ok:!0,bytes:f}}catch{return{ok:false,why:i?.signal.aborted?"timeout":"error"}}finally{clearTimeout(u)}}function Lc(e){let t=e.hasDom&&Object.keys(e.keys).length>0&&e.fetch!==null&&e.crypto!==null,r=e.manifestTimeoutMs??Zd,n=e.partTimeoutMs??Xd,l=e.manifestMaxBytes??Jd,i=e.partMaxBytes??ec,o=`${e.origin}/web-runtime`,a=null,s=/* @__PURE__ */new Map,u=/* @__PURE__ */new Map,d=/* @__PURE__ */new Map,c=/* @__PURE__ */new Map,f=null,p=null;async function h(){let t=await Nc(e.fetch,`${o}/${1}/manifest.json`,r,l,"no-store");if(!t.ok){let r=t.why==="timeout"?"manifest-timeout":t.why==="too-large"?"manifest-too-large":"manifest-fetch";if(t.why==="error"||t.why==="timeout")try{e.unreachable?.()?.setItem($c,`${e.now()+Dc}|${r}`)}catch{}return{ok:false,reason:r}}let n;try{n=JSON.parse((new TextDecoder).decode(t.bytes))}catch{return{ok:false,reason:"manifest-shape"}}return Oc(n,e.keys,e.crypto,e.now(),e.minIssuedAt??Qd)}function g(t){let r=t??"",n=s.get(r);if(n)return n;let l=(async()=>{a??=h();let r=await a;if(!r.ok)return{ok:false,reason:r.reason};let n=t===null?null:await jc(t,e.crypto),l=Ac(r.manifest,{tenantKey:n,sessionBucket:e.sessionBucket(),bundledVersion:e.bundledVersion});return l.use==="remote"?{ok:true,choice:l}:{ok:false,reason:l.reason}})();return s.set(r,l),l}async function m(t,r){if(await Promise.resolve(),mc())return{ok:false,reason:"disabled",version:null};let l=oc();if(l===null)return{ok:false,reason:"react-unregistered",version:null};let a=await g(r);if(!a.ok)return{ok:false,reason:a.reason,version:null};let{version:s,entry:u}=a.choice;if(!u.react.includes(l.reactMajor))return{ok:false,reason:"react-mismatch",version:s};let d=u.parts[t];if(d===void 0)return{ok:false,reason:"part-missing",version:s};if(!uc(t,s,d.integrity))return{ok:false,reason:"part-integrity",version:s};let c=sc(t,s);if(c!==null)return{ok:true,namespace:c,version:s};let f=`${o}/${s}/${d.path}`;if(mc())return{ok:false,reason:"disabled",version:s};let h=await Nc(e.fetch,f,n,i);if(!h.ok)return{ok:false,reason:h.why==="timeout"?"part-timeout":h.why==="too-large"?"part-too-large":"part-fetch",version:s};let m=h.bytes,b;try{b=`sha384-${Bc(new Uint8Array(await e.crypto.subtle.digest("SHA-384",m)))}`}catch{return{ok:false,reason:"part-integrity",version:s}}if(b!==d.integrity)return{ok:false,reason:"part-integrity",version:s};if(mc())return{ok:false,reason:"disabled",version:s};let y=e.createBlobUrl?.(m)??null,v="error";if(y!==null&&(v=await e.runScript(y,d.integrity,"blob",p),e.revokeBlobUrl(y)),v==="error"&&(v=await e.runScript(f,d.integrity,"cdn",p)),v==="error")return{ok:false,reason:"part-load",version:s};let w=await dc(t,s,50);return w===null?{ok:false,reason:"part-load",version:s}:{ok:true,namespace:w,version:s}}let b=t?null:e.hasDom?"disabled":"server";try{let[t,r]=(e.unreachable?.()?.getItem($c)??"").split("|");Number(t)>e.now()&&Mc.test(String(r))&&(b??=r)}catch{}function y(e,t){if(b!==null)return Promise.resolve({ok:false,reason:b,version:null});f??=t;let r=`${t??""}|${e}`,n=u.get(r);if(n)return n;let l=m(e,t).then(e=>e,()=>({ok:false,reason:"part-load",version:null}));return l.then(e=>d.set(r,e)),u.set(r,l),l}return t&&cc(e=>{let t=Object.prototype.hasOwnProperty.call(Yd,e)?Yd[e]:void 0,r=()=>{let t=c.get(e);return t?t():Promise.reject(new TypeError(`${e} is not available to the Everfur web runtime`))};return t===void 0?r():y(t,f).then(e=>e.ok?e.namespace:r())}),{enabled:t,peek:(e,t)=>b!==null?{ok:false,reason:b,version:null}:d.get(`${t??""}|${e}`)??null,load:y,registerHostSubpaths:e=>{for(let[t,r]of Object.entries(e))c.has(t)||c.set(t,r)},setCspNonce:e=>{p=e===null||e===""?null:e}}}var Uc="everfur:web-runtime:bucket",Hc=null;function Wc(){try{let e=globalThis.sessionStorage?.getItem(Uc);if(e)return e}catch{}Hc??=Math.floor(Math.random()*4294967296).toString(16);try{globalThis.sessionStorage?.setItem(Uc,Hc)}catch{}return Hc}function qc(e){return(t,r,n,l)=>new Promise(i=>{let o;try{o=e.createElement("script"),o.type="module",n==="cdn"&&(o.integrity=r,o.crossOrigin="anonymous"),l!==null&&(o.nonce=l),o.addEventListener("load",()=>{o.remove(),i("load")}),o.addEventListener("error",()=>{o.remove(),i("error")}),o.src=t,(e.head??e.documentElement).appendChild(o)}catch{i("error")}})}function Vc(){let e=typeof document>"u"?null:document,t=globalThis.crypto;return{origin:Vd,keys:Kd,bundledVersion:Me,fetch:typeof fetch=="function"?fetch.bind(globalThis):null,crypto:t?.subtle?t:null,hasDom:e!==null&&typeof window<"u",runScript:e===null?()=>Promise.resolve("error"):qc(e),createBlobUrl:typeof Blob=="function"&&typeof URL.createObjectURL=="function"?e=>{try{return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}catch{return null}}:null,revokeBlobUrl:e=>{try{URL.revokeObjectURL(e)}catch{}},now:()=>Date.now(),sessionBucket:Wc,unreachable:()=>globalThis.sessionStorage}}var Kc=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeLoader@${pc}`);function Gc(){let e=globalThis;return e[Kc]??=Lc(Vc())}var Yc=/* @__PURE__ */new Set(["disabled","server","bundled-newer"]),Qc=/* @__PURE__ */new Set;function Zc(e,t,r,n){if(Yc.has(r))return;let l=`${t}|${r}`;if(!Qc.has(l)){Qc.add(l);try{e?.trackExpectedFailure(tc,{part:t,reason:r,version:n,bundled:Me})}catch{}}}var Xc=/* @__PURE__ */new Set,Jc=class extends g{constructor(){super(...arguments);this.state={failed:false}}static getDerivedStateFromError(){return{failed:true}}componentDidCatch(){this.props.onError()}render(){return this.state.failed?this.props.fallback():this.props.children}},ef=/* @__PURE__ */new Map;function tf(e,t,r){let n=`${t??""}|${e.part}|${e.name}`,l=ef.get(n);return l===void 0&&(l=h(async()=>{let n=await Gc().load(e.part,t),l=n.ok?n.namespace[e.name]:void 0;return n.ok&&typeof l!="function"&&(typeof l!="object"||l===null)?(Zc(r.current,e.part,"part-missing",n.version),{default:e.bundled}):(n.ok||Zc(r.current,e.part,n.reason,n.version),{default:n.ok?l:e.bundled})}),ef.set(n,l)),l}var rf=()=>()=>{},nf=()=>false,lf=()=>true;function RuntimeSurface({spec:l,props:s}){let u=t(Pd),c=mc(),f=u?.publishableKey?u.publishableKey:null,p=o(null);p.current=u?.runtime.registry?.services?.telemetry??null;let h=n(rf,nf,lf),g=o(null),[,m]=i(0),y=c?null:Gc();if(l.hostSubpaths!==void 0&&y?.enabled&&y.registerHostSubpaths(l.hostSubpaths),h)g.current=l.wait==="bundled"&&y!==null?"hydrate":"bundled";else if(g.current===null)if(!y?.enabled||Xc.has(l.part))g.current="bundled";else if(ic({React:e,ReactDOM:b})===null)Zc(p.current,l.part,"react-mismatch",null),g.current="bundled";else{let e=y.peek(l.part,f);g.current=e===null?"suspense":e.ok?"direct":"bundled"}let v=g.current,w=h||v!=="hydrate"?null:y?.peek(l.part,f)??null,k=!h&&v==="hydrate"&&w===null&&y?.enabled===true&&!Xc.has(l.part);a(()=>{if(!k||y===null)return;if(ic({React:e,ReactDOM:b})===null){Zc(p.current,l.part,"react-mismatch",null);return}let t=true;return y.load(l.part,f).then(e=>{e.ok||Zc(p.current,l.part,e.reason,e.version),t&&m(e=>e+1)}),()=>{t=false}},[k,y,l.part,f]);let x=()=>r(l.bundled,s),C=e=>r(Jc,{fallback:x,onError:()=>{Xc.add(l.part),Zc(p.current,l.part,"render",null)},children:e});if(h||v==="bundled")return x();if(v==="hydrate"||v==="direct"){let e=w??y?.peek(l.part,f),t=e?.ok?e.namespace[l.name]:void 0;return t===void 0||Xc.has(l.part)?x():C(r(t,s))}let S=tf(l,f,p),_=l.wait==="bundled"?x():r("div",{"data-everfur-runtime":"loading","aria-busy":true});return C(r(d,{fallback:_},r(S,s)))}var of=/* @__PURE__ */Symbol.for(`@everfur/sdk#WebRuntimeRenderer@${pc}`),af=globalThis;function sf(e,t=false){e===null?delete af[of]:(t||af[of]===void 0)&&(af[of]=e)}var uf=RuntimeSurface,df=(e,t)=>r(uf,{spec:e,props:t});function cf(e){if(sf(df),e!==void 0&&e!==""){let t=Gc();t.enabled&&t.setCspNonce(e)}}var ff=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[ff[t]]}}function pf(e,t){let{scale:r,scaleCaps:n}=e.type,l=n[t];return l>0?Math.min(r,l):r}function headingFace(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type;if(r===null&&n===null)return face(e,t);if(r!==null)return{fontFamily:r,fontWeight:n??e.type.weight[ff[t]]};let l=face(e,t);return l.fontWeight===void 0||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}function hf(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var gf=/* @__PURE__ */new Map,mf=/* @__PURE__ */new Set,bf=typeof document>"u"?a:u;function yf(e){return e.cssSrc!==void 0?`css\n${e.cssSrc}`:`file\n${e.family}\n${e.src??""}\n${e.weight??"400"}\n${e.style??"normal"}`}function vf(e,t){if(!t)return;let r=e.cssSrc??e.src??"",n=`[everfur] A font in appearance.fonts did not load: "${e.family}" from ${r}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(e.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!mf.has(n)){mf.add(n);try{globalThis.console?.warn?.(n)}catch{}}}function wf(e){let t=document.getElementsByTagName("link");for(let r=0;r<t.length;r+=1){let n=t[r];if(n.rel==="stylesheet"&&n.getAttribute("href")===e)return n}return null}function kf(e){return wf(e)!==null?Promise.resolve(true):new Promise(t=>{let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-everfur-font",""),r.addEventListener("load",()=>t(true)),r.addEventListener("error",()=>t(false)),document.head.appendChild(r)})}function xf(e){let t=document.fonts;return new FontFace(e.family,`url("${e.src}")`,{display:"swap",weight:e.weight??"400",style:e.style??"normal"}).load().then(e=>(t.add(e),true)).catch(()=>false)}function Cf(e,t=false){let r=yf(e),n=gf.get(r);if(n===void 0){n=Promise.resolve(false);try{if(typeof document<"u"){let t=e.cssSrc===void 0?null:ls(e.cssSrc),r=e.src===void 0?null:ls(e.src);t!==null?n=kf(t):r!==null&&(n=xf({...e,src:r}))}}catch{n=Promise.resolve(false)}let l=n.then(r=>(r||vf(e,t),r));gf.set(r,l),n=l}return n}function Sf(e,t){let r=e.type.fontSources;bf(()=>{if(r.length===0)return;let e=false;try{e=t()}catch{}for(let t of r)Cf(t,e)},[r,t])}var _f=/* @__PURE__ */new RegExp(`^${La}\\/fonts\\/[\\w./-]+\\.woff2$`);function Rf(e){return _f.test(e)&&!e.includes("..")}var If=/* @__PURE__ */new Map;function zf(e,t,r="400"){let n=e.trim(),l=`${n}\n${t}\n${r}`,i=If.get(l);if(i===void 0){if(i=Promise.resolve(false),t!==null&&n!==""&&n!=="System"&&Rf(t))try{let e=document.fonts;i=new FontFace(n,`url("${t}") format("woff2")`,{display:"swap",weight:r}).load().then(t=>(e.add(t),!0)).catch(()=>!1)}catch{}If.set(l,i)}return i}var Tf=["regular","medium","bold","mono","monoMedium","monoBold"];function Of(e){let{families:t,fontUrls:r,weight:n,namedFaces:l}=e.type;a(()=>{for(let e of Tf){let i=r[e];i!=null&&zf(t[e],i,l[e]?n.regular:n[ff[e]])}},[t,r,n,l]),Sf(e,hf)}function Pf(e){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(e)??null}catch{return null}}function Ef(e){return t=>{let r=Pf(e);return r===null||typeof r.addEventListener!="function"?()=>{}:(r.addEventListener("change",t),()=>r.removeEventListener?.("change",t))}}var Ff="(prefers-color-scheme: dark)",jf="(prefers-color-scheme: light)",Af="(prefers-reduced-motion: reduce)",Mf="(prefers-contrast: more)",$f=Ef(Ff),Df=Ef(Af),Bf=Ef(Mf);function Nf(){let e=Pf(Ff);return e===null?null:e.matches?"dark":Pf(jf)?.matches?"light":null}function Lf(){return Pf(Af)?.matches===true}function Uf(){return Pf(Mf)?.matches===true}var Hf=16,Wf=false;var qf=null;function Vf(e){return Number.parseFloat(window.getComputedStyle(e).fontSize)}function Kf(){let e=document.body??document.documentElement,t=document.createElement("span");t.setAttribute("aria-hidden","true"),t.style.setProperty("position","absolute","important"),t.style.setProperty("visibility","hidden","important"),t.style.setProperty("font-size","medium","important"),e.appendChild(t);try{return Vf(t)}finally{t.remove()}}function Gf(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let e=Wf?Vf(document.documentElement):Kf();return Number.isFinite(e)&&e>0?e/Hf:1}catch{return 1}}function Yf(){return qf===null&&(qf=Gf()),qf}function Qf(e){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let t=()=>{qf=null,e()};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)}function Zf(){return n($f,Nf,()=>null)}function Xf(){return n(Df,Lf,()=>false)}function Jf(){return n(Bf,Uf,()=>false)}function ep(){return n(Qf,Yf,()=>1)}var tp=/* @__PURE__ */Object.freeze({useColorScheme:Zf,useReducedMotion:Xf,useTextScale:ep,useHighContrast:Jf,scaleTypeSizes:true,useResolvedTheme:Of,isDevelopment:hf});function rp(e){return e.storage===void 0?{...e,storage:createLocalStorageKv()}:e}var np=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:rp,theme:tp});function EverfurProvider(e){let{cspNonce:t,webRuntime:n,...l}=e;return n!==void 0&&n!=="updates"&&bc(),mc()||cf(t),r(EverfurProviderCore,{...l,seams:np})}function useCapability(e){let{runtime:t}=Ed(),r=t.entitlements,i=n(r.subscribe,r.getSnapshot,r.getSnapshot);return l(()=>decideCapability(e,i.decisions,{isPending:i.isPending}),[e,i])}function lp(e){let{runtime:t}=Ed(),r=t.entitlements,l=s(e=>r===void 0?()=>{}:r.subscribe(e),[r]),i=s(()=>{if(r===void 0)return false;let t=r.getSnapshot();return decideCapability(e,t.decisions,{isPending:t.isPending}).enabled},[r,e]);return n(l,i,i)}var ip=class extends g{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:e,fallback:t,resetKey:n}){return r(ip,{fallback:t,resetKey:n,children:r(RenderHost,{render:e})})}function op(e,t,r){return Math.round(r*pf(e,t)*10)/10}var ap='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',sp="System";function up(e){let t=e.trim();return t.length===0||t===sp?ap:`${cp(t)}, ${ap}`}function dp(e){let t=e.trim();return t.length===0||t==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${cp(t)}, ui-monospace, Menlo, Consolas, monospace`}function cp(e){return`"${e.replace(/[\\"]/g,"\\$&")}"`}function faceCss(e,t){let r=e.type,n=r.families[t];return{fontFamily:t==="mono"||t==="monoMedium"||t==="monoBold"?dp(n):up(n),fontWeight:r.namedFaces[t]?r.weight.regular:r.weight[ff[t]]}}function headingFaceCss(e,t="bold"){let{headingFamily:r,headingWeight:n}=e.type,l=faceCss(e,t);return r===null&&n===null?l:r!==null?{fontFamily:up(r),fontWeight:n??e.type.weight[ff[t]]}:e.type.namedFaces[t]||n===null?l:{fontFamily:l.fontFamily,fontWeight:n}}var fp=/* @__PURE__ */Object.freeze({textAlign:"start"});var pp=48;function hp(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}function CapabilityGate(e){let{capability:t,children:r,renderDisabled:n,renderPending:i,style:o,className:a}=e,s=useCapability(t),u=l(()=>hp(s),[s]);switch(u){case"enabled":return r;case"pending":return i?/* @__PURE__ */v(HostRender,{render:i,fallback:/* @__PURE__ */v(PendingSkeleton,{capability:t,style:o,className:a})}):/* @__PURE__ */v(PendingSkeleton,{capability:t,style:o,className:a});case"disabled":return n?/* @__PURE__ */v(HostRender,{render:()=>n(s),fallback:/* @__PURE__ */v(OffState,{decision:s,style:o,className:a}),resetKey:s}):/* @__PURE__ */v(OffState,{decision:s,style:o,className:a});default:return assertNever(u)}}function PendingSkeleton({capability:e,style:t,className:r}){let n=useEverfurTheme(),i=l(()=>gp(n),[n]);/* @__PURE__ */
50
50
  return v("div",{role:"status","aria-busy":"true","aria-label":`Loading ${e}`,className:r,style:{...i.offstate,...t},children:/* @__PURE__ */v("div",{style:i.skeletonBar})})}function OffState({decision:e,style:t,className:r}){let n=useEverfurTheme(),i=l(()=>gp(n),[n]),o=e.disabled?.reason??"";/* @__PURE__ */
51
51
  return v("div",{className:r,style:{...i.offstate,...t},children:o.length>0?/* @__PURE__ */v("p",{style:i.offstateText,children:o}):null})}function gp(e){let{color:t,space:r,radius:n,type:l}=e;return{offstate:{...fp,boxSizing:"border-box",minHeight:pp,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${r.md}px ${r.lg}px`,backgroundColor:t.surfaceCream,borderRadius:n.md,border:`1px solid ${t.brandBorder}`},offstateText:{margin:0,...faceCss(e,"regular"),fontSize:l.size.body,lineHeight:`${Math.round(l.size.body*l.lineHeight.normal)}px`,color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}}}var mp="Go to the nearest emergency vet now.";var bp=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",sourcesHeading:"Sources",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:mp,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",capReached:"You've used your {cap} free messages this month.",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function yp(e,t){return e.replace(/\{(\w+)\}/g,(e,r)=>{let n=t[r];return n===void 0?e:String(n)})}function vp(e){return e?.trim()||bp.emptyTitlePetFallback}function wp(e,t){return yp(e,{petName:vp(t)})}var kp="tel:+18884264435";var xp=/* @__PURE__ */Object.freeze([
52
52
  /* @__PURE__ */Object.freeze({key:"inaccurate",label:bp.feedbackReasonInaccurate,feedbackType:"wrong"}),
@@ -1,8 +1,8 @@
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
- export { D as DeviceLocale, b as DevicePlatform, c as EverfurInboxRequest, d as EverfurInboxRouter, e as EverfurNotificationRouteOutcome, f as EverfurNotificationRouterOptions, g as EverfurNotificationSurfaceRoute, E as EverfurNotificationsOptions, a as EverfurNotificationsState, h as EverfurNotificationsStatus, N as NOTIFICATIONS_REASON_MESSAGES, i as NO_INBOX_ROUTER, j as NotificationPreferences, k as NotificationPreferencesInput, l as NotificationsClient, m as NotificationsReasonCode, n as NotificationsRuntime, P as PushProvider, R as RegisterDeviceInput, o as RegisteredDevice, p as createEverfurInboxRouter, q as createNotificationsClient, r as explainNotificationsReason, s as readDeviceLocale, t as routeEverfurNotification, u as surfaceForNotification, w as useEverfurNotifications, v as useEverfurNotificationsClient } from '../../route.d-Nt-r-7IO.cjs';
3
+ export { D as DeviceLocale, b as DevicePlatform, c as EverfurInboxRequest, d as EverfurInboxRouter, e as EverfurNotificationRouteOutcome, f as EverfurNotificationRouterOptions, g as EverfurNotificationSurfaceRoute, E as EverfurNotificationsOptions, a as EverfurNotificationsState, h as EverfurNotificationsStatus, N as NOTIFICATIONS_REASON_MESSAGES, i as NO_INBOX_ROUTER, j as NotificationPreferences, k as NotificationPreferencesInput, l as NotificationsClient, m as NotificationsReasonCode, n as NotificationsRuntime, P as PushProvider, R as RegisterDeviceInput, o as RegisteredDevice, p as createEverfurInboxRouter, q as createNotificationsClient, r as explainNotificationsReason, s as readDeviceLocale, t as routeEverfurNotification, u as surfaceForNotification, w as useEverfurNotifications, v as useEverfurNotificationsClient } from '../../route.d-QBCoO62z.cjs';
4
4
  export { E as EVERFUR_NOTIFICATION_EVENT_TYPES, a as EVERFUR_NOTIFICATION_TARGET_KINDS, b as EVERFUR_NOTIFICATION_VERSION, c as EverfurMedicationIntent, d as EverfurNotification, e as EverfurNotificationEventName, f as EverfurNotificationEventType, g as EverfurNotificationTarget, h as EverfurNotificationTargetKind, i as EverfurOrderIntent, j as EverfurVisitPushIntent, p as parseEverfurNotification } from '../../parse.d-_Ttu2h5g.cjs';
5
- export { a as ChatCheckinTarget } from '../../checkin.d-BP3ZWBfX.cjs';
5
+ export { a as ChatCheckinTarget } from '../../checkin.d-CuIUahcd.cjs';
6
6
  export { V as VetVisitIntent } from '../../visitIntent.d-CY7mrflo.cjs';
7
7
  export { a as AnonIdentityProvider, A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-DDpXOtas.cjs';
8
8
  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 FreeCapRefusal, H as HeartbeatFrame, i as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, j as UrgencyLevel } from '../../config.d-ClAI2RZ6.cjs';
@@ -1,8 +1,8 @@
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
- export { D as DeviceLocale, b as DevicePlatform, c as EverfurInboxRequest, d as EverfurInboxRouter, e as EverfurNotificationRouteOutcome, f as EverfurNotificationRouterOptions, g as EverfurNotificationSurfaceRoute, E as EverfurNotificationsOptions, a as EverfurNotificationsState, h as EverfurNotificationsStatus, N as NOTIFICATIONS_REASON_MESSAGES, i as NO_INBOX_ROUTER, j as NotificationPreferences, k as NotificationPreferencesInput, l as NotificationsClient, m as NotificationsReasonCode, n as NotificationsRuntime, P as PushProvider, R as RegisterDeviceInput, o as RegisteredDevice, p as createEverfurInboxRouter, q as createNotificationsClient, r as explainNotificationsReason, s as readDeviceLocale, t as routeEverfurNotification, u as surfaceForNotification, w as useEverfurNotifications, v as useEverfurNotificationsClient } from '../../route.d-DtuKY5dM.js';
3
+ export { D as DeviceLocale, b as DevicePlatform, c as EverfurInboxRequest, d as EverfurInboxRouter, e as EverfurNotificationRouteOutcome, f as EverfurNotificationRouterOptions, g as EverfurNotificationSurfaceRoute, E as EverfurNotificationsOptions, a as EverfurNotificationsState, h as EverfurNotificationsStatus, N as NOTIFICATIONS_REASON_MESSAGES, i as NO_INBOX_ROUTER, j as NotificationPreferences, k as NotificationPreferencesInput, l as NotificationsClient, m as NotificationsReasonCode, n as NotificationsRuntime, P as PushProvider, R as RegisterDeviceInput, o as RegisteredDevice, p as createEverfurInboxRouter, q as createNotificationsClient, r as explainNotificationsReason, s as readDeviceLocale, t as routeEverfurNotification, u as surfaceForNotification, w as useEverfurNotifications, v as useEverfurNotificationsClient } from '../../route.d-B3u14HJT.js';
4
4
  export { E as EVERFUR_NOTIFICATION_EVENT_TYPES, a as EVERFUR_NOTIFICATION_TARGET_KINDS, b as EVERFUR_NOTIFICATION_VERSION, c as EverfurMedicationIntent, d as EverfurNotification, e as EverfurNotificationEventName, f as EverfurNotificationEventType, g as EverfurNotificationTarget, h as EverfurNotificationTargetKind, i as EverfurOrderIntent, j as EverfurVisitPushIntent, p as parseEverfurNotification } from '../../parse.d-QjB2LJCd.js';
5
- export { a as ChatCheckinTarget } from '../../checkin.d-CokpahFL.js';
5
+ export { a as ChatCheckinTarget } from '../../checkin.d-BoZXWjxX.js';
6
6
  export { V as VetVisitIntent } from '../../visitIntent.d-CY7mrflo.js';
7
7
  export { a as AnonIdentityProvider, A as AuthContext, I as IdentityProvider, M as MintedToken, T as TokenProvider } from '../../identity.d-D4VtpqRr.js';
8
8
  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 FreeCapRefusal, H as HeartbeatFrame, i as HttpMethod, M as MultipartBody, T as TransportPort, U as UnknownFrame, j as UrgencyLevel } from '../../config.d-B7Z-KTGq.js';
@@ -4,7 +4,7 @@
4
4
  return Object.freeze({features:/* @__PURE__ */Object.freeze({...t.data.features}),uploadContentTypes:/* @__PURE__ */Object.freeze([v,...n]),shareAudiences:mapShareAudiences(t.data.share_audiences)})}function acceptsPhotos(e){return e!==void 0&&e.some(j)}var C=class extends e.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(e,t){return Object.is(e.resetKey,t.key)?null:{failed:false,key:e.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:e}){return e()}function HostRender({render:t,fallback:r,resetKey:n}){return e.createElement(C,{fallback:r,resetKey:n,children:e.createElement(RenderHost,{render:t})})}var F="your pet";var S=e=>e.charAt(0).toUpperCase()+e.slice(1);function pronounForSex(e){let t=e?.trim().toLowerCase();return t==="female"?"her":t==="male"?"his":null}function E(e,t){let r=e.trim(),n=r.length>0?r:F,l=S(n);return t==="her"?{name:n,Name:l,poss:"her",Poss:"Her",subj:"she"}:t==="his"?{name:n,Name:l,poss:"his",Poss:"His",subj:"he"}:{name:n,Name:l,poss:`${n}'s`,Poss:`${l}'s`,subj:n}}var R=/* @__PURE__ */Object.freeze({vitalsFrom:(e,t,r)=>`Vitals from ${e.poss} ${t}, ${r}`,vitalsSource:e=>`Where ${e.name}'s vitals come from`,temperature:"Temperature",heartRate:"Heart rate",breathing:"Breathing",upcomingCare:"Upcoming care",overdueBy:e=>`Overdue · due by ${e}`,dueSoon:"Due soon",later:"Later",noDate:"No date",dueIn:(e,t)=>`Due ${e} · in ${t} ${t===1?"day":"days"}`,dueToday:e=>`Due ${e} · today`,overdueByDays:(e,t)=>`Overdue by ${t} ${t===1?"day":"days"} · due ${e}`,recordsHistory:"Records & history",labs:"Labs & bloodwork",results:"results",screenings:"Screenings",screeningsClear:"All clear",screeningsToReview:e=>`${e} to review`,noScreenings:"No screenings yet",visits:"Visits & records",timeline:"Timeline",events:e=>`${e} ${e===1?"event":"events"}`,weight:"Weight",vetVisits:e=>`${e} vet ${e===1?"visit":"visits"}`,history:"History",theirClinic:e=>`${e.Poss} clinic`,bloodPanel:"Blood panel",aboveRange:"above range",belowRange:"below range",othersInRange:"Other values in range.",addRecords:e=>`Add ${e.name}'s records`,moreThanOneClinic:"Records can come from more than one clinic over a lifetime.",visitsCount:e=>`${e} ${e===1?"visit":"visits"}`,panelsCount:e=>`${e} blood ${e===1?"panel":"panels"}`,requestFromClinic:"Request from a clinic",uploadDocument:"Upload a document",onFileNow:"On file now",firstRecord:e=>`Add ${e.name}'s first record`,firstLead:e=>`Records can come from more than one clinic over a lifetime. Start with the one ${e.subj} sees most, and this page fills in from there.`,requestFromTheirClinic:e=>`Request from ${e.poss} clinic`,requestDetail:"We send a secure request and read every page they send back.",uploadDetail:"A PDF, or a photo of a paper record.",findClinic:e=>`Find ${e.name}'s clinic`,chooseFile:"Choose a file",sayBeats:/* @__PURE__ */Object.freeze(["Hmmm","I wonder","what I may be","hiding"]),sayStill:"I wonder what I may be hiding",sample:"Sample",peekLead:e=>`A sneak peek at how ${e.name}'s records will read. Every number links back to the page it came from.`,sampleNote:e=>`Sample data until ${e.poss} records arrive.`,onTheWay:e=>`${e.Name}'s records are on the way`,clinicsTake:"Clinics usually take 2 to 5 days.",anotherClinic:"Another clinic",anotherClinicDetail:"Seen more than one vet? We ask each one.",noDueDate:"No due date on file",noLabs:e=>`No lab results on file for ${e.name} yet. They show up here when a record includes a blood or urine panel.`,noVisits:e=>`No visits in ${e.name}'s records yet. They show up here when a record includes one.`,oneReading:"One reading so far: we'll plot a trend as more come in.",takingNow:"Taking now",noCurrentMeds:"No current medications on file.",noVetTitle:e=>`When ${e.name} has a vet, start here.`,requestedFrom:e=>`Requested from ${e}. Clinics usually take 2 to 5 days.`,onTheWayFrom:(e,t)=>`${e.Name}'s records from ${t} are on the way.`,readingUpload:"We're reading the document you uploaded.",seeWhereItStands:"See where it stands",topRisk:e=>`${e.Poss} top risk`,seePlan:e=>`See ${e.poss} Health Plan`,panelOn:e=>`${e} blood panel`,latestReading:"Latest reading",rangeLine:(e,t,r)=>`range ${e} to ${t}${r?` ${r}`:""}`,noRange:"No range on the report",above:"Above",inRange:"In range",below:"Below",high:"High",belowRangePill:"Below range",changeUp:(e,t)=>`Up ${e}${t?` ${t}`:""}`,changeDown:(e,t)=>`Down ${e}${t?` ${t}`:""}`,changeSince:(e,t)=>` since ${e}, about ${t}%.`,whatIs:e=>`What ${e} is`,otherValues:e=>`Other ${e} values`,panelTitle:(e,t)=>`${e} · ${t}`,askAboutThis:"Ask about this"});function I(e){let t=e?.trim().toLowerCase()??"";return/^(dog|canine|k9|puppy)\b/.test(t)?"dog":/^(cat|feline|kitten)\b/.test(t)?"cat":"other"}var T=/* @__PURE__ */Object.freeze(["published","failed","revoked"]);function isTerminalStatus(e){return T.includes(e)}var $=864e5,A=30,D=2.20462,M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function L(e){if(e==null||e.length===0)return null;let t=Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e);return Number.isNaN(t)?null:t}function B(e){let t=new Date(e);return`${M[t.getUTCMonth()]??""} ${t.getUTCDate()}`}function P(e){return`${B(e)}, ${new Date(e).getUTCFullYear()}`}function N(e){let t=new Date(e);return`${t.getUTCMonth()+1}/${String(t.getUTCFullYear()%100).padStart(2,"0")}`}var H=e=>new Date(e).toISOString().slice(0,10);function W(e){return String(Math.round(e*100)/100)}var q=e=>Math.round(e*D*10)/10;function U(e){let t=e.trim();return t.length<2||t[1]===t[1]?.toUpperCase()?t:t.charAt(0).toLowerCase()+t.slice(1)}function V(e){return/temp/i.test(e)?"temp":/heart|pulse/i.test(e)?"heart":/resp|breath/i.test(e)?"breath":null}var K=["temp","heart","breath"],Y={temp:R.temperature,heart:R.heartRate,breath:R.breathing};function G(e){if(e===null||e.withheld)return{vitals:[],observedMs:null};let t=/* @__PURE__ */new Map;for(let r of e.entities){if(r.category!=="vital"||r.value===null||r.value.trim().length===0)continue;let e=V(`${r.canonicalKey??""} ${r.key} ${r.label}`);if(e===null)continue;let n=L(r.observedAt)??0,l=t.get(e);(l===void 0||n>l.ms)&&t.set(e,{value:r.value.trim(),unit:r.unit,ms:n})}let r=K.flatMap(e=>{let r=t.get(e);return r===void 0?[]:[{kind:e,value:r.value,unit:r.unit,label:Y[e]}]}),n=[...t.values()].map(e=>e.ms).filter(e=>e>0);return{vitals:r,observedMs:n.length>0?Math.max(...n):null}}function J(e,t){let r=H(t);return e.find(e=>{let t=L(e.date);return t!==null&&H(t)===r})??null}function Z(e){return/vaccin|rabies|dhpp|booster|bordetella|lepto|lyme|parvo|distemper/i.test(e)?"efi-shield":/\b(alt|alp|lab|labs|blood|panel|bloodwork|urinalysis|chemistry|cbc)\b/i.test(e)?"efi-flask-sm":"efi-calendar"}function X(e,t){return e.map(e=>{let r=L(e.dueAt),n=Z(e.title);if(r!==null&&r<t-$+1)return{item:e,title:e.title,when:R.overdueBy(B(r)),tone:"alert",pill:null,icon:n};let l=e.detail??(r===null?R.noDueDate:P(r));if(r===null)return{item:e,title:e.title,when:l,tone:"none",pill:null,icon:n};let a=r-t<=A*$;return{item:e,title:e.title,when:l,tone:a?"watch":"later",pill:a?R.dueSoon:R.later,icon:n}})}function Q(e){return e==null?null:/above|high/i.test(e)?"above":/below|low/i.test(e)?"below":/in_range|normal|in range/i.test(e)?"in":null}var ee=e=>Math.round(e*10)/10;function te(e,t){let r=`${W(q(e))} lb`,n=`${W(ee(e))} kg`;return t==="kg"?{main:n,other:r}:{main:r,other:n}}function re(e,t){if(e===null||e.withheld)return null;let r=e.weights.flatMap(e=>{let t=L(e.observedOn);return t===null||e.weightKg===null?[]:[{ms:t,kg:e.weightKg}]}).sort((e,t)=>e.ms-t.ms),n=r[r.length-1];if(n===void 0)return null;let l=r.map(e=>q(e.kg)),a=Math.min(...l),i=Math.max(...l),o=r[0]?.ms??n.ms,s=n.ms-o,c=r.map((e,r)=>({x:s>0?Math.round((3.55+93.45*(e.ms-o)/s)*100)/100:50,y:i>a?Math.round((75-50*((l[r]??a)-a)/(i-a))*10)/10:50,lb:l[r]??0,value:t==="kg"?ee(e.kg):l[r]??0,ms:e.ms})),u=c.length<=4?c:[c[0],c[c.length-1]].filter(e=>e!==void 0),d=te(n.kg,t);return{latest:d.main,sub:`${d.other} · ${B(n.ms)}`,single:c.length===1,points:c,ticks:u.map(e=>({x:e.x,label:N(e.ms)})),vetCount:c.length}}function ne(e){let t=/* @__PURE__ */new Map;if(e===null||e.withheld)return t;for(let r of e.markers)for(let e of r.points){let n=L(e.at);if(n===null)continue;let l=H(n),a=t.get(l)??{ms:n,flagged:[],total:0,inRange:0,clinics:/* @__PURE__ */new Set};a.total+=1;let i=Q(e.status);i==="in"&&(a.inRange+=1),(i==="above"||i==="below")&&a.flagged.push({marker:r,point:e,ms:n,flag:i}),e.sourceClinic&&a.clinics.add(e.sourceClinic),t.set(l,a)}return t}function le(e,t){let r=[];for(let[e,n]of t)n.flagged.forEach((t,l)=>{let a=t.point.value===null?t.point.qualitativeResult??"":W(t.point.value),i=t.point.unit??t.marker.unit,o=n.flagged.length===1&&n.inRange===n.total-1&&n.total>1;r.push({key:`lab-${e}-${t.marker.markerId}-${l}`,ms:n.ms,date:`${B(n.ms)} · ${R.bloodPanel}`,title:`${t.marker.name} ${a}${i?` ${i}`:""}, ${t.flag==="above"?R.aboveRange:R.belowRange}`,text:o?R.othersInRange:null,alert:true,markerId:t.marker.markerId,order:0})});let n=e.depth?.withheld===false?e.depth.encounters:[],l=e.timeline?.withheld===false?e.timeline.visits:[],a=/* @__PURE__ */new Set;n.forEach((e,t)=>{let n=L(e.date);if(n===null)return;let i=l.find(t=>e.docId!==null&&t.docId===e.docId||L(t.visitDate)!==null&&H(L(t.visitDate)??0)===H(n))??null;i!==null&&a.add(i.visitId);let o=i?.summary?.trim()||null,s=e.type?.trim()||null,c=o??s;c!==null&&r.push({key:`enc-${e.encounterId}-${t}`,ms:n,date:o!==null&&s!==null?`${B(n)} · ${s}`:B(n),title:c,text:null,alert:false,markerId:null,order:1})});for(let e of l){let t=L(e.visitDate),n=e.summary?.trim()||null;a.has(e.visitId)||t===null||n===null||r.push({key:`visit-${e.visitId}`,ms:t,date:B(t),title:n,text:null,alert:false,markerId:null,order:1})}r.sort((e,t)=>t.ms-e.ms||e.order-t.order);let i=[];for(let e of r){let t={key:e.key,ms:e.ms,date:e.date,title:e.title,text:e.text,alert:e.alert,markerId:e.markerId},r=String(new Date(t.ms).getUTCFullYear()),n=i[i.length-1];n!==void 0&&n.year===r?n.items.push(t):i.push({year:r,items:[t]})}return{years:i,count:r.length}}function ae(e,t){let r=e.depth?.withheld===false?e.depth.encounters:[],n=t=>t?.trim()||R.theirClinic(e.words),l=/* @__PURE__ */new Map;for(let e of r)l.set(n(e.clinicName),(l.get(n(e.clinicName))??0)+1);let a=/* @__PURE__ */new Map,i=l.size===1?[...l.keys()][0]:void 0;for(let r of t.values()){let t=r.clinics.size>0?[...r.clinics].map(n):[i??R.theirClinic(e.words)];for(let e of t)a.set(e,(a.get(e)??0)+1)}return[.../* @__PURE__ */new Set([...l.keys(),...a.keys()])].map(e=>({label:e,detail:[(l.get(e)??0)>0?R.visitsCount(l.get(e)??0):null,(a.get(e)??0)>0?R.panelsCount(a.get(e)??0):null].filter(e=>e!==null).join(" · ")}))}var ie={requested:15,awaiting_clinic:35,awaiting_upload:35,received:60,parsing:75,in_review:90};function oe(e){let t=e.filter(e=>!isTerminalStatus(e.status)).sort((e,t)=>(L(t.updatedAt)??0)-(L(e.updatedAt)??0))[0];if(t===void 0)return null;let r=(t.waitingExpectation?.trim()||t.statusLabel).trim();return r.length===0?null:{step:r,pct:ie[t.status]??15}}var se=e=>[...e].sort((e,t)=>(L(t.updatedAt)??0)-(L(e.updatedAt)??0)),ce=e=>/[.!?]$/.test(e)?e:`${e}.`;function ue(e,t){let r=se(t).filter(e=>!isTerminalStatus(e.status)),n=r.filter(e=>e.status==="awaiting_upload"),l=r.filter(e=>e.status!=="awaiting_upload"),a=[],i=/* @__PURE__ */new Map;for(let e of l){let t=e.clinicName?.trim()??"";e.source!=="clinic_request"||t===""||i.has(t)||i.set(t,e)}for(let[t,r]of i)a.push({key:`clinic-${t}`,text:R.onTheWayFrom(e,t),requestId:r.id});let o=l.find(e=>e.source==="owner_provided");o!==void 0&&a.push({key:"upload",text:R.readingUpload,requestId:o.id});let s=n[0],c=s?.statusLabel.trim()??"";return s!==void 0&&c!==""&&a.push({key:"awaiting-upload",text:ce(c),requestId:s.id}),a}function de(e){return se(e).find(e=>!isTerminalStatus(e.status)&&e.status!=="awaiting_upload"&&e.source==="clinic_request"&&(e.clinicName?.trim()??"")!=="")?.clinicName?.trim()??null}function fe(e){if(e===null||e.withheld)return null;let t=e.medications.filter(e=>(e.drugName?.trim()??"")!=="");return t.length===0?null:{current:t.filter(e=>(e.stoppedOn?.trim()??"")==="").map(e=>{let t=[e.dose,e.frequency,e.route].map(e=>e?.trim()??"").filter(e=>e!==""),r=e.sig?.trim()||(t.length>0?t.join(" · "):null);return{key:e.medicationId,name:(e.drugName??"").trim(),detail:r}})}}function pe(e){if(e.some(e=>!isTerminalStatus(e.status)))return null;let t=[...e].sort((e,t)=>(L(t.updatedAt)??0)-(L(e.updatedAt)??0))[0];if(t===void 0||t.status!=="failed")return null;let r=t.statusLabel.trim();return r.length>0?r:null}function he(e,t,r){return e!==null&&!e.withheld&&!e.isEmpty||t!==null&&!t.withheld&&t.markers.length>0?true:r!==null&&!r.withheld&&r.encounters.length>0}function me(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;let t=Math.floor(e*12+1e-9),r=Math.floor(t/12),n=t%12;return r<=0?`${n}M`:n>0?`${r}Y ${n}M`:`${r}Y`}function be(e){let{record:t,depth:r,markers:n,nowMs:l}=e,a=he(t,n,r),i=oe(e.requests),o=ne(n),{vitals:s,observedMs:c}=G(t),u=r?.withheld===false?r.encounters:[],d=c===null?null:J(u,c),f=c!==null&&d?.type?R.vitalsFrom(e.words,U(d.type),B(c)):null,p=e.weightUnit??"lb",h=re(e.timeline,p),m=h!==null?null:e.petWeightKg,b=[e.breed?.trim()||null,me(e.petAgeYears),h?.latest??(m!==null?te(m,p).main:null)].filter(e=>e!==null),g=e.timeline?.withheld===false?e.timeline.visits.length:0,w=le(e,o),y=u.map(e=>L(e.date)).filter(e=>e!==null),_=n?.withheld===false?n.markers:[],v=n?.featuredMarkerId??_.find(e=>Q(e.latest?.status)==="above"||Q(e.latest?.status)==="below")?.markerId??_[0]?.markerId??null;return{state:a?"full":i!==null?"onTheWay":"none",meta:b.length>0?b.join(" · "):null,vitals:s,vitalsFrom:f,due:t!==null&&!t.withheld?X(t.forwardLooking,l):[],labsCount:n?.withheld===false?n.summary?.totalMarkers??n.markers.length:0,featuredMarkerId:v,latestVisit:y.length>0?P(Math.max(...y)):null,weight:h,history:w.years,historyCount:w.count,sources:ae(e,o),pull:i,hasVisits:u.length>0||g>0,medications:fe(e.timeline),failedRequest:i===null?pe(e.requests):null,inFlight:ue(e.words,e.requests),requestedClinic:de(e.requests)}}function ge(e){let t=e.points.filter(e=>e.value!==null);return t[t.length-1]??e.points[e.points.length-1]??null}function we(e){return e===null||e.refLow===null||e.refHigh===null||!Number.isFinite(e.refLow)||!Number.isFinite(e.refHigh)||e.refHigh<=e.refLow?null:{low:e.refLow,high:e.refHigh}}function ye(e,t=ge(e)){let r=we(t),n=t?.unit??e.unit,l=t?.value??null;return{markerId:e.markerId,name:e.name,value:l===null?t?.qualitativeResult??"":W(l),unit:n,range:r===null?null:`${W(r.low)} to ${W(r.high)}${n?` ${n}`:""}`,at:r===null||l===null?null:Math.round(Math.min(100,Math.max(0,20+60*(l-r.low)/(r.high-r.low)))),flag:Q(t?.status??e.latest?.status??null)}}function _e(e){return e==="above"?R.high:e==="below"?R.belowRangePill:e==="in"?R.inRange:null}var ve=e=>{let t=e.replace(/\s+panel$/i,"").trim()||e;return t.length>1&&t[1]===t[1]?.toUpperCase()?t:t.charAt(0).toLowerCase()+t.slice(1)};function xe(e,t){let r=e.markers.find(e=>e.markerId===t);if(r===void 0)return null;let n=ge(r),l=ye(r,n),a=L(n?.at??r.latest?.at??null),i=we(n),o=[a===null?null:B(a),i===null?R.noRange:R.rangeLine(W(i.low),W(i.high),l.unit)].filter(e=>e!==null).join(" · "),s=r.points.flatMap(e=>{let t=L(e.at);return e.value===null||t===null?[]:[{p:e,ms:t,v:e.value}]}),c=[];if(s.length>0){let e=s.map(e=>e.v),t=i?.low??Math.min(...e),r=i?.high??Math.max(...e);c=s.map((e,n)=>({x:s.length===1?50:Math.round((18+64*n/(s.length-1))*100)/100,y:r>t?Math.min(98,Math.max(2,Math.round((75-50*(e.v-t)/(r-t))*10)/10)):50,label:W(e.v),out:Q(e.p.status)==="above"||Q(e.p.status)==="below",tick:B(e.ms)}))}let u=s[0],d=s[s.length-1],f=null;if(u!==void 0&&d!==void 0&&s.length>=2&&d.v!==u.v){let e=Math.abs(d.v-u.v),t=u.v!==0?Math.round(e/Math.abs(u.v)*100):null,r=d.v>u.v?R.changeUp(W(e),l.unit):R.changeDown(W(e),l.unit);f=t===null?null:{lead:r,rest:R.changeSince(B(u.ms),t)}}let p=[],h=a===null?null:H(a),m=e.markers.filter(e=>e.markerId!==r.markerId),b=m.filter(e=>e.panel!==null&&e.panel===r.panel);if(b.length>0&&r.panel!==null){let e=b.map(e=>ye(e));p.push({title:R.otherValues(ve(r.panel)),allInRange:e.every(e=>e.flag==="in"),rows:e})}if(h!==null&&a!==null){let e=/* @__PURE__ */new Map;for(let t of m){if(t.panel===null||t.panel===r.panel)continue;let n=[...t.points].reverse().find(e=>{let t=L(e.at);return t!==null&&H(t)===h});n!==void 0&&e.set(t.panel,[...e.get(t.panel)??[],ye(t,n)])}for(let[t,r]of e)p.push({title:R.panelTitle(t,B(a)),allInRange:r.every(e=>e.flag==="in"),rows:r})}return{markerId:r.markerId,name:r.name,meta:a===null?null:R.panelOn(P(a)),pill:_e(l.flag),flagged:l.flag==="above"||l.flag==="below",latest:`${l.value}${l.unit?` ${l.unit}`:""}`,latestSub:o,hasRange:i!==null,chart:c,change:f,meaning:(r.meaning??"").split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0),groups:p}}var je=/* @__PURE__ */Object.freeze({vitalsFromLabel:e=>`Where ${e}’s vitals come from`,vitalsFrom:(e,t)=>`From ${e}’s exam, ${t}. `,examNotes:"Exam notes",onTheWayFrom:(e,t)=>`${e}’s records from ${t} are on the way.`,readingUpload:"We’re reading the document you uploaded.",uploadFormatHint:"Upload PDF records you already have, up to 25 MB each. You can pick several at once. We'll read them and add the results to your records.",uploadLimitHint:"PDFs up to 25 MB each. You can pick several at once.",results:e=>e===1?"result":"results",noScreenings:"No screenings yet",screeningsToReview:e=>`${e} to review`,screeningsClear:"All clear",noVisits:"No visits yet",oneReading:"One reading so far: we’ll plot a trend as more come in.",uploadedDocument:"Uploaded document"}),ke=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ze(e){let t=new Date(e);return`${ke[t.getUTCMonth()]??""} ${t.getUTCDate()}, ${t.getUTCFullYear()}`}function Oe(e){let t=je,r=e.filter(e=>(e.latest?.qualitativeResult??"").trim().length>0);if(r.length===0)return null;let n=r.filter(e=>Ce(e.latest?.status??null,e.latest?.qualitativeResult??"")),l=n[0]??r[0];return n.length>0?{label:t.screeningsToReview(n.length),flagged:true,markerId:l.markerId}:{label:t.screeningsClear,flagged:false,markerId:l.markerId}}function Ce(e,t){return e==="in_range"?false:e==="above"||e==="below"?true:/negative|not detected|clear|none/i.test(t)?false:/positive|detected|present|reactive/i.test(t)}function Fe(e){let t=e.replace(/_/g," ").trim();return t.length>0?t.charAt(0).toUpperCase()+t.slice(1):e}function Se(e,t){if(e===null||e.withheld)return[];let r=/* @__PURE__ */new Map;if(t!==null&&!t.withheld)for(let e of t.encounters){let t=e.clinicName?.trim();e.docId!==null&&t&&r.set(e.docId,t)}return Object.values(e.documents).sort((e,t)=>(L(t.receivedAt)??0)-(L(e.receivedAt)??0)).slice(0,4).reverse().map(e=>{let t=L(e.receivedAt);return{key:e.docId,name:r.get(e.docId)??je.uploadedDocument,meta:[e.documentClass?Fe(e.documentClass):null,t!==null?ze(t):null].filter(e=>e!==null).join(" · ")}})}var Ee=["January","February","March","April","May","June","July","August","September","October","November","December"];function Re(e){let t=new Date(e);return`${Ee[t.getUTCMonth()]??""} ${t.getUTCDate()}`}function Ie(e,t){if(t===null||e===null||e.withheld)return null;let r=new Date(t).toISOString().slice(0,10),n=e.encounters.find(e=>{let t=L(e.date);return t!==null&&new Date(t).toISOString().slice(0,10)===r}),l=n?.veterinarian?.trim(),a=L(n?.date);return l&&a!==null?{vet:l,date:Re(a)}:null}function Te(e,t){let r=je;return ue(E(e,null),t).map(t=>t.key==="upload"?{...t,text:r.readingUpload}:t.key.startsWith("clinic-")?{...t,text:r.onTheWayFrom(e,t.key.slice(7))}:t)}var $e=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],Ae=/* @__PURE__ */Object.freeze($e.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(Ae.map(e=>e.wireCode));var De=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),Me=/* @__PURE__ */Object.freeze(Ae.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:De[e.wireCode]}))),Le=new Map(Me.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Be=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(Me.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...Be]){let t=Le.get(e+r);if(t)return t}}var Pe=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(e){return Pe[e]}function fromWire(e){let t=contractErrorFor(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return"authRejected";if(r.startsWith("AUTH"))return"authExpired";switch(n){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var Ne=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return Ne.has(e)}var He=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||He.has(e)}var We=500,qe=8e3,Ue=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(We*2**r,qe);return Math.floor(t()*n)}var Ve="This feature isn't available on your account right now.",Ke="Something in that request was not right. Check the details and try again.",Ye=/* @__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:Ve,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:Ke,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:Ve,runtimeDisposed:Ke,unknown:"Something went wrong. Please try again."}),Ge="This session has ended. Please sign in again.",Je="linked_account_read_only";function Ze(e,t,r){return e==="conflict"&&r===Je?Ve:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?Ge:userFacingError(e)}function userFacingError(e){return Ye[e]}function Xe(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var Qe=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===Je,l={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:Ze(e,t?.wireCode,n?Je:null)};t?.httpStatus!==void 0&&(l.httpStatus=t.httpStatus),t?.requestId&&(l.requestId=t.requestId),typeof t?.reasonCode=="string"&&Qe.test(t.reasonCode)&&(l.reasonCode=t.reasonCode);let a=t?.retryAfterSeconds;if(typeof a=="number"&&Number.isFinite(a)&&a>=0&&(l.retryAfterSeconds=Math.round(a)),r);return t?.wireMessage&&Xe(l,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Xe(l,"raw",t.raw),/* @__PURE__ */Object.freeze(l)}function ok(e,t){/* @__PURE__ */
5
5
  return Object.freeze({ok:true,value:e})}function err(e){/* @__PURE__ */
6
6
  return Object.freeze({ok:false,error:e})}var et=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function errorFrame(e){/* @__PURE__ */
7
- return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:null,...e.freeCap?{freeCap:/* @__PURE__ */Object.freeze({...e.freeCap})}:{}})}var tt="x-everfur-anon-token",rt="anonTokenInvalid";async function nt(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function lt(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[tt]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...at(e.headers),...authHeaders(t)}}}function at(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===tt||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await nt(t),n=await t.transport.request(withAuthHeaders(e,it(t,r)));if(n.ok||st(n.error.raw)!==rt||t.anonIdentity===void 0||t.userRef!==null)return n;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===r?n:t.transport.request(withAuthHeaders(e,it(t,l)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(lt(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(lt(e,{wireCode:st(n.error.raw),requestId:n.error.requestId}))}let a=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!a.ok&&a.error.httpStatus===401?(t.identity.reportRejected?.(),err(ot(a.error))):a}function it(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function ot(e){let t=e.raw,r=st(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function st(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var ct="1.5.3";function networkError(e){return makeEverfurError("internalError",{retryable:true,wireMessage:ut(e)})}function ut(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var dt=3e4,ft=qe*2,pt="idempotency-key",ht=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),mt=/* @__PURE__ */Object.freeze({onEvent(){}}),bt=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function gt(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}function createRequestFunnel(e){let t=e.observer??mt,r=e.timers??bt,n=e.rng??Math.random,l=e.sleep??((e,t)=>Tt(e,r,t)),a=e.maxAttempts??Ue,i=e.unaryTimeoutMs??dt,o=e.newIdempotencyKey??yt(),s=e=>{try{t.onEvent(e)}catch{}};async function c(t,c,u){let d=u?.maxAttempts,f=Math.max(1,d??a),p=u?.idempotent??ht.has(c.method),h=u?.idempotencyKey===void 0?null:gt(u.idempotencyKey),m=p?h??o():null,b=wt(c,m),g=0;for(;;){let a=e=>/* @__PURE__ */Object.freeze({call:t,method:c.method,path:c.path,attempt:g,...m?{idempotencyKey:m}:{},...e});s(a({phase:"attempt"}));let o=Rt(i,r),u=It(o.signal,c.signal),p;try{p=await authedSend({...b,signal:u.signal},e.auth)}catch(e){p=err(networkError(e))}finally{u.dispose(),o.cancel()}if(p.ok)return s(a({phase:"settled",ok:true,reason:"ok"})),p;let h=p.error,w=vt(h,g,{maxAttempts:f,rng:n,now:r.now(),aborted:c.signal?.aborted===true,...d!==void 0?{perCallMaxAttempts:d}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),y={ok:false,code:h.code,reason:w.reason,...h.httpStatus!==void 0?{httpStatus:h.httpStatus}:{},...h.requestId!==void 0?{requestId:h.requestId}:{}};if(!w.retry)return s(a({phase:"settled",...y})),err(h);if(s(a({phase:"retry",...y,delayMs:w.delayMs})),await l(w.delayMs,c.signal),c.signal?.aborted===true)return s(a({phase:"settled",...y,reason:"aborted"})),err(h);g+=1}}async function u(t){return withAuthHeaders(t,await Et(e.auth))}async function*d(t,r,n){s(
7
+ return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:null,...e.freeCap?{freeCap:/* @__PURE__ */Object.freeze({...e.freeCap})}:{}})}var tt="x-everfur-anon-token",rt="anonTokenInvalid";async function nt(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}function lt(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[tt]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...at(e.headers),...authHeaders(t)}}}function at(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===tt||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await nt(t),n=await t.transport.request(withAuthHeaders(e,it(t,r)));if(n.ok||st(n.error.raw)!==rt||t.anonIdentity===void 0||t.userRef!==null)return n;let l=await t.anonIdentity.token({forceRefresh:true});return l===null||l===r?n:t.transport.request(withAuthHeaders(e,it(t,l)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(lt(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let l;try{l=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(lt(e,{wireCode:st(n.error.raw),requestId:n.error.requestId}))}let a=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:l,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!a.ok&&a.error.httpStatus===401?(t.identity.reportRejected?.(),err(ot(a.error))):a}function it(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function ot(e){let t=e.raw,r=st(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function st(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var ct="1.6.0";function networkError(e){return makeEverfurError("internalError",{retryable:true,wireMessage:ut(e)})}function ut(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}var dt=3e4,ft=qe*2,pt="idempotency-key",ht=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),mt=/* @__PURE__ */Object.freeze({onEvent(){}}),bt=/* @__PURE__ */Object.freeze({setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()});function gt(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}function createRequestFunnel(e){let t=e.observer??mt,r=e.timers??bt,n=e.rng??Math.random,l=e.sleep??((e,t)=>Tt(e,r,t)),a=e.maxAttempts??Ue,i=e.unaryTimeoutMs??dt,o=e.newIdempotencyKey??yt(),s=e=>{try{t.onEvent(e)}catch{}};async function c(t,c,u){let d=u?.maxAttempts,f=Math.max(1,d??a),p=u?.idempotent??ht.has(c.method),h=u?.idempotencyKey===void 0?null:gt(u.idempotencyKey),m=p?h??o():null,b=wt(c,m),g=0;for(;;){let a=e=>/* @__PURE__ */Object.freeze({call:t,method:c.method,path:c.path,attempt:g,...m?{idempotencyKey:m}:{},...e});s(a({phase:"attempt"}));let o=Rt(i,r),u=It(o.signal,c.signal),p;try{p=await authedSend({...b,signal:u.signal},e.auth)}catch(e){p=err(networkError(e))}finally{u.dispose(),o.cancel()}if(p.ok)return s(a({phase:"settled",ok:true,reason:"ok"})),p;let h=p.error,w=vt(h,g,{maxAttempts:f,rng:n,now:r.now(),aborted:c.signal?.aborted===true,...d!==void 0?{perCallMaxAttempts:d}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),y={ok:false,code:h.code,reason:w.reason,...h.httpStatus!==void 0?{httpStatus:h.httpStatus}:{},...h.requestId!==void 0?{requestId:h.requestId}:{}};if(!w.retry)return s(a({phase:"settled",...y})),err(h);if(s(a({phase:"retry",...y,delayMs:w.delayMs})),await l(w.delayMs,c.signal),c.signal?.aborted===true)return s(a({phase:"settled",...y,reason:"aborted"})),err(h);g+=1}}async function u(t){return withAuthHeaders(t,await Et(e.auth))}async function*d(t,r,n){s(
8
8
  /* @__PURE__ */Object.freeze({call:t,phase:"stream.open",method:r.method,path:r.path,attempt:0}));try{yield*e.auth.transport.stream(r,n)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
9
9
  return Object.freeze({send:c,authorize:u,stream:d})}function wt(e,t){let r={};for(let[t,n]of Object.entries(e.headers??{}))t.toLowerCase()!==pt&&(r[t]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}function yt(){let e=0;return()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var _t=10;function vt(e,t,r){if(r.aborted)return{retry:false,reason:"aborted"};let n=xt(e);if(n==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!isAutoRetryable(e.code))return{retry:false,reason:"terminal-code"};let l=n==="burst"?"burst-throttle":"retryable-code";if((()=>{if(r.policy===void 0)return false;try{return!r.policy.shouldRetry(e.code,t)}catch{return false}})())return{retry:false,reason:"terminal-code"};let a=()=>{if(r.policy===void 0)return null;let t;try{t=r.policy.maxAttempts(e.code)}catch{return null}return typeof t!="number"||!Number.isFinite(t)?null:Math.max(1,Math.min(_t,Math.floor(t)))},i=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=i)return{retry:false,reason:"attempts-exhausted"};let o=jt(e,r.now);return o!==null?o>ft?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:l,delayMs:o}:{retry:true,reason:l,delayMs:backoffDelayMs(t,r.rng)}}function xt(e){let t=e.code==="unknown"?fromWire(Ft(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}function jt(e,t){let r=zt(e.raw);if(r!==null){let e=r-t;return e>0?e:0}let n=kt(e.raw);return n===null?null:Math.round(n*1e3)}function kt(e){for(let t of Ot(e)){let e=t.retry_after_seconds;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e}return null}function zt(e){for(let t of Ot(e)){let e=t.resets_at,r=Ct(e);if(r!==null)return r}return null}function Ot(e){if(!St(e))return[];let t=[e];for(let r of["error","detail"]){let n=e[r];St(n)&&t.push(n)}return t}function Ct(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}function Ft(e){for(let t of Ot(e)){let e=t.code;if(typeof e=="string"&&e.length>0)return e}return null}function St(e){return typeof e=="object"&&e!==null}async function Et(e){if(e.mode==="anonymous"){let t=await nt(e);return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}return{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}function Rt(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return{signal:r.signal,cancel:()=>t.clearTimeout(n)}}function It(e,t){let r=()=>{};if(!t)return{signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let l=()=>n.abort();return e.addEventListener("abort",l,{once:true}),t.addEventListener("abort",l,{once:true}),{signal:n.signal,dispose:()=>{e.removeEventListener("abort",l),t.removeEventListener("abort",l)}}}function Tt(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let l=t.setTimeout(()=>{r?.removeEventListener("abort",a),n()},e),a=()=>{t.clearTimeout(l),n()};r?.addEventListener("abort",a,{once:true})})}function $t(e){return e!=null&&(e.httpStatus===404||e.category==="notFound")}function At(e){return e.code!=="conversationNotFound"?e:makeEverfurError("resourceNotFound",{retryable:false,...e.httpStatus===void 0?{}:{httpStatus:e.httpStatus},...e.requestId===void 0?{}:{requestId:e.requestId},...e.reasonCode===void 0?{}:{reasonCode:e.reasonCode},...e.wireMessage===void 0?{}:{wireMessage:e.wireMessage},...e.raw===void 0?{}:{raw:e.raw}})}function Dt(e){return e.ok?e:err(At(e.error))}function Mt(e){return{send:async(...t)=>Dt(await e.send(...t)),authorize:t=>e.authorize(t),stream:(t,r,n)=>e.stream(t,r,n)}}var Lt=(e,t=4e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null;function Bt(e){let t=Lt(e,2048);return t===null?null:/^https:\/\/[^\s]+$/i.test(t)?t:null}var Pt=6;function Nt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=400?e:null}function Ht(e,t,r){if(!Array.isArray(e))/* @__PURE__ */return Object.freeze([]);let n=[];for(let l of e){if(n.length>=r)break;if(l===null||typeof l!="object"||Array.isArray(l))continue;let e=t(l);e!==null&&n.push(e)}/* @__PURE__ */
10
10
  return Object.freeze(n)}function Wt(e){let t=Lt(e.title,80),r=Lt(e.body,600);return t===null||r===null?null:/* @__PURE__ */Object.freeze({title:t,body:r})}function qt(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,r=[];if(Array.isArray(t.gallery))for(let e of t.gallery){let t=Bt(e);t!==null&&r.length<Pt&&r.push(t)}let n=Ht(t.doses,e=>{let t=Lt(e.label,60),r=Lt(e.amount,60);return t===null||r===null?null:/* @__PURE__ */Object.freeze({label:t,amount:r,minLb:Nt(e.minLb??e.min_lb),maxLb:Nt(e.maxLb??e.max_lb)})},Pt),l=Ht(t.details,Wt,Pt),a=t.fit,i=a!==null&&typeof a=="object"&&!Array.isArray(a)?Wt(a):null,o=i!==null&&a.pet===true?/* @__PURE__ */Object.freeze({...i,pet:true}):i,s=/* @__PURE__ */Object.freeze({kicker:Lt(t.kicker,80),gallery:/* @__PURE__ */Object.freeze(r),doses:n,details:l,fine:Lt(t.fine,300),fit:o});return s.kicker===null&&r.length===0&&n.length===0&&l.length===0&&s.fine===null&&o===null?void 0:s}var Ut=128;var Vt=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),Kt=/* @__PURE__ */new Set(["y","c","g","r"]),Yt=/* @__PURE__ */new Set(["done","now","next"]),Gt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null,Jt=(e,t=1e3)=>typeof e=="string"&&e.trim().length>0&&e.length<=t?e.trim():null,Zt=e=>typeof e=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(e)?e:null,Xt=e=>typeof e=="string"&&Vt.has(e)?e:null;function Qt(e){let t=Jt(e,2048);return t===null||/\s/.test(t)?null:/^https:\/\/[^/]/i.test(t)||/^\/(?![/\\])/.test(t)?t:null}var er=e=>typeof e=="number"&&Number.isInteger(e)?String(e):Jt(e,Ut);function tr(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function rr(e){/* @__PURE__ */