@everfur/sdk 0.10.0 → 0.12.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 (137) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +9 -7
  3. package/dist/{Chat-Ml-HlOiV.d.cts → Chat-BOG0SXKV.d.cts} +3 -3
  4. package/dist/{Chat-DwGk5APA.d.ts → Chat-CIolBgjJ.d.ts} +3 -3
  5. package/dist/{DepthViews-DwCS5KKh.d.ts → DepthViews-280t3BcQ.d.ts} +1 -1
  6. package/dist/{DepthViews-DAJySZqL.d.cts → DepthViews-BR6VQ3Ta.d.cts} +1 -1
  7. package/dist/{DepthViews-PgA2KvTE.d.cts → DepthViews-BTbF_DJY.d.cts} +1 -1
  8. package/dist/{DepthViews-kM-_Mn2x.d.ts → DepthViews-DlBuFsgN.d.ts} +1 -1
  9. package/dist/animations/index.cjs +4 -2
  10. package/dist/animations/index.d.cts +3 -3
  11. package/dist/animations/index.d.ts +3 -3
  12. package/dist/animations/index.js +4 -2
  13. package/dist/{attachments-BV1Mbqm-.d.cts → attachments-B6h4cJU-.d.cts} +5 -5
  14. package/dist/{attachments-DWv9stp1.d.ts → attachments-CGxvnYu4.d.ts} +5 -5
  15. package/dist/{attachments-BH0vdghi.d.ts → attachments-CWNj1ZkM.d.ts} +2 -2
  16. package/dist/{attachments-DaWeeeBW.d.cts → attachments-waXcJWCp.d.cts} +2 -2
  17. package/dist/{bookingCopy-DRwrhDUe.d.cts → bookingCopy-8aEU6ZmR.d.cts} +2 -2
  18. package/dist/{bookingCopy-Cc3Cl-IJ.d.ts → bookingCopy-CjPKeg75.d.ts} +2 -2
  19. package/dist/{casesRepository-BhfPDWhY.d.cts → casesRepository-CGdhvzTu.d.cts} +1 -1
  20. package/dist/{casesRepository-DMkRRKr8.d.ts → casesRepository-ZG9Sg0e4.d.ts} +1 -1
  21. package/dist/chat/index.cjs +4 -2
  22. package/dist/chat/index.d.cts +9 -9
  23. package/dist/chat/index.d.ts +9 -9
  24. package/dist/chat/index.js +4 -2
  25. package/dist/client/index.cjs +6 -4
  26. package/dist/client/index.d.cts +7 -7
  27. package/dist/client/index.d.ts +7 -7
  28. package/dist/client/index.js +6 -4
  29. package/dist/{config-lilR0260.d.cts → config-B0p6Lygh.d.cts} +1 -1
  30. package/dist/{config-CuOczZUI.d.ts → config-DmFAZJOx.d.ts} +1 -1
  31. package/dist/consent/index.cjs +4 -2
  32. package/dist/consent/index.d.cts +5 -5
  33. package/dist/consent/index.d.ts +5 -5
  34. package/dist/consent/index.js +4 -2
  35. package/dist/{context-CL3cR0MA.d.ts → context-BNreNLtL.d.ts} +10 -6
  36. package/dist/{context-BA6X6ZHd.d.cts → context-BgS2a57J.d.cts} +10 -6
  37. package/dist/{copy-A2n7xXsL.d.ts → copy-DLJriGQS.d.ts} +2 -2
  38. package/dist/{copy-DkoUo0VR.d.cts → copy-lWp-Lkv5.d.cts} +2 -2
  39. package/dist/core/index.cjs +8 -6
  40. package/dist/core/index.d.cts +12 -12
  41. package/dist/core/index.d.ts +12 -12
  42. package/dist/core/index.js +8 -6
  43. package/dist/{depth-DOPtk0vF.d.cts → depth-BYb3RXoA.d.cts} +2 -2
  44. package/dist/{depth-6_BYIt0s.d.ts → depth-COz-sSG5.d.ts} +2 -2
  45. package/dist/{entitlementRepository-BE-L6vX1.d.ts → entitlementRepository-CrTOP_-o.d.ts} +2 -2
  46. package/dist/{entitlementRepository-Blh38A2b.d.cts → entitlementRepository-D-Lse67w.d.cts} +2 -2
  47. package/dist/{identity-4lohfP2L.d.ts → identity-Cw07BKZp.d.ts} +1 -1
  48. package/dist/{identity-YXqHjBln.d.cts → identity-DFVGYn1o.d.cts} +1 -1
  49. package/dist/index.cjs +8 -6
  50. package/dist/index.d.cts +12 -12
  51. package/dist/index.d.ts +12 -12
  52. package/dist/index.js +8 -6
  53. package/dist/notifications/index.cjs +5 -3
  54. package/dist/notifications/index.d.cts +2 -2
  55. package/dist/notifications/index.d.ts +2 -2
  56. package/dist/notifications/index.js +5 -3
  57. package/dist/{pets-DzXi_9hY.d.ts → pets-BYALZTSu.d.ts} +2 -2
  58. package/dist/{pets-m61lisZt.d.cts → pets-CcyPQS-H.d.cts} +2 -2
  59. package/dist/{petsRepository-B1I6Lq_m.d.ts → petsRepository-518QkPxH.d.ts} +1 -1
  60. package/dist/{petsRepository-CQeuDdDC.d.cts → petsRepository-B_Q1gFkE.d.cts} +1 -1
  61. package/dist/photo/index.cjs +4 -2
  62. package/dist/photo/index.js +4 -2
  63. package/dist/{ports-CrGAcey9.d.ts → ports-DmQeMArX.d.ts} +4 -4
  64. package/dist/{ports-DUqO_XX0.d.cts → ports-RuNJmBA-.d.cts} +4 -4
  65. package/dist/records/depth/index.cjs +4 -2
  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 +4 -2
  69. package/dist/records/index.cjs +4 -2
  70. package/dist/records/index.d.cts +9 -9
  71. package/dist/records/index.d.ts +9 -9
  72. package/dist/records/index.js +4 -2
  73. package/dist/{requestFunnel-B86gQFka.d.ts → requestFunnel-B9fdXMi5.d.ts} +2 -2
  74. package/dist/{requestFunnel-hXkP5T7K.d.cts → requestFunnel-BBjNNwc9.d.cts} +2 -2
  75. package/dist/{runtimeTypes-Bt_tIj3h.d.cts → runtimeTypes-CstDBX8w.d.cts} +4 -4
  76. package/dist/{runtimeTypes-DXKxY2yq.d.ts → runtimeTypes-N_K4BVZB.d.ts} +4 -4
  77. package/dist/server/events/index.cjs +4 -2
  78. package/dist/server/events/index.d.cts +2 -2
  79. package/dist/server/events/index.d.ts +2 -2
  80. package/dist/server/events/index.js +4 -2
  81. package/dist/server/index.cjs +7 -5
  82. package/dist/server/index.d.cts +27 -4
  83. package/dist/server/index.d.ts +27 -4
  84. package/dist/server/index.js +7 -5
  85. package/dist/televet/booking/index.cjs +5 -3
  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 +5 -3
  89. package/dist/televet/index.cjs +4 -2
  90. package/dist/televet/index.js +4 -2
  91. package/dist/testing/index.cjs +4 -2
  92. package/dist/testing/index.d.cts +1 -1
  93. package/dist/testing/index.d.ts +1 -1
  94. package/dist/testing/index.js +4 -2
  95. package/dist/testing/rn/index.cjs +4 -2
  96. package/dist/testing/rn/index.d.cts +7 -7
  97. package/dist/testing/rn/index.d.ts +7 -7
  98. package/dist/testing/rn/index.js +4 -2
  99. package/dist/testing/web/index.cjs +4 -2
  100. package/dist/testing/web/index.d.cts +7 -7
  101. package/dist/testing/web/index.d.ts +7 -7
  102. package/dist/testing/web/index.js +4 -2
  103. package/dist/{timelineRows-C2ObTmfN.d.ts → timelineRows-7yjHyh8i.d.ts} +1 -1
  104. package/dist/{timelineRows-CrA-ePrQ.d.cts → timelineRows-WvnL-Lds.d.cts} +1 -1
  105. package/dist/{useRecordsDepth-NQNJaGyk.d.ts → useRecordsDepth-Bp6L4M5P.d.ts} +1 -1
  106. package/dist/{useRecordsDepth-Dcr9y6i-.d.cts → useRecordsDepth-DPdAK_81.d.cts} +1 -1
  107. package/dist/video/index.cjs +4 -2
  108. package/dist/video/index.js +4 -2
  109. package/dist/{view-DWJa2L0U.d.ts → view-C6go2uUt.d.ts} +2 -2
  110. package/dist/{view-Dk7xpBJ4.d.cts → view-CiF_HVFQ.d.cts} +2 -2
  111. package/dist/web/consent/index.cjs +4 -2
  112. package/dist/web/consent/index.d.cts +5 -5
  113. package/dist/web/consent/index.d.ts +5 -5
  114. package/dist/web/consent/index.js +4 -2
  115. package/dist/web/index.cjs +8 -6
  116. package/dist/web/index.d.cts +14 -14
  117. package/dist/web/index.d.ts +14 -14
  118. package/dist/web/index.js +8 -6
  119. package/dist/web/notifications/index.cjs +5 -3
  120. package/dist/web/notifications/index.d.cts +3 -3
  121. package/dist/web/notifications/index.d.ts +3 -3
  122. package/dist/web/notifications/index.js +5 -3
  123. package/dist/web/records/depth/index.cjs +4 -2
  124. package/dist/web/records/depth/index.d.cts +7 -7
  125. package/dist/web/records/depth/index.d.ts +7 -7
  126. package/dist/web/records/depth/index.js +4 -2
  127. package/dist/web/records/index.cjs +8 -6
  128. package/dist/web/records/index.d.cts +9 -9
  129. package/dist/web/records/index.d.ts +9 -9
  130. package/dist/web/records/index.js +8 -6
  131. package/dist/web/televet/booking/index.cjs +5 -3
  132. package/dist/web/televet/booking/index.d.cts +6 -6
  133. package/dist/web/televet/booking/index.d.ts +6 -6
  134. package/dist/web/televet/booking/index.js +5 -3
  135. package/dist/web/televet/index.cjs +4 -2
  136. package/dist/web/televet/index.js +4 -2
  137. package/package.json +1 -1
@@ -66,6 +66,7 @@ import{createContext,forwardRef,createElement,useMemo,useState,useRef,useEffect,
66
66
  /* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
67
67
  /* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
68
68
  /* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
69
+ /* @__PURE__ */Object.freeze({wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false}),
69
70
  /* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
70
71
  /* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
71
72
  /* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
@@ -77,6 +78,7 @@ import{createContext,forwardRef,createElement,useMemo,useState,useRef,useEffect,
77
78
  /* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
78
79
  /* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
79
80
  /* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
81
+ /* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
80
82
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
81
83
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
82
84
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
@@ -85,7 +87,7 @@ import{createContext,forwardRef,createElement,useMemo,useState,useRef,useEffect,
85
87
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
86
88
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
87
89
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
88
- /* @__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__ */
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",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"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."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.";function displayFor(code,wireCode){return(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:displayFor(code,opts?.wireCode)};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__ */
89
91
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
90
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)}};var EMERGENCY_ER_LINE="Go to the nearest emergency vet now.";var CHAT_COPY=/* @__PURE__ */Object.freeze({placeholder:"Ask anything about {petName}…",placeholderFollowUpWeb:"Ask a follow-up…",placeholderUrgentWeb:"Tell us what’s happening…",composerLabel:"Message",attachPhotoOrFileNative:"Add a photo or file",footnoteNative:"Educational, not a diagnosis. Emergency? Call a vet.",footnoteWeb:"Everfur’s assistant isn’t a vet and doesn’t diagnose. Your vet makes the calls. Not for emergencies: if {petName} is in distress, go to the nearest emergency animal hospital now.",suggestions:"Suggestions",reading:"Reading {petName}’s records…",answered:"Everfur answered.",assistantName:"Everfur",followUpsHeadingNative:"Follow-up questions",turnFailedTitleWeb:"Everfur couldn’t answer that just now.",send:"Send",stop:"Stop",retry:"Try again",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",senderVet:"Your vet",loading:"Loading",empty:"No messages yet",transcript:"Chat with Everfur",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting…",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",nearestEmergencyVet:"Nearest emergency vet",goToNearestEmergencyVet:EMERGENCY_ER_LINE,poisonControlWeb:"ASPCA Poison Control",poisonControlNative:"ASPCA Animal Poison Control, (888) 426-4435",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openHistoryNative:"Chats and vet messages",openHistoryWeb:"Chats",showChatsWeb:"Show chats",hideChatsWeb:"Hide chats",newReplySuffix:", a new reply",yourPets:"Your pets",yourPet:"Your pet",switchActivePet:"{name}. Switch pet",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active · ",close:"Close",addAnotherPet:"Add a pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function fillCopy(template,values){return template.replace(/\{(\w+)\}/g,(match,key)=>{let value=values[key];return value===void 0?match:String(value)})}function petNameSlot(name){return name?.trim()||CHAT_COPY.emptyTitlePetFallback}function forPet(template,name){return fillCopy(template,{petName:petNameSlot(name)})}var POISON_CONTROL_TEL="tel:+18884264435";var FEEDBACK_REASONS=/* @__PURE__ */Object.freeze([
91
93
  /* @__PURE__ */Object.freeze({key:"inaccurate",label:CHAT_COPY.feedbackReasonInaccurate,feedbackType:"wrong"}),
@@ -96,7 +98,7 @@ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _Everf
96
98
  /* @__PURE__ */Object.freeze({sentiment:"up",label:CHAT_COPY.feedbackHelpful}),
97
99
  /* @__PURE__ */Object.freeze({sentiment:"neutral",label:CHAT_COPY.feedbackNeutral}),
98
100
  /* @__PURE__ */Object.freeze({sentiment:"down",label:CHAT_COPY.feedbackNotHelpful})]);function sentimentToFeedbackType(sentiment){switch(sentiment){case"up":return"helpful";case"neutral":return"neutral";case"down":return"not_helpful"}}function feedbackTypeFor(sentiment,reason){if(sentiment==="down"&&reason!==null){let option=FEEDBACK_REASONS.find(entry=>entry.key===reason);if(option!==void 0)return option.feedbackType}return sentimentToFeedbackType(sentiment)}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
99
- 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(
101
+ return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals(deadline.signal,req.signal),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(
100
102
  /* @__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__ */
101
103
  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})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str(o.ref),name:name,dose:str(o.dose),frequency:str(o.frequency),startDate:str(o.start_date),endDate:str(o.end_date),notes:str(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
102
104
  return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str(o.food_brand),foodType:str(o.food_type),microchipId:str(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),conditionName:conditionName,diagnosedDate:str(row.diagnosed_date),notes:str(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid("pet_ref must be a string");if(petRef.trim().length===0)return invalid("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid("profile must be an object");let checks=[checkString("pet_ref",petRef,PET_REF_MAX)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str2=v=>typeof v=="string"?v:null,num=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
@@ -66,6 +66,7 @@
66
66
  /* @__PURE__ */Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),
67
67
  /* @__PURE__ */Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),
68
68
  /* @__PURE__ */Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),
69
+ /* @__PURE__ */Object.freeze({wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false}),
69
70
  /* @__PURE__ */Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),
70
71
  /* @__PURE__ */Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),
71
72
  /* @__PURE__ */Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),
@@ -77,6 +78,7 @@
77
78
  /* @__PURE__ */Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
78
79
  /* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),
79
80
  /* @__PURE__ */Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
81
+ /* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
80
82
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
81
83
  /* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
82
84
  /* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
@@ -85,13 +87,13 @@
85
87
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
86
88
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
87
89
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
88
- /* @__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}}function contractDocUrl(entry){return entry.envelope==="sse_frame"?`/errors#sse-${entry.wireCode}`:entry.envelope==="oauth_error"?`/errors#oauth-${entry.wireCode}`:`/errors#${entry.wireCode}`}var DOC_SITE_ORIGIN=null;function publishedDocUrl(entry){return null}var EVERFUR_ERROR_CODES=/* @__PURE__ */Object.freeze(["authExpired","authRejected","sessionRequired","accessDenied","paymentRequired","quotaExceeded","rateLimited","validationFailed","sdkUpdateRequired","conflict","idempotencyConflict","idempotencyInFlight","conversationNotFound","petNotFound","resourceNotFound","streamTimeout","mediaUploadFailed","moderationBlocked","upstreamLlmTimeout","internalError","notImplemented","serviceUnavailable","streamIncomplete","identitySignatureRequired","runtimeDisposed","unknown"]),EVERFUR_ERROR_CATEGORIES=/* @__PURE__ */Object.freeze(["authentication","authorization","entitlement","rateLimit","invalidRequest","notFound","conflict","connection","server","media","policy","unknown"]),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"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"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)}function shouldRetry(code,frameRetryable=false){return frameRetryable||isAutoRetryable(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)}function canRecreateOnNotFound(code){return code==="conversationNotFound"}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__ */
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",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"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}}function contractDocUrl(entry){return entry.envelope==="sse_frame"?`/errors#sse-${entry.wireCode}`:entry.envelope==="oauth_error"?`/errors#oauth-${entry.wireCode}`:`/errors#${entry.wireCode}`}var DOC_SITE_ORIGIN=null;function publishedDocUrl(entry){return null}var EVERFUR_ERROR_CODES=/* @__PURE__ */Object.freeze(["authExpired","authRejected","sessionRequired","accessDenied","paymentRequired","quotaExceeded","rateLimited","validationFailed","sdkUpdateRequired","conflict","idempotencyConflict","idempotencyInFlight","conversationNotFound","petNotFound","resourceNotFound","streamTimeout","mediaUploadFailed","moderationBlocked","upstreamLlmTimeout","internalError","notImplemented","serviceUnavailable","streamIncomplete","identitySignatureRequired","runtimeDisposed","unknown"]),EVERFUR_ERROR_CATEGORIES=/* @__PURE__ */Object.freeze(["authentication","authorization","entitlement","rateLimit","invalidRequest","notFound","conflict","connection","server","media","policy","unknown"]),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"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"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)}function shouldRetry(code,frameRetryable=false){return frameRetryable||isAutoRetryable(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)}function canRecreateOnNotFound(code){return code==="conversationNotFound"}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.";function displayFor(code,wireCode){return(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:displayFor(code,opts?.wireCode)};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__ */
89
91
  return Object.freeze(warning===void 0?{ok:true,value:value}:{ok:true,value:value,warning:warning})}function err(error){/* @__PURE__ */
90
- return Object.freeze({ok:false,error:error})}function isOk(r){return r.ok}function isErr(r){return!r.ok}var EverfurThrownError=class _EverfurThrownError extends Error{constructor(error){super(`${error.code}: ${error.displayMessage}`),this.name="EverfurThrownError",this.error=error,this.code=error.code,this.category=error.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(r){if(r.ok)return r.value;throw new EverfurThrownError(r.error)}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var SDK_VERSION="0.10.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
92
+ return Object.freeze({ok:false,error:error})}function isOk(r){return r.ok}function isErr(r){return!r.ok}var EverfurThrownError=class _EverfurThrownError extends Error{constructor(error){super(`${error.code}: ${error.displayMessage}`),this.name="EverfurThrownError",this.error=error,this.code=error.code,this.category=error.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(r){if(r.ok)return r.value;throw new EverfurThrownError(r.error)}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var SDK_VERSION="0.12.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
91
93
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function checkPublishableKey(raw){let publishableKey=typeof raw=="string"?raw.trim():"";return publishableKey.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(publishableKey)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}function tryResolveClientConfig(config,options){let keyFailure=checkPublishableKey(config?.publishableKey);if(keyFailure!==null)/* @__PURE__ */
92
94
  return Object.freeze({ok:false,failure:keyFailure});let publishableKey=config.publishableKey.trim(),baseUrl=tryResolveApiBaseUrl(config.apiBaseUrl);if(!baseUrl.ok)return baseUrl;let contractVersion=config.contractVersion?.trim()||DEFAULT_CONTRACT_VERSION;/* @__PURE__ */
93
95
  return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:publishableKey,apiBaseUrl:baseUrl.value,contractVersion:contractVersion,sdkVersion:SDK_VERSION,platform:options?.platform??SDK_PLATFORM,debug:config.debug===true})})}function resolveClientConfig(config,options){let outcome=tryResolveClientConfig(config,options);if(!outcome.ok)throw new EverfurConfigError("invalid-argument",outcome.failure.message);return outcome.config}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function resolveApiBaseUrl(apiBaseUrl){let outcome=tryResolveApiBaseUrl(apiBaseUrl);if(!outcome.ok)throw new EverfurConfigError("invalid-argument",outcome.failure.message);return outcome.value}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
94
- return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var MAX_USER_REF_LEN=128,MAX_PET_REF_LEN=128,CONTROL_CHAR=/[\u0000-\u001F\u007F]/,UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_PET_REF_LEN)throw new EverfurConfigError("invalid-argument",`petRef must be 1..${MAX_PET_REF_LEN} characters`);if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","petRef must be printable (no control characters)");return v}function userRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_USER_REF_LEN)throw new EverfurConfigError("invalid-argument",`userRef must be 1..${MAX_USER_REF_LEN} characters`);if(v.includes("@"))throw new EverfurConfigError("invalid-argument","userRef must not contain '@'");if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","userRef must be printable (no control characters)");return v}function conversationId(raw){if(!UUID_RE.test(raw))throw new EverfurConfigError("invalid-argument","conversationId must be a UUID");return raw}function unsafePetRef(raw){return raw}function unsafeUserRef(raw){return raw}function unsafeConversationId(raw){return raw}function unsafeResponseId(raw){return raw}function unsafeClientId(raw){return raw}function unsafeDocumentId(raw){return raw}function unsafeJobId(raw){return raw}function unsafeRecordsRequestId(raw){return raw}function createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight=null,revoked=false,load=()=>inFlight||(inFlight=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight=null}})(),inFlight);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch{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 assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}var EMPTY_STRINGS=/* @__PURE__ */Object.freeze([]),EMPTY_MAPS=/* @__PURE__ */Object.freeze([]);function acceptedFrame(streamId,lastEventId,serverRequestId=null){/* @__PURE__ */
96
+ return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var MAX_USER_REF_LEN=128,MAX_PET_REF_LEN=128,CONTROL_CHAR=/[\u0000-\u001F\u007F]/,UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function petRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_PET_REF_LEN)throw new EverfurConfigError("invalid-argument",`petRef must be 1..${MAX_PET_REF_LEN} characters`);if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","petRef must be printable (no control characters)");return v}function userRef(raw){let v=raw,length=serverLength(v);if(length===0||length>MAX_USER_REF_LEN)throw new EverfurConfigError("invalid-argument",`userRef must be 1..${MAX_USER_REF_LEN} characters`);if(v.includes("@"))throw new EverfurConfigError("invalid-argument","userRef must not contain '@'");if(CONTROL_CHAR.test(v))throw new EverfurConfigError("invalid-argument","userRef must be printable (no control characters)");return v}function conversationId(raw){if(!UUID_RE.test(raw))throw new EverfurConfigError("invalid-argument","conversationId must be a UUID");return raw}function unsafePetRef(raw){return raw}function unsafeUserRef(raw){return raw}function unsafeConversationId(raw){return raw}function unsafeResponseId(raw){return raw}function unsafeClientId(raw){return raw}function unsafeDocumentId(raw){return raw}function unsafeJobId(raw){return raw}function unsafeRecordsRequestId(raw){return raw}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function createIdentityProvider(userRef2,getToken,onMinted,onRejected){let cached=null,rejectionReported=false,inFlight=null,revoked=false,load=()=>inFlight||(inFlight=(async()=>{try{let minted=await getToken(),token=typeof minted=="string"?minted:minted?.token;if(typeof token!="string"||token.length===0)throw new EverfurConfigError("invalid-argument","TokenProvider returned an empty token");return cached=token,rejectionReported=!1,onMinted?.(typeof minted=="string"?null:expiryMs(minted.expiresAt)),token}finally{inFlight=null}})(),inFlight);return{userRef:userRef2,async currentToken(opts){if(revoked)throw new EverfurConfigError("not-initialized","This identity was cleared (sign-out); mint a new one.");return opts?.forceRefresh&&(cached=null),cached!==null?cached:load()},hasToken(){return!revoked&&cached!==null},clear(){revoked=true,cached=null},reportRejected(){revoked||rejectionReported||(rejectionReported=true,onRejected?.())}}}function expiryMs(value){if(value===void 0)return null;let ms=typeof value=="number"?value<1e11?value*1e3:value:new Date(value).getTime();return Number.isFinite(ms)?ms:null}function newSessionId(){let bytes=new Uint8Array(16),cryptoObj=globalThis.crypto;if(typeof cryptoObj?.getRandomValues=="function")cryptoObj.getRandomValues(bytes);else for(let i=0;i<bytes.length;i+=1)bytes[i]=Math.floor(Math.random()*256);bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex=[];for(let i=0;i<bytes.length;i+=1)hex.push(bytes[i].toString(16).padStart(2,"0"));return hex.slice(0,4).join("")+"-"+hex.slice(4,6).join("")+"-"+hex.slice(6,8).join("")+"-"+hex.slice(8,10).join("")+"-"+hex.slice(10,16).join("")}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}var EMPTY_STRINGS=/* @__PURE__ */Object.freeze([]),EMPTY_MAPS=/* @__PURE__ */Object.freeze([]);function acceptedFrame(streamId,lastEventId,serverRequestId=null){/* @__PURE__ */
95
97
  return Object.freeze({kind:"accepted",streamId:streamId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function heartbeatFrame(lastEventId,serverRequestId=null){/* @__PURE__ */
96
98
  return Object.freeze({kind:"heartbeat",lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function deltaFrame(delta,lastEventId,serverRequestId=null){/* @__PURE__ */
97
99
  return Object.freeze({kind:"delta",delta:delta,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function doneFrame(fields,serverRequestId=null){/* @__PURE__ */
@@ -99,7 +101,7 @@ return Object.freeze({kind:"done",terminal:true,conversationId:fields.conversati
99
101
  return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:fields.serverRequestId??null})}function analysisStartedFrame(requestId,lastEventId,serverRequestId=null){/* @__PURE__ */
100
102
  return Object.freeze({kind:"analysisStarted",requestId:requestId,lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}function analysisCompleteFrame(fields,serverRequestId=null){/* @__PURE__ */
101
103
  return Object.freeze({kind:"analysisComplete",terminal:false,resultId:fields.resultId,analysisType:fields.analysisType,modelVersion:fields.modelVersion,confidence:fields.confidence,detections:/* @__PURE__ */Object.freeze([...fields.detections]),interpretation:fields.interpretation,lastEventId:fields.lastEventId,serverRequestId:serverRequestId})}function unknownFrame(raw,lastEventId,serverRequestId=null){/* @__PURE__ */
102
- return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var EMPTY_FRAME_ARRAYS=/* @__PURE__ */Object.freeze({strings:EMPTY_STRINGS,maps:EMPTY_MAPS});var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string(),/* @__PURE__ */zod.z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=new TextDecoder("utf-8"),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}var UNARY_TIMEOUT_MS=3e4,REQUEST_ID_HEADER="x-request-id";async function*fetchByteSource(body){if(!body)return;let reader=body.getReader();try{for(;;){let{done:done,value:value}=await reader.read();if(done)break;value&&value.length>0&&(yield value)}}finally{await(reader.cancel?.())}}async function*bufferedTextByteSource(text2,splitAt=[]){let bytes=(new TextEncoder).encode(text2),points=[...new Set(splitAt)].filter(n=>n>0&&n<bytes.length).sort((a,b)=>a-b),start=0;for(let point of points)yield bytes.subarray(start,point),start=point;yield bytes.subarray(start)}function eventSourceByteSource(es){let enc=new TextEncoder,queue=createByteQueue(),cleaned=false,onMessage=ev=>{let block="";ev.lastEventId&&(block+=`id: ${ev.lastEventId}\n`);let data=ev.data??"";for(let line of data.split(`\n`))block+=`data: ${line}\n`;block+=`\n`,queue.push(enc.encode(block))},onDone=()=>{cleanup(),queue.end()},onError=ev=>{let status=typeof ev.xhrStatus=="number"?ev.xhrStatus:0;if(status>=400){let wireCode=statusToWireCode(status),retryable=isAutoRetryable(fromWire(wireCode));queue.push(enc.encode(`data: ${JSON.stringify({type:"error",code:wireCode,retryable:retryable})}\n\n`))}cleanup(),queue.end()};es.addEventListener("message",onMessage),es.addEventListener("done",onDone),es.addEventListener("error",onError);function cleanup(){if(!cleaned){cleaned=true,es.removeEventListener("message",onMessage),es.removeEventListener("done",onDone),es.removeEventListener("error",onError);try{es.close()}catch{}}}return sourceWithCleanup(queue.source,cleanup)}async function*sourceWithCleanup(source,cleanup){try{yield*source}finally{cleanup()}}function createByteQueue(){let buffer=[],done=false,wake=null,signal=()=>{if(wake){let fn=wake;wake=null,fn()}};async function*gen(){for(;;){let next=buffer.shift();if(next!==void 0){yield next;continue}if(done)return;await new Promise(resolve=>{wake=resolve})}}return{source:gen(),push:u=>{buffer.push(u),signal()},end:()=>{done=true,signal()}}}async function requestJson(req,deps){let fetchImpl=deps.fetchImpl??getGlobalFetch(),url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"application/json",req.body!==void 0&&req.multipart===void 0),deadline=timeoutSignal(UNARY_TIMEOUT_MS),signal=mergeAbortSignals(deadline.signal,req.signal),res;try{res=await fetchImpl(url,buildInit({...req,signal:signal},headers))}catch(cause){return err(networkError(cause))}finally{deadline.cancel()}let bodyJson=await safeJson(res);return res.ok?ok(bodyJson):err(errorFromResponse(res.status,withRetryAfter(res,bodyJson),requestIdOf(res)))}async function requestRaw(req,deps,byteSourceFor){let fetchImpl=deps.fetchImpl??getGlobalFetch(),url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"text/event-stream",req.body!==void 0&&req.multipart===void 0),res;try{res=await fetchImpl(url,buildInit(req,headers))}catch(cause){return err(networkError(cause))}if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,await safeJson(res)),requestIdOf(res)));let bytes=byteSourceFor?byteSourceFor(res):fetchByteSource(res.body);return ok({ok:res.ok,status:res.status,headers:collectHeaders(res),bytes:bytes})}function createHttpTransport(deps){return{request:req=>requestJson(req,deps),stream:(req,signal)=>streamFrames(withSignal(req,signal),deps)}}async function*streamFrames(req,deps){let url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"text/event-stream",req.body!==void 0&&req.multipart===void 0);if(deps.eventSourceFactory){let es=deps.eventSourceFactory(url,buildEventSourceInit(req,headers));yield*parseSse(eventSourceByteSource(es),()=>eventSourceRequestId(es));return}let fetchImpl=deps.fetchImpl??getGlobalFetch(),res;try{res=await fetchImpl(url,buildInit(req,headers))}catch(cause){yield syntheticErrorFrame("",true,describeCause(cause));return}let requestId=requestIdOf(res);if(!res.ok){let body=await safeJson(res),wireCode=extractWireCode(body)??statusToWireCode(res.status),retryable=extractRetryable(body)||isAutoRetryable(fromWire(wireCode));yield syntheticErrorFrame(wireCode,retryable,extractWireMessage(body),requestId);return}if(res.body){yield*parseSse(fetchByteSource(res.body),requestId);return}yield*parseSse(fetchByteSource(null),requestId)}function buildEventSourceInit(req,headers){return{method:req.method,headers:headers,pollingInterval:0,...req.body!==void 0?{body:JSON.stringify(req.body)}:{}}}function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function eventSourceRequestId(es){if(typeof es.getResponseHeader!="function")return null;let value;try{value=es.getResponseHeader(REQUEST_ID_HEADER)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function statusToWireCode(status){return status===401?"AUTH_EXPIRED":status===403?"ACCESS_DENIED":status===404?"NOT_FOUND":status===409?"IDEMPOTENCY_CONFLICT":status===421?"MISDIRECTED_REQUEST":status===429?"RATE_LIMITED":status===400||status===422?"INVALID_REQUEST":status===503||status>=500?"INTERNAL_ERROR":""}function syntheticErrorFrame(code,retryable,wireMessage,serverRequestId=null){return errorFrame({code:code,retryable:retryable,wireMessage:wireMessage,synthesized:true,lastEventId:null,serverRequestId:serverRequestId})}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function buildUrl(base,path,query){let rel=path.startsWith("/")?path:`/${path}`,url=`${base}${rel}`;if(query){let qs=Object.entries(query).filter(entry=>entry[1]!==void 0).map(([k,v])=>`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");qs&&(url+=`?${qs}`)}return url}function mergeHeaders(config,reqHeaders,accept,hasJsonBody){let headers={...buildBaseHeaders(config),accept:accept};return hasJsonBody&&(headers["content-type"]="application/json"),reqHeaders&&Object.assign(headers,reqHeaders),headers}function buildInit(req,headers){let init={method:req.method,headers:headers};return req.multipart!==void 0?init.body=req.multipart:req.body!==void 0&&(init.body=JSON.stringify(req.body)),req.signal&&(init.signal=req.signal),init}function withSignal(req,signal){return req.signal?req:{...req,signal:signal}}function timeoutSignal(ms){let ctrl=new AbortController,handle=setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>clearTimeout(handle)}}function mergeAbortSignals(deadline,caller){if(!caller)return deadline;let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),ctrl.signal}async function safeJson(res){try{return await res.json()}catch{return null}}function collectHeaders(res){let out={};return res.headers.forEach?.((value,key)=>{out[key.toLowerCase()]=value}),out}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?code:null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}function resolveEntitlements(levels){if(levels.length===0)return freezeResolved({granted:[],asGrant:{allow:[],deny:[]}});let allowed=null,denied=/* @__PURE__ */new Set;for(let level of levels){let allow=new Set(level.allow);allowed=allowed===null?allow:intersect(allowed,allow);for(let key of level.deny)denied.add(key)}let granted=[...allowed??/* @__PURE__ */new Set].filter(key=>!denied.has(key)).sort();return freezeResolved({granted:granted,asGrant:{allow:granted,deny:[]}})}function intersect(a,b){let out=/* @__PURE__ */new Set;for(let key of a)b.has(key)&&out.add(key);return out}function freezeResolved(r){/* @__PURE__ */
104
+ return Object.freeze({kind:"unknown",raw:{...raw},lastEventId:lastEventId,serverRequestId:serverRequestId,terminal:false})}var EMPTY_FRAME_ARRAYS=/* @__PURE__ */Object.freeze({strings:EMPTY_STRINGS,maps:EMPTY_MAPS});var BLOCK_SEPARATOR=`\n\n`,MAX_PENDING_BLOCK_CHARS=1048576,wireObjectSchema=/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string(),/* @__PURE__ */zod.z.unknown()),URGENCY_LEVELS=["emergency","schedule_soon","home_care"];async function*parseSse(bytes,serverRequestId=null){let resolvedRequestId=null,requestIdNow=()=>(resolvedRequestId!==null||(resolvedRequestId=typeof serverRequestId=="function"?serverRequestId():serverRequestId),resolvedRequestId),decoder=new TextDecoder("utf-8"),buffer="",scanFrom=0,sawDelta=false;for await(let chunk of bytes){for(buffer+=decoder.decode(chunk,{stream:true});;){let sep=buffer.indexOf(BLOCK_SEPARATOR,scanFrom);if(sep===-1)break;let block=buffer.slice(0,sep);buffer=buffer.slice(sep+BLOCK_SEPARATOR.length),scanFrom=0;let frame=parseBlock(block,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}if(scanFrom=buffer.length>0?buffer.length-1:0,buffer.length>MAX_PENDING_BLOCK_CHARS){yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()});return}}if(buffer+=decoder.decode(),buffer.trim().length>0){let frame=parseBlock(buffer,requestIdNow());if(frame!==null&&(frame.kind==="delta"&&(sawDelta=true),yield frame,frame.terminal))return}yield errorFrame({code:sawDelta?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:requestIdNow()})}function parseBlock(block,serverRequestId){let id=null,dataLines=[];for(let rawLine of block.split(`\n`)){let line=rawLine.replace(/\s+$/,"");line.length===0||line.startsWith(":")||(line.startsWith("id:")?id=line.slice(3).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).replace(/^ /,"")))}if(dataLines.length===0)return null;let decoded;try{decoded=JSON.parse(dataLines.join(`\n`))}catch{return null}if(typeof decoded!="object"||decoded===null||Array.isArray(decoded))return null;let parsed=wireObjectSchema.safeParse(decoded);return parsed.success?frameFromWire(parsed.data,id,serverRequestId):null}function frameFromWire(json,lastEventId,serverRequestId){let type=json.type,event=json.event;if(type==="error"||"error"in json)return errorFrame({code:asString(json.code)??"unknown",retryable:json.retryable===true,wireMessage:asString(json.error),synthesized:false,lastEventId:lastEventId,serverRequestId:serverRequestId});if(type==="done"||json.done===true)return doneFrame({conversationId:asString(json.conversation_id)??"",messageId:asString(json.message_id),title:asString(json.title),followUpQuestions:asStringList(json.follow_up_questions),citations:asMapList(json.citations),citationStatus:asString(json.citation_status),urgencyLevel:asUrgency(json.urgency_level),urgencyReason:asString(json.urgency_reason),urgencyProvided:urgencySlotProvided(json),resultId:asString(json.result_id),lastEventId:lastEventId},serverRequestId);if(type==="accepted"||json.status==="reasoning")return acceptedFrame(asString(json.stream_id),lastEventId,serverRequestId);if(type==="heartbeat"||json.heartbeat===true)return heartbeatFrame(lastEventId,serverRequestId);if(type==="text.delta"||"delta"in json||"token"in json){let delta=asString(json.delta)??asString(json.token)??"";return deltaFrame(delta,lastEventId,serverRequestId)}return event==="analysis_started"?analysisStartedFrame(asString(json.request_id),lastEventId,serverRequestId):event==="analysis_complete"?analysisCompleteFrame({resultId:asString(json.result_id),analysisType:asString(json.analysis_type),modelVersion:asString(json.model_version),confidence:asNumber(json.confidence),detections:asMapList(json.detections),interpretation:asString(json.interpretation),lastEventId:lastEventId},serverRequestId):unknownFrame(json,lastEventId,serverRequestId)}function asString(v){return typeof v=="string"?v:null}function asNumber(v){return typeof v=="number"&&Number.isFinite(v)?v:null}function asUrgency(v){return typeof v=="string"&&URGENCY_LEVELS.includes(v)?v:null}function urgencySlotProvided(json){if(!Object.prototype.hasOwnProperty.call(json,"urgency_level"))return false;let raw=json.urgency_level;return raw===null||asUrgency(raw)!==null}function asStringList(v){return Array.isArray(v)?v.map(e=>typeof e=="string"?e:String(e)):[]}function isPlainObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function asMapList(v){return Array.isArray(v)?v.filter(isPlainObject):[]}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var UNARY_TIMEOUT_MS=3e4,REQUEST_ID_HEADER="x-request-id";async function*fetchByteSource(body){if(!body)return;let reader=body.getReader();try{for(;;){let{done:done,value:value}=await reader.read();if(done)break;value&&value.length>0&&(yield value)}}finally{await(reader.cancel?.())}}async function*bufferedTextByteSource(text2,splitAt=[]){let bytes=(new TextEncoder).encode(text2),points=[...new Set(splitAt)].filter(n=>n>0&&n<bytes.length).sort((a,b)=>a-b),start=0;for(let point of points)yield bytes.subarray(start,point),start=point;yield bytes.subarray(start)}function eventSourceByteSource(es){let enc=new TextEncoder,queue=createByteQueue(),cleaned=false,onMessage=ev=>{let block="";ev.lastEventId&&(block+=`id: ${ev.lastEventId}\n`);let data=ev.data??"";for(let line of data.split(`\n`))block+=`data: ${line}\n`;block+=`\n`,queue.push(enc.encode(block))},onDone=()=>{cleanup(),queue.end()},onError=ev=>{let status=typeof ev.xhrStatus=="number"?ev.xhrStatus:0;if(status>=400){let wireCode=statusToWireCode(status),retryable=isAutoRetryable(fromWire(wireCode));queue.push(enc.encode(`data: ${JSON.stringify({type:"error",code:wireCode,retryable:retryable})}\n\n`))}cleanup(),queue.end()};es.addEventListener("message",onMessage),es.addEventListener("done",onDone),es.addEventListener("error",onError);function cleanup(){if(!cleaned){cleaned=true,es.removeEventListener("message",onMessage),es.removeEventListener("done",onDone),es.removeEventListener("error",onError);try{es.close()}catch{}}}return sourceWithCleanup(queue.source,cleanup)}async function*sourceWithCleanup(source,cleanup){try{yield*source}finally{cleanup()}}function createByteQueue(){let buffer=[],done=false,wake=null,signal=()=>{if(wake){let fn=wake;wake=null,fn()}};async function*gen(){for(;;){let next=buffer.shift();if(next!==void 0){yield next;continue}if(done)return;await new Promise(resolve=>{wake=resolve})}}return{source:gen(),push:u=>{buffer.push(u),signal()},end:()=>{done=true,signal()}}}async function requestJson(req,deps){let fetchImpl=deps.fetchImpl??getGlobalFetch(),url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"application/json",req.body!==void 0&&req.multipart===void 0),deadline=timeoutSignal(UNARY_TIMEOUT_MS),signal=mergeAbortSignals(deadline.signal,req.signal),res;try{res=await fetchImpl(url,buildInit({...req,signal:signal},headers))}catch(cause){return err(networkError(cause))}finally{deadline.cancel()}let bodyJson=await safeJson(res);return res.ok?ok(bodyJson):err(errorFromResponse(res.status,withRetryAfter(res,bodyJson),requestIdOf(res)))}async function requestRaw(req,deps,byteSourceFor){let fetchImpl=deps.fetchImpl??getGlobalFetch(),url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"text/event-stream",req.body!==void 0&&req.multipart===void 0),res;try{res=await fetchImpl(url,buildInit(req,headers))}catch(cause){return err(networkError(cause))}if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,await safeJson(res)),requestIdOf(res)));let bytes=byteSourceFor?byteSourceFor(res):fetchByteSource(res.body);return ok({ok:res.ok,status:res.status,headers:collectHeaders(res),bytes:bytes})}function createHttpTransport(deps){return{request:req=>requestJson(req,deps),stream:(req,signal)=>streamFrames(withSignal(req,signal),deps)}}async function*streamFrames(req,deps){let url=buildUrl(deps.config.apiBaseUrl,req.path,req.query),headers=mergeHeaders(deps.config,req.headers,"text/event-stream",req.body!==void 0&&req.multipart===void 0);if(deps.eventSourceFactory){let es=deps.eventSourceFactory(url,buildEventSourceInit(req,headers));yield*parseSse(eventSourceByteSource(es),()=>eventSourceRequestId(es));return}let fetchImpl=deps.fetchImpl??getGlobalFetch(),res;try{res=await fetchImpl(url,buildInit(req,headers))}catch(cause){yield syntheticErrorFrame("",true,describeCause(cause));return}let requestId=requestIdOf(res);if(!res.ok){let body=await safeJson(res),wireCode=extractWireCode(body)??statusToWireCode(res.status),retryable=extractRetryable(body)||isAutoRetryable(fromWire(wireCode));yield syntheticErrorFrame(wireCode,retryable,extractWireMessage(body),requestId);return}if(res.body){yield*parseSse(fetchByteSource(res.body),requestId);return}yield*parseSse(fetchByteSource(null),requestId)}function buildEventSourceInit(req,headers){return{method:req.method,headers:headers,pollingInterval:0,...req.body!==void 0?{body:JSON.stringify(req.body)}:{}}}function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function eventSourceRequestId(es){if(typeof es.getResponseHeader!="function")return null;let value;try{value=es.getResponseHeader(REQUEST_ID_HEADER)}catch{return null}return typeof value=="string"&&value.length>0?value:null}function statusToWireCode(status){return status===401?"AUTH_EXPIRED":status===403?"ACCESS_DENIED":status===404?"NOT_FOUND":status===409?"IDEMPOTENCY_CONFLICT":status===421?"MISDIRECTED_REQUEST":status===429?"RATE_LIMITED":status===400||status===422?"INVALID_REQUEST":status===503||status>=500?"INTERNAL_ERROR":""}function syntheticErrorFrame(code,retryable,wireMessage,serverRequestId=null){return errorFrame({code:code,retryable:retryable,wireMessage:wireMessage,synthesized:true,lastEventId:null,serverRequestId:serverRequestId})}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function buildUrl(base,path,query){let rel=path.startsWith("/")?path:`/${path}`,url=`${base}${rel}`;if(query){let qs=Object.entries(query).filter(entry=>entry[1]!==void 0).map(([k,v])=>`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");qs&&(url+=`?${qs}`)}return url}function mergeHeaders(config,reqHeaders,accept,hasJsonBody){let headers={...buildBaseHeaders(config),accept:accept};return hasJsonBody&&(headers["content-type"]="application/json"),reqHeaders&&Object.assign(headers,reqHeaders),headers}function buildInit(req,headers){let init={method:req.method,headers:headers};return req.multipart!==void 0?init.body=req.multipart:req.body!==void 0&&(init.body=JSON.stringify(req.body)),req.signal&&(init.signal=req.signal),init}function withSignal(req,signal){return req.signal?req:{...req,signal:signal}}function timeoutSignal(ms){let ctrl=new AbortController,handle=setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>clearTimeout(handle)}}function mergeAbortSignals(deadline,caller){if(!caller)return deadline;let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),ctrl.signal}async function safeJson(res){try{return await res.json()}catch{return null}}function collectHeaders(res){let out={};return res.headers.forEach?.((value,key)=>{out[key.toLowerCase()]=value}),out}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?code:null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}function resolveEntitlements(levels){if(levels.length===0)return freezeResolved({granted:[],asGrant:{allow:[],deny:[]}});let allowed=null,denied=/* @__PURE__ */new Set;for(let level of levels){let allow=new Set(level.allow);allowed=allowed===null?allow:intersect(allowed,allow);for(let key of level.deny)denied.add(key)}let granted=[...allowed??/* @__PURE__ */new Set].filter(key=>!denied.has(key)).sort();return freezeResolved({granted:granted,asGrant:{allow:granted,deny:[]}})}function intersect(a,b){let out=/* @__PURE__ */new Set;for(let key of a)b.has(key)&&out.add(key);return out}function freezeResolved(r){/* @__PURE__ */
103
105
  return Object.freeze({granted:/* @__PURE__ */Object.freeze([...r.granted]),asGrant:/* @__PURE__ */Object.freeze({allow:/* @__PURE__ */Object.freeze([...r.asGrant.allow]),deny:/* @__PURE__ */Object.freeze([...r.asGrant.deny])})})}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"])});function requires(name){return REQUIRES[name]}function deniedDecisionsFor(level,reason){let disabled=/* @__PURE__ */Object.freeze({reason:reason,level:level,recoverable:false}),rows=[],seen=/* @__PURE__ */new Set;for(let name of Object.keys(REQUIRES))for(let resource of REQUIRES[name])seen.has(resource)||(seen.add(resource),rows.push(/* @__PURE__ */Object.freeze({resource:resource,granted:false,disabled:disabled}))/* @__PURE__ */);return Object.freeze(rows)}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
104
106
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
105
107
  return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}var 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(
@@ -1,25 +1,25 @@
1
1
  import { b as EverfurErrorCode } from '../EverfurError-DeBqRpQV.cjs';
2
2
  export { A as AUTO_RETRYABLE_CODES, B as BACKOFF_BASE_MS, d as BACKOFF_CAP_MS, e as EVERFUR_ERROR_CATEGORIES, f as EVERFUR_ERROR_CODES, E as EverfurError, a as EverfurErrorCategory, M as MAX_RETRY_ATTEMPTS, g as MakeEverfurErrorOptions, R as RETRYABLE_CONTRACT_CODES, h as backoffDelayMs, j as canRecreateOnNotFound, c as categoryFor, k as fromHttpStatus, l as fromWire, m as isAutoRetryable, i as isRetryableCode, n as makeEverfurError, s as shouldRetry, u as userFacingError } from '../EverfurError-DeBqRpQV.cjs';
3
3
  export { a as EverfurConfigError, E as EverfurResult, b as EverfurThrownError, e as err, i as isErr, c as isOk, o as ok, u as unwrap } from '../EverfurResult-COlXj1wq.cjs';
4
- export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, B as ByteSource, C as ClientConfigFailure, k as ClientConfigFailureReason, l as ClientConfigOutcome, m as DEFAULT_CONTRACT_VERSION, D as DeltaFrame, c as DoneFrame, n as EMPTY_FRAME_ARRAYS, o as ENV_API_BASE_URL, E as ErrorFrame, p as EventSourceFactory, q as EventSourceInit, r as EventSourceLike, s as EventSourceMessage, t as EverfurConfig, d as EverfurRequest, e as EverfurRequestBase, u as FetchInit, j as FetchLike, v as FetchResponseLike, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, R as RawResponse, w as ReadableStreamLike, x as ResolveClientConfigOptions, y as ResolvedClientConfig, S as SDK_PLATFORM, z as SDK_VERSION, G as SdkPlatform, I as ServerRequestIdSource, J as TransportDeps, T as TransportPort, U as UnknownFrame, i as UrgencyLevel, K as acceptedFrame, L as analysisCompleteFrame, N as analysisStartedFrame, O as assertNever, P as bufferedTextByteSource, Q as buildBaseHeaders, V as checkPublishableKey, W as createHttpTransport, X as deltaFrame, Y as doneFrame, Z as errorFrame, _ as errorFromResponse, $ as eventSourceByteSource, a0 as eventSourceRequestId, a1 as fetchByteSource, a2 as getGlobalFetch, a3 as heartbeatFrame, a4 as networkError, a5 as parseSse, a6 as requestIdOf, a7 as requestJson, a8 as requestRaw, a9 as resolveApiBaseUrl, aa as resolveClientConfig, ab as tryResolveApiBaseUrl, ac as tryResolveClientConfig, ad as unknownFrame } from '../config-lilR0260.cjs';
4
+ export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, B as ByteSource, C as ClientConfigFailure, k as ClientConfigFailureReason, l as ClientConfigOutcome, m as DEFAULT_CONTRACT_VERSION, D as DeltaFrame, c as DoneFrame, n as EMPTY_FRAME_ARRAYS, o as ENV_API_BASE_URL, E as ErrorFrame, p as EventSourceFactory, q as EventSourceInit, r as EventSourceLike, s as EventSourceMessage, t as EverfurConfig, d as EverfurRequest, e as EverfurRequestBase, u as FetchInit, j as FetchLike, v as FetchResponseLike, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, R as RawResponse, w as ReadableStreamLike, x as ResolveClientConfigOptions, y as ResolvedClientConfig, S as SDK_PLATFORM, z as SDK_VERSION, G as SdkPlatform, I as ServerRequestIdSource, J as TransportDeps, T as TransportPort, U as UnknownFrame, i as UrgencyLevel, K as acceptedFrame, L as analysisCompleteFrame, N as analysisStartedFrame, O as assertNever, P as bufferedTextByteSource, Q as buildBaseHeaders, V as checkPublishableKey, W as createHttpTransport, X as deltaFrame, Y as doneFrame, Z as errorFrame, _ as errorFromResponse, $ as eventSourceByteSource, a0 as eventSourceRequestId, a1 as fetchByteSource, a2 as getGlobalFetch, a3 as heartbeatFrame, a4 as networkError, a5 as parseSse, a6 as requestIdOf, a7 as requestJson, a8 as requestRaw, a9 as resolveApiBaseUrl, aa as resolveClientConfig, ab as tryResolveApiBaseUrl, ac as tryResolveClientConfig, ad as unknownFrame } from '../config-B0p6Lygh.cjs';
5
5
  export { B as Brand, a as ClientId, C as ConversationId, D as DocumentId, J as JobId, P as PetRef, R as RecordsRequestId, b as ResponseId, U as UserRef, _ as __brand, c as conversationId, p as petRef, d as unsafeClientId, e as unsafeConversationId, f as unsafeDocumentId, g as unsafeJobId, h as unsafePetRef, i as unsafeRecordsRequestId, j as unsafeResponseId, k as unsafeUserRef, u as userRef } from '../ids-B2GAAifq.cjs';
6
- export { A as AuthContext, D as DeviceAuth, I as IdentityProvider, M as MintedToken, T as TokenProvider, a as authHeaders, b as authedSend, c as createIdentityProvider, n as newSessionId, w as withAuthHeaders } from '../identity-YXqHjBln.cjs';
6
+ export { A as AuthContext, D as DeviceAuth, I as IdentityProvider, M as MintedToken, T as TokenProvider, a as authHeaders, b as authedSend, c as createIdentityProvider, n as newSessionId, w as withAuthHeaders } from '../identity-DFVGYn1o.cjs';
7
7
  export { a as CapabilityDecision, b as CapabilityDisabled, C as CapabilityName, c as DecideOptions, D as DisabledLevel, E as EntitlementDecision, L as LevelGrant, R as ResolvedEntitlements, d as decideCapability, e as deniedDecisionsFor, r as requires, f as resolveEntitlements } from '../resolve-D4Ywz5OS.cjs';
8
- export { E as ENTITLEMENTS_PATH, a as EntitlementResolution, F as FetchEntitlementsArgs, f as fetchEntitlements } from '../entitlementRepository-Blh38A2b.cjs';
8
+ export { E as ENTITLEMENTS_PATH, a as EntitlementResolution, F as FetchEntitlementsArgs, f as fetchEntitlements } from '../entitlementRepository-D-Lse67w.cjs';
9
9
  import { m as EverfurTheme } from '../tokens-DLj8OnLH.cjs';
10
10
  export { D as DEFAULT_MAX_FONT_SCALE, w as EASING_CURVES, x as EVERFUR_DARK, y as EVERFUR_LIGHT, E as EverfurColorTokens, z as EverfurEasingCurve, a as EverfurFontFaceKey, b as EverfurFontFamilies, c as EverfurFontSource, d as EverfurFontWeight, e as EverfurLetterSpacingTokens, f as EverfurLineHeightTokens, g as EverfurMotionDurationTokens, h as EverfurMotionTokens, i as EverfurRadiusTokens, j as EverfurSpaceTokens, k as EverfurSpringToken, l as EverfurTextColorTokens, A as EverfurTextScaleTier, n as EverfurThemeMeta, o as EverfurThemeSlot, p as EverfurThemeSlotKey, q as EverfurThemeSlotName, r as EverfurThemeSlots, s as EverfurTypeSizeTokens, t as EverfurTypeTokens, u as EverfurWeightTokens, S as SLOT_MIN_BORDER_CONTRAST, B as SLOT_MIN_CONTRAST, C as SYSTEM_FONT_FAMILY, F as SYSTEM_MONO_FAMILY, G as SlotGrounds, H as SlotSurrounds, I as TEXT_SCALE_TIER_CAPS, T as THEME_SLOT_KEYS, v as THEME_SLOT_NAMES, J as cssCubicBezier, K as deepFreeze, L as guardSlotContrast, M as mergeThemeSlots, N as parseThemeSlots } from '../tokens-DLj8OnLH.cjs';
11
11
  export { E as EverfurFaceStyle, a as EverfurThemeAdjustment, R as ResolveThemeInput, T as TEXT_SCALE_FLOOR, f as face, h as headingFace, p as previewTheme, r as resolveTheme, t as themeAdjustments, w as withServerBranding } from '../typeStyle-DJedEu14.cjs';
12
12
  export { A as APPEARANCE_PRESETS, a as APPEARANCE_PRESET_NAMES, b as APPEARANCE_SIZE_RANGES, C as ClientBranding, c as EverfurAppearance, d as EverfurAppearanceFont, e as EverfurAppearancePreset, f as EverfurAppearanceRules, g as EverfurAppearanceVariables, h as EverfurThemeFontFaceKey, i as EverfurThemeFontUrlsInput, j as EverfurThemeFontsInput, E as EverfurThemeInput, k as EverfurThemeSlotInput, l as EverfurThemeSlotsInput, L as LOCKABLE_THEME_FIELDS, n as LockableThemeField, M as MAX_FONT_SCALE_CEILING, R as RadiusScale, o as SLOT_LOCK_PREFIX, p as SlotLockName, S as SurfaceStyle, T as THEME_SCHEMA_VERSIONS, q as ThemeLockName, m as expandAppearance, r as hardenBrandAssetUrl, s as hardenHttpsUrl, t as isEmptyBranding, u as isKnownBrandingSchema, v as lockedFieldsOf, w as parseClientBranding, x as parsePx } from '../branding-BCfwLj0h.cjs';
13
- export { F as FunnelSendOptions, R as RequestFunnel, a as RequestFunnelDeps, c as createRequestFunnel } from '../requestFunnel-hXkP5T7K.cjs';
14
- export { c as PET_AGE_YEARS_MAX, d as PET_BREED_MAX, e as PET_NAME_MAX, f as PET_SPECIES_MAX, g as PET_WEIGHT_KG_MAX, P as PetProfileInput, a as PetProfilePatch, h as PetsRepository, R as RegisteredPet, W as WidgetPet, i as createPetsRepository, w as widgetPetFromWire } from '../petsRepository-CQeuDdDC.cjs';
15
- export { b as CHECKIN_ANSWERS, c as CasesRepository, C as CheckinAnswer, a as CheckinOutcome, W as WatchCase, d as createCasesRepository } from '../casesRepository-BhfPDWhY.cjs';
13
+ export { F as FunnelSendOptions, R as RequestFunnel, a as RequestFunnelDeps, c as createRequestFunnel } from '../requestFunnel-BBjNNwc9.cjs';
14
+ export { c as PET_AGE_YEARS_MAX, d as PET_BREED_MAX, e as PET_NAME_MAX, f as PET_SPECIES_MAX, g as PET_WEIGHT_KG_MAX, P as PetProfileInput, a as PetProfilePatch, h as PetsRepository, R as RegisteredPet, W as WidgetPet, i as createPetsRepository, w as widgetPetFromWire } from '../petsRepository-B_Q1gFkE.cjs';
15
+ export { b as CHECKIN_ANSWERS, c as CasesRepository, C as CheckinAnswer, a as CheckinOutcome, W as WatchCase, d as createCasesRepository } from '../casesRepository-CGdhvzTu.cjs';
16
16
  import '../ErrorPolicyPort-10s3HJCt.cjs';
17
17
  import '../profile-CSs1wlXT.cjs';
18
18
 
19
19
  /** Which wire shape a code arrives in. The two envelopes are different objects, not casings. */
20
20
  type ContractErrorEnvelope = "http_envelope" | "oauth_error" | "sse_frame";
21
21
  /** Every wire error code the contract declares, spelled EXACTLY as the server sends it. */
22
- type ContractWireErrorCode = "AccessDeniedException" | "AuthorizationException" | "ConflictException" | "DAILY_QUOTA_EXCEEDED" | "FILE_TOO_LARGE" | "IDEMPOTENCY_KEY_IN_FLIGHT" | "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST" | "INVALID_CONTENT_TYPE" | "InternalFailureException" | "MethodNotAllowedException" | "NotImplementedException" | "PaymentRequiredException" | "ResourceNotFoundException" | "ServiceUnavailableException" | "TIER_UPGRADE_REQUIRED" | "ThrottlingException" | "ValidationException" | "accessDenied" | "access_denied" | "attachment_unreadable" | "authExpired" | "authRejected" | "consent_invalid" | "consent_required" | "consent_scope_wrong_route" | "device_cipher_unavailable" | "email_invalid" | "event_cursor_invalid" | "event_filter_invalid" | "event_payload_invalid" | "event_type_not_available" | "event_type_unknown" | "idempotency_key_invalid" | "idempotency_key_required" | "idempotency_key_reused" | "insufficientCapability" | "insufficient_scope" | "internal_error" | "invalidRequest" | "invalid_client" | "invalid_client_metadata" | "invalid_grant" | "invalid_redirect_uri" | "invalid_request" | "invalid_scope" | "invalid_target" | "mcp_connection_not_found" | "mcp_request_conflict" | "mcp_request_gone" | "mcp_request_not_found" | "not_found" | "partner_visit_link_conflict" | "partner_visit_owner_only" | "partner_visit_pet_already_mapped" | "payload_too_large" | "petRefInUse" | "pet_health_list_removals_unconfirmed" | "pet_health_species_unsupported" | "pet_not_registered" | "provider_unsupported" | "rateLimited" | "record_species_unsupported" | "record_subject_not_found" | "record_upload_invalid" | "records_consent_required" | "sandbox_only" | "session_required" | "share_limit_reached" | "slow_down" | "species_unsupported" | "tenant_filter_invalid" | "tenant_has_no_capabilities" | "tenant_resource_not_found" | "tenant_surface_not_enabled" | "timeout" | "token_invalid" | "unavailable" | "unsupported_grant_type" | "unsupported_response_type" | "verify_mint_rate_limited" | "verify_mint_refused" | "verify_mint_unavailable" | "verify_user_ref_invalid" | "webhook_endpoint_update_empty" | "webhook_endpoint_update_invalid" | "webhook_url_rejected";
22
+ type ContractWireErrorCode = "AccessDeniedException" | "AuthorizationException" | "ConflictException" | "DAILY_QUOTA_EXCEEDED" | "FILE_TOO_LARGE" | "IDEMPOTENCY_KEY_IN_FLIGHT" | "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST" | "INVALID_CONTENT_TYPE" | "InternalFailureException" | "MethodNotAllowedException" | "NotImplementedException" | "PaymentRequiredException" | "ResourceNotFoundException" | "ServiceUnavailableException" | "TIER_UPGRADE_REQUIRED" | "ThrottlingException" | "ValidationException" | "accessDenied" | "access_denied" | "attachment_unreadable" | "authExpired" | "authRejected" | "consent_invalid" | "consent_required" | "consent_scope_wrong_route" | "device_cipher_unavailable" | "email_invalid" | "event_cursor_invalid" | "event_filter_invalid" | "event_payload_invalid" | "event_type_not_available" | "event_type_unknown" | "idempotency_key_invalid" | "idempotency_key_required" | "idempotency_key_reused" | "insufficientCapability" | "insufficient_scope" | "internal_error" | "invalidRequest" | "invalid_client" | "invalid_client_metadata" | "invalid_grant" | "invalid_redirect_uri" | "invalid_request" | "invalid_scope" | "invalid_target" | "mcp_connection_not_found" | "mcp_request_conflict" | "mcp_request_gone" | "mcp_request_not_found" | "not_found" | "partner_visit_link_conflict" | "partner_visit_owner_only" | "partner_visit_pet_already_mapped" | "payload_too_large" | "petRefInUse" | "pet_health_list_removals_unconfirmed" | "pet_health_species_unsupported" | "pet_not_registered" | "provider_unsupported" | "rateLimited" | "record_species_unsupported" | "record_subject_not_found" | "record_upload_invalid" | "records_consent_required" | "sandbox_only" | "session_required" | "session_revoked" | "share_limit_reached" | "slow_down" | "species_unsupported" | "tenant_filter_invalid" | "tenant_has_no_capabilities" | "tenant_resource_not_found" | "tenant_surface_not_enabled" | "timeout" | "token_invalid" | "unavailable" | "unrestrictedKeyRequired" | "unsupported_grant_type" | "unsupported_response_type" | "verify_mint_rate_limited" | "verify_mint_refused" | "verify_mint_unavailable" | "verify_user_ref_invalid" | "webhook_endpoint_update_empty" | "webhook_endpoint_update_invalid" | "webhook_url_rejected";
23
23
 
24
24
  /** One registry row, reduced to the facts the SDK needs at runtime. */
25
25
  interface ContractErrorRow {
@@ -1,25 +1,25 @@
1
1
  import { b as EverfurErrorCode } from '../EverfurError-DeBqRpQV.js';
2
2
  export { A as AUTO_RETRYABLE_CODES, B as BACKOFF_BASE_MS, d as BACKOFF_CAP_MS, e as EVERFUR_ERROR_CATEGORIES, f as EVERFUR_ERROR_CODES, E as EverfurError, a as EverfurErrorCategory, M as MAX_RETRY_ATTEMPTS, g as MakeEverfurErrorOptions, R as RETRYABLE_CONTRACT_CODES, h as backoffDelayMs, j as canRecreateOnNotFound, c as categoryFor, k as fromHttpStatus, l as fromWire, m as isAutoRetryable, i as isRetryableCode, n as makeEverfurError, s as shouldRetry, u as userFacingError } from '../EverfurError-DeBqRpQV.js';
3
3
  export { a as EverfurConfigError, E as EverfurResult, b as EverfurThrownError, e as err, i as isErr, c as isOk, o as ok, u as unwrap } from '../EverfurResult-ClPTS0P2.js';
4
- export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, B as ByteSource, C as ClientConfigFailure, k as ClientConfigFailureReason, l as ClientConfigOutcome, m as DEFAULT_CONTRACT_VERSION, D as DeltaFrame, c as DoneFrame, n as EMPTY_FRAME_ARRAYS, o as ENV_API_BASE_URL, E as ErrorFrame, p as EventSourceFactory, q as EventSourceInit, r as EventSourceLike, s as EventSourceMessage, t as EverfurConfig, d as EverfurRequest, e as EverfurRequestBase, u as FetchInit, j as FetchLike, v as FetchResponseLike, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, R as RawResponse, w as ReadableStreamLike, x as ResolveClientConfigOptions, y as ResolvedClientConfig, S as SDK_PLATFORM, z as SDK_VERSION, G as SdkPlatform, I as ServerRequestIdSource, J as TransportDeps, T as TransportPort, U as UnknownFrame, i as UrgencyLevel, K as acceptedFrame, L as analysisCompleteFrame, N as analysisStartedFrame, O as assertNever, P as bufferedTextByteSource, Q as buildBaseHeaders, V as checkPublishableKey, W as createHttpTransport, X as deltaFrame, Y as doneFrame, Z as errorFrame, _ as errorFromResponse, $ as eventSourceByteSource, a0 as eventSourceRequestId, a1 as fetchByteSource, a2 as getGlobalFetch, a3 as heartbeatFrame, a4 as networkError, a5 as parseSse, a6 as requestIdOf, a7 as requestJson, a8 as requestRaw, a9 as resolveApiBaseUrl, aa as resolveClientConfig, ab as tryResolveApiBaseUrl, ac as tryResolveClientConfig, ad as unknownFrame } from '../config-CuOczZUI.js';
4
+ export { A as AcceptedFrame, a as AnalysisCompleteFrame, b as AnalysisStartedFrame, B as ByteSource, C as ClientConfigFailure, k as ClientConfigFailureReason, l as ClientConfigOutcome, m as DEFAULT_CONTRACT_VERSION, D as DeltaFrame, c as DoneFrame, n as EMPTY_FRAME_ARRAYS, o as ENV_API_BASE_URL, E as ErrorFrame, p as EventSourceFactory, q as EventSourceInit, r as EventSourceLike, s as EventSourceMessage, t as EverfurConfig, d as EverfurRequest, e as EverfurRequestBase, u as FetchInit, j as FetchLike, v as FetchResponseLike, F as Frame, f as FrameBase, g as FrameKind, H as HeartbeatFrame, h as HttpMethod, M as MultipartBody, R as RawResponse, w as ReadableStreamLike, x as ResolveClientConfigOptions, y as ResolvedClientConfig, S as SDK_PLATFORM, z as SDK_VERSION, G as SdkPlatform, I as ServerRequestIdSource, J as TransportDeps, T as TransportPort, U as UnknownFrame, i as UrgencyLevel, K as acceptedFrame, L as analysisCompleteFrame, N as analysisStartedFrame, O as assertNever, P as bufferedTextByteSource, Q as buildBaseHeaders, V as checkPublishableKey, W as createHttpTransport, X as deltaFrame, Y as doneFrame, Z as errorFrame, _ as errorFromResponse, $ as eventSourceByteSource, a0 as eventSourceRequestId, a1 as fetchByteSource, a2 as getGlobalFetch, a3 as heartbeatFrame, a4 as networkError, a5 as parseSse, a6 as requestIdOf, a7 as requestJson, a8 as requestRaw, a9 as resolveApiBaseUrl, aa as resolveClientConfig, ab as tryResolveApiBaseUrl, ac as tryResolveClientConfig, ad as unknownFrame } from '../config-DmFAZJOx.js';
5
5
  export { B as Brand, a as ClientId, C as ConversationId, D as DocumentId, J as JobId, P as PetRef, R as RecordsRequestId, b as ResponseId, U as UserRef, _ as __brand, c as conversationId, p as petRef, d as unsafeClientId, e as unsafeConversationId, f as unsafeDocumentId, g as unsafeJobId, h as unsafePetRef, i as unsafeRecordsRequestId, j as unsafeResponseId, k as unsafeUserRef, u as userRef } from '../ids-B2GAAifq.js';
6
- export { A as AuthContext, D as DeviceAuth, I as IdentityProvider, M as MintedToken, T as TokenProvider, a as authHeaders, b as authedSend, c as createIdentityProvider, n as newSessionId, w as withAuthHeaders } from '../identity-4lohfP2L.js';
6
+ export { A as AuthContext, D as DeviceAuth, I as IdentityProvider, M as MintedToken, T as TokenProvider, a as authHeaders, b as authedSend, c as createIdentityProvider, n as newSessionId, w as withAuthHeaders } from '../identity-Cw07BKZp.js';
7
7
  export { a as CapabilityDecision, b as CapabilityDisabled, C as CapabilityName, c as DecideOptions, D as DisabledLevel, E as EntitlementDecision, L as LevelGrant, R as ResolvedEntitlements, d as decideCapability, e as deniedDecisionsFor, r as requires, f as resolveEntitlements } from '../resolve-D4Ywz5OS.js';
8
- export { E as ENTITLEMENTS_PATH, a as EntitlementResolution, F as FetchEntitlementsArgs, f as fetchEntitlements } from '../entitlementRepository-BE-L6vX1.js';
8
+ export { E as ENTITLEMENTS_PATH, a as EntitlementResolution, F as FetchEntitlementsArgs, f as fetchEntitlements } from '../entitlementRepository-CrTOP_-o.js';
9
9
  import { m as EverfurTheme } from '../tokens-DLj8OnLH.js';
10
10
  export { D as DEFAULT_MAX_FONT_SCALE, w as EASING_CURVES, x as EVERFUR_DARK, y as EVERFUR_LIGHT, E as EverfurColorTokens, z as EverfurEasingCurve, a as EverfurFontFaceKey, b as EverfurFontFamilies, c as EverfurFontSource, d as EverfurFontWeight, e as EverfurLetterSpacingTokens, f as EverfurLineHeightTokens, g as EverfurMotionDurationTokens, h as EverfurMotionTokens, i as EverfurRadiusTokens, j as EverfurSpaceTokens, k as EverfurSpringToken, l as EverfurTextColorTokens, A as EverfurTextScaleTier, n as EverfurThemeMeta, o as EverfurThemeSlot, p as EverfurThemeSlotKey, q as EverfurThemeSlotName, r as EverfurThemeSlots, s as EverfurTypeSizeTokens, t as EverfurTypeTokens, u as EverfurWeightTokens, S as SLOT_MIN_BORDER_CONTRAST, B as SLOT_MIN_CONTRAST, C as SYSTEM_FONT_FAMILY, F as SYSTEM_MONO_FAMILY, G as SlotGrounds, H as SlotSurrounds, I as TEXT_SCALE_TIER_CAPS, T as THEME_SLOT_KEYS, v as THEME_SLOT_NAMES, J as cssCubicBezier, K as deepFreeze, L as guardSlotContrast, M as mergeThemeSlots, N as parseThemeSlots } from '../tokens-DLj8OnLH.js';
11
11
  export { E as EverfurFaceStyle, a as EverfurThemeAdjustment, R as ResolveThemeInput, T as TEXT_SCALE_FLOOR, f as face, h as headingFace, p as previewTheme, r as resolveTheme, t as themeAdjustments, w as withServerBranding } from '../typeStyle-BxVyF71R.js';
12
12
  export { A as APPEARANCE_PRESETS, a as APPEARANCE_PRESET_NAMES, b as APPEARANCE_SIZE_RANGES, C as ClientBranding, c as EverfurAppearance, d as EverfurAppearanceFont, e as EverfurAppearancePreset, f as EverfurAppearanceRules, g as EverfurAppearanceVariables, h as EverfurThemeFontFaceKey, i as EverfurThemeFontUrlsInput, j as EverfurThemeFontsInput, E as EverfurThemeInput, k as EverfurThemeSlotInput, l as EverfurThemeSlotsInput, L as LOCKABLE_THEME_FIELDS, n as LockableThemeField, M as MAX_FONT_SCALE_CEILING, R as RadiusScale, o as SLOT_LOCK_PREFIX, p as SlotLockName, S as SurfaceStyle, T as THEME_SCHEMA_VERSIONS, q as ThemeLockName, m as expandAppearance, r as hardenBrandAssetUrl, s as hardenHttpsUrl, t as isEmptyBranding, u as isKnownBrandingSchema, v as lockedFieldsOf, w as parseClientBranding, x as parsePx } from '../branding-DJf4h12Q.js';
13
- export { F as FunnelSendOptions, R as RequestFunnel, a as RequestFunnelDeps, c as createRequestFunnel } from '../requestFunnel-B86gQFka.js';
14
- export { c as PET_AGE_YEARS_MAX, d as PET_BREED_MAX, e as PET_NAME_MAX, f as PET_SPECIES_MAX, g as PET_WEIGHT_KG_MAX, P as PetProfileInput, a as PetProfilePatch, h as PetsRepository, R as RegisteredPet, W as WidgetPet, i as createPetsRepository, w as widgetPetFromWire } from '../petsRepository-B1I6Lq_m.js';
15
- export { b as CHECKIN_ANSWERS, c as CasesRepository, C as CheckinAnswer, a as CheckinOutcome, W as WatchCase, d as createCasesRepository } from '../casesRepository-DMkRRKr8.js';
13
+ export { F as FunnelSendOptions, R as RequestFunnel, a as RequestFunnelDeps, c as createRequestFunnel } from '../requestFunnel-B9fdXMi5.js';
14
+ export { c as PET_AGE_YEARS_MAX, d as PET_BREED_MAX, e as PET_NAME_MAX, f as PET_SPECIES_MAX, g as PET_WEIGHT_KG_MAX, P as PetProfileInput, a as PetProfilePatch, h as PetsRepository, R as RegisteredPet, W as WidgetPet, i as createPetsRepository, w as widgetPetFromWire } from '../petsRepository-518QkPxH.js';
15
+ export { b as CHECKIN_ANSWERS, c as CasesRepository, C as CheckinAnswer, a as CheckinOutcome, W as WatchCase, d as createCasesRepository } from '../casesRepository-ZG9Sg0e4.js';
16
16
  import '../ErrorPolicyPort-C3nNSS_j.js';
17
17
  import '../profile-CSs1wlXT.js';
18
18
 
19
19
  /** Which wire shape a code arrives in. The two envelopes are different objects, not casings. */
20
20
  type ContractErrorEnvelope = "http_envelope" | "oauth_error" | "sse_frame";
21
21
  /** Every wire error code the contract declares, spelled EXACTLY as the server sends it. */
22
- type ContractWireErrorCode = "AccessDeniedException" | "AuthorizationException" | "ConflictException" | "DAILY_QUOTA_EXCEEDED" | "FILE_TOO_LARGE" | "IDEMPOTENCY_KEY_IN_FLIGHT" | "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST" | "INVALID_CONTENT_TYPE" | "InternalFailureException" | "MethodNotAllowedException" | "NotImplementedException" | "PaymentRequiredException" | "ResourceNotFoundException" | "ServiceUnavailableException" | "TIER_UPGRADE_REQUIRED" | "ThrottlingException" | "ValidationException" | "accessDenied" | "access_denied" | "attachment_unreadable" | "authExpired" | "authRejected" | "consent_invalid" | "consent_required" | "consent_scope_wrong_route" | "device_cipher_unavailable" | "email_invalid" | "event_cursor_invalid" | "event_filter_invalid" | "event_payload_invalid" | "event_type_not_available" | "event_type_unknown" | "idempotency_key_invalid" | "idempotency_key_required" | "idempotency_key_reused" | "insufficientCapability" | "insufficient_scope" | "internal_error" | "invalidRequest" | "invalid_client" | "invalid_client_metadata" | "invalid_grant" | "invalid_redirect_uri" | "invalid_request" | "invalid_scope" | "invalid_target" | "mcp_connection_not_found" | "mcp_request_conflict" | "mcp_request_gone" | "mcp_request_not_found" | "not_found" | "partner_visit_link_conflict" | "partner_visit_owner_only" | "partner_visit_pet_already_mapped" | "payload_too_large" | "petRefInUse" | "pet_health_list_removals_unconfirmed" | "pet_health_species_unsupported" | "pet_not_registered" | "provider_unsupported" | "rateLimited" | "record_species_unsupported" | "record_subject_not_found" | "record_upload_invalid" | "records_consent_required" | "sandbox_only" | "session_required" | "share_limit_reached" | "slow_down" | "species_unsupported" | "tenant_filter_invalid" | "tenant_has_no_capabilities" | "tenant_resource_not_found" | "tenant_surface_not_enabled" | "timeout" | "token_invalid" | "unavailable" | "unsupported_grant_type" | "unsupported_response_type" | "verify_mint_rate_limited" | "verify_mint_refused" | "verify_mint_unavailable" | "verify_user_ref_invalid" | "webhook_endpoint_update_empty" | "webhook_endpoint_update_invalid" | "webhook_url_rejected";
22
+ type ContractWireErrorCode = "AccessDeniedException" | "AuthorizationException" | "ConflictException" | "DAILY_QUOTA_EXCEEDED" | "FILE_TOO_LARGE" | "IDEMPOTENCY_KEY_IN_FLIGHT" | "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST" | "INVALID_CONTENT_TYPE" | "InternalFailureException" | "MethodNotAllowedException" | "NotImplementedException" | "PaymentRequiredException" | "ResourceNotFoundException" | "ServiceUnavailableException" | "TIER_UPGRADE_REQUIRED" | "ThrottlingException" | "ValidationException" | "accessDenied" | "access_denied" | "attachment_unreadable" | "authExpired" | "authRejected" | "consent_invalid" | "consent_required" | "consent_scope_wrong_route" | "device_cipher_unavailable" | "email_invalid" | "event_cursor_invalid" | "event_filter_invalid" | "event_payload_invalid" | "event_type_not_available" | "event_type_unknown" | "idempotency_key_invalid" | "idempotency_key_required" | "idempotency_key_reused" | "insufficientCapability" | "insufficient_scope" | "internal_error" | "invalidRequest" | "invalid_client" | "invalid_client_metadata" | "invalid_grant" | "invalid_redirect_uri" | "invalid_request" | "invalid_scope" | "invalid_target" | "mcp_connection_not_found" | "mcp_request_conflict" | "mcp_request_gone" | "mcp_request_not_found" | "not_found" | "partner_visit_link_conflict" | "partner_visit_owner_only" | "partner_visit_pet_already_mapped" | "payload_too_large" | "petRefInUse" | "pet_health_list_removals_unconfirmed" | "pet_health_species_unsupported" | "pet_not_registered" | "provider_unsupported" | "rateLimited" | "record_species_unsupported" | "record_subject_not_found" | "record_upload_invalid" | "records_consent_required" | "sandbox_only" | "session_required" | "session_revoked" | "share_limit_reached" | "slow_down" | "species_unsupported" | "tenant_filter_invalid" | "tenant_has_no_capabilities" | "tenant_resource_not_found" | "tenant_surface_not_enabled" | "timeout" | "token_invalid" | "unavailable" | "unrestrictedKeyRequired" | "unsupported_grant_type" | "unsupported_response_type" | "verify_mint_rate_limited" | "verify_mint_refused" | "verify_mint_unavailable" | "verify_user_ref_invalid" | "webhook_endpoint_update_empty" | "webhook_endpoint_update_invalid" | "webhook_url_rejected";
23
23
 
24
24
  /** One registry row, reduced to the facts the SDK needs at runtime. */
25
25
  interface ContractErrorRow {