@everfur/sdk 0.9.2 → 0.10.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 (135) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +17 -8
  3. package/dist/{Chat-Cugs9Dsl.d.ts → Chat-DwGk5APA.d.ts} +3 -3
  4. package/dist/{Chat-B7oN62ww.d.cts → Chat-Ml-HlOiV.d.cts} +3 -3
  5. package/dist/{DepthViews-GxV7wSzT.d.cts → DepthViews-DAJySZqL.d.cts} +1 -1
  6. package/dist/{DepthViews-CiYBIBEZ.d.ts → DepthViews-DwCS5KKh.d.ts} +1 -1
  7. package/dist/{DepthViews-CUNmy99u.d.cts → DepthViews-PgA2KvTE.d.cts} +1 -1
  8. package/dist/{DepthViews-C6qFJ3fV.d.ts → DepthViews-kM-_Mn2x.d.ts} +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-20X7Vuip.d.ts → attachments-BH0vdghi.d.ts} +2 -2
  14. package/dist/{attachments-HXFmzk-D.d.cts → attachments-BV1Mbqm-.d.cts} +5 -5
  15. package/dist/{attachments-DN2cNGwe.d.ts → attachments-DWv9stp1.d.ts} +5 -5
  16. package/dist/{attachments-CkaPnIUw.d.cts → attachments-DaWeeeBW.d.cts} +2 -2
  17. package/dist/{bookingCopy-B5igVNE0.d.ts → bookingCopy-Cc3Cl-IJ.d.ts} +2 -2
  18. package/dist/{bookingCopy-pJpizqgz.d.cts → bookingCopy-DRwrhDUe.d.cts} +2 -2
  19. package/dist/{casesRepository-DFoK5N1O.d.cts → casesRepository-BhfPDWhY.d.cts} +1 -1
  20. package/dist/{casesRepository-qAkKKgji.d.ts → casesRepository-DMkRRKr8.d.ts} +1 -1
  21. package/dist/chat/index.cjs +16 -15
  22. package/dist/chat/index.d.cts +9 -9
  23. package/dist/chat/index.d.ts +9 -9
  24. package/dist/chat/index.js +16 -15
  25. package/dist/client/index.cjs +2 -2
  26. package/dist/client/index.d.cts +6 -6
  27. package/dist/client/index.d.ts +6 -6
  28. package/dist/client/index.js +2 -2
  29. package/dist/{config-BB7e52FP.d.ts → config-CuOczZUI.d.ts} +1 -1
  30. package/dist/{config-u6rK4mKt.d.cts → config-lilR0260.d.cts} +1 -1
  31. package/dist/consent/index.cjs +1 -1
  32. package/dist/consent/index.d.cts +5 -5
  33. package/dist/consent/index.d.ts +5 -5
  34. package/dist/consent/index.js +1 -1
  35. package/dist/{context-BZ1k4qE3.d.cts → context-BA6X6ZHd.d.cts} +13 -5
  36. package/dist/{context-CJYmubjx.d.ts → context-CL3cR0MA.d.ts} +13 -5
  37. package/dist/{copy-CtfctY-J.d.ts → copy-A2n7xXsL.d.ts} +2 -2
  38. package/dist/{copy-DCO_lUXd.d.cts → copy-DkoUo0VR.d.cts} +2 -2
  39. package/dist/core/index.cjs +6 -7
  40. package/dist/core/index.d.cts +12 -12
  41. package/dist/core/index.d.ts +12 -12
  42. package/dist/core/index.js +6 -7
  43. package/dist/{depth-_vMRMm4x.d.ts → depth-6_BYIt0s.d.ts} +2 -2
  44. package/dist/{depth-C_ym3qyi.d.cts → depth-DOPtk0vF.d.cts} +2 -2
  45. package/dist/{entitlementRepository-tSY9WWad.d.ts → entitlementRepository-BE-L6vX1.d.ts} +2 -2
  46. package/dist/{entitlementRepository-DA04yM54.d.cts → entitlementRepository-Blh38A2b.d.cts} +2 -2
  47. package/dist/{identity-D5uywCtp.d.ts → identity-4lohfP2L.d.ts} +8 -2
  48. package/dist/{identity-CUynm8S2.d.cts → identity-YXqHjBln.d.cts} +8 -2
  49. package/dist/index.cjs +16 -16
  50. package/dist/index.d.cts +15 -14
  51. package/dist/index.d.ts +15 -14
  52. package/dist/index.js +16 -16
  53. package/dist/notifications/index.cjs +1 -1
  54. package/dist/notifications/index.d.cts +2 -2
  55. package/dist/notifications/index.d.ts +2 -2
  56. package/dist/notifications/index.js +1 -1
  57. package/dist/{pets-mnbN0kZG.d.ts → pets-DzXi_9hY.d.ts} +1 -1
  58. package/dist/{pets-BrdkpNJH.d.cts → pets-m61lisZt.d.cts} +1 -1
  59. package/dist/{petsRepository-RGI_xPK1.d.ts → petsRepository-B1I6Lq_m.d.ts} +1 -1
  60. package/dist/{petsRepository-CQgzEFyz.d.cts → petsRepository-CQeuDdDC.d.cts} +1 -1
  61. package/dist/photo/index.cjs +1 -1
  62. package/dist/photo/index.js +1 -1
  63. package/dist/{ports-Cu_Wc5Aw.d.ts → ports-CrGAcey9.d.ts} +6 -4
  64. package/dist/{ports-DibY-h60.d.cts → ports-DUqO_XX0.d.cts} +6 -4
  65. package/dist/records/depth/index.cjs +3 -3
  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 +3 -3
  69. package/dist/records/index.cjs +7 -7
  70. package/dist/records/index.d.cts +9 -9
  71. package/dist/records/index.d.ts +9 -9
  72. package/dist/records/index.js +7 -7
  73. package/dist/{requestFunnel-BkSFsLKh.d.ts → requestFunnel-B86gQFka.d.ts} +2 -2
  74. package/dist/{requestFunnel-nmhlEdbM.d.cts → requestFunnel-hXkP5T7K.d.cts} +2 -2
  75. package/dist/{runtimeTypes-CWG1Cm4N.d.cts → runtimeTypes-Bt_tIj3h.d.cts} +29 -5
  76. package/dist/{runtimeTypes-CU2xVmiQ.d.ts → runtimeTypes-DXKxY2yq.d.ts} +29 -5
  77. package/dist/server/events/index.cjs +2 -2
  78. package/dist/server/events/index.d.cts +25 -6
  79. package/dist/server/events/index.d.ts +25 -6
  80. package/dist/server/events/index.js +2 -2
  81. package/dist/server/index.cjs +4 -4
  82. package/dist/server/index.d.cts +5 -4
  83. package/dist/server/index.d.ts +5 -4
  84. package/dist/server/index.js +4 -4
  85. package/dist/televet/booking/index.cjs +18 -15
  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 +19 -16
  89. package/dist/televet/index.cjs +1 -1
  90. package/dist/televet/index.js +1 -1
  91. package/dist/testing/index.d.cts +1 -1
  92. package/dist/testing/index.d.ts +1 -1
  93. package/dist/testing/rn/index.cjs +1 -1
  94. package/dist/testing/rn/index.d.cts +7 -7
  95. package/dist/testing/rn/index.d.ts +7 -7
  96. package/dist/testing/rn/index.js +1 -1
  97. package/dist/testing/web/index.cjs +1 -1
  98. package/dist/testing/web/index.d.cts +7 -7
  99. package/dist/testing/web/index.d.ts +7 -7
  100. package/dist/testing/web/index.js +1 -1
  101. package/dist/{timelineRows-PWRoTntZ.d.ts → timelineRows-C2ObTmfN.d.ts} +1 -1
  102. package/dist/{timelineRows-CYF_I5Aq.d.cts → timelineRows-CrA-ePrQ.d.cts} +1 -1
  103. package/dist/{useRecordsDepth-Cg4cc4bQ.d.cts → useRecordsDepth-Dcr9y6i-.d.cts} +1 -1
  104. package/dist/{useRecordsDepth-eS9BJv_a.d.ts → useRecordsDepth-NQNJaGyk.d.ts} +1 -1
  105. package/dist/video/index.cjs +1 -1
  106. package/dist/video/index.js +1 -1
  107. package/dist/{view-n_oSGiiT.d.ts → view-DWJa2L0U.d.ts} +2 -2
  108. package/dist/{view-D4UOm-yo.d.cts → view-Dk7xpBJ4.d.cts} +2 -2
  109. package/dist/web/consent/index.cjs +1 -1
  110. package/dist/web/consent/index.d.cts +5 -5
  111. package/dist/web/consent/index.d.ts +5 -5
  112. package/dist/web/consent/index.js +1 -1
  113. package/dist/web/index.cjs +13 -12
  114. package/dist/web/index.d.cts +17 -16
  115. package/dist/web/index.d.ts +17 -16
  116. package/dist/web/index.js +13 -12
  117. package/dist/web/notifications/index.cjs +1 -1
  118. package/dist/web/notifications/index.d.cts +3 -3
  119. package/dist/web/notifications/index.d.ts +3 -3
  120. package/dist/web/notifications/index.js +1 -1
  121. package/dist/web/records/depth/index.cjs +3 -3
  122. package/dist/web/records/depth/index.d.cts +7 -7
  123. package/dist/web/records/depth/index.d.ts +7 -7
  124. package/dist/web/records/depth/index.js +3 -3
  125. package/dist/web/records/index.cjs +7 -7
  126. package/dist/web/records/index.d.cts +9 -9
  127. package/dist/web/records/index.d.ts +9 -9
  128. package/dist/web/records/index.js +7 -7
  129. package/dist/web/televet/booking/index.cjs +4 -4
  130. package/dist/web/televet/booking/index.d.cts +6 -6
  131. package/dist/web/televet/booking/index.d.ts +6 -6
  132. package/dist/web/televet/booking/index.js +4 -4
  133. package/dist/web/televet/index.cjs +1 -1
  134. package/dist/web/televet/index.js +1 -1
  135. package/package.json +1 -1
@@ -89,7 +89,7 @@ return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fiel
89
89
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
90
90
  /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row2=>row2.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row2=BY_KEY.get(candidate+key);if(row2)return row2}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});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 row2=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)),row2);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 ok(value,warning){/* @__PURE__ */
91
91
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
92
- return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function 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}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp2({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
92
+ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function 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 ctx.identity.reportRejected?.(),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 ctx.identity.reportRejected?.(),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?(ctx.identity.reportRejected?.(),err(authRejectedError(retry.error.httpStatus))):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp2({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
93
93
  /* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
94
94
  return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}var TELEVET_ATTACHMENT_MIME_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/webp","image/heic","image/heif","application/pdf","text/csv","video/mp4","video/quicktime"]),TELEVET_ATTACHMENT_MAX_BYTES=25*1024*1024,TELEVET_ATTACHMENT_VIDEO_MAX_BYTES=200*1024*1024,SUFFIX_TYPES=[[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".heic","image/heic"],[".heif","image/heif"],[".pdf","application/pdf"],[".csv","text/csv"],[".mp4","video/mp4"],[".mov","video/quicktime"]];function televetAttachmentContentType(filename,mimeType){let direct=(mimeType??"").trim().toLowerCase();if(direct==="image/jpg")return"image/jpeg";if(TELEVET_ATTACHMENT_MIME_TYPES.includes(direct))return direct;if(direct.length>0)return null;let name=filename.toLowerCase();return SUFFIX_TYPES.find(([suffix])=>name.endsWith(suffix))?.[1]??null}function televetAttachmentRefusal(pick2){let type=televetAttachmentContentType(pick2.filename,pick2.mimeType);if(type===null)return"type";if(!Number.isFinite(pick2.fileSize)||pick2.fileSize<=0)return"unreadable";let ceiling=type.startsWith("video/")?TELEVET_ATTACHMENT_VIDEO_MAX_BYTES:TELEVET_ATTACHMENT_MAX_BYTES;return pick2.fileSize<=ceiling?null:"size"}function parseTelevetAttachmentPolicy(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,str4=v=>typeof v=="string"&&v.length>0?v:null,num3=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadUrl=str4(o.upload_url),s3Key=str4(o.s3_key);if(uploadUrl===null||s3Key===null)return null;let fields={},rawFields=o.upload_fields;if(typeof rawFields=="object"&&rawFields!==null)for(let[key,value]of Object.entries(rawFields))typeof value=="string"&&(fields[key]=value);/* @__PURE__ */
95
95
  return Object.freeze({upload_id:str4(o.upload_id)??"",upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num3(o.expires_in_seconds)??0,max_content_length:num3(o.max_content_length)??TELEVET_ATTACHMENT_MAX_BYTES,s3_key:s3Key,purpose:str4(o.purpose)})}function wireCodeOf(raw){if(typeof raw!="object"||raw===null)return null;let scopes=[raw,raw.detail,raw.error];for(let scope of scopes)if(!(typeof scope!="object"||scope===null))for(let key of["error","code"]){let value=scope[key];if(typeof value=="string"&&value.length>0)return value}return null}function televetAttachmentInitiateFailure(error){if(error.httpStatus===404)return"dark";if(error.httpStatus===400){let code=wireCodeOf(error.raw);if(code==="FILE_TOO_LARGE")return"size";if(code==="INVALID_CONTENT_TYPE")return"type"}return"failed"}var TELEVET_BOOKING_NOT_LIVE="televet_booking_not_live";function televetBookingNotLiveError(status){return makeEverfurError("conflict",{retryable:false,reasonCode:TELEVET_BOOKING_NOT_LIVE,wireMessage:`the booking was answered with a consult whose status is ${status}, which is not a live visit`})}var TELEVET_BOOKING_KEY_REUSED="televet_booking_key_reused",KEY_REUSED_WIRE_CODE="IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST";function foldTelevetBookingKeyReused(error){return error.httpStatus!==409||error.reasonCode===TELEVET_BOOKING_KEY_REUSED||details(error)?.code!==KEY_REUSED_WIRE_CODE?error:makeEverfurError(error.code,{retryable:false,httpStatus:409,...error.requestId!==void 0?{requestId:error.requestId}:{},wireCode:KEY_REUSED_WIRE_CODE,reasonCode:TELEVET_BOOKING_KEY_REUSED,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}function details(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let direct=raw,nested=direct.detail??direct.error;return typeof nested=="object"&&nested!==null?nested:direct}function categoriesOf(error){let raw=details(error)?.categories;return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.filter(c=>typeof c=="string")):/* @__PURE__ */Object.freeze([])}function retryAfterOf(error){let raw=details(error)?.retry_after_seconds;return typeof raw=="number"&&Number.isFinite(raw)&&raw>0?raw:null}function messageOf(error){let wire=error.wireMessage;if(typeof wire=="string"&&wire.trim().length>0)return wire.trim();let raw=details(error)?.message;return typeof raw=="string"&&raw.trim().length>0?raw.trim():null}function codeOf(error){let reason=error.reasonCode;if(typeof reason=="string"&&reason.length>0)return reason;let raw=details(error),code=raw?.code??raw?.error_code;return typeof code=="string"&&code.length>0?code:null}function televetBookingRefusal(error){let status=error.httpStatus;if(status===402)/* @__PURE__ */return Object.freeze({kind:"not_entitled"});if(status===429||error.code==="rateLimited"||error.code==="quotaExceeded")/* @__PURE__ */
@@ -168,10 +168,10 @@ return jsxRuntime.jsxs("div",{"data-testid":"televet-booking-not-entitled",style
168
168
  /* @__PURE__ */jsxRuntime.jsxs("div",{"data-testid":"televet-booking-state-blocked",children:[
169
169
  /* @__PURE__ */jsxRuntime.jsx(TelevetStateCard,{title:TELEVET_BOOKING_COPY_WEB.stateBlockedTitle}),
170
170
  /* @__PURE__ */jsxRuntime.jsx(TelevetStateInterestAction,{action:stateInterest,testIDPrefix:"televet-state-interest-state-blocked"})]}):step==="reason"&&triageOpen?/* @__PURE__ */jsxRuntime.jsx(TelevetEarlyEmergency,{...petName!==void 0?{petName:petName}:{},...primaryVet?{primaryVet:primaryVet}:{},onFindEmergencyVet:onFindEmergencyVet,onContinue:onAcknowledgeEmergency}):null}function televetClinicianOutcomeApplies(state){return state.noState?true:state.isPending||state.isError?false:state.isEmpty||state.notEntitled}function TelevetClinicianOutcome({state:state,cause:cause,locationStatus:locationStatus,onRequestLocation:onRequestLocation,onRetry:onRetry,stateInterest:stateInterest=null,renderUnavailable:renderUnavailable}){return state.noState?
171
- /* @__PURE__ */jsxRuntime.jsx("div",{"data-testid":"televet-booking-location-unknown",children:/* @__PURE__ */jsxRuntime.jsx(TelevetStateCard,{title:locationStatus==="blocked"?TELEVET_BOOKING_COPY_WEB.locationBlockedTitle:locationStatus==="unavailable"?TELEVET_BOOKING_COPY_WEB.locationUnavailableTitle:TELEVET_BOOKING_COPY_WEB.locationUnknownTitle,message:locationStatus==="blocked"?TELEVET_BOOKING_COPY_WEB.locationBlockedBody:locationStatus==="unavailable"?TELEVET_BOOKING_COPY_WEB.locationUnavailableBody:TELEVET_BOOKING_COPY_WEB.locationUnknownBody,actionLabel:onRequestLocation&&locationStatus!=="blocked"?TELEVET_BOOKING_COPY_WEB.locationUnknownCta:void 0,onAction:locationStatus==="blocked"?void 0:onRequestLocation})}):state.isEmpty?/* @__PURE__ */jsxRuntime.jsx(TelevetClinicianEmptyState,{cause:cause,onRetry:onRetry,stateInterest:stateInterest}):/* @__PURE__ */jsxRuntime.jsx(EntitlementPausedState,{...renderUnavailable?{renderUnavailable:renderUnavailable}:{}})}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")}function composite(fg,bg){let a=fg.a,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(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 PINK_SOFT_ALPHA=.22,TINT_SOFT_ALPHA=.5,EVERFUR_PINK="#FFC3BC";function televetPlainLook(theme){let c=theme.color;return{ink:c.brandInk,text:c.text.primary,muted:c.text.muted,line:c.borderRingCream,mist:c.surfaceSubtle,surface:c.surface,pink:c.highlight,onPink:c.onHighlight,go:c.mark,alert:c.danger,alertWash:c.badgeBgCritical}}function televetLook(theme){let c=theme.color,everfurPink=parseColor(c.highlight)===EVERFUR_PINK,soft=withAlpha(c.highlight,everfurPink?PINK_SOFT_ALPHA:TINT_SOFT_ALPHA);return{...televetPlainLook(theme),pinkSoft:(soft===null?null:flattenOnto(soft,c.surface))??c.surface}}function televetConsultCalendarKey(consultId){return`televet-consult-${consultId}`}function TelevetBookedScreen({consult:consult,petName:petName,onDone:onDone,onAddToCalendar:onAddToCalendar,canJoinInApp:canJoinInApp=false,lengthMinutes:lengthMinutes,sharedRecords:sharedRecords=false,sentPhoto:sentPhoto=false}){let theme=useEverfurTheme(),shared=useBookingStyles(),styles=react.useMemo(()=>makeStyles2(theme),[theme]),titleId=`${react.useId()}-booked-title`,Title=headingTag(useNestedHeadingLevel()),[calendarState,setCalendarState]=react.useState("idle"),addToCalendar=async()=>{if(!onAddToCalendar)return;setCalendarState("saving");let start=new Date(consult.scheduledAt);if(Number.isNaN(start.getTime())){setCalendarState("failed");return}let minutes=typeof lengthMinutes=="number"&&Number.isFinite(lengthMinutes)&&lengthMinutes>0?lengthMinutes:CONSULT_MINUTES,outcome=await callHostAsync(onAddToCalendar,{key:televetConsultCalendarKey(consult.consultId),title:TELEVET_BOOKING_COPY_WEB.visit.title,startDate:start,endDate:new Date(start.getTime()+minutes*6e4),alarmOffsetMinutes:-30});if(!outcome.ok){setCalendarState("failed");return}setCalendarState(outcome.value===true?"saved":outcome.value==="handed-off"?"idle":"failed")},steps=[TELEVET_BOOKING_COPY_WEB.booked.remindPromise,sharedRecords&&consult.clinicianName?fill(sentPhoto?TELEVET_BOOKING_COPY_WEB.booked.recordsPhotoPromiseTemplate:TELEVET_BOOKING_COPY_WEB.booked.recordsPromiseTemplate,{pet:petName??TELEVET_BOOKING_COPY_WEB.petFallback,vet:consult.clinicianName}):fill(TELEVET_BOOKING_COPY_WEB.booked.summaryPromise,{pet:petName??""}),...canJoinInApp?[TELEVET_BOOKING_COPY_WEB.booked.joinPromise]:[]];if(!isTelevetBookingCopyReady())/* @__PURE__ */
171
+ /* @__PURE__ */jsxRuntime.jsx("div",{"data-testid":"televet-booking-location-unknown",children:/* @__PURE__ */jsxRuntime.jsx(TelevetStateCard,{title:locationStatus==="blocked"?TELEVET_BOOKING_COPY_WEB.locationBlockedTitle:locationStatus==="unavailable"?TELEVET_BOOKING_COPY_WEB.locationUnavailableTitle:TELEVET_BOOKING_COPY_WEB.locationUnknownTitle,message:locationStatus==="blocked"?TELEVET_BOOKING_COPY_WEB.locationBlockedBody:locationStatus==="unavailable"?TELEVET_BOOKING_COPY_WEB.locationUnavailableBody:TELEVET_BOOKING_COPY_WEB.locationUnknownBody,actionLabel:onRequestLocation&&locationStatus!=="blocked"?TELEVET_BOOKING_COPY_WEB.locationUnknownCta:void 0,onAction:locationStatus==="blocked"?void 0:onRequestLocation})}):state.isEmpty?/* @__PURE__ */jsxRuntime.jsx(TelevetClinicianEmptyState,{cause:cause,onRetry:onRetry,stateInterest:stateInterest}):/* @__PURE__ */jsxRuntime.jsx(EntitlementPausedState,{...renderUnavailable?{renderUnavailable:renderUnavailable}:{}})}function clinicianInitial(displayName){return displayName.trim().replace(/^dr\.?\s+/i,"").slice(0,1).toUpperCase()}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")}function composite(fg,bg){let a=fg.a,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(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 PINK_SOFT_ALPHA=.22,TINT_SOFT_ALPHA=.5,EVERFUR_PINK="#FFC3BC";function televetPlainLook(theme){let c=theme.color;return{ink:c.brandInk,text:c.text.primary,muted:c.text.muted,line:c.borderRingCream,mist:c.surfaceSubtle,surface:c.surface,pink:c.highlight,onPink:c.onHighlight,go:c.mark,alert:c.danger,alertWash:c.badgeBgCritical}}function televetLook(theme){let c=theme.color,everfurPink=parseColor(c.highlight)===EVERFUR_PINK,soft=withAlpha(c.highlight,everfurPink?PINK_SOFT_ALPHA:TINT_SOFT_ALPHA);return{...televetPlainLook(theme),pinkSoft:(soft===null?null:flattenOnto(soft,c.surface))??c.surface}}function televetConsultCalendarKey(consultId){return`televet-consult-${consultId}`}function TelevetBookedScreen({consult:consult,petName:petName,onDone:onDone,onAddToCalendar:onAddToCalendar,canJoinInApp:canJoinInApp=false,lengthMinutes:lengthMinutes,sharedRecords:sharedRecords=false,sentPhoto:sentPhoto=false}){let theme=useEverfurTheme(),shared=useBookingStyles(),styles=react.useMemo(()=>makeStyles2(theme),[theme]),titleId=`${react.useId()}-booked-title`,Title=headingTag(useNestedHeadingLevel()),[calendarState,setCalendarState]=react.useState("idle"),addToCalendar=async()=>{if(!onAddToCalendar)return;setCalendarState("saving");let start=new Date(consult.scheduledAt);if(Number.isNaN(start.getTime())){setCalendarState("failed");return}let minutes=typeof lengthMinutes=="number"&&Number.isFinite(lengthMinutes)&&lengthMinutes>0?lengthMinutes:CONSULT_MINUTES,outcome=await callHostAsync(onAddToCalendar,{key:televetConsultCalendarKey(consult.consultId),title:TELEVET_BOOKING_COPY_WEB.visit.title,startDate:start,endDate:new Date(start.getTime()+minutes*6e4),alarmOffsetMinutes:-30});if(!outcome.ok){setCalendarState("failed");return}setCalendarState(outcome.value===true?"saved":outcome.value==="handed-off"?"idle":"failed")},steps=[TELEVET_BOOKING_COPY_WEB.booked.remindPromise,sharedRecords&&consult.clinicianName?fill(sentPhoto?TELEVET_BOOKING_COPY_WEB.booked.recordsPhotoPromiseTemplate:TELEVET_BOOKING_COPY_WEB.booked.recordsPromiseTemplate,{pet:petName??TELEVET_BOOKING_COPY_WEB.petFallback,vet:consult.clinicianName}):fill(TELEVET_BOOKING_COPY_WEB.booked.summaryPromise,{pet:petName??""}),...canJoinInApp?[TELEVET_BOOKING_COPY_WEB.booked.joinPromise]:[]];if(!isTelevetBookingCopyReady())/* @__PURE__ */
172
172
  return jsxRuntime.jsx("div",{style:styles.screen,"data-testid":"televet-booked-copy-unapproved"});let vetName=consult.clinicianName?.trim()??"";/* @__PURE__ */
173
173
  return jsxRuntime.jsxs("section",{style:styles.screen,"aria-labelledby":titleId,"data-testid":"televet-booked",children:[
174
- /* @__PURE__ */jsxRuntime.jsx("div",{"aria-hidden":"true",style:styles.avatar,children:vetName.length>0?vetName.replace(/^dr\.?\s+/i,"").slice(0,1).toUpperCase():null}),
174
+ /* @__PURE__ */jsxRuntime.jsx("div",{"aria-hidden":"true",style:styles.avatar,children:vetName.length>0?clinicianInitial(vetName):null}),
175
175
  /* @__PURE__ */jsxRuntime.jsx(Title,{id:titleId,style:styles.title,children:vetName.length>0?fill(TELEVET_BOOKING_COPY_WEB.bookedTitleTemplate,{vet:vetName}):TELEVET_BOOKING_COPY_WEB.bookedTitle}),
176
176
  /* @__PURE__ */jsxRuntime.jsx("p",{style:styles.when,children:petName?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
177
177
  /* @__PURE__ */jsxRuntime.jsx("time",{dateTime:consult.scheduledAt,children:formatBookedWhen(consult.scheduledAt)}),fill(TELEVET_BOOKING_COPY_WEB.bookedLeadTemplate,{when:"",pet:petName})]}):/* @__PURE__ */jsxRuntime.jsx("time",{dateTime:consult.scheduledAt,children:formatBookedWhen(consult.scheduledAt)})}),
@@ -249,7 +249,7 @@ return jsxRuntime.jsx("div",{role:"progressbar","aria-label":TELEVET_BOOKING_COP
249
249
  return jsxRuntime.jsx("div",{"data-testid":"televet-clinicians-error",children:/* @__PURE__ */jsxRuntime.jsx(TelevetLoadFailed,{error:error,title:TELEVET_BOOKING_COPY_WEB.chrome.loadFailedTitle,actionLabel:TELEVET_BOOKING_COPY_WEB.chrome.retryCta,onRetry:onRetry})});if(clinicians.length===0)/* @__PURE__ */
250
250
  return jsxRuntime.jsx("div",{"data-testid":"televet-clinicians-empty",children:/* @__PURE__ */jsxRuntime.jsx(TelevetStateCard,{title:TELEVET_BOOKING_COPY_WEB.noCliniciansTitle,message:TELEVET_BOOKING_COPY_WEB.noCliniciansBody,actionLabel:TELEVET_BOOKING_COPY_WEB.noCliniciansRetryCta,onAction:onRetry})});let vet=clinicians.find(c=>c.clinicianId===selectedId)??clinicians[0];if(vet===void 0)return null;let code=stateCode?.trim().toUpperCase()??"",licensedHere=code.length>0&&vet.licensedStates.some(l=>l.state.trim().toUpperCase()===code);/* @__PURE__ */
251
251
  return jsxRuntime.jsx(TelevetStepFrame,{headingRef:headingRef,heading:TELEVET_BOOKING_COPY_WEB.yourVetTitle,testID:"televet-clinicians",footer:/* @__PURE__ */jsxRuntime.jsx(TelevetButton,{label:TELEVET_BOOKING_COPY_WEB.continueCta,kind:"primary",size:"lg",onPress:()=>onSelect(vet.clinicianId),testID:`televet-clinician-${vet.clinicianId}`}),children:/* @__PURE__ */jsxRuntime.jsxs("div",{style:local.meet,children:[
252
- /* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:local.vetAvatar,children:initialOf(vet.displayName)}),
252
+ /* @__PURE__ */jsxRuntime.jsx("span",{"aria-hidden":"true",style:local.vetAvatar,children:clinicianInitial(vet.displayName)||PERSON_GLYPH}),
253
253
  /* @__PURE__ */jsxRuntime.jsx("p",{style:local.vetName,children:vet.credentials?`${vet.displayName}, ${vet.credentials}`:vet.displayName}),licensedHere&&stateName?/* @__PURE__ */jsxRuntime.jsx("div",{style:local.pills,children:/* @__PURE__ */jsxRuntime.jsx("span",{style:local.pill,"data-testid":"televet-vet-licensed",children:fill(TELEVET_BOOKING_COPY_WEB.licensedPillTemplate,{state:stateName})})}):null,vet.rating!==null&&vet.ratingCount!==null?/* @__PURE__ */jsxRuntime.jsx("p",{style:local.vetRating,"data-testid":"televet-vet-rating",children:`★ ${String(vet.rating)} · ${String(vet.ratingCount)} ${TELEVET_BOOKING_COPY_WEB.reviewsLabel}`}):null,vet.bio?/* @__PURE__ */jsxRuntime.jsx("p",{style:local.vetBio,"data-testid":"televet-vet-bio",children:vet.bio}):null]})})}function SlotStep({headingRef:headingRef,slots:slots,enabled:enabled,isPending:isPending,isError:isError,error:error,busySlotId:busySlotId,failure:failure2,selectedSlot:selectedSlot,nextOpening:nextOpening,onPick:onPick,onRetry:onRetry,onSeeOtherVets:onSeeOtherVets}){let styles=useBookingStyles();return enabled?isPending?/* @__PURE__ */jsxRuntime.jsx("div",{role:"progressbar","aria-label":TELEVET_BOOKING_COPY_WEB.loading.slots,"aria-busy":"true",style:styles.list,"data-testid":"televet-slots-loading",children:[0,1,2].map(i=>/* @__PURE__ */jsxRuntime.jsx(TelevetSkeletonBlock,{height:48},i))}):isError?/* @__PURE__ */jsxRuntime.jsx(TelevetLoadFailed,{error:error,title:TELEVET_BOOKING_COPY_WEB.slotsErrorTitle,actionLabel:TELEVET_BOOKING_COPY_WEB.retryCta,onRetry:onRetry,testID:"televet-slots-error"}):slots.length===0?/* @__PURE__ */jsxRuntime.jsx("div",{"data-testid":"televet-slots-empty",children:/* @__PURE__ */jsxRuntime.jsx(TelevetStateCard,{title:TELEVET_BOOKING_COPY_WEB.noSlotsTitle,message:nextOpening?fill(TELEVET_BOOKING_COPY_WEB.nextOpeningTemplate,{when:formatWhenWithDay(nextOpening.startsAt)}):void 0,actionLabel:nextOpening?TELEVET_BOOKING_COPY_WEB.seeOtherVetsCta:void 0,onAction:nextOpening?onSeeOtherVets:void 0})}):
254
254
  /* @__PURE__ */jsxRuntime.jsxs(TelevetStepFrame,{headingRef:headingRef,heading:TELEVET_BOOKING_COPY_WEB.timeHeading,testID:"televet-slots",children:[failure2==="expired"?/* @__PURE__ */jsxRuntime.jsx(TelevetFailureLine,{message:TELEVET_BOOKING_COPY_WEB.holdExpired}):null,failure2==="taken"?/* @__PURE__ */jsxRuntime.jsx(TelevetFailureLine,{message:TELEVET_BOOKING_COPY_WEB.slotTaken}):null,failure2==="failed"||failure2==="rate_limited"?/* @__PURE__ */jsxRuntime.jsx(TelevetFailureLine,{message:TELEVET_BOOKING_COPY_WEB.confirmFailed,testID:"televet-slots-hold-failed"}):null,
255
255
  /* @__PURE__ */jsxRuntime.jsx(TelevetSlotPicker,{slots:slots,busySlotId:busySlotId,onPick:onPick,selectedSlot:selectedSlot,dayGroupLabel:TELEVET_BOOKING_COPY_WEB.dayLegend,timeGroupLabel:TELEVET_BOOKING_COPY_WEB.timeHeading,periodLabels:{morning:TELEVET_BOOKING_COPY_WEB.timeMorning,afternoon:TELEVET_BOOKING_COPY_WEB.timeAfternoon,evening:TELEVET_BOOKING_COPY_WEB.timeEvening},timeLegendTemplate:TELEVET_BOOKING_COPY_WEB.timeLegendTemplate})]}):/* @__PURE__ */jsxRuntime.jsx("div",{"data-testid":"televet-slots-unavailable",children:/* @__PURE__ */jsxRuntime.jsx(TelevetStateCard,{title:TELEVET_BOOKING_COPY_WEB.bookingPausedTitle})})}function IssuesStep({headingRef:headingRef,petName:petName,chips:chips,selected:selected,onToggle:onToggle,onNext:onNext}){let theme=useEverfurTheme(),local=react.useMemo(()=>makeLocalStyles(theme),[theme]),[refused,setRefused]=react.useState(false),heading=fill(TELEVET_BOOKING_COPY_WEB.issuesTitleTemplate,{pet:petName??TELEVET_BOOKING_COPY_WEB.petFallback});/* @__PURE__ */
@@ -1,8 +1,8 @@
1
1
  import { ReactNode, CSSProperties } from 'react';
2
2
  import { P as PetRef } from '../../../ids-B2GAAifq.cjs';
3
3
  export { B as Brand, _ as __brand } from '../../../ids-B2GAAifq.cjs';
4
- import { c as TelevetBookingStep, d as TelevetBookingContext, e as TelevetBookingController, f as TelevetTriageRead, g as TelevetStateInterestWrite, T as TelevetEmptyRosterCause, a as TelevetStateInterestAction$1, b as TelevetMediaShortfall, h as TelevetVetThreadTarget, i as TelevetDayPeriod } from '../../../bookingCopy-pJpizqgz.cjs';
5
- export { C as CONSULT_MINUTES, N as NO_MEDIA_SHORTFALL, j as TELEVET_BOOKING_BASE, k as TELEVET_BOOKING_COPY, l as TELEVET_BOOKING_STEPS, m as TELEVET_CONSULT_PAGE_LIMIT, n as TELEVET_JOIN_CLOSES_MINUTES_AFTER, o as TELEVET_JOIN_OPENS_MINUTES_BEFORE, p as TELEVET_MESSAGE_THREADS_PATH, q as TelevetAttachmentMeta, r as TelevetAttachmentPolicy, s as TelevetBookingAction, t as TelevetBookingControllerDeps, u as TelevetBookingCopy, v as TelevetBookingDraft, w as TelevetBookingFailure, x as TelevetBookingRefusal, y as TelevetBookingState, z as TelevetEarlyTriage, A as TelevetEmptyRosterView, aR as TelevetJoinBlock, aS as TelevetJoinDecision, D as TelevetJoinState, E as TelevetMediaRefusal, F as TelevetRead, G as TelevetStateInterestReason, H as TelevetWrite, U as UseVetThreadOptions, V as VET_MESSAGES_COPY, I as VET_MESSAGE_CONTENT_MAX, J as VET_MESSAGE_PAGE_DEFAULT, K as VET_MESSAGE_PAGE_MAX, L as VetMessage, M as VetMessagePage, O as VetMessageRole, P as VetMessagesAvailability, Q as VetSendFailure, R as VetThread, S as VetThreadState, W as VetThreadsState, X as VisitSummary, Y as VisitSummaryMedication, Z as VisitSummaryState, _ as attestation, $ as canConfirm, a0 as canManageTelevetVisit, a1 as createTelevetBookingController, a2 as currentStep, a3 as emptyTelevetDraft, a4 as formatVisitRange, a5 as formatWhen, a6 as formatWhenWithDay, a7 as hasPreviousStep, a8 as initialTelevetBookingState, a9 as isHoldExpired, aa as isMediaShortfallEmpty, ab as isSkipped, ac as isTelevetBookingCopyReady, ad as isVetMessagesDark, ae as isVetThreadVetFirst, af as mediaShortfallFromUnsentPicks, ag as splitTelevetVisits, ah as televetBookingKey, ai as televetBookingReducer, aj as televetBookingRefusal, ak as televetCancelCall, al as televetConsultCall, am as televetEmptyRosterCause, an as televetEmptyRosterView, ao as televetHoldCall, ap as televetJoinCall, aT as televetJoinDecision, aq as televetJoinOpensAtMs, as as televetMediaShortfallLines, at as televetRescheduleCall, au as televetThreadMessagesCall, av as televetThreadReadCall, aw as televetVisitSummaryCall, ax as useEarlyTriage, ay as useStateInterest, az as useTelevetBookConsult, aA as useTelevetBookingAvailable, aB as useTelevetBookingController, aC as useTelevetBookingEntitlement, aD as useTelevetCancellationPolicy, aE as useTelevetClinicians, aF as useTelevetHoldSlot, aG as useTelevetJoin, aH as useTelevetNextSlot, aI as useTelevetRescheduleConsult, aJ as useTelevetSlots, aK as useTelevetStatePolicy, aL as useVetThread, aM as useVetThreads, aN as useVisitSummary, aO as validateBookingBody, aP as vetThreadPetRef, aQ as withUnsentPicks } from '../../../bookingCopy-pJpizqgz.cjs';
4
+ import { c as TelevetBookingStep, d as TelevetBookingContext, e as TelevetBookingController, f as TelevetTriageRead, g as TelevetStateInterestWrite, T as TelevetEmptyRosterCause, a as TelevetStateInterestAction$1, b as TelevetMediaShortfall, h as TelevetVetThreadTarget, i as TelevetDayPeriod } from '../../../bookingCopy-DRwrhDUe.cjs';
5
+ export { C as CONSULT_MINUTES, N as NO_MEDIA_SHORTFALL, j as TELEVET_BOOKING_BASE, k as TELEVET_BOOKING_COPY, l as TELEVET_BOOKING_STEPS, m as TELEVET_CONSULT_PAGE_LIMIT, n as TELEVET_JOIN_CLOSES_MINUTES_AFTER, o as TELEVET_JOIN_OPENS_MINUTES_BEFORE, p as TELEVET_MESSAGE_THREADS_PATH, q as TelevetAttachmentMeta, r as TelevetAttachmentPolicy, s as TelevetBookingAction, t as TelevetBookingControllerDeps, u as TelevetBookingCopy, v as TelevetBookingDraft, w as TelevetBookingFailure, x as TelevetBookingRefusal, y as TelevetBookingState, z as TelevetEarlyTriage, A as TelevetEmptyRosterView, aR as TelevetJoinBlock, aS as TelevetJoinDecision, D as TelevetJoinState, E as TelevetMediaRefusal, F as TelevetRead, G as TelevetStateInterestReason, H as TelevetWrite, U as UseVetThreadOptions, V as VET_MESSAGES_COPY, I as VET_MESSAGE_CONTENT_MAX, J as VET_MESSAGE_PAGE_DEFAULT, K as VET_MESSAGE_PAGE_MAX, L as VetMessage, M as VetMessagePage, O as VetMessageRole, P as VetMessagesAvailability, Q as VetSendFailure, R as VetThread, S as VetThreadState, W as VetThreadsState, X as VisitSummary, Y as VisitSummaryMedication, Z as VisitSummaryState, _ as attestation, $ as canConfirm, a0 as canManageTelevetVisit, a1 as createTelevetBookingController, a2 as currentStep, a3 as emptyTelevetDraft, a4 as formatVisitRange, a5 as formatWhen, a6 as formatWhenWithDay, a7 as hasPreviousStep, a8 as initialTelevetBookingState, a9 as isHoldExpired, aa as isMediaShortfallEmpty, ab as isSkipped, ac as isTelevetBookingCopyReady, ad as isVetMessagesDark, ae as isVetThreadVetFirst, af as mediaShortfallFromUnsentPicks, ag as splitTelevetVisits, ah as televetBookingKey, ai as televetBookingReducer, aj as televetBookingRefusal, ak as televetCancelCall, al as televetConsultCall, am as televetEmptyRosterCause, an as televetEmptyRosterView, ao as televetHoldCall, ap as televetJoinCall, aT as televetJoinDecision, aq as televetJoinOpensAtMs, as as televetMediaShortfallLines, at as televetRescheduleCall, au as televetThreadMessagesCall, av as televetThreadReadCall, aw as televetVisitSummaryCall, ax as useEarlyTriage, ay as useStateInterest, az as useTelevetBookConsult, aA as useTelevetBookingAvailable, aB as useTelevetBookingController, aC as useTelevetBookingEntitlement, aD as useTelevetCancellationPolicy, aE as useTelevetClinicians, aF as useTelevetHoldSlot, aG as useTelevetJoin, aH as useTelevetNextSlot, aI as useTelevetRescheduleConsult, aJ as useTelevetSlots, aK as useTelevetStatePolicy, aL as useVetThread, aM as useVetThreads, aN as useVisitSummary, aO as validateBookingBody, aP as vetThreadPetRef, aQ as withUnsentPicks } from '../../../bookingCopy-DRwrhDUe.cjs';
6
6
  import { T as TelevetConsult, E as EverfurTelevetFlowRequest, c as TelevetSlot } from '../../../televetGlobal-C5dTUACe.cjs';
7
7
  export { C as CANCELLATION_POLICY_VERSION_MAX, d as CANCEL_REASON_MAX, e as CONSULT_KINDS, f as CONSULT_STATUSES, g as ConsultKind, h as ConsultStatus, M as MEDIA_REFS_MAX, R as REASON_TEXT_MAX, i as TERMINAL_CONSULT_STATUSES, j as TelevetBookingBody, k as TelevetBookingEntitlement, b as TelevetCancelReceipt, l as TelevetCancellationPolicy, m as TelevetClinician, n as TelevetSlotHold, o as TelevetStatePolicy, p as TelevetTriageVerdict, q as isWellFormedStateCode } from '../../../televetGlobal-C5dTUACe.cjs';
8
8
  import { V as VetVisitIntent } from '../../../visitIntent-D7_yVp1I.cjs';
@@ -12,11 +12,11 @@ import { m as EverfurTheme } from '../../../tokens-DLj8OnLH.cjs';
12
12
  export { b as VetCallCredential, c as VetCallJoinRefusal, d as VetCallLimits, p as parseVetCallCredential, v as vetCallJoinReason, e as vetCallJoinRefusal } from '../../../callRoom-BhIdadyV.cjs';
13
13
  export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode } from '../../../EverfurError-DeBqRpQV.cjs';
14
14
  export { E as EverfurResult } from '../../../EverfurResult-COlXj1wq.cjs';
15
- export { W as WidgetPet } from '../../../petsRepository-CQgzEFyz.cjs';
16
- import '../../../requestFunnel-nmhlEdbM.cjs';
15
+ export { W as WidgetPet } from '../../../petsRepository-CQeuDdDC.cjs';
16
+ import '../../../requestFunnel-hXkP5T7K.cjs';
17
17
  import '../../../ErrorPolicyPort-10s3HJCt.cjs';
18
- import '../../../config-u6rK4mKt.cjs';
19
- import '../../../identity-CUynm8S2.cjs';
18
+ import '../../../config-lilR0260.cjs';
19
+ import '../../../identity-YXqHjBln.cjs';
20
20
  import '../../../TelemetryPort-BDNr00hu.cjs';
21
21
  import '../../../profile-CSs1wlXT.cjs';
22
22
 
@@ -1,8 +1,8 @@
1
1
  import { ReactNode, CSSProperties } from 'react';
2
2
  import { P as PetRef } from '../../../ids-B2GAAifq.js';
3
3
  export { B as Brand, _ as __brand } from '../../../ids-B2GAAifq.js';
4
- import { c as TelevetBookingStep, d as TelevetBookingContext, e as TelevetBookingController, f as TelevetTriageRead, g as TelevetStateInterestWrite, T as TelevetEmptyRosterCause, a as TelevetStateInterestAction$1, b as TelevetMediaShortfall, h as TelevetVetThreadTarget, i as TelevetDayPeriod } from '../../../bookingCopy-B5igVNE0.js';
5
- export { C as CONSULT_MINUTES, N as NO_MEDIA_SHORTFALL, j as TELEVET_BOOKING_BASE, k as TELEVET_BOOKING_COPY, l as TELEVET_BOOKING_STEPS, m as TELEVET_CONSULT_PAGE_LIMIT, n as TELEVET_JOIN_CLOSES_MINUTES_AFTER, o as TELEVET_JOIN_OPENS_MINUTES_BEFORE, p as TELEVET_MESSAGE_THREADS_PATH, q as TelevetAttachmentMeta, r as TelevetAttachmentPolicy, s as TelevetBookingAction, t as TelevetBookingControllerDeps, u as TelevetBookingCopy, v as TelevetBookingDraft, w as TelevetBookingFailure, x as TelevetBookingRefusal, y as TelevetBookingState, z as TelevetEarlyTriage, A as TelevetEmptyRosterView, aR as TelevetJoinBlock, aS as TelevetJoinDecision, D as TelevetJoinState, E as TelevetMediaRefusal, F as TelevetRead, G as TelevetStateInterestReason, H as TelevetWrite, U as UseVetThreadOptions, V as VET_MESSAGES_COPY, I as VET_MESSAGE_CONTENT_MAX, J as VET_MESSAGE_PAGE_DEFAULT, K as VET_MESSAGE_PAGE_MAX, L as VetMessage, M as VetMessagePage, O as VetMessageRole, P as VetMessagesAvailability, Q as VetSendFailure, R as VetThread, S as VetThreadState, W as VetThreadsState, X as VisitSummary, Y as VisitSummaryMedication, Z as VisitSummaryState, _ as attestation, $ as canConfirm, a0 as canManageTelevetVisit, a1 as createTelevetBookingController, a2 as currentStep, a3 as emptyTelevetDraft, a4 as formatVisitRange, a5 as formatWhen, a6 as formatWhenWithDay, a7 as hasPreviousStep, a8 as initialTelevetBookingState, a9 as isHoldExpired, aa as isMediaShortfallEmpty, ab as isSkipped, ac as isTelevetBookingCopyReady, ad as isVetMessagesDark, ae as isVetThreadVetFirst, af as mediaShortfallFromUnsentPicks, ag as splitTelevetVisits, ah as televetBookingKey, ai as televetBookingReducer, aj as televetBookingRefusal, ak as televetCancelCall, al as televetConsultCall, am as televetEmptyRosterCause, an as televetEmptyRosterView, ao as televetHoldCall, ap as televetJoinCall, aT as televetJoinDecision, aq as televetJoinOpensAtMs, as as televetMediaShortfallLines, at as televetRescheduleCall, au as televetThreadMessagesCall, av as televetThreadReadCall, aw as televetVisitSummaryCall, ax as useEarlyTriage, ay as useStateInterest, az as useTelevetBookConsult, aA as useTelevetBookingAvailable, aB as useTelevetBookingController, aC as useTelevetBookingEntitlement, aD as useTelevetCancellationPolicy, aE as useTelevetClinicians, aF as useTelevetHoldSlot, aG as useTelevetJoin, aH as useTelevetNextSlot, aI as useTelevetRescheduleConsult, aJ as useTelevetSlots, aK as useTelevetStatePolicy, aL as useVetThread, aM as useVetThreads, aN as useVisitSummary, aO as validateBookingBody, aP as vetThreadPetRef, aQ as withUnsentPicks } from '../../../bookingCopy-B5igVNE0.js';
4
+ import { c as TelevetBookingStep, d as TelevetBookingContext, e as TelevetBookingController, f as TelevetTriageRead, g as TelevetStateInterestWrite, T as TelevetEmptyRosterCause, a as TelevetStateInterestAction$1, b as TelevetMediaShortfall, h as TelevetVetThreadTarget, i as TelevetDayPeriod } from '../../../bookingCopy-Cc3Cl-IJ.js';
5
+ export { C as CONSULT_MINUTES, N as NO_MEDIA_SHORTFALL, j as TELEVET_BOOKING_BASE, k as TELEVET_BOOKING_COPY, l as TELEVET_BOOKING_STEPS, m as TELEVET_CONSULT_PAGE_LIMIT, n as TELEVET_JOIN_CLOSES_MINUTES_AFTER, o as TELEVET_JOIN_OPENS_MINUTES_BEFORE, p as TELEVET_MESSAGE_THREADS_PATH, q as TelevetAttachmentMeta, r as TelevetAttachmentPolicy, s as TelevetBookingAction, t as TelevetBookingControllerDeps, u as TelevetBookingCopy, v as TelevetBookingDraft, w as TelevetBookingFailure, x as TelevetBookingRefusal, y as TelevetBookingState, z as TelevetEarlyTriage, A as TelevetEmptyRosterView, aR as TelevetJoinBlock, aS as TelevetJoinDecision, D as TelevetJoinState, E as TelevetMediaRefusal, F as TelevetRead, G as TelevetStateInterestReason, H as TelevetWrite, U as UseVetThreadOptions, V as VET_MESSAGES_COPY, I as VET_MESSAGE_CONTENT_MAX, J as VET_MESSAGE_PAGE_DEFAULT, K as VET_MESSAGE_PAGE_MAX, L as VetMessage, M as VetMessagePage, O as VetMessageRole, P as VetMessagesAvailability, Q as VetSendFailure, R as VetThread, S as VetThreadState, W as VetThreadsState, X as VisitSummary, Y as VisitSummaryMedication, Z as VisitSummaryState, _ as attestation, $ as canConfirm, a0 as canManageTelevetVisit, a1 as createTelevetBookingController, a2 as currentStep, a3 as emptyTelevetDraft, a4 as formatVisitRange, a5 as formatWhen, a6 as formatWhenWithDay, a7 as hasPreviousStep, a8 as initialTelevetBookingState, a9 as isHoldExpired, aa as isMediaShortfallEmpty, ab as isSkipped, ac as isTelevetBookingCopyReady, ad as isVetMessagesDark, ae as isVetThreadVetFirst, af as mediaShortfallFromUnsentPicks, ag as splitTelevetVisits, ah as televetBookingKey, ai as televetBookingReducer, aj as televetBookingRefusal, ak as televetCancelCall, al as televetConsultCall, am as televetEmptyRosterCause, an as televetEmptyRosterView, ao as televetHoldCall, ap as televetJoinCall, aT as televetJoinDecision, aq as televetJoinOpensAtMs, as as televetMediaShortfallLines, at as televetRescheduleCall, au as televetThreadMessagesCall, av as televetThreadReadCall, aw as televetVisitSummaryCall, ax as useEarlyTriage, ay as useStateInterest, az as useTelevetBookConsult, aA as useTelevetBookingAvailable, aB as useTelevetBookingController, aC as useTelevetBookingEntitlement, aD as useTelevetCancellationPolicy, aE as useTelevetClinicians, aF as useTelevetHoldSlot, aG as useTelevetJoin, aH as useTelevetNextSlot, aI as useTelevetRescheduleConsult, aJ as useTelevetSlots, aK as useTelevetStatePolicy, aL as useVetThread, aM as useVetThreads, aN as useVisitSummary, aO as validateBookingBody, aP as vetThreadPetRef, aQ as withUnsentPicks } from '../../../bookingCopy-Cc3Cl-IJ.js';
6
6
  import { T as TelevetConsult, E as EverfurTelevetFlowRequest, c as TelevetSlot } from '../../../televetGlobal-CnjrfhT4.js';
7
7
  export { C as CANCELLATION_POLICY_VERSION_MAX, d as CANCEL_REASON_MAX, e as CONSULT_KINDS, f as CONSULT_STATUSES, g as ConsultKind, h as ConsultStatus, M as MEDIA_REFS_MAX, R as REASON_TEXT_MAX, i as TERMINAL_CONSULT_STATUSES, j as TelevetBookingBody, k as TelevetBookingEntitlement, b as TelevetCancelReceipt, l as TelevetCancellationPolicy, m as TelevetClinician, n as TelevetSlotHold, o as TelevetStatePolicy, p as TelevetTriageVerdict, q as isWellFormedStateCode } from '../../../televetGlobal-CnjrfhT4.js';
8
8
  import { V as VetVisitIntent } from '../../../visitIntent-D7_yVp1I.js';
@@ -12,11 +12,11 @@ import { m as EverfurTheme } from '../../../tokens-DLj8OnLH.js';
12
12
  export { b as VetCallCredential, c as VetCallJoinRefusal, d as VetCallLimits, p as parseVetCallCredential, v as vetCallJoinReason, e as vetCallJoinRefusal } from '../../../callRoom-B92eH_ij.js';
13
13
  export { E as EverfurError, a as EverfurErrorCategory, b as EverfurErrorCode } from '../../../EverfurError-DeBqRpQV.js';
14
14
  export { E as EverfurResult } from '../../../EverfurResult-ClPTS0P2.js';
15
- export { W as WidgetPet } from '../../../petsRepository-RGI_xPK1.js';
16
- import '../../../requestFunnel-BkSFsLKh.js';
15
+ export { W as WidgetPet } from '../../../petsRepository-B1I6Lq_m.js';
16
+ import '../../../requestFunnel-B86gQFka.js';
17
17
  import '../../../ErrorPolicyPort-C3nNSS_j.js';
18
- import '../../../config-BB7e52FP.js';
19
- import '../../../identity-D5uywCtp.js';
18
+ import '../../../config-CuOczZUI.js';
19
+ import '../../../identity-4lohfP2L.js';
20
20
  import '../../../TelemetryPort-BDNr00hu.js';
21
21
  import '../../../profile-CSs1wlXT.js';
22
22
 
@@ -89,7 +89,7 @@ return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fiel
89
89
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
90
90
  /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row2=>row2.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row2=BY_KEY.get(candidate+key);if(row2)return row2}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});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 row2=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)),row2);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 ok(value,warning){/* @__PURE__ */
91
91
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
92
- return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function 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}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp2({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
92
+ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function 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 ctx.identity.reportRejected?.(),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 ctx.identity.reportRejected?.(),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?(ctx.identity.reportRejected?.(),err(authRejectedError(retry.error.httpStatus))):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp2({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
93
93
  /* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
94
94
  return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}var TELEVET_ATTACHMENT_MIME_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/webp","image/heic","image/heif","application/pdf","text/csv","video/mp4","video/quicktime"]),TELEVET_ATTACHMENT_MAX_BYTES=25*1024*1024,TELEVET_ATTACHMENT_VIDEO_MAX_BYTES=200*1024*1024,SUFFIX_TYPES=[[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".webp","image/webp"],[".heic","image/heic"],[".heif","image/heif"],[".pdf","application/pdf"],[".csv","text/csv"],[".mp4","video/mp4"],[".mov","video/quicktime"]];function televetAttachmentContentType(filename,mimeType){let direct=(mimeType??"").trim().toLowerCase();if(direct==="image/jpg")return"image/jpeg";if(TELEVET_ATTACHMENT_MIME_TYPES.includes(direct))return direct;if(direct.length>0)return null;let name=filename.toLowerCase();return SUFFIX_TYPES.find(([suffix])=>name.endsWith(suffix))?.[1]??null}function televetAttachmentRefusal(pick2){let type=televetAttachmentContentType(pick2.filename,pick2.mimeType);if(type===null)return"type";if(!Number.isFinite(pick2.fileSize)||pick2.fileSize<=0)return"unreadable";let ceiling=type.startsWith("video/")?TELEVET_ATTACHMENT_VIDEO_MAX_BYTES:TELEVET_ATTACHMENT_MAX_BYTES;return pick2.fileSize<=ceiling?null:"size"}function parseTelevetAttachmentPolicy(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,str4=v=>typeof v=="string"&&v.length>0?v:null,num3=v=>typeof v=="number"&&Number.isFinite(v)?v:null,uploadUrl=str4(o.upload_url),s3Key=str4(o.s3_key);if(uploadUrl===null||s3Key===null)return null;let fields={},rawFields=o.upload_fields;if(typeof rawFields=="object"&&rawFields!==null)for(let[key,value]of Object.entries(rawFields))typeof value=="string"&&(fields[key]=value);/* @__PURE__ */
95
95
  return Object.freeze({upload_id:str4(o.upload_id)??"",upload_url:uploadUrl,upload_fields:/* @__PURE__ */Object.freeze(fields),expires_in_seconds:num3(o.expires_in_seconds)??0,max_content_length:num3(o.max_content_length)??TELEVET_ATTACHMENT_MAX_BYTES,s3_key:s3Key,purpose:str4(o.purpose)})}function wireCodeOf(raw){if(typeof raw!="object"||raw===null)return null;let scopes=[raw,raw.detail,raw.error];for(let scope of scopes)if(!(typeof scope!="object"||scope===null))for(let key of["error","code"]){let value=scope[key];if(typeof value=="string"&&value.length>0)return value}return null}function televetAttachmentInitiateFailure(error){if(error.httpStatus===404)return"dark";if(error.httpStatus===400){let code=wireCodeOf(error.raw);if(code==="FILE_TOO_LARGE")return"size";if(code==="INVALID_CONTENT_TYPE")return"type"}return"failed"}var TELEVET_BOOKING_NOT_LIVE="televet_booking_not_live";function televetBookingNotLiveError(status){return makeEverfurError("conflict",{retryable:false,reasonCode:TELEVET_BOOKING_NOT_LIVE,wireMessage:`the booking was answered with a consult whose status is ${status}, which is not a live visit`})}var TELEVET_BOOKING_KEY_REUSED="televet_booking_key_reused",KEY_REUSED_WIRE_CODE="IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST";function foldTelevetBookingKeyReused(error){return error.httpStatus!==409||error.reasonCode===TELEVET_BOOKING_KEY_REUSED||details(error)?.code!==KEY_REUSED_WIRE_CODE?error:makeEverfurError(error.code,{retryable:false,httpStatus:409,...error.requestId!==void 0?{requestId:error.requestId}:{},wireCode:KEY_REUSED_WIRE_CODE,reasonCode:TELEVET_BOOKING_KEY_REUSED,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}function details(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let direct=raw,nested=direct.detail??direct.error;return typeof nested=="object"&&nested!==null?nested:direct}function categoriesOf(error){let raw=details(error)?.categories;return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.filter(c=>typeof c=="string")):/* @__PURE__ */Object.freeze([])}function retryAfterOf(error){let raw=details(error)?.retry_after_seconds;return typeof raw=="number"&&Number.isFinite(raw)&&raw>0?raw:null}function messageOf(error){let wire=error.wireMessage;if(typeof wire=="string"&&wire.trim().length>0)return wire.trim();let raw=details(error)?.message;return typeof raw=="string"&&raw.trim().length>0?raw.trim():null}function codeOf(error){let reason=error.reasonCode;if(typeof reason=="string"&&reason.length>0)return reason;let raw=details(error),code=raw?.code??raw?.error_code;return typeof code=="string"&&code.length>0?code:null}function televetBookingRefusal(error){let status=error.httpStatus;if(status===402)/* @__PURE__ */return Object.freeze({kind:"not_entitled"});if(status===429||error.code==="rateLimited"||error.code==="quotaExceeded")/* @__PURE__ */
@@ -168,10 +168,10 @@ return jsxs("div",{"data-testid":"televet-booking-not-entitled",style:styles.lis
168
168
  /* @__PURE__ */jsxs("div",{"data-testid":"televet-booking-state-blocked",children:[
169
169
  /* @__PURE__ */jsx(TelevetStateCard,{title:TELEVET_BOOKING_COPY_WEB.stateBlockedTitle}),
170
170
  /* @__PURE__ */jsx(TelevetStateInterestAction,{action:stateInterest,testIDPrefix:"televet-state-interest-state-blocked"})]}):step==="reason"&&triageOpen?/* @__PURE__ */jsx(TelevetEarlyEmergency,{...petName!==void 0?{petName:petName}:{},...primaryVet?{primaryVet:primaryVet}:{},onFindEmergencyVet:onFindEmergencyVet,onContinue:onAcknowledgeEmergency}):null}function televetClinicianOutcomeApplies(state){return state.noState?true:state.isPending||state.isError?false:state.isEmpty||state.notEntitled}function TelevetClinicianOutcome({state:state,cause:cause,locationStatus:locationStatus,onRequestLocation:onRequestLocation,onRetry:onRetry,stateInterest:stateInterest=null,renderUnavailable:renderUnavailable}){return state.noState?
171
- /* @__PURE__ */jsx("div",{"data-testid":"televet-booking-location-unknown",children:/* @__PURE__ */jsx(TelevetStateCard,{title:locationStatus==="blocked"?TELEVET_BOOKING_COPY_WEB.locationBlockedTitle:locationStatus==="unavailable"?TELEVET_BOOKING_COPY_WEB.locationUnavailableTitle:TELEVET_BOOKING_COPY_WEB.locationUnknownTitle,message:locationStatus==="blocked"?TELEVET_BOOKING_COPY_WEB.locationBlockedBody:locationStatus==="unavailable"?TELEVET_BOOKING_COPY_WEB.locationUnavailableBody:TELEVET_BOOKING_COPY_WEB.locationUnknownBody,actionLabel:onRequestLocation&&locationStatus!=="blocked"?TELEVET_BOOKING_COPY_WEB.locationUnknownCta:void 0,onAction:locationStatus==="blocked"?void 0:onRequestLocation})}):state.isEmpty?/* @__PURE__ */jsx(TelevetClinicianEmptyState,{cause:cause,onRetry:onRetry,stateInterest:stateInterest}):/* @__PURE__ */jsx(EntitlementPausedState,{...renderUnavailable?{renderUnavailable:renderUnavailable}:{}})}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")}function composite(fg,bg){let a=fg.a,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(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 PINK_SOFT_ALPHA=.22,TINT_SOFT_ALPHA=.5,EVERFUR_PINK="#FFC3BC";function televetPlainLook(theme){let c=theme.color;return{ink:c.brandInk,text:c.text.primary,muted:c.text.muted,line:c.borderRingCream,mist:c.surfaceSubtle,surface:c.surface,pink:c.highlight,onPink:c.onHighlight,go:c.mark,alert:c.danger,alertWash:c.badgeBgCritical}}function televetLook(theme){let c=theme.color,everfurPink=parseColor(c.highlight)===EVERFUR_PINK,soft=withAlpha(c.highlight,everfurPink?PINK_SOFT_ALPHA:TINT_SOFT_ALPHA);return{...televetPlainLook(theme),pinkSoft:(soft===null?null:flattenOnto(soft,c.surface))??c.surface}}function televetConsultCalendarKey(consultId){return`televet-consult-${consultId}`}function TelevetBookedScreen({consult:consult,petName:petName,onDone:onDone,onAddToCalendar:onAddToCalendar,canJoinInApp:canJoinInApp=false,lengthMinutes:lengthMinutes,sharedRecords:sharedRecords=false,sentPhoto:sentPhoto=false}){let theme=useEverfurTheme(),shared=useBookingStyles(),styles=useMemo(()=>makeStyles2(theme),[theme]),titleId=`${useId()}-booked-title`,Title=headingTag(useNestedHeadingLevel()),[calendarState,setCalendarState]=useState("idle"),addToCalendar=async()=>{if(!onAddToCalendar)return;setCalendarState("saving");let start=new Date(consult.scheduledAt);if(Number.isNaN(start.getTime())){setCalendarState("failed");return}let minutes=typeof lengthMinutes=="number"&&Number.isFinite(lengthMinutes)&&lengthMinutes>0?lengthMinutes:CONSULT_MINUTES,outcome=await callHostAsync(onAddToCalendar,{key:televetConsultCalendarKey(consult.consultId),title:TELEVET_BOOKING_COPY_WEB.visit.title,startDate:start,endDate:new Date(start.getTime()+minutes*6e4),alarmOffsetMinutes:-30});if(!outcome.ok){setCalendarState("failed");return}setCalendarState(outcome.value===true?"saved":outcome.value==="handed-off"?"idle":"failed")},steps=[TELEVET_BOOKING_COPY_WEB.booked.remindPromise,sharedRecords&&consult.clinicianName?fill(sentPhoto?TELEVET_BOOKING_COPY_WEB.booked.recordsPhotoPromiseTemplate:TELEVET_BOOKING_COPY_WEB.booked.recordsPromiseTemplate,{pet:petName??TELEVET_BOOKING_COPY_WEB.petFallback,vet:consult.clinicianName}):fill(TELEVET_BOOKING_COPY_WEB.booked.summaryPromise,{pet:petName??""}),...canJoinInApp?[TELEVET_BOOKING_COPY_WEB.booked.joinPromise]:[]];if(!isTelevetBookingCopyReady())/* @__PURE__ */
171
+ /* @__PURE__ */jsx("div",{"data-testid":"televet-booking-location-unknown",children:/* @__PURE__ */jsx(TelevetStateCard,{title:locationStatus==="blocked"?TELEVET_BOOKING_COPY_WEB.locationBlockedTitle:locationStatus==="unavailable"?TELEVET_BOOKING_COPY_WEB.locationUnavailableTitle:TELEVET_BOOKING_COPY_WEB.locationUnknownTitle,message:locationStatus==="blocked"?TELEVET_BOOKING_COPY_WEB.locationBlockedBody:locationStatus==="unavailable"?TELEVET_BOOKING_COPY_WEB.locationUnavailableBody:TELEVET_BOOKING_COPY_WEB.locationUnknownBody,actionLabel:onRequestLocation&&locationStatus!=="blocked"?TELEVET_BOOKING_COPY_WEB.locationUnknownCta:void 0,onAction:locationStatus==="blocked"?void 0:onRequestLocation})}):state.isEmpty?/* @__PURE__ */jsx(TelevetClinicianEmptyState,{cause:cause,onRetry:onRetry,stateInterest:stateInterest}):/* @__PURE__ */jsx(EntitlementPausedState,{...renderUnavailable?{renderUnavailable:renderUnavailable}:{}})}function clinicianInitial(displayName){return displayName.trim().replace(/^dr\.?\s+/i,"").slice(0,1).toUpperCase()}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")}function composite(fg,bg){let a=fg.a,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(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 PINK_SOFT_ALPHA=.22,TINT_SOFT_ALPHA=.5,EVERFUR_PINK="#FFC3BC";function televetPlainLook(theme){let c=theme.color;return{ink:c.brandInk,text:c.text.primary,muted:c.text.muted,line:c.borderRingCream,mist:c.surfaceSubtle,surface:c.surface,pink:c.highlight,onPink:c.onHighlight,go:c.mark,alert:c.danger,alertWash:c.badgeBgCritical}}function televetLook(theme){let c=theme.color,everfurPink=parseColor(c.highlight)===EVERFUR_PINK,soft=withAlpha(c.highlight,everfurPink?PINK_SOFT_ALPHA:TINT_SOFT_ALPHA);return{...televetPlainLook(theme),pinkSoft:(soft===null?null:flattenOnto(soft,c.surface))??c.surface}}function televetConsultCalendarKey(consultId){return`televet-consult-${consultId}`}function TelevetBookedScreen({consult:consult,petName:petName,onDone:onDone,onAddToCalendar:onAddToCalendar,canJoinInApp:canJoinInApp=false,lengthMinutes:lengthMinutes,sharedRecords:sharedRecords=false,sentPhoto:sentPhoto=false}){let theme=useEverfurTheme(),shared=useBookingStyles(),styles=useMemo(()=>makeStyles2(theme),[theme]),titleId=`${useId()}-booked-title`,Title=headingTag(useNestedHeadingLevel()),[calendarState,setCalendarState]=useState("idle"),addToCalendar=async()=>{if(!onAddToCalendar)return;setCalendarState("saving");let start=new Date(consult.scheduledAt);if(Number.isNaN(start.getTime())){setCalendarState("failed");return}let minutes=typeof lengthMinutes=="number"&&Number.isFinite(lengthMinutes)&&lengthMinutes>0?lengthMinutes:CONSULT_MINUTES,outcome=await callHostAsync(onAddToCalendar,{key:televetConsultCalendarKey(consult.consultId),title:TELEVET_BOOKING_COPY_WEB.visit.title,startDate:start,endDate:new Date(start.getTime()+minutes*6e4),alarmOffsetMinutes:-30});if(!outcome.ok){setCalendarState("failed");return}setCalendarState(outcome.value===true?"saved":outcome.value==="handed-off"?"idle":"failed")},steps=[TELEVET_BOOKING_COPY_WEB.booked.remindPromise,sharedRecords&&consult.clinicianName?fill(sentPhoto?TELEVET_BOOKING_COPY_WEB.booked.recordsPhotoPromiseTemplate:TELEVET_BOOKING_COPY_WEB.booked.recordsPromiseTemplate,{pet:petName??TELEVET_BOOKING_COPY_WEB.petFallback,vet:consult.clinicianName}):fill(TELEVET_BOOKING_COPY_WEB.booked.summaryPromise,{pet:petName??""}),...canJoinInApp?[TELEVET_BOOKING_COPY_WEB.booked.joinPromise]:[]];if(!isTelevetBookingCopyReady())/* @__PURE__ */
172
172
  return jsx("div",{style:styles.screen,"data-testid":"televet-booked-copy-unapproved"});let vetName=consult.clinicianName?.trim()??"";/* @__PURE__ */
173
173
  return jsxs("section",{style:styles.screen,"aria-labelledby":titleId,"data-testid":"televet-booked",children:[
174
- /* @__PURE__ */jsx("div",{"aria-hidden":"true",style:styles.avatar,children:vetName.length>0?vetName.replace(/^dr\.?\s+/i,"").slice(0,1).toUpperCase():null}),
174
+ /* @__PURE__ */jsx("div",{"aria-hidden":"true",style:styles.avatar,children:vetName.length>0?clinicianInitial(vetName):null}),
175
175
  /* @__PURE__ */jsx(Title,{id:titleId,style:styles.title,children:vetName.length>0?fill(TELEVET_BOOKING_COPY_WEB.bookedTitleTemplate,{vet:vetName}):TELEVET_BOOKING_COPY_WEB.bookedTitle}),
176
176
  /* @__PURE__ */jsx("p",{style:styles.when,children:petName?/* @__PURE__ */jsxs(Fragment,{children:[
177
177
  /* @__PURE__ */jsx("time",{dateTime:consult.scheduledAt,children:formatBookedWhen(consult.scheduledAt)}),fill(TELEVET_BOOKING_COPY_WEB.bookedLeadTemplate,{when:"",pet:petName})]}):/* @__PURE__ */jsx("time",{dateTime:consult.scheduledAt,children:formatBookedWhen(consult.scheduledAt)})}),
@@ -249,7 +249,7 @@ return jsx("div",{role:"progressbar","aria-label":TELEVET_BOOKING_COPY_WEB.loadi
249
249
  return jsx("div",{"data-testid":"televet-clinicians-error",children:/* @__PURE__ */jsx(TelevetLoadFailed,{error:error,title:TELEVET_BOOKING_COPY_WEB.chrome.loadFailedTitle,actionLabel:TELEVET_BOOKING_COPY_WEB.chrome.retryCta,onRetry:onRetry})});if(clinicians.length===0)/* @__PURE__ */
250
250
  return jsx("div",{"data-testid":"televet-clinicians-empty",children:/* @__PURE__ */jsx(TelevetStateCard,{title:TELEVET_BOOKING_COPY_WEB.noCliniciansTitle,message:TELEVET_BOOKING_COPY_WEB.noCliniciansBody,actionLabel:TELEVET_BOOKING_COPY_WEB.noCliniciansRetryCta,onAction:onRetry})});let vet=clinicians.find(c=>c.clinicianId===selectedId)??clinicians[0];if(vet===void 0)return null;let code=stateCode?.trim().toUpperCase()??"",licensedHere=code.length>0&&vet.licensedStates.some(l=>l.state.trim().toUpperCase()===code);/* @__PURE__ */
251
251
  return jsx(TelevetStepFrame,{headingRef:headingRef,heading:TELEVET_BOOKING_COPY_WEB.yourVetTitle,testID:"televet-clinicians",footer:/* @__PURE__ */jsx(TelevetButton,{label:TELEVET_BOOKING_COPY_WEB.continueCta,kind:"primary",size:"lg",onPress:()=>onSelect(vet.clinicianId),testID:`televet-clinician-${vet.clinicianId}`}),children:/* @__PURE__ */jsxs("div",{style:local.meet,children:[
252
- /* @__PURE__ */jsx("span",{"aria-hidden":"true",style:local.vetAvatar,children:initialOf(vet.displayName)}),
252
+ /* @__PURE__ */jsx("span",{"aria-hidden":"true",style:local.vetAvatar,children:clinicianInitial(vet.displayName)||PERSON_GLYPH}),
253
253
  /* @__PURE__ */jsx("p",{style:local.vetName,children:vet.credentials?`${vet.displayName}, ${vet.credentials}`:vet.displayName}),licensedHere&&stateName?/* @__PURE__ */jsx("div",{style:local.pills,children:/* @__PURE__ */jsx("span",{style:local.pill,"data-testid":"televet-vet-licensed",children:fill(TELEVET_BOOKING_COPY_WEB.licensedPillTemplate,{state:stateName})})}):null,vet.rating!==null&&vet.ratingCount!==null?/* @__PURE__ */jsx("p",{style:local.vetRating,"data-testid":"televet-vet-rating",children:`★ ${String(vet.rating)} · ${String(vet.ratingCount)} ${TELEVET_BOOKING_COPY_WEB.reviewsLabel}`}):null,vet.bio?/* @__PURE__ */jsx("p",{style:local.vetBio,"data-testid":"televet-vet-bio",children:vet.bio}):null]})})}function SlotStep({headingRef:headingRef,slots:slots,enabled:enabled,isPending:isPending,isError:isError,error:error,busySlotId:busySlotId,failure:failure2,selectedSlot:selectedSlot,nextOpening:nextOpening,onPick:onPick,onRetry:onRetry,onSeeOtherVets:onSeeOtherVets}){let styles=useBookingStyles();return enabled?isPending?/* @__PURE__ */jsx("div",{role:"progressbar","aria-label":TELEVET_BOOKING_COPY_WEB.loading.slots,"aria-busy":"true",style:styles.list,"data-testid":"televet-slots-loading",children:[0,1,2].map(i=>/* @__PURE__ */jsx(TelevetSkeletonBlock,{height:48},i))}):isError?/* @__PURE__ */jsx(TelevetLoadFailed,{error:error,title:TELEVET_BOOKING_COPY_WEB.slotsErrorTitle,actionLabel:TELEVET_BOOKING_COPY_WEB.retryCta,onRetry:onRetry,testID:"televet-slots-error"}):slots.length===0?/* @__PURE__ */jsx("div",{"data-testid":"televet-slots-empty",children:/* @__PURE__ */jsx(TelevetStateCard,{title:TELEVET_BOOKING_COPY_WEB.noSlotsTitle,message:nextOpening?fill(TELEVET_BOOKING_COPY_WEB.nextOpeningTemplate,{when:formatWhenWithDay(nextOpening.startsAt)}):void 0,actionLabel:nextOpening?TELEVET_BOOKING_COPY_WEB.seeOtherVetsCta:void 0,onAction:nextOpening?onSeeOtherVets:void 0})}):
254
254
  /* @__PURE__ */jsxs(TelevetStepFrame,{headingRef:headingRef,heading:TELEVET_BOOKING_COPY_WEB.timeHeading,testID:"televet-slots",children:[failure2==="expired"?/* @__PURE__ */jsx(TelevetFailureLine,{message:TELEVET_BOOKING_COPY_WEB.holdExpired}):null,failure2==="taken"?/* @__PURE__ */jsx(TelevetFailureLine,{message:TELEVET_BOOKING_COPY_WEB.slotTaken}):null,failure2==="failed"||failure2==="rate_limited"?/* @__PURE__ */jsx(TelevetFailureLine,{message:TELEVET_BOOKING_COPY_WEB.confirmFailed,testID:"televet-slots-hold-failed"}):null,
255
255
  /* @__PURE__ */jsx(TelevetSlotPicker,{slots:slots,busySlotId:busySlotId,onPick:onPick,selectedSlot:selectedSlot,dayGroupLabel:TELEVET_BOOKING_COPY_WEB.dayLegend,timeGroupLabel:TELEVET_BOOKING_COPY_WEB.timeHeading,periodLabels:{morning:TELEVET_BOOKING_COPY_WEB.timeMorning,afternoon:TELEVET_BOOKING_COPY_WEB.timeAfternoon,evening:TELEVET_BOOKING_COPY_WEB.timeEvening},timeLegendTemplate:TELEVET_BOOKING_COPY_WEB.timeLegendTemplate})]}):/* @__PURE__ */jsx("div",{"data-testid":"televet-slots-unavailable",children:/* @__PURE__ */jsx(TelevetStateCard,{title:TELEVET_BOOKING_COPY_WEB.bookingPausedTitle})})}function IssuesStep({headingRef:headingRef,petName:petName,chips:chips,selected:selected,onToggle:onToggle,onNext:onNext}){let theme=useEverfurTheme(),local=useMemo(()=>makeLocalStyles(theme),[theme]),[refused,setRefused]=useState(false),heading=fill(TELEVET_BOOKING_COPY_WEB.issuesTitleTemplate,{pet:petName??TELEVET_BOOKING_COPY_WEB.petFallback});/* @__PURE__ */
@@ -90,7 +90,7 @@ return jsxRuntime.jsx(EverfurTelevetDialog,{request:host.request,onClose:host.di
90
90
  /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});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 ok(value,warning){/* @__PURE__ */
91
91
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
92
92
  return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function errorFrame(fields){/* @__PURE__ */
93
- return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function 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}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
93
+ return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function 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 ctx.identity.reportRejected?.(),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 ctx.identity.reportRejected?.(),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?(ctx.identity.reportRejected?.(),err(authRejectedError(retry.error.httpStatus))):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
94
94
  /* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
95
95
  return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}var 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}$/,RETURN_FLOW_PARAM="everfur_flow",STATE_MAX=32,PET_REF_MAX=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 invalid(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef,options){let body={};petRef!==void 0&&(body.pet_ref=petRef);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"||petRef===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(petRef,options){let pet;if(petRef!=null){let length=typeof petRef=="string"?[...petRef].length:0;if(length<1||length>PET_REF_MAX)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX} characters`}));pet=petRef}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid(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 invalid(`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 parseVetVisitReturn(url){if(typeof url!="string")return null;let hashAt=url.indexOf("#"),beforeHash=hashAt<0?url:url.slice(0,hashAt),queryAt=beforeHash.indexOf("?");if(queryAt<0)return null;let found=beforeHash.slice(queryAt+1).split("&").filter(pair=>pair.startsWith(`${RETURN_FLOW_PARAM}=`)).map(pair=>pair.slice(RETURN_FLOW_PARAM.length+1));return found.length!==1||!FLOW_ID.test(found[0]??"")?null:/* @__PURE__ */Object.freeze({flowId:found[0]})}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_URL=/^([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_URL.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 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}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 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__ */
96
96
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
@@ -90,7 +90,7 @@ return jsx(EverfurTelevetDialog,{request:host.request,onClose:host.dismiss,...on
90
90
  /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});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 ok(value,warning){/* @__PURE__ */
91
91
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
92
92
  return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function errorFrame(fields){/* @__PURE__ */
93
- return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function 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}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
93
+ return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function 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 ctx.identity.reportRejected?.(),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 ctx.identity.reportRejected?.(),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?(ctx.identity.reportRejected?.(),err(authRejectedError(retry.error.httpStatus))):retry}function authRejectedError(httpStatus){return makeEverfurError("authRejected",{retryable:false,...httpStatus!==void 0?{httpStatus:httpStatus}:{}})}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),settled;try{settled=await authedSend({...base,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp({phase:"settled",...settledEvent})),err(error);if(emit(stamp({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
94
94
  /* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
95
95
  return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}var 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}$/,RETURN_FLOW_PARAM="everfur_flow",STATE_MAX=32,PET_REF_MAX=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 invalid(wireMessage){return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage}))}function unusable(wireMessage){return err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:wireMessage}))}function handoffBody(petRef,options){let body={};petRef!==void 0&&(body.pet_ref=petRef);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"||petRef===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(petRef,options){let pet;if(petRef!=null){let length=typeof petRef=="string"?[...petRef].length:0;if(length<1||length>PET_REF_MAX)return failed(makeEverfurError("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${PET_REF_MAX} characters`}));pet=petRef}let built=handoffBody(pet,options);if(!built.ok){let refused=invalid(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 invalid(`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 parseVetVisitReturn(url){if(typeof url!="string")return null;let hashAt=url.indexOf("#"),beforeHash=hashAt<0?url:url.slice(0,hashAt),queryAt=beforeHash.indexOf("?");if(queryAt<0)return null;let found=beforeHash.slice(queryAt+1).split("&").filter(pair=>pair.startsWith(`${RETURN_FLOW_PARAM}=`)).map(pair=>pair.slice(RETURN_FLOW_PARAM.length+1));return found.length!==1||!FLOW_ID.test(found[0]??"")?null:/* @__PURE__ */Object.freeze({flowId:found[0]})}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_URL=/^([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_URL.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 EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}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 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__ */
96
96
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@everfur/sdk",
3
- "version": "0.9.2",
3
+ "version": "0.10.0",
4
4
  "description": "Embed Everfur veterinary chat, health records, and pet-state surfaces in your React Native app.",
5
5
  "license": "MIT",
6
6
  "repository": {