@everfur/sdk 0.8.0 → 0.9.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 (139) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -1
  3. package/dist/{Chat-s2vcPbw3.d.cts → Chat-Cb3Y8VwS.d.cts} +3 -3
  4. package/dist/{Chat-Cv9EYMYA.d.ts → Chat-ClhB_8sp.d.ts} +3 -3
  5. package/dist/{DepthViews-CVxUHOJ-.d.ts → DepthViews-BSkuUGBB.d.ts} +1 -1
  6. package/dist/{DepthViews-DNRY0Ugm.d.ts → DepthViews-CSCS-tZg.d.ts} +1 -1
  7. package/dist/{DepthViews-Cz7mSW7p.d.cts → DepthViews-CW1z8pnl.d.cts} +1 -1
  8. package/dist/{DepthViews-DvNixbxg.d.cts → DepthViews-DDiPxyzg.d.cts} +1 -1
  9. package/dist/animations/index.cjs +1 -1
  10. package/dist/animations/index.d.cts +3 -3
  11. package/dist/animations/index.d.ts +3 -3
  12. package/dist/animations/index.js +1 -1
  13. package/dist/{attachments-y3EcOX_w.d.cts → attachments-BD70jZZL.d.cts} +2 -2
  14. package/dist/{attachments-y_aO4hlk.d.ts → attachments-CC7aHpwZ.d.ts} +5 -5
  15. package/dist/{attachments-BaslXMdS.d.ts → attachments-DAUy3vPR.d.ts} +2 -2
  16. package/dist/{attachments-DbFwz4iq.d.cts → attachments-DaOaIBNf.d.cts} +5 -5
  17. package/dist/{bookingCopy-B3UMITD-.d.ts → bookingCopy-CUW9Gdzc.d.ts} +2 -2
  18. package/dist/{bookingCopy-4i1R7klo.d.cts → bookingCopy-oEjqkiNA.d.cts} +2 -2
  19. package/dist/{branding-BYEqU855.d.ts → branding-aGleD_ki.d.ts} +99 -6
  20. package/dist/{branding-BwEu68C8.d.cts → branding-ctD0B2Th.d.cts} +99 -6
  21. package/dist/{casesRepository-B6Z0XBIb.d.cts → casesRepository-Bzs7aw4t.d.cts} +1 -1
  22. package/dist/{casesRepository-SI0zp5YH.d.ts → casesRepository-CywqL6mj.d.ts} +1 -1
  23. package/dist/chat/index.cjs +20 -18
  24. package/dist/chat/index.d.cts +9 -9
  25. package/dist/chat/index.d.ts +9 -9
  26. package/dist/chat/index.js +20 -18
  27. package/dist/client/index.cjs +7 -7
  28. package/dist/client/index.d.cts +10 -10
  29. package/dist/client/index.d.ts +10 -10
  30. package/dist/client/index.js +7 -7
  31. package/dist/{config-Cvo47voG.d.ts → config-BysLVhku.d.ts} +1 -1
  32. package/dist/{config-v5k6NsK_.d.cts → config-EZzEyS-c.d.cts} +1 -1
  33. package/dist/consent/index.cjs +1 -1
  34. package/dist/consent/index.d.cts +5 -5
  35. package/dist/consent/index.d.ts +5 -5
  36. package/dist/consent/index.js +1 -1
  37. package/dist/{context-BZOtJbBO.d.cts → context-DUwYArkM.d.cts} +7 -7
  38. package/dist/{context-cZ7NZ0sG.d.ts → context-DpfgbnOU.d.ts} +7 -7
  39. package/dist/{copy-ChJupm1p.d.cts → copy-DK4r9oGz.d.cts} +2 -2
  40. package/dist/{copy-CZBUHbyS.d.ts → copy-LxZGnFXJ.d.ts} +2 -2
  41. package/dist/core/index.cjs +2 -2
  42. package/dist/core/index.d.cts +15 -15
  43. package/dist/core/index.d.ts +15 -15
  44. package/dist/core/index.js +2 -2
  45. package/dist/{depth-CRyU7-pf.d.cts → depth-DAd77kRe.d.cts} +2 -2
  46. package/dist/{depth-vNpwOkZ8.d.ts → depth-Mk7quUNa.d.ts} +2 -2
  47. package/dist/{entitlementRepository-CUdxbQrP.d.ts → entitlementRepository-CrD0O7VR.d.ts} +3 -3
  48. package/dist/{entitlementRepository-Bv8nSYRd.d.cts → entitlementRepository-Dra_4FU_.d.cts} +3 -3
  49. package/dist/{identity-BHaMJ3KK.d.cts → identity-75whJXyP.d.cts} +1 -1
  50. package/dist/{identity-B8GkH53J.d.ts → identity-BiyMDMrR.d.ts} +1 -1
  51. package/dist/index.cjs +24 -22
  52. package/dist/index.d.cts +16 -16
  53. package/dist/index.d.ts +16 -16
  54. package/dist/index.js +24 -22
  55. package/dist/notifications/index.d.cts +2 -2
  56. package/dist/notifications/index.d.ts +2 -2
  57. package/dist/{pets-BI7Ji8hi.d.cts → pets-DoXxTw4x.d.cts} +1 -1
  58. package/dist/{pets-Dnn-DK1T.d.ts → pets-W2BuLYko.d.ts} +1 -1
  59. package/dist/{petsRepository-B2lO1sKS.d.ts → petsRepository-ByMzq1Z9.d.ts} +1 -1
  60. package/dist/{petsRepository-BP9nhM1R.d.cts → petsRepository-yyoo0k2I.d.cts} +1 -1
  61. package/dist/photo/index.cjs +1 -1
  62. package/dist/photo/index.js +1 -1
  63. package/dist/{ports-C40S2V14.d.cts → ports-BeVJYP0_.d.cts} +4 -4
  64. package/dist/{ports-BUXF0Rp3.d.ts → ports-zYl8S_lI.d.ts} +4 -4
  65. package/dist/records/depth/index.cjs +6 -6
  66. package/dist/records/depth/index.d.cts +7 -7
  67. package/dist/records/depth/index.d.ts +7 -7
  68. package/dist/records/depth/index.js +6 -6
  69. package/dist/records/index.cjs +30 -30
  70. package/dist/records/index.d.cts +9 -9
  71. package/dist/records/index.d.ts +9 -9
  72. package/dist/records/index.js +30 -30
  73. package/dist/{requestFunnel-BrOijMcw.d.ts → requestFunnel-BPeBZdKp.d.ts} +2 -2
  74. package/dist/{requestFunnel-BxNVGyGm.d.cts → requestFunnel-DHeSzCT6.d.cts} +2 -2
  75. package/dist/{runtimeTypes-CvI1ZH8j.d.ts → runtimeTypes-Cc207nbn.d.ts} +5 -5
  76. package/dist/{runtimeTypes-DOO3f-W-.d.cts → runtimeTypes-DgMizQKz.d.cts} +5 -5
  77. package/dist/server/events/index.cjs +1 -1
  78. package/dist/server/events/index.d.cts +2 -2
  79. package/dist/server/events/index.d.ts +2 -2
  80. package/dist/server/events/index.js +1 -1
  81. package/dist/server/index.cjs +1 -1
  82. package/dist/server/index.d.cts +3 -3
  83. package/dist/server/index.d.ts +3 -3
  84. package/dist/server/index.js +1 -1
  85. package/dist/televet/booking/index.cjs +15 -13
  86. package/dist/televet/booking/index.d.cts +6 -6
  87. package/dist/televet/booking/index.d.ts +6 -6
  88. package/dist/televet/booking/index.js +15 -13
  89. package/dist/televet/call/index.cjs +1 -1
  90. package/dist/televet/call/index.js +1 -1
  91. package/dist/televet/index.cjs +1 -1
  92. package/dist/televet/index.js +1 -1
  93. package/dist/testing/index.d.cts +1 -1
  94. package/dist/testing/index.d.ts +1 -1
  95. package/dist/testing/rn/index.cjs +1 -1
  96. package/dist/testing/rn/index.d.cts +9 -9
  97. package/dist/testing/rn/index.d.ts +9 -9
  98. package/dist/testing/rn/index.js +1 -1
  99. package/dist/testing/web/index.d.cts +9 -9
  100. package/dist/testing/web/index.d.ts +9 -9
  101. package/dist/{timelineRows-CEx2TzYB.d.ts → timelineRows-D22vGN9t.d.ts} +1 -1
  102. package/dist/{timelineRows-Dffceql_.d.cts → timelineRows-DUQIWSjc.d.cts} +1 -1
  103. package/dist/{tokens-Tzo1KBND.d.cts → tokens-RAKZj7M8.d.cts} +47 -4
  104. package/dist/{tokens-Tzo1KBND.d.ts → tokens-RAKZj7M8.d.ts} +47 -4
  105. package/dist/{typeStyle-C3IG9Sft.d.ts → typeStyle-DVj8iCC1.d.ts} +11 -3
  106. package/dist/{typeStyle-CZ3Tj60N.d.cts → typeStyle-Nt7w0rhE.d.cts} +11 -3
  107. package/dist/{useRecordsDepth-DuPUJFDQ.d.ts → useRecordsDepth-C0Qfoghi.d.ts} +1 -1
  108. package/dist/{useRecordsDepth-D6a6-_u_.d.cts → useRecordsDepth-Mbysp548.d.cts} +1 -1
  109. package/dist/video/index.cjs +1 -1
  110. package/dist/video/index.js +1 -1
  111. package/dist/{view-UFwCG1Pn.d.cts → view-CskIgOFV.d.cts} +2 -2
  112. package/dist/{view-BSmN5RWf.d.ts → view-DqKXtxEZ.d.ts} +2 -2
  113. package/dist/web/consent/index.cjs +1 -1
  114. package/dist/web/consent/index.d.cts +5 -5
  115. package/dist/web/consent/index.d.ts +5 -5
  116. package/dist/web/consent/index.js +1 -1
  117. package/dist/web/index.cjs +29 -28
  118. package/dist/web/index.d.cts +26 -20
  119. package/dist/web/index.d.ts +26 -20
  120. package/dist/web/index.js +29 -28
  121. package/dist/web/notifications/index.d.cts +3 -3
  122. package/dist/web/notifications/index.d.ts +3 -3
  123. package/dist/web/records/depth/index.cjs +9 -8
  124. package/dist/web/records/depth/index.d.cts +7 -7
  125. package/dist/web/records/depth/index.d.ts +7 -7
  126. package/dist/web/records/depth/index.js +9 -8
  127. package/dist/web/records/index.cjs +51 -49
  128. package/dist/web/records/index.d.cts +9 -9
  129. package/dist/web/records/index.d.ts +9 -9
  130. package/dist/web/records/index.js +52 -50
  131. package/dist/web/televet/booking/index.cjs +21 -19
  132. package/dist/web/televet/booking/index.d.cts +11 -11
  133. package/dist/web/televet/booking/index.d.ts +11 -11
  134. package/dist/web/televet/booking/index.js +21 -19
  135. package/dist/web/televet/call/index.cjs +1 -1
  136. package/dist/web/televet/call/index.js +1 -1
  137. package/dist/web/televet/index.cjs +1 -1
  138. package/dist/web/televet/index.js +1 -1
  139. package/package.json +1 -1
@@ -96,7 +96,7 @@ return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversati
96
96
  return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:fields.serverRequestId??null})}function analysisStartedFrame(requestId,lastEventId,serverRequestId=null){/* @__PURE__ */
97
97
  return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
98
98
  return Object.freeze({kind:"analysisComplete",terminal:false,resultId:fields.resultId,analysisType:fields.analysisType,modelVersion:fields.modelVersion,confidence:fields.confidence,detections:/* @__PURE__ */Object.freeze([...fields.detections]),interpretation:fields.interpretation,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function unknownFrame(raw,lastEventId,serverRequestId=null){/* @__PURE__ */
99
- return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function createIdentityProvider(userRef2,getToken,onMinted){let cached=null,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string(),/* @__PURE__ */zod.z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=new TextDecoder("utf-8"),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var SDK_VERSION="0.8.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
99
+ return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function createIdentityProvider(userRef2,getToken,onMinted){let cached=null,inFlight3=null,revoked=false,load=()=>inFlight3||(inFlight3=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight3=null}})(),inFlight3);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{return err(authRejectedError())}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch{return err(authRejectedError())}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?err(authRejectedError(retry.error.httpStatus)):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string(),/* @__PURE__ */zod.z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=new TextDecoder("utf-8"),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var SDK_VERSION="0.9.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
100
100
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function checkPublishableKey(raw){let publishableKey=typeof raw=="string"?raw.trim():"";return publishableKey.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(publishableKey)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}function tryResolveClientConfig(config,options){let keyFailure=checkPublishableKey(config?.publishableKey);if(keyFailure!==null)/* @__PURE__ */
101
101
  return Object.freeze({ok:false,failure:keyFailure});let publishableKey=config.publishableKey.trim(),baseUrl=tryResolveApiBaseUrl(config.apiBaseUrl);if(!baseUrl.ok)return baseUrl;let contractVersion=config.contractVersion?.trim()||DEFAULT_CONTRACT_VERSION;/* @__PURE__ */
102
102
  return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:publishableKey,apiBaseUrl:baseUrl.value,contractVersion:contractVersion,sdkVersion:SDK_VERSION,platform:options?.platform??SDK_PLATFORM,debug:config.debug===true})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
@@ -119,16 +119,16 @@ return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(
119
119
  return Object.freeze({petRef:str3(o.pet_ref)??petRef2,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef2=str3(o.pet_ref);return petRef2===null||petRef2.length===0?null:/* @__PURE__ */Object.freeze({petId:str3(o.pet_id),petRef:petRef2,name:str3(o.name),species:str3(o.species),breed:str3(o.breed),ageYears:num(o.age_years),weightKg:num(o.weight_kg),updatedAt:str3(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
120
120
  return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal2=(req,signal)=>signal?{...req,signal:signal}:req,petPath2=petRef2=>validate(petRef2,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef2)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal2({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef2,profile,opts){let invalid4=validate(petRef2,profile);if(invalid4!==null)return err(invalid4);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef2)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base,signal:opts.signal}:base);return res.ok?ok(fromWire2(res.value,petRef2)):err(res.error)},async updatePet(petRef2,patch,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal2({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef2)):err(res.error)},async getPetProfile(petRef2,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal2({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef2,opts){let path=petPath2(petRef2);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal2({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal2({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"])});function requires(name){return REQUIRES[name]}function deniedDecisionsFor(level,reason){let disabled=/* @__PURE__ */Object.freeze({reason:reason,level:level,recoverable:false}),rows=[],seen=/* @__PURE__ */new Set;for(let name of Object.keys(REQUIRES))for(let resource of REQUIRES[name])seen.has(resource)||(seen.add(resource),rows.push(/* @__PURE__ */Object.freeze({resource:resource,granted:false,disabled:disabled}))/* @__PURE__ */);return Object.freeze(rows)}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
121
121
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
122
- return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function setPetRegistrationTenant(runtime,tenant){tenants.set(runtime,tenant)}function petRegistrationKey(runtime,auth,petRef2,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef2}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function notifyPetsChanged(runtime){let set=listeners.get(runtime);if(set!==void 0)for(let listener of[...set])try{listener()}catch{}}var inFlight2=/* @__PURE__ */new Map;function sharedTokenProvider(scope,getToken){return()=>{let pending=inFlight2.get(scope);if(pending!==void 0)return pending;let mint;try{mint=Promise.resolve(getToken())}catch(error){mint=Promise.reject(error)}let settled=mint.finally(()=>{inFlight2.get(scope)===settled&&inFlight2.delete(scope)});return inFlight2.set(scope,settled),settled}}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel2){return channel2<=.03928?channel2/12.92:Math.pow((channel2+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}function rgbToHsl(r,g,b){let rn=r/255,gn=g/255,bn=b/255,mx=Math.max(rn,gn,bn),mn=Math.min(rn,gn,bn),l=(mx+mn)/2;if(mx===mn)return{h:0,s:0,l:l};let d=mx-mn,s=d/(1-Math.abs(2*l-1)),h;return mx===rn?(h=(gn-bn)/d*60,h<0&&(h=h+360)):mx===gn?h=((bn-rn)/d+2)*60:h=((rn-gn)/d+4)*60,{h:h,s:s,l:l}}function hslToRgb(hsl){let{h:h,s:s,l:l}=hsl,c=(1-Math.abs(2*l-1))*s,hp=h/60,x=c*(1-Math.abs(hp%2-1)),m=l-c/2,sector=Math.floor(hp)%6,rgb1=[[c,x,0],[x,c,0],[0,c,x],[0,x,c],[x,0,c],[c,0,x]],[r1,g1,b1]=rgb1[sector];return{r:channel(r1+m),g:channel(g1+m),b:channel(b1+m)}}function channel(v){return Math.min(255,Math.max(0,Math.floor(v*255+.5)))}var THEME_SLOT_NAMES=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link"]),THEME_SLOT_KEYS=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),SLOT_MIN_CONTRAST=4.5,EMPTY=/* @__PURE__ */Object.freeze({});function isSlotName(value){return THEME_SLOT_NAMES.includes(value)}function parseRadius(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):Number.NaN;return Number.isFinite(n)?Math.max(0,n):null}function parseThemeSlots(json){if(json===null||typeof json!="object"||Array.isArray(json))return null;let out={},any=false;for(let[name,raw]of Object.entries(json)){if(!isSlotName(name)||raw===null||typeof raw!="object")continue;let slot=parseSlot(raw);slot!==null&&(out[name]=slot,any=true)}return any?/* @__PURE__ */Object.freeze(out):null}function pick2(raw,snake,camel){return raw[snake]!==void 0?raw[snake]:raw[camel]}function parseSlot(raw){let slot={},backgroundColor=parseColor(pick2(raw,"background_color","backgroundColor"));backgroundColor!==null&&(slot.backgroundColor=backgroundColor);let borderColor=parseColor(pick2(raw,"border_color","borderColor"));borderColor!==null&&(slot.borderColor=borderColor);let borderRadius=parseRadius(pick2(raw,"border_radius","borderRadius"));borderRadius!==null&&(slot.borderRadius=borderRadius);let textColor=parseColor(pick2(raw,"text_color","textColor"));return textColor!==null&&(slot.textColor=textColor),Object.keys(slot).length===0?null:/* @__PURE__ */Object.freeze(slot)}function mergeThemeSlots(base,over){return over===null||Object.keys(over).length===0?base??EMPTY:base===null||Object.keys(base).length===0?over:/* @__PURE__ */Object.freeze({...base,...over})}function isOpaque(color){let rgba=toRgba(color);return rgba!==null&&rgba.a>=1}var SLOT_MIN_BORDER_CONTRAST=3;function boundaryFor(fill,surrounds,seats=[]){if(surrounds.length===0)return null;let shown=surrounds.map(ground=>flattenOnto(fill,ground)??fill);if(surrounds.every((ground,index)=>contrastRatio(shown[index],ground)>=SLOT_MIN_BORDER_CONTRAST))return null;let against=[...surrounds,...shown,...seats];return pushToContrast(shown[0],against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST)}function seatsOf(background,defaults){return background===void 0?defaults:defaults.length===0?[background]:defaults.map(ground=>flattenOnto(background,ground)??ground)}function someInkReads(seats,target){let pole=poleForGrounds(seats);return seats.every(seat=>contrastRatio(pole,seat)>=target)}function collapseUnsatisfiableFill(background,defaults){let ground=defaults[0];return ground===void 0?null:flattenOnto(background,ground)}function inkFor(seats){let pick4=legibleOn(seats[0],SLOT_MIN_CONTRAST);return seats.every(seat=>contrastRatio(pick4,seat)>=SLOT_MIN_CONTRAST)?pick4:poleForGrounds(seats)}function guardSlotContrast(slots,grounds2,surrounds){let changed=false,out={};for(let name of THEME_SLOT_NAMES){let slot=slots[name];if(slot===void 0)continue;let bg=slot.backgroundColor,defaults=grounds2?.[name]??[],seats=seatsOf(bg,defaults),next={...slot},fixed=false;if(bg!==void 0&&seats.length>1&&!someInkReads(seats,SLOT_MIN_CONTRAST)){let opaque=collapseUnsatisfiableFill(bg,defaults);opaque!==null&&(next.backgroundColor=opaque,seats=[opaque],fixed=true)}let around=surrounds?.[name],fill=next.backgroundColor,melts=around!==void 0&&fill!==void 0&&isOpaque(fill)&&boundaryFor(fill,around,seats)!==null;if(seats.length>0){let ink=slot.textColor;if(bg!==void 0)(ink===void 0||seats.some(seat=>contrastRatio(ink,seat)<SLOT_MIN_CONTRAST))&&(next.textColor=inkFor(seats),fixed=true);else if(ink!==void 0){let legible=pushToContrast(ink,seats,poleForGrounds(seats),SLOT_MIN_CONTRAST);legible!==ink&&(next.textColor=legible,fixed=true)}if(slot.borderColor!==void 0){let against=melts?[...seats,...around??[]]:seats,edge=pushToContrast(slot.borderColor,against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST);edge!==slot.borderColor&&(next.borderColor=edge,fixed=true)}}if(melts&&fill!==void 0&&around!==void 0&&next.borderColor===void 0){let edge=boundaryFor(fill,around,seats);edge!==null&&(next.borderColor=edge,fixed=true)}out[name]=fixed?/* @__PURE__ */Object.freeze(next):slot,changed=changed||fixed}return changed?/* @__PURE__ */Object.freeze(out):slots}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});function textGrounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function controlGrounds(c){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill]}function brandReadsOnControls(c){return controlGrounds(c).every(ground=>contrastRatio(c.brand,ground)>=SLOT_MIN_BORDER_CONTRAST)}function linkGrounds(c){return[c.chatGround,c.surface,c.surfaceCream]}function statusGrounds(c,wash){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill,...washGrounds(c,wash)]}function washGrounds(c,wash){return[flattenOnto(wash,c.surface)??c.surface,flattenOnto(wash,c.surfaceCream)??c.surfaceCream]}function composerGrounds(c){return[c.composerFill,c.chatGround]}var AUTHORED_AS_IS=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function onCompiledGrounds(c,compiled){let own=new Set(textGrounds(compiled));return textGrounds(c).every(ground=>own.has(ground))}function guardInks(theme){let c=theme.color,compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,other=(theme.brightness==="dark"?EVERFUR_LIGHT:EVERFUR_DARK).color,grounds2=textGrounds(c),flipped=poleForGrounds(grounds2)!==poleForGrounds(textGrounds(compiled)),keepCompiled=onCompiledGrounds(c,compiled),dangerIsCompiled=c.danger===compiled.danger&&c.badgeBgCritical===compiled.badgeBgCritical,ink=(name,value,authored,twin,on,target)=>{let untouched=value===authored&&(name!=="errorRed"||dangerIsCompiled);return untouched&&keepCompiled&&AUTHORED_AS_IS.has(name)?value:pushToContrast(untouched&&flipped?twin:value,on,poleForGrounds(on),target)},text3=(key,on,target)=>ink(`text.${key}`,c.text[key],compiled.text[key],other.text[key],on,target),token=(key,value,on,target)=>ink(key,value,compiled[key],other[key],on,target),tint=key=>flipped&&c[key]===compiled[key]?other[key]:c[key],primary=c.primary,onPrimary=legibleOn(primary,SLOT_MIN_CONTRAST),danger=token("danger",c.danger,[...grounds2,...washGrounds(c,c.badgeBgCritical)],SLOT_MIN_CONTRAST),guarded={...c,onPrimary:onPrimary,onAccent:legibleOn(c.accent,SLOT_MIN_CONTRAST),onDanger:contrastRatio(onPrimary,danger)>=SLOT_MIN_CONTRAST?onPrimary:legibleOn(danger,SLOT_MIN_CONTRAST),brandSoft:tint("brandSoft"),brandSofter:tint("brandSofter"),brandBorder:tint("brandBorder"),borderHairlineGreen:tint("borderHairlineGreen"),brandInk:token("brandInk",c.brandInk,grounds2,SLOT_MIN_CONTRAST),linkInk:token("linkInk",theme.slots.link?.textColor??c.accent,linkGrounds(c),SLOT_MIN_CONTRAST),text:{...c.text,primary:text3("primary",grounds2,SLOT_MIN_CONTRAST),secondary:text3("secondary",grounds2,SLOT_MIN_CONTRAST),muted:text3("muted",grounds2,SLOT_MIN_CONTRAST),metaCool:text3("metaCool",grounds2,SLOT_MIN_CONTRAST),timestamp:text3("timestamp",grounds2,SLOT_MIN_CONTRAST),placeholder:text3("placeholder",controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},danger:danger,errorRed:token("errorRed",c.errorRed,statusGrounds(c,c.badgeBgCritical),SLOT_MIN_CONTRAST),warningStrong:token("warningStrong",c.warningStrong,statusGrounds(c,c.badgeBgCaution),SLOT_MIN_CONTRAST),composerBorder:token("composerBorder",c.composerBorder,composerGrounds(c),SLOT_MIN_BORDER_CONTRAST),brandBorderStrong:token("brandBorderStrong",c.brandBorderStrong,controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)};return{...guarded,...accentFamily(guarded,compiled,keepCompiled)}}var HIGHLIGHT_LIGHT_TINT=.24,HIGHLIGHT_DARK_TINT=.3;function same(a,b){return parseColor(a)===parseColor(b)}function partnerHue(c,compiled){return same(c.accent,compiled.accent)?same(c.brand,compiled.brand)?null:c.brand:c.accent}function tintOver(hue,surface,tint){let wash=withAlpha(hue,tint);return(wash===null?null:flattenOnto(wash,surface))??surface}function accentFamily(c,compiled,keepCompiled){let hue=partnerHue(c,compiled),controls=controlGrounds(c),controlPole=poleForGrounds(controls),darkGround=poleForGrounds([c.surface])===WHITE,everfurMarks=hue===null&&keepCompiled,highlight;everfurMarks?highlight=compiled.highlight:hue===null?highlight=darkGround?tintOver(EVERFUR_LIGHT.color.highlight,c.surface,HIGHLIGHT_DARK_TINT):EVERFUR_LIGHT.color.highlight:highlight=tintOver(hue,c.surface,darkGround?HIGHLIGHT_DARK_TINT:HIGHLIGHT_LIGHT_TINT);let onHighlight=everfurMarks?compiled.onHighlight:pushToContrast(c.text.primary,[highlight],poleForGrounds([highlight]),SLOT_MIN_CONTRAST),mark=hue===null?compiled.mark:pushToContrast(hue,controls,controlPole,SLOT_MIN_BORDER_CONTRAST),toward=brandReadsOnControls(c)?c.brand:controlPole,edge=(value,authored,compiledEdge)=>keepCompiled&&same(value,authored)?compiledEdge:pushToContrast(value,controls,toward,SLOT_MIN_BORDER_CONTRAST),primaryGrounds=[c.chatGround,c.composerFill,c.surface,c.surfaceCream],primaryEdge=primaryGrounds.every(ground=>contrastRatio(c.primary,ground)>=SLOT_MIN_BORDER_CONTRAST)?c.primary:pushToContrast(c.primary,primaryGrounds,poleForGrounds(primaryGrounds),SLOT_MIN_BORDER_CONTRAST);return{highlight:highlight,onHighlight:onHighlight,mark:mark,controlEdge:edge(c.brandBorder,compiled.brandBorder,compiled.controlEdge),structureEdge:edge(c.borderHairlineGreen,compiled.borderHairlineGreen,compiled.structureEdge),primaryEdge:primaryEdge}}var same2=(a,b)=>a!==void 0&&b!==void 0&&parseColor(a)===parseColor(b);function diffThemeAdjustments(merged,resolved){let compiled=(merged.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,m=merged.color,r=resolved.color,out=[],add=(field,role,requested,painted)=>{out.push(/* @__PURE__ */Object.freeze({field:field,role:role,requested:requested,painted:painted}))},own=(value,compiledValue)=>!same2(value,compiledValue);own(m.text.primary,compiled.text.primary)&&!same2(r.text.primary,m.text.primary)&&add("text_color","body text",m.text.primary,r.text.primary),own(m.brand,compiled.brand)&&(same2(r.brandInk,m.brand)||add("primary_color","brand text and icons",m.brand,r.brandInk),same2(r.primaryEdge,m.primary)||add("primary_color","edge of a filled control",m.primary,r.primaryEdge),!same2(r.controlEdge,m.brandBorder)&&!brandReadsOnControls({...r,brand:m.brand})&&add("primary_color","control outline",m.brand,r.controlEdge)),own(m.accent,compiled.accent)&&merged.slots.link?.textColor===void 0&&!same2(r.linkInk,m.accent)&&add("accent_color","link text",m.accent,r.linkInk),own(m.danger,compiled.danger)&&!same2(r.danger,m.danger)&&add("danger_color","error text",m.danger,r.danger);for(let name of THEME_SLOT_NAMES){let before=merged.slots[name],after=resolved.slots[name];before===void 0||after===void 0||before===after||(after.backgroundColor!==void 0&&!same2(after.backgroundColor,before.backgroundColor)&&add(`slots.${name}.background_color`,"fill",before.backgroundColor??null,after.backgroundColor),before.textColor!==void 0&&after.textColor!==void 0&&!same2(after.textColor,before.textColor)&&add(`slots.${name}.text_color`,"text",before.textColor??null,after.textColor),after.borderColor!==void 0&&!same2(after.borderColor,before.borderColor)&&add(`slots.${name}.border_color`,"outline",before.borderColor??null,after.borderColor))}/* @__PURE__ */
123
- return Object.freeze(out)}var warned=/* @__PURE__ */new Set;function warnThemeAdjustments(adjustments){if(adjustments.length===0)return;let message=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${adjustments.map(a=>` ${a.field} (${a.role}): ${a.requested??"not set"} -> ${a.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(warned.has(message))return;warned.add(message);let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}var DARK_VARIANT_GROUND="#23272C",DARK_VARIANT_TARGET_RATIO=4.5,DARK_VARIANT_LIGHTNESS_FLOOR=.6,DARK_VARIANT_LIGHTNESS_CEILING=.9,DARK_VARIANT_LIGHTNESS_STEP=.02,WHITE_INK="#FFFFFF",NEAR_BLACK_INK="#111111";function readsOnDark(candidate){return contrastRatio(candidate,DARK_VARIANT_GROUND)>=DARK_VARIANT_TARGET_RATIO&&Math.max(contrastRatio(candidate,WHITE_INK),contrastRatio(candidate,NEAR_BLACK_INK))>=DARK_VARIANT_TARGET_RATIO}function deriveDarkVariant(color){let rgba=toRgba(color);if(rgba===null)return null;let{h:h,s:s,l:l}=rgbToHsl(rgba.r,rgba.g,rgba.b),lDark=Math.min(Math.max(l,DARK_VARIANT_LIGHTNESS_FLOOR),DARK_VARIANT_LIGHTNESS_CEILING);for(let i=0;;i+=1){let li=lDark+i*DARK_VARIANT_LIGHTNESS_STEP;if(li>DARK_VARIANT_LIGHTNESS_CEILING)break;let rgb=hslToRgb({h:h,s:s,l:li}),candidate=rgbToHex(rgb.r,rgb.g,rgb.b);if(readsOnDark(candidate))return candidate}let ceiling=hslToRgb({h:h,s:s,l:DARK_VARIANT_LIGHTNESS_CEILING});return rgbToHex(ceiling.r,ceiling.g,ceiling.b)}var HIGH_CONTRAST_TARGET_RATIO=7,PUSH_STEP2=.05,BLACK2="#000000",WHITE2="#FFFFFF";function pushContrast(color,ground,pole,target){let flat=flattenOnto(color,ground);if(flat===null)return pole;if(contrastRatio(flat,ground)>=target)return flat;let from=toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP2;step+=1){let t=step*PUSH_STEP2,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(contrastRatio(candidate,ground)>=target)return candidate}return pole}function hardestGround(color,dark){let grounds2=textGrounds(color),pick4=grounds2[0],pickLum=luminanceOf(pick4);for(let ground of grounds2){let lum=luminanceOf(ground);(dark?lum>pickLum:lum<pickLum)&&(pick4=ground,pickLum=lum)}return pick4}function luminanceOf(color){let rgba=toRgba(color);return rgba===null?0:relativeLuminance(rgba)}function solid(wash,surface){return flattenOnto(wash,surface)??parseColor(wash)??surface}function deriveHighContrast(theme){let c=theme.color,lightInk=poleForGrounds(textGrounds(c))===WHITE2,pole=lightInk?WHITE2:BLACK2,ground=hardestGround(c,lightInk),text3=color2=>pushContrast(color2,ground,pole,HIGH_CONTRAST_TARGET_RATIO),color={...c,brandSoft:solid(c.brandSoft,c.surface),brandSofter:solid(c.brandSofter,c.surface),brandBorder:text3(c.brandBorder),borderHairlineGreen:text3(c.borderHairlineGreen),brandBorderStrong:text3(c.brandBorderStrong),controlEdge:text3(c.controlEdge),structureEdge:text3(c.structureEdge),brandInk:text3(c.brandInk),linkInk:text3(c.linkInk),borderRingCream:text3(c.borderRingCream),composerBorder:text3(c.composerBorder),text:{primary:text3(c.text.primary),secondary:text3(c.text.secondary),muted:text3(c.text.muted),placeholder:text3(c.text.placeholder),onBrand:c.text.onBrand,metaCool:text3(c.text.metaCool),timestamp:text3(c.text.timestamp)},badgeBgPositive:solid(c.badgeBgPositive,c.surface),badgeBgCaution:solid(c.badgeBgCaution,c.surface),badgeBgCritical:solid(c.badgeBgCritical,c.surface),badgeBgNeutral:solid(c.badgeBgNeutral,c.surface),checkupCardLowRiskBg:solid(c.checkupCardLowRiskBg,c.surface),checkupCardConcernBg:solid(c.checkupCardConcernBg,c.surface)};return deepFreeze({...theme,highContrast:true,color:color})}var BACKGROUND_STEPS=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),CREAM_STEP=BACKGROUND_STEPS.cream,SUBTLE_STEP=BACKGROUND_STEPS.subtle,RING_STEP=BACKGROUND_STEPS.ring,MIN_DERIVED_TYPE_SIZE=10;function mix(color,toward,t){let from=toRgba(color),to=toRgba(toward);if(from===null||to===null)return null;let at=(a,b)=>Math.round(a+(b-a)*t);return rgbToHex(at(from.r,to.r),at(from.g,to.g),at(from.b,to.b))}function surfaceFamily(background){if(background===null)return{};let pole=poleForGrounds([background]),cream=mix(background,pole,CREAM_STEP),subtle=mix(background,pole,SUBTLE_STEP),ring=mix(background,pole,RING_STEP);return cream===null||subtle===null||ring===null?{}:{surface:background,background:background,chatGround:background,bubbleAssistant:background,surfaceCream:cream,composerFill:cream,surfaceSubtle:subtle,skeleton:subtle,borderRingCream:ring}}function dangerFamily(danger){if(danger===null)return{};let rgba=toRgba(danger);return rgba===null?{}:{danger:danger,errorRed:danger,badgeBgCritical:`rgba(${rgba.r},${rgba.g},${rgba.b},0.12)`}}function typeSizesFor(base,current,compiled){if(base===null)return current;let factor=base/compiled.type.size.body;if(factor===1)return compiled.type.size;let out={};for(let[key,value]of Object.entries(compiled.type.size))out[key]=Math.max(MIN_DERIVED_TYPE_SIZE,Math.round(value*factor*10)/10);return out}function spaceFor(unit,current,compiled){if(unit===null)return current;let factor=unit/compiled.space.xs,s=n=>Math.round(n*factor),c=compiled.space;return{xs:s(c.xs),sm:s(c.sm),md:s(c.md),lg:s(c.lg),xl:s(c.xl),xxl:s(c.xxl)}}function radiiFor(base,compiled){let factor=base/compiled.radius.md,s=n=>Math.round(n*factor),r=compiled.radius;return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var APPEARANCE_PRESET_NAMES=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),APPEARANCE_PRESETS=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),APPEARANCE_SIZE_RANGES=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function isRecord2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isPreset(value){return typeof value=="string"&&APPEARANCE_PRESET_NAMES.includes(value.trim().toLowerCase())}function present(vars,key){let value=vars[key];return value??void 0}var PX_MAX_LENGTH=16;function parsePx(value){if(typeof value=="number")return Number.isFinite(value)?value:void 0;if(typeof value!="string"||value.length>PX_MAX_LENGTH)return;let match=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(value.trim());return match===null?void 0:Number(match[1])}var COLOR_VARIABLES=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],SIZE_VARIABLES=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(appearance){if(!isRecord2(appearance))return null;let preset=isPreset(appearance.theme)?APPEARANCE_PRESETS[appearance.theme.trim().toLowerCase()]:{},own=isRecord2(appearance.variables)?appearance.variables:{},vars={...preset};for(let[key,value]of Object.entries(own))value!=null&&(vars[key]=value);let out={},scheme=present(vars,"colorScheme"),schemeName=typeof scheme=="string"?scheme.trim().toLowerCase():null;(schemeName==="light"||schemeName==="dark"||schemeName==="auto")&&(out.color_scheme=schemeName);let suffix=schemeName==="dark"?"_dark":"";for(let[variable,field]of COLOR_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}let danger=present(vars,"colorDanger");danger!==void 0&&(out[`danger_color${suffix}`]=danger);let family=present(vars,"fontFamily");typeof family=="string"&&family.trim().length>0&&(out.font_family=family.trim());for(let[variable,field]of SIZE_VARIABLES){let px=parsePx(present(vars,variable));px!==void 0&&(out[field]=px)}let rules=appearance.rules;if(isRecord2(rules)){let slots={};for(let name of THEME_SLOT_NAMES){let paint=rules[name];isRecord2(paint)&&(slots[name]=paint)}Object.keys(slots).length>0&&(out.slots=slots)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var LOCKABLE_THEME_FIELDS=/* @__PURE__ */Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit"]),SLOT_LOCK_PREFIX="slots.",THEME_SCHEMA_VERSIONS=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(b){return Object.keys(b).every(key=>key==="schemaVersion"||(b[key]??null)===null)}function isKnownBrandingSchema(b){let version=b?.schemaVersion??null;return version===null||THEME_SCHEMA_VERSIONS.includes(version)}function lockedFieldsOf(b){/* @__PURE__ */
124
- return new Set(["hide_powered_by",...b?.lockedFields??[]])}function isThemeLockName(name){return name==="hide_powered_by"||LOCKABLE_THEME_FIELDS.includes(name)?true:name.startsWith(SLOT_LOCK_PREFIX)&&THEME_SLOT_NAMES.includes(name.slice(SLOT_LOCK_PREFIX.length))}function parseClientBranding(json){if(json===null||typeof json!="object")return null;let raw=json,flat=parseFlat(raw),expanded=expandAppearance(pick3(raw,"appearance")),branding=expanded===null?flat:overlayFlat(parseFlat(expanded),flat);return isEmptyBranding(branding)?null:/* @__PURE__ */Object.freeze(branding)}function overlayFlat(base,over){let out={...base};for(let[key,value]of Object.entries(over))value!=null&&(out[key]=value);let slots=mergeThemeSlots(base.slots??null,over.slots??null);return out.slots=Object.keys(slots).length===0?null:slots,out}function parseFlat(raw){return{displayName:parseNonEmptyString(pick3(raw,"display_name","displayName")),logoUrl:parseNonEmptyString(pick3(raw,"logo_url","logoUrl")),primaryColor:parseColor(pick3(raw,"primary_color","primaryColor")),accentColor:parseColor(pick3(raw,"accent_color","accentColor")),brightness:parseBrightness(pick3(raw,"brightness","color_scheme","colorScheme")),fontFamily:parseNonEmptyString(pick3(raw,"font_family","fontFamily")),fontUrl:parseNonEmptyString(pick3(raw,"font_url","fontUrl")),fonts:parseFaceMap(pick3(raw,"fonts")),fontUrls:parseFaceMap(pick3(raw,"font_urls","fontUrls")),placeholder:parseNonEmptyString(pick3(raw,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:parseBool(pick3(raw,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(pick3(raw,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(pick3(raw,"accent_color_dark","accentColorDark")),surfaceStyle:parseEnum(pick3(raw,"surface_style","surfaceStyle"),SURFACE_STYLES),radiusScale:parseEnum(pick3(raw,"radius_scale","radiusScale"),RADIUS_SCALES),logoUrlDark:parseNonEmptyString(pick3(raw,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(pick3(raw,"slots")),accessibilityMaxFontScale:parseMaxFontScale(pick3(raw,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:parseLockedFields(pick3(raw,"locked_fields","lockedFields")),schemaVersion:parseSchemaVersion(pick3(raw,"schema_version","schemaVersion")),backgroundColor:parseColor(pick3(raw,"background_color","backgroundColor")),backgroundColorDark:parseColor(pick3(raw,"background_color_dark","backgroundColorDark")),textColor:parseColor(pick3(raw,"text_color","textColor")),textColorDark:parseColor(pick3(raw,"text_color_dark","textColorDark")),dangerColor:parseColor(pick3(raw,"danger_color","dangerColor")),dangerColorDark:parseColor(pick3(raw,"danger_color_dark","dangerColorDark")),fontSizeBase:parseClamped(pick3(raw,"font_size_base","fontSizeBase"),APPEARANCE_SIZE_RANGES.fontSizeBase),borderRadius:parseClamped(pick3(raw,"border_radius","borderRadius"),APPEARANCE_SIZE_RANGES.borderRadius),spacingUnit:parseClamped(pick3(raw,"spacing_unit","spacingUnit"),APPEARANCE_SIZE_RANGES.spacingUnit)}}function parseClamped(value,range){let n=parseNumber(typeof value=="string"?value.trim().replace(/px$/i,""):value);return n===null?null:Math.min(range.max,Math.max(range.min,n))}function parseBool(value){if(typeof value=="boolean")return value;if(typeof value=="string"){let lower=value.trim().toLowerCase();if(lower==="true")return true;if(lower==="false")return false}return null}function pick3(raw,...keys){for(let key of keys)if(Object.prototype.hasOwnProperty.call(raw,key)){let value=raw[key];if(value!==void 0)return value}}function parseNonEmptyString(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}var FONT_FACE_KEYS=["regular","medium","bold","mono","monoMedium","monoBold"];function parseFaceMap(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;let raw=value,out={};for(let key of FONT_FACE_KEYS){let entry=parseNonEmptyString(pick3(raw,key));entry!==null&&(out[key]=entry)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var SURFACE_STYLES=["white","cream","subtle"],RADIUS_SCALES=["sharp","default","round"];function parseEnum(value,allowed){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return allowed.includes(lower)?lower:null}function parseBrightness(value){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return lower==="light"||lower==="dark"||lower==="auto"?lower:null}function parseNumber(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):Number.NaN;return Number.isFinite(n)&&(typeof value!="string"||value.trim().length>0)?n:null}var MAX_FONT_SCALE_FLOOR=1,MAX_FONT_SCALE_CEILING=3.1;function parseMaxFontScale(value){let n=parseNumber(value);return n===null?null:n<=0?0:Math.min(MAX_FONT_SCALE_CEILING,Math.max(MAX_FONT_SCALE_FLOOR,n))}function parseSchemaVersion(value){if(value==null)return null;let n=parseNumber(value);return n!==null&&Number.isInteger(n)&&n>=1?n:0}function toWireName(name){let trimmed=name.trim();return trimmed.startsWith(SLOT_LOCK_PREFIX)?trimmed:trimmed.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function parseLockedFields(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(typeof entry!="string")continue;let name=toWireName(entry);isThemeLockName(name)&&!out.includes(name)&&out.push(name)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}function hardenHttpsUrl(url){if(url===null)return null;let trimmed=url.trim();return trimmed.length===0?null:/^https:\/\/\S+$/i.test(trimmed)?trimmed:null}function withServerBranding(base,b){if(b===null||isEmptyBranding(b))return base;let palette=(b.brightness==="light"||b.brightness==="dark")&&b.brightness!==base.brightness?b.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT:base,compiled=palette.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,dark=palette.brightness==="dark",primaryIn=dark?b.primaryColorDark??darkVariantOf(b.primaryColor):b.primaryColor,accentIn=dark?b.accentColorDark??darkVariantOf(b.accentColor):b.accentColor,primaryRaw=primaryIn??palette.color.primary,accent=accentIn??palette.color.accent,keepsCompiled=primaryIn!==null&&isCompiledPrimary(b,primaryRaw,compiled,dark),primary=keepsCompiled?compiled.color.primary:primaryRaw,pr=primaryIn!==null&&!keepsCompiled?toRgba(primary):null,lift=c=>Math.round(c+(255-c)*.4),brandFamily=pr!==null?{brand:primary,bubbleUser:primary,brandInk:primary,text:{...palette.color.text,secondary:primary},brandSoft:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.10)`,brandSofter:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.15)`,brandBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.20)`,borderHairlineGreen:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.28)`,brandBorderStrong:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.55)`,composerBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.75)`,accentEdge:`rgb(${lift(pr.r)}, ${lift(pr.g)}, ${lift(pr.b)})`}:keepsCompiled?compiledBrandFamily(compiled,palette.color.text):{},background=(dark?b.backgroundColorDark:b.backgroundColor)??null,grounds2=surfaceFamily(background),groundFamily={...palette.color,...grounds2},bodyInk=(dark?b.textColorDark:b.textColor)??null,next={brightness:palette.brightness,highContrast:palette.highContrast,meta:{displayName:b.displayName??palette.meta.displayName,logoUrl:(dark?b.logoUrlDark??b.logoUrl:b.logoUrl)??palette.meta.logoUrl,placeholder:b.placeholder??palette.meta.placeholder,hidePoweredBy:b.hidePoweredBy??palette.meta.hidePoweredBy},color:{...palette.color,...brandFamily,...grounds2,...dangerFamily((dark?b.dangerColorDark??darkVariantOf(b.dangerColor??null):b.dangerColor)??null),...bodyInk!==null?{text:{...brandFamily.text??palette.color.text,primary:bodyInk}}:{},...surfaceOf(b.surfaceStyle??null,groundFamily),primary:primary,accent:accent,onPrimary:palette.color.onPrimary,onAccent:palette.color.onAccent},space:spaceFor(b.spacingUnit??null,palette.space,compiled),radius:b.borderRadius!=null?radiiFor(b.borderRadius,compiled):radiusOf(b.radiusScale??null,palette.radius,compiled),type:{...palette.type,...mergeFaces(palette.type,b),size:typeSizesFor(b.fontSizeBase??null,palette.type.size,compiled),maxScale:b.accessibilityMaxFontScale??palette.type.maxScale},motion:palette.motion,slots:mergeThemeSlots(palette.slots,b.slots??null)};return deepFreeze(next)}var FACE_CHAIN={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},FACE_GROUPS=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function isMonoFace(face2){return face2==="mono"||face2==="monoMedium"||face2==="monoBold"}function mergeFaces(base,b){let fonts=b.fonts??{},urls=b.fontUrls??{},families={...base.families},namedFaces={...base.namedFaces},fontUrls={...base.fontUrls};for(let face2 of FONT_FACE_KEYS){let named=FACE_CHAIN[face2].map(key=>fonts[key]).find(name=>name!==void 0),legacy=isMonoFace(face2)?null:b.fontFamily;named!==void 0?(families[face2]=named,namedFaces[face2]=true):legacy!==null&&(families[face2]=legacy,namedFaces[face2]=false);let url=urls[face2]??(face2==="regular"?b.fontUrl:null)??null;url!==null?fontUrls[face2]=url:named!==void 0&&delete fontUrls[face2]}for(let group of FACE_GROUPS)for(let face2 of group)namedFaces[face2]&&group.some(other=>other!==face2&&families[other]===families[face2])&&(namedFaces[face2]=false);return{family:families.regular,mono:families.mono,fontUrl:fontUrls.regular??null,families:families,namedFaces:namedFaces,fontUrls:fontUrls}}function darkVariantOf(color){return color===null?null:deriveDarkVariant(color)}function surfaceOf(style,family){if(style===null)return{};let c=family;return{chatGround:style==="white"?c.surface:style==="subtle"?c.surfaceSubtle:c.surfaceCream}}function sameColor(a,b){return a==null?false:parseColor(a)===parseColor(b)}function isCompiledPrimary(b,primary,compiled,dark){return sameColor(primary,compiled.color.primary)?true:dark&&(b.primaryColorDark??null)===null&&sameColor(b.primaryColor,EVERFUR_LIGHT.color.primary)}function compiledBrandFamily(compiled,text3){let c=compiled.color;return{text:{...text3,secondary:c.text.secondary},brand:c.brand,bubbleUser:c.bubbleUser,brandInk:c.brandInk,brandSoft:c.brandSoft,brandSofter:c.brandSofter,brandBorder:c.brandBorder,borderHairlineGreen:c.borderHairlineGreen,brandBorderStrong:c.brandBorderStrong,composerBorder:c.composerBorder,accentEdge:c.accentEdge}}var RADIUS_FACTOR={sharp:.5,default:1,round:1.5};function radiusOf(scale,base,compiled){if(scale===null)return base;let f=RADIUS_FACTOR[scale],r=compiled.radius,s=n=>Math.round(n*f);return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var DEFAULT_DISPLAY_NAME="Everfur",TEXT_SCALE_FLOOR=.5;function resolveTheme(input){return finalize(mergeLayers(input),input)}function themeAdjustments(input){let merged=mergeLayers(input);return diffThemeAdjustments(merged,finalize(merged,{...input,highContrast:false}))}function mergeLayers(input){let candidate=input?.branding??null,server=isKnownBrandingSchema(candidate)?candidate:null,client=withoutFields(input?.clientOverride??null,lockedFieldsOf(server)),device=input?.colorScheme==="dark"?"dark":"light",chosen=client?.brightness??server?.brightness??"light",withServer=withServerBranding((chosen==="auto"?device:chosen)==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,withoutBrightness(server));return withServerBranding(withServer,withoutBrightness(client))}function previewTheme(input,hints,options){return resolveTheme({...options,branding:parseClientBranding(hints),clientOverride:parseClientBranding(input)})}function wireNameOf(key){return key==="placeholder"?"chat_placeholder":toWireName(key)}var LOCK_ALIASES={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function isLocked(key,locked){return locked.has(wireNameOf(key))?true:(LOCK_ALIASES[key]??[]).some(name=>locked.has(name))}function withoutFields(b,locked){if(b===null)return null;let changed=false,out={...b};for(let key of Object.keys(b))(b[key]??null)!==null&&(isLocked(key,locked)||key==="lockedFields")&&(out[key]=null,changed=true);let slots=out.slots??null;if(slots!==null){let kept={},dropped=false;for(let name of THEME_SLOT_NAMES){let slot=slots[name];slot!==void 0&&(locked.has(`${SLOT_LOCK_PREFIX}${name}`)?dropped=true:kept[name]=slot)}dropped&&(out.slots=Object.keys(kept).length===0?null:/* @__PURE__ */Object.freeze(kept),changed=true)}if(!changed)return b;let stripped=/* @__PURE__ */Object.freeze(out);return isEmptyBranding(stripped)?null:stripped}function withoutBrightness(b){return b===null||b.brightness===null?b:/* @__PURE__ */Object.freeze({...b,brightness:null})}function scaledSizes(size,scale){if(scale===1)return size;let out={};for(let[key,value]of Object.entries(size))out[key]=Math.round(value*scale*10)/10;return out}function effectiveScale(textScale){return textScale===void 0||!Number.isFinite(textScale)?1:Math.max(TEXT_SCALE_FLOOR,textScale)}var SCALE_TIERS=["content","heading","control","compact","badge"];function tierCaps(maxScale){if(!(maxScale>0))return TEXT_SCALE_TIER_CAPS;let out={};for(let tier of SCALE_TIERS){let cap=TEXT_SCALE_TIER_CAPS[tier];out[tier]=cap===0?0:Math.min(cap,maxScale)}return out}function capped(scale,cap){return cap>0?Math.min(scale,cap):scale}function sizesByTier(size,scale,caps,scaleSizes){let out={};for(let tier of SCALE_TIERS)out[tier]=scaleSizes?scaledSizes(size,capped(scale,caps[tier])):size;return out}function slotGrounds(c){return{composerInput:[c.composerFill],sendButton:[c.composerFill],userBubble:[c.bubbleUser],assistantBubble:[c.chatGround,c.surfaceCream],vetBubble:[c.bubbleVet],recordCard:[c.surface],vetVisitButton:[c.primary],primaryButton:[c.brand],link:linkGrounds(c)}}function slotSurrounds(c){return{userBubble:[c.chatGround],assistantBubble:[c.chatGround],vetBubble:[c.chatGround],sendButton:[c.composerFill],vetVisitButton:[c.surfaceCream,c.surface,c.chatGround],primaryButton:[c.surface,c.surfaceCream]}}function registration(isFontRegistered,family){try{let answer=isFontRegistered(family);return answer===!0||answer===!1?answer:null}catch{return null}}function platformFaces(type,input){let isFontRegistered=input?.isFontRegistered,platformMono=input?.platformMonoFamily?.trim()||null;if(isFontRegistered===void 0&&platformMono===null)return{family:type.family,mono:type.mono,families:type.families,namedFaces:type.namedFaces};let families={...type.families},namedFaces={...type.namedFaces};for(let key of FONT_FACE_KEYS)!(families[key]===SYSTEM_FONT_FAMILY||families[key]===SYSTEM_MONO_FAMILY)&&isFontRegistered!==void 0&&registration(isFontRegistered,families[key])===false&&(families[key]=isMonoFace(key)?SYSTEM_MONO_FAMILY:SYSTEM_FONT_FAMILY,namedFaces[key]=false),platformMono!==null&&isMonoFace(key)&&families[key]===SYSTEM_MONO_FAMILY&&(families[key]=platformMono);return{family:families.regular,mono:families.mono,families:families,namedFaces:namedFaces}}function finalize(theme,input){let displayName=theme.meta.displayName.trim().length===0?DEFAULT_DISPLAY_NAME:theme.meta.displayName,logoUrl=hardenHttpsUrl(theme.meta.logoUrl),fontUrls={};for(let face2 of FONT_FACE_KEYS){let url=theme.type.fontUrls[face2];url!==void 0&&(fontUrls[face2]=hardenHttpsUrl(url))}let fontUrl=fontUrls.regular??null,motion=input?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:theme.motion.easing,reducedMotion:true}:theme.motion,maxScale=Number.isFinite(theme.type.maxScale)?theme.type.maxScale:DEFAULT_MAX_FONT_SCALE,scale=effectiveScale(input?.textScale),scaleCaps=tierCaps(maxScale),tierSizes=sizesByTier(theme.type.size,scale,scaleCaps,input?.scaleTypeSizes===true),color=guardInks(theme),finalized={brightness:theme.brightness,highContrast:false,meta:{displayName:displayName,logoUrl:logoUrl,placeholder:theme.meta.placeholder,hidePoweredBy:theme.meta.hidePoweredBy},color:color,space:theme.space,radius:theme.radius,type:{...theme.type,...platformFaces(theme.type,input),fontUrl:fontUrl,fontUrls:fontUrls,size:tierSizes.content,tierSizes:tierSizes,scale:scale,maxScale:maxScale,scaleCaps:scaleCaps},motion:motion,slots:guardSlotContrast(theme.slots,slotGrounds(color),slotSurrounds(color))};return input?.highContrast===true?deriveHighContrast(deepFreeze(finalized)):deepFreeze(finalized)}var ENTITLEMENTS_PATH="/widget/v1/entitlements",HTTP_NOT_MODIFIED=304,NOT_MODIFIED=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(auth,args={},funnel=createRequestFunnel({auth:auth})){let result=await funnel.send("entitlements.fetch",buildRequest(args));return result.ok?parseUpdated(result.value):result.error.httpStatus===HTTP_NOT_MODIFIED?NOT_MODIFIED:{kind:"failed",error:result.error}}var REGION_MAX=64;function buildRequest(args){let headers={};return isFiniteNumber(args.cachedRevision)&&(headers["if-none-match"]=`"${args.cachedRevision}"`),args.region&&args.region.length<=REGION_MAX?{method:"GET",path:ENTITLEMENTS_PATH,headers:headers,query:{region:args.region}}:{method:"GET",path:ENTITLEMENTS_PATH,headers:headers}}function parseUpdated(body){if(body===null||typeof body!="object"||!isFiniteNumber(body.revision))return malformed3();let region=typeof body.region=="string"?body.region:"",ttlSeconds=isFiniteNumber(body.ttl_seconds)?body.ttl_seconds:0;/* @__PURE__ */
122
+ return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}var tenants=/* @__PURE__ */new WeakMap,inFlight=/* @__PURE__ */new Map;function setPetRegistrationTenant(runtime,tenant){tenants.set(runtime,tenant)}function petRegistrationKey(runtime,auth,petRef2,body){let tenant=tenants.get(runtime);if(tenant===void 0)return null;let identity;if(auth.mode==="personalized"&&typeof auth.userRef=="string")identity=`u:${auth.userRef}`;else if(auth.mode==="anonymous"&&typeof auth.sessionId=="string")identity=`a:${auth.sessionId}|${auth.userRef??""}`;else return null;return`${tenant}|${identity}|${petRef2}|${stableKey(body)}`}function sharedPetRegistration(key,start){if(key===null)return start();let pending=inFlight.get(key);if(pending!==void 0)return pending;let settled=start().finally(()=>{inFlight.get(key)===settled&&inFlight.delete(key)});return inFlight.set(key,settled),settled}function stableKey(value){return value===null||typeof value!="object"?JSON.stringify(value)??"undefined":Array.isArray(value)?`[${value.map(stableKey).join(",")}]`:`{${Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>`${JSON.stringify(k)}:${stableKey(v)}`).join(",")}}`}var listeners=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function notifyPetsChanged(runtime){let set=listeners.get(runtime);if(set!==void 0)for(let listener of[...set])try{listener()}catch{}}var inFlight2=/* @__PURE__ */new Map;function sharedTokenProvider(scope,getToken){return()=>{let pending=inFlight2.get(scope);if(pending!==void 0)return pending;let mint;try{mint=Promise.resolve(getToken())}catch(error){mint=Promise.reject(error)}let settled=mint.finally(()=>{inFlight2.get(scope)===settled&&inFlight2.delete(scope)});return inFlight2.set(scope,settled),settled}}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds2){let worst=ink=>grounds2.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel2){return channel2<=.03928?channel2/12.92:Math.pow((channel2+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds2,pole,target){let first=grounds2[0];if(first===void 0)return pole;let reads=candidate=>grounds2.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}function rgbToHsl(r,g,b){let rn=r/255,gn=g/255,bn=b/255,mx=Math.max(rn,gn,bn),mn=Math.min(rn,gn,bn),l=(mx+mn)/2;if(mx===mn)return{h:0,s:0,l:l};let d=mx-mn,s=d/(1-Math.abs(2*l-1)),h;return mx===rn?(h=(gn-bn)/d*60,h<0&&(h=h+360)):mx===gn?h=((bn-rn)/d+2)*60:h=((rn-gn)/d+4)*60,{h:h,s:s,l:l}}function hslToRgb(hsl){let{h:h,s:s,l:l}=hsl,c=(1-Math.abs(2*l-1))*s,hp=h/60,x=c*(1-Math.abs(hp%2-1)),m=l-c/2,sector=Math.floor(hp)%6,rgb1=[[c,x,0],[x,c,0],[0,c,x],[0,x,c],[x,0,c],[c,0,x]],[r1,g1,b1]=rgb1[sector];return{r:channel(r1+m),g:channel(g1+m),b:channel(b1+m)}}function channel(v){return Math.min(255,Math.max(0,Math.floor(v*255+.5)))}var THEME_SLOT_NAMES=/* @__PURE__ */Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","vetBubble","recordCard","vetVisitButton","primaryButton","link","header","banner","chip","card","input","tab","bookingStep","dialog"]),THEME_SLOT_KEYS=/* @__PURE__ */Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),SLOT_MIN_CONTRAST=4.5,EMPTY=/* @__PURE__ */Object.freeze({});function isSlotName(value){return THEME_SLOT_NAMES.includes(value)}function parseRadius(value){let text3=typeof value=="string"&&value.length<=16?value.trim().replace(/ ?px$/i,""):null,n=typeof value=="number"?value:text3!==null&&text3.length>0?Number(text3):Number.NaN;return Number.isFinite(n)?Math.max(0,n):null}function parseThemeSlots(json){if(json===null||typeof json!="object"||Array.isArray(json))return null;let out={},any=false;for(let[name,raw]of Object.entries(json)){if(!isSlotName(name)||raw===null||typeof raw!="object")continue;let slot=parseSlot(raw);slot!==null&&(out[name]=slot,any=true)}return any?/* @__PURE__ */Object.freeze(out):null}function pick2(raw,snake,camel){return raw[snake]!==void 0?raw[snake]:raw[camel]}function parseSlot(raw){let slot={},backgroundColor=parseColor(pick2(raw,"background_color","backgroundColor"));backgroundColor!==null&&(slot.backgroundColor=backgroundColor);let borderColor=parseColor(pick2(raw,"border_color","borderColor"));borderColor!==null&&(slot.borderColor=borderColor);let borderRadius=parseRadius(pick2(raw,"border_radius","borderRadius"));borderRadius!==null&&(slot.borderRadius=borderRadius);let textColor=parseColor(pick2(raw,"text_color","textColor"));return textColor!==null&&(slot.textColor=textColor),Object.keys(slot).length===0?null:/* @__PURE__ */Object.freeze(slot)}function mergeThemeSlots(base,over){return over===null||Object.keys(over).length===0?base??EMPTY:base===null||Object.keys(base).length===0?over:/* @__PURE__ */Object.freeze({...base,...over})}function isOpaque(color){let rgba=toRgba(color);return rgba!==null&&rgba.a>=1}var SLOT_MIN_BORDER_CONTRAST=3;function boundaryFor(fill,surrounds,seats=[]){if(surrounds.length===0)return null;let shown=surrounds.map(ground=>flattenOnto(fill,ground)??fill);if(surrounds.every((ground,index)=>contrastRatio(shown[index],ground)>=SLOT_MIN_BORDER_CONTRAST))return null;let against=[...surrounds,...shown,...seats];return pushToContrast(shown[0],against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST)}function seatsOf(background,defaults){return background===void 0?defaults:defaults.length===0?[background]:defaults.map(ground=>flattenOnto(background,ground)??ground)}function someInkReads(seats,target){let pole=poleForGrounds(seats);return seats.every(seat=>contrastRatio(pole,seat)>=target)}function collapseUnsatisfiableFill(background,defaults){let ground=defaults[0];return ground===void 0?null:flattenOnto(background,ground)}function inkFor(seats){let pick5=legibleOn(seats[0],SLOT_MIN_CONTRAST);return seats.every(seat=>contrastRatio(pick5,seat)>=SLOT_MIN_CONTRAST)?pick5:poleForGrounds(seats)}function guardSlotContrast(slots,grounds2,surrounds){let changed=false,out={};for(let name of THEME_SLOT_NAMES){let slot=slots[name];if(slot===void 0)continue;let bg=slot.backgroundColor,defaults=grounds2?.[name]??[],seats=seatsOf(bg,defaults),next={...slot},fixed=false;if(bg!==void 0&&seats.length>1&&!someInkReads(seats,SLOT_MIN_CONTRAST)){let opaque=collapseUnsatisfiableFill(bg,defaults);opaque!==null&&(next.backgroundColor=opaque,seats=[opaque],fixed=true)}let around=surrounds?.[name],fill=next.backgroundColor,melts=around!==void 0&&fill!==void 0&&isOpaque(fill)&&boundaryFor(fill,around,seats)!==null;if(seats.length>0){let ink=slot.textColor;if(bg!==void 0)(ink===void 0||seats.some(seat=>contrastRatio(ink,seat)<SLOT_MIN_CONTRAST))&&(next.textColor=inkFor(seats),fixed=true);else if(ink!==void 0){let legible=pushToContrast(ink,seats,poleForGrounds(seats),SLOT_MIN_CONTRAST);legible!==ink&&(next.textColor=legible,fixed=true)}if(slot.borderColor!==void 0){let against=melts?[...seats,...around??[]]:seats,edge=pushToContrast(slot.borderColor,against,poleForGrounds(against),SLOT_MIN_BORDER_CONTRAST);edge!==slot.borderColor&&(next.borderColor=edge,fixed=true)}}if(melts&&fill!==void 0&&around!==void 0&&next.borderColor===void 0){let edge=boundaryFor(fill,around,seats);edge!==null&&(next.borderColor=edge,fixed=true)}out[name]=fixed?/* @__PURE__ */Object.freeze(next):slot,changed=changed||fixed}return changed?/* @__PURE__ */Object.freeze(out):slots}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});function textGrounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function controlGrounds(c){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill]}function brandReadsOnControls(c){return controlGrounds(c).every(ground=>contrastRatio(c.brand,ground)>=SLOT_MIN_BORDER_CONTRAST)}function linkGrounds(c){return[c.chatGround,c.surface,c.surfaceCream]}function statusGrounds(c,wash2){return[c.surface,c.surfaceCream,c.background,c.chatGround,c.composerFill,...washGrounds(c,wash2)]}function washGrounds(c,wash2){return[flattenOnto(wash2,c.surface)??c.surface,flattenOnto(wash2,c.surfaceCream)??c.surfaceCream]}function composerGrounds(c){return[c.composerFill,c.chatGround]}var AUTHORED_AS_IS=/* @__PURE__ */new Set(["text.timestamp","text.placeholder","errorRed","warningStrong","composerBorder"]);function onCompiledGrounds(c,compiled){let own=new Set(textGrounds(compiled));return textGrounds(c).every(ground=>own.has(ground))}function guardInks(theme){let c=theme.color,compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,other=(theme.brightness==="dark"?EVERFUR_LIGHT:EVERFUR_DARK).color,grounds2=textGrounds(c),flipped=poleForGrounds(grounds2)!==poleForGrounds(textGrounds(compiled)),keepCompiled=onCompiledGrounds(c,compiled),dangerIsCompiled=c.danger===compiled.danger&&c.badgeBgCritical===compiled.badgeBgCritical,ink=(name,value,authored,twin,on,target)=>{let untouched=value===authored&&(name!=="errorRed"||dangerIsCompiled);return untouched&&keepCompiled&&AUTHORED_AS_IS.has(name)?value:pushToContrast(untouched&&flipped?twin:value,on,poleForGrounds(on),target)},text3=(key,on,target)=>ink(`text.${key}`,c.text[key],compiled.text[key],other.text[key],on,target),token=(key,value,on,target)=>ink(key,value,compiled[key],other[key],on,target),tint=key=>flipped&&c[key]===compiled[key]?other[key]:c[key],primary=c.primary,onPrimary=legibleOn(primary,SLOT_MIN_CONTRAST),danger=token("danger",c.danger,[...grounds2,...washGrounds(c,c.badgeBgCritical)],SLOT_MIN_CONTRAST),guarded={...c,onPrimary:onPrimary,onAccent:legibleOn(c.accent,SLOT_MIN_CONTRAST),onDanger:contrastRatio(onPrimary,danger)>=SLOT_MIN_CONTRAST?onPrimary:legibleOn(danger,SLOT_MIN_CONTRAST),brandSoft:tint("brandSoft"),brandSofter:tint("brandSofter"),brandBorder:tint("brandBorder"),borderHairlineGreen:tint("borderHairlineGreen"),brandInk:token("brandInk",c.brandInk,grounds2,SLOT_MIN_CONTRAST),linkInk:token("linkInk",theme.slots.link?.textColor??c.accent,linkGrounds(c),SLOT_MIN_CONTRAST),text:{...c.text,primary:text3("primary",grounds2,SLOT_MIN_CONTRAST),secondary:text3("secondary",grounds2,SLOT_MIN_CONTRAST),muted:text3("muted",grounds2,SLOT_MIN_CONTRAST),metaCool:text3("metaCool",grounds2,SLOT_MIN_CONTRAST),timestamp:text3("timestamp",grounds2,SLOT_MIN_CONTRAST),placeholder:text3("placeholder",controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},danger:danger,errorRed:token("errorRed",c.errorRed,statusGrounds(c,c.badgeBgCritical),SLOT_MIN_CONTRAST),warningStrong:token("warningStrong",c.warningStrong,statusGrounds(c,c.badgeBgCaution),SLOT_MIN_CONTRAST),composerBorder:token("composerBorder",c.composerBorder,composerGrounds(c),SLOT_MIN_BORDER_CONTRAST),brandBorderStrong:token("brandBorderStrong",c.brandBorderStrong,controlGrounds(c),SLOT_MIN_BORDER_CONTRAST)},accented={...guarded,...accentFamily(guarded,compiled,keepCompiled)};return{...accented,...statusInks(c,accented,compiled)}}function statusInks(merged,g,compiled){let out={},push=(value,on,target)=>pushToContrast(value,on,poleForGrounds(on),target);if((!same(merged.success,compiled.success)||!same(merged.badgeBgPositive,compiled.badgeBgPositive))&&(out.success=push(merged.success,statusGrounds(g,merged.badgeBgPositive),SLOT_MIN_CONTRAST)),(!same(merged.cautionAccent,compiled.cautionAccent)||!same(merged.badgeBgCaution,compiled.badgeBgCaution))&&(out.cautionAccent=push(merged.cautionAccent,statusGrounds(g,merged.badgeBgCaution),SLOT_MIN_CONTRAST)),isPartnerInfo(merged,compiled)){out.info=push(merged.info,statusGrounds(g,merged.badgeBgInfo),SLOT_MIN_CONTRAST);let edgeGrounds=[g.surface,g.chatGround,...washGrounds(g,merged.badgeBgInfo)];out.infoEdge=push(merged.infoEdge,edgeGrounds,SLOT_MIN_BORDER_CONTRAST)}else out.info=g.brandInk,out.badgeBgInfo=g.brandSoft,out.infoEdge=g.structureEdge;return out}function isPartnerInfo(c,compiled){return!same(c.info,compiled.info)||!same(c.badgeBgInfo,compiled.badgeBgInfo)}var HIGHLIGHT_LIGHT_TINT=.24,HIGHLIGHT_DARK_TINT=.3;function same(a,b){return parseColor(a)===parseColor(b)}function partnerHue(c,compiled){return same(c.accent,compiled.accent)?same(c.brand,compiled.brand)?null:c.brand:c.accent}function tintOver(hue,surface,tint){let wash2=withAlpha(hue,tint);return(wash2===null?null:flattenOnto(wash2,surface))??surface}function accentFamily(c,compiled,keepCompiled){let hue=partnerHue(c,compiled),controls=controlGrounds(c),controlPole=poleForGrounds(controls),darkGround=poleForGrounds([c.surface])===WHITE,everfurMarks=hue===null&&keepCompiled,highlight;everfurMarks?highlight=compiled.highlight:hue===null?highlight=darkGround?tintOver(EVERFUR_LIGHT.color.highlight,c.surface,HIGHLIGHT_DARK_TINT):EVERFUR_LIGHT.color.highlight:highlight=tintOver(hue,c.surface,darkGround?HIGHLIGHT_DARK_TINT:HIGHLIGHT_LIGHT_TINT);let onHighlight=everfurMarks?compiled.onHighlight:pushToContrast(c.text.primary,[highlight],poleForGrounds([highlight]),SLOT_MIN_CONTRAST),mark=hue===null?compiled.mark:pushToContrast(hue,controls,controlPole,SLOT_MIN_BORDER_CONTRAST),toward=brandReadsOnControls(c)?c.brand:controlPole,edge=(value,authored,compiledEdge)=>keepCompiled&&same(value,authored)?compiledEdge:pushToContrast(value,controls,toward,SLOT_MIN_BORDER_CONTRAST),primaryGrounds=[c.chatGround,c.composerFill,c.surface,c.surfaceCream],primaryEdge=primaryGrounds.every(ground=>contrastRatio(c.primary,ground)>=SLOT_MIN_BORDER_CONTRAST)?c.primary:pushToContrast(c.primary,primaryGrounds,poleForGrounds(primaryGrounds),SLOT_MIN_BORDER_CONTRAST);return{highlight:highlight,onHighlight:onHighlight,mark:mark,controlEdge:edge(c.brandBorder,compiled.brandBorder,compiled.controlEdge),structureEdge:edge(c.borderHairlineGreen,compiled.borderHairlineGreen,compiled.structureEdge),primaryEdge:primaryEdge}}var same2=(a,b)=>a!==void 0&&b!==void 0&&parseColor(a)===parseColor(b);function diffThemeAdjustments(merged,resolved){let compiled=(merged.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,m=merged.color,r=resolved.color,out=[],add=(field,role,requested,painted)=>{out.push(/* @__PURE__ */Object.freeze({field:field,role:role,requested:requested,painted:painted}))},own=(value,compiledValue)=>!same2(value,compiledValue);own(m.text.primary,compiled.text.primary)&&!same2(r.text.primary,m.text.primary)&&add("text_color","body text",m.text.primary,r.text.primary),own(m.brand,compiled.brand)&&(same2(r.brandInk,m.brand)||add("primary_color","brand text and icons",m.brand,r.brandInk),same2(r.primaryEdge,m.primary)||add("primary_color","edge of a filled control",m.primary,r.primaryEdge),!same2(r.controlEdge,m.brandBorder)&&!brandReadsOnControls({...r,brand:m.brand})&&add("primary_color","control outline",m.brand,r.controlEdge)),own(m.accent,compiled.accent)&&merged.slots.link?.textColor===void 0&&!same2(r.linkInk,m.accent)&&add("accent_color","link text",m.accent,r.linkInk),own(m.danger,compiled.danger)&&!same2(r.danger,m.danger)&&add("danger_color","error text",m.danger,r.danger),own(m.success,compiled.success)&&!same2(r.success,m.success)&&add("success_color","positive status",m.success,r.success),own(m.warningStrong,compiled.warningStrong)&&!same2(r.warningStrong,m.warningStrong)&&add("warning_color","caution text",m.warningStrong,r.warningStrong),own(m.cautionAccent,compiled.cautionAccent)&&!same2(r.cautionAccent,m.cautionAccent)&&add("warning_color","caution accent",m.cautionAccent,r.cautionAccent),(own(m.info,compiled.info)||own(m.badgeBgInfo,compiled.badgeBgInfo))&&(same2(r.info,m.info)||add("info_color","information text",m.info,r.info),same2(r.infoEdge,m.infoEdge)||add("info_color","information outline",m.infoEdge,r.infoEdge));for(let name of THEME_SLOT_NAMES){let before=merged.slots[name],after=resolved.slots[name];before===void 0||after===void 0||before===after||(after.backgroundColor!==void 0&&!same2(after.backgroundColor,before.backgroundColor)&&add(`slots.${name}.background_color`,"fill",before.backgroundColor??null,after.backgroundColor),before.textColor!==void 0&&after.textColor!==void 0&&!same2(after.textColor,before.textColor)&&add(`slots.${name}.text_color`,"text",before.textColor??null,after.textColor),after.borderColor!==void 0&&!same2(after.borderColor,before.borderColor)&&add(`slots.${name}.border_color`,"outline",before.borderColor??null,after.borderColor))}/* @__PURE__ */
123
+ return Object.freeze(out)}var warned=/* @__PURE__ */new Set;function warnThemeAdjustments(adjustments){if(adjustments.length===0)return;let message=`[everfur] The theme guard changed colours that did not reach WCAG contrast (4.5:1 for text, 3:1 for outlines) on the grounds they are drawn on:\n${adjustments.map(a=>` ${a.field} (${a.role}): ${a.requested??"not set"} -> ${a.painted}`).join(`\n`)}\nThe painted colours are what useEverfurTheme() and previewTheme() return. Choose colours that read on your background to keep them as given.`;if(warned.has(message))return;warned.add(message);let globalConsole=globalThis.console;try{globalConsole?.warn?.(message)}catch{}}var DARK_VARIANT_GROUND="#23272C",DARK_VARIANT_TARGET_RATIO=4.5,DARK_VARIANT_LIGHTNESS_FLOOR=.6,DARK_VARIANT_LIGHTNESS_CEILING=.9,DARK_VARIANT_LIGHTNESS_STEP=.02,WHITE_INK="#FFFFFF",NEAR_BLACK_INK="#111111";function readsOnDark(candidate){return contrastRatio(candidate,DARK_VARIANT_GROUND)>=DARK_VARIANT_TARGET_RATIO&&Math.max(contrastRatio(candidate,WHITE_INK),contrastRatio(candidate,NEAR_BLACK_INK))>=DARK_VARIANT_TARGET_RATIO}function deriveDarkVariant(color){let rgba=toRgba(color);if(rgba===null)return null;let{h:h,s:s,l:l}=rgbToHsl(rgba.r,rgba.g,rgba.b),lDark=Math.min(Math.max(l,DARK_VARIANT_LIGHTNESS_FLOOR),DARK_VARIANT_LIGHTNESS_CEILING);for(let i=0;;i+=1){let li=lDark+i*DARK_VARIANT_LIGHTNESS_STEP;if(li>DARK_VARIANT_LIGHTNESS_CEILING)break;let rgb=hslToRgb({h:h,s:s,l:li}),candidate=rgbToHex(rgb.r,rgb.g,rgb.b);if(readsOnDark(candidate))return candidate}let ceiling=hslToRgb({h:h,s:s,l:DARK_VARIANT_LIGHTNESS_CEILING});return rgbToHex(ceiling.r,ceiling.g,ceiling.b)}var HIGH_CONTRAST_TARGET_RATIO=7,PUSH_STEP2=.05,BLACK2="#000000",WHITE2="#FFFFFF";function pushContrast(color,ground,pole,target){let flat=flattenOnto(color,ground);if(flat===null)return pole;if(contrastRatio(flat,ground)>=target)return flat;let from=toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP2;step+=1){let t=step*PUSH_STEP2,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(contrastRatio(candidate,ground)>=target)return candidate}return pole}function hardestGround(color,dark){let grounds2=textGrounds(color),pick5=grounds2[0],pickLum=luminanceOf(pick5);for(let ground of grounds2){let lum=luminanceOf(ground);(dark?lum>pickLum:lum<pickLum)&&(pick5=ground,pickLum=lum)}return pick5}function luminanceOf(color){let rgba=toRgba(color);return rgba===null?0:relativeLuminance(rgba)}function solid(wash2,surface){return flattenOnto(wash2,surface)??parseColor(wash2)??surface}function deriveHighContrast(theme){let c=theme.color,lightInk=poleForGrounds(textGrounds(c))===WHITE2,pole=lightInk?WHITE2:BLACK2,ground=hardestGround(c,lightInk),text3=color2=>pushContrast(color2,ground,pole,HIGH_CONTRAST_TARGET_RATIO),color={...c,brandSoft:solid(c.brandSoft,c.surface),brandSofter:solid(c.brandSofter,c.surface),brandBorder:text3(c.brandBorder),borderHairlineGreen:text3(c.borderHairlineGreen),brandBorderStrong:text3(c.brandBorderStrong),controlEdge:text3(c.controlEdge),structureEdge:text3(c.structureEdge),brandInk:text3(c.brandInk),linkInk:text3(c.linkInk),borderRingCream:text3(c.borderRingCream),composerBorder:text3(c.composerBorder),text:{primary:text3(c.text.primary),secondary:text3(c.text.secondary),muted:text3(c.text.muted),placeholder:text3(c.text.placeholder),onBrand:c.text.onBrand,metaCool:text3(c.text.metaCool),timestamp:text3(c.text.timestamp)},badgeBgPositive:solid(c.badgeBgPositive,c.surface),badgeBgCaution:solid(c.badgeBgCaution,c.surface),badgeBgCritical:solid(c.badgeBgCritical,c.surface),badgeBgNeutral:solid(c.badgeBgNeutral,c.surface),checkupCardLowRiskBg:solid(c.checkupCardLowRiskBg,c.surface),checkupCardConcernBg:solid(c.checkupCardConcernBg,c.surface),info:text3(c.info),infoEdge:text3(c.infoEdge),badgeBgInfo:solid(c.badgeBgInfo,c.surface)};return deepFreeze({...theme,highContrast:true,color:color})}var BACKGROUND_STEPS=/* @__PURE__ */Object.freeze({cream:.03,subtle:.07,ring:.16}),CREAM_STEP=BACKGROUND_STEPS.cream,SUBTLE_STEP=BACKGROUND_STEPS.subtle,RING_STEP=BACKGROUND_STEPS.ring,MIN_DERIVED_TYPE_SIZE=10;function mix(color,toward,t){let from=toRgba(color),to=toRgba(toward);if(from===null||to===null)return null;let at=(a,b)=>Math.round(a+(b-a)*t);return rgbToHex(at(from.r,to.r),at(from.g,to.g),at(from.b,to.b))}function surfaceFamily(background){if(background===null)return{};let pole=poleForGrounds([background]),cream=mix(background,pole,CREAM_STEP),subtle=mix(background,pole,SUBTLE_STEP),ring=mix(background,pole,RING_STEP);return cream===null||subtle===null||ring===null?{}:{surface:background,background:background,chatGround:background,bubbleAssistant:background,surfaceCream:cream,composerFill:cream,surfaceSubtle:subtle,skeleton:subtle,borderRingCream:ring}}function dangerFamily(danger){if(danger===null)return{};let rgba=toRgba(danger);return rgba===null?{}:{danger:danger,errorRed:danger,badgeBgCritical:`rgba(${rgba.r},${rgba.g},${rgba.b},0.12)`}}function typeSizesFor(base,current,compiled){if(base===null)return current;let factor=base/compiled.type.size.body;if(factor===1)return compiled.type.size;let out={};for(let[key,value]of Object.entries(compiled.type.size))out[key]=Math.max(MIN_DERIVED_TYPE_SIZE,Math.round(value*factor*10)/10);return out}function spaceFor(unit,current,compiled){if(unit===null)return current;let factor=unit/compiled.space.xs,s=n=>Math.round(n*factor),c=compiled.space;return{xs:s(c.xs),sm:s(c.sm),md:s(c.md),lg:s(c.lg),xl:s(c.xl),xxl:s(c.xxl)}}function radiiFor(base,compiled){let factor=base/compiled.radius.md,s=n=>Math.round(n*factor),r=compiled.radius;return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var STATUS_WASH=/* @__PURE__ */Object.freeze({success:/* @__PURE__ */Object.freeze({light:.12,dark:.18}),successCard:/* @__PURE__ */Object.freeze({light:.1,dark:.16}),warning:/* @__PURE__ */Object.freeze({light:.14,dark:.2}),info:/* @__PURE__ */Object.freeze({light:.1,dark:.12})});function wash(color,alpha){let rgba=toRgba(color);return rgba===null?null:`rgba(${rgba.r},${rgba.g},${rgba.b},${alpha})`}function successFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.success.dark:STATUS_WASH.success.light),card=wash(color,dark?STATUS_WASH.successCard.dark:STATUS_WASH.successCard.light);return badge===null||card===null?{}:{success:color,badgeBgPositive:badge,checkupCardLowRiskBg:card}}function warningFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.warning.dark:STATUS_WASH.warning.light);return badge===null?{}:{warningStrong:color,cautionAccent:color,badgeBgCaution:badge}}function infoFamily(color,dark){if(color===null)return{};let badge=wash(color,dark?STATUS_WASH.info.dark:STATUS_WASH.info.light);return badge===null?{}:{info:color,infoEdge:color,badgeBgInfo:badge}}function lineHeightsFor(lineHeight,current,compiled){if(lineHeight===null)return current;let c=compiled.type.lineHeight,factor=lineHeight/c.normal;if(factor===1)return c;let s=n=>Math.round(n*factor*100)/100;return{tight:s(c.tight),snug:s(c.snug),normal:s(c.normal),relaxed:s(c.relaxed)}}function slotGrounds(c){return{composerInput:[c.composerFill],sendButton:[c.composerFill],userBubble:[c.bubbleUser],assistantBubble:[c.chatGround,c.surfaceCream],vetBubble:[c.bubbleVet],recordCard:[c.surface],vetVisitButton:[c.primary],primaryButton:[c.brand],link:linkGrounds(c),header:[c.surface,c.background,c.chatGround],banner:[flattenOnto(c.badgeBgInfo,c.surface)??c.surface,flattenOnto(c.badgeBgCaution,c.surface)??c.surface,c.surface],chip:[c.chatGround,c.surface,c.background,c.surfaceCream],card:[c.surface],input:[c.surface,c.composerFill,c.surfaceCream,c.surfaceSubtle],tab:[c.surface,c.background],bookingStep:[c.surface,c.background],dialog:[c.surface]}}function slotSurrounds(c){return{userBubble:[c.chatGround],assistantBubble:[c.chatGround],vetBubble:[c.chatGround],sendButton:[c.composerFill],vetVisitButton:[c.surfaceCream,c.surface,c.chatGround],primaryButton:[c.surface,c.surfaceCream]}}var APPEARANCE_PRESET_NAMES=/* @__PURE__ */Object.freeze(["everfur","minimal","night"]),APPEARANCE_PRESETS=/* @__PURE__ */Object.freeze({everfur:/* @__PURE__ */Object.freeze({}),minimal:/* @__PURE__ */Object.freeze({colorPrimary:"#111111",colorAccent:"#111111",borderRadius:6}),night:/* @__PURE__ */Object.freeze({colorScheme:"dark"})}),APPEARANCE_SIZE_RANGES=/* @__PURE__ */Object.freeze({fontSizeBase:/* @__PURE__ */Object.freeze({min:12,max:20,default:14}),borderRadius:/* @__PURE__ */Object.freeze({min:0,max:32,default:14}),spacingUnit:/* @__PURE__ */Object.freeze({min:3,max:6,default:4})});function isRecord2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isPreset(value){return typeof value=="string"&&APPEARANCE_PRESET_NAMES.includes(value.trim().toLowerCase())}function present(vars,key){let value=vars[key];return value??void 0}var PX_MAX_LENGTH=16;function parsePx(value){if(typeof value=="number")return Number.isFinite(value)?value:void 0;if(typeof value!="string"||value.length>PX_MAX_LENGTH)return;let match=/^(-?\d+(?:\.\d+)?)(?: ?px)?$/i.exec(value.trim());return match===null?void 0:Number(match[1])}var COLOR_VARIABLES=[["colorPrimary","primary_color"],["colorAccent","accent_color"],["colorBackground","background_color"],["colorText","text_color"]],STATUS_VARIABLES=[["colorDanger","danger_color"],["colorSuccess","success_color"],["colorWarning","warning_color"],["colorInfo","info_color"]],PASSTHROUGH_VARIABLES=[["fontWeightBody","font_weight_body"],["fontWeightHeading","font_weight_heading"],["lineHeight","line_height"]],STRING_VARIABLES=[["fontFamily","font_family"],["fontFamilyHeading","heading_font_family"],["logoUrl","logo_url"],["assistantAvatarUrl","assistant_avatar_url"]],SIZE_VARIABLES=[["fontSizeBase","font_size_base"],["borderRadius","border_radius"],["spacingUnit","spacing_unit"]];function expandAppearance(appearance){if(!isRecord2(appearance))return null;let preset=isPreset(appearance.theme)?APPEARANCE_PRESETS[appearance.theme.trim().toLowerCase()]:{},own=isRecord2(appearance.variables)?appearance.variables:{},vars={...preset};for(let[key,value]of Object.entries(own))value!=null&&(vars[key]=value);let out={},scheme=present(vars,"colorScheme"),schemeName=typeof scheme=="string"?scheme.trim().toLowerCase():null;(schemeName==="light"||schemeName==="dark"||schemeName==="auto")&&(out.color_scheme=schemeName);let suffix=schemeName==="dark"?"_dark":"";for(let[variable,field]of COLOR_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}for(let[variable,field]of STATUS_VARIABLES){let value=present(vars,variable);value!==void 0&&(out[`${field}${suffix}`]=value)}for(let[variable,field]of STRING_VARIABLES){let value=present(vars,variable);typeof value=="string"&&value.trim().length>0&&(out[field]=value.trim())}for(let[variable,field]of SIZE_VARIABLES){let px=parsePx(present(vars,variable));px!==void 0&&(out[field]=px)}for(let[variable,field]of PASSTHROUGH_VARIABLES){let value=present(vars,variable);(typeof value=="number"||typeof value=="string")&&(out[field]=value)}let fonts=appearance.fonts;Array.isArray(fonts)&&fonts.length>0&&(out.font_sources=fonts);let rules=appearance.rules;if(isRecord2(rules)){let slots={};for(let name of THEME_SLOT_NAMES){let paint=rules[name];isRecord2(paint)&&(slots[name]=paint)}Object.keys(slots).length>0&&(out.slots=slots)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var LINE_HEIGHT_RANGE=/* @__PURE__ */Object.freeze({min:1,max:2}),FAMILY_MAX_LENGTH=100,URL_MAX_LENGTH=2048,WEIGHTS=["100","200","300","400","500","600","700","800","900"];function finiteNumber(value){if(typeof value=="number")return Number.isFinite(value)?value:null;if(typeof value!="string"||value.trim().length===0||value.length>16)return null;let n=Number(value.trim());return Number.isFinite(n)?n:null}function parseFontWeight(value){let n=finiteNumber(value);if(n===null)return null;let name=String(n);return WEIGHTS.includes(name)?name:null}function parseLineHeight(value){let n=finiteNumber(value);return n===null?null:Math.min(LINE_HEIGHT_RANGE.max,Math.max(LINE_HEIGHT_RANGE.min,n))}function fontSourceUrl(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>URL_MAX_LENGTH?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(trimmed)?trimmed:null}function familyName(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>FAMILY_MAX_LENGTH||/[\u0000-\u001F\u007F]/.test(trimmed)?null:trimmed}function isRecord3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function pick3(raw,...keys){for(let key of keys)if(raw[key]!==void 0&&raw[key]!==null)return raw[key]}function parseFontSource(raw){if(!isRecord3(raw))return null;let family=familyName(raw.family);if(family===null)return null;let srcRaw=pick3(raw,"src"),cssRaw=pick3(raw,"cssSrc","css_src");if(srcRaw===void 0==(cssRaw===void 0))return null;if(cssRaw!==void 0){let cssSrc=fontSourceUrl(cssRaw);return cssSrc===null?null:/* @__PURE__ */Object.freeze({family:family,cssSrc:cssSrc})}let src=fontSourceUrl(srcRaw);if(src===null)return null;let out={family:family,src:src},weight=parseFontWeight(raw.weight);weight!==null&&(out.weight=weight);let style=typeof raw.style=="string"?raw.style.trim().toLowerCase():null;return(style==="normal"||style==="italic")&&(out.style=style),/* @__PURE__ */Object.freeze(out)}function parseFontSources(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(out.length>=4)break;let source=parseFontSource(entry);source!==null&&out.push(source)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var LOCKABLE_THEME_FIELDS=/* @__PURE__ */Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots","background_color","background_color_dark","text_color","text_color_dark","danger_color","danger_color_dark","font_size_base","border_radius","spacing_unit","success_color","success_color_dark","warning_color","warning_color_dark","info_color","info_color_dark","heading_font_family","font_weight_body","font_weight_heading","line_height","assistant_avatar_url","font_sources"]),SLOT_LOCK_PREFIX="slots.",THEME_SCHEMA_VERSIONS=/* @__PURE__ */Object.freeze([1,2]);function isEmptyBranding(b){return Object.keys(b).every(key=>key==="schemaVersion"||(b[key]??null)===null)}function isKnownBrandingSchema(b){let version=b?.schemaVersion??null;return version===null||THEME_SCHEMA_VERSIONS.includes(version)}function lockedFieldsOf(b){/* @__PURE__ */
124
+ return new Set(["hide_powered_by",...b?.lockedFields??[]])}function isThemeLockName(name){return name==="hide_powered_by"||LOCKABLE_THEME_FIELDS.includes(name)?true:name.startsWith(SLOT_LOCK_PREFIX)&&THEME_SLOT_NAMES.includes(name.slice(SLOT_LOCK_PREFIX.length))}function parseClientBranding(json){if(json===null||typeof json!="object")return null;let raw=json,flat=parseFlat(raw),expanded=expandAppearance(pick4(raw,"appearance")),branding=expanded===null?flat:overlayFlat(parseFlat(expanded),flat);return isEmptyBranding(branding)?null:/* @__PURE__ */Object.freeze(branding)}function overlayFlat(base,over){let out={...base};for(let[key,value]of Object.entries(over))value!=null&&(out[key]=value);let slots=mergeThemeSlots(base.slots??null,over.slots??null);return out.slots=Object.keys(slots).length===0?null:slots,out}function parseFlat(raw){return{displayName:parseNonEmptyString(pick4(raw,"display_name","displayName")),logoUrl:parseNonEmptyString(pick4(raw,"logo_url","logoUrl")),primaryColor:parseColor(pick4(raw,"primary_color","primaryColor")),accentColor:parseColor(pick4(raw,"accent_color","accentColor")),brightness:parseBrightness(pick4(raw,"brightness","color_scheme","colorScheme")),fontFamily:parseNonEmptyString(pick4(raw,"font_family","fontFamily")),fontUrl:parseNonEmptyString(pick4(raw,"font_url","fontUrl")),fonts:parseFaceMap(pick4(raw,"fonts")),fontUrls:parseFaceMap(pick4(raw,"font_urls","fontUrls")),placeholder:parseNonEmptyString(pick4(raw,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:parseBool(pick4(raw,"hide_powered_by","hidePoweredBy")),primaryColorDark:parseColor(pick4(raw,"primary_color_dark","primaryColorDark")),accentColorDark:parseColor(pick4(raw,"accent_color_dark","accentColorDark")),surfaceStyle:parseEnum(pick4(raw,"surface_style","surfaceStyle"),SURFACE_STYLES),radiusScale:parseEnum(pick4(raw,"radius_scale","radiusScale"),RADIUS_SCALES),logoUrlDark:parseNonEmptyString(pick4(raw,"logo_url_dark","logoUrlDark")),slots:parseThemeSlots(pick4(raw,"slots")),accessibilityMaxFontScale:parseMaxFontScale(pick4(raw,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:parseLockedFields(pick4(raw,"locked_fields","lockedFields")),schemaVersion:parseSchemaVersion(pick4(raw,"schema_version","schemaVersion")),backgroundColor:parseColor(pick4(raw,"background_color","backgroundColor")),backgroundColorDark:parseColor(pick4(raw,"background_color_dark","backgroundColorDark")),textColor:parseColor(pick4(raw,"text_color","textColor")),textColorDark:parseColor(pick4(raw,"text_color_dark","textColorDark")),dangerColor:parseColor(pick4(raw,"danger_color","dangerColor")),dangerColorDark:parseColor(pick4(raw,"danger_color_dark","dangerColorDark")),fontSizeBase:parseClamped(pick4(raw,"font_size_base","fontSizeBase"),APPEARANCE_SIZE_RANGES.fontSizeBase),borderRadius:parseClamped(pick4(raw,"border_radius","borderRadius"),APPEARANCE_SIZE_RANGES.borderRadius),spacingUnit:parseClamped(pick4(raw,"spacing_unit","spacingUnit"),APPEARANCE_SIZE_RANGES.spacingUnit),successColor:parseColor(pick4(raw,"success_color","successColor")),successColorDark:parseColor(pick4(raw,"success_color_dark","successColorDark")),warningColor:parseColor(pick4(raw,"warning_color","warningColor")),warningColorDark:parseColor(pick4(raw,"warning_color_dark","warningColorDark")),infoColor:parseColor(pick4(raw,"info_color","infoColor")),infoColorDark:parseColor(pick4(raw,"info_color_dark","infoColorDark")),headingFontFamily:parseNonEmptyString(pick4(raw,"heading_font_family","headingFontFamily")),fontWeightBody:parseFontWeight(pick4(raw,"font_weight_body","fontWeightBody")),fontWeightHeading:parseFontWeight(pick4(raw,"font_weight_heading","fontWeightHeading")),lineHeight:parseLineHeight(pick4(raw,"line_height","lineHeight")),fontSources:parseFontSources(pick4(raw,"font_sources","fontSources")),assistantAvatarUrl:parseNonEmptyString(pick4(raw,"assistant_avatar_url","assistantAvatarUrl"))}}function parseClamped(value,range){let n=parseNumber(typeof value=="string"?value.trim().replace(/px$/i,""):value);return n===null?null:Math.min(range.max,Math.max(range.min,n))}function parseBool(value){if(typeof value=="boolean")return value;if(typeof value=="string"){let lower=value.trim().toLowerCase();if(lower==="true")return true;if(lower==="false")return false}return null}function pick4(raw,...keys){for(let key of keys)if(Object.prototype.hasOwnProperty.call(raw,key)){let value=raw[key];if(value!==void 0)return value}}function parseNonEmptyString(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}var FONT_FACE_KEYS=["regular","medium","bold","mono","monoMedium","monoBold"];function parseFaceMap(value){if(value===null||typeof value!="object"||Array.isArray(value))return null;let raw=value,out={};for(let key of FONT_FACE_KEYS){let entry=parseNonEmptyString(pick4(raw,key));entry!==null&&(out[key]=entry)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}var SURFACE_STYLES=["white","cream","subtle"],RADIUS_SCALES=["sharp","default","round"];function parseEnum(value,allowed){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return allowed.includes(lower)?lower:null}function parseBrightness(value){if(typeof value!="string")return null;let lower=value.trim().toLowerCase();return lower==="light"||lower==="dark"||lower==="auto"?lower:null}function parseNumber(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):Number.NaN;return Number.isFinite(n)&&(typeof value!="string"||value.trim().length>0)?n:null}var MAX_FONT_SCALE_FLOOR=1,MAX_FONT_SCALE_CEILING=3.1;function parseMaxFontScale(value){let n=parseNumber(value);return n===null?null:n<=0?0:Math.min(MAX_FONT_SCALE_CEILING,Math.max(MAX_FONT_SCALE_FLOOR,n))}function parseSchemaVersion(value){if(value==null)return null;let n=parseNumber(value);return n!==null&&Number.isInteger(n)&&n>=1?n:0}function toWireName(name){let trimmed=name.trim();return trimmed.startsWith(SLOT_LOCK_PREFIX)?trimmed:trimmed.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function parseLockedFields(value){if(!Array.isArray(value))return null;let out=[];for(let entry of value){if(typeof entry!="string")continue;let name=toWireName(entry);isThemeLockName(name)&&!out.includes(name)&&out.push(name)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}function hardenHttpsUrl(url){if(url===null)return null;let trimmed=url.trim();return trimmed.length===0?null:/^https:\/\/\S+$/i.test(trimmed)?trimmed:null}var BRAND_ASSET_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/brand\/[0-9a-f]{16}\.(png|jpg|webp)$/;function hardenBrandAssetUrl(url){let https=hardenHttpsUrl(url);return https!==null&&BRAND_ASSET_URL.test(https)?https:null}function withServerBranding(base,b){if(b===null||isEmptyBranding(b))return base;let palette=(b.brightness==="light"||b.brightness==="dark")&&b.brightness!==base.brightness?b.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT:base,compiled=palette.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,dark=palette.brightness==="dark",primaryIn=dark?b.primaryColorDark??darkVariantOf(b.primaryColor):b.primaryColor,accentIn=dark?b.accentColorDark??darkVariantOf(b.accentColor):b.accentColor,primaryRaw=primaryIn??palette.color.primary,accent=accentIn??palette.color.accent,keepsCompiled=primaryIn!==null&&isCompiledPrimary(b,primaryRaw,compiled,dark),primary=keepsCompiled?compiled.color.primary:primaryRaw,pr=primaryIn!==null&&!keepsCompiled?toRgba(primary):null,lift=c=>Math.round(c+(255-c)*.4),brandFamily=pr!==null?{brand:primary,bubbleUser:primary,brandInk:primary,text:{...palette.color.text,secondary:primary},brandSoft:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.10)`,brandSofter:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.15)`,brandBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.20)`,borderHairlineGreen:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.28)`,brandBorderStrong:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.55)`,composerBorder:`rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.75)`,accentEdge:`rgb(${lift(pr.r)}, ${lift(pr.g)}, ${lift(pr.b)})`}:keepsCompiled?compiledBrandFamily(compiled,palette.color.text):{},background=(dark?b.backgroundColorDark:b.backgroundColor)??null,grounds2=surfaceFamily(background),groundFamily={...palette.color,...grounds2},bodyInk=(dark?b.textColorDark:b.textColor)??null,status=(light,darkTwin)=>(dark?darkTwin??darkVariantOf(light??null):light)??null,next={brightness:palette.brightness,highContrast:palette.highContrast,meta:{displayName:b.displayName??palette.meta.displayName,logoUrl:(dark?b.logoUrlDark??b.logoUrl:b.logoUrl)??palette.meta.logoUrl,placeholder:b.placeholder??palette.meta.placeholder,hidePoweredBy:b.hidePoweredBy??palette.meta.hidePoweredBy,assistantAvatarUrl:b.assistantAvatarUrl??palette.meta.assistantAvatarUrl},color:{...palette.color,...brandFamily,...grounds2,...dangerFamily(status(b.dangerColor,b.dangerColorDark)),...successFamily(status(b.successColor,b.successColorDark),dark),...warningFamily(status(b.warningColor,b.warningColorDark),dark),...infoFamily(status(b.infoColor,b.infoColorDark),dark),...bodyInk!==null?{text:{...brandFamily.text??palette.color.text,primary:bodyInk}}:{},...surfaceOf(b.surfaceStyle??null,groundFamily),primary:primary,accent:accent,onPrimary:palette.color.onPrimary,onAccent:palette.color.onAccent},space:spaceFor(b.spacingUnit??null,palette.space,compiled),radius:b.borderRadius!=null?radiiFor(b.borderRadius,compiled):radiusOf(b.radiusScale??null,palette.radius,compiled),type:{...palette.type,...mergeFaces(palette.type,b),size:typeSizesFor(b.fontSizeBase??null,palette.type.size,compiled),maxScale:b.accessibilityMaxFontScale??palette.type.maxScale,lineHeight:lineHeightsFor(b.lineHeight??null,palette.type.lineHeight,compiled),weight:b.fontWeightBody==null?palette.type.weight:{...palette.type.weight,regular:b.fontWeightBody},headingFamily:b.headingFontFamily??palette.type.headingFamily,headingWeight:b.fontWeightHeading??palette.type.headingWeight,fontSources:b.fontSources??palette.type.fontSources},motion:palette.motion,slots:mergeThemeSlots(palette.slots,b.slots??null)};return deepFreeze(next)}var FACE_CHAIN={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},FACE_GROUPS=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function isMonoFace(face2){return face2==="mono"||face2==="monoMedium"||face2==="monoBold"}function mergeFaces(base,b){let fonts=b.fonts??{},urls=b.fontUrls??{},families={...base.families},namedFaces={...base.namedFaces},fontUrls={...base.fontUrls};for(let face2 of FONT_FACE_KEYS){let named=FACE_CHAIN[face2].map(key=>fonts[key]).find(name=>name!==void 0),legacy=isMonoFace(face2)?null:b.fontFamily;named!==void 0?(families[face2]=named,namedFaces[face2]=true):legacy!==null&&(families[face2]=legacy,namedFaces[face2]=false);let url=urls[face2]??(face2==="regular"?b.fontUrl:null)??null;url!==null?fontUrls[face2]=url:named!==void 0&&delete fontUrls[face2]}for(let group of FACE_GROUPS)for(let face2 of group)namedFaces[face2]&&group.some(other=>other!==face2&&families[other]===families[face2])&&(namedFaces[face2]=false);return{family:families.regular,mono:families.mono,fontUrl:fontUrls.regular??null,families:families,namedFaces:namedFaces,fontUrls:fontUrls}}function darkVariantOf(color){return color===null?null:deriveDarkVariant(color)}function surfaceOf(style,family){if(style===null)return{};let c=family;return{chatGround:style==="white"?c.surface:style==="subtle"?c.surfaceSubtle:c.surfaceCream}}function sameColor(a,b){return a==null?false:parseColor(a)===parseColor(b)}function isCompiledPrimary(b,primary,compiled,dark){return sameColor(primary,compiled.color.primary)?true:dark&&(b.primaryColorDark??null)===null&&sameColor(b.primaryColor,EVERFUR_LIGHT.color.primary)}function compiledBrandFamily(compiled,text3){let c=compiled.color;return{text:{...text3,secondary:c.text.secondary},brand:c.brand,bubbleUser:c.bubbleUser,brandInk:c.brandInk,brandSoft:c.brandSoft,brandSofter:c.brandSofter,brandBorder:c.brandBorder,borderHairlineGreen:c.borderHairlineGreen,brandBorderStrong:c.brandBorderStrong,composerBorder:c.composerBorder,accentEdge:c.accentEdge}}var RADIUS_FACTOR={sharp:.5,default:1,round:1.5};function radiusOf(scale,base,compiled){if(scale===null)return base;let f=RADIUS_FACTOR[scale],r=compiled.radius,s=n=>Math.round(n*f);return{tile:s(r.tile),xs:s(r.xs),sm:s(r.sm),md:s(r.md),lg:s(r.lg),xl:s(r.xl),pill:r.pill}}var DEFAULT_DISPLAY_NAME="Everfur",TEXT_SCALE_FLOOR=.5;function resolveTheme(input){return finalize(mergeLayers(input),input)}function themeAdjustments(input){let merged=mergeLayers(input);return diffThemeAdjustments(merged,finalize(merged,{...input,highContrast:false}))}function mergeLayers(input){let candidate=input?.branding??null,server=isKnownBrandingSchema(candidate)?candidate:null,client=withoutFields(input?.clientOverride??null,lockedFieldsOf(server)),device=input?.colorScheme==="dark"?"dark":"light",chosen=client?.brightness??server?.brightness??"light",withServer=withServerBranding((chosen==="auto"?device:chosen)==="dark"?EVERFUR_DARK:EVERFUR_LIGHT,withoutBrightness(server));return withServerBranding(withServer,withoutBrightness(client))}function previewTheme(input,hints,options){return resolveTheme({...options,branding:parseClientBranding(hints),clientOverride:parseClientBranding(input)})}function wireNameOf(key){return key==="placeholder"?"chat_placeholder":toWireName(key)}var LOCK_ALIASES={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family","fonts"],fontSources:["font_family","heading_font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"],backgroundColorDark:["background_color"],textColorDark:["text_color"],dangerColorDark:["danger_color"],successColorDark:["success_color"],warningColorDark:["warning_color"],infoColorDark:["info_color"],borderRadius:["radius_scale"],radiusScale:["border_radius"]};function isLocked(key,locked){return locked.has(wireNameOf(key))?true:(LOCK_ALIASES[key]??[]).some(name=>locked.has(name))}function withoutFields(b,locked){if(b===null)return null;let changed=false,out={...b};for(let key of Object.keys(b))(b[key]??null)!==null&&(isLocked(key,locked)||key==="lockedFields")&&(out[key]=null,changed=true);let slots=out.slots??null;if(slots!==null){let kept={},dropped=false;for(let name of THEME_SLOT_NAMES){let slot=slots[name];slot!==void 0&&(locked.has(`${SLOT_LOCK_PREFIX}${name}`)?dropped=true:kept[name]=slot)}dropped&&(out.slots=Object.keys(kept).length===0?null:/* @__PURE__ */Object.freeze(kept),changed=true)}if(!changed)return b;let stripped=/* @__PURE__ */Object.freeze(out);return isEmptyBranding(stripped)?null:stripped}function withoutBrightness(b){return b===null||b.brightness===null?b:/* @__PURE__ */Object.freeze({...b,brightness:null})}function scaledSizes(size,scale){if(scale===1)return size;let out={};for(let[key,value]of Object.entries(size))out[key]=Math.round(value*scale*10)/10;return out}function effectiveScale(textScale){return textScale===void 0||!Number.isFinite(textScale)?1:Math.max(TEXT_SCALE_FLOOR,textScale)}var SCALE_TIERS=["content","heading","control","compact","badge"];function tierCaps(maxScale){if(!(maxScale>0))return TEXT_SCALE_TIER_CAPS;let out={};for(let tier of SCALE_TIERS){let cap=TEXT_SCALE_TIER_CAPS[tier];out[tier]=cap===0?0:Math.min(cap,maxScale)}return out}function capped(scale,cap){return cap>0?Math.min(scale,cap):scale}function sizesByTier(size,scale,caps,scaleSizes){let out={};for(let tier of SCALE_TIERS)out[tier]=scaleSizes?scaledSizes(size,capped(scale,caps[tier])):size;return out}function registration(isFontRegistered,family){try{let answer=isFontRegistered(family);return answer===!0||answer===!1?answer:null}catch{return null}}function platformFaces(type,input){let isFontRegistered=input?.isFontRegistered,platformMono=input?.platformMonoFamily?.trim()||null;if(isFontRegistered===void 0&&platformMono===null)return{family:type.family,mono:type.mono,families:type.families,namedFaces:type.namedFaces,headingFamily:type.headingFamily};let headingFamily=type.headingFamily!==null&&isFontRegistered!==void 0&&registration(isFontRegistered,type.headingFamily)===false?null:type.headingFamily,families={...type.families},namedFaces={...type.namedFaces};for(let key of FONT_FACE_KEYS)!(families[key]===SYSTEM_FONT_FAMILY||families[key]===SYSTEM_MONO_FAMILY)&&isFontRegistered!==void 0&&registration(isFontRegistered,families[key])===false&&(families[key]=isMonoFace(key)?SYSTEM_MONO_FAMILY:SYSTEM_FONT_FAMILY,namedFaces[key]=false),platformMono!==null&&isMonoFace(key)&&families[key]===SYSTEM_MONO_FAMILY&&(families[key]=platformMono);return{family:families.regular,mono:families.mono,families:families,namedFaces:namedFaces,headingFamily:headingFamily}}function finalize(theme,input){let displayName=theme.meta.displayName.trim().length===0?DEFAULT_DISPLAY_NAME:theme.meta.displayName,logoUrl=hardenBrandAssetUrl(theme.meta.logoUrl),fontUrls={};for(let face2 of FONT_FACE_KEYS){let url=theme.type.fontUrls[face2];url!==void 0&&(fontUrls[face2]=hardenHttpsUrl(url))}let fontUrl=fontUrls.regular??null,motion=input?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:theme.motion.easing,reducedMotion:true}:theme.motion,maxScale=Number.isFinite(theme.type.maxScale)?theme.type.maxScale:DEFAULT_MAX_FONT_SCALE,scale=effectiveScale(input?.textScale),scaleCaps=tierCaps(maxScale),tierSizes=sizesByTier(theme.type.size,scale,scaleCaps,input?.scaleTypeSizes===true),color=guardInks(theme),finalized={brightness:theme.brightness,highContrast:false,meta:{displayName:displayName,logoUrl:logoUrl,placeholder:theme.meta.placeholder,hidePoweredBy:theme.meta.hidePoweredBy,assistantAvatarUrl:hardenBrandAssetUrl(theme.meta.assistantAvatarUrl)},color:color,space:theme.space,radius:theme.radius,type:{...theme.type,...platformFaces(theme.type,input),fontUrl:fontUrl,fontUrls:fontUrls,size:tierSizes.content,tierSizes:tierSizes,scale:scale,maxScale:maxScale,scaleCaps:scaleCaps},motion:motion,slots:guardSlotContrast(theme.slots,slotGrounds(color),slotSurrounds(color))};return input?.highContrast===true?deriveHighContrast(deepFreeze(finalized)):deepFreeze(finalized)}var ENTITLEMENTS_PATH="/widget/v1/entitlements",HTTP_NOT_MODIFIED=304,NOT_MODIFIED=/* @__PURE__ */Object.freeze({kind:"notModified"});async function fetchEntitlements(auth,args={},funnel=createRequestFunnel({auth:auth})){let result=await funnel.send("entitlements.fetch",buildRequest(args));return result.ok?parseUpdated(result.value):result.error.httpStatus===HTTP_NOT_MODIFIED?NOT_MODIFIED:{kind:"failed",error:result.error}}var REGION_MAX=64;function buildRequest(args){let headers={};return isFiniteNumber(args.cachedRevision)&&(headers["if-none-match"]=`"${args.cachedRevision}"`),args.region&&args.region.length<=REGION_MAX?{method:"GET",path:ENTITLEMENTS_PATH,headers:headers,query:{region:args.region}}:{method:"GET",path:ENTITLEMENTS_PATH,headers:headers}}function parseUpdated(body){if(body===null||typeof body!="object"||!isFiniteNumber(body.revision))return malformed3();let region=typeof body.region=="string"?body.region:"",ttlSeconds=isFiniteNumber(body.ttl_seconds)?body.ttl_seconds:0;/* @__PURE__ */
125
125
  return Object.freeze({kind:"updated",revision:body.revision,region:region,ttlSeconds:ttlSeconds,decisions:mapCapabilities(body.capabilities),branding:parseBranding(body),livemode:body.livemode!==false})}function parseBranding(body){let direct=parseClientBranding(body.branding);if(direct!==null)return direct;let hints=body.render_hints;if(hints!==null&&typeof hints=="object"){let nested=parseClientBranding(hints.branding);return nested!==null?nested:parseClientBranding(hints)}return null}function mapCapabilities(capabilities){if(capabilities===null||typeof capabilities!="object")/* @__PURE__ */return Object.freeze([]);let out=[];for(let[resource,value]of Object.entries(capabilities))isEnabled(value)&&out.push(/* @__PURE__ */Object.freeze({resource:resource,granted:true}));/* @__PURE__ */
126
126
  return Object.freeze(out)}function isEnabled(value){return typeof value=="object"&&value!==null&&value.enabled===true}function malformed3(){return{kind:"failed",error:makeEverfurError("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}var MIN_POLL_INTERVAL_SECONDS=30;function createEntitlementPoller(deps){let scheduler=deps.scheduler??defaultScheduler,resolve=deps.resolve??fetchEntitlements,floorSeconds=Math.max(1,deps.floorSeconds??MIN_POLL_INTERVAL_SECONDS),rng=deps.rng??Math.random,jitteredFloorSeconds=()=>floorSeconds+rng()*floorSeconds,started=false,stopped=false,timer=null,cachedRevision=null,lastCadenceSeconds=floorSeconds,generation=0,clearTimer=()=>{timer!==null&&(scheduler.clear(timer),timer=null)},schedule=seconds=>{stopped||!started||(lastCadenceSeconds=Math.max(floorSeconds,seconds),timer=scheduler.set(()=>{timer=null,run()},lastCadenceSeconds*1e3))},inFlight3=null,tick=async()=>{if(stopped)return null;let myGen=generation;deps.onFetch?.();let args=deps.region?{cachedRevision:cachedRevision,region:deps.region}:{cachedRevision:cachedRevision},resolution;try{resolution=await resolve(deps.authFor(),args)}catch(cause){return deps.telemetry?.track("sdk.entitlements.poll_error",{reason:describe(cause)}),!stopped&&myGen===generation&&(deps.onSettled?.(),schedule(jitteredFloorSeconds())),null}if(stopped||myGen!==generation)return null;switch(resolution.kind){case"updated":cachedRevision=resolution.revision,deps.update(resolution.decisions,resolution.branding??null,resolution.livemode!==false),schedule(resolution.ttlSeconds);break;case"notModified":schedule(lastCadenceSeconds);break;case"failed":deps.telemetry?.track("sdk.entitlements.poll_failed",{code:resolution.error.code}),schedule(jitteredFloorSeconds());break;default:schedule(jitteredFloorSeconds())}return deps.onSettled?.(),resolution},run=()=>{let current=tick().finally(()=>{inFlight3===current&&(inFlight3=null)});return inFlight3=current,current};return{start(){started||stopped||(started=true,run())},prime(){return stopped?Promise.resolve(null):inFlight3??run()},stop(){stopped||(stopped=true,generation++,clearTimer())},refresh(){stopped||!started||(generation++,cachedRevision=null,clearTimer(),run())}}}var defaultScheduler={set(callback,ms){let handle=setTimeout(callback,ms);return handle.unref?.(),handle},clear(handle){clearTimeout(handle)}};function describe(cause){return cause instanceof Error?cause.message:"poll failed"}var NOTIFICATIONS_DEVICE_KV_KEY="everfur.notifications.device";var LOGOUT_HOOK_BUDGET_MS=3e3,PER_USER_KV_KEYS=/* @__PURE__ */Object.freeze([NOTIFICATIONS_DEVICE_KV_KEY]);function startBeforeLogoutHooks(deps){let{leaving:leaving,identity:identity,hooks:hooks,telemetry:telemetry}=deps;if(leaving===null||identity===null||hooks.size===0)return null;let context=/* @__PURE__ */Object.freeze({userRef:leaving.userRef,auth:deps.graceAuth()}),runs=[...hooks].map(hook=>{try{return Promise.resolve(hook(context))}catch(cause){return Promise.reject(cause)}}),report=(reason,count2)=>{try{telemetry.track("sdk.logout.hookFailed",{reason:reason,count:count2,totalCount:runs.length})}catch{}},settled=Promise.allSettled(runs).then(outcomes=>{let failed=outcomes.filter(outcome=>outcome.status==="rejected").length;failed>0&&report("failed",failed)});return new Promise(resolve=>{let done=false,finish=()=>{done||(done=true,clearTimeout(timer),resolve())},timer=setTimeout(()=>{done||report("timeout",runs.length),finish()},LOGOUT_HOOK_BUDGET_MS);settled.then(finish,finish)})}function graceAuth(deps){let{leaving:leaving,identity:identity,transport:transport,sessionId:sessionId}=deps,token=identity.currentToken();token.catch(()=>{});let frozen={userRef:leaving.userRef,currentToken:()=>token,hasToken:()=>true,clear:()=>{}};return{mode:"personalized",transport:transport,identity:frozen,userRef:leaving.userRef,sessionId:sessionId}}async function sweepPerUserKv(kv,telemetry){if(PER_USER_KV_KEYS.length===0)return;let results=await Promise.allSettled(PER_USER_KV_KEYS.map(key=>kv.removeItem(key))),failedCount=results.filter(result=>result.status==="rejected").length;failedCount>0&&telemetry.track("sdk.logout.sweepPartialFailure",{failedCount:failedCount,totalCount:results.length})}function compiledDefaultDecisions(){/* @__PURE__ */
127
127
  return Object.freeze([/* @__PURE__ */Object.freeze({resource:"chat.message.create",granted:true})])}function createEntitlementStore(floorDecisions=compiledDefaultDecisions){let listeners2=/* @__PURE__ */new Set,snapshot=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit=()=>{for(let listener of listeners2)listener()};return{subscribe(listener){return listeners2.add(listener),()=>{listeners2.delete(listener)}},getSnapshot(){return snapshot},set(next){snapshot=/* @__PURE__ */Object.freeze({decisions:/* @__PURE__ */Object.freeze([...next.decisions]),isPending:next.isPending,branding:next.branding??null,...next.livemode===false?{livemode:false}:{}}),emit()},reset(){snapshot=/* @__PURE__ */Object.freeze({decisions:floorDecisions(),isPending:false,branding:null}),emit()},setPending(pending){snapshot.isPending!==pending&&(snapshot=/* @__PURE__ */Object.freeze({...snapshot,isPending:pending}),emit())}}}function notConfiguredError(failure2){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`})}function tryResolveClient(cfg,platform){let clientCfg={publishableKey:cfg.publishableKey,...cfg.apiBaseUrl!==void 0?{apiBaseUrl:cfg.apiBaseUrl}:{},...cfg.contractVersion!==void 0?{contractVersion:cfg.contractVersion}:{},...cfg.debug!==void 0?{debug:cfg.debug}:{}};return tryResolveClientConfig(clientCfg,platform===void 0?void 0:{platform:platform})}function guardTelemetry(port){/* @__PURE__ */
128
128
  return Object.freeze({track(event,props){try{port.track(event,props)}catch{}},trackExpectedFailure(code,props){try{port.trackExpectedFailure(code,props)}catch{}}})}var ENV_HINT=/* @__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 ${ENV_API_BASE_URL} to the SDK at run time (bundlers inline only the variables your own code names), so pass apiBaseUrl in config.`});function reportConfigFailure(failure2,telemetry,platform=SDK_PLATFORM){try{telemetry.trackExpectedFailure("sdk.config.invalid",{reason:failure2.reason})}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${failure2.message}\n[everfur] Every Everfur capability will render its off-state until this is fixed. `+ENV_HINT[platform])}function refusingTransport(failure2){/* @__PURE__ */
129
129
  return Object.freeze({request(){return Promise.resolve(err(notConfiguredError(failure2)))},stream(_req,signal){let frame=errorFrame({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${failure2.message}`,synthesized:true,lastEventId:null});return{async*[Symbol.asyncIterator](){signal.aborted||(yield frame)}}}})}function createInMemoryKv(){let map=/* @__PURE__ */new Map;return{async getItem(key){return map.get(key)??null},async setItem(key,value){map.set(key,value)},async removeItem(key){map.delete(key)},async keys(prefix){return[...map.keys()].filter(k=>k.startsWith(prefix))}}}var noopImageCache=/* @__PURE__ */Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function createEverfurRuntime(input,opts){return new EverfurRuntimeImpl(input,opts)}var TOKEN_REFRESH_SKEW_MS=6e4,EverfurRuntimeImpl=class{constructor(input,opts){this.sessionId=newSessionId();this.entries=/* @__PURE__ */new Map;this.destroyers=/* @__PURE__ */new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=/* @__PURE__ */new WeakMap;this.prepared=null;this.beforeLogoutHooks=/* @__PURE__ */new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let cfg=input.config;if(cfg.secureStore!==void 0&&cfg.secureStore.isAvailable===true)throw new EverfurConfigError("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.telemetry=cfg.telemetry?guardTelemetry(cfg.telemetry):noopTelemetry;let publishableKey=typeof cfg?.publishableKey=="string"?cfg.publishableKey.trim():"",failure2=checkPublishableKey(cfg?.publishableKey),transportInjected=cfg.transport!==void 0,resolvedTransport,resolvedApiBaseUrl=typeof cfg.apiBaseUrl=="string"&&cfg.apiBaseUrl.trim().length>0?cfg.apiBaseUrl.trim():null;if(failure2!==null)resolvedTransport=refusingTransport(failure2);else if(cfg.transport!==void 0)resolvedTransport=cfg.transport;else{let resolved=tryResolveClient(cfg,opts?.platform);resolved.ok?(resolvedApiBaseUrl=resolved.config.apiBaseUrl,resolvedTransport=createHttpTransport({config:resolved.config,...opts?.eventSourceFactory?{eventSourceFactory:opts.eventSourceFactory}:{}})):(failure2=resolved.failure,resolvedTransport=refusingTransport(resolved.failure))}this.configFailure=failure2,this.publishableKey=failure2===null?publishableKey:"",this.mintScope=`${this.publishableKey}|${resolvedApiBaseUrl??""}`,setPetRegistrationTenant(this,this.mintScope),this.transport=resolvedTransport,failure2!==null&&reportConfigFailure(failure2,this.telemetry,opts?.platform),this.errorPolicy=cfg.errorPolicy,this.camera=cfg.camera??unavailableCamera,this.upload=cfg.upload??unavailableUpload,this.uploadTransport=cfg.uploadTransport??unavailableUploadTransport,this.imageCache=cfg.imageCache??noopImageCache,this.kv=cfg.storage??createInMemoryKv(),this.currentUser=input.user??null,this.identity=this.buildIdentity(input.user??null),this.activePet=input.activePet,this.store=failure2===null?createEntitlementStore():createEntitlementStore(()=>deniedDecisionsFor("sdk_config",userFacingError("accessDenied"))),this.services={authFor:userRef2=>this.buildAuth(userRef2),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:resolvedApiBaseUrl},this.registry={services:this.services,acquireChat:scope=>this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat),releaseChat:controller=>this.releaseInternal(controller),peekChat:scope=>this.entries.get(`${this.epoch}|chat|${chatScopeKey(scope)}`)?.controller??null,acquire:(kind,scopeKey,create,destroy)=>this.acquireInternal(kind,scopeKey,create,destroy),release:controller=>this.releaseInternal(controller)},this.entitlements=this.store;let shouldPoll=failure2===null&&(opts?.startEntitlementPolling??!transportInjected);this.poller=failure2===null?this.buildPoller(opts?.pollScheduler):null,shouldPoll&&this.poller?.start()}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(user){if(user===null)return null;let getToken=sharedTokenProvider(`${this.mintScope}|${user.userRef}`,user.getToken),identity=createIdentityProvider(user.userRef,getToken,expiresAtMs=>this.armTokenRefresh(identity,expiresAtMs));return identity}armTokenRefresh(identity,expiresAtMs){if(this.clearTokenRefresh(),expiresAtMs===null||this.disposed||identity!==this.identity)return;let remaining=expiresAtMs-Date.now();if(remaining<=0)return;let delay=Math.max(remaining-TOKEN_REFRESH_SKEW_MS,remaining/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||identity!==this.identity)&&identity.currentToken({forceRefresh:true}).catch(()=>{})},delay),this.refreshTimer.unref?.()}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null}buildPoller(scheduler){return createEntitlementPoller({authFor:()=>this.buildAuth(this.currentUser?.userRef??null),update:(decisions,branding,livemode)=>this.updateEntitlements({decisions:decisions,isPending:false,branding:branding,...livemode===false?{livemode:livemode}:{}}),onFetch:()=>{this.verdictSettled||this.store.setPending(true)},onSettled:()=>{this.verdictSettled=true,this.store.setPending(false)},telemetry:this.telemetry,...scheduler?{scheduler:scheduler}:{}})}acquireInternal(kind,scopeKey,create,destroy,warm=false){let key=`${this.epoch}|${kind}|${scopeKey}`,existing=this.entries.get(key);if(existing)return warm||(existing.warm?existing.warm=false:existing.refCount+=1),existing.controller;let controller=create();return this.entries.set(key,{controller:controller,refCount:1,warm:warm}),this.destroyers.set(controller,destroy),controller}releaseInternal(controller){for(let[key,entry]of this.entries)if(entry.controller===controller){entry.refCount-=1,entry.refCount<=0&&(this.runDestroyer(controller),this.entries.delete(key));return}}runDestroyer(controller){let destroy=this.destroyers.get(controller);this.destroyers.delete(controller),destroy&&destroy(controller)}buildChatController(scope){let controller=createChatController({auth:this.buildAuth(scope.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:scope.conversationId,petRef:scope.petRef});return this.runBootstrap(controller,scope),controller}runBootstrap(controller,scope){let input={};scope.petRef!==null&&(input.petRef=scope.petRef),scope.conversationId!==null&&(input.resumeConversationId=scope.conversationId);let boot=bootstrapChat(input,{controller:controller});return boot.then(result=>controller.adoptPrompts(result.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(controller,boot),boot}buildAuth(scopeUserRef){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:scopeUserRef,sessionId:this.sessionId}}setUser(user){if(this.disposed)return;let nextRef=user?.userRef??null,currentRef=this.currentUser?.userRef??null;if(nextRef===currentRef){this.currentUser=user,user&&this.identity===null&&(this.identity=this.buildIdentity(user));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=user,this.identity=this.buildIdentity(user),this.rescopeAll()}async logout(){if(this.disposed)return;let wasAnonymous=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=newSessionId(),this.setUser(null),this.leavingSessionId=null,wasAnonymous&&this.rescopeAll();let pending=this.pendingBeforeLogout;this.pendingBeforeLogout=null,pending!==null&&await pending,await sweepPerUserKv(this.kv,this.telemetry)}onBeforeLogout(hook){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(hook),()=>{this.beforeLogoutHooks.delete(hook)})}beforeLogoutSettlement(){let leaving=this.currentUser,identity=this.identity;return startBeforeLogoutHooks({leaving:leaving,identity:identity,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:()=>graceAuth({leaving:leaving,identity:identity,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId})})}async registerPet(pet,profile){return this.withPets("registerPet",(repo,auth)=>sharedPetRegistration(petRegistrationKey(this,auth,pet,profile),()=>profile===void 0?repo.registerPet(pet):repo.registerPet(pet,profile)))}updatePet(pet,patch){return this.withPets("updatePet",repo=>repo.updatePet(pet,patch))}deletePet(pet){return this.withPets("deletePet",repo=>repo.deletePet(pet))}eraseUserData(){return this.withPets("eraseUserData",repo=>repo.eraseUserData())}async withPets(verb,run){if(this.disposed)return err(disposedError(verb));let auth=this.buildAuth(this.currentUser?.userRef??null),result=await run(createPetsRepository(auth),auth);return result.ok&&!this.disposed&&notifyPetsChanged(this),result}prepare(opts){let petRef2=opts?.petRef??null,key=`${this.epoch}|${this.currentUser?.userRef??""}|${petRef2??""}`,current=this.prepared;if(current!==null&&current.key===key&&(current.result===null||current.result.status==="ready"))return current.promise;let entry={key:key,result:null,promise:this.runPrepare(petRef2).then(result=>(entry.result=result,result))};return this.prepared=entry,entry.promise}async runPrepare(petRef2){let startedAt=Date.now(),failure2=this.configFailure,refused=this.disposed?disposedError("prepare"):failure2===null?null:notConfiguredError(failure2),identity=this.identity,[session,entitlements,chat]=await Promise.all([refused?err(refused):identity===null?ok(void 0):identity.currentToken().then(()=>ok(void 0),()=>err(makeEverfurError("authRejected",{retryable:false}))),refused?err(refused):this.primeEntitlements(),petRef2===null?void 0:refused?err(refused):this.primeChat(petRef2)]),status=session.ok?entitlements.ok&&(chat?.ok??true)?"ready":"partial":"failed",durationMs=Date.now()-startedAt;try{this.telemetry.track("sdk.prepare.timing",{durationMs:durationMs,status:status})}catch{}/* @__PURE__ */
130
130
  return Object.freeze({status:status,durationMs:durationMs,session:session,entitlements:entitlements,...chat?{chat:chat}:{}})}async primeEntitlements(){let resolution=await(this.poller?.prime());return resolution?resolution.kind==="failed"?err(resolution.error):ok(void 0):err(makeEverfurError("internalError",{retryable:true}))}async primeChat(petRef2){let scope={userRef:this.currentUser?.userRef??null,petRef:petRef2,conversationId:null},controller=this.acquireInternal("chat",chatScopeKey(scope),()=>this.buildChatController(scope),disposeChat,true),result=await this.bootstraps.get(controller);return result?.cause&&controller.getSnapshot().conversationId===null&&(result=await this.runBootstrap(controller,scope)),result?.cause?err(result.cause):ok(void 0)}setActivePet(pet){if(this.disposed)return;let next=pet??null;next!==this.activePet&&(this.activePet=next,this.rescopeAll())}updateEntitlements(next){this.disposed||this.configFailure===null&&this.store.set(next)}open(capability){this.telemetry.track("sdk.open",{capability:capability})}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers())}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh()}disposeAllControllers(){for(let entry of this.entries.values())this.runDestroyer(entry.controller);this.entries.clear(),this.destroyers.clear()}};function chatScopeKey(scope){return`${scope.userRef??""}|${scope.petRef??""}|${scope.conversationId??""}`}function disposeChat(controller){controller.dispose()}function disposedError(verb){return makeEverfurError("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}function useEverfur(){return useEverfurContext().handle}var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function EverfurThemeProviderCore(props){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot),scheme=props.seams.useColorScheme(),reducedMotion=props.seams.useReducedMotion(),textScale=props.seams.useTextScale(),highContrast=props.seams.useHighContrast(),scaleTypeSizes=props.seams.scaleTypeSizes,platformMonoFamily=props.seams.platformMonoFamily?.(),isFontRegistered=props.seams.isFontRegistered,clientKey=props.clientTheme?stableKey2(props.clientTheme):"",clientOverride=react.useMemo(()=>props.clientTheme?parseClientBranding(props.clientTheme):null,[clientKey]),serverBranding=snapshot.branding??null,theme=react.useMemo(()=>resolveTheme({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme,reducedMotion:reducedMotion,textScale:textScale,scaleTypeSizes:scaleTypeSizes,highContrast:highContrast,...platformMonoFamily===void 0?{}:{platformMonoFamily:platformMonoFamily},...isFontRegistered===void 0?{}:{isFontRegistered:isFontRegistered}}),[serverBranding,clientOverride,scheme,reducedMotion,textScale,scaleTypeSizes,highContrast,platformMonoFamily,isFontRegistered]);props.seams.useResolvedTheme?.(theme);let isDevelopment=props.seams.isDevelopment;return react.useEffect(()=>{isDevelopment===void 0||!safeDevelopment(isDevelopment)||warnThemeAdjustments(themeAdjustments({branding:serverBranding,clientOverride:clientOverride,colorScheme:scheme}))},[isDevelopment,serverBranding,clientOverride,scheme]),react.createElement(EverfurThemeContext.Provider,{value:theme},props.children)}function stableKey2(input){try{return JSON.stringify(input)}catch{return Object.keys(input).join("&")}}function safeDevelopment(isDevelopment){try{return isDevelopment()===!0}catch{return false}}function EverfurProviderCore(props){let{config:config,user:user,activePet:activePet,theme:theme,warmUp:warmUp,children:children,seams:seams}=props,configKey=`${config?.publishableKey??""}|${config?.apiBaseUrl??""}|${config?.contractVersion??""}`,runtimeRef=react.useRef(null),supersededRef=react.useRef(null),[renderTick,scheduleRender]=react.useReducer(n=>n+1,0),imperativeUserRef=react.useRef(null),lastPropUserRef=react.useRef(void 0),propUserRefKey=user?.userRef??null;lastPropUserRef.current!==propUserRefKey&&(lastPropUserRef.current!==void 0&&(imperativeUserRef.current=null),lastPropUserRef.current=propUserRefKey);let effectiveUser=imperativeUserRef.current!==null?imperativeUserRef.current.user:user??null,imperativePetRef=react.useRef(null),lastPropPetRef=react.useRef(void 0),propPetRef=activePet??null;lastPropPetRef.current!==propPetRef&&(lastPropPetRef.current!==void 0&&(imperativePetRef.current=null),lastPropPetRef.current=propPetRef);let effectivePet=imperativePetRef.current!==null?imperativePetRef.current.pet:activePet??null;(runtimeRef.current===null||runtimeRef.current.key!==configKey||runtimeRef.current.runtime.isDisposed)&&(runtimeRef.current!==null&&!runtimeRef.current.runtime.isDisposed&&(supersededRef.current=runtimeRef.current.runtime),runtimeRef.current={key:configKey,runtime:createEverfurRuntime({config:seams.withDefaults?seams.withDefaults(config):config,user:effectiveUser,activePet:effectivePet,theme:theme??null},{platform:seams.platform,...seams.eventSourceFactory?{eventSourceFactory:seams.eventSourceFactory}:{}})});let runtime=runtimeRef.current.runtime,bumpedForRef=react.useRef(null);react.useEffect(()=>{let current=runtimeRef.current?.runtime;current===void 0||!current.isDisposed||bumpedForRef.current!==current&&(bumpedForRef.current=current,scheduleRender())}),react.useEffect(()=>{let superseded=supersededRef.current;superseded!==null&&(supersededRef.current=null,superseded.dispose())});let userRefKey=effectiveUser?.userRef??null;react.useLayoutEffect(()=>{runtime.setUser(effectiveUser)},[runtime,userRefKey]),react.useLayoutEffect(()=>{runtime.setActivePet(effectivePet)},[runtime,effectivePet]),react.useEffect(()=>()=>runtime.dispose(),[runtime]),react.useEffect(()=>{warmUp==="onMount"&&runtime.prepare(effectivePet===null?{}:{petRef:effectivePet})},[runtime,warmUp,userRefKey,effectivePet]);let handle=react.useMemo(()=>({setUser:u=>{imperativeUserRef.current={user:u},runtime.setUser(u),scheduleRender()},setActivePet:p=>{imperativePetRef.current={pet:p},runtime.setActivePet(p),scheduleRender()},open:c=>runtime.open(c),prepare:opts=>runtime.prepare(opts),registerPet:(pet,profile)=>runtime.registerPet(pet,profile),updatePet:(pet,patch)=>runtime.updatePet(pet,patch),deletePet:pet=>runtime.deletePet(pet),eraseUserData:()=>runtime.eraseUserData(),logout:()=>{imperativeUserRef.current={user:null};let settled=runtime.logout();return scheduleRender(),settled}}),[runtime,scheduleRender]),value=react.useMemo(()=>({runtime:runtime,handle:handle,userRef:userRefKey,activePet:effectivePet,scopeEpoch:runtime.scopeEpoch}),[runtime,handle,userRefKey,effectivePet,renderTick]),themed=react.createElement(EverfurThemeProviderCore,{clientTheme:theme??null,seams:seams.theme,children:children});return react.createElement(EverfurContext.Provider,{value:value},seams.wrap?seams.wrap(themed):themed)}var NAMESPACE="everfur:";function storage(){try{if(typeof window>"u")return null;let store=window.localStorage;return store&&typeof store.getItem=="function"?store:null}catch{return null}}function createLocalStorageKv(){return{async getItem(key){try{return storage()?.getItem(NAMESPACE+key)??null}catch{return null}},async setItem(key,value){try{storage()?.setItem(NAMESPACE+key,value)}catch{}},async removeItem(key){try{storage()?.removeItem(NAMESPACE+key)}catch{}},async keys(prefix){try{let store=storage();if(store===null)return[];let out=[],wanted=NAMESPACE+prefix;for(let index=0;index<store.length;index+=1){let key=store.key(index);key!==null&&key.startsWith(wanted)&&out.push(key.slice(NAMESPACE.length))}/* @__PURE__ */
131
- return Object.freeze(out)}catch{return[]}}}}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function tierScale(theme,tier){let{scale:scale,scaleCaps:scaleCaps}=theme.type,cap=scaleCaps[tier];return cap>0?Math.min(scale,cap):scale}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face2=>(fonts.add(face2),!0)).catch(()=>!1)}catch{}loads.set(key,load)}return load}var FACES=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;react.useEffect(()=>{for(let face2 of FACES){let url=fontUrls[face2];url!=null&&loadBrandFont(families[face2],url,namedFaces[face2]?weight.regular:weight[FACE_WEIGHT[face2]])}},[families,fontUrls,weight,namedFaces])}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return react.useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return react.useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return react.useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return react.useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});function withWebDefaults(config){return config.storage===void 0?{...config,storage:createLocalStorageKv()}:config}var webSeams=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:withWebDefaults,theme:webThemeSeams});function EverfurProvider(props){return react.createElement(EverfurProviderCore,{...props,seams:webSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return react.useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}function tierPx(theme,tier,points){return Math.round(points*tierScale(theme,tier)*10)/10}var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style,className:className}=props,decision=useCapability(capability),view=react.useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style,className:className})}):/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
131
+ return Object.freeze(out)}catch{return[]}}}}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function tierScale(theme,tier){let{scale:scale,scaleCaps:scaleCaps}=theme.type,cap=scaleCaps[tier];return cap>0?Math.min(scale,cap):scale}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base=face(theme,fallback);return base.fontWeight===void 0||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var loads=/* @__PURE__ */new Map,warned2=/* @__PURE__ */new Set,useBeforePaintEffect=typeof document>"u"?react.useEffect:react.useLayoutEffect;function keyOf(source){return source.cssSrc!==void 0?`css\n${source.cssSrc}`:`file\n${source.family}\n${source.src??""}\n${source.weight??"400"}\n${source.style??"normal"}`}function warnOnce(source,warn){if(!warn)return;let url=source.cssSrc??source.src??"",message=`[everfur] A font in appearance.fonts did not load: "${source.family}" from ${url}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(source.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!warned2.has(message)){warned2.add(message);try{globalThis.console?.warn?.(message)}catch{}}}function existingLink(href){let links=document.getElementsByTagName("link");for(let index=0;index<links.length;index+=1){let link=links[index];if(link.rel==="stylesheet"&&link.getAttribute("href")===href)return link}return null}function loadStylesheet(href){return existingLink(href)!==null?Promise.resolve(true):new Promise(resolve=>{let link=document.createElement("link");link.rel="stylesheet",link.href=href,link.setAttribute("data-everfur-font",""),link.addEventListener("load",()=>resolve(true)),link.addEventListener("error",()=>resolve(false)),document.head.appendChild(link)})}function loadFile(source){let fonts=document.fonts;return new FontFace(source.family,`url("${source.src}")`,{display:"swap",weight:source.weight??"400",style:source.style??"normal"}).load().then(face2=>(fonts.add(face2),true)).catch(()=>false)}function loadFontSource(source,warn=false){let key=keyOf(source),load=loads.get(key);if(load===void 0){load=Promise.resolve(false);try{if(typeof document<"u"){let css=source.cssSrc===void 0?null:fontSourceUrl(source.cssSrc),src=source.src===void 0?null:fontSourceUrl(source.src);css!==null?load=loadStylesheet(css):src!==null&&(load=loadFile({...source,src:src}))}}catch{load=Promise.resolve(false)}let settled=load.then(ok3=>(ok3||warnOnce(source,warn),ok3));loads.set(key,settled),load=settled}return load}function useFontSources(theme,isDevelopment){let sources=theme.type.fontSources;useBeforePaintEffect(()=>{if(sources.length===0)return;let warn=false;try{warn=isDevelopment()}catch{}for(let source of sources)loadFontSource(source,warn)},[sources,isDevelopment])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads2=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads2.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face2=>(fonts.add(face2),!0)).catch(()=>!1)}catch{}loads2.set(key,load)}return load}var FACES=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;react.useEffect(()=>{for(let face2 of FACES){let url=fontUrls[face2];url!=null&&loadBrandFont(families[face2],url,namedFaces[face2]?weight.regular:weight[FACE_WEIGHT[face2]])}},[families,fontUrls,weight,namedFaces]),useFontSources(theme,isWebDevelopment)}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument2=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument2?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return react.useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return react.useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return react.useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return react.useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});function withWebDefaults(config){return config.storage===void 0?{...config,storage:createLocalStorageKv()}:config}var webSeams=/* @__PURE__ */Object.freeze({platform:"web",withDefaults:withWebDefaults,theme:webThemeSeams});function EverfurProvider(props){return react.createElement(EverfurProviderCore,{...props,seams:webSeams})}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return react.useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}function tierPx(theme,tier,points){return Math.round(points*tierScale(theme,tier)*10)/10}var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function headingFaceCss(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type,base=faceCss(theme,fallback);return headingFamily===null&&headingWeight===null?base:headingFamily!==null?{fontFamily:cssFontFamily(headingFamily),fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]}:theme.type.namedFaces[fallback]||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style,className:className}=props,decision=useCapability(capability),view=react.useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style,className:className})}):/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
132
132
  return jsxRuntime.jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${capability}`,className:className,style:{...styles.offstate,...style},children:/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.skeletonBar})})}function OffState({decision:decision,style:style,className:className}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
133
133
  return jsxRuntime.jsx("div",{className:className,style:{...styles.offstate,...style},children:message.length>0?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{offstate:{...SURFACE_ROOT_RESET,boxSizing:"border-box",minHeight:MIN_OFFSTATE_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${space.md}px ${space.lg}px`,backgroundColor:color.surfaceCream,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`},offstateText:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.body,lineHeight:`${Math.round(type.size.body*type.lineHeight.normal)}px`,color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}}}var CHAT_COPY=/* @__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",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",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",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",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",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 fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";var FEEDBACK_REASONS=/* @__PURE__ */Object.freeze([
134
134
  /* @__PURE__ */Object.freeze({key:"inaccurate",label:CHAT_COPY.feedbackReasonInaccurate,feedbackType:"wrong"}),
@@ -140,7 +140,7 @@ return jsxRuntime.jsx("div",{className:className,style:{...styles.offstate,...st
140
140
  /* @__PURE__ */Object.freeze({sentiment:"neutral",label:CHAT_COPY.feedbackNeutral}),
141
141
  /* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}var BOOTSTRAP_SNAPSHOT=/* @__PURE__ */Object.freeze({status:"idle",messages:/* @__PURE__ */Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:/* @__PURE__ */Object.freeze([]),unreadCount:null});function useEverfurChat(opts){let{runtime:runtime,userRef:userRef2,activePet:activePet,scopeEpoch:scopeEpoch}=useEverfurContext(),petRef2=opts?.petRef??activePet??null,conversationId2=opts?.conversationId??null,scope=react.useMemo(()=>({runtime:runtime,userRef:userRef2,petRef:petRef2,conversationId:conversationId2,scopeEpoch:scopeEpoch}),[runtime,userRef2,petRef2,conversationId2,scopeEpoch]),[binding,setBinding]=react.useState(null),controller=binding?.scope===scope?binding.controller:runtime.registry.peekChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2}),active=react.useRef(null);react.useEffect(()=>{let acquired=runtime.registry.acquireChat({userRef:userRef2,petRef:petRef2,conversationId:conversationId2});return active.current=acquired,setBinding({scope:scope,controller:acquired}),()=>{active.current=null,setBinding(current=>current?.controller===acquired?null:current),runtime.registry.releaseChat(acquired)}},[runtime,userRef2,petRef2,conversationId2,scopeEpoch,scope]);let subscribe=react.useCallback(onChange=>controller?controller.subscribe(onChange):NOOP_UNSUBSCRIBE,[controller]),getSnapshot=react.useCallback(()=>controller?controller.getSnapshot():BOOTSTRAP_SNAPSHOT,[controller]),snapshot=react.useSyncExternalStore(subscribe,getSnapshot,getSnapshot),send=react.useCallback((text3,opts2)=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.send(text3,opts2?.imageS3Keys===void 0?{}:{imageS3Keys:opts2.imageS3Keys}),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),askEverfur=react.useCallback(prompt=>controller&&active.current===controller&&!controller.getSnapshot().isBootstrapping?driveToResult(controller,controller.askEverfur(prompt),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),retryLast=react.useCallback(()=>controller&&active.current===controller?driveToResult(controller,controller.retryLast(),()=>active.current===controller):Promise.resolve(notReadyError()),[controller]),stop=react.useCallback(()=>{controller&&active.current===controller&&controller.stop()},[controller]),newConversation=react.useCallback(()=>{controller&&active.current===controller&&controller.newConversation()},[controller]),[ratings,setRatings]=react.useState({controller:null,byMessage:{}}),sentimentByMessage=ratings.controller===controller?ratings.byMessage:EMPTY_RATINGS,feedback=react.useCallback(async(responseId,sentiment,reason,notes)=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let key=String(responseId),previous=ratings.controller===controller?ratings.byMessage[key]:void 0;if(previous===sentiment&&reason==null)return setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return delete rest[key],{controller:controller,byMessage:rest}}),ok(/* @__PURE__ */Object.freeze({feedbackId:""}));setRatings(current=>({controller:controller,byMessage:{...current.controller===controller?current.byMessage:{},[key]:sentiment}}));let result=await controller.submitFeedback(responseId,feedbackTypeFor(sentiment,reason??null),notes??null);return active.current!==controller?err(makeEverfurError("accessDenied")):(result.ok||setRatings(current=>{let rest={...current.controller===controller?current.byMessage:{}};return previous===void 0?delete rest[key]:rest[key]=previous,{controller:controller,byMessage:rest}}),result)},[controller,ratings]),history=react.useMemo(()=>{let run=async operation=>{if(!controller||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation(controller);return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{listConversations:options=>run(current=>current.listConversations({...petRef2?{petRef:petRef2}:{},...options})),getMessages:(id,options)=>run(current=>current.getMessages(id,options)),resumeConversation:id=>run(current=>current.resumeConversation(id)),loadOlderMessages:()=>run(current=>current.loadOlderMessages()),markRead:()=>run(current=>current.markRead()),refreshActiveThread:()=>run(current=>current.refreshActiveThread()),answerCheckin:(caseId,answer)=>run(current=>current.answerCheckin(caseId,answer)),openCheckin:target=>run(current=>current.openCheckin(target))}},[controller,petRef2]);return react.useMemo(()=>({status:snapshot.status,messages:snapshot.messages,conversationId:snapshot.conversationId,petRef:petRef2,error:snapshot.error,isStreaming:snapshot.isStreaming,isBootstrapping:snapshot.isBootstrapping,historyCursor:snapshot.historyCursor??null,isLoadingHistory:snapshot.isLoadingHistory??false,stopped:snapshot.stopped??false,reconnecting:snapshot.reconnecting??false,...history,suggestedPrompts:snapshot.suggestedPrompts,unreadCount:snapshot.unreadCount,hasUnreadThreads:snapshot.hasUnreadThreads??false,newConversation:newConversation,sentimentByMessage:sentimentByMessage,feedback:feedback,send:send,askEverfur:askEverfur,retryLast:retryLast,stop:stop}),[snapshot,petRef2,send,askEverfur,retryLast,stop,history,newConversation,sentimentByMessage,feedback])}var NOOP_UNSUBSCRIBE=()=>{},EMPTY_RATINGS=/* @__PURE__ */Object.freeze({});async function driveToResult(controller,iterable,current){for await(let _frame of iterable);if(!current())return err(makeEverfurError("accessDenied"));let snapshot=controller.getSnapshot();return snapshot.status==="error"&&snapshot.error!==null?err(snapshot.error):ok(lastAssistantResponseId(snapshot.messages))}function lastAssistantResponseId(messages){for(let i=messages.length-1;i>=0;i-=1){let message=messages[i];if(message&&message.role==="assistant"&&message.responseId!==void 0)return message.responseId}return null}function notReadyError(){return err(makeEverfurError("internalError",{retryable:true}))}function attachmentErrorMessage(error){switch(error.code){case"too_large":return fillCopy(CHAT_COPY.attachmentTooLarge,{max:formatBytes(MAX_ATTACHMENT_BYTES),filename:error.filename,size:formatBytes(error.sizeBytes??0)});case"too_many":return fillCopy(CHAT_COPY.attachmentTooMany,{max:MAX_ATTACHMENTS_PER_MESSAGE});case"unsupported_type":return fillCopy(CHAT_COPY.attachmentUnsupported,{filename:error.filename});case"network":return CHAT_COPY.attachmentNetwork;case"server":return fillCopy(CHAT_COPY.attachmentServer,{status:error.httpStatus?` (${error.httpStatus})`:""});case"cancelled":return CHAT_COPY.attachmentCancelled;case"rate_limited":return CHAT_COPY.attachmentRateLimited;case"quota_exceeded":return CHAT_COPY.attachmentQuota;case"idempotency_conflict":return CHAT_COPY.attachmentConflict;case"unknown":return CHAT_COPY.attachmentUnknown}}function attachControlLabel(used,total){return fillCopy(used>=total?CHAT_COPY.attachmentsFull:CHAT_COPY.addAttachment,{used:used,total:total})}var EMPTY_SNAPSHOT=/* @__PURE__ */Object.freeze({attachments:/* @__PURE__ */Object.freeze([])});function useChatAttachments(options={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),maxPerMessage=options.maxPerMessage??MAX_ATTACHMENTS_PER_MESSAGE,build=react.useCallback(()=>{let{services:services}=runtime.registry;return createAttachmentQueue({funnel:createRequestFunnel({auth:services.authFor(userRef2),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),transport:options.transport??services.uploadTransport,maxPerMessage:maxPerMessage})},[runtime,userRef2,scopeEpoch,maxPerMessage,options.transport]),scoped=react.useMemo(()=>options.queue??build(),[options.queue,build]),disposed=react.useRef(/* @__PURE__ */new WeakSet),[revived,setRevived]=react.useState(null),queue=revived!==null&&revived.of===scoped?revived.queue:scoped;react.useEffect(()=>{if(queue!==options.queue){if(disposed.current.has(queue)){setRevived({of:scoped,queue:build()});return}return()=>{queue.dispose(),disposed.current.add(queue)}}},[queue,scoped,build,options.queue]);let snapshot=react.useSyncExternalStore(queue.subscribe,queue.getSnapshot,()=>EMPTY_SNAPSHOT),[rejected,setRejected]=react.useState(null),add=react.useCallback(files=>{let outcomes=(Array.isArray(files)?files:[files]).map(file=>queue.add(file)),first=outcomes.find(outcome=>!outcome.ok);return first!==void 0&&!first.ok&&setRejected(first.error),outcomes},[queue,setRejected]),retry=react.useCallback(id=>queue.retry(id),[queue]),remove=react.useCallback(id=>queue.remove(id),[queue]),clear=react.useCallback(()=>queue.clear(),[queue]),dismissRejected=react.useCallback(()=>setRejected(null),[setRejected]),uploading=snapshot.attachments.some(row=>row.status==="uploading"),failed=snapshot.attachments.some(row=>row.status==="failed");return react.useMemo(()=>({available:queue.available,attachments:snapshot.attachments,maxPerMessage:maxPerMessage,uploading:uploading,failed:failed,blocked:uploading||failed,s3Keys:snapshot.attachments.flatMap(row=>row.status==="uploaded"&&row.s3Key!==null?[row.s3Key]:[]),rejected:rejected,add:add,retry:retry,remove:remove,clear:clear,dismissRejected:dismissRejected}),[queue.available,snapshot,maxPerMessage,uploading,failed,rejected,add,retry,remove,clear,dismissRejected])}var PET_NOT_REGISTERED="pet_not_registered";function isPetNotRegistered(error){return error!=null&&error.reasonCode===PET_NOT_REGISTERED}var IDLE=/* @__PURE__ */Object.freeze({status:"idle",error:null,registered:null,retry:()=>{}});function useChatPetRegistration(petRef2,pet,onRegistered){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),register=react.useCallback((ref,body)=>{let auth=runtime.registry.services.authFor(userRef2);return sharedPetRegistration(petRegistrationKey(runtime,auth,ref,body),()=>createPetsRepository(auth).registerPet(ref,body))},[runtime,userRef2,scopeEpoch]),bodyKey=react.useMemo(()=>pet===void 0?null:stableKey(pet),[pet]),[state,setState]=react.useState({key:null,status:"idle",error:null,registered:null}),generation=react.useRef(0),onRegisteredRef=react.useRef(onRegistered);onRegisteredRef.current=onRegistered;let scopeKey=petRef2===null||bodyKey===null?null:`${String(userRef2)}|${scopeEpoch}|${petRef2}|${bodyKey}`,run=react.useCallback(()=>{if(petRef2===null||pet===void 0||scopeKey===null)return;let attempt=++generation.current;setState({key:scopeKey,status:"registering",error:null,registered:null}),register(petRef2,pet).then(result=>{attempt===generation.current&&(result.ok?(setState({key:scopeKey,status:"registered",error:null,registered:result.value}),onRegisteredRef.current?.()):setState({key:scopeKey,status:"failed",error:result.error,registered:null}))})},[register,petRef2,scopeKey]);react.useEffect(()=>{if(scopeKey===null){generation.current+=1;return}return run(),()=>{generation.current+=1}},[scopeKey,run]);let retry=react.useCallback(()=>{state.status==="failed"&&run()},[state.status,run]);return react.useMemo(()=>scopeKey===null?IDLE:state.key!==scopeKey?{status:"registering",error:null,registered:null,retry:retry}:{status:state.status,error:state.error,registered:state.registered,retry:retry},[scopeKey,state,retry])}var MAX_SEED_LENGTH=500;function sanitizeSeedPrompt(raw){if(!raw)return null;let stripped=raw.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return stripped?stripped.slice(0,MAX_SEED_LENGTH):null}function useInitialAsk(askEverfur,isBootstrapping,prompt){let clean=sanitizeSeedPrompt(prompt),latest=react.useRef(askEverfur);latest.current=askEverfur;let asked=react.useRef(null);react.useEffect(()=>{if(clean===null||isBootstrapping||asked.current===clean)return;let ask=latest.current;ask!==void 0&&(asked.current=clean,Promise.resolve(ask(clean)).catch(()=>{}))},[clean,isBootstrapping])}function isCoalesced(trigger,conversationId2,state){if(trigger==="announced")return false;let last=state.lastRefresh;return last===null||last.conversationId!==conversationId2?false:state.now-last.at<15e3}function decideChatRefresh(trigger,state){let conversationId2=state.activeConversationId;return conversationId2===null||conversationId2.length===0?{action:"skip",reason:"no_thread"}:state.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:state.isOffline?{action:"defer",reason:"offline"}:isCoalesced(trigger,conversationId2,state)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:conversationId2}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}function useChatLifecycle(lifecycle,target){let latest=react.useRef(target);latest.current=target;let lastRefresh=react.useRef(null),deferred=react.useRef(null),isOffline=lifecycle?.isOffline===void 0?false:callHost(()=>lifecycle.isOffline?.()===!0)===true,run=react.useRef(()=>{});run.current=trigger=>{let{conversationId:conversationId2,isTurnInFlight:isTurnInFlight,refresh:refresh}=latest.current,decision=decideChatRefresh(trigger,{activeConversationId:conversationId2,isTurnInFlight:isTurnInFlight,isOffline:isOffline,lastRefresh:lastRefresh.current,now:Date.now()});if(decision.action!=="skip"){if(decision.action==="defer"){deferred.current!=="announced"&&(deferred.current=trigger);return}deferred.current=null,lastRefresh.current={conversationId:decision.conversationId,at:Date.now()},refresh!==void 0&&Promise.resolve(refresh()).catch(()=>{})}},react.useEffect(()=>{if(target.isTurnInFlight||isOffline)return;let owed=deferred.current;owed!==null&&run.current(owed)},[target.isTurnInFlight,isOffline]),react.useEffect(()=>{if(lifecycle===void 0)return;let stops=[],subscribe=(attach,trigger)=>{if(attach===void 0)return;let stop=callHost(()=>attach(()=>{run.current(trigger)}));typeof stop=="function"&&stops.push(stop)};return subscribe(lifecycle.onForeground?.bind(lifecycle),"foreground"),subscribe(lifecycle.onOnline?.bind(lifecycle),"foreground"),subscribe(lifecycle.onAnnounced?.bind(lifecycle),"announced"),()=>{for(let stop of stops)callHost(stop)}},[lifecycle])}function targetKey(target){if(target===void 0)return null;let conversationId2=target.conversationId??"",petRef2=target.petRef??"";return conversationId2===""&&petRef2===""?null:`${String(conversationId2)}|${String(petRef2)}`}function useCheckinTarget(openCheckin,target){let key=targetKey(target),latest=react.useRef({openCheckin:openCheckin,target:target});latest.current={openCheckin:openCheckin,target:target};let opened=react.useRef(null);react.useEffect(()=>{if(key===null||opened.current===key)return;opened.current=key;let{openCheckin:open,target:current}=latest.current;open===void 0||current===void 0||Promise.resolve(open(current)).catch(()=>{})},[key])}var HISTORY_COPY=/* @__PURE__ */Object.freeze({heading:"Chats",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No chats match that.",loading:"Loading your chats…",loadFailed:"Couldn’t load your chats",loadingMore:"Loading more…",untitled:"New conversation",newChat:"New chat",searchPlaceholder:"Search chats…",search:"Search chats",countLabel:"Chats and vet messages",countSeparator:" · ",newReply:"New reply · {date}",retry:"Try again",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages…",openConversation:"Open conversation",unreadPrefix:"Unread. "});function conversationTitle(title){let collapsed=title?.replace(/\s+/g," ").trim();return collapsed||HISTORY_COPY.untitled}function conversationDate(iso){if(!iso)return null;let parsed=new Date(iso);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleDateString([],{month:"short",day:"numeric"})}function conversationMeta(row){let date2=conversationDate(row.updatedAt);return date2===null?null:row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.newReply.replace("{date}",date2):date2}function historyCountLabel(count2,complete){return complete?`${HISTORY_COPY.countLabel}${HISTORY_COPY.countSeparator}${count2}`:HISTORY_COPY.countLabel}function openConversationLabel(row){return`${row.unreadCount!==null&&row.unreadCount>0?HISTORY_COPY.unreadPrefix:""}${HISTORY_COPY.openConversation} ${conversationTitle(row.title)}`}function normalizeForSearch(text3){return text3.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}function filterConversations(rows,query){let q=normalizeForSearch(query);if(q.length===0)return rows;let tiers=[[],[],[]];for(let row of rows){let label=normalizeForSearch(conversationTitle(row.title)),at=label.indexOf(q);if(at<0)continue;let tier=at===0?0:label.charAt(at-1)===" "?1:2;tiers[tier]?.push(row)}return tiers.flat()}function fresh(scope){return{scope:scope,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}function useHistoryPanel(chat){let[open,setOpen]=react.useState(false),[query,setQuery]=react.useState(""),scope=chat.listConversations,generation=react.useRef(0),[state,setState]=react.useState(()=>fresh(scope)),current=state.scope===scope?state:fresh(scope);react.useEffect(()=>(generation.current+=1,setOpen(false),setQuery(""),setState(fresh(scope)),()=>{generation.current+=1}),[scope]);let load=react.useCallback(async cursor2=>{let request=++generation.current,more=cursor2!==void 0;setState(previous=>({...previous,scope:scope,loading:!more,loadingMore:more,error:null}));let result=await chat.listConversations(cursor2?{cursor:cursor2}:void 0);if(request===generation.current){if(!result.ok){setState(previous=>({...previous,loading:false,loadingMore:false,error:result.error.displayMessage}));return}setState(previous=>{let existing=cursor2&&previous.scope===scope?previous.rows:[],ids=new Set(existing.map(row=>row.id));return{scope:scope,loading:false,loadingMore:false,error:null,rows:[...existing,...result.value.conversations.filter(row=>!ids.has(row.id))],cursor:result.value.nextCursor===cursor2?null:result.value.nextCursor}})}},[chat.listConversations,scope]),show=()=>{setOpen(true),setQuery(""),load()},close=()=>{generation.current+=1,setOpen(false)},resume=async id=>{let request=++generation.current;setState(previous=>({...previous,loading:true,error:null}));let result=await chat.resumeConversation(id);request===generation.current&&(setState(previous=>({...previous,loading:false,error:result.ok?null:result.error.displayMessage})),result.ok&&setOpen(false))},earlier=async()=>{let request=generation.current,result=await chat.loadOlderMessages();request===generation.current&&!result.ok&&setState(previous=>({...previous,error:result.error.displayMessage}))},newConversation=()=>{chat.newConversation(),generation.current+=1,setOpen(false)},loadMore=()=>{current.cursor===null||current.loading||current.loadingMore||query.trim().length>0||load(current.cursor)},filtered=react.useMemo(()=>filterConversations(current.rows,query),[current.rows,query]),searching=query.trim().length>0;return{...current,open:open,show:show,close:close,load:load,resume:resume,earlier:earlier,newConversation:newConversation,loadMore:loadMore,query:query,setQuery:setQuery,searching:searching,filtered:filtered,emptyKind:current.rows.length===0?"empty":"noMatch"}}var TIER_REASON_INK="#111111",TIER_PILL_FILL="#FFFFFF",URGENCY_TIERS=/* @__PURE__ */Object.freeze({emergency:/* @__PURE__ */Object.freeze({level:"emergency",label:"Call a vet now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),schedule_soon:/* @__PURE__ */Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:true}),home_care:/* @__PURE__ */Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false}),general:/* @__PURE__ */Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:TIER_REASON_INK,pillColor:TIER_PILL_FILL,showsVetAction:false})});function urgencySignature(source){return`${source.messageId}:${source.level}:${source.reason??""}`}function generalUrgencyReason(petName){return fillCopy(CHAT_COPY.urgencyGeneralReason,{petName:CHAT_COPY.emptyTitlePetFallback})}function latestUrgencySource(messages,petName){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role!=="assistant"||message.responseId===void 0)continue;let level=message.urgencyLevel;return level?{messageId:message.id,level:level,reason:shownReason(message.urgencyReason)}:message.urgencyProvided===true?{messageId:message.id,level:"general",reason:generalUrgencyReason()}:null}return null}function shownReason(reason){return typeof reason=="string"&&reason.trim().length>0?reason:null}function useUrgencySurface(source){let signature=source===null?null:urgencySignature(source),[dismissedSignature,setDismissedSignature]=react.useState(null),[expanded,setExpanded]=react.useState(false);react.useEffect(()=>setExpanded(false),[signature]);let showBanner=source!==null&&(expanded||!(dismissedSignature!==null&&dismissedSignature===signature)),tier=source===null?null:URGENCY_TIERS[source.level],showCompactIcon=source!==null&&!showBanner&&source.level!=="general",dismiss=react.useCallback(()=>{signature!==null&&setDismissedSignature(signature),setExpanded(false)},[signature]),expand=react.useCallback(()=>setExpanded(true),[]);return react.useMemo(()=>({source:source,tier:tier,signature:signature,showBanner:showBanner,showCompactIcon:showCompactIcon,showVetAction:showBanner&&tier!==null&&tier.showsVetAction,dismissLabel:tier===null?null:fillCopy(CHAT_COPY.dismissBanner,{label:tier.label}),dismiss:dismiss,expand:expand}),[source,tier,signature,showBanner,showCompactIcon,dismiss,expand])}function selectView2(state){return state.isBootstrapping?"loading":state.status==="error"&&state.error&&state.messages.length===0?"error":state.messages.length===0?"empty":"populated"}function needsNewConversation(error){return error.code==="accessDenied"||error.code==="conversationNotFound"}function turnNotice(state,host="native"){if(state.messages.length===0)return null;let error=state.status==="error"?state.error:null;if(error!==null){let startNew=needsNewConversation(error),web=host==="web";return{tone:"error",title:startNew?CHAT_COPY.turnUnreachableTitle:web?CHAT_COPY.turnFailedTitleWeb:CHAT_COPY.turnFailedTitle,body:error.displayMessage,actionLabel:startNew?CHAT_COPY.turnStartNewChat:web?CHAT_COPY.retry:CHAT_COPY.turnRetry,action:startNew?"startNew":"retry"}}return state.stopped===true?{tone:"neutral",title:CHAT_COPY.turnStoppedTitle,body:CHAT_COPY.turnStoppedBody,actionLabel:CHAT_COPY.turnRetry,action:"retry"}:null}function awaitingAssistant(messages,isStreaming){let lastMessage=messages[messages.length-1];return isStreaming&&(lastMessage===void 0||lastMessage.role==="user")}var MAX_VISIBLE_FOLLOW_UPS=3,NO_FOLLOW_UPS=/* @__PURE__ */Object.freeze([]);function visibleFollowUps(state){let last=state.messages[state.messages.length-1];if(state.isStreaming||state.status==="error"||last===void 0||last.role!=="assistant")return NO_FOLLOW_UPS;let seen=/* @__PURE__ */new Set,out=[];for(let prompt of state.suggestedPrompts){let text3=prompt.trim(),key=text3.replace(/\s+/g," ").toLowerCase();if(!(key.length===0||seen.has(key))&&(seen.add(key),out.push(text3),out.length===MAX_VISIBLE_FOLLOW_UPS))break}/* @__PURE__ */
142
142
  return Object.freeze(out)}function vetSenderLabel(message){return message.sender?.displayName??CHAT_COPY.senderVet}function buildChatOpts(petRef2,conversationId2){let opts={};return petRef2!==void 0&&(opts.petRef=petRef2),conversationId2!==void 0&&(opts.conversationId=conversationId2),opts}function useEverfurPets(){let{runtime:runtime,userRef:userRef2,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=react.useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),[state,setState]=react.useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=react.useRef(0),load=react.useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]),react.useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=react.useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return react.useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}function headerPetOf(pets,activePetRef){if(activePetRef!==null){let active=pets.find(pet=>pet.petRef===activePetRef);if(active!==void 0)return active}return pets[0]??null}var VISUALLY_HIDDEN=/* @__PURE__ */Object.freeze({position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0});var FOCUS_RING_WIDTH=2,SELF_FOCUS_RING_ATTRIBUTE="data-ef-focus-ring",FOCUS_RING_COLOR_ATTRIBUTE="data-ef-focus-ring-color";function focusRingStyle(color){return{outline:`${FOCUS_RING_WIDTH}px solid ${color}`,outlineOffset:FOCUS_RING_WIDTH}}var keyboardDriving=false,bound=0;function onKeyDown(event){event.metaKey||event.ctrlKey||event.altKey||(keyboardDriving=true)}function onPointerDown(){keyboardDriving=false}function bindModality(){return typeof document>"u"?()=>{}:(bound===0&&(document.addEventListener("keydown",onKeyDown,true),document.addEventListener("pointerdown",onPointerDown,true),document.addEventListener("mousedown",onPointerDown,true),document.addEventListener("touchstart",onPointerDown,true)),bound+=1,()=>{bound-=1,!(bound>0)&&(document.removeEventListener("keydown",onKeyDown,true),document.removeEventListener("pointerdown",onPointerDown,true),document.removeEventListener("mousedown",onPointerDown,true),document.removeEventListener("touchstart",onPointerDown,true),keyboardDriving=false)})}var TEXT_INPUT_TYPES=/* @__PURE__ */new Set(["","text","search","email","tel","url","password","number"]);function isTextField(element){return element.tagName==="TEXTAREA"||element.isContentEditable?true:element.tagName!=="INPUT"?false:TEXT_INPUT_TYPES.has((element.getAttribute("type")??"").toLowerCase())}function useKeyboardFocusRing(root,color){react.useEffect(()=>{let node=root.current;if(node===null)return;let unbind=bindModality(),painted=/* @__PURE__ */new Map,onFocusIn=event=>{let target=event.target;if(!(target instanceof HTMLElement)||painted.has(target)||target.closest(`[${SELF_FOCUS_RING_ATTRIBUTE}="self"]`)!==null||!keyboardDriving&&!isTextField(target))return;painted.set(target,{outline:target.style.outline,outlineOffset:target.style.outlineOffset});let region=target.closest(`[${FOCUS_RING_COLOR_ATTRIBUTE}]`),ring=focusRingStyle(region?.getAttribute(FOCUS_RING_COLOR_ATTRIBUTE)||color);target.style.outline=ring.outline,target.style.outlineOffset=`${ring.outlineOffset}px`},onFocusOut=event=>{let target=event.target;if(!(target instanceof HTMLElement))return;let before=painted.get(target);before!==void 0&&(painted.delete(target),target.style.outline=before.outline,target.style.outlineOffset=before.outlineOffset)};return node.addEventListener("focusin",onFocusIn),node.addEventListener("focusout",onFocusOut),()=>{node.removeEventListener("focusin",onFocusIn),node.removeEventListener("focusout",onFocusOut);for(let[element,before]of painted)element.style.outline=before.outline,element.style.outlineOffset=before.outlineOffset;painted.clear(),unbind()}},[root,color])}function chatVetVisitOptions(petRef2,vet){let options={entry:"chat",petRef:petRef2};return vet?.returnTo!==void 0&&(options.returnTo=vet.returnTo),vet?.usState!==void 0&&(options.usState=vet.usState),vet?.prefer!==void 0&&(options.prefer=vet.prefer),options}var SLOT=/* @__PURE__ */Symbol.for("@everfur/sdk/televet");function televetGlobal(){let realm=globalThis,existing=realm[SLOT];if(existing!==void 0)return existing;let created={presenter:null,snapshot:/* @__PURE__ */Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:/* @__PURE__ */new Set,dailyRegistered:false};return realm[SLOT]=created,created}function publish(next){let g=televetGlobal();g.snapshot=/* @__PURE__ */Object.freeze({...g.snapshot,...next});for(let listener of[...g.listeners])try{listener()}catch{}}function callTelevetPresenter(request){let present2=televetGlobal().presenter;if(present2===null)return"absent";try{return present2(request)===!1?"declined":"presented"}catch(cause){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",cause),"threw"}}function subscribeTelevetExperience(listener){let g=televetGlobal();return g.listeners.add(listener),()=>{g.listeners.delete(listener)}}function televetExperienceSnapshot(){return televetGlobal().snapshot}function hasTelevetHost(){return televetGlobal().hosts.length>0}function presentTelevetExperience(request){if(!hasTelevetHost())return false;let frozen=/* @__PURE__ */Object.freeze({...request});return publish({request:frozen,serial:televetGlobal().snapshot.serial+1}),true}function dismissTelevetExperience(){televetGlobal().snapshot.request!==null&&publish({request:null})}function claimTelevetHost(){let g=televetGlobal(),id=g.nextHost;return g.nextHost+=1,g.hosts=[...g.hosts,id],publish({activeHost:g.hosts[0]??null}),id}function releaseTelevetHost(id){let g=televetGlobal();g.hosts=g.hosts.filter(host=>host!==id);let activeHost=g.hosts[0]??null;publish(activeHost===null?{activeHost:activeHost,request:null}:{activeHost:activeHost})}function memoizeTelevetLoader(load){let pending=null;return()=>{if(pending!==null)return pending;let started=load();return pending=started,started.then(void 0,()=>{pending===started&&(pending=null)}),started}}function useTelevetExperienceHost(load){let[id,setId]=react.useState(null);react.useEffect(()=>{let claimed=claimTelevetHost();return setId(claimed),()=>{releaseTelevetHost(claimed)}},[]);let snapshot=react.useSyncExternalStore(subscribeTelevetExperience,televetExperienceSnapshot,televetExperienceSnapshot),request=id!==null&&snapshot.activeHost===id?snapshot.request:null,[module,setModule]=react.useState(null),wanted=request!==null&&module===null;return react.useEffect(()=>{if(!wanted)return;let live=true;return load().then(loaded=>{live&&setModule(()=>loaded)},cause=>{live&&(console.warn("[everfur] The in-app vet visit could not load its screens.",cause),dismissTelevetExperience())}),()=>{live=false}},[wanted,load]),request===null||module===null?null:{module:module,request:request,serial:snapshot.serial,dismiss:dismissTelevetExperience}}var loadExperience=memoizeTelevetLoader(()=>import("@everfur/sdk/web/televet/booking"));function EverfurTelevetHost({onAddToCalendar:onAddToCalendar,onPickMedia:onPickMedia,primaryVet:primaryVet,onFindEmergencyVet:onFindEmergencyVet}){let host=useTelevetExperienceHost(loadExperience);if(host===null)return null;let{EverfurTelevetDialog:EverfurTelevetDialog}=host.module;/* @__PURE__ */
143
- return jsxRuntime.jsx(EverfurTelevetDialog,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef2,options){let body={};petRef2!==void 0&&(body.pet_ref=petRef2);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef2===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef2,options){let pet;if(petRef2!=null){let length=typeof petRef2=="string"?[...petRef2].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef2}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL2=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL2.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var warned2=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned2||(warned2=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=react.useState(null);if(react.useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef2!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=react.useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef2),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef2,scopeEpoch,opts.controller]),preflightController=react.useRef(controller);preflightController.current=controller;let scope=react.useMemo(()=>({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}),[runtime,userRef2,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=react.useState(IDLE2),inFlight3=react.useRef(null),scopeRef=react.useRef({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch};let controllerRef=react.useRef(controller);controllerRef.current=controller;let availableRef=react.useRef(available);availableRef.current=available;let start=react.useCallback((petRef2,visit)=>{if(inFlight3.current)return inFlight3.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef2===void 0?defaultPet:petRef2;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight3.current===tracked&&(inFlight3.current=null)});return inFlight3.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=react.useCallback((petRef2,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef2===void 0?defaultPet:petRef2,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=react.useCallback(petRef2=>redirect?start(petRef2,null):openInApp(petRef2,null),[redirect,start,openInApp]),openVisit=react.useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit}}function closeQuietly(tab){try{tab.closed||tab.close()}catch{}}var BROWSER_OPENER=/* @__PURE__ */Object.freeze({prepare(){let tab=null;try{tab=typeof window>"u"?null:window.open("about:blank","_blank")}catch{tab=null}if(tab===null)return{ok:false,reason:"popupBlocked"};try{tab.opener=null}catch{}return{ok:true,value:{tab:tab}}},async finish({tab:tab},handoff){if(tab.closed)return"cancelled";try{return tab.location.replace(handoff.url),null}catch{return closeQuietly(tab),"popupBlocked"}},abandon({tab:tab}){closeQuietly(tab)}});function useVetVisit(opts){return useVetVisitWith(BROWSER_OPENER,opts)}var FOCUSABLE='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function isDialogElement(node){return node.tagName==="DIALOG"}function useModalDialog(open,onClose,returnFocusTo,options){let escapeAtKeyDown=options?.escapeAtKeyDown===true,dialogRef=react.useRef(null),wasOpen=react.useRef(false),opener=react.useRef(null),trigger=react.useRef(returnFocusTo);trigger.current=returnFocusTo;let restoreFocus=react.useCallback(()=>{if(!wasOpen.current)return;wasOpen.current=false;let target=trigger.current===void 0?opener.current:trigger.current.current;target&&target.isConnected&&target.focus(),(!target||!target.isConnected||document.activeElement===target)&&(opener.current=null)},[]);react.useEffect(()=>{if(!open){restoreFocus();return}let node=dialogRef.current;if(!wasOpen.current){let active=typeof document>"u"?null:document.activeElement;active!==null&&node!==null&&node.contains(active)||(opener.current=active instanceof HTMLElement?active:null)}if(wasOpen.current=true,node===null)return;if(!isDialogElement(node)){node.contains(document.activeElement)||(node.querySelector(FOCUSABLE)??node).focus();return}let dialog=node;typeof dialog.showModal=="function"?dialog.open||dialog.showModal():dialog.setAttribute("open","")},[open,restoreFocus]),react.useEffect(()=>restoreFocus,[restoreFocus]),react.useEffect(()=>{let node=dialogRef.current;if(!open||node===null||!isDialogElement(node))return;let dialog=node;if(typeof dialog.showModal!="function")return;let lastFocused=null,onFocusIn=event=>{event.target instanceof HTMLElement&&(lastFocused=event.target)},onNativeClose=()=>{if(!dialog.isConnected||dialog.open)return;let back=lastFocused;dialog.showModal(),back!==null&&back.isConnected&&dialog.contains(back)&&document.activeElement!==back&&back.focus()};return dialog.addEventListener("focusin",onFocusIn),dialog.addEventListener("close",onNativeClose),()=>{dialog.removeEventListener("focusin",onFocusIn),dialog.removeEventListener("close",onNativeClose)}},[open]);let onKeyDown2=react.useCallback(event=>{let node=dialogRef.current;if(node===null)return;if(event.key==="Escape"&&!isDialogElement(node)){event.preventDefault(),event.stopPropagation(),onClose();return}if(event.key==="Escape"&&escapeAtKeyDown);if(event.key!=="Tab")return;let focusable=Array.from(node.querySelectorAll(FOCUSABLE)),first=focusable[0],last=focusable[focusable.length-1];if(!first||!last){event.preventDefault();return}let active=document.activeElement;event.shiftKey&&(active===first||!node.contains(active))?(event.preventDefault(),last.focus()):!event.shiftKey&&(active===last||!node.contains(active))&&(event.preventDefault(),first.focus())},[onClose,escapeAtKeyDown]),onCancel=react.useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),onClose())},[onClose]);return{dialogRef:dialogRef,onKeyDown:onKeyDown2,onCancel:onCancel}}var PATHS=/* @__PURE__ */Object.freeze({check:/* @__PURE__ */jsxRuntime.jsx("polyline",{points:"20 6 9 17 4 12"}),copy:/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
143
+ return jsxRuntime.jsx(EverfurTelevetDialog,{request:host.request,onClose:host.dismiss,...onAddToCalendar?{onAddToCalendar:onAddToCalendar}:{},...onPickMedia?{onPickMedia:onPickMedia}:{},...primaryVet?{primaryVet:primaryVet}:{},...onFindEmergencyVet?{onFindEmergencyVet:onFindEmergencyVet}:{}},host.serial)}var VET_VISIT_INTENTS=/* @__PURE__ */Object.freeze(["visit","join","summary","messages"]);function isVetVisitIntent(value){return typeof value=="string"&&VET_VISIT_INTENTS.includes(value)}var VET_VISIT_HANDOFF_PATH="/widget/v1/televet/handoffs",VET_VISIT_AVAILABILITY_PATH="/widget/v1/televet/availability",VET_VISIT_CHAT_ENTRY_PATH="/widget/v1/televet/chat-entry",RETURN_KEY=/^[a-z0-9][a-z0-9_-]{0,39}$/,FLOW_ID=/^[A-Za-z0-9_-]{22}$/;var STATE_MAX=32,PET_REF_MAX2=128,VISIT_REF_MAX=64;function vetVisitErrorReasonOf(error){let status=error.httpStatus;switch(error.code){case"sessionRequired":return"sessionRequired";case"authExpired":case"authRejected":return"authRejected";case"sdkUpdateRequired":return"sdkUpdateRequired";case"validationFailed":return"invalidRequest";case"rateLimited":case"quotaExceeded":return"rateLimited"}return status===void 0?error.code==="internalError"?"network":"unknown":status===429?"rateLimited":status===404?"unavailable":status===403?"accessDenied":status===401?"authRejected":status===400||status===422?"invalidRequest":status>=500?"serverError":"unknown"}function invalid3(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef2,options){let body={};petRef2!==void 0&&(body.pet_ref=petRef2);let returnTo=options?.returnTo;if(returnTo!=null){if(typeof returnTo!="string"||!RETURN_KEY.test(returnTo))return{ok:false,message:"returnTo must be a registered return destination key"};body.return_to=returnTo}let entry=options?.entry;if(entry!=null){if(entry!=="chat"||petRef2===void 0)return{ok:false,message:"entry 'chat' needs the pet the chat is about"};body.entry=entry}let visitRef=options?.visitRef,intent=options?.intent,named=visitRef!=null;if(named){let trimmed=typeof visitRef=="string"?visitRef.trim():"";if(trimmed.length<1||[...trimmed].length>VISIT_REF_MAX)return{ok:false,message:`visitRef must be 1..${VISIT_REF_MAX} characters`};body.visit_ref=trimmed}if(intent!=null){if(!named)return{ok:false,message:"intent needs the visitRef it opens"};if(!isVetVisitIntent(intent))return{ok:false,message:`intent must be one of ${VET_VISIT_INTENTS.join(", ")}`};body.intent=intent}return{ok:true,body:body}}function parseVisitEcho(wire){if(typeof wire!="object"||wire===null)return null;let{visit_ref:visitRef,intent:intent}=wire;return typeof visitRef!="string"||visitRef.length===0||!isVetVisitIntent(intent)?null:/* @__PURE__ */Object.freeze({visitRef:visitRef,intent:intent})}function createVetVisitController(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),telemetry=deps.telemetry,failed=error=>(safeTrack(telemetry,"televet.visit.handoff_failed",{reason:vetVisitErrorReasonOf(error)}),err(error));return{async createHandoff(petRef2,options){let pet;if(petRef2!=null){let length=typeof petRef2=="string"?[...petRef2].length:0;if(length<1||length>PET_REF_MAX2)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX2} characters`}));pet=petRef2}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid3(built.message);return refused.ok?refused:failed(refused.error)}let body=built.body,res=await funnel.send("televet.visit.handoff",{method:"POST",path:VET_VISIT_HANDOFF_PATH,body:body},{idempotent:false,maxAttempts:1});if(!res.ok)return failed(res.error);let parsed=parseHandoff(res.value),wantsReturn=body.return_to!==void 0,flowId=wantsReturn?res.value?.flow_id:void 0;if(wantsReturn&&(typeof flowId!="string"||!FLOW_ID.test(flowId))){let refused=unusable("the handoff response carried no usable return flow id");return refused.ok?refused:failed(refused.error)}let wantsVisit=body.visit_ref!==void 0,visit=wantsVisit?parseVisitEcho(res.value?.visit):null;if(wantsVisit&&visit===null){let refused=unusable("the handoff response did not confirm the visit it opens");return refused.ok?refused:failed(refused.error)}let handoff=parsed===null?null:/* @__PURE__ */Object.freeze({...parsed,...wantsReturn?{flowId:flowId}:{},...visit!==null?{visit:visit}:{}});return handoff===null?failed(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(safeTrack(telemetry,"televet.visit.handoff_created",{pet_scoped:body.pet_ref!==void 0}),ok(handoff))},async checkAvailability(state){if(typeof state!="string"||state.length>STATE_MAX)return invalid3(`state must be at most ${STATE_MAX} characters`);let res=await funnel.send("televet.visit.availability",{method:"POST",path:VET_VISIT_AVAILABILITY_PATH,body:{state:state}},{idempotent:false,maxAttempts:1});if(!res.ok)return err(res.error);let available=res.value?.available;return typeof available!="boolean"?unusable("the availability response carried no usable answer"):ok(/* @__PURE__ */Object.freeze({available:available}))},async chatEntryOpen(){try{let res=await funnel.send("televet.visit.chat_entry",{method:"GET",path:VET_VISIT_CHAT_ENTRY_PATH},{maxAttempts:1});return res.ok&&res.value?.open===!0}catch{return false}}}}function parseHandoff(wire){if(typeof wire!="object"||wire===null)return null;let{url:url,expires_at:expiresAt}=wire;return typeof url!="string"||typeof expiresAt!="string"||expiresAt.length===0||!isOpenableVisitUrl(url)?null:/* @__PURE__ */Object.freeze({url:url,expiresAt:expiresAt})}var LOOPBACK_HOSTS=/* @__PURE__ */new Set(["localhost","127.0.0.1","[::1]"]),ABSOLUTE_URL2=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,UNSAFE_CHAR=/[\s\u0000-\u001f\u007f]/;function isOpenableVisitUrl(raw){if(UNSAFE_CHAR.test(raw))return false;let match=ABSOLUTE_URL2.exec(raw);if(match===null)return false;let scheme=(match[1]??"").toLowerCase(),authority=match[2]??"";if(authority.length===0||authority.includes("@"))return false;let host=authority.replace(/:\d+$/,"").toLowerCase(),secure=scheme==="https",loopback=scheme==="http"&&LOOPBACK_HOSTS.has(host);if(!secure&&!loopback)return false;let hashAt=raw.indexOf("#");if(hashAt<0)return false;let fragment=raw.slice(hashAt);return fragment.startsWith("#h=")&&fragment.length>3}function safeTrack(telemetry,event,props){if(telemetry)try{telemetry.track(event,props)}catch{}}var warned3=false;function openVetVisitInApp(request,onStartInApp){return onStartInApp!==void 0?(callHost(onStartInApp,request),"onStartInApp"):callTelevetPresenter(request)==="presented"?"presenter":presentTelevetExperience(request)?"experience":(warned3||(warned3=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}var IDLE2=/* @__PURE__ */Object.freeze({status:"idle",error:null,errorReason:null});function usePreflight(controllerRef,enabled,question){let{usState:usState,chat:chat,scope:scope}=question,needed=enabled&&(usState!==null||chat),key=`${usState??""}|${chat?"chat":""}`,[settled,setSettled]=react.useState(null);if(react.useEffect(()=>{if(!needed)return;let live=true,controller=controllerRef.current;return setSettled(null),(async()=>{try{if(chat&&!(controller.chatEntryOpen&&await controller.chatEntryOpen()))return!1;if(usState===null)return!0;if(!controller.checkAvailability)return!1;let answer=await controller.checkAvailability(usState);return answer.ok&&answer.value.available}catch{return false}})().then(open=>{live&&setSettled({key:key,open:open})}),()=>{live=false}},[needed,key,usState,chat,scope,controllerRef]),!needed)return null;let current=settled!==null&&settled.key===key;return{open:current&&settled.open,pending:!current}}var OPENING=/* @__PURE__ */Object.freeze({status:"opening",error:null,errorReason:null});function useVetVisitWith(opener,opts={}){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),capability=useCapability("televet"),signedIn=capability.enabled&&userRef2!==null,usState=opts.usState??null,chat=opts.entry==="chat",defaultPet=opts.petRef??null,redirect=opts.prefer==="redirect",controller=react.useMemo(()=>{if(opts.controller)return opts.controller;let{services:services}=runtime.registry;return createVetVisitController({auth:services.authFor(userRef2),telemetry:services.telemetry,...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef2,scopeEpoch,opts.controller]),preflightController=react.useRef(controller);preflightController.current=controller;let scope=react.useMemo(()=>({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}),[runtime,userRef2,scopeEpoch]),preflight=usePreflight(preflightController,signedIn,{usState:usState,chat:chat,scope:scope}),available=signedIn&&(preflight===null||preflight.open)&&(!chat||defaultPet!==null),returnTo=opts.returnTo??null,[settled,setSettled]=react.useState(IDLE2),inFlight3=react.useRef(null),scopeRef=react.useRef({runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch});scopeRef.current={runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch};let controllerRef=react.useRef(controller);controllerRef.current=controller;let availableRef=react.useRef(available);availableRef.current=available;let start=react.useCallback((petRef2,visit)=>{if(inFlight3.current)return inFlight3.current;let fail=(reason,error)=>(setSettled({status:reason==="cancelled"?"idle":"error",error:error,errorReason:reason==="cancelled"?null:reason}),/* @__PURE__ */Object.freeze({opened:false,reason:reason,error:error}));if(!availableRef.current)return Promise.resolve(fail("unavailable",null));let prepared=opener.prepare();if(!prepared.ok)return Promise.resolve(fail(prepared.reason,null));let started=scopeRef.current,controller2=controllerRef.current;setSettled(OPENING);let tracked=(async()=>{let result,named={...returnTo!==null?{returnTo:returnTo}:{},...chat?{entry:"chat"}:{},...visit!==null?{visitRef:visit.visitRef}:{},...visit!==null&&visit.intent!==null&&visit.intent!==void 0?{intent:visit.intent}:{}},options=Object.keys(named).length===0?void 0:named,pet=petRef2===void 0?defaultPet:petRef2;try{result=await(options===void 0?controller2.createHandoff(pet):controller2.createHandoff(pet,options))}catch{return opener.abandon(prepared.value),fail("unknown",null)}let current=scopeRef.current;if(current.runtime!==started.runtime||current.userRef!==started.userRef||current.scopeEpoch!==started.scopeEpoch)return opener.abandon(prepared.value),fail("cancelled",null);if(!result.ok)return opener.abandon(prepared.value),fail(vetVisitErrorReasonOf(result.error),result.error);let openFailure=await opener.finish(prepared.value,result.value);return openFailure!==null?fail(openFailure,null):(setSettled(IDLE2),/* @__PURE__ */Object.freeze(result.value.flowId===void 0?{opened:true}:{opened:true,flowId:result.value.flowId}))})().finally(()=>{inFlight3.current===tracked&&(inFlight3.current=null)});return inFlight3.current=tracked,tracked},[opener,defaultPet,returnTo,chat]),openInApp=react.useCallback((petRef2,visit)=>{if(!availableRef.current)return setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}));let pet=petRef2===void 0?defaultPet:petRef2,request={...pet!==null?{petRef:pet}:{},...usState!==null?{usState:usState}:{},...visit!==null?{visitRef:visit.visitRef,intent:visit.intent}:{}};return openVetVisitInApp(request)===null?(setSettled({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(/* @__PURE__ */Object.freeze({opened:false,reason:"unavailable",error:null}))):(setSettled(IDLE2),Promise.resolve(/* @__PURE__ */Object.freeze({opened:true})))},[defaultPet,usState]),open=react.useCallback(petRef2=>redirect?start(petRef2,null):openInApp(petRef2,null),[redirect,start,openInApp]),openVisit=react.useCallback((visitRef,intent)=>redirect?start(void 0,{visitRef:visitRef,intent:intent??null}):openInApp(void 0,{visitRef:visitRef,intent:intent??null}),[redirect,start,openInApp]);return{available:available,isPending:capability.isPending||(preflight?.pending??false),status:settled.status,error:settled.error,errorReason:settled.errorReason,open:open,openVisit:openVisit}}function closeQuietly(tab){try{tab.closed||tab.close()}catch{}}var BROWSER_OPENER=/* @__PURE__ */Object.freeze({prepare(){let tab=null;try{tab=typeof window>"u"?null:window.open("about:blank","_blank")}catch{tab=null}if(tab===null)return{ok:false,reason:"popupBlocked"};try{tab.opener=null}catch{}return{ok:true,value:{tab:tab}}},async finish({tab:tab},handoff){if(tab.closed)return"cancelled";try{return tab.location.replace(handoff.url),null}catch{return closeQuietly(tab),"popupBlocked"}},abandon({tab:tab}){closeQuietly(tab)}});function useVetVisit(opts){return useVetVisitWith(BROWSER_OPENER,opts)}var FOCUSABLE='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function isDialogElement(node){return node.tagName==="DIALOG"}function useModalDialog(open,onClose,returnFocusTo,options){let escapeAtKeyDown=options?.escapeAtKeyDown===true,dialogRef=react.useRef(null),wasOpen=react.useRef(false),opener=react.useRef(null),trigger=react.useRef(returnFocusTo);trigger.current=returnFocusTo;let restoreFocus=react.useCallback(()=>{if(!wasOpen.current)return;wasOpen.current=false;let target=trigger.current===void 0?opener.current:trigger.current.current;target&&target.isConnected&&target.focus(),(!target||!target.isConnected||document.activeElement===target)&&(opener.current=null)},[]);react.useEffect(()=>{if(!open){restoreFocus();return}let node=dialogRef.current;if(!wasOpen.current){let active=typeof document>"u"?null:document.activeElement;active!==null&&node!==null&&node.contains(active)||(opener.current=active instanceof HTMLElement?active:null)}if(wasOpen.current=true,node===null)return;if(!isDialogElement(node)){node.contains(document.activeElement)||(node.querySelector(FOCUSABLE)??node).focus();return}let dialog=node;typeof dialog.showModal=="function"?dialog.open||dialog.showModal():dialog.setAttribute("open","")},[open,restoreFocus]),react.useEffect(()=>restoreFocus,[restoreFocus]),react.useEffect(()=>{let node=dialogRef.current;if(!open||node===null||!isDialogElement(node))return;let dialog=node;if(typeof dialog.showModal!="function")return;let lastFocused=null,onFocusIn=event=>{event.target instanceof HTMLElement&&(lastFocused=event.target)},onNativeClose=()=>{if(!dialog.isConnected||dialog.open)return;let back=lastFocused;dialog.showModal(),back!==null&&back.isConnected&&dialog.contains(back)&&document.activeElement!==back&&back.focus()};return dialog.addEventListener("focusin",onFocusIn),dialog.addEventListener("close",onNativeClose),()=>{dialog.removeEventListener("focusin",onFocusIn),dialog.removeEventListener("close",onNativeClose)}},[open]);let onKeyDown2=react.useCallback(event=>{let node=dialogRef.current;if(node===null)return;if(event.key==="Escape"&&!isDialogElement(node)){event.preventDefault(),event.stopPropagation(),onClose();return}if(event.key==="Escape"&&escapeAtKeyDown);if(event.key!=="Tab")return;let focusable=Array.from(node.querySelectorAll(FOCUSABLE)),first=focusable[0],last=focusable[focusable.length-1];if(!first||!last){event.preventDefault();return}let active=document.activeElement;event.shiftKey&&(active===first||!node.contains(active))?(event.preventDefault(),last.focus()):!event.shiftKey&&(active===last||!node.contains(active))&&(event.preventDefault(),first.focus())},[onClose,escapeAtKeyDown]),onCancel=react.useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),onClose())},[onClose]);return{dialogRef:dialogRef,onKeyDown:onKeyDown2,onCancel:onCancel}}var PATHS=/* @__PURE__ */Object.freeze({check:/* @__PURE__ */jsxRuntime.jsx("polyline",{points:"20 6 9 17 4 12"}),copy:/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
144
144
  /* @__PURE__ */jsxRuntime.jsx("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),
145
145
  /* @__PURE__ */jsxRuntime.jsx("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]}),thumbsUp:/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
146
146
  /* @__PURE__ */jsxRuntime.jsx("path",{d:"M7 10v12"}),
@@ -180,13 +180,14 @@ return jsxRuntime.jsx("svg",{"aria-hidden":"true",focusable:"false",width:size,h
180
180
  /* @__PURE__ */jsxRuntime.jsx("img",{src:image.uri,alt:image.filename,style:styles.image}),
181
181
  /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onClose,"aria-label":CHAT_COPY.closePreview,style:styles.closeHit,children:/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.closeDisc,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"x",size:18,color:ON_BLACK})})})]})}function makeStyles2(theme){let r=theme.radius;return{lightbox:{boxSizing:"border-box",position:"fixed",top:0,right:0,bottom:0,left:0,margin:0,width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",padding:0,border:0,backgroundColor:"#000000",display:"flex",alignItems:"center",justifyContent:"center"},image:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",objectFit:"contain"},closeHit:{position:"absolute",top:CLOSE_TOP-(MIN_TOUCH_TARGET-CLOSE_DISC_SIZE)/2,right:CLOSE_RIGHT-(MIN_TOUCH_TARGET-CLOSE_DISC_SIZE)/2,boxSizing:"border-box",width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,minWidth:MIN_TOUCH_TARGET,minHeight:MIN_TOUCH_TARGET,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},closeDisc:{boxSizing:"border-box",width:CLOSE_DISC_SIZE,height:CLOSE_DISC_SIZE,borderRadius:r.pill,backgroundColor:"rgba(0,0,0,0.45)",display:"inline-flex",alignItems:"center",justifyContent:"center"}}}var FILE_FIELD="file",NO_BYTES="chat attachment upload: the file handle carries no bytes",FAILED="chat attachment upload failed";function createWebAttachmentTransport(options={}){let doFetch=options.fetch??((input,init)=>fetch(input,init));/* @__PURE__ */
182
182
  return Object.freeze({postMultipart(policy,file,opts){let blob=file.blob;if(blob===void 0)return Promise.reject(new Error(NO_BYTES));if(opts.signal?.aborted===true)return Promise.reject(new Error(FAILED));let form=new FormData;for(let[name,value]of Object.entries(policy.upload_fields))form.append(name,value);return form.append(FILE_FIELD,blob,"image"),doFetch(policy.upload_url,{method:"POST",body:form,mode:"cors",credentials:"omit",...opts.signal?{signal:opts.signal}:{}}).then(response=>{if(!(response.status>=200&&response.status<300))return Promise.reject(new Error(FAILED));opts.onProgress?.(1)},()=>Promise.reject(new Error(FAILED)))}})}function fileToAttachmentHandle(file){/* @__PURE__ */
183
- return Object.freeze({uri:URL.createObjectURL(file),mimeType:file.type,sizeBytes:file.size,name:file.name,blob:file})}function revokeObjectUrl(url){try{URL.revokeObjectURL(url)}catch{}}function grounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function isEverfurLightLook(theme){if(theme.brightness!=="light")return false;let compiled=EVERFUR_LIGHT.color,c=theme.color,same3=(a,b)=>parseColor(a)===parseColor(b),own=new Set(grounds(compiled));return same3(c.brand,compiled.brand)&&same3(c.accent,compiled.accent)&&grounds(c).every(ground=>own.has(ground))}function speciesOf(species){return canonicalPetSpecies(species)==="cat"?"cat":"dog"}function petAgeYears(ageYears){return typeof ageYears!="number"||!Number.isFinite(ageYears)||ageYears<0?null:Math.floor(ageYears)}function formatPetMeta(pet){let ageYears=petAgeYears(pet.ageYears),speciesLabel=speciesOf(pet.species)==="cat"?"Cat":"Dog";if(ageYears==null)return speciesLabel;let ageLabel=ageYears===1?"1 yr":`${ageYears} yrs`;return`${speciesLabel} · ${ageLabel}`}var INITIALS_PALETTE=/* @__PURE__ */Object.freeze([
183
+ return Object.freeze({uri:URL.createObjectURL(file),mimeType:file.type,sizeBytes:file.size,name:file.name,blob:file})}function revokeObjectUrl(url){try{URL.revokeObjectURL(url)}catch{}}function grounds(c){return[c.surface,c.surfaceCream,c.surfaceSubtle,c.background,c.chatGround,c.composerFill]}function isEverfurLightLook(theme){if(theme.brightness!=="light")return false;let compiled=EVERFUR_LIGHT.color,c=theme.color,same3=(a,b)=>parseColor(a)===parseColor(b),own=new Set(grounds(compiled));return same3(c.brand,compiled.brand)&&same3(c.accent,compiled.accent)&&grounds(c).every(ground=>own.has(ground))}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same3=(a,b)=>parseColor(a)===parseColor(b);return{success:!same3(c.success,compiled.success),warning:!same3(c.warningStrong,compiled.warningStrong)||!same3(c.cautionAccent,compiled.cautionAccent),info:!(same3(c.info,c.brandInk)&&same3(c.badgeBgInfo,c.brandSoft)&&same3(c.infoEdge,c.structureEdge))}}function speciesOf(species){return canonicalPetSpecies(species)==="cat"?"cat":"dog"}function petAgeYears(ageYears){return typeof ageYears!="number"||!Number.isFinite(ageYears)||ageYears<0?null:Math.floor(ageYears)}function formatPetMeta(pet){let ageYears=petAgeYears(pet.ageYears),speciesLabel=speciesOf(pet.species)==="cat"?"Cat":"Dog";if(ageYears==null)return speciesLabel;let ageLabel=ageYears===1?"1 yr":`${ageYears} yrs`;return`${speciesLabel} · ${ageLabel}`}var INITIALS_PALETTE=/* @__PURE__ */Object.freeze([
184
184
  /* @__PURE__ */Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),
185
185
  /* @__PURE__ */Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),
186
186
  /* @__PURE__ */Object.freeze({background:"#fbc558",foreground:"#10462e"}),
187
187
  /* @__PURE__ */Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),
188
188
  /* @__PURE__ */Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),
189
- /* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function pickInitialsPalette(key){let hash=0;for(let i=0;i<key.length;i+=1)hash=hash*31+key.charCodeAt(i)>>>0;return INITIALS_PALETTE[hash%INITIALS_PALETTE.length]}function getInitial(name){let trimmed=(name??"").trim();return(Array.from(trimmed)[0]??"?").toUpperCase()}function petInitials(pet){return{...pickInitialsPalette(pet.petRef),initial:getInitial(pet.name)}}function petDiscPaint(pet,everfurLook,highlight){let initials=petInitials(pet);return everfurLook?initials:{background:highlight.fill,foreground:highlight.ink,initial:initials.initial}}var TELEVET_COPY=/* @__PURE__ */Object.freeze({visitButton:"Vet"});var MIN_TOUCH_TARGET2=44,ROW_AVATAR_SIZE=44,ROW_RING_SIZE=48,CHECK_SIZE=18,SHEET_RADIUS=22,SHEET_MAX_HEIGHT="80vh";function PetSwitcherDialog(props){let{open:open,pets:pets,activePetRef:activePetRef,onClose:onClose,onSelect:onSelect,onAddPet:onAddPet=null,returnFocusTo:returnFocusTo}=props,theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles3(theme),[theme]),dialog=useModalDialog(open,onClose,returnFocusTo),everfurLook=isEverfurLightLook(theme);return open?/* @__PURE__ */jsxRuntime.jsxs("dialog",{ref:dialog.dialogRef,"aria-label":CHAT_COPY.yourPets,onCancel:dialog.onCancel,onKeyDown:dialog.onKeyDown,style:styles.sheet,children:[
189
+ /* @__PURE__ */Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function pickInitialsPalette(key){let hash=0;for(let i=0;i<key.length;i+=1)hash=hash*31+key.charCodeAt(i)>>>0;return INITIALS_PALETTE[hash%INITIALS_PALETTE.length]}function getInitial(name){let trimmed=(name??"").trim();return(Array.from(trimmed)[0]??"?").toUpperCase()}function petInitials(pet){return{...pickInitialsPalette(pet.petRef),initial:getInitial(pet.name)}}function petDiscPaint(pet,everfurLook,highlight){let initials=petInitials(pet);return everfurLook?initials:{background:highlight.fill,foreground:highlight.ink,initial:initials.initial}}var TELEVET_COPY=/* @__PURE__ */Object.freeze({visitButton:"Vet"});function BrandImage({src:src,alt:alt,decorative:decorative=false,style:style,height:height,fallback:fallback=null,onFailed:onFailed}){let[failed,setFailed]=react.useState(null);return src===null||failed===src?fallback:/* @__PURE__ */jsxRuntime.jsx("img",{src:src,alt:decorative?"":alt,...decorative?{"aria-hidden":true}:{},...height===void 0?{}:{height:height},style:style,decoding:"async",referrerPolicy:"no-referrer",onError:()=>{setFailed(src),onFailed?.()}})}var LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,LOGO_STYLE=/* @__PURE__ */Object.freeze({display:"block",height:LOGO_HEIGHT,width:"auto",maxWidth:LOGO_MAX_WIDTH,objectFit:"contain"});function BrandLogo({logoUrl:logoUrl,name:name,styles:styles}){/* @__PURE__ */
190
+ return jsxRuntime.jsx(BrandImage,{src:logoUrl,alt:name,height:LOGO_HEIGHT,style:styles?.logo??LOGO_STYLE})}function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function ownGroundSlot(slot){return slot===void 0||slot.backgroundColor!==void 0?slot:slot.borderRadius===void 0?void 0:{borderRadius:slot.borderRadius}}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function slotBoxCss(slot,borderWidth){let box=slotBox(slot,borderWidth),out={};return box.backgroundColor!==void 0&&(out.backgroundColor=box.backgroundColor),box.borderColor!==void 0&&(out.border=`${box.borderWidth??1}px solid ${box.borderColor}`),box.borderRadius!==void 0&&(out.borderRadius=box.borderRadius),out}function slotCss(slot,borderWidth){return{...slotBoxCss(slot,borderWidth),...slotText(slot)}}function sheetSlotCss(slot,borderWidth){let css=slotCss(slot,borderWidth),radius=slot?.borderRadius;return radius===void 0?css:{...css,borderRadius:`${radius}px ${radius}px 0 0`}}function slotRadius(slot){return slot?.borderRadius===void 0?{}:{borderRadius:slot.borderRadius}}var MIN_TOUCH_TARGET2=44,ROW_AVATAR_SIZE=44,ROW_RING_SIZE=48,CHECK_SIZE=18,SHEET_RADIUS=22,SHEET_MAX_HEIGHT="80vh";function PetSwitcherDialog(props){let{open:open,pets:pets,activePetRef:activePetRef,onClose:onClose,onSelect:onSelect,onAddPet:onAddPet=null,returnFocusTo:returnFocusTo}=props,theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles3(theme),[theme]),dialog=useModalDialog(open,onClose,returnFocusTo),everfurLook=isEverfurLightLook(theme);return open?/* @__PURE__ */jsxRuntime.jsxs("dialog",{ref:dialog.dialogRef,"aria-label":CHAT_COPY.yourPets,onCancel:dialog.onCancel,onKeyDown:dialog.onKeyDown,style:styles.sheet,children:[
190
191
  /* @__PURE__ */jsxRuntime.jsx("h2",{style:styles.title,children:CHAT_COPY.yourPets}),
191
192
  /* @__PURE__ */jsxRuntime.jsx("ul",{style:styles.list,children:pets.map(pet=>{let active=pet.petRef===activePetRef,name=pet.name?.trim()||CHAT_COPY.yourPet,initials=petDiscPaint(pet,everfurLook,{fill:theme.color.highlight,ink:theme.color.onHighlight});/* @__PURE__ */
192
193
  return jsxRuntime.jsx("li",{children:/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button","aria-current":active?"true":void 0,"aria-label":fillCopy(active?CHAT_COPY.petCurrentlyActive:CHAT_COPY.switchToPet,{name:name}),onClick:()=>onSelect(pet.petRef),style:{...styles.row,...active?styles.rowActive:null},children:[
@@ -196,43 +197,43 @@ return jsxRuntime.jsx("li",{children:/* @__PURE__ */jsxRuntime.jsxs("button",{ty
196
197
  /* @__PURE__ */jsxRuntime.jsx("span",{style:styles.meta,children:`${active?CHAT_COPY.activePrefix:""}${formatPetMeta(pet)}`})]}),active?/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"check",size:CHECK_SIZE,color:theme.color.brandInk,strokeWidth:2.5}):null]})},pet.petRef)})}),onAddPet!==null?/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button","aria-label":CHAT_COPY.addAnotherPet,onClick:onAddPet,style:styles.addRow,children:[
197
198
  /* @__PURE__ */jsxRuntime.jsx("span",{style:styles.addDisc,children:"+"}),
198
199
  /* @__PURE__ */jsxRuntime.jsx("span",{style:styles.addLabel,children:CHAT_COPY.addAnotherPet})]}):null,
199
- /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onClose,style:styles.close,children:CHAT_COPY.close})]}):null}function makeStyles3(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type;return{sheet:{boxSizing:"border-box",position:"fixed",top:"auto",right:0,bottom:0,left:0,margin:0,width:"100%",maxWidth:"100%",maxHeight:SHEET_MAX_HEIGHT,overflowY:"auto",padding:`${s.lg+4}px ${s.lg+4}px ${s.xxl}px`,border:0,borderRadius:`${SHEET_RADIUS}px ${SHEET_RADIUS}px 0 0`,backgroundColor:c.surface,color:c.text.primary,display:"flex",flexDirection:"column",gap:s.md+2},title:{margin:0,...faceCss(theme,"bold"),fontSize:t.tierSizes.heading.heading,lineHeight:`${Math.round(t.tierSizes.heading.heading*1.22)}px`,color:c.brandInk},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:s.sm},row:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET2,display:"flex",flexDirection:"row",alignItems:"center",gap:s.md,margin:0,padding:s.md,borderRadius:r.md,border:`1px solid ${c.brandBorder}`,backgroundColor:c.surfaceCream,color:c.text.primary,textAlign:"left",cursor:"pointer",font:"inherit"},rowActive:{border:`1px solid ${c.brandInk}`,backgroundColor:c.brandSoft},ring:{boxSizing:"border-box",flexShrink:0,width:ROW_RING_SIZE,height:ROW_RING_SIZE,borderRadius:r.pill,border:`2px solid ${c.mark}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:ROW_AVATAR_SIZE,height:ROW_AVATAR_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:Math.round(ROW_AVATAR_SIZE*.42),lineHeight:1,textTransform:"uppercase"},text:{flex:"1 1 auto",minWidth:0,display:"flex",flexDirection:"column",gap:2},name:{...faceCss(theme,"bold"),fontSize:t.size.body+1,lineHeight:`${t.size.body+4}px`,color:c.text.primary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},meta:{...faceCss(theme,"monoBold"),fontSize:t.tierSizes.compact.tiny,lineHeight:`${t.tierSizes.compact.tiny+2}px`,letterSpacing:.4,textTransform:"uppercase",color:c.text.muted},addRow:{boxSizing:"border-box",display:"flex",alignItems:"center",gap:s.sm,width:"100%",minHeight:MIN_TOUCH_TARGET2,padding:`${s.xs}px ${s.sm}px`,background:"none",border:"none",borderRadius:r.lg,cursor:"pointer",textAlign:"left"},addDisc:{boxSizing:"border-box",width:ROW_RING_SIZE,height:ROW_RING_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",border:`2px dashed ${c.brandBorder}`,backgroundColor:c.surfaceCream,color:c.brandInk,fontSize:t.size.subtitle,lineHeight:1},addLabel:{...faceCss(theme,"bold"),fontSize:t.size.body,color:c.text.primary},close:{boxSizing:"border-box",alignSelf:"center",minHeight:MIN_TOUCH_TARGET2,minWidth:MIN_TOUCH_TARGET2,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${s.xl}px`,borderRadius:r.pill,border:`1px solid ${c.brandBorder}`,backgroundColor:c.surface,color:c.text.primary,cursor:"pointer",...faceCss(theme,"medium"),fontSize:t.tierSizes.control.body}}}var HEADER_AVATAR_SIZE=35,RING_WIDTH=1.75,AVATAR_INNER_SIZE=HEADER_AVATAR_SIZE-RING_WIDTH*2,ADD_BADGE_SIZE=12.4,MENU_BUTTON_SIZE=36,HISTORY_GLYPH_SIZE=20,UNREAD_DOT_SIZE=9,UNREAD_DOT_RING=1.5,MIN_TOUCH_TARGET3=44,LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160;function ChatHeader(props){let{pets:pets,activePet:activePet,unread:unread,onOpenHistory:onOpenHistory,historyTriggerRef:historyTriggerRef,onSelectPet:onSelectPet,onAddPet:onAddPet=null,vetEntry:vetEntry=null}=props,{rail:rail=false,historyOpen:historyOpen=false,onNewChat:onNewChat}=props,theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles4(theme),[theme]),historyControls=/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.historyControls,children:[onNewChat!==void 0?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onNewChat,"aria-label":HISTORY_COPY.newChat,style:styles.menuButton,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"squarePen",size:HISTORY_GLYPH_SIZE,color:theme.color.text.primary})}):null,
200
+ /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onClose,style:styles.close,children:CHAT_COPY.close})]}):null}function makeStyles3(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type;return{sheet:{boxSizing:"border-box",position:"fixed",top:"auto",right:0,bottom:0,left:0,margin:0,width:"100%",maxWidth:"100%",maxHeight:SHEET_MAX_HEIGHT,overflowY:"auto",padding:`${s.lg+4}px ${s.lg+4}px ${s.xxl}px`,border:0,borderRadius:`${SHEET_RADIUS}px ${SHEET_RADIUS}px 0 0`,backgroundColor:c.surface,color:c.text.primary,display:"flex",flexDirection:"column",gap:s.md+2,...sheetSlotCss(theme.slots.dialog)},title:{margin:0,...headingFaceCss(theme,"bold"),fontSize:t.tierSizes.heading.heading,lineHeight:`${Math.round(t.tierSizes.heading.heading*1.22)}px`,color:c.brandInk,...slotText(theme.slots.dialog)},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:s.sm},row:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET2,display:"flex",flexDirection:"row",alignItems:"center",gap:s.md,margin:0,padding:s.md,borderRadius:r.md,border:`1px solid ${c.brandBorder}`,backgroundColor:c.surfaceCream,color:c.text.primary,textAlign:"left",cursor:"pointer",font:"inherit"},rowActive:{border:`1px solid ${c.brandInk}`,backgroundColor:c.brandSoft},ring:{boxSizing:"border-box",flexShrink:0,width:ROW_RING_SIZE,height:ROW_RING_SIZE,borderRadius:r.pill,border:`2px solid ${c.mark}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:ROW_AVATAR_SIZE,height:ROW_AVATAR_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:Math.round(ROW_AVATAR_SIZE*.42),lineHeight:1,textTransform:"uppercase"},text:{flex:"1 1 auto",minWidth:0,display:"flex",flexDirection:"column",gap:2},name:{...faceCss(theme,"bold"),fontSize:t.size.body+1,lineHeight:`${t.size.body+4}px`,color:c.text.primary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},meta:{...faceCss(theme,"monoBold"),fontSize:t.tierSizes.compact.tiny,lineHeight:`${t.tierSizes.compact.tiny+2}px`,letterSpacing:.4,textTransform:"uppercase",color:c.text.muted},addRow:{boxSizing:"border-box",display:"flex",alignItems:"center",gap:s.sm,width:"100%",minHeight:MIN_TOUCH_TARGET2,padding:`${s.xs}px ${s.sm}px`,background:"none",border:"none",borderRadius:r.lg,cursor:"pointer",textAlign:"left"},addDisc:{boxSizing:"border-box",width:ROW_RING_SIZE,height:ROW_RING_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",border:`2px dashed ${c.brandBorder}`,backgroundColor:c.surfaceCream,color:c.brandInk,fontSize:t.size.subtitle,lineHeight:1},addLabel:{...faceCss(theme,"bold"),fontSize:t.size.body,color:c.text.primary,...slotText(theme.slots.dialog)},close:{boxSizing:"border-box",alignSelf:"center",minHeight:MIN_TOUCH_TARGET2,minWidth:MIN_TOUCH_TARGET2,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${s.xl}px`,borderRadius:r.pill,border:`1px solid ${c.brandBorder}`,backgroundColor:c.surface,color:c.text.primary,cursor:"pointer",...faceCss(theme,"medium"),fontSize:t.tierSizes.control.body}}}var HEADER_AVATAR_SIZE=35,RING_WIDTH=1.75,AVATAR_INNER_SIZE=HEADER_AVATAR_SIZE-RING_WIDTH*2,ADD_BADGE_SIZE=12.4,MENU_BUTTON_SIZE=36,HISTORY_GLYPH_SIZE=20,UNREAD_DOT_SIZE=9,UNREAD_DOT_RING=1.5,MIN_TOUCH_TARGET3=44;function ChatHeader(props){let{pets:pets,activePet:activePet,unread:unread,onOpenHistory:onOpenHistory,historyTriggerRef:historyTriggerRef,onSelectPet:onSelectPet,onAddPet:onAddPet=null,vetEntry:vetEntry=null}=props,{rail:rail=false,historyOpen:historyOpen=false,onNewChat:onNewChat}=props,theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles4(theme),[theme]),glyphInk=theme.slots.header?.textColor??theme.color.text.primary,historyControls=/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.historyControls,children:[onNewChat!==void 0?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onNewChat,"aria-label":HISTORY_COPY.newChat,style:styles.menuButton,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"squarePen",size:HISTORY_GLYPH_SIZE,color:glyphInk})}):null,
200
201
  /* @__PURE__ */jsxRuntime.jsx("button",{ref:historyTriggerRef,type:"button",onClick:onOpenHistory,"aria-label":historyControlLabel(rail,historyOpen,unread),"aria-expanded":historyOpen,style:styles.menuButton,children:/* @__PURE__ */jsxRuntime.jsxs("span",{"aria-hidden":"true",style:styles.menuDisc,children:[
201
- /* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"history",size:HISTORY_GLYPH_SIZE,color:theme.color.text.primary}),unread?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.unreadDot}):null]})})]});/* @__PURE__ */
202
+ /* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"history",size:HISTORY_GLYPH_SIZE,color:glyphInk}),unread?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.unreadDot}):null]})})]});/* @__PURE__ */
202
203
  return jsxRuntime.jsxs("header",{style:styles.bar,children:[rail?null:historyControls,
203
204
  /* @__PURE__ */jsxRuntime.jsx("div",{style:styles.centre,children:/* @__PURE__ */jsxRuntime.jsx(BrandLogo,{logoUrl:theme.meta.logoUrl,name:theme.meta.displayName,styles:styles})}),vetEntry!==null?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:vetEntry,style:styles.vetEntry,children:TELEVET_COPY.visitButton}):null,
204
- /* @__PURE__ */jsxRuntime.jsx(PetAvatarSlot,{pets:pets,activePet:activePet,styles:styles,onSelectPet:onSelectPet,onAddPet:onAddPet}),rail?historyControls:null]})}function historyControlLabel(rail,open,unread){let base=rail?open?CHAT_COPY.hideChatsWeb:CHAT_COPY.showChatsWeb:CHAT_COPY.openHistoryWeb;return unread?`${base}${CHAT_COPY.newReplySuffix}`:base}function BrandLogo({logoUrl:logoUrl,name:name,styles:styles}){let[failed,setFailed]=react.useState(null);return logoUrl===null||failed===logoUrl?null:/* @__PURE__ */jsxRuntime.jsx("img",{src:logoUrl,alt:name,height:LOGO_HEIGHT,style:styles.logo,decoding:"async",referrerPolicy:"no-referrer",onError:()=>setFailed(logoUrl)})}function PetAvatarSlot({pets:pets,activePet:activePet,styles:styles,onSelectPet:onSelectPet,onAddPet:onAddPet}){let[open,setOpen]=react.useState(false),triggerRef=react.useRef(null),name=activePet?.name?.trim()||CHAT_COPY.yourPet;return pets.length<2&&onAddPet===null||activePet===null?/* @__PURE__ */jsxRuntime.jsx("div",{role:"img","aria-label":name,style:styles.avatarSlot,children:/* @__PURE__ */jsxRuntime.jsx(AvatarRing,{pet:activePet,styles:styles})}):/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.avatarSlot,children:[
205
+ /* @__PURE__ */jsxRuntime.jsx(PetAvatarSlot,{pets:pets,activePet:activePet,styles:styles,onSelectPet:onSelectPet,onAddPet:onAddPet}),rail?historyControls:null]})}function historyControlLabel(rail,open,unread){let base=rail?open?CHAT_COPY.hideChatsWeb:CHAT_COPY.showChatsWeb:CHAT_COPY.openHistoryWeb;return unread?`${base}${CHAT_COPY.newReplySuffix}`:base}function PetAvatarSlot({pets:pets,activePet:activePet,styles:styles,onSelectPet:onSelectPet,onAddPet:onAddPet}){let[open,setOpen]=react.useState(false),triggerRef=react.useRef(null),name=activePet?.name?.trim()||CHAT_COPY.yourPet;return pets.length<2&&onAddPet===null||activePet===null?/* @__PURE__ */jsxRuntime.jsx("div",{role:"img","aria-label":name,style:styles.avatarSlot,children:/* @__PURE__ */jsxRuntime.jsx(AvatarRing,{pet:activePet,styles:styles})}):/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.avatarSlot,children:[
205
206
  /* @__PURE__ */jsxRuntime.jsxs("button",{ref:triggerRef,type:"button","aria-haspopup":"dialog","aria-expanded":open,"aria-label":fillCopy(CHAT_COPY.switchActivePet,{name:name}),onClick:()=>setOpen(true),style:styles.avatarButton,children:[
206
207
  /* @__PURE__ */jsxRuntime.jsx(AvatarRing,{pet:activePet,styles:styles}),
207
208
  /* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.addBadge,children:/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.addBadgeGlyph,children:"+"})})]}),
208
209
  /* @__PURE__ */jsxRuntime.jsx(PetSwitcherDialog,{open:open,pets:pets,activePetRef:activePet.petRef,returnFocusTo:triggerRef,onClose:()=>setOpen(false),onSelect:petRef2=>{setOpen(false),onSelectPet(petRef2)},onAddPet:onAddPet===null?null:()=>{setOpen(false),onAddPet()}})]})}function AvatarRing({pet:pet,styles:styles}){let theme=useEverfurTheme(),palette=pet===null?null:petDiscPaint(pet,isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight});/* @__PURE__ */
209
- return jsxRuntime.jsx("span",{style:styles.ring,children:/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.disc,...palette===null?styles.discEmpty:{backgroundColor:palette.background,color:palette.foreground}},children:palette===null?getInitial(null):palette.initial})})}function makeStyles4(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type;return{vetEntry:{boxSizing:"border-box",minHeight:44,padding:`0 ${s.md}px`,borderRadius:r.pill,backgroundColor:c.surfaceCream,border:`1px solid ${c.controlEdge}`,color:c.brandInk,cursor:"pointer",whiteSpace:"nowrap",...faceCss(theme,"bold"),fontSize:t.size.caption},bar:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm+2}px ${s.lg}px`,backgroundColor:c.surfaceCream},menuButton:{boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",cursor:"pointer",color:c.text.primary},menuDisc:{position:"relative",boxSizing:"border-box",width:MENU_BUTTON_SIZE,height:MENU_BUTTON_SIZE,borderRadius:r.pill,display:"inline-flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4},historyControls:{display:"flex",flexDirection:"row",alignItems:"center",flexShrink:0},unreadDot:{position:"absolute",top:6,right:6,boxSizing:"border-box",width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:r.pill,backgroundColor:c.danger,border:`${UNREAD_DOT_RING}px solid ${c.surfaceCream}`},centre:{flex:"1 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"center"},logo:{display:"block",height:LOGO_HEIGHT,width:"auto",maxWidth:LOGO_MAX_WIDTH,objectFit:"contain"},avatarSlot:{position:"relative",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center"},avatarButton:{position:"relative",boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer"},ring:{boxSizing:"border-box",width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,borderRadius:r.pill,border:`${RING_WIDTH}px solid ${c.mark}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:AVATAR_INNER_SIZE,height:AVATAR_INNER_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:Math.round(AVATAR_INNER_SIZE*.42),lineHeight:1,textTransform:"uppercase"},discEmpty:{backgroundColor:c.surfaceSubtle,color:c.text.muted},addBadge:{position:"absolute",bottom:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,right:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,boxSizing:"border-box",width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:r.pill,border:`0.5px solid ${c.mark}`,backgroundColor:c.surface,display:"inline-flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},addBadgeGlyph:{...faceCss(theme,"bold"),fontSize:t.tierSizes.badge.small,lineHeight:1,color:c.brandInk}}}var STATIC=/* @__PURE__ */Object.freeze({kind:"static"}),CitationLinkContext=react.createContext(STATIC);function useCitationLinks(){return react.useContext(CitationLinkContext)}function useCitationLinkMode(onOpenUrl){return react.useMemo(()=>onOpenUrl===void 0?STATIC:/* @__PURE__ */Object.freeze({kind:"host",open:url=>{callHost(onOpenUrl,url,"citation")}}),[onOpenUrl])}function CitationLinksScope({onOpenUrl:onOpenUrl,children:children}){let mode=useCitationLinkMode(onOpenUrl);return react.createElement(CitationLinkContext.Provider,{value:mode},children)}function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function ownGroundSlot(slot){return slot===void 0||slot.backgroundColor!==void 0?slot:slot.borderRadius===void 0?void 0:{borderRadius:slot.borderRadius}}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function slotBoxCss(slot,borderWidth){let box=slotBox(slot,borderWidth),out={};return box.backgroundColor!==void 0&&(out.backgroundColor=box.backgroundColor),box.borderColor!==void 0&&(out.border=`${box.borderWidth??1}px solid ${box.borderColor}`),box.borderRadius!==void 0&&(out.borderRadius=box.borderRadius),out}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);react.createContext(NESTED_HEADING_LEVEL_DEFAULT);var HISTORY_PANEL_WIDTH=320,MIN_THREAD_WIDTH=480,RAIL_MIN_CONTAINER_WIDTH=HISTORY_PANEL_WIDTH+MIN_THREAD_WIDTH,DESKTOP_MIN_CONTAINER_WIDTH=1024,CHAT_COLUMN_MAX_WIDTH=768,ASSISTANT_MEASURE="72ch",NARROW_LAYOUT=/* @__PURE__ */Object.freeze({rail:false,desktop:false}),RAIL_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:false}),DESKTOP_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:true});function layoutFor(width){return width===null||width<RAIL_MIN_CONTAINER_WIDTH?NARROW_LAYOUT:width>=DESKTOP_MIN_CONTAINER_WIDTH?DESKTOP_LAYOUT:RAIL_LAYOUT}var ChatLayoutContext=react.createContext({layout:NARROW_LAYOUT,report:()=>{},headingLevel:headingLevel(void 0)});function useChatLayout(){return react.useContext(ChatLayoutContext).layout}function useChatHeadingLevel(){return react.useContext(ChatLayoutContext).headingLevel}function ChatLayoutScope({children:children,headingLevel:hostLevel}){let[layout,setLayout]=react.useState(NARROW_LAYOUT),level=headingLevel(hostLevel),value=react.useMemo(()=>({layout:layout,report:setLayout,headingLevel:level}),[layout,level]);return react.createElement(ChatLayoutContext.Provider,{value:value},children)}function useMeasuredLayout(root){let{report:report}=react.useContext(ChatLayoutContext);react.useEffect(()=>{let node=root.current;if(node===null||typeof ResizeObserver>"u")return;let read=()=>{let width=node.getBoundingClientRect().width;report(layoutFor(width>0?Math.round(width):null))};read();let observer=new ResizeObserver(read);return observer.observe(node),()=>observer.disconnect()},[root,report])}var CHAT_EASING=/* @__PURE__ */Object.freeze({standard:EASING_CURVES.standard,emphasized:EASING_CURVES.emphasized,exit:EASING_CURVES.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])}),cubicBezier=cssCubicBezier,CHAT_MOTION=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),CHAT_MOTION_REDUCED=/* @__PURE__ */Object.freeze({...CHAT_MOTION,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function chatMotion(theme){return theme.motion.reducedMotion?CHAT_MOTION_REDUCED:CHAT_MOTION}function followUpDelayMs(motion,index){return Math.max(0,index)*motion.followUpStaggerMs}function nextRevealLength(motion,visible,total){if(motion.reduced||visible>=total)return total;let step=Math.max(1,Math.ceil((total-visible)/motion.revealDivisor));return Math.min(total,visible+step)}function useChatMotion(){let theme=useEverfurTheme();return react.useMemo(()=>chatMotion(theme),[theme])}function canAnimate(node){return node!==null&&typeof node.animate=="function"}function animateEnter(node,motion){if(!canAnimate(node)||motion.durationMs<=0)return null;let translate=[motion.fromTranslateX!==void 0?`translateX(${motion.fromTranslateX})`:"",motion.fromTranslateY!==void 0&&motion.fromTranslateY!==0?`translateY(${motion.fromTranslateY}px)`:""].filter(part=>part.length>0).join(" "),from={...motion.fromOpacity!==void 0?{opacity:motion.fromOpacity}:{},...translate.length>0?{transform:translate}:{}},to={...motion.fromOpacity!==void 0?{opacity:1}:{},...translate.length>0?{transform:"none"}:{}};try{return node.animate([from,to],{duration:motion.durationMs,delay:motion.delayMs??0,easing:cubicBezier(CHAT_EASING.standard),fill:"backwards"})}catch{return null}}function popIn(node,motion){if(!canAnimate(node)||motion.bubbleInMs<=0)return null;try{return node.animate([{opacity:0,transform:`translateY(${motion.bubbleRisePx}px) scale(${motion.bubbleFromScale})`},{opacity:1,transform:"none"}],{duration:motion.bubbleInMs,easing:cubicBezier(CHAT_EASING.out),fill:"backwards"})}catch{return null}}function animateExit(node,durationMs,toTranslateX){if(!canAnimate(node)||durationMs<=0)return Promise.resolve();try{let animation=node.animate([{opacity:1,transform:"none"},{opacity:0,...toTranslateX!==void 0?{transform:`translateX(${toTranslateX})`}:{}}],{duration:durationMs,easing:cubicBezier(CHAT_EASING.exit),fill:"forwards"});return new Promise(resolve=>{animation.onfinish=()=>resolve(),animation.oncancel=()=>resolve()})}catch{return Promise.resolve()}}function usePresence(show,exitMs){let[present2,setPresent]=react.useState(show),exiting=present2&&!show;return react.useEffect(()=>{if(show){setPresent(true);return}if(!present2)return;if(exitMs<=0){setPresent(false);return}let handle=setTimeout(()=>setPresent(false),exitMs);return()=>clearTimeout(handle)},[show,exitMs,present2]),{present:present2,exiting:exiting}}function useRevealedText(text3,active,motion){let[visible,setVisible]=react.useState(active&&!motion.reduced?0:text3.length),latest=react.useRef({text:text3,active:active});return latest.current={text:text3,active:active},react.useEffect(()=>{if(!active||motion.reduced||motion.revealTickMs<=0){setVisible(latest.current.text.length);return}let handle=setInterval(()=>{setVisible(current=>nextRevealLength(motion,current,latest.current.text.length))},motion.revealTickMs);return()=>clearInterval(handle)},[active,motion]),active&&!motion.reduced?text3.slice(0,Math.min(visible,text3.length)):text3}var MIN_TOUCH_TARGET4=44,DRAWER_MAX_WIDTH="85%",DRAWER_SHADOW={y:16,blur:48,alpha:.18},SCRIM_ALPHA=.32,UNREAD_DOT_SIZE2=8,ACTIVE_ROW_ALPHA=.22,SEARCH_EDGE_WIDTH=1.5,LOAD_MORE_MARGIN="50%";function HistoryDrawer({chat:chat,history:history,mode:mode,returnFocusTo:returnFocusTo}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles5(theme),[theme]),motion=useChatMotion(),dialog=useModalDialog(mode==="dialog"&&history.open,history.close,returnFocusTo),panelRef=react.useRef(null),open=history.open,slideMs=motion.drawerMs;if(react.useEffect(()=>{if(!open||mode!=="dialog")return;let animation=animateEnter(panelRef.current,{durationMs:slideMs,fromOpacity:0,fromTranslateX:"-100%"});return()=>animation?.cancel()},[open,mode,slideMs]),!open)return null;let body=/* @__PURE__ */jsxRuntime.jsx(PanelBody,{chat:chat,history:history,styles:styles,theme:theme,rail:mode==="rail"});return mode==="rail"?/* @__PURE__ */jsxRuntime.jsx("aside",{ref:node=>{panelRef.current=node},"aria-label":HISTORY_COPY.heading,style:styles.rail,children:body}):/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.scrim,onClick:history.close,children:/* @__PURE__ */jsxRuntime.jsx("div",{ref:node=>{dialog.dialogRef.current=node,panelRef.current=node},role:"dialog","aria-modal":"true","aria-label":HISTORY_COPY.heading,tabIndex:-1,onKeyDown:dialog.onKeyDown,onClick:event=>event.stopPropagation(),style:styles.overlay,children:body})})}function PanelBody({chat:chat,history:history,styles:styles,theme:theme,rail:rail}){let{rows:rows,filtered:filtered,loading:loading,loadingMore:loadingMore,error:error,cursor:cursor2,emptyKind:emptyKind,searching:searching,query:query,setQuery:setQuery}=history,showRows=!loading&&error===null,[searchFocused,setSearchFocused]=react.useState(false);/* @__PURE__ */
210
+ return jsxRuntime.jsx("span",{style:styles.ring,children:/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.disc,...palette===null?styles.discEmpty:{backgroundColor:palette.background,color:palette.foreground}},children:palette===null?getInitial(null):palette.initial})})}function makeStyles4(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,header=theme.slots.header;return{vetEntry:{boxSizing:"border-box",minHeight:44,padding:`0 ${s.md}px`,borderRadius:r.pill,backgroundColor:c.surfaceCream,border:`1px solid ${c.controlEdge}`,color:c.brandInk,cursor:"pointer",whiteSpace:"nowrap",...faceCss(theme,"bold"),fontSize:t.size.caption},bar:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm+2}px ${s.lg}px`,backgroundColor:c.surfaceCream,...slotCss(header)},menuButton:{boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",cursor:"pointer",color:header?.textColor??c.text.primary},menuDisc:{position:"relative",boxSizing:"border-box",width:MENU_BUTTON_SIZE,height:MENU_BUTTON_SIZE,borderRadius:r.pill,display:"inline-flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4},historyControls:{display:"flex",flexDirection:"row",alignItems:"center",flexShrink:0},unreadDot:{position:"absolute",top:6,right:6,boxSizing:"border-box",width:UNREAD_DOT_SIZE,height:UNREAD_DOT_SIZE,borderRadius:r.pill,backgroundColor:c.danger,border:`${UNREAD_DOT_RING}px solid ${header?.backgroundColor??c.surfaceCream}`},centre:{flex:"1 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"center"},logo:LOGO_STYLE,avatarSlot:{position:"relative",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center"},avatarButton:{position:"relative",boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET3,minHeight:MIN_TOUCH_TARGET3,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer"},ring:{boxSizing:"border-box",width:HEADER_AVATAR_SIZE,height:HEADER_AVATAR_SIZE,borderRadius:r.pill,border:`${RING_WIDTH}px solid ${c.mark}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:AVATAR_INNER_SIZE,height:AVATAR_INNER_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:Math.round(AVATAR_INNER_SIZE*.42),lineHeight:1,textTransform:"uppercase"},discEmpty:{backgroundColor:c.surfaceSubtle,color:c.text.muted},addBadge:{position:"absolute",bottom:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,right:(MIN_TOUCH_TARGET3-HEADER_AVATAR_SIZE)/2,boxSizing:"border-box",width:ADD_BADGE_SIZE,height:ADD_BADGE_SIZE,borderRadius:r.pill,border:`0.5px solid ${c.mark}`,backgroundColor:c.surface,display:"inline-flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},addBadgeGlyph:{...faceCss(theme,"bold"),fontSize:t.tierSizes.badge.small,lineHeight:1,color:c.brandInk}}}var STATIC=/* @__PURE__ */Object.freeze({kind:"static"}),CitationLinkContext=react.createContext(STATIC);function useCitationLinks(){return react.useContext(CitationLinkContext)}function useCitationLinkMode(onOpenUrl){return react.useMemo(()=>onOpenUrl===void 0?STATIC:/* @__PURE__ */Object.freeze({kind:"host",open:url=>{callHost(onOpenUrl,url,"citation")}}),[onOpenUrl])}function CitationLinksScope({onOpenUrl:onOpenUrl,children:children}){let mode=useCitationLinkMode(onOpenUrl);return react.createElement(CitationLinkContext.Provider,{value:mode},children)}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);react.createContext(NESTED_HEADING_LEVEL_DEFAULT);var HISTORY_PANEL_WIDTH=320,MIN_THREAD_WIDTH=480,RAIL_MIN_CONTAINER_WIDTH=HISTORY_PANEL_WIDTH+MIN_THREAD_WIDTH,DESKTOP_MIN_CONTAINER_WIDTH=1024,CHAT_COLUMN_MAX_WIDTH=768,ASSISTANT_MEASURE="72ch",NARROW_LAYOUT=/* @__PURE__ */Object.freeze({rail:false,desktop:false}),RAIL_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:false}),DESKTOP_LAYOUT=/* @__PURE__ */Object.freeze({rail:true,desktop:true});function layoutFor(width){return width===null||width<RAIL_MIN_CONTAINER_WIDTH?NARROW_LAYOUT:width>=DESKTOP_MIN_CONTAINER_WIDTH?DESKTOP_LAYOUT:RAIL_LAYOUT}var ChatLayoutContext=react.createContext({layout:NARROW_LAYOUT,report:()=>{},headingLevel:headingLevel(void 0)});function useChatLayout(){return react.useContext(ChatLayoutContext).layout}function useChatHeadingLevel(){return react.useContext(ChatLayoutContext).headingLevel}function ChatLayoutScope({children:children,headingLevel:hostLevel}){let[layout,setLayout]=react.useState(NARROW_LAYOUT),level=headingLevel(hostLevel),value=react.useMemo(()=>({layout:layout,report:setLayout,headingLevel:level}),[layout,level]);return react.createElement(ChatLayoutContext.Provider,{value:value},children)}function useMeasuredLayout(root){let{report:report}=react.useContext(ChatLayoutContext);react.useEffect(()=>{let node=root.current;if(node===null||typeof ResizeObserver>"u")return;let read=()=>{let width=node.getBoundingClientRect().width;report(layoutFor(width>0?Math.round(width):null))};read();let observer=new ResizeObserver(read);return observer.observe(node),()=>observer.disconnect()},[root,report])}var CHAT_EASING=/* @__PURE__ */Object.freeze({standard:EASING_CURVES.standard,emphasized:EASING_CURVES.emphasized,exit:EASING_CURVES.exit,outQuad:/* @__PURE__ */Object.freeze([.25,.46,.45,.94]),out:/* @__PURE__ */Object.freeze([.23,1,.32,1])}),cubicBezier=cssCubicBezier,CHAT_MOTION=/* @__PURE__ */Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:/* @__PURE__ */Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,bubbleInMs:280,bubbleFromScale:.94,bubbleRisePx:6,promptRisePx:8,reduced:false}),CHAT_MOTION_REDUCED=/* @__PURE__ */Object.freeze({...CHAT_MOTION,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,bubbleInMs:0,bubbleFromScale:1,bubbleRisePx:0,promptRisePx:0,reduced:true});function chatMotion(theme){return theme.motion.reducedMotion?CHAT_MOTION_REDUCED:CHAT_MOTION}function followUpDelayMs(motion,index){return Math.max(0,index)*motion.followUpStaggerMs}function nextRevealLength(motion,visible,total){if(motion.reduced||visible>=total)return total;let step=Math.max(1,Math.ceil((total-visible)/motion.revealDivisor));return Math.min(total,visible+step)}function useChatMotion(){let theme=useEverfurTheme();return react.useMemo(()=>chatMotion(theme),[theme])}function canAnimate(node){return node!==null&&typeof node.animate=="function"}function animateEnter(node,motion){if(!canAnimate(node)||motion.durationMs<=0)return null;let translate=[motion.fromTranslateX!==void 0?`translateX(${motion.fromTranslateX})`:"",motion.fromTranslateY!==void 0&&motion.fromTranslateY!==0?`translateY(${motion.fromTranslateY}px)`:""].filter(part=>part.length>0).join(" "),from={...motion.fromOpacity!==void 0?{opacity:motion.fromOpacity}:{},...translate.length>0?{transform:translate}:{}},to={...motion.fromOpacity!==void 0?{opacity:1}:{},...translate.length>0?{transform:"none"}:{}};try{return node.animate([from,to],{duration:motion.durationMs,delay:motion.delayMs??0,easing:cubicBezier(CHAT_EASING.standard),fill:"backwards"})}catch{return null}}function popIn(node,motion){if(!canAnimate(node)||motion.bubbleInMs<=0)return null;try{return node.animate([{opacity:0,transform:`translateY(${motion.bubbleRisePx}px) scale(${motion.bubbleFromScale})`},{opacity:1,transform:"none"}],{duration:motion.bubbleInMs,easing:cubicBezier(CHAT_EASING.out),fill:"backwards"})}catch{return null}}function animateExit(node,durationMs,toTranslateX){if(!canAnimate(node)||durationMs<=0)return Promise.resolve();try{let animation=node.animate([{opacity:1,transform:"none"},{opacity:0,...toTranslateX!==void 0?{transform:`translateX(${toTranslateX})`}:{}}],{duration:durationMs,easing:cubicBezier(CHAT_EASING.exit),fill:"forwards"});return new Promise(resolve=>{animation.onfinish=()=>resolve(),animation.oncancel=()=>resolve()})}catch{return Promise.resolve()}}function usePresence(show,exitMs){let[present2,setPresent]=react.useState(show),exiting=present2&&!show;return react.useEffect(()=>{if(show){setPresent(true);return}if(!present2)return;if(exitMs<=0){setPresent(false);return}let handle=setTimeout(()=>setPresent(false),exitMs);return()=>clearTimeout(handle)},[show,exitMs,present2]),{present:present2,exiting:exiting}}function useRevealedText(text3,active,motion){let[visible,setVisible]=react.useState(active&&!motion.reduced?0:text3.length),latest=react.useRef({text:text3,active:active});return latest.current={text:text3,active:active},react.useEffect(()=>{if(!active||motion.reduced||motion.revealTickMs<=0){setVisible(latest.current.text.length);return}let handle=setInterval(()=>{setVisible(current=>nextRevealLength(motion,current,latest.current.text.length))},motion.revealTickMs);return()=>clearInterval(handle)},[active,motion]),active&&!motion.reduced?text3.slice(0,Math.min(visible,text3.length)):text3}var MIN_TOUCH_TARGET4=44,DRAWER_MAX_WIDTH="85%",DRAWER_SHADOW={y:16,blur:48,alpha:.18},SCRIM_ALPHA=.32,UNREAD_DOT_SIZE2=8,ACTIVE_ROW_ALPHA=.22,SEARCH_EDGE_WIDTH=1.5,LOAD_MORE_MARGIN="50%";function HistoryDrawer({chat:chat,history:history,mode:mode,returnFocusTo:returnFocusTo}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles5(theme,mode==="dialog"),[theme,mode]),motion=useChatMotion(),dialog=useModalDialog(mode==="dialog"&&history.open,history.close,returnFocusTo),panelRef=react.useRef(null),open=history.open,slideMs=motion.drawerMs;if(react.useEffect(()=>{if(!open||mode!=="dialog")return;let animation=animateEnter(panelRef.current,{durationMs:slideMs,fromOpacity:0,fromTranslateX:"-100%"});return()=>animation?.cancel()},[open,mode,slideMs]),!open)return null;let body=/* @__PURE__ */jsxRuntime.jsx(PanelBody,{chat:chat,history:history,styles:styles,theme:theme,rail:mode==="rail"});return mode==="rail"?/* @__PURE__ */jsxRuntime.jsx("aside",{ref:node=>{panelRef.current=node},"aria-label":HISTORY_COPY.heading,style:styles.rail,children:body}):/* @__PURE__ */jsxRuntime.jsx("div",{style:styles.scrim,onClick:history.close,children:/* @__PURE__ */jsxRuntime.jsx("div",{ref:node=>{dialog.dialogRef.current=node,panelRef.current=node},role:"dialog","aria-modal":"true","aria-label":HISTORY_COPY.heading,tabIndex:-1,onKeyDown:dialog.onKeyDown,onClick:event=>event.stopPropagation(),style:styles.overlay,children:body})})}function PanelBody({chat:chat,history:history,styles:styles,theme:theme,rail:rail}){let{rows:rows,filtered:filtered,loading:loading,loadingMore:loadingMore,error:error,cursor:cursor2,emptyKind:emptyKind,searching:searching,query:query,setQuery:setQuery}=history,showRows=!loading&&error===null,[searchFocused,setSearchFocused]=react.useState(false),closeInk=(rail?void 0:theme.slots.dialog?.textColor)??theme.color.brandInk,searchInk=theme.slots.input?.textColor??theme.color.text.muted;/* @__PURE__ */
210
211
  return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
211
212
  /* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.head,children:[
212
213
  /* @__PURE__ */jsxRuntime.jsx("p",{style:styles.heading,children:HISTORY_COPY.heading}),
213
214
  /* @__PURE__ */jsxRuntime.jsxs("button",{type:"button",onClick:history.newConversation,style:styles.newChat,children:[
214
215
  /* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"squarePen",size:16,color:theme.color.onPrimary}),
215
216
  /* @__PURE__ */jsxRuntime.jsx("span",{children:HISTORY_COPY.newChat})]}),
216
- /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:history.close,"aria-label":rail?CHAT_COPY.hideChatsWeb:HISTORY_COPY.close,style:styles.roundControl,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"x",size:18,color:theme.color.brandInk})})]}),
217
+ /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:history.close,"aria-label":rail?CHAT_COPY.hideChatsWeb:HISTORY_COPY.close,style:styles.roundControl,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"x",size:18,color:closeInk})})]}),
217
218
  /* @__PURE__ */jsxRuntime.jsxs("label",{style:{...styles.searchPill,...searchFocused?{borderColor:theme.color.brandInk,...focusRingStyle(theme.color.brandInk)}:null},children:[
218
- /* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"search",size:16,color:theme.color.text.muted}),
219
+ /* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"search",size:16,color:searchInk}),
219
220
  /* @__PURE__ */jsxRuntime.jsx("input",{type:"search",value:query,onChange:event=>setQuery(event.target.value),onFocus:()=>setSearchFocused(true),onBlur:()=>setSearchFocused(false),"data-ef-focus-ring":"self","aria-label":HISTORY_COPY.search,placeholder:HISTORY_COPY.searchPlaceholder,autoComplete:"off",style:styles.searchInput})]}),showRows&&rows.length>0?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.count,children:historyCountLabel(rows.length,cursor2===null)}):null,loading?/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",style:styles.state,children:HISTORY_COPY.loading}):null,error!==null?/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.stateBlock,children:[
220
221
  /* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.state,children:HISTORY_COPY.loadFailed}),
221
222
  /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:()=>{history.load()},style:styles.retryControl,children:HISTORY_COPY.retry})]}):null,showRows&&filtered.length===0?/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.stateBlock,children:[
222
223
  /* @__PURE__ */jsxRuntime.jsx("p",{style:styles.state,children:emptyKind==="noMatch"?HISTORY_COPY.noMatch:HISTORY_COPY.empty}),emptyKind==="noMatch"?null:/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.stateBody,children:HISTORY_COPY.emptyBody})]}):null,showRows&&filtered.length>0?/* @__PURE__ */jsxRuntime.jsx(RowList,{rows:filtered,activeId:chat.conversationId,onSelect:id=>{history.resume(id)},styles:styles,canLoadMore:cursor2!==null&&!searching&&!loadingMore,onLoadMore:history.loadMore}):null,loadingMore?/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",style:styles.state,children:HISTORY_COPY.loadingMore}):null]})}function RowList({rows:rows,activeId:activeId,onSelect:onSelect,styles:styles,canLoadMore:canLoadMore,onLoadMore:onLoadMore}){let sentinel=react.useRef(null),observable=typeof IntersectionObserver=="function",loadMore=react.useRef(onLoadMore);loadMore.current=onLoadMore;let observe=react.useCallback(node=>{sentinel.current=node},[]);return react.useEffect(()=>{let node=sentinel.current;if(!observable||!canLoadMore||node===null)return;let observer=new IntersectionObserver(entries=>{entries.some(entry=>entry.isIntersecting)&&loadMore.current()},{rootMargin:LOAD_MORE_MARGIN});return observer.observe(node),()=>observer.disconnect()},[observable,canLoadMore,rows.length]),/* @__PURE__ */jsxRuntime.jsxs("ul",{style:styles.list,children:[rows.map(row=>{let unread=row.unreadCount!==null&&row.unreadCount>0,active=row.id===activeId,meta=conversationMeta(row);/* @__PURE__ */
223
224
  return jsxRuntime.jsx("li",{children:/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button","aria-label":openConversationLabel(row),"aria-current":active?"true":void 0,onClick:()=>onSelect(row.id),style:{...styles.row,...active?styles.rowActive:null},children:[
224
225
  /* @__PURE__ */jsxRuntime.jsxs("span",{style:styles.rowText,children:[
225
- /* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowTitle,children:conversationTitle(row.title)}),meta!==null?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowMeta,...unread?styles.rowMetaUnread:null},children:meta}):null]}),unread?/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.unreadDot}):null]})},row.id)}),canLoadMore?/* @__PURE__ */jsxRuntime.jsx("li",{ref:observe,style:styles.sentinel,children:observable?null:/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onLoadMore,style:styles.textControl,children:HISTORY_COPY.more})}):null]})}function makeStyles5(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,control=t.tierSizes.control,ink=c.text.primary,panel={boxSizing:"border-box",display:"flex",flexDirection:"column",gap:s.md,padding:`${s.lg}px ${s.lg}px ${s.lg}px`,backgroundColor:c.surface,color:ink,overflowY:"auto"},textControl={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET4,minWidth:MIN_TOUCH_TARGET4,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${s.md}px`,borderRadius:r.pill,border:`1px solid ${c.brandInk}`,background:"transparent",color:c.brandInk,cursor:"pointer",...faceCss(theme,"medium"),fontSize:control.body};return{rail:{...panel,flex:`0 0 ${HISTORY_PANEL_WIDTH}px`,width:HISTORY_PANEL_WIDTH,minHeight:0,borderLeft:`1px solid ${c.borderRingCream}`},scrim:{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden",zIndex:1,backgroundColor:withAlpha(c.shadow,SCRIM_ALPHA)??"transparent"},overlay:{...panel,position:"absolute",top:0,bottom:0,left:0,margin:0,width:HISTORY_PANEL_WIDTH,maxWidth:DRAWER_MAX_WIDTH,border:0,borderRadius:0,boxShadow:`0 ${DRAWER_SHADOW.y}px ${DRAWER_SHADOW.blur}px ${withAlpha(c.brand,DRAWER_SHADOW.alpha)??"transparent"}`,outline:"none"},head:{display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm},heading:{margin:0,marginRight:"auto",...faceCss(theme,"bold"),fontSize:t.tierSizes.heading.subtitle,lineHeight:`${Math.round(t.tierSizes.heading.subtitle*t.lineHeight.snug)}px`,color:ink},newChat:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET4,display:"inline-flex",alignItems:"center",gap:s.xs+2,margin:0,padding:`0 ${s.lg}px`,border:0,borderRadius:r.pill,backgroundColor:c.primary,color:c.onPrimary,cursor:"pointer",...faceCss(theme,"bold"),fontSize:control.bodyTight,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},searchPill:{boxSizing:"border-box",minWidth:0,minHeight:MIN_TOUCH_TARGET4,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,padding:`0 ${s.md+s.xs/2}px`,borderRadius:r.pill,backgroundColor:c.surface,border:`${SEARCH_EDGE_WIDTH}px solid ${c.brandBorderStrong}`,color:c.text.primary},searchInput:{boxSizing:"border-box",flex:"1 1 auto",minWidth:0,minHeight:MIN_TOUCH_TARGET4-SEARCH_EDGE_WIDTH*2,margin:0,padding:0,border:0,outline:"none",background:"transparent",...faceCss(theme,"regular"),fontSize:Math.max(16,t.size.bodyTight),lineHeight:`${t.size.bodyTight+5}px`,color:c.text.primary},roundControl:{boxSizing:"border-box",flexShrink:0,width:MIN_TOUCH_TARGET4,height:MIN_TOUCH_TARGET4,minWidth:MIN_TOUCH_TARGET4,minHeight:MIN_TOUCH_TARGET4,margin:0,padding:0,border:0,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",background:"transparent",borderRadius:r.pill},count:{margin:`${s.xs}px 0 0`,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+5}px`,color:c.text.muted},state:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:`${t.size.bodyTight+5}px`,color:c.text.muted},stateBody:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+4}px`,color:c.text.muted},stateBlock:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.sm},textControl:textControl,retryControl:{...textControl,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},list:{listStyle:"none",margin:`0 -${s.md}px`,padding:0,display:"flex",flexDirection:"column",gap:2},row:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET4,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,margin:0,padding:`${s.sm+s.xs/2}px ${s.md}px`,border:0,borderRadius:r.md,background:"transparent",color:ink,textAlign:"left",cursor:"pointer",font:"inherit"},rowActive:{backgroundColor:withAlpha(c.highlight,ACTIVE_ROW_ALPHA)??"transparent"},rowText:{flex:"1 1 auto",minWidth:0,display:"flex",flexDirection:"column",gap:1},rowTitle:{...faceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*t.lineHeight.snug)}px`,color:c.brandInk,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},rowMeta:{...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+5}px`,color:c.text.muted},rowMetaUnread:{...faceCss(theme,"bold"),color:c.text.primary},unreadDot:{boxSizing:"border-box",flexShrink:0,width:UNREAD_DOT_SIZE2,height:UNREAD_DOT_SIZE2,borderRadius:r.pill,backgroundColor:c.danger},sentinel:{minHeight:1,display:"flex",justifyContent:"center",padding:`${s.xs}px 0`}}}function readOn(ink,grounds2,target){return pushToContrast(ink,grounds2,poleForGrounds(grounds2),target)}function themedUrgencyTier(tier,theme){if(tier.level==="emergency"||isEverfurLightLook(theme))return tier;let c=theme.color,caution=tier.level==="schedule_soon",fill=flattenOnto(caution?c.badgeBgCaution:c.brandSoft,c.surface)??c.surface,edgeFrom=caution?c.cautionAccent:c.structureEdge,borderColor=readOn(flattenOnto(edgeFrom,c.surface)??edgeFrom,[c.surface,c.chatGround],SLOT_MIN_BORDER_CONTRAST),textColor=readOn(caution?c.warningStrong:c.brandInk,[fill,c.surface],SLOT_MIN_CONTRAST);/* @__PURE__ */
226
- return Object.freeze({...tier,borderColor:borderColor,backgroundColor:fill,textColor:textColor,reasonColor:readOn(c.text.primary,[fill],SLOT_MIN_CONTRAST),pillColor:c.surface})}var MIN_TOUCH_TARGET5=44,DISMISS_SIZE=22,DISMISS_GLYPH_SIZE=14,INFO_GLYPH_SIZE=20,PIN_GLYPH_SIZE=16,ALERT_GLYPH_SIZE=20,BANNER_BORDER=1.5,ACTION_EDGE=1.5;function UrgencyBanner({surface:surface,vetEntry:vetEntry,renderVetAction:renderVetAction,onFindVet:onFindVet}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles6(theme),[theme]),motion=useChatMotion(),banner=usePresence(surface.showBanner,motion.bannerOutMs),icon=usePresence(surface.showCompactIcon,motion.iconOutMs);/* @__PURE__ */
226
+ /* @__PURE__ */jsxRuntime.jsx("span",{style:styles.rowTitle,children:conversationTitle(row.title)}),meta!==null?/* @__PURE__ */jsxRuntime.jsx("span",{style:{...styles.rowMeta,...unread?styles.rowMetaUnread:null},children:meta}):null]}),unread?/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.unreadDot}):null]})},row.id)}),canLoadMore?/* @__PURE__ */jsxRuntime.jsx("li",{ref:observe,style:styles.sentinel,children:observable?null:/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onLoadMore,style:styles.textControl,children:HISTORY_COPY.more})}):null]})}function makeStyles5(theme,drawer){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,control=t.tierSizes.control,dialogSlot=drawer?theme.slots.dialog:void 0,panelInk=slotText(dialogSlot),inputSlot=theme.slots.input,ink=c.text.primary,panel={boxSizing:"border-box",display:"flex",flexDirection:"column",gap:s.md,padding:`${s.lg}px ${s.lg}px ${s.lg}px`,backgroundColor:c.surface,color:ink,overflowY:"auto"},textControl={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET4,minWidth:MIN_TOUCH_TARGET4,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${s.md}px`,borderRadius:r.pill,border:`1px solid ${dialogSlot?.textColor??c.brandInk}`,background:"transparent",color:dialogSlot?.textColor??c.brandInk,cursor:"pointer",...faceCss(theme,"medium"),fontSize:control.body};return{rail:{...panel,flex:`0 0 ${HISTORY_PANEL_WIDTH}px`,width:HISTORY_PANEL_WIDTH,minHeight:0,borderLeft:`1px solid ${c.borderRingCream}`},scrim:{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden",zIndex:1,backgroundColor:withAlpha(c.shadow,SCRIM_ALPHA)??"transparent"},overlay:{...panel,position:"absolute",top:0,bottom:0,left:0,margin:0,width:HISTORY_PANEL_WIDTH,maxWidth:DRAWER_MAX_WIDTH,border:0,borderRadius:0,boxShadow:`0 ${DRAWER_SHADOW.y}px ${DRAWER_SHADOW.blur}px ${withAlpha(c.brand,DRAWER_SHADOW.alpha)??"transparent"}`,outline:"none",...slotCss(dialogSlot),...dialogSlot?.borderRadius===void 0?null:{borderRadius:`0 ${dialogSlot.borderRadius}px ${dialogSlot.borderRadius}px 0`}},head:{display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm},heading:{margin:0,marginRight:"auto",...headingFaceCss(theme,"bold"),fontSize:t.tierSizes.heading.subtitle,lineHeight:`${Math.round(t.tierSizes.heading.subtitle*t.lineHeight.snug)}px`,color:ink,...panelInk},newChat:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET4,display:"inline-flex",alignItems:"center",gap:s.xs+2,margin:0,padding:`0 ${s.lg}px`,border:0,borderRadius:r.pill,backgroundColor:c.primary,color:c.onPrimary,cursor:"pointer",...faceCss(theme,"bold"),fontSize:control.bodyTight,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},searchPill:{boxSizing:"border-box",minWidth:0,minHeight:MIN_TOUCH_TARGET4,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,padding:`0 ${s.md+s.xs/2}px`,borderRadius:r.pill,backgroundColor:c.surface,border:`${SEARCH_EDGE_WIDTH}px solid ${c.brandBorderStrong}`,color:c.text.primary,...slotCss(inputSlot,SEARCH_EDGE_WIDTH)},searchInput:{boxSizing:"border-box",flex:"1 1 auto",minWidth:0,minHeight:MIN_TOUCH_TARGET4-SEARCH_EDGE_WIDTH*2,margin:0,padding:0,border:0,outline:"none",background:"transparent",...faceCss(theme,"regular"),fontSize:Math.max(16,t.size.bodyTight),lineHeight:`${t.size.bodyTight+5}px`,color:c.text.primary,...slotText(inputSlot)},roundControl:{boxSizing:"border-box",flexShrink:0,width:MIN_TOUCH_TARGET4,height:MIN_TOUCH_TARGET4,minWidth:MIN_TOUCH_TARGET4,minHeight:MIN_TOUCH_TARGET4,margin:0,padding:0,border:0,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",background:"transparent",borderRadius:r.pill},count:{margin:`${s.xs}px 0 0`,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+5}px`,color:c.text.muted,...panelInk},state:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:`${t.size.bodyTight+5}px`,color:c.text.muted,...panelInk},stateBody:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+4}px`,color:c.text.muted,...panelInk},stateBlock:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.sm},textControl:textControl,retryControl:{...textControl,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},list:{listStyle:"none",margin:`0 -${s.md}px`,padding:0,display:"flex",flexDirection:"column",gap:2},row:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET4,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,margin:0,padding:`${s.sm+s.xs/2}px ${s.md}px`,border:0,borderRadius:r.md,background:"transparent",color:ink,textAlign:"left",cursor:"pointer",font:"inherit",...panelInk},rowActive:{backgroundColor:withAlpha(c.highlight,ACTIVE_ROW_ALPHA)??"transparent"},rowText:{flex:"1 1 auto",minWidth:0,display:"flex",flexDirection:"column",gap:1},rowTitle:{...faceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*t.lineHeight.snug)}px`,color:c.brandInk,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...panelInk},rowMeta:{...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${t.size.caption+5}px`,color:c.text.muted,...panelInk},rowMetaUnread:{...faceCss(theme,"bold"),color:c.text.primary,...panelInk},unreadDot:{boxSizing:"border-box",flexShrink:0,width:UNREAD_DOT_SIZE2,height:UNREAD_DOT_SIZE2,borderRadius:r.pill,backgroundColor:c.danger},sentinel:{minHeight:1,display:"flex",justifyContent:"center",padding:`${s.xs}px 0`}}}function readOn(ink,grounds2,target){return pushToContrast(ink,grounds2,poleForGrounds(grounds2),target)}function themedUrgencyTier(tier,theme){if(tier.level==="emergency")return tier;let caution=tier.level==="schedule_soon",branded=brandedStatus(theme),statusSet=caution?branded.warning:branded.info,painted=isEverfurLightLook(theme)&&!statusSet?tier:tokenPaint(tier,theme,caution);return withBannerSlot(painted,theme.slots.banner)}function tokenPaint(tier,theme,caution){let c=theme.color,fill=flattenOnto(caution?c.badgeBgCaution:c.badgeBgInfo,c.surface)??c.surface,edgeFrom=caution?c.cautionAccent:c.infoEdge,borderColor=readOn(flattenOnto(edgeFrom,c.surface)??edgeFrom,[c.surface,c.chatGround],SLOT_MIN_BORDER_CONTRAST),textColor=readOn(caution?c.warningStrong:c.info,[fill,c.surface],SLOT_MIN_CONTRAST);/* @__PURE__ */
227
+ return Object.freeze({...tier,borderColor:borderColor,backgroundColor:fill,textColor:textColor,reasonColor:readOn(c.text.primary,[fill],SLOT_MIN_CONTRAST),pillColor:c.surface})}function withBannerSlot(tier,slot){if(slot===void 0)return tier;let next={...tier};return slot.backgroundColor!==void 0&&(next.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(next.borderColor=slot.borderColor),slot.textColor!==void 0&&(next.textColor=slot.textColor,next.reasonColor=slot.textColor),/* @__PURE__ */Object.freeze(next)}var MIN_TOUCH_TARGET5=44,DISMISS_SIZE=22,DISMISS_GLYPH_SIZE=14,INFO_GLYPH_SIZE=20,PIN_GLYPH_SIZE=16,ALERT_GLYPH_SIZE=20,BANNER_BORDER=1.5,ACTION_EDGE=1.5;function UrgencyBanner({surface:surface,vetEntry:vetEntry,renderVetAction:renderVetAction,onFindVet:onFindVet}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles6(theme),[theme]),motion=useChatMotion(),banner=usePresence(surface.showBanner,motion.bannerOutMs),icon=usePresence(surface.showCompactIcon,motion.iconOutMs);/* @__PURE__ */
227
228
  return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[banner.present&&surface.tier!==null&&surface.source!==null?/* @__PURE__ */jsxRuntime.jsx(Banner,{surface:surface,exiting:banner.exiting,styles:styles,action:surface.showVetAction?/* @__PURE__ */jsxRuntime.jsx(VetAction,{tier:themedUrgencyTier(surface.tier,theme),styles:styles,vetEntry:vetEntry,renderVetAction:renderVetAction,onFindVet:onFindVet}):null},surface.signature??"banner"):null,icon.present?/* @__PURE__ */jsxRuntime.jsx(CompactIcon,{exiting:icon.exiting,onExpand:surface.expand,styles:styles}):null]})}function Banner({surface:surface,exiting:exiting,styles:styles,action:action}){let ref=react.useRef(null),motion=useChatMotion(),theme=useEverfurTheme();react.useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:motion.bannerInMs,fromOpacity:0});return()=>animation?.cancel()},[motion.bannerInMs]),react.useEffect(()=>{exiting&&animateExit(ref.current,motion.bannerOutMs)},[exiting,motion.bannerOutMs]);let source=surface.source;if(surface.tier===null||source===null)return null;let tier=themedUrgencyTier(surface.tier,theme),urgent=tier.level==="emergency"||tier.level==="schedule_soon",paint=tierPaint(tier,theme);/* @__PURE__ */
228
- return jsxRuntime.jsxs("div",{ref:ref,role:urgent?"alert":"status","aria-hidden":exiting?true:void 0,style:{...styles.banner,borderColor:paint.edge,backgroundColor:paint.fill},children:[
229
+ return jsxRuntime.jsxs("div",{ref:ref,role:urgent?"alert":"status","aria-hidden":exiting?true:void 0,style:{...styles.banner,borderColor:paint.edge,backgroundColor:paint.fill,...bannerRadius(tier,theme)},children:[
229
230
  /* @__PURE__ */jsxRuntime.jsxs("p",{style:{...styles.label,color:paint.title},children:[tier.level==="emergency"?/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"alert",size:ALERT_GLYPH_SIZE,color:paint.title}):null,
230
231
  /* @__PURE__ */jsxRuntime.jsx("span",{children:tier.label})]}),source.reason?/* @__PURE__ */jsxRuntime.jsx("p",{style:{...styles.reason,color:paint.reason},children:source.reason}):null,action,
231
- /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:surface.dismiss,"aria-label":surface.dismissLabel??CHAT_COPY.close,style:styles.dismissHit,children:/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.dismissDisc,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"x",size:DISMISS_GLYPH_SIZE,color:paint.title,strokeWidth:2.25})})})]})}function tierPaint(tier,theme){if(tier.level==="emergency"){let c=theme.color;return{edge:c.danger,fill:c.badgeBgCritical,title:c.danger,reason:c.text.primary}}return{edge:tier.borderColor,fill:tier.backgroundColor,title:tier.textColor,reason:tier.reasonColor}}function VetAction({tier:tier,styles:styles,vetEntry:vetEntry,renderVetAction:renderVetAction,onFindVet:onFindVet}){let theme=useEverfurTheme(),level=tier.level,emergency=level==="emergency",toHostFinder=!vetEntry.available&&onFindVet!==void 0,onClick=vetEntry.available?vetEntry.open:onFindVet!==void 0?()=>{callHost(onFindVet,level)}:null,label=emergency&&toHostFinder?CHAT_COPY.nearestEmergencyVet:CHAT_COPY.findVet,a11y=emergency&&toHostFinder?CHAT_COPY.nearestEmergencyVet:CHAT_COPY.findVetA11y,slot=ownGroundSlot(theme.slots.vetVisitButton),paint=tierPaint(tier,theme),base=emergency?{...styles.pill,borderColor:theme.color.primary,backgroundColor:theme.color.primary,color:theme.color.onPrimary}:{...styles.pill,borderColor:tier.borderColor,backgroundColor:tier.pillColor,color:tier.textColor},ink=slot?.textColor??(emergency?theme.color.onPrimary:paint.title),pill=onClick===null?null:/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button",onClick:onClick,"aria-label":a11y,style:{...base,...slotBoxCss(slot),...slotText(slot)},children:[
232
+ /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:surface.dismiss,"aria-label":surface.dismissLabel??CHAT_COPY.close,style:styles.dismissHit,children:/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.dismissDisc,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"x",size:DISMISS_GLYPH_SIZE,color:paint.title,strokeWidth:2.25})})})]})}function tierPaint(tier,theme){if(tier.level==="emergency"){let c=theme.color;return{edge:c.danger,fill:c.badgeBgCritical,title:c.danger,reason:c.text.primary}}return{edge:tier.borderColor,fill:tier.backgroundColor,title:tier.textColor,reason:tier.reasonColor}}function bannerRadius(tier,theme){let radius=theme.slots.banner?.borderRadius;return tier.level==="emergency"||radius===void 0?null:{borderRadius:radius}}function VetAction({tier:tier,styles:styles,vetEntry:vetEntry,renderVetAction:renderVetAction,onFindVet:onFindVet}){let theme=useEverfurTheme(),level=tier.level,emergency=level==="emergency",toHostFinder=!vetEntry.available&&onFindVet!==void 0,onClick=vetEntry.available?vetEntry.open:onFindVet!==void 0?()=>{callHost(onFindVet,level)}:null,label=emergency&&toHostFinder?CHAT_COPY.nearestEmergencyVet:CHAT_COPY.findVet,a11y=emergency&&toHostFinder?CHAT_COPY.nearestEmergencyVet:CHAT_COPY.findVetA11y,slot=ownGroundSlot(theme.slots.vetVisitButton),paint=tierPaint(tier,theme),base=emergency?{...styles.pill,borderColor:theme.color.primary,backgroundColor:theme.color.primary,color:theme.color.onPrimary}:{...styles.pill,borderColor:tier.borderColor,backgroundColor:tier.pillColor,color:tier.textColor},ink=slot?.textColor??(emergency?theme.color.onPrimary:paint.title),pill=onClick===null?null:/* @__PURE__ */jsxRuntime.jsxs("button",{type:"button",onClick:onClick,"aria-label":a11y,style:{...base,...slotBoxCss(slot),...slotText(slot)},children:[
232
233
  /* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"mapPin",size:PIN_GLYPH_SIZE,color:ink}),
233
234
  /* @__PURE__ */jsxRuntime.jsx("span",{children:label})]}),poison=emergency?/* @__PURE__ */jsxRuntime.jsxs("a",{href:POISON_CONTROL_TEL,style:{...styles.pill,...styles.ghost,borderColor:paint.title,color:paint.title},children:[
234
235
  /* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"phone",size:PIN_GLYPH_SIZE,color:paint.title}),
235
- /* @__PURE__ */jsxRuntime.jsx("span",{children:CHAT_COPY.poisonControlWeb})]}):null,vet=renderVetAction!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderVetAction(level),fallback:pill,resetKey:level}):pill;return vet===null&&poison===null?null:/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.actionRow,children:[vet,poison]})}function CompactIcon({exiting:exiting,onExpand:onExpand,styles:styles}){let ref=react.useRef(null),motion=useChatMotion(),theme=useEverfurTheme();return react.useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:motion.iconInMs,fromOpacity:0});return()=>animation?.cancel()},[motion.iconInMs]),react.useEffect(()=>{exiting&&animateExit(ref.current,motion.iconOutMs)},[exiting,motion.iconOutMs]),/* @__PURE__ */jsxRuntime.jsx("div",{ref:ref,"aria-hidden":exiting?true:void 0,style:styles.iconRow,children:/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onExpand,"aria-label":CHAT_COPY.showLatestVetAlert,style:styles.iconButton,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"info",size:INFO_GLYPH_SIZE,color:theme.color.text.muted})})})}function makeStyles6(theme){let s=theme.space,r=theme.radius,t=theme.type,heading=t.tierSizes.heading,control=t.tierSizes.control;return{banner:{position:"relative",boxSizing:"border-box",width:`calc(100% - ${s.lg*2}px)`,maxWidth:CHAT_COLUMN_MAX_WIDTH,margin:`${s.sm}px auto ${s.xs}px`,padding:`${s.lg}px ${s.lg+s.xs/2}px`,borderRadius:r.lg,borderStyle:"solid",borderWidth:BANNER_BORDER,display:"flex",flexDirection:"column",gap:s.xs},label:{margin:0,paddingRight:DISMISS_SIZE,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,...faceCss(theme,"bold"),fontSize:heading.body,lineHeight:`${Math.round(heading.body*t.lineHeight.snug)}px`},reason:{margin:0,paddingRight:DISMISS_SIZE,...faceCss(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*1.5)}px`,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},actionRow:{display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm,marginTop:s.sm},pill:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET5,display:"inline-flex",flexDirection:"row",alignItems:"center",gap:s.sm,margin:0,padding:`0 ${s.lg}px`,borderRadius:r.pill,borderStyle:"solid",borderWidth:ACTION_EDGE,cursor:"pointer",textDecoration:"none",...faceCss(theme,"bold"),fontSize:control.bodyTight,lineHeight:`${Math.round(control.bodyTight*t.lineHeight.snug)}px`},ghost:{backgroundColor:"transparent"},dismissHit:{position:"absolute",top:6-(MIN_TOUCH_TARGET5-DISMISS_SIZE)/2,right:6-(MIN_TOUCH_TARGET5-DISMISS_SIZE)/2,boxSizing:"border-box",width:MIN_TOUCH_TARGET5,height:MIN_TOUCH_TARGET5,minWidth:MIN_TOUCH_TARGET5,minHeight:MIN_TOUCH_TARGET5,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},dismissDisc:{boxSizing:"border-box",width:DISMISS_SIZE,height:DISMISS_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center"},iconRow:{display:"flex",flexDirection:"row",justifyContent:"flex-end",padding:`2px ${s.lg}px ${s.xs}px`},iconButton:{boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET5,minHeight:MIN_TOUCH_TARGET5,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}}}var SPINNER_DELAY_MS=300,MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET6=44,INPUT_MAX_HEIGHT=120;var EMPTY_LEAD_RATIO="100 / 12",EMPTY_MIN_HEIGHT=480,EMPTY_GAP=18,BUBBLE_MAX_WIDTH="min(88%, 520px)",BUBBLE_PADDING_Y_TOKEN="md",BUBBLE_PADDING_X_TOKEN="lg",BUBBLE_RADIUS_TOKEN="lg",BUBBLE_TAIL_RADIUS_TOKEN="xs",USER_LINE_HEIGHT=1.5,ASSISTANT_LINE_HEIGHT=1.6;var BUBBLE_SLOT_EDGE_WIDTH=1,PENDING_OPACITY=.6,TURN_GAP_TOKEN="lg",ASSISTANT_INSET_TOKEN="xl",COMPOSER_BORDER_WIDTH=1.5,COMPOSER_PADDING_TOKEN="sm",COMPOSER_LEAD_EXTRA_TOKEN="xs",COMPOSER_GAP_TOKEN="xs",COMPOSER_MIN_HEIGHT=60,INPUT_MIN_HEIGHT=44,INPUT_MIN_FONT_SIZE=16,INPUT_LINE_HEIGHT=1.4,SEND_DISC_SIZE=44,SEND_GLYPH_SIZE=22,STOP_GLYPH_SIZE=18,DISABLED_OPACITY=.4,EARLIER_LETTER_SPACING=.5;var SPINNER_SIZE=24,SPINNER_STROKE=3,SPINNER_LOOP_MS=900,ATTACH_GLYPH_SIZE=20,FOLLOW_UP_EDGE_WIDTH=1.5,FOLLOW_UP_LINE_HEIGHT=1.3,FOOTNOTE_LINE_HEIGHT=1.5;function useChatTheme(){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles7(theme),[theme]);return{theme:theme,styles:styles}}function columnInset(minimum){return`max(${minimum}px, calc((100% - ${CHAT_COLUMN_MAX_WIDTH}px) / 2))`}function linePx(size,ratio){return`${Math.round(size*ratio)}px`}function makeStyles7(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,slots=theme.slots,family=cssFontFamily(t.family),body=t.size.body,inputSize=Math.max(INPUT_MIN_FONT_SIZE,body),inputLine=Math.round(inputSize*INPUT_LINE_HEIGHT),controlSize=t.tierSizes.control,compactSize=t.tierSizes.compact,bubblePadY=s[BUBBLE_PADDING_Y_TOKEN]+s.xs/2,bubblePadX=s[BUBBLE_PADDING_X_TOKEN]+s.xs/2,control={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET6,minWidth:MIN_TOUCH_TARGET6,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,border:0,cursor:"pointer",...faceCss(theme,"medium"),fontSize:controlSize.body,lineHeight:`${Math.round(controlSize.body*t.lineHeight.normal)}px`},sendSlot=slots.sendButton,discFill=sendSlot?.backgroundColor??(sendSlot?.textColor!==void 0?"transparent":c.primary),primaryOutline=c.primaryEdge!==c.primary?c.primaryEdge:null;return{container:{...SURFACE_ROOT_RESET,boxSizing:"border-box",position:"relative",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT,height:"100%",backgroundColor:c.chatGround,color:c.text.primary,fontFamily:family},split:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"row"},main:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:s.xl},spinner:{boxSizing:"border-box",width:SPINNER_SIZE,height:SPINNER_SIZE,borderRadius:r.pill,border:`${SPINNER_STROKE}px solid ${c.brandSofter}`,borderTopColor:c.brandInk},emptyScroller:{boxSizing:"border-box",flex:`1 1 ${EMPTY_MIN_HEIGHT}px`,minHeight:0,overflowY:"auto"},emptyContent:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"stretch",justifyContent:"flex-start",height:"100%",paddingLeft:columnInset(s.lg),paddingRight:columnInset(s.lg),paddingBottom:s.lg,gap:EMPTY_GAP},emptyLead:{flex:"0 1 auto",width:"100%",maxHeight:s.xxl*2,aspectRatio:EMPTY_LEAD_RATIO,minHeight:0,marginBottom:-EMPTY_GAP},errorText:{margin:`0 0 ${s.md}px`,...faceCss(theme,"regular"),fontSize:t.size.subtitle,lineHeight:`${Math.round(t.size.subtitle*t.lineHeight.snug)}px`,color:c.danger,textAlign:"center"},retryButton:{...control,padding:`${s.sm}px ${s.xl}px`,borderRadius:r.pill,backgroundColor:c.brand,color:c.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},setupNotice:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm}px ${s.lg}px`,backgroundColor:c.surfaceCream},setupNoticeText:{...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger},setupNoticeAction:{...control,padding:0,background:"none",border:"none",color:c.brandInk,fontSize:t.size.caption,minHeight:MIN_TOUCH_TARGET6},turnNotice:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.xs,padding:s.md,borderRadius:r.md,backgroundColor:c.surfaceCream,border:`1px solid ${c.borderRingCream}`},turnNoticeError:{border:`1px solid ${c.danger}`},turnNoticeTitle:{...faceCss(theme,"bold"),margin:0,fontSize:t.size.bodyTight,color:c.text.primary},turnNoticeTitleError:{color:c.danger},reconnectingCaption:{...faceCss(theme,"medium"),margin:0,fontSize:t.size.caption,color:c.text.muted,textTransform:"uppercase",letterSpacing:"0.5px"},turnNoticeBody:{...faceCss(theme,"regular"),margin:0,fontSize:t.size.caption,color:c.text.muted},turnNoticeAction:{...control,padding:0,background:"none",border:"none",color:c.brandInk,minHeight:MIN_TOUCH_TARGET6,...faceCss(theme,"bold"),fontSize:t.size.bodyTight},earlierButton:{...control,alignSelf:"center",padding:`0 ${s.md+s.xs/2}px`,backgroundColor:"transparent",color:c.linkInk,...faceCss(theme,"monoBold"),fontSize:compactSize.tiny,lineHeight:`${Math.round(compactSize.tiny*t.lineHeight.snug)}px`,letterSpacing:EARLIER_LETTER_SPACING,textTransform:"uppercase"},list:{boxSizing:"border-box",flex:"1 1 auto",minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column",gap:s[TURN_GAP_TOKEN]+s.xs/2,paddingTop:s.lg,paddingBottom:s.lg,paddingLeft:columnInset(s.lg),paddingRight:columnInset(s.lg)},messageList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:s[TURN_GAP_TOKEN]+s.xs/2},row:{display:"flex",flexDirection:"column"},rowUser:{alignItems:"flex-end"},rowAssistant:{alignItems:"flex-start"},bubble:{boxSizing:"border-box",maxWidth:BUBBLE_MAX_WIDTH,paddingTop:bubblePadY,paddingBottom:bubblePadY,paddingLeft:bubblePadX,paddingRight:bubblePadX,borderRadius:r[BUBBLE_RADIUS_TOKEN],position:"relative"},bubbleUser:{backgroundColor:c.bubbleUser,...primaryOutline!==null&&c.bubbleUser===c.primary?{border:`${BUBBLE_SLOT_EDGE_WIDTH}px solid ${primaryOutline}`}:{},borderBottomRightRadius:r[BUBBLE_TAIL_RADIUS_TOKEN],transformOrigin:"100% 100%",...slotBoxCss(slots.userBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubbleAssistant:{...slots.assistantBubble?.backgroundColor===void 0?{paddingTop:0,paddingBottom:0,paddingLeft:0,paddingRight:s[ASSISTANT_INSET_TOKEN],maxWidth:`min(100%, ${ASSISTANT_MEASURE})`}:{},transformOrigin:"0 100%",...slotBoxCss(slots.assistantBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubbleVet:{backgroundColor:c.bubbleVet,borderTopLeftRadius:r[BUBBLE_TAIL_RADIUS_TOKEN],transformOrigin:"0 100%",...slotBoxCss(slots.vetBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubblePending:{opacity:PENDING_OPACITY},bubbleTextUser:{margin:0,...faceCss(theme,"regular"),color:c.onPrimary,fontSize:body,lineHeight:linePx(body,USER_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.userBubble)},bubbleTextAssistant:{margin:0,...faceCss(theme,"regular"),color:c.text.primary,fontSize:body,lineHeight:linePx(body,ASSISTANT_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.assistantBubble)},bubbleTextVet:{margin:0,...faceCss(theme,"regular"),color:c.onBubbleVet,fontSize:body,lineHeight:linePx(body,USER_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.vetBubble)},senderRow:{display:"flex",flexDirection:"row",alignItems:"baseline",flexWrap:"wrap",gap:s.sm,margin:`0 0 ${s.sm}px`},assistantName:{margin:0,...faceCss(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,lineHeight:linePx(t.size.bodyTight,t.lineHeight.snug)},vetSender:{margin:0,...faceCss(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight,lineHeight:linePx(t.size.bodyTight,t.lineHeight.snug),overflowWrap:"anywhere"},bubbleBold:faceCss(theme,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:faceCss(theme,"mono"),followUps:{listStyle:"none",margin:`${s.md}px 0 0`,padding:0,display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm},followUpRow:{...control,justifyContent:"flex-start",textAlign:"left",maxWidth:"100%",padding:`${s.sm}px ${s.lg}px`,borderRadius:r.pill,border:`${FOLLOW_UP_EDGE_WIDTH}px solid ${c.brandInk}`,background:c.chatGround,color:c.brandInk,...faceCss(theme,"bold"),fontSize:controlSize.bodyTight,lineHeight:linePx(controlSize.bodyTight,FOLLOW_UP_LINE_HEIGHT),whiteSpace:"normal",overflowWrap:"anywhere"},composerBlock:{boxSizing:"border-box",display:"flex",flexDirection:"column",width:`calc(100% - ${s.md*2}px)`,maxWidth:CHAT_COLUMN_MAX_WIDTH,margin:"0 auto"},composerError:{margin:`${s.xs}px ${s.md}px 0`,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${Math.round(t.size.caption*t.lineHeight.normal)}px`,color:c.danger},composer:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"flex-end",gap:s[COMPOSER_GAP_TOKEN],minHeight:COMPOSER_MIN_HEIGHT,width:"100%",margin:`${s.xs}px 0 0`,paddingTop:s[COMPOSER_PADDING_TOKEN],paddingRight:s[COMPOSER_PADDING_TOKEN],paddingBottom:s[COMPOSER_PADDING_TOKEN],paddingLeft:s.lg+s[COMPOSER_LEAD_EXTRA_TOKEN],backgroundColor:c.chatGround,border:`${COMPOSER_BORDER_WIDTH}px solid ${c.composerBorder}`,borderRadius:r.xl,...slotBoxCss(slots.composerInput,COMPOSER_BORDER_WIDTH)},composerFocused:{border:`${COMPOSER_BORDER_WIDTH}px solid ${slots.composerInput?.borderColor??c.brandInk}`,outline:`${FOCUS_RING_WIDTH}px solid ${c.brandInk}`,outlineOffset:FOCUS_RING_WIDTH},inputWrap:{position:"relative",flex:"1 1 auto",minWidth:0,minHeight:INPUT_MIN_HEIGHT,display:"flex",alignItems:"center"},placeholder:{position:"absolute",top:"50%",left:0,right:0,transform:"translateY(-50%)",pointerEvents:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...faceCss(theme,"regular"),fontSize:inputSize,lineHeight:`${inputLine}px`,color:c.text.placeholder,...slotText(slots.composerInput)},input:{boxSizing:"border-box",flex:"1 1 auto",width:"100%",maxHeight:INPUT_MAX_HEIGHT,margin:0,padding:`${Math.max(0,(INPUT_MIN_HEIGHT-inputLine)/2)}px 0`,border:0,outline:"none",resize:"none",background:"transparent",...faceCss(theme,"regular"),fontSize:inputSize,lineHeight:`${inputLine}px`,color:c.text.primary,...slotText(slots.composerInput)},iconControl:{...control,flexShrink:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",color:c.brandInk},actionButton:{...control,flexShrink:0,padding:0,backgroundColor:"transparent",borderRadius:r.pill},sendDisc:{boxSizing:"border-box",width:SEND_DISC_SIZE,height:SEND_DISC_SIZE,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:SEND_DISC_SIZE/2,backgroundColor:discFill,border:"1px solid transparent",...primaryOutline!==null&&discFill===c.primary?{border:`1.5px solid ${primaryOutline}`}:{},...slotBoxCss(sendSlot)},actionButtonDisabled:{opacity:DISABLED_OPACITY,cursor:"not-allowed"},footnote:{margin:`${s.md}px 0 ${s.sm}px`,padding:`0 ${s.xs}px`,...faceCss(theme,"regular"),color:c.text.muted,fontSize:t.size.caption,lineHeight:linePx(t.size.caption,FOOTNOTE_LINE_HEIGHT)},poweredBy:{margin:0,padding:`0 0 ${s.xs}px`,...faceCss(theme,"regular"),color:c.text.muted,fontSize:compactSize.micro,lineHeight:`${Math.round(compactSize.micro*t.lineHeight.normal)}px`,textAlign:"center"}}}function sendGlyphInk(theme){return theme.slots.sendButton?.textColor??theme.color.onPrimary}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}function liveCheckinIds(placements){let live=/* @__PURE__ */new Set;for(let[id,placement]of placements)placement.kind==="live"&&live.add(id);return live}var MIN_TOUCH_TARGET7=44,CARD_SIZE=56,CARD_RADIUS=12,REMOVE_SIZE=22,SPINNER_SIZE2=18,SPINNER_STROKE2=2,SPINNER_LOOP_MS2=900,SINGLE_IMAGE_SIZE=220,SINGLE_IMAGE_RADIUS=14,GRID_IMAGE_SIZE=100,GRID_IMAGE_RADIUS=10,GRID_GAP=6,UPLOADING_ALPHA=.45,SUCCESS_WASH="rgba(7,193,104,0.55)",FAILED_WASH="rgba(185,28,28,0.55)",NO_IMAGES=/* @__PURE__ */Object.freeze([]);function AttachmentTray({attachments:attachments,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles8(theme),[theme]);return attachments.length===0?null:/* @__PURE__ */jsxRuntime.jsx("ul",{style:styles.tray,children:attachments.map(row=>/* @__PURE__ */jsxRuntime.jsx("li",{style:styles.cardSlot,children:/* @__PURE__ */jsxRuntime.jsx(TrayCard,{row:row,styles:styles,theme:theme,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview})},row.id))})}function TrayCard({row:row,styles:styles,theme:theme,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let motion=useChatMotion(),previewRef=react.useRef(null),[flash,setFlash]=react.useState(false),wasUploading=react.useRef(row.status==="uploading");react.useEffect(()=>{if(row.status==="uploaded"&&wasUploading.current){setFlash(true);let handle=setTimeout(()=>setFlash(false),motion.uploadFlashMs);return wasUploading.current=false,()=>clearTimeout(handle)}wasUploading.current=row.status==="uploading"},[row.status,motion.uploadFlashMs]);let image={uri:row.previewUri,filename:row.filename};/* @__PURE__ */
236
+ /* @__PURE__ */jsxRuntime.jsx("span",{children:CHAT_COPY.poisonControlWeb})]}):null,vet=renderVetAction!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderVetAction(level),fallback:pill,resetKey:level}):pill;return vet===null&&poison===null?null:/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.actionRow,children:[vet,poison]})}function CompactIcon({exiting:exiting,onExpand:onExpand,styles:styles}){let ref=react.useRef(null),motion=useChatMotion(),theme=useEverfurTheme();return react.useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:motion.iconInMs,fromOpacity:0});return()=>animation?.cancel()},[motion.iconInMs]),react.useEffect(()=>{exiting&&animateExit(ref.current,motion.iconOutMs)},[exiting,motion.iconOutMs]),/* @__PURE__ */jsxRuntime.jsx("div",{ref:ref,"aria-hidden":exiting?true:void 0,style:styles.iconRow,children:/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onExpand,"aria-label":CHAT_COPY.showLatestVetAlert,style:styles.iconButton,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"info",size:INFO_GLYPH_SIZE,color:theme.color.text.muted})})})}function makeStyles6(theme){let s=theme.space,r=theme.radius,t=theme.type,heading=t.tierSizes.heading,control=t.tierSizes.control;return{banner:{position:"relative",boxSizing:"border-box",width:`calc(100% - ${s.lg*2}px)`,maxWidth:CHAT_COLUMN_MAX_WIDTH,margin:`${s.sm}px auto ${s.xs}px`,padding:`${s.lg}px ${s.lg+s.xs/2}px`,borderRadius:r.lg,borderStyle:"solid",borderWidth:BANNER_BORDER,display:"flex",flexDirection:"column",gap:s.xs},label:{margin:0,paddingRight:DISMISS_SIZE,display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm,...faceCss(theme,"bold"),fontSize:heading.body,lineHeight:`${Math.round(heading.body*t.lineHeight.snug)}px`},reason:{margin:0,paddingRight:DISMISS_SIZE,...faceCss(theme,"regular"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*1.5)}px`,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},actionRow:{display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm,marginTop:s.sm},pill:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET5,display:"inline-flex",flexDirection:"row",alignItems:"center",gap:s.sm,margin:0,padding:`0 ${s.lg}px`,borderRadius:r.pill,borderStyle:"solid",borderWidth:ACTION_EDGE,cursor:"pointer",textDecoration:"none",...faceCss(theme,"bold"),fontSize:control.bodyTight,lineHeight:`${Math.round(control.bodyTight*t.lineHeight.snug)}px`},ghost:{backgroundColor:"transparent"},dismissHit:{position:"absolute",top:6-(MIN_TOUCH_TARGET5-DISMISS_SIZE)/2,right:6-(MIN_TOUCH_TARGET5-DISMISS_SIZE)/2,boxSizing:"border-box",width:MIN_TOUCH_TARGET5,height:MIN_TOUCH_TARGET5,minWidth:MIN_TOUCH_TARGET5,minHeight:MIN_TOUCH_TARGET5,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},dismissDisc:{boxSizing:"border-box",width:DISMISS_SIZE,height:DISMISS_SIZE,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center"},iconRow:{display:"flex",flexDirection:"row",justifyContent:"flex-end",padding:`2px ${s.lg}px ${s.xs}px`},iconButton:{boxSizing:"border-box",minWidth:MIN_TOUCH_TARGET5,minHeight:MIN_TOUCH_TARGET5,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}}}var SPINNER_DELAY_MS=300,MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET6=44,INPUT_MAX_HEIGHT=120;var EMPTY_LEAD_RATIO="100 / 12",EMPTY_MIN_HEIGHT=480,EMPTY_GAP=18,BUBBLE_MAX_WIDTH="min(88%, 520px)",BUBBLE_PADDING_Y_TOKEN="md",BUBBLE_PADDING_X_TOKEN="lg",BUBBLE_RADIUS_TOKEN="lg",BUBBLE_TAIL_RADIUS_TOKEN="xs",USER_LINE_HEIGHT=1.5,ASSISTANT_LINE_HEIGHT=1.6;var BUBBLE_SLOT_EDGE_WIDTH=1,PENDING_OPACITY=.6,TURN_GAP_TOKEN="lg",ASSISTANT_INSET_TOKEN="xl",COMPOSER_BORDER_WIDTH=1.5,COMPOSER_PADDING_TOKEN="sm",COMPOSER_LEAD_EXTRA_TOKEN="xs",COMPOSER_GAP_TOKEN="xs",COMPOSER_MIN_HEIGHT=60,INPUT_MIN_HEIGHT=44,INPUT_MIN_FONT_SIZE=16,INPUT_LINE_HEIGHT=1.4,SEND_DISC_SIZE=44,SEND_GLYPH_SIZE=22,STOP_GLYPH_SIZE=18,DISABLED_OPACITY=.4,EARLIER_LETTER_SPACING=.5;var SPINNER_SIZE=24,SPINNER_STROKE=3,SPINNER_LOOP_MS=900,ATTACH_GLYPH_SIZE=20,FOLLOW_UP_EDGE_WIDTH=1.5,ASSISTANT_AVATAR_SIZE=20,FOLLOW_UP_LINE_HEIGHT=1.3,FOOTNOTE_LINE_HEIGHT=1.5;function useChatTheme(){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles7(theme),[theme]);return{theme:theme,styles:styles}}function columnInset(minimum){return`max(${minimum}px, calc((100% - ${CHAT_COLUMN_MAX_WIDTH}px) / 2))`}function linePx(size,ratio){return`${Math.round(size*ratio)}px`}function makeStyles7(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,slots=theme.slots,family=cssFontFamily(t.family),body=t.size.body,inputSize=Math.max(INPUT_MIN_FONT_SIZE,body),inputLine=Math.round(inputSize*INPUT_LINE_HEIGHT),controlSize=t.tierSizes.control,compactSize=t.tierSizes.compact,bubblePadY=s[BUBBLE_PADDING_Y_TOKEN]+s.xs/2,bubblePadX=s[BUBBLE_PADDING_X_TOKEN]+s.xs/2,control={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET6,minWidth:MIN_TOUCH_TARGET6,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,border:0,cursor:"pointer",...faceCss(theme,"medium"),fontSize:controlSize.body,lineHeight:`${Math.round(controlSize.body*t.lineHeight.normal)}px`},sendSlot=slots.sendButton,discFill=sendSlot?.backgroundColor??(sendSlot?.textColor!==void 0?"transparent":c.primary),primaryOutline=c.primaryEdge!==c.primary?c.primaryEdge:null;return{container:{...SURFACE_ROOT_RESET,boxSizing:"border-box",position:"relative",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT,height:"100%",backgroundColor:c.chatGround,color:c.text.primary,fontFamily:family},split:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"row"},main:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:s.xl},spinner:{boxSizing:"border-box",width:SPINNER_SIZE,height:SPINNER_SIZE,borderRadius:r.pill,border:`${SPINNER_STROKE}px solid ${c.brandSofter}`,borderTopColor:c.brandInk},emptyScroller:{boxSizing:"border-box",flex:`1 1 ${EMPTY_MIN_HEIGHT}px`,minHeight:0,overflowY:"auto"},emptyContent:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"stretch",justifyContent:"flex-start",height:"100%",paddingLeft:columnInset(s.lg),paddingRight:columnInset(s.lg),paddingBottom:s.lg,gap:EMPTY_GAP},emptyLead:{flex:"0 1 auto",width:"100%",maxHeight:s.xxl*2,aspectRatio:EMPTY_LEAD_RATIO,minHeight:0,marginBottom:-EMPTY_GAP},errorText:{margin:`0 0 ${s.md}px`,...faceCss(theme,"regular"),fontSize:t.size.subtitle,lineHeight:`${Math.round(t.size.subtitle*t.lineHeight.snug)}px`,color:c.danger,textAlign:"center"},retryButton:{...control,padding:`${s.sm}px ${s.xl}px`,borderRadius:r.pill,backgroundColor:c.brand,color:c.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},setupNotice:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.sm,padding:`${s.sm}px ${s.lg}px`,backgroundColor:c.surfaceCream},setupNoticeText:{...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger},setupNoticeAction:{...control,padding:0,background:"none",border:"none",color:c.brandInk,fontSize:t.size.caption,minHeight:MIN_TOUCH_TARGET6},turnNotice:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.xs,padding:s.md,borderRadius:r.md,backgroundColor:c.surfaceCream,border:`1px solid ${c.borderRingCream}`},turnNoticeError:{border:`1px solid ${c.danger}`},turnNoticeTitle:{...faceCss(theme,"bold"),margin:0,fontSize:t.size.bodyTight,color:c.text.primary},turnNoticeTitleError:{color:c.danger},reconnectingCaption:{...faceCss(theme,"medium"),margin:0,fontSize:t.size.caption,color:c.text.muted,textTransform:"uppercase",letterSpacing:"0.5px"},turnNoticeBody:{...faceCss(theme,"regular"),margin:0,fontSize:t.size.caption,color:c.text.muted},turnNoticeAction:{...control,padding:0,background:"none",border:"none",color:c.brandInk,minHeight:MIN_TOUCH_TARGET6,...faceCss(theme,"bold"),fontSize:t.size.bodyTight},earlierButton:{...control,alignSelf:"center",padding:`0 ${s.md+s.xs/2}px`,backgroundColor:"transparent",color:c.linkInk,...faceCss(theme,"monoBold"),fontSize:compactSize.tiny,lineHeight:`${Math.round(compactSize.tiny*t.lineHeight.snug)}px`,letterSpacing:EARLIER_LETTER_SPACING,textTransform:"uppercase"},list:{boxSizing:"border-box",flex:"1 1 auto",minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column",gap:s[TURN_GAP_TOKEN]+s.xs/2,paddingTop:s.lg,paddingBottom:s.lg,paddingLeft:columnInset(s.lg),paddingRight:columnInset(s.lg)},messageList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:s[TURN_GAP_TOKEN]+s.xs/2},row:{display:"flex",flexDirection:"column"},rowUser:{alignItems:"flex-end"},rowAssistant:{alignItems:"flex-start"},bubble:{boxSizing:"border-box",maxWidth:BUBBLE_MAX_WIDTH,paddingTop:bubblePadY,paddingBottom:bubblePadY,paddingLeft:bubblePadX,paddingRight:bubblePadX,borderRadius:r[BUBBLE_RADIUS_TOKEN],position:"relative"},bubbleUser:{backgroundColor:c.bubbleUser,...primaryOutline!==null&&c.bubbleUser===c.primary?{border:`${BUBBLE_SLOT_EDGE_WIDTH}px solid ${primaryOutline}`}:{},borderBottomRightRadius:r[BUBBLE_TAIL_RADIUS_TOKEN],transformOrigin:"100% 100%",...slotBoxCss(slots.userBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubbleAssistant:{...slots.assistantBubble?.backgroundColor===void 0?{paddingTop:0,paddingBottom:0,paddingLeft:0,paddingRight:s[ASSISTANT_INSET_TOKEN],maxWidth:`min(100%, ${ASSISTANT_MEASURE})`}:{},transformOrigin:"0 100%",...slotBoxCss(slots.assistantBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubbleVet:{backgroundColor:c.bubbleVet,borderTopLeftRadius:r[BUBBLE_TAIL_RADIUS_TOKEN],transformOrigin:"0 100%",...slotBoxCss(slots.vetBubble,BUBBLE_SLOT_EDGE_WIDTH)},bubblePending:{opacity:PENDING_OPACITY},bubbleTextUser:{margin:0,...faceCss(theme,"regular"),color:c.onPrimary,fontSize:body,lineHeight:linePx(body,USER_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.userBubble)},bubbleTextAssistant:{margin:0,...faceCss(theme,"regular"),color:c.text.primary,fontSize:body,lineHeight:linePx(body,ASSISTANT_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.assistantBubble)},bubbleTextVet:{margin:0,...faceCss(theme,"regular"),color:c.onBubbleVet,fontSize:body,lineHeight:linePx(body,USER_LINE_HEIGHT),whiteSpace:"pre-wrap",overflowWrap:"anywhere",...slotText(slots.vetBubble)},senderRow:{display:"flex",flexDirection:"row",alignItems:"baseline",flexWrap:"wrap",gap:s.sm,margin:`0 0 ${s.sm}px`},assistantName:{margin:0,...faceCss(theme,"bold"),color:c.brandInk,fontSize:t.size.bodyTight,lineHeight:linePx(t.size.bodyTight,t.lineHeight.snug)},assistantAvatar:{display:"block",flexShrink:0,alignSelf:"center",width:ASSISTANT_AVATAR_SIZE,height:ASSISTANT_AVATAR_SIZE,borderRadius:r.pill,objectFit:"cover"},vetSender:{margin:0,...faceCss(theme,"bold"),color:c.text.primary,fontSize:t.size.bodyTight,lineHeight:linePx(t.size.bodyTight,t.lineHeight.snug),overflowWrap:"anywhere"},bubbleBold:faceCss(theme,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:faceCss(theme,"mono"),followUps:{listStyle:"none",margin:`${s.md}px 0 0`,padding:0,display:"flex",flexDirection:"row",flexWrap:"wrap",gap:s.sm},followUpRow:{...control,justifyContent:"flex-start",textAlign:"left",maxWidth:"100%",padding:`${s.sm}px ${s.lg}px`,borderRadius:r.pill,border:`${FOLLOW_UP_EDGE_WIDTH}px solid ${c.brandInk}`,background:c.chatGround,color:c.brandInk,...faceCss(theme,"bold"),fontSize:controlSize.bodyTight,lineHeight:linePx(controlSize.bodyTight,FOLLOW_UP_LINE_HEIGHT),whiteSpace:"normal",overflowWrap:"anywhere",...slotCss(slots.chip,FOLLOW_UP_EDGE_WIDTH)},composerBlock:{boxSizing:"border-box",display:"flex",flexDirection:"column",width:`calc(100% - ${s.md*2}px)`,maxWidth:CHAT_COLUMN_MAX_WIDTH,margin:"0 auto"},composerError:{margin:`${s.xs}px ${s.md}px 0`,...faceCss(theme,"regular"),fontSize:t.size.caption,lineHeight:`${Math.round(t.size.caption*t.lineHeight.normal)}px`,color:c.danger},composer:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"flex-end",gap:s[COMPOSER_GAP_TOKEN],minHeight:COMPOSER_MIN_HEIGHT,width:"100%",margin:`${s.xs}px 0 0`,paddingTop:s[COMPOSER_PADDING_TOKEN],paddingRight:s[COMPOSER_PADDING_TOKEN],paddingBottom:s[COMPOSER_PADDING_TOKEN],paddingLeft:s.lg+s[COMPOSER_LEAD_EXTRA_TOKEN],backgroundColor:c.chatGround,border:`${COMPOSER_BORDER_WIDTH}px solid ${c.composerBorder}`,borderRadius:r.xl,...slotBoxCss(slots.composerInput,COMPOSER_BORDER_WIDTH)},composerFocused:{border:`${COMPOSER_BORDER_WIDTH}px solid ${slots.composerInput?.borderColor??c.brandInk}`,outline:`${FOCUS_RING_WIDTH}px solid ${c.brandInk}`,outlineOffset:FOCUS_RING_WIDTH},inputWrap:{position:"relative",flex:"1 1 auto",minWidth:0,minHeight:INPUT_MIN_HEIGHT,display:"flex",alignItems:"center"},placeholder:{position:"absolute",top:"50%",left:0,right:0,transform:"translateY(-50%)",pointerEvents:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...faceCss(theme,"regular"),fontSize:inputSize,lineHeight:`${inputLine}px`,color:c.text.placeholder,...slotText(slots.composerInput)},input:{boxSizing:"border-box",flex:"1 1 auto",width:"100%",maxHeight:INPUT_MAX_HEIGHT,margin:0,padding:`${Math.max(0,(INPUT_MIN_HEIGHT-inputLine)/2)}px 0`,border:0,outline:"none",resize:"none",background:"transparent",...faceCss(theme,"regular"),fontSize:inputSize,lineHeight:`${inputLine}px`,color:c.text.primary,...slotText(slots.composerInput)},iconControl:{...control,flexShrink:0,padding:0,border:"1px solid transparent",borderRadius:r.pill,background:"transparent",color:c.brandInk},actionButton:{...control,flexShrink:0,padding:0,backgroundColor:"transparent",borderRadius:r.pill},sendDisc:{boxSizing:"border-box",width:SEND_DISC_SIZE,height:SEND_DISC_SIZE,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:SEND_DISC_SIZE/2,backgroundColor:discFill,border:"1px solid transparent",...primaryOutline!==null&&discFill===c.primary?{border:`1.5px solid ${primaryOutline}`}:{},...slotBoxCss(sendSlot)},actionButtonDisabled:{opacity:DISABLED_OPACITY,cursor:"not-allowed"},footnote:{margin:`${s.md}px 0 ${s.sm}px`,padding:`0 ${s.xs}px`,...faceCss(theme,"regular"),color:c.text.muted,fontSize:t.size.caption,lineHeight:linePx(t.size.caption,FOOTNOTE_LINE_HEIGHT)},poweredBy:{margin:0,padding:`0 0 ${s.xs}px`,...faceCss(theme,"regular"),color:c.text.muted,fontSize:compactSize.micro,lineHeight:`${Math.round(compactSize.micro*t.lineHeight.normal)}px`,textAlign:"center"}}}function sendGlyphInk(theme){return theme.slots.sendButton?.textColor??theme.color.onPrimary}var LIVE=/* @__PURE__ */Object.freeze({kind:"live"}),FOLDED=/* @__PURE__ */Object.freeze({kind:"folded"});function askOf(message){if(message.role!=="assistant"||message.checkin===void 0)return null;let caseId=message.checkin.caseId,origin=parseCheckinOrigin(message.proactiveOriginRef);return{caseId:caseId,dueDay:origin!==null&&origin.caseId===caseId?origin.dueDay:""}}function placeCheckins(messages){let placements=/* @__PURE__ */new Map,newestByCase=/* @__PURE__ */new Map;for(let message of messages){let ask=askOf(message);if(ask===null)continue;let current=newestByCase.get(ask.caseId);(current===void 0||ask.dueDay>=current.dueDay)&&newestByCase.set(ask.caseId,{messageId:message.id,dueDay:ask.dueDay})}if(newestByCase.size===0)return placements;let leader=null;for(let message of messages){let ask=askOf(message);if(ask===null){leader=null;continue}if(newestByCase.get(ask.caseId)?.messageId===message.id){placements.set(message.id,LIVE),leader=null;continue}if(leader!==null&&leader.caseId===ask.caseId){leader.days.push(ask.dueDay),placements.set(message.id,FOLDED);continue}let days=[ask.dueDay];leader={id:message.id,caseId:ask.caseId,days:days},placements.set(message.id,{kind:"past",runDueDays:days})}return placements}function liveCheckinIds(placements){let live=/* @__PURE__ */new Set;for(let[id,placement]of placements)placement.kind==="live"&&live.add(id);return live}var MIN_TOUCH_TARGET7=44,CARD_SIZE=56,CARD_RADIUS=12,REMOVE_SIZE=22,SPINNER_SIZE2=18,SPINNER_STROKE2=2,SPINNER_LOOP_MS2=900,SINGLE_IMAGE_SIZE=220,SINGLE_IMAGE_RADIUS=14,GRID_IMAGE_SIZE=100,GRID_IMAGE_RADIUS=10,GRID_GAP=6,UPLOADING_ALPHA=.45,SUCCESS_WASH="rgba(7,193,104,0.55)",FAILED_WASH="rgba(185,28,28,0.55)",NO_IMAGES=/* @__PURE__ */Object.freeze([]);function AttachmentTray({attachments:attachments,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles8(theme),[theme]);return attachments.length===0?null:/* @__PURE__ */jsxRuntime.jsx("ul",{style:styles.tray,children:attachments.map(row=>/* @__PURE__ */jsxRuntime.jsx("li",{style:styles.cardSlot,children:/* @__PURE__ */jsxRuntime.jsx(TrayCard,{row:row,styles:styles,theme:theme,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview})},row.id))})}function TrayCard({row:row,styles:styles,theme:theme,onRetry:onRetry,onRemove:onRemove,onPreview:onPreview}){let motion=useChatMotion(),previewRef=react.useRef(null),[flash,setFlash]=react.useState(false),wasUploading=react.useRef(row.status==="uploading");react.useEffect(()=>{if(row.status==="uploaded"&&wasUploading.current){setFlash(true);let handle=setTimeout(()=>setFlash(false),motion.uploadFlashMs);return wasUploading.current=false,()=>clearTimeout(handle)}wasUploading.current=row.status==="uploading"},[row.status,motion.uploadFlashMs]);let image={uri:row.previewUri,filename:row.filename};/* @__PURE__ */
236
237
  return jsxRuntime.jsxs("div",{style:styles.card,children:[
237
238
  /* @__PURE__ */jsxRuntime.jsx("button",{ref:previewRef,type:"button","aria-label":fillCopy(CHAT_COPY.previewAttachment,{filename:row.filename}),onClick:()=>onPreview(image,previewRef.current),style:styles.previewButton,children:/* @__PURE__ */jsxRuntime.jsx("img",{src:row.previewUri,alt:"",style:styles.thumb})}),row.status==="uploading"?/* @__PURE__ */jsxRuntime.jsx("div",{role:"status","aria-busy":"true","aria-label":fillCopy(CHAT_COPY.previewAttachment,{filename:row.filename}),style:{...styles.wash,backgroundColor:withAlpha(theme.color.brandInk,UPLOADING_ALPHA)??theme.color.brandSofter},children:/* @__PURE__ */jsxRuntime.jsx(Spinner,{styles:styles})}):null,row.status==="uploaded"&&flash?/* @__PURE__ */jsxRuntime.jsx("div",{"aria-hidden":"true",style:{...styles.wash,backgroundColor:SUCCESS_WASH}}):null,row.status==="failed"?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button","aria-label":fillCopy(CHAT_COPY.retryUpload,{filename:row.filename}),onClick:()=>onRetry(row.id),style:{...styles.wash,...styles.retry,backgroundColor:FAILED_WASH},children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"upload",size:18,color:"#FFFFFF"})}):null,
238
239
  /* @__PURE__ */jsxRuntime.jsx("button",{type:"button","aria-label":fillCopy(CHAT_COPY.removeAttachment,{filename:row.filename}),onClick:()=>onRemove(row.id),style:styles.removeHit,children:/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.removeDisc,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"x",size:12,color:theme.color.surface,strokeWidth:2.5})})})]})}function Spinner({styles:styles}){let motion=useChatMotion(),ref=react.useRef(null);return react.useEffect(()=>{let node=ref.current;if(motion.reduced||!canAnimate(node))return;let animation=node.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:SPINNER_LOOP_MS2,iterations:1/0,easing:"linear"});return()=>animation.cancel()},[motion.reduced]),/* @__PURE__ */jsxRuntime.jsx("span",{ref:ref,"aria-hidden":"true",style:styles.spinner})}function MessageAttachments({images:images,onPreview:onPreview}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles8(theme),[theme]);if(images.length===0)return null;let single=images.length===1;/* @__PURE__ */
@@ -241,29 +242,29 @@ return jsxRuntime.jsx("button",{ref:ref,type:"button","aria-label":fillCopy(CHAT
241
242
  return jsxRuntime.jsx("li",{style:styles.row,children:/* @__PURE__ */jsxRuntime.jsxs("div",{role:"group","aria-label":CHECKIN_COPY.eyebrow,"aria-busy":state.pending!==null?true:void 0,style:styles.card,children:[
242
243
  /* @__PURE__ */jsxRuntime.jsx("p",{style:styles.eyebrow,children:CHECKIN_COPY.eyebrow}),
243
244
  /* @__PURE__ */jsxRuntime.jsx("p",{style:styles.question,children:message.text}),answerable?/* @__PURE__ */jsxRuntime.jsx("div",{style:{...styles.answers,...state.pending?styles.answersPending:null},children:CHECKIN_OPTIONS.map(({answer:answer,label:label})=>{let selected=(state.pending??state.answer)===answer;/* @__PURE__ */
244
- return jsxRuntime.jsx("button",{type:"button",onClick:()=>state.choose(answer),disabled:settled,"aria-pressed":selected,style:{...styles.pill,...selected?styles.pillSelected:null},children:label},answer)})}):null,state.answer!==null?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.logged,children:CHECKIN_COPY.logged}):null,checkin.resolutionText?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.question,children:checkin.resolutionText}):null,state.escalated&&onFindVet?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onFindVet,style:styles.findVet,children:CHECKIN_COPY.findVet}):null,state.error?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.error,children:state.error.displayMessage}):null]})})}function makeStyles9(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,regular=faceCss(theme,"regular"),text3={margin:0,...regular,fontSize:t.size.body,lineHeight:`${Math.round(t.size.body*t.lineHeight.normal)}px`},compact=t.tierSizes.compact,control=t.tierSizes.control;return{row:{display:"flex",justifyContent:"flex-start",listStyle:"none"},card:{boxSizing:"border-box",maxWidth:"92%",padding:s.md,display:"flex",flexDirection:"column",gap:s.sm,borderRadius:r.lg,backgroundColor:c.surface,border:`1px solid ${c.brandBorder}`},eyebrow:{margin:0,...regular,color:c.text.secondary,fontSize:compact.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...text3,color:c.text.primary,whiteSpace:"pre-wrap"},answers:{display:"flex",gap:s.sm,marginTop:s.xs},answersPending:{opacity:PENDING_OPACITY2},pill:{...text3,fontSize:control.body,lineHeight:`${Math.round(control.body*t.lineHeight.normal)}px`,boxSizing:"border-box",flex:1,minHeight:MIN_TOUCH_TARGET8,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:`0 ${s.md}px`,borderRadius:r.pill,border:`1px solid ${c.controlEdge}`,backgroundColor:c.surfaceCream,color:c.text.primary,cursor:"pointer"},pillSelected:{backgroundColor:c.brand,borderColor:c.brandInk,color:c.onPrimary},logged:{margin:0,...regular,color:c.text.secondary,fontSize:t.size.caption},error:{margin:0,...regular,color:c.danger,fontSize:t.size.caption},findVet:{boxSizing:"border-box",alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET8,borderRadius:r.pill,border:`1.5px solid ${c.controlEdge}`,backgroundColor:c.surface,color:c.brandInk,cursor:"pointer",...faceCss(theme,"bold"),fontSize:t.size.body}}}var TIER_DOT_COLOR=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),TIER_DOT_UNKNOWN="#C8BEB4";function tierColor(authorityTier){return authorityTier?TIER_DOT_COLOR[authorityTier.toUpperCase()]??TIER_DOT_UNKNOWN:TIER_DOT_UNKNOWN}function tierLabel(authorityTier){if(!authorityTier)return null;let match=/^tier[_\s-]?(\d+)$/i.exec(authorityTier.trim());return match?`Tier ${match[1]}`:authorityTier}function text2(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}function httpsUrl(value){let raw=text2(value);return raw!==null&&/^https:\/\/\S+$/i.test(raw)?raw:null}function toCitationCard(raw,index){let sourceName=text2(raw.source_name)??text2(raw.sourceName),section=text2(raw.section),authorityTier=text2(raw.authority_tier)??text2(raw.authorityTier),label=tierLabel(authorityTier),title=sourceName??text2(raw.title)??`Source ${index+1}`,chunkId=text2(raw.monograph_chunk_id)??text2(raw.chunkId),meta=[section,label].filter(part=>part!==null).join(" · ");/* @__PURE__ */
245
+ return jsxRuntime.jsx("button",{type:"button",onClick:()=>state.choose(answer),disabled:settled,"aria-pressed":selected,style:{...styles.pill,...selected?styles.pillSelected:null},children:label},answer)})}):null,state.answer!==null?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.logged,children:CHECKIN_COPY.logged}):null,checkin.resolutionText?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.question,children:checkin.resolutionText}):null,state.escalated&&onFindVet?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onFindVet,style:styles.findVet,children:CHECKIN_COPY.findVet}):null,state.error?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.error,children:state.error.displayMessage}):null]})})}function makeStyles9(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,regular=faceCss(theme,"regular"),text3={margin:0,...regular,fontSize:t.size.body,lineHeight:`${Math.round(t.size.body*t.lineHeight.normal)}px`},compact=t.tierSizes.compact,control=t.tierSizes.control,cardText=slotText(theme.slots.card);return{row:{display:"flex",justifyContent:"flex-start",listStyle:"none"},card:{boxSizing:"border-box",maxWidth:"92%",padding:s.md,display:"flex",flexDirection:"column",gap:s.sm,borderRadius:r.lg,backgroundColor:c.surface,border:`1px solid ${c.brandBorder}`,...slotCss(theme.slots.card,1)},eyebrow:{margin:0,...regular,color:c.text.secondary,fontSize:compact.caption,letterSpacing:t.letterSpacing.eyebrow,textTransform:"uppercase",...cardText},question:{...text3,color:c.text.primary,whiteSpace:"pre-wrap",...cardText},answers:{display:"flex",gap:s.sm,marginTop:s.xs},answersPending:{opacity:PENDING_OPACITY2},pill:{...text3,fontSize:control.body,lineHeight:`${Math.round(control.body*t.lineHeight.normal)}px`,boxSizing:"border-box",flex:1,minHeight:MIN_TOUCH_TARGET8,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:`0 ${s.md}px`,borderRadius:r.pill,border:`1px solid ${c.controlEdge}`,backgroundColor:c.surfaceCream,color:c.text.primary,cursor:"pointer"},pillSelected:{backgroundColor:c.brand,borderColor:c.brandInk,color:c.onPrimary},logged:{margin:0,...regular,color:c.text.secondary,fontSize:t.size.caption,...cardText},error:{margin:0,...regular,color:c.danger,fontSize:t.size.caption},findVet:{boxSizing:"border-box",alignSelf:"stretch",minHeight:MIN_TOUCH_TARGET8,borderRadius:r.pill,border:`1.5px solid ${c.controlEdge}`,backgroundColor:c.surface,color:c.brandInk,cursor:"pointer",...faceCss(theme,"bold"),fontSize:t.size.body}}}var TIER_DOT_COLOR=/* @__PURE__ */Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),TIER_DOT_UNKNOWN="#C8BEB4";function tierColor(authorityTier){return authorityTier?TIER_DOT_COLOR[authorityTier.toUpperCase()]??TIER_DOT_UNKNOWN:TIER_DOT_UNKNOWN}function tierLabel(authorityTier){if(!authorityTier)return null;let match=/^tier[_\s-]?(\d+)$/i.exec(authorityTier.trim());return match?`Tier ${match[1]}`:authorityTier}function text2(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0?null:trimmed}function httpsUrl(value){let raw=text2(value);return raw!==null&&/^https:\/\/\S+$/i.test(raw)?raw:null}function toCitationCard(raw,index){let sourceName=text2(raw.source_name)??text2(raw.sourceName),section=text2(raw.section),authorityTier=text2(raw.authority_tier)??text2(raw.authorityTier),label=tierLabel(authorityTier),title=sourceName??text2(raw.title)??`Source ${index+1}`,chunkId=text2(raw.monograph_chunk_id)??text2(raw.chunkId),meta=[section,label].filter(part=>part!==null).join(" · ");/* @__PURE__ */
245
246
  return Object.freeze({title:title,sourceName:sourceName,section:section,authorityTier:authorityTier,tierLabel:label,meta:meta.length===0?null:meta,url:httpsUrl(raw.url),excerpt:text2(raw.excerpt),tierColor:tierColor(authorityTier),key:`${title}-${chunkId??"none"}-${index}`})}function toCitationCards(citations){return citations===void 0||citations.length===0?EMPTY_CARDS:/* @__PURE__ */Object.freeze(citations.map((citation,index)=>toCitationCard(citation,index)))}var EMPTY_CARDS=/* @__PURE__ */Object.freeze([]);function sourcesLabel(count2){return count2===1?`1 ${CHAT_COPY.sourceSingular}`:`${count2} ${CHAT_COPY.sourcePlural}`}function sourcesToggleLabel(count2,expanded){return`${expanded?CHAT_COPY.hideSources:CHAT_COPY.showSources} ${sourcesLabel(count2)}`}function citationA11yLabel(card){return[card.url!==null?`${CHAT_COPY.openSource}: ${card.title}`:card.title,card.meta,card.excerpt].filter(part=>part!==null&&part.length>0).join(". ")}var MIN_TOUCH_TARGET9=44,CARD_WIDTH=244,TIER_DOT_SIZE=8,PILL_GLYPH_SIZE=13,LINK_GLYPH_SIZE=14,TITLE_LINES=2,EXCERPT_LINES=3,SOURCE_PILL_HEIGHT=32;function CitationCards({citations:citations}){let cards=react.useMemo(()=>toCitationCards(citations),[citations]),theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles10(theme),[theme]),[expanded,setExpanded]=react.useState(false);return cards.length===0?null:/* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.wrap,children:[
246
247
  /* @__PURE__ */jsxRuntime.jsx("button",{type:"button","aria-expanded":expanded,"aria-label":sourcesToggleLabel(cards.length,expanded),onClick:()=>setExpanded(current=>!current),style:styles.pill,children:/* @__PURE__ */jsxRuntime.jsxs("span",{style:styles.pillFace,children:[
247
248
  /* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"bookOpen",size:PILL_GLYPH_SIZE,color:theme.color.text.muted}),
248
249
  /* @__PURE__ */jsxRuntime.jsx("span",{style:styles.pillLabel,children:sourcesLabel(cards.length)}),
249
250
  /* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"chevronDown",size:PILL_GLYPH_SIZE,color:theme.color.text.muted,style:expanded?{transform:"rotate(180deg)"}:void 0})]})}),expanded?/* @__PURE__ */jsxRuntime.jsx(Deck,{cards:cards,styles:styles,theme:theme}):null]})}function Deck({cards:cards,styles:styles,theme:theme}){let ref=react.useRef(null),motion=useChatMotion(),links=useCitationLinks();return react.useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:motion.citationsInMs,fromOpacity:0,fromTranslateY:motion.citationsRisePx});return()=>animation?.cancel()},[motion]),/* @__PURE__ */jsxRuntime.jsx("ul",{ref:ref,style:styles.deck,children:cards.map(card=>{let url=links.kind==="static"?null:card.url;/* @__PURE__ */
250
251
  return jsxRuntime.jsx("li",{style:styles.cardSlot,children:url!==null?/* @__PURE__ */jsxRuntime.jsx("a",{href:url,...linkBehaviour(links,url),"aria-label":citationA11yLabel(card),style:{...styles.card,...styles.cardLink},children:/* @__PURE__ */jsxRuntime.jsx(CardBody,{card:card,linked:true,styles:styles,theme:theme})}):
251
- /* @__PURE__ */jsxRuntime.jsx("div",{style:styles.card,children:/* @__PURE__ */jsxRuntime.jsx(CardBody,{card:card,linked:false,styles:styles,theme:theme})})},card.key)})})}function linkBehaviour(links,url){return links.kind==="static"?{}:{rel:"noopener noreferrer",onClick:event=>{event.defaultPrevented||event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey||(event.preventDefault(),links.open(url))}}}function CardBody({card:card,linked:linked,styles:styles,theme:theme}){/* @__PURE__ */
252
+ /* @__PURE__ */jsxRuntime.jsx("div",{style:styles.card,children:/* @__PURE__ */jsxRuntime.jsx(CardBody,{card:card,linked:false,styles:styles,theme:theme})})},card.key)})})}function linkBehaviour(links,url){return links.kind==="static"?{}:{rel:"noopener noreferrer",onClick:event=>{event.defaultPrevented||event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey||(event.preventDefault(),links.open(url))}}}function CardBody({card:card,linked:linked,styles:styles,theme:theme}){let linkInk=theme.slots.card?.textColor??theme.color.linkInk;/* @__PURE__ */
252
253
  return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
253
254
  /* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.cardHeader,children:[
254
255
  /* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{...styles.tierDot,backgroundColor:card.tierColor}}),
255
- /* @__PURE__ */jsxRuntime.jsx("span",{style:linked?{...styles.cardTitle,color:theme.color.linkInk}:styles.cardTitle,children:card.title}),linked?/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"arrowUpRight",size:LINK_GLYPH_SIZE,color:theme.color.linkInk}):null]}),card.meta!==null?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.cardMeta,children:card.meta}):null,card.excerpt!==null?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.cardExcerpt,children:card.excerpt}):null]})}function clamp2(lines){return{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:lines,overflow:"hidden"}}function makeStyles10(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type;return{wrap:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.xs,marginTop:s.sm},pill:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET9,minWidth:MIN_TOUCH_TARGET9,display:"inline-flex",alignItems:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer",font:"inherit"},pillFace:{boxSizing:"border-box",minHeight:SOURCE_PILL_HEIGHT,display:"inline-flex",flexDirection:"row",alignItems:"center",gap:s.xs+2,padding:`0 ${s.md}px`,borderRadius:r.pill,border:`1px solid ${c.borderRingCream}`,backgroundColor:c.chatGround},pillLabel:{...faceCss(theme,"regular"),fontSize:t.tierSizes.compact.caption,lineHeight:`${t.tierSizes.compact.caption+3}px`,color:c.brandInk},deck:{listStyle:"none",margin:0,padding:`${s.xs}px ${s.xl}px 0 0`,maxWidth:"100%",display:"flex",flexDirection:"row",gap:s.sm,overflowX:"auto"},cardSlot:{flex:"0 0 auto"},card:{boxSizing:"border-box",width:CARD_WIDTH,display:"flex",flexDirection:"column",gap:s.xs+2,padding:s.md,borderRadius:r.md,border:`1px solid ${c.borderRingCream}`,backgroundColor:c.surface,color:c.text.primary},cardLink:{textDecoration:"none",cursor:"pointer"},cardHeader:{display:"flex",flexDirection:"row",alignItems:"flex-start",gap:s.sm},tierDot:{flexShrink:0,width:TIER_DOT_SIZE,height:TIER_DOT_SIZE,borderRadius:r.pill,marginTop:7},cardTitle:{flex:"1 1 auto",minWidth:0,...faceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*1.7)}px`,letterSpacing:-.24,color:c.text.primary,...clamp2(TITLE_LINES)},cardMeta:{...faceCss(theme,"monoMedium"),fontSize:t.tierSizes.compact.nano,lineHeight:`${t.tierSizes.compact.nano+2}px`,letterSpacing:t.letterSpacing.monoWide,textTransform:"uppercase",color:c.text.metaCool,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},cardExcerpt:{...faceCss(theme,"regular"),fontSize:t.size.tiny,lineHeight:`${t.size.tiny+4}px`,color:c.text.muted,...clamp2(EXCERPT_LINES)}}}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}var MIN_TOUCH_TARGET10=44,RADIO_SIZE=20,NOTES_ROWS=3,PENDING_OPACITY3=.6;function FeedbackReasons(props){let{open:open,onSubmit:onSubmit,onClose:onClose,returnFocusTo:returnFocusTo}=props,theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles11(theme),[theme]),dialog=useModalDialog(open,onClose,returnFocusTo),[reason,setReason]=react.useState(null),[notes,setNotes]=react.useState(""),[pending,setPending]=react.useState(false),[failed,setFailed]=react.useState(false);if(!open)return null;let submit=()=>{if(pending)return;setPending(true),setFailed(false);let trimmed=notes.trim();onSubmit(reason,trimmed.length>0?trimmed:null).then(took=>{setPending(false),took?onClose():setFailed(true)})};/* @__PURE__ */
256
+ /* @__PURE__ */jsxRuntime.jsx("span",{style:linked?{...styles.cardTitle,color:linkInk}:styles.cardTitle,children:card.title}),linked?/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"arrowUpRight",size:LINK_GLYPH_SIZE,color:linkInk}):null]}),card.meta!==null?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.cardMeta,children:card.meta}):null,card.excerpt!==null?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.cardExcerpt,children:card.excerpt}):null]})}function clamp2(lines){return{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:lines,overflow:"hidden"}}function makeStyles10(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,cardText=slotText(theme.slots.card);return{wrap:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.xs,marginTop:s.sm},pill:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET9,minWidth:MIN_TOUCH_TARGET9,display:"inline-flex",alignItems:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer",font:"inherit"},pillFace:{boxSizing:"border-box",minHeight:SOURCE_PILL_HEIGHT,display:"inline-flex",flexDirection:"row",alignItems:"center",gap:s.xs+2,padding:`0 ${s.md}px`,borderRadius:r.pill,border:`1px solid ${c.borderRingCream}`,backgroundColor:c.chatGround},pillLabel:{...faceCss(theme,"regular"),fontSize:t.tierSizes.compact.caption,lineHeight:`${t.tierSizes.compact.caption+3}px`,color:c.brandInk},deck:{listStyle:"none",margin:0,padding:`${s.xs}px ${s.xl}px 0 0`,maxWidth:"100%",display:"flex",flexDirection:"row",gap:s.sm,overflowX:"auto"},cardSlot:{flex:"0 0 auto"},card:{boxSizing:"border-box",width:CARD_WIDTH,display:"flex",flexDirection:"column",gap:s.xs+2,padding:s.md,borderRadius:r.md,border:`1px solid ${c.borderRingCream}`,backgroundColor:c.surface,color:c.text.primary,...slotCss(theme.slots.card,1)},cardLink:{textDecoration:"none",cursor:"pointer"},cardHeader:{display:"flex",flexDirection:"row",alignItems:"flex-start",gap:s.sm},tierDot:{flexShrink:0,width:TIER_DOT_SIZE,height:TIER_DOT_SIZE,borderRadius:r.pill,marginTop:7},cardTitle:{flex:"1 1 auto",minWidth:0,...headingFaceCss(theme,"bold"),fontSize:t.size.bodyTight,lineHeight:`${Math.round(t.size.bodyTight*1.7)}px`,letterSpacing:-.24,color:c.text.primary,...clamp2(TITLE_LINES),...cardText},cardMeta:{...faceCss(theme,"monoMedium"),fontSize:t.tierSizes.compact.nano,lineHeight:`${t.tierSizes.compact.nano+2}px`,letterSpacing:t.letterSpacing.monoWide,textTransform:"uppercase",color:c.text.metaCool,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...cardText},cardExcerpt:{...faceCss(theme,"regular"),fontSize:t.size.tiny,lineHeight:`${t.size.tiny+4}px`,color:c.text.muted,...clamp2(EXCERPT_LINES),...cardText}}}function formatMessageTime(createdAt){if(!createdAt)return null;let parsed=new Date(createdAt);return Number.isNaN(parsed.getTime())?null:parsed.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}var MIN_TOUCH_TARGET10=44,RADIO_SIZE=20,NOTES_ROWS=3,PENDING_OPACITY3=.6;function FeedbackReasons(props){let{open:open,onSubmit:onSubmit,onClose:onClose,returnFocusTo:returnFocusTo}=props,theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles11(theme),[theme]),dialog=useModalDialog(open,onClose,returnFocusTo),[reason,setReason]=react.useState(null),[notes,setNotes]=react.useState(""),[pending,setPending]=react.useState(false),[failed,setFailed]=react.useState(false);if(!open)return null;let submit=()=>{if(pending)return;setPending(true),setFailed(false);let trimmed=notes.trim();onSubmit(reason,trimmed.length>0?trimmed:null).then(took=>{setPending(false),took?onClose():setFailed(true)})};/* @__PURE__ */
256
257
  return jsxRuntime.jsxs("dialog",{ref:dialog.dialogRef,"aria-label":CHAT_COPY.feedbackTitle,"aria-busy":pending?true:void 0,onCancel:dialog.onCancel,onKeyDown:dialog.onKeyDown,style:styles.sheet,children:[
257
258
  /* @__PURE__ */jsxRuntime.jsx("h2",{style:styles.title,children:CHAT_COPY.feedbackTitle}),
258
259
  /* @__PURE__ */jsxRuntime.jsx("p",{style:styles.subtitle,children:CHAT_COPY.feedbackSubtitle}),
259
260
  /* @__PURE__ */jsxRuntime.jsx("div",{role:"group","aria-label":CHAT_COPY.feedbackTitle,style:styles.options,children:FEEDBACK_REASONS.map(option=>{let selected=option.key===reason;/* @__PURE__ */
260
- return jsxRuntime.jsxs("button",{type:"button","aria-pressed":selected,disabled:pending,onClick:()=>setReason(selected?null:option.key),style:{...styles.option,...selected?styles.optionSelected:null},children:[
261
+ return jsxRuntime.jsxs("button",{type:"button","aria-pressed":selected,disabled:pending,onClick:()=>setReason(selected?null:option.key),style:{...styles.option,...selected?styles.optionSelected:styles.optionRest},children:[
261
262
  /* @__PURE__ */jsxRuntime.jsx("span",{style:styles.optionLabel,children:option.label}),
262
263
  /* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:{...styles.radio,...selected?styles.radioSelected:null},children:selected?/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"check",size:12,color:theme.color.surface,strokeWidth:3}):null})]},option.key)})}),
263
264
  /* @__PURE__ */jsxRuntime.jsx("textarea",{rows:NOTES_ROWS,value:notes,disabled:pending,"aria-label":CHAT_COPY.feedbackNotesPlaceholder,placeholder:CHAT_COPY.feedbackNotesPlaceholder,onChange:event=>{let next=event.target.value;[...next].length<=FEEDBACK_NOTES_MAX_CHARS&&setNotes(next)},style:styles.notes}),failed?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.failed,children:CHAT_COPY.feedbackFailed}):null,
264
265
  /* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.actions,children:[
265
266
  /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:submit,"aria-disabled":pending,style:{...styles.submit,...pending?styles.pending:null},children:CHAT_COPY.feedbackSubmit}),
266
- /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onClose,"aria-label":CHAT_COPY.feedbackSkipA11y,disabled:pending,style:styles.skip,children:CHAT_COPY.feedbackSkip})]})]})}function makeStyles11(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,bodyLineHeight=`${Math.round(t.size.body*t.lineHeight.normal)}px`,heading=t.tierSizes.heading.heading,controlSize=t.tierSizes.control.body,control={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET10,minWidth:MIN_TOUCH_TARGET10,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,cursor:"pointer",...faceCss(theme,"medium"),fontSize:t.size.body,lineHeight:bodyLineHeight};return{sheet:{boxSizing:"border-box",position:"fixed",top:"auto",right:0,bottom:0,left:0,margin:0,width:"100%",maxWidth:"100%",maxHeight:"80vh",overflowY:"auto",padding:`${s.lg+4}px ${s.lg+4}px ${s.xxl}px`,border:0,borderRadius:`${r.lg}px ${r.lg}px 0 0`,backgroundColor:c.surface,color:c.text.primary,display:"flex",flexDirection:"column",gap:s.md},title:{margin:0,...faceCss(theme,"bold"),fontSize:heading,lineHeight:`${Math.round(heading*1.22)}px`,color:c.text.primary},subtitle:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.body,lineHeight:bodyLineHeight,color:c.text.muted},options:{display:"flex",flexDirection:"column",gap:s.sm},option:{...control,width:"100%",justifyContent:"space-between",gap:s.md,padding:`${s.sm}px ${s.md}px`,borderRadius:r.md,border:`1px solid ${c.controlEdge}`,backgroundColor:c.surfaceCream,color:c.text.primary,textAlign:"left"},optionSelected:{border:`1px solid ${c.brandInk}`,backgroundColor:c.brandSoft},optionLabel:{flex:"1 1 auto",minWidth:0},radio:{boxSizing:"border-box",flexShrink:0,width:RADIO_SIZE,height:RADIO_SIZE,borderRadius:r.pill,border:`1.5px solid ${c.brandBorderStrong}`,backgroundColor:c.surface,display:"inline-flex",alignItems:"center",justifyContent:"center"},radioSelected:{border:`1.5px solid ${c.brandInk}`,backgroundColor:c.brandInk},notes:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET10,margin:0,padding:`${s.sm}px ${s.md}px`,borderRadius:r.md,border:`1px solid ${c.brandBorderStrong}`,backgroundColor:c.surfaceCream,color:c.text.primary,resize:"vertical",...faceCss(theme,"regular"),fontSize:t.size.body,lineHeight:bodyLineHeight},failed:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger},actions:{display:"flex",flexDirection:"column",alignItems:"stretch",gap:s.sm},submit:{...control,fontSize:controlSize,padding:`0 ${s.xl}px`,border:0,borderRadius:r.pill,backgroundColor:c.brand,color:c.onPrimary,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},pending:{opacity:PENDING_OPACITY3,cursor:"progress"},skip:{...control,fontSize:controlSize,padding:`0 ${s.xl}px`,border:0,borderRadius:r.pill,background:"transparent",color:c.text.secondary}}}var MIN_TOUCH_TARGET11=44,GLYPH_SIZE=15,ROW_HEIGHT=16;function canCopyToClipboard(){return typeof navigator<"u"&&typeof navigator.clipboard?.writeText=="function"}function MessageFooter(props){let{role:role,text:text3,createdAt:createdAt,responseId:responseId,sentiment:sentiment,feedback:feedback}=props,theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles12(theme),[theme]),motion=useChatMotion(),timeLabel=react.useMemo(()=>formatMessageTime(createdAt),[createdAt]),copyable=role!=="vet"&&canCopyToClipboard()&&text3.length>0,[copied,setCopied]=react.useState(false),copyTimer=react.useRef(null);react.useEffect(()=>()=>{copyTimer.current!==null&&clearTimeout(copyTimer.current)},[]);let onCopy=react.useCallback(()=>{navigator.clipboard.writeText(text3).catch(()=>{}),setCopied(true),copyTimer.current!==null&&clearTimeout(copyTimer.current),copyTimer.current=setTimeout(()=>{setCopied(false),copyTimer.current=null},motion.copiedMs)},[text3,motion.copiedMs]),[reasonsOpen,setReasonsOpen]=react.useState(false),[thanked,setThanked]=react.useState(false),[failed,setFailed]=react.useState(false),downRef=react.useRef(null),onSentiment=react.useCallback(next=>{if(responseId===void 0)return;setThanked(false),setFailed(false);let clearing=sentiment===next;feedback(responseId,next).then(result=>{result.ok||setFailed(true)}),next==="down"&&!clearing&&setReasonsOpen(true)},[responseId,sentiment,feedback]),onSubmitReason=react.useCallback(async(reason,notes)=>{if(responseId===void 0)return false;if(reason===null&&notes===null)return setThanked(true),true;let result=await feedback(responseId,"down",reason??"other",notes);return result.ok&&setThanked(true),result.ok},[responseId,feedback]);/* @__PURE__ */
267
+ /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onClose,"aria-label":CHAT_COPY.feedbackSkipA11y,disabled:pending,style:styles.skip,children:CHAT_COPY.feedbackSkip})]})]})}function makeStyles11(theme){let c=theme.color,s=theme.space,r=theme.radius,t=theme.type,bodyLineHeight=`${Math.round(t.size.body*t.lineHeight.normal)}px`,heading=t.tierSizes.heading.heading,controlSize=t.tierSizes.control.body,dialogText=slotText(theme.slots.dialog),control={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET10,minWidth:MIN_TOUCH_TARGET10,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,cursor:"pointer",...faceCss(theme,"medium"),fontSize:t.size.body,lineHeight:bodyLineHeight};return{sheet:{boxSizing:"border-box",position:"fixed",top:"auto",right:0,bottom:0,left:0,margin:0,width:"100%",maxWidth:"100%",maxHeight:"80vh",overflowY:"auto",padding:`${s.lg+4}px ${s.lg+4}px ${s.xxl}px`,border:0,borderRadius:`${r.lg}px ${r.lg}px 0 0`,backgroundColor:c.surface,color:c.text.primary,display:"flex",flexDirection:"column",gap:s.md,...sheetSlotCss(theme.slots.dialog)},title:{margin:0,...headingFaceCss(theme,"bold"),fontSize:heading,lineHeight:`${Math.round(heading*1.22)}px`,color:c.text.primary,...dialogText},subtitle:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.body,lineHeight:bodyLineHeight,color:c.text.muted,...dialogText},options:{display:"flex",flexDirection:"column",gap:s.sm},option:{...control,width:"100%",justifyContent:"space-between",gap:s.md,padding:`${s.sm}px ${s.md}px`,borderRadius:r.md,border:`1px solid ${c.controlEdge}`,backgroundColor:c.surfaceCream,color:c.text.primary,textAlign:"left",...slotRadius(theme.slots.chip)},optionSelected:{border:`1px solid ${c.brandInk}`,backgroundColor:c.brandSoft},optionRest:slotCss(theme.slots.chip,1),optionLabel:{flex:"1 1 auto",minWidth:0},radio:{boxSizing:"border-box",flexShrink:0,width:RADIO_SIZE,height:RADIO_SIZE,borderRadius:r.pill,border:`1.5px solid ${c.brandBorderStrong}`,backgroundColor:c.surface,display:"inline-flex",alignItems:"center",justifyContent:"center"},radioSelected:{border:`1.5px solid ${c.brandInk}`,backgroundColor:c.brandInk},notes:{boxSizing:"border-box",width:"100%",minHeight:MIN_TOUCH_TARGET10,margin:0,padding:`${s.sm}px ${s.md}px`,borderRadius:r.md,border:`1px solid ${c.brandBorderStrong}`,backgroundColor:c.surfaceCream,color:c.text.primary,resize:"vertical",...faceCss(theme,"regular"),fontSize:t.size.body,lineHeight:bodyLineHeight,...slotCss(theme.slots.input,1)},failed:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger},actions:{display:"flex",flexDirection:"column",alignItems:"stretch",gap:s.sm},submit:{...control,fontSize:controlSize,padding:`0 ${s.xl}px`,border:0,borderRadius:r.pill,backgroundColor:c.brand,color:c.onPrimary,...slotBoxCss(theme.slots.primaryButton),...slotText(theme.slots.primaryButton)},pending:{opacity:PENDING_OPACITY3,cursor:"progress"},skip:{...control,fontSize:controlSize,padding:`0 ${s.xl}px`,border:0,borderRadius:r.pill,background:"transparent",color:c.text.secondary}}}var MIN_TOUCH_TARGET11=44,GLYPH_SIZE=15,ROW_HEIGHT=16;function canCopyToClipboard(){return typeof navigator<"u"&&typeof navigator.clipboard?.writeText=="function"}function MessageFooter(props){let{role:role,text:text3,createdAt:createdAt,responseId:responseId,sentiment:sentiment,feedback:feedback}=props,theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles12(theme),[theme]),motion=useChatMotion(),timeLabel=react.useMemo(()=>formatMessageTime(createdAt),[createdAt]),copyable=role!=="vet"&&canCopyToClipboard()&&text3.length>0,[copied,setCopied]=react.useState(false),copyTimer=react.useRef(null);react.useEffect(()=>()=>{copyTimer.current!==null&&clearTimeout(copyTimer.current)},[]);let onCopy=react.useCallback(()=>{navigator.clipboard.writeText(text3).catch(()=>{}),setCopied(true),copyTimer.current!==null&&clearTimeout(copyTimer.current),copyTimer.current=setTimeout(()=>{setCopied(false),copyTimer.current=null},motion.copiedMs)},[text3,motion.copiedMs]),[reasonsOpen,setReasonsOpen]=react.useState(false),[thanked,setThanked]=react.useState(false),[failed,setFailed]=react.useState(false),downRef=react.useRef(null),onSentiment=react.useCallback(next=>{if(responseId===void 0)return;setThanked(false),setFailed(false);let clearing=sentiment===next;feedback(responseId,next).then(result=>{result.ok||setFailed(true)}),next==="down"&&!clearing&&setReasonsOpen(true)},[responseId,sentiment,feedback]),onSubmitReason=react.useCallback(async(reason,notes)=>{if(responseId===void 0)return false;if(reason===null&&notes===null)return setThanked(true),true;let result=await feedback(responseId,"down",reason??"other",notes);return result.ok&&setThanked(true),result.ok},[responseId,feedback]);/* @__PURE__ */
267
268
  return jsxRuntime.jsxs("div",{style:{...styles.footer,...role==="user"?styles.footerUser:styles.footerAssistant},children:[
268
269
  /* @__PURE__ */jsxRuntime.jsxs("div",{style:styles.row,children:[timeLabel!==null?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.timestamp,children:timeLabel}):null,copyable?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:onCopy,"aria-label":copied?CHAT_COPY.copied:role==="user"?CHAT_COPY.copyUserMessage:CHAT_COPY.copyAssistantMessage,style:styles.iconButton,children:copied?/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"check",size:GLYPH_SIZE,color:theme.color.success}):/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:"copy",size:GLYPH_SIZE,color:theme.color.text.timestamp})}):null,role==="assistant"&&responseId!==void 0?SENTIMENT_OPTIONS.map(option=>{let active=sentiment===option.sentiment,color=theme.color.sentiment[option.sentiment];/* @__PURE__ */
269
270
  return jsxRuntime.jsx("button",{ref:option.sentiment==="down"?downRef:void 0,type:"button","aria-pressed":active,"aria-label":option.label,onClick:()=>onSentiment(option.sentiment),style:styles.iconButton,children:/* @__PURE__ */jsxRuntime.jsx(Glyph,{name:option.sentiment==="up"?"thumbsUp":"thumbsDown",size:GLYPH_SIZE,color:color,fill:active?color:"transparent",style:option.sentiment==="neutral"?{transform:"rotate(-90deg)"}:void 0})},option.sentiment)}):null]}),thanked?/* @__PURE__ */jsxRuntime.jsx("p",{role:"status",style:styles.thanks,children:CHAT_COPY.feedbackThanks}):null,failed?/* @__PURE__ */jsxRuntime.jsx("p",{role:"alert",style:styles.failed,children:CHAT_COPY.feedbackFailed}):null,reasonsOpen?/* @__PURE__ */jsxRuntime.jsx(FeedbackReasons,{open:true,onSubmit:onSubmitReason,onClose:()=>setReasonsOpen(false),returnFocusTo:downRef}):null]})}function makeStyles12(theme){let c=theme.color,s=theme.space,t=theme.type;return{footer:{display:"flex",flexDirection:"column",gap:s.xs,paddingTop:s.xs+2},footerUser:{alignItems:"flex-end"},footerAssistant:{alignItems:"flex-start"},row:{display:"flex",flexDirection:"row",alignItems:"center",gap:s.sm+2,minHeight:ROW_HEIGHT},timestamp:{...faceCss(theme,"monoMedium"),fontSize:t.tierSizes.compact.nano,lineHeight:`${t.tierSizes.compact.nano+2}px`,color:theme.color.text.timestamp},iconButton:{boxSizing:"border-box",width:MIN_TOUCH_TARGET11,height:MIN_TOUCH_TARGET11,minWidth:MIN_TOUCH_TARGET11,minHeight:MIN_TOUCH_TARGET11,margin:`${-28/2}px 0`,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},thanks:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.text.secondary},failed:{margin:0,...faceCss(theme,"regular"),fontSize:t.size.caption,color:c.danger}}}var QUICK_PROMPT_BRAND_EDGE="#10462E",VET_PREP_LABEL_WEB="Book a video visit",QUICK_PROMPT_TEXT_COLOR="#000000",PILL_ACTIVITY_ON_WHITE="#83E0B4",PROMPTS=/* @__PURE__ */Object.freeze([
@@ -275,7 +276,7 @@ return Object.freeze(PROMPTS.map(template=>{let usesBreed=template.label.include
275
276
  return Object.freeze({id:template.id,intent:template.intent,label:label,background:template.background,borderColor:template.brandEdge===true?brandEdge:template.borderColor,borderWidth:template.borderWidth})}))}var MIN_TOUCH_TARGET12=44,TITLE_SIZE=30,TITLE_SIZE_DESKTOP=38,TITLE_LINE_HEIGHT=1.1,TITLE_LETTER_SPACING="-0.03em",CHIPS_OFFSET_EXTRA=4;function QuickPrompts({pet:pet,onSend:onSend,onVetPrep:onVetPrep}){let theme=useEverfurTheme(),{desktop:desktop}=useChatLayout(),styles=react.useMemo(()=>makeStyles13(theme,desktop),[theme,desktop]),motion=useChatMotion(),title=emptyStateTitle(pet),Heading=headingTag(useChatHeadingLevel()),chips=react.useMemo(()=>resolveQuickPrompts(pet,theme.color.brandInk).filter(chip=>chip.intent!=="vet_report"||onVetPrep!==null).map(chip=>chip.intent==="vet_report"?{...chip,label:VET_PREP_LABEL_WEB}:chip),[pet,onVetPrep,theme.color.brandInk]),themed=react.useMemo(()=>quickPromptThemePaint(isEverfurLightLook(theme),{fill:theme.color.highlight,ink:theme.color.onHighlight}),[theme]);/* @__PURE__ */
276
277
  return jsxRuntime.jsxs("div",{style:styles.wrap,children:[
277
278
  /* @__PURE__ */jsxRuntime.jsx(Heading,{style:styles.title,children:title}),
278
- /* @__PURE__ */jsxRuntime.jsx("ul",{"aria-label":CHAT_COPY.suggestions,style:styles.list,children:chips.map((chip,index)=>/* @__PURE__ */jsxRuntime.jsx("li",{children:/* @__PURE__ */jsxRuntime.jsx(Chip,{chip:chip,themed:themed,delayMs:followUpDelayMs(motion,index),durationMs:motion.followUpInMs,risePx:motion.promptRisePx,style:styles.chip,onPress:()=>chip.intent==="vet_report"?onVetPrep?.():onSend(chip.label)})},chip.id))})]})}function Chip({chip:chip,themed:themed,delayMs:delayMs,durationMs:durationMs,risePx:risePx,style:style,onPress:onPress}){let ref=react.useRef(null);return react.useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:durationMs,delayMs:delayMs,fromOpacity:0,fromTranslateY:risePx});return()=>animation?.cancel()},[durationMs,delayMs,risePx]),/* @__PURE__ */jsxRuntime.jsx("button",{ref:ref,type:"button",onClick:onPress,style:themed===null?{...style,backgroundColor:chip.background}:{...style,backgroundColor:themed.fill,color:themed.ink},children:chip.label})}function makeStyles13(theme,desktop){let s=theme.space,r=theme.radius,t=theme.type,titleSize=tierPx(theme,"heading",desktop?TITLE_SIZE_DESKTOP:TITLE_SIZE),chipSize=t.tierSizes.compact.bodyTight;return{wrap:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.lg+CHIPS_OFFSET_EXTRA,width:"100%"},title:{margin:0,...faceCss(theme,"medium"),fontSize:titleSize,lineHeight:`${Math.round(titleSize*TITLE_LINE_HEIGHT)}px`,letterSpacing:TITLE_LETTER_SPACING,color:theme.color.brandInk,textAlign:"left",textWrap:"balance"},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"row",flexWrap:"wrap",alignItems:"flex-start",gap:s.sm},chip:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET12,minWidth:MIN_TOUCH_TARGET12,maxWidth:"100%",display:"inline-flex",alignItems:"center",justifyContent:"flex-start",margin:0,padding:`${s.sm-1}px ${s.lg-1}px`,border:"1px solid transparent",borderRadius:r.pill,cursor:"pointer",...faceCss(theme,"bold"),fontSize:chipSize,lineHeight:`${Math.round(chipSize*1.3)}px`,color:QUICK_PROMPT_TEXT_COLOR,textAlign:"left",whiteSpace:"normal"}}}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function hasInlineMarkup(text3){return text3.includes("*")||text3.includes("`")}function tokenizeInlineMarkdown(text3){let runs=[],cursor2=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor2&&runs.push({kind:"text",text:text3.slice(cursor2,match.index)});let bold=match[1],italic=match[2],code=match[3];bold!==void 0?runs.push({kind:"bold",text:bold}):italic!==void 0?runs.push({kind:"italic",text:italic}):code!==void 0&&runs.push({kind:"code",text:code}),cursor2=match.index+match[0].length}return cursor2<text3.length&&runs.push({kind:"text",text:text3.slice(cursor2)}),runs}function renderInlineMarkdown(text3,styles){return hasInlineMarkup(text3)?tokenizeInlineMarkdown(text3).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
279
+ /* @__PURE__ */jsxRuntime.jsx("ul",{"aria-label":CHAT_COPY.suggestions,style:styles.list,children:chips.map((chip,index)=>/* @__PURE__ */jsxRuntime.jsx("li",{children:/* @__PURE__ */jsxRuntime.jsx(Chip,{chip:chip,themed:themed,delayMs:followUpDelayMs(motion,index),durationMs:motion.followUpInMs,risePx:motion.promptRisePx,style:styles.chip,slotStyle:styles.chipSlot,onPress:()=>chip.intent==="vet_report"?onVetPrep?.():onSend(chip.label)})},chip.id))})]})}function Chip({chip:chip,themed:themed,delayMs:delayMs,durationMs:durationMs,risePx:risePx,style:style,slotStyle:slotStyle,onPress:onPress}){let ref=react.useRef(null);return react.useEffect(()=>{let animation=animateEnter(ref.current,{durationMs:durationMs,delayMs:delayMs,fromOpacity:0,fromTranslateY:risePx});return()=>animation?.cancel()},[durationMs,delayMs,risePx]),/* @__PURE__ */jsxRuntime.jsx("button",{ref:ref,type:"button",onClick:onPress,style:{...themed===null?{...style,backgroundColor:chip.background}:{...style,backgroundColor:themed.fill,color:themed.ink},...slotStyle},children:chip.label})}function makeStyles13(theme,desktop){let s=theme.space,r=theme.radius,t=theme.type,titleSize=tierPx(theme,"heading",desktop?TITLE_SIZE_DESKTOP:TITLE_SIZE),chipSize=t.tierSizes.compact.bodyTight;return{wrap:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:s.lg+CHIPS_OFFSET_EXTRA,width:"100%"},title:{margin:0,...headingFaceCss(theme,"medium"),fontSize:titleSize,lineHeight:`${Math.round(titleSize*TITLE_LINE_HEIGHT)}px`,letterSpacing:TITLE_LETTER_SPACING,color:theme.color.brandInk,textAlign:"left",textWrap:"balance"},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"row",flexWrap:"wrap",alignItems:"flex-start",gap:s.sm},chip:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET12,minWidth:MIN_TOUCH_TARGET12,maxWidth:"100%",display:"inline-flex",alignItems:"center",justifyContent:"flex-start",margin:0,padding:`${s.sm-1}px ${s.lg-1}px`,border:"1px solid transparent",borderRadius:r.pill,cursor:"pointer",...faceCss(theme,"bold"),fontSize:chipSize,lineHeight:`${Math.round(chipSize*1.3)}px`,color:QUICK_PROMPT_TEXT_COLOR,textAlign:"left",whiteSpace:"normal"},chipSlot:slotCss(ownGroundSlot(theme.slots.chip),1)}}var INLINE_TOKEN=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function hasInlineMarkup(text3){return text3.includes("*")||text3.includes("`")}function tokenizeInlineMarkdown(text3){let runs=[],cursor2=0;INLINE_TOKEN.lastIndex=0;for(let match=INLINE_TOKEN.exec(text3);match!==null;match=INLINE_TOKEN.exec(text3)){match.index>cursor2&&runs.push({kind:"text",text:text3.slice(cursor2,match.index)});let bold=match[1],italic=match[2],code=match[3];bold!==void 0?runs.push({kind:"bold",text:bold}):italic!==void 0?runs.push({kind:"italic",text:italic}):code!==void 0&&runs.push({kind:"code",text:code}),cursor2=match.index+match[0].length}return cursor2<text3.length&&runs.push({kind:"text",text:text3.slice(cursor2)}),runs}function renderInlineMarkdown(text3,styles){return hasInlineMarkup(text3)?tokenizeInlineMarkdown(text3).map((run,key)=>{switch(run.kind){case"bold":/* @__PURE__ */
279
280
  return jsxRuntime.jsx("strong",{style:styles.bold,children:run.text},key);case"italic":return styles.italic?/* @__PURE__ */jsxRuntime.jsx("em",{style:styles.italic,children:run.text},key):run.text;case"code":return styles.code?/* @__PURE__ */jsxRuntime.jsx("code",{style:styles.code,children:run.text},key):run.text;default:return run.text}}):text3}var DOT_SIZE=6,DOT_RISE=3,LOOP_MS=1e3,STAGGER_MS=150,OPACITY_REST=.25,OPACITY_STATIC=.5,DOT_INDICES=[0,1,2];function TypingIndicator({petName:petName}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles14(theme),[theme]),animate=!theme.motion.reducedMotion;/* @__PURE__ */
280
281
  return jsxRuntime.jsxs("div",{style:styles.card,children:[
281
282
  /* @__PURE__ */jsxRuntime.jsx("p",{style:styles.line,children:forPet(CHAT_COPY.reading,petName)}),
@@ -295,8 +296,8 @@ return jsxRuntime.jsxs("div",{role:"alert",style:styles.centered,children:[
295
296
  /* @__PURE__ */
296
297
  return jsxRuntime.jsxs("div",{ref:scrollerRef,onScroll:onScroll,role:"region","aria-label":CHAT_COPY.transcript,tabIndex:0,style:styles.list,children:[chat.historyCursor?/* @__PURE__ */jsxRuntime.jsx("button",{type:"button",disabled:chat.isLoadingHistory,onClick:()=>{chat.loadOlderMessages()},style:styles.earlierButton,children:chat.isLoadingHistory?HISTORY_COPY.loadingEarlier:HISTORY_COPY.earlier}):null,
297
298
  /* @__PURE__ */jsxRuntime.jsx("ol",{ref:listRef,style:styles.messageList,children:messages.map(message=>message.checkin&&liveCheckins.has(message.id)?/* @__PURE__ */jsxRuntime.jsx(CheckinCard,{message:message,checkin:message.checkin,onAnswer:onAnswerCheckin,onFindVet:onCheckinFindVet},message.id):/* @__PURE__ */jsxRuntime.jsx(MessageRow,{message:message,streaming:message.id===streamingId,chat:chat,images:imagesFor(message),onPreview:onPreview,enters:!settledIds.has(message.id)},message.id))}),chat.reconnecting===true?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.reconnectingCaption,children:CHAT_COPY.reconnecting}):null,awaiting?/* @__PURE__ */jsxRuntime.jsx(TypingIndicator,{petName:petName}):null,notice!==null?/* @__PURE__ */jsxRuntime.jsx(TurnNoticeCard,{notice:notice,onRetry:chat.retryLast,onStartNew:chat.newConversation}):null,
298
- /* @__PURE__ */jsxRuntime.jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt})]})}var NO_IDS=/* @__PURE__ */new Set;function useSettledIds(messages,conversationId2){let ref=react.useRef(null);if(ref.current===null||ref.current.scope!==conversationId2){let carried=ref.current!==null&&ref.current.scope===null?ref.current.ids:null,opened=conversationId2===null?NO_IDS:new Set(messages.map(message=>message.id));ref.current={scope:conversationId2,ids:carried??opened}}return ref.current.ids}function MessageRow({message:message,streaming:streaming,chat:chat,images:images,onPreview:onPreview,enters:enters}){let{theme:theme,styles:styles}=useChatTheme(),motion=useChatMotion(),bubbleRef=react.useRef(null),isUser=message.role==="user",isVet=message.role==="vet";react.useEffect(()=>{if(!enters)return;let animation=popIn(bubbleRef.current,motion);return()=>animation?.cancel()},[]);let text3=useRevealedText(message.text,streaming&&message.role==="assistant",motion),showAssistantName=message.role==="assistant"&&!theme.meta.hidePoweredBy,hiddenSender=isUser?CHAT_COPY.senderUser:message.role==="assistant"&&!showAssistantName?CHAT_COPY.senderAssistant:null,showFooter=message.pending!==true&&!streaming;/* @__PURE__ */
299
- return jsxRuntime.jsxs("li",{style:{...styles.row,...isUser?styles.rowUser:styles.rowAssistant},"aria-busy":message.pending===true?true:void 0,children:[showAssistantName?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.senderRow,children:/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.assistantName,children:CHAT_COPY.assistantName})}):null,isVet?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.senderRow,children:/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.vetSender,children:vetSenderLabel(message)})}):null,
299
+ /* @__PURE__ */jsxRuntime.jsx(FollowUps,{prompts:prompts,onSelectPrompt:onSelectPrompt})]})}var NO_IDS=/* @__PURE__ */new Set;function useSettledIds(messages,conversationId2){let ref=react.useRef(null);if(ref.current===null||ref.current.scope!==conversationId2){let carried=ref.current!==null&&ref.current.scope===null?ref.current.ids:null,opened=conversationId2===null?NO_IDS:new Set(messages.map(message=>message.id));ref.current={scope:conversationId2,ids:carried??opened}}return ref.current.ids}function AssistantSender({showName:showName}){let{theme:theme,styles:styles}=useChatTheme(),avatarUrl=theme.meta.assistantAvatarUrl,[avatarFailed,setAvatarFailed]=react.useState(null),avatar=avatarUrl!==null&&avatarFailed!==avatarUrl?avatarUrl:null;return!showName&&avatar===null?null:/* @__PURE__ */jsxRuntime.jsxs("p",{style:styles.senderRow,children:[avatar!==null?/* @__PURE__ */jsxRuntime.jsx(BrandImage,{src:avatar,alt:"",decorative:true,style:styles.assistantAvatar,onFailed:()=>setAvatarFailed(avatar)}):null,showName?/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.assistantName,children:CHAT_COPY.assistantName}):null]})}function MessageRow({message:message,streaming:streaming,chat:chat,images:images,onPreview:onPreview,enters:enters}){let{theme:theme,styles:styles}=useChatTheme(),motion=useChatMotion(),bubbleRef=react.useRef(null),isUser=message.role==="user",isVet=message.role==="vet";react.useEffect(()=>{if(!enters)return;let animation=popIn(bubbleRef.current,motion);return()=>animation?.cancel()},[]);let text3=useRevealedText(message.text,streaming&&message.role==="assistant",motion),showAssistantName=message.role==="assistant"&&!theme.meta.hidePoweredBy,hiddenSender=isUser?CHAT_COPY.senderUser:message.role==="assistant"&&!showAssistantName?CHAT_COPY.senderAssistant:null,showFooter=message.pending!==true&&!streaming;/* @__PURE__ */
300
+ return jsxRuntime.jsxs("li",{style:{...styles.row,...isUser?styles.rowUser:styles.rowAssistant},"aria-busy":message.pending===true?true:void 0,children:[message.role==="assistant"?/* @__PURE__ */jsxRuntime.jsx(AssistantSender,{showName:showAssistantName}):null,isVet?/* @__PURE__ */jsxRuntime.jsx("p",{style:styles.senderRow,children:/* @__PURE__ */jsxRuntime.jsx("span",{style:styles.vetSender,children:vetSenderLabel(message)})}):null,
300
301
  /* @__PURE__ */jsxRuntime.jsxs("div",{ref:bubbleRef,style:{...styles.bubble,...isUser?styles.bubbleUser:isVet?styles.bubbleVet:styles.bubbleAssistant,...message.pending?styles.bubblePending:null},children:[hiddenSender!==null?/* @__PURE__ */jsxRuntime.jsx("span",{style:VISUALLY_HIDDEN,children:`${hiddenSender}: `}):null,images.length>0?/* @__PURE__ */jsxRuntime.jsx(MessageAttachments,{images:images,onPreview:onPreview}):null,
301
302
  /* @__PURE__ */jsxRuntime.jsx("p",{style:isUser?styles.bubbleTextUser:isVet?styles.bubbleTextVet:styles.bubbleTextAssistant,children:message.role==="assistant"?renderInlineMarkdown(text3,{bold:styles.bubbleBold,italic:styles.bubbleItalic,code:styles.bubbleCode}):text3})]}),message.role==="assistant"&&!streaming?/* @__PURE__ */jsxRuntime.jsx(CitationCards,{citations:message.citations}):null,showFooter?/* @__PURE__ */jsxRuntime.jsx(MessageFooter,{role:message.role,text:message.text,createdAt:message.createdAt,...message.responseId!==void 0?{responseId:message.responseId}:{},sentiment:chat.sentimentByMessage[message.id]??null,feedback:chat.feedback}):null]})}function useChatDraft(send,conversationId2,seed){let[state,setState]=react.useState({send:send,conversationId:conversationId2,text:seed??"",seeded:seed??null}),belongs=state.send===send&&(state.conversationId===null||state.conversationId===conversationId2);react.useEffect(()=>{setState(previous=>{let kept=previous.send===send&&(previous.conversationId===null||previous.conversationId===conversationId2),text3=kept?previous.text:"",seeded=kept?previous.seeded:null,fresh2=seed!=null&&seed!==seeded&&text3.length===0;return{send:send,conversationId:conversationId2,text:fresh2?seed:text3,seeded:fresh2?seed:seeded}})},[send,conversationId2,seed]);let setDraft=react.useCallback(text3=>setState(previous=>({send:send,conversationId:conversationId2,text:text3,seeded:previous.seeded})),[send,conversationId2]);return[belongs?state.text:"",setDraft]}function usePersistedDraft(store,conversationId2,draft,setDraft){let latest=react.useRef({draft:draft,setDraft:setDraft});latest.current={draft:draft,setDraft:setDraft};let asked=react.useRef(null),[settled,setSettled]=react.useState(null);react.useEffect(()=>{if(store===void 0)return;let key=`${conversationId2??""}`;if(asked.current===key)return;asked.current=key;let live=true;return(async()=>{let outcome=await callHostAsync(()=>store.read(conversationId2));if(!live)return;let stored=outcome.ok&&typeof outcome.value=="string"?outcome.value:"";stored.length>0&&latest.current.draft.length===0&&latest.current.setDraft(stored),setSettled(key)})(),()=>{live=false}},[store,conversationId2]),react.useEffect(()=>{store===void 0||settled!==`${conversationId2??""}`||callHost(()=>store.write(conversationId2,draft))},[store,conversationId2,draft,settled])}var MIN_TOUCH_TARGET13=44,MIC_GLYPH_SIZE=18,STOP_GLYPH_SIZE2=14,PULSE_INSET=6,PULSE_LOOP_MS=1200,DISABLED_OPACITY2=.4;function formatDictationElapsed(elapsedMs){let totalSeconds=Math.max(0,Math.floor(elapsedMs/1e3)),minutes=Math.floor(totalSeconds/60),seconds=totalSeconds%60;return`${minutes}:${seconds.toString().padStart(2,"0")}`}function dictationErrorMessage(kind){switch(kind){case"permissionDenied":return CHAT_COPY.micBlocked;case"noSpeech":return CHAT_COPY.noSpeech;case"unavailable":return CHAT_COPY.dictationUnavailable}}function DictationButton({active:active,listening:listening,elapsedMs:elapsedMs,disabled:disabled=false,onToggle:onToggle}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles15(theme),[theme]);/* @__PURE__ */
302
303
  return jsxRuntime.jsxs("span",{style:styles.wrap,children:[listening?/* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:styles.timer,children:formatDictationElapsed(elapsedMs)}):null,
@@ -322,4 +323,4 @@ return jsxRuntime.jsx(CapabilityGate,{capability:"chat",style:style,className:cl
322
323
  /* @__PURE__ */jsxRuntime.jsx(AttachmentImageLightbox,{image:lightbox,onClose:closeLightbox,returnFocusTo:lightboxTrigger}),
323
324
  /* @__PURE__ */jsxRuntime.jsx("div",{"data-ef-focus-ring":"self",style:TELEVET_HOST_SCOPE,children:/* @__PURE__ */jsxRuntime.jsx(EverfurTelevetHost,{})})]})}function useSentImages(messages){let store=react.useRef({pending:[],byMessage:/* @__PURE__ */new Map}),latest=react.useRef(messages);latest.current=messages;let record=react.useCallback((text3,images)=>{images.length!==0&&store.current.pending.push({text:text3,images:images,before:new Set(latest.current.map(message=>message.id))})},[]),imagesFor=react.useCallback(message=>{let current=store.current,known=current.byMessage.get(message.id);if(known!==void 0)return known;if(message.role!=="user")return NO_IMAGES2;let at=current.pending.findIndex(entry2=>entry2.text===message.text&&!entry2.before.has(message.id));if(at<0)return NO_IMAGES2;let[entry]=current.pending.splice(at,1);return entry===void 0?NO_IMAGES2:(current.byMessage.set(message.id,entry.images),entry.images)},[]);return react.useMemo(()=>({record:record,imagesFor:imagesFor}),[record,imagesFor])}function useReplyAnnouncement(chat,petName){let awaiting=awaitingAssistant(chat.messages,chat.isStreaming),[settled,setSettled]=react.useState({send:chat.send,id:chat.conversationId,text:""}),wasStreaming=react.useRef(false),previousScope=react.useRef({send:chat.send,id:chat.conversationId});return react.useEffect(()=>{let previous=previousScope.current;if((previous.send!==chat.send||previous.id!==null&&previous.id!==chat.conversationId)&&(wasStreaming.current=false),previousScope.current={send:chat.send,id:chat.conversationId},wasStreaming.current&&!chat.isStreaming){let last=chat.messages[chat.messages.length-1];setSettled({send:chat.send,id:chat.conversationId,text:last!==void 0&&last.role==="assistant"?CHAT_COPY.answered:""})}wasStreaming.current=chat.isStreaming},[chat.isStreaming,chat.messages,chat.send,chat.conversationId]),awaiting?forPet(CHAT_COPY.reading,petName):settled.send===chat.send&&settled.id===chat.conversationId?settled.text:""}function composerMood(view,level){return level==="emergency"?"urgent":view==="populated"?"followUp":"ask"}function PetSetupNotice({petRef:petRef2,pet:pet,onRegistered:onRegistered}){let{styles:styles}=useChatTheme(),setup=useChatPetRegistration(petRef2,pet,onRegistered);return setup.status!=="failed"||setup.error===null?null:/* @__PURE__ */jsxRuntime.jsxs("div",{role:"alert",style:styles.setupNotice,children:[
324
325
  /* @__PURE__ */jsxRuntime.jsx("span",{style:styles.setupNoticeText,children:setup.error.displayMessage}),
325
- /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:setup.retry,style:styles.setupNoticeAction,children:CHAT_COPY.retry})]})}function useEverfurPetProfile(petRef2){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=react.useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),key=react.useMemo(()=>({repository:repository,petRef:petRef2}),[repository,petRef2]),[state,setState]=react.useState({key:key,profile:null,loading:petRef2!==null,error:null}),current=state.key===key?state:{profile:null,loading:petRef2!==null,error:null},generation=react.useRef(0),load=react.useCallback(async()=>{let request=++generation.current;if(key.petRef===null){setState({key:key,profile:null,loading:false,error:null});return}setState(previous=>({key:key,profile:previous.key===key?previous.profile:null,loading:true,error:null}));let result=await key.repository.getPetProfile(key.petRef);request===generation.current&&setState(result.ok?{key:key,profile:result.value,loading:false,error:null}:{key:key,profile:null,loading:false,error:result.error})},[key]);return react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]),react.useMemo(()=>({profile:current.profile,loading:current.loading,error:current.error,refresh:load}),[current.profile,current.loading,current.error,load])}function EverfurThemeProvider(props){return react.createElement(EverfurThemeProviderCore,{clientTheme:props.clientTheme??null,seams:webThemeSeams,children:props.children})}exports.APPEARANCE_PRESETS=APPEARANCE_PRESETS;exports.APPEARANCE_PRESET_NAMES=APPEARANCE_PRESET_NAMES;exports.APPEARANCE_SIZE_RANGES=APPEARANCE_SIZE_RANGES;exports.CapabilityGate=CapabilityGate;exports.EverfurChat=EverfurChat;exports.EverfurConfigError=EverfurConfigError;exports.EverfurProvider=EverfurProvider;exports.EverfurThemeProvider=EverfurThemeProvider;exports.EverfurThrownError=EverfurThrownError;exports.THEME_SLOT_KEYS=THEME_SLOT_KEYS;exports.THEME_SLOT_NAMES=THEME_SLOT_NAMES;exports.canonicalPetSpecies=canonicalPetSpecies;exports.categoryFor=categoryFor;exports.conversationId=conversationId;exports.createLocalStorageKv=createLocalStorageKv;exports.createWebAttachmentTransport=createWebAttachmentTransport;exports.expandAppearance=expandAppearance;exports.face=face;exports.faceCss=faceCss;exports.fileToAttachmentHandle=fileToAttachmentHandle;exports.isErr=isErr;exports.isOk=isOk;exports.isRetryableCode=isRetryableCode;exports.petRef=petRef;exports.previewTheme=previewTheme;exports.themeAdjustments=themeAdjustments;exports.unwrap=unwrap;exports.useCapability=useCapability;exports.useChatAttachments=useChatAttachments;exports.useEverfur=useEverfur;exports.useEverfurChat=useEverfurChat;exports.useEverfurPetProfile=useEverfurPetProfile;exports.useEverfurPets=useEverfurPets;exports.useEverfurTheme=useEverfurTheme;exports.userFacingError=userFacingError;exports.userRef=userRef;
326
+ /* @__PURE__ */jsxRuntime.jsx("button",{type:"button",onClick:setup.retry,style:styles.setupNoticeAction,children:CHAT_COPY.retry})]})}function useEverfurPetProfile(petRef2){let{runtime:runtime,userRef:userRef2,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=react.useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef2)),[runtime,userRef2,scopeEpoch]),key=react.useMemo(()=>({repository:repository,petRef:petRef2}),[repository,petRef2]),[state,setState]=react.useState({key:key,profile:null,loading:petRef2!==null,error:null}),current=state.key===key?state:{profile:null,loading:petRef2!==null,error:null},generation=react.useRef(0),load=react.useCallback(async()=>{let request=++generation.current;if(key.petRef===null){setState({key:key,profile:null,loading:false,error:null});return}setState(previous=>({key:key,profile:previous.key===key?previous.profile:null,loading:true,error:null}));let result=await key.repository.getPetProfile(key.petRef);request===generation.current&&setState(result.ok?{key:key,profile:result.value,loading:false,error:null}:{key:key,profile:null,loading:false,error:result.error})},[key]);return react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]),react.useMemo(()=>({profile:current.profile,loading:current.loading,error:current.error,refresh:load}),[current.profile,current.loading,current.error,load])}function EverfurThemeProvider(props){return react.createElement(EverfurThemeProviderCore,{clientTheme:props.clientTheme??null,seams:webThemeSeams,children:props.children})}exports.APPEARANCE_PRESETS=APPEARANCE_PRESETS;exports.APPEARANCE_PRESET_NAMES=APPEARANCE_PRESET_NAMES;exports.APPEARANCE_SIZE_RANGES=APPEARANCE_SIZE_RANGES;exports.CapabilityGate=CapabilityGate;exports.EverfurChat=EverfurChat;exports.EverfurConfigError=EverfurConfigError;exports.EverfurProvider=EverfurProvider;exports.EverfurThemeProvider=EverfurThemeProvider;exports.EverfurThrownError=EverfurThrownError;exports.THEME_SLOT_KEYS=THEME_SLOT_KEYS;exports.THEME_SLOT_NAMES=THEME_SLOT_NAMES;exports.canonicalPetSpecies=canonicalPetSpecies;exports.categoryFor=categoryFor;exports.conversationId=conversationId;exports.createLocalStorageKv=createLocalStorageKv;exports.createWebAttachmentTransport=createWebAttachmentTransport;exports.expandAppearance=expandAppearance;exports.face=face;exports.faceCss=faceCss;exports.fileToAttachmentHandle=fileToAttachmentHandle;exports.headingFace=headingFace;exports.headingFaceCss=headingFaceCss;exports.isErr=isErr;exports.isOk=isOk;exports.isRetryableCode=isRetryableCode;exports.petRef=petRef;exports.previewTheme=previewTheme;exports.themeAdjustments=themeAdjustments;exports.unwrap=unwrap;exports.useCapability=useCapability;exports.useChatAttachments=useChatAttachments;exports.useEverfur=useEverfur;exports.useEverfurChat=useEverfurChat;exports.useEverfurPetProfile=useEverfurPetProfile;exports.useEverfurPets=useEverfurPets;exports.useEverfurTheme=useEverfurTheme;exports.userFacingError=userFacingError;exports.userRef=userRef;