@everfur/sdk 0.1.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +703 -4
- package/README.md +63 -23
- package/consent/package.json +8 -0
- package/dist/Chat-BZZ-Py5l.d.ts +128 -0
- package/dist/Chat-Dq4fffIO.d.cts +128 -0
- package/dist/DepthViews-BG3E25MD.d.ts +16 -0
- package/dist/DepthViews-B_hIypI6.d.cts +19 -0
- package/dist/DepthViews-CL75jyRA.d.cts +16 -0
- package/dist/DepthViews-CkYri51q.d.ts +19 -0
- package/dist/ErrorPolicyPort-CNf4uQZP.d.cts +22 -0
- package/dist/ErrorPolicyPort-CwbfmxzJ.d.ts +22 -0
- package/dist/{EverfurResult-D92-uL82.d.cts → EverfurResult-DN9pL2Ab.d.cts} +11 -10
- package/dist/{EverfurResult-D92-uL82.d.ts → EverfurResult-DN9pL2Ab.d.ts} +11 -10
- package/dist/{PhotoController-BItt5M7u.d.cts → PhotoController-3l7MT9jA.d.cts} +1 -1
- package/dist/{PhotoController-D8zMTdcW.d.ts → PhotoController-vzY5bfY_.d.ts} +1 -1
- package/dist/animations/index.cjs +1 -1997
- package/dist/animations/index.d.cts +35 -35
- package/dist/animations/index.d.ts +35 -35
- package/dist/animations/index.js +1 -1972
- package/dist/attachments-BorG422I.d.cts +146 -0
- package/dist/attachments-BrUWQYNK.d.ts +257 -0
- package/dist/attachments-D_SECjr1.d.cts +257 -0
- package/dist/attachments-DpldrvIW.d.ts +146 -0
- package/dist/bookingCopy-CqtDYvCR.d.ts +732 -0
- package/dist/bookingCopy-SREvkG19.d.cts +732 -0
- package/dist/branding-CsRdeNwK.d.cts +566 -0
- package/dist/branding-CsRdeNwK.d.ts +566 -0
- package/dist/callCopy-DoQKG3-L.d.cts +40 -0
- package/dist/callCopy-DoQKG3-L.d.ts +40 -0
- package/dist/casesRepository-DwtZVsbj.d.cts +51 -0
- package/dist/casesRepository-v6QczS9N.d.ts +51 -0
- package/dist/chat/index.cjs +1 -1170
- package/dist/chat/index.d.cts +32 -53
- package/dist/chat/index.d.ts +32 -53
- package/dist/chat/index.js +1 -1167
- package/dist/client/index.cjs +9 -2315
- package/dist/client/index.d.cts +80 -16
- package/dist/client/index.d.ts +80 -16
- package/dist/client/index.js +9 -2215
- package/dist/{config-CiJ0PVBB.d.ts → config--Wu1Umhd.d.cts} +64 -26
- package/dist/{config-BSjBdxrZ.d.cts → config-C7eb_IMD.d.ts} +64 -26
- package/dist/consent/index.cjs +1 -0
- package/dist/consent/index.d.cts +33 -0
- package/dist/consent/index.d.ts +33 -0
- package/dist/consent/index.js +1 -0
- package/dist/context-CL3lyuy1.d.cts +159 -0
- package/dist/context-CahAEha8.d.ts +159 -0
- package/dist/copy-DdVFDL01.d.ts +198 -0
- package/dist/copy-UeUJVk8X.d.cts +198 -0
- package/dist/core/index.cjs +13 -3178
- package/dist/core/index.d.cts +164 -29
- package/dist/core/index.d.ts +164 -29
- package/dist/core/index.js +13 -3166
- package/dist/depth-D5HwcvKC.d.cts +533 -0
- package/dist/depth-DvPwPuT_.d.ts +533 -0
- package/dist/entitlementRepository-B7egEdW6.d.ts +43 -0
- package/dist/entitlementRepository-BpJ7tiwl.d.cts +43 -0
- package/dist/{identity-Brl-lDd6.d.cts → identity-C2-08BZW.d.cts} +20 -7
- package/dist/{identity-DK9zORrG.d.ts → identity-CEi9GRFZ.d.ts} +20 -7
- package/dist/{ids-CJ1S6adf.d.cts → ids-B2GAAifq.d.cts} +1 -1
- package/dist/{ids-CJ1S6adf.d.ts → ids-B2GAAifq.d.ts} +1 -1
- package/dist/index.cjs +12 -4494
- package/dist/index.d.cts +30 -121
- package/dist/index.d.ts +30 -121
- package/dist/index.js +12 -4470
- package/dist/models-B-Uh2LTf.d.ts +214 -0
- package/dist/models-D2EUxPZY.d.cts +214 -0
- package/dist/notifications/index.cjs +2 -0
- package/dist/notifications/index.d.cts +17 -0
- package/dist/notifications/index.d.ts +17 -0
- package/dist/notifications/index.js +2 -0
- package/dist/optionalModule-DbJmsq5f.d.cts +21 -0
- package/dist/optionalModule-DbJmsq5f.d.ts +21 -0
- package/dist/pets-DJv2sj2H.d.ts +92 -0
- package/dist/pets-JVCXgRgR.d.cts +92 -0
- package/dist/petsRepository-B_gKbAzJ.d.cts +142 -0
- package/dist/petsRepository-Bk6GDwLs.d.ts +142 -0
- package/dist/photo/index.cjs +1 -2189
- package/dist/photo/index.d.cts +6 -6
- package/dist/photo/index.d.ts +6 -6
- package/dist/photo/index.js +1 -2186
- package/dist/ports-BN6RHF9W.d.cts +48 -0
- package/dist/ports-BN6RHF9W.d.ts +48 -0
- package/dist/ports-BY2ph0_y.d.cts +376 -0
- package/dist/ports-D7YW8qz9.d.ts +376 -0
- package/dist/profile-CSs1wlXT.d.cts +93 -0
- package/dist/profile-CSs1wlXT.d.ts +93 -0
- package/dist/records/depth/index.cjs +2 -0
- package/dist/records/depth/index.d.cts +13 -0
- package/dist/records/depth/index.d.ts +13 -0
- package/dist/records/depth/index.js +2 -0
- package/dist/records/index.cjs +3 -2839
- package/dist/records/index.d.cts +137 -203
- package/dist/records/index.d.ts +137 -203
- package/dist/records/index.js +3 -2833
- package/dist/requestFunnel-BjDpqqvm.d.cts +110 -0
- package/dist/requestFunnel-DFMGcluw.d.ts +110 -0
- package/dist/{resolve-Dq_4_agU.d.ts → resolve-D4Ywz5OS.d.cts} +10 -4
- package/dist/{resolve-Dq_4_agU.d.cts → resolve-D4Ywz5OS.d.ts} +10 -4
- package/dist/{runtime-Bvr8yqXm.d.cts → runtimeTypes-gZEJu-da.d.cts} +104 -132
- package/dist/{runtime-BIYzf9cK.d.ts → runtimeTypes-w5KqBMcs.d.ts} +104 -132
- package/dist/server/events/index.cjs +2 -0
- package/dist/server/events/index.d.cts +550 -0
- package/dist/server/events/index.d.ts +550 -0
- package/dist/server/events/index.js +2 -0
- package/dist/server/index.cjs +2 -533
- package/dist/server/index.d.cts +73 -18
- package/dist/server/index.d.ts +73 -18
- package/dist/server/index.js +2 -530
- package/dist/species-BXAIMh7I.d.cts +9 -0
- package/dist/species-BXAIMh7I.d.ts +9 -0
- package/dist/televet/booking/index.cjs +1 -0
- package/dist/televet/booking/index.d.cts +294 -0
- package/dist/televet/booking/index.d.ts +294 -0
- package/dist/televet/booking/index.js +1 -0
- package/dist/televet/call/index.cjs +1 -0
- package/dist/televet/call/index.d.cts +141 -0
- package/dist/televet/call/index.d.ts +141 -0
- package/dist/televet/call/index.js +1 -0
- package/dist/televet/index.cjs +1 -0
- package/dist/televet/index.d.cts +142 -0
- package/dist/televet/index.d.ts +142 -0
- package/dist/televet/index.js +1 -0
- package/dist/testing/index.cjs +5 -823
- package/dist/testing/index.d.cts +18 -4
- package/dist/testing/index.d.ts +18 -4
- package/dist/testing/index.js +5 -820
- package/dist/testing/rn/index.cjs +1 -449
- package/dist/testing/rn/index.d.cts +18 -29
- package/dist/testing/rn/index.d.ts +18 -29
- package/dist/testing/rn/index.js +1 -444
- package/dist/testing/web/index.cjs +1 -0
- package/dist/testing/web/index.d.cts +132 -0
- package/dist/testing/web/index.d.ts +132 -0
- package/dist/testing/web/index.js +1 -0
- package/dist/timelineRows-C15jxFFH.d.ts +19 -0
- package/dist/timelineRows-odO8g9r2.d.cts +19 -0
- package/dist/typeStyle-CKqVYD6L.d.cts +111 -0
- package/dist/typeStyle-DmoyacDG.d.ts +111 -0
- package/dist/uploadTransport-D0M0T4hN.d.ts +38 -0
- package/dist/uploadTransport-DKJHs3Yj.d.cts +38 -0
- package/dist/useRecordsDepth-C6rjEaLn.d.cts +237 -0
- package/dist/useRecordsDepth-crhBllQK.d.ts +237 -0
- package/dist/useVetVisit-Bc84hWUU.d.cts +187 -0
- package/dist/useVetVisit-CjmMa896.d.ts +187 -0
- package/dist/video/index.cjs +1 -1941
- package/dist/video/index.d.cts +4 -4
- package/dist/video/index.d.ts +4 -4
- package/dist/video/index.js +1 -1938
- package/dist/view-Bxwxp4xD.d.ts +310 -0
- package/dist/view-DyitEO0m.d.cts +310 -0
- package/dist/visitIntent-D7_yVp1I.d.cts +8 -0
- package/dist/visitIntent-D7_yVp1I.d.ts +8 -0
- package/dist/web/consent/index.cjs +1 -0
- package/dist/web/consent/index.d.cts +34 -0
- package/dist/web/consent/index.d.ts +34 -0
- package/dist/web/consent/index.js +1 -0
- package/dist/web/index.cjs +14 -0
- package/dist/web/index.d.cts +218 -0
- package/dist/web/index.d.ts +218 -0
- package/dist/web/index.js +14 -0
- package/dist/web/notifications/index.cjs +2 -0
- package/dist/web/notifications/index.d.cts +213 -0
- package/dist/web/notifications/index.d.ts +213 -0
- package/dist/web/notifications/index.js +2 -0
- package/dist/web/records/depth/index.cjs +2 -0
- package/dist/web/records/depth/index.d.cts +12 -0
- package/dist/web/records/depth/index.d.ts +12 -0
- package/dist/web/records/depth/index.js +2 -0
- package/dist/web/records/index.cjs +4 -0
- package/dist/web/records/index.d.cts +285 -0
- package/dist/web/records/index.d.ts +285 -0
- package/dist/web/records/index.js +4 -0
- package/dist/web/televet/booking/index.cjs +1 -0
- package/dist/web/televet/booking/index.d.cts +349 -0
- package/dist/web/televet/booking/index.d.ts +349 -0
- package/dist/web/televet/booking/index.js +1 -0
- package/dist/web/televet/call/index.cjs +1 -0
- package/dist/web/televet/call/index.d.cts +142 -0
- package/dist/web/televet/call/index.d.ts +142 -0
- package/dist/web/televet/call/index.js +1 -0
- package/dist/web/televet/index.cjs +1 -0
- package/dist/web/televet/index.d.cts +136 -0
- package/dist/web/televet/index.d.ts +136 -0
- package/dist/web/televet/index.js +1 -0
- package/notifications/package.json +8 -0
- package/package.json +266 -10
- package/records/depth/package.json +8 -0
- package/server/events/device-blocked.cjs +15 -0
- package/server/events/package.json +9 -0
- package/televet/booking/package.json +8 -0
- package/televet/call/package.json +8 -0
- package/televet/package.json +8 -0
- package/testing/web/native-blocked.cjs +12 -0
- package/testing/web/package.json +8 -0
- package/web/consent/native-blocked.cjs +12 -0
- package/web/consent/package.json +8 -0
- package/web/native-blocked.cjs +12 -0
- package/web/notifications/native-blocked.cjs +12 -0
- package/web/notifications/package.json +8 -0
- package/web/package.json +8 -0
- package/web/records/depth/native-blocked.cjs +12 -0
- package/web/records/depth/package.json +8 -0
- package/web/records/native-blocked.cjs +12 -0
- package/web/records/package.json +8 -0
- package/web/televet/booking/native-blocked.cjs +12 -0
- package/web/televet/booking/package.json +8 -0
- package/web/televet/call/native-blocked.cjs +12 -0
- package/web/televet/call/package.json +8 -0
- package/web/televet/native-blocked.cjs +12 -0
- package/web/televet/package.json +8 -0
- package/dist/ChatController-CKdBvPj2.d.ts +0 -146
- package/dist/ChatController-CpUMvvZf.d.cts +0 -146
- package/dist/FilePort-BabWrv7I.d.cts +0 -22
- package/dist/FilePort-BabWrv7I.d.ts +0 -22
- package/dist/petsRepository-BEGb97M9.d.cts +0 -326
- package/dist/petsRepository-Bu18r2kK.d.ts +0 -326
- package/dist/requestFunnel-DuUH-kAe.d.cts +0 -28
- package/dist/requestFunnel-dio5OmR9.d.ts +0 -28
package/dist/client/index.js
CHANGED
|
@@ -1,2217 +1,11 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
1
|
+
import {z as z$1}from'zod';var ft=Object.defineProperty;var t=(e,r)=>ft(e,"name",{value:r,configurable:true});var Pe=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(Pe.map(e=>e.wireCode));var pt=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"}),Tr=Object.freeze(Pe.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:pt[e.wireCode]}))),yt=new Map(Tr.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),mt=Object.freeze(["http_envelope",...[...new Set(Tr.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function ge(e,r){if(typeof e!="string")return;let n=e.trim().toUpperCase();if(n.length!==0)for(let o of [r??"http_envelope",...mt]){let i=yt.get(o+n);if(i)return i}}t(ge,"contractErrorFor");function gt(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}t(gt,"contractDocUrl");var Cr=null;function kr(e){return null}t(kr,"publishedDocUrl");var Oa=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","unknown"]),Aa=Object.freeze(["authentication","authorization","entitlement","rateLimit","invalidRequest","notFound","conflict","connection","server","media","policy","unknown"]),bt=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"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 Sr(e){return bt[e]}t(Sr,"categoryFor");function X(e){let r=ge(e);if(r)return r.normalized;let n=(e??"").trim().toUpperCase(),o=n.replace(/[^A-Z0-9]/g,"");if(o==="AUTHREJECTED")return "authRejected";if(n.startsWith("AUTH"))return "authExpired";switch(o){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";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"}}t(X,"fromWire");function Fr(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}t(Fr,"fromHttpStatus");var ht=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function z(e){return ht.has(e)}t(z,"isAutoRetryable");var Et=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function xr(e){return z(e)||Et.has(e)}t(xr,"isRetryableCode");function Ia(e,r=false){return r||z(e)}t(Ia,"shouldRetry");var vt=500,De=8e3,wr=4;function Or(e,r=Math.random){let n=Math.max(0,e),o=Math.min(vt*2**n,De);return Math.floor(r()*o)}t(Or,"backoffDelayMs");function Pa(e){return e==="conversationNotFound"}t(Pa,"canRecreateOnNotFound");var _t=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:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function Me(e){return _t[e]}t(Me,"userFacingError");function Ar(e,r,n){Object.defineProperty(e,r,{value:n,enumerable:false,writable:false,configurable:false});}t(Ar,"defineHidden");var Rt=/^[a-z][a-z0-9_]{0,63}$/;function C(e,r){let n=ge(r?.wireCode,r?.wireEnvelope),o={code:e,category:Sr(e),retryable:r?.retryable??xr(e),displayMessage:Me(e)};if(r?.httpStatus!==void 0&&(o.httpStatus=r.httpStatus),r?.requestId&&(o.requestId=r.requestId),typeof r?.reasonCode=="string"&&Rt.test(r.reasonCode)&&(o.reasonCode=r.reasonCode),n);return r?.wireMessage&&Ar(o,"wireMessage",r.wireMessage),r?.raw!==void 0&&r.raw!==null&&Ar(o,"raw",r.raw),Object.freeze(o)}t(C,"makeEverfurError");function k(e,r){return Object.freeze(r===void 0?{ok:true,value:e}:{ok:true,value:e,warning:r})}t(k,"ok");function y(e){return Object.freeze({ok:false,error:e})}t(y,"err");function ja(e){return e.ok}t(ja,"isOk");function Ua(e){return !e.ok}t(Ua,"isErr");var be=class be extends Error{constructor(r){super(`${r.code}: ${r.displayMessage}`),this.name="EverfurThrownError",this.error=r,this.code=r.code,this.category=r.category,Object.setPrototypeOf(this,be.prototype);}};t(be,"EverfurThrownError");var Le=be;function qa(e){if(e.ok)return e.value;throw new Le(e.error)}t(qa,"unwrap");var he=class he extends Error{constructor(r,n){super(n),this.name="EverfurConfigError",this.kind=r,Object.setPrototypeOf(this,he.prototype);}};t(he,"EverfurConfigError");var E=he;var Ct="0.4.0",Tt="react-native",kt="2026-09-19",Ir="EVERFUR_API_BASE_URL";function ne(e,r){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:r})})}t(ne,"configFailure");function St(e){let r=typeof e=="string"?e.trim():"";return r.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(r)?{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}t(St,"checkPublishableKey");function Ft(e,r){let n=St(e?.publishableKey);if(n!==null)return Object.freeze({ok:false,failure:n});let o=e.publishableKey.trim(),i=Pr(e.apiBaseUrl);if(!i.ok)return i;let a=e.contractVersion?.trim()||kt;return Object.freeze({ok:true,config:Object.freeze({publishableKey:o,apiBaseUrl:i.value,contractVersion:a,sdkVersion:Ct,platform:r?.platform??Tt,debug:e.debug===true})})}t(Ft,"tryResolveClientConfig");function Wa(e,r){let n=Ft(e,r);if(!n.ok)throw new E("invalid-argument",n.failure.message);return n.config}t(Wa,"resolveClientConfig");function Pr(e){let r=e?.trim(),n=r&&r.length>0?r:Mt(Ir);return n?Pt(n):ne("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Ir}. The SDK never ships a hardcoded host.`)}t(Pr,"tryResolveApiBaseUrl");function Ga(e){let r=Pr(e);if(!r.ok)throw new E("invalid-argument",r.failure.message);return r.value}t(Ga,"resolveApiBaseUrl");function Dr(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}t(Dr,"buildBaseHeaders");var xt=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function wt(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}t(wt,"hostOf");function Ot(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}t(Ot,"isPrintableHost");function At(e,r){let n=e.indexOf("://");return n<0||e.slice(n+3).includes("@")?false:Ot(r)}t(At,"canEchoOrigin");function It(e,r){return `${e}://${r}`}t(It,"safeOrigin");function Pt(e){let r=e.trim(),n=xt.exec(r);if(n===null||n[2]===void 0||n[2].length===0)return ne("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let o=(n[1]??"").toLowerCase(),i=wt(n[2]);if(i.length===0)return ne("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let a=At(r,i)?`: ${It(o,i)}`:"";if(o!=="https"){if(!(o==="http"&&Dt(i)))return o==="http"?ne("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${a}`):ne("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${a}`)}let s=r.endsWith("/")?r.slice(0,-1):r;return Object.freeze({ok:true,value:s})}t(Pt,"normalizeBaseUrl");function Dt(e){let r=e.toLowerCase();return r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r==="::1"}t(Dt,"isLoopbackHost");function Mt(e){let n=globalThis.process?.env?.[e];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}t(Mt,"readEnv");function Q(e){for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let o=e.charCodeAt(r+1);if(!(o>=56320&&o<=57343))return true;r+=1;}else if(n>=56320&&n<=57343)return true}return false}t(Q,"hasLoneSurrogate");function B(e){return [...e].length}t(B,"serverLength");var Mr=128,Lr=128,Nr=/[\u0000-\u001F\u007F]/,Lt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function es(e){let r=e,n=B(r);if(n===0||n>Lr)throw new E("invalid-argument",`petRef must be 1..${Lr} characters`);if(Nr.test(r))throw new E("invalid-argument","petRef must be printable (no control characters)");return r}t(es,"petRef");function rs(e){let r=e,n=B(r);if(n===0||n>Mr)throw new E("invalid-argument",`userRef must be 1..${Mr} characters`);if(r.includes("@"))throw new E("invalid-argument","userRef must not contain '@'");if(Nr.test(r))throw new E("invalid-argument","userRef must be printable (no control characters)");return r}t(rs,"userRef");function ns(e){if(!Lt.test(e))throw new E("invalid-argument","conversationId must be a UUID");return e}t(ns,"conversationId");function ts(e){return e}t(ts,"unsafePetRef");function os(e){return e}t(os,"unsafeUserRef");function is(e){return e}t(is,"unsafeConversationId");function as(e){return e}t(as,"unsafeResponseId");function ss(e){return e}t(ss,"unsafeClientId");function ls(e){return e}t(ls,"unsafeDocumentId");function us(e){return e}t(us,"unsafeJobId");function ds(e){return e}t(ds,"unsafeRecordsRequestId");function ms(e,r,n){let o=null,i=null,a=false,s=t(()=>i||(i=(async()=>{try{let l=await r(),u=typeof l=="string"?l:l?.token;if(typeof u!="string"||u.length===0)throw new E("invalid-argument","TokenProvider returned an empty token");return o=u,n?.(typeof l=="string"?null:Nt(l.expiresAt)),u}finally{i=null;}})(),i),"load");return {userRef:e,async currentToken(l){if(a)throw new E("not-initialized","This identity was cleared (sign-out); mint a new one.");return l?.forceRefresh&&(o=null),o!==null?o:s()},hasToken(){return !a&&o!==null},clear(){a=true,o=null;}}}t(ms,"createIdentityProvider");function Nt(e){if(e===void 0)return null;let r=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(r)?r:null}t(Nt,"expiryMs");function gs(){let e=new Uint8Array(16),r=globalThis.crypto;if(typeof r?.getRandomValues=="function")r.getRandomValues(e);else for(let o=0;o<e.length;o+=1)e[o]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=[];for(let o=0;o<e.length;o+=1)n.push(e[o].toString(16).padStart(2,"0"));return n.slice(0,4).join("")+"-"+n.slice(4,6).join("")+"-"+n.slice(6,8).join("")+"-"+n.slice(8,10).join("")+"-"+n.slice(10,16).join("")}t(gs,"newSessionId");function zt(e){let r={};return e.mode==="personalized"?r.authorization=`Bearer ${e.token}`:r["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(r["x-everfur-user-ref"]=e.userRef),e.sessionId&&(r["x-everfur-session-id"]=e.sessionId),r}t(zt,"authHeaders");function te(e,r){return {...e,headers:{...Bt(e.headers),...zt(r)}}}t(te,"withAuthHeaders");function Bt(e){if(!e)return {};let r={};for(let[n,o]of Object.entries(e)){let i=n.toLowerCase();i==="authorization"||i==="x-everfur-partner-key"||(r[n]=o);}return r}t(Bt,"stripAuthHeaders");async function zr(e,r){if(r.mode==="anonymous")return r.transport.request(te(e,{mode:"anonymous",publishableKey:r.publishableKey,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));let n;try{n=await r.identity.currentToken();}catch{return y(Ne())}let o=await r.transport.request(te(e,{mode:"personalized",token:n,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));if(o.ok||o.error.httpStatus!==401)return o;let i;try{i=await r.identity.currentToken({forceRefresh:!0});}catch{return y(Ne())}let a=await r.transport.request(te(e,{mode:"personalized",token:i,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));return !a.ok&&a.error.httpStatus===401?y(Ne(a.error.httpStatus)):a}t(zr,"authedSend");function Ne(e){return C("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}t(Ne,"authRejectedError");function Es(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}t(Es,"assertNever");var jt=Object.freeze([]),Ut=Object.freeze([]);function Br(e,r,n=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:r,serverRequestId:n,terminal:false})}t(Br,"acceptedFrame");function jr(e,r=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:r,terminal:false})}t(jr,"heartbeatFrame");function Ur(e,r,n=null){return Object.freeze({kind:"delta",delta:e,lastEventId:r,serverRequestId:n,terminal:false})}t(Ur,"deltaFrame");function qr(e,r=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:r})}t(qr,"doneFrame");function D(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}t(D,"errorFrame");function Hr(e,r,n=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:r,serverRequestId:n,terminal:false})}t(Hr,"analysisStartedFrame");function Kr(e,r=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:r})}t(Kr,"analysisCompleteFrame");function $r(e,r,n=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:r,serverRequestId:n,terminal:false})}t($r,"unknownFrame");var vs=Object.freeze({strings:jt,maps:Ut});var Wr=`
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
Object.freeze({ wireCode: "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST", envelope: "http_envelope", httpStatus: 409, retryable: false }),
|
|
11
|
-
Object.freeze({ wireCode: "InternalFailureException", envelope: "http_envelope", httpStatus: 500, retryable: true }),
|
|
12
|
-
Object.freeze({ wireCode: "NotImplementedException", envelope: "http_envelope", httpStatus: 501, retryable: false }),
|
|
13
|
-
Object.freeze({ wireCode: "PaymentRequiredException", envelope: "http_envelope", httpStatus: 402, retryable: false }),
|
|
14
|
-
Object.freeze({ wireCode: "ResourceNotFoundException", envelope: "http_envelope", httpStatus: 404, retryable: false }),
|
|
15
|
-
Object.freeze({ wireCode: "ServiceUnavailableException", envelope: "http_envelope", httpStatus: 503, retryable: true }),
|
|
16
|
-
Object.freeze({ wireCode: "TIER_UPGRADE_REQUIRED", envelope: "http_envelope", httpStatus: 402, retryable: false }),
|
|
17
|
-
Object.freeze({ wireCode: "ThrottlingException", envelope: "http_envelope", httpStatus: 429, retryable: true }),
|
|
18
|
-
Object.freeze({ wireCode: "ValidationException", envelope: "http_envelope", httpStatus: 400, retryable: false }),
|
|
19
|
-
Object.freeze({ wireCode: "accessDenied", envelope: "http_envelope", httpStatus: 403, retryable: false }),
|
|
20
|
-
Object.freeze({ wireCode: "authExpired", envelope: "http_envelope", httpStatus: 401, retryable: true }),
|
|
21
|
-
Object.freeze({ wireCode: "internal_error", envelope: "sse_frame", httpStatus: 200, retryable: false }),
|
|
22
|
-
Object.freeze({ wireCode: "invalidRequest", envelope: "http_envelope", httpStatus: 400, retryable: false }),
|
|
23
|
-
Object.freeze({ wireCode: "not_found", envelope: "sse_frame", httpStatus: 200, retryable: false }),
|
|
24
|
-
Object.freeze({ wireCode: "session_required", envelope: "http_envelope", httpStatus: 403, retryable: false }),
|
|
25
|
-
Object.freeze({ wireCode: "timeout", envelope: "sse_frame", httpStatus: 200, retryable: true }),
|
|
26
|
-
Object.freeze({ wireCode: "unavailable", envelope: "http_envelope", httpStatus: 503, retryable: true })
|
|
27
|
-
]);
|
|
28
|
-
Object.freeze(
|
|
29
|
-
CONTRACT_RETRYABILITY.map((row) => row.wireCode)
|
|
30
|
-
);
|
|
3
|
+
`,qt=1048576,Ht=z$1.record(z$1.string(),z$1.unknown()),Kt=["emergency","schedule_soon","home_care"];async function*Ee(e,r=null){let n=null,o=t(()=>(n!==null||(n=typeof r=="function"?r():r),n),"requestIdNow"),i=new TextDecoder("utf-8"),a="",s=0,l=false;for await(let u of e){for(a+=i.decode(u,{stream:true});;){let d=a.indexOf(Wr,s);if(d===-1)break;let f=a.slice(0,d);a=a.slice(d+Wr.length),s=0;let c=Gr(f,o());if(c!==null&&(c.kind==="delta"&&(l=true),yield c,c.terminal))return}if(s=a.length>0?a.length-1:0,a.length>qt){yield D({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:o()});return}}if(a+=i.decode(),a.trim().length>0){let u=Gr(a,o());if(u!==null&&(u.kind==="delta"&&(l=true),yield u,u.terminal))return}yield D({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:o()});}t(Ee,"parseSse");function Gr(e,r){let n=null,o=[];for(let s of e.split(`
|
|
4
|
+
`)){let l=s.replace(/\s+$/,"");l.length===0||l.startsWith(":")||(l.startsWith("id:")?n=l.slice(3).trim():l.startsWith("data:")&&o.push(l.slice(5).replace(/^ /,"")));}if(o.length===0)return null;let i;try{i=JSON.parse(o.join(`
|
|
5
|
+
`));}catch{return null}if(typeof i!="object"||i===null||Array.isArray(i))return null;let a=Ht.safeParse(i);return a.success?$t(a.data,n,r):null}t(Gr,"parseBlock");function $t(e,r,n){let o=e.type,i=e.event;if(o==="error"||"error"in e)return D({code:v(e.code)??"unknown",retryable:e.retryable===true,wireMessage:v(e.error),synthesized:false,lastEventId:r,serverRequestId:n});if(o==="done"||e.done===true)return qr({conversationId:v(e.conversation_id)??"",messageId:v(e.message_id),title:v(e.title),followUpQuestions:Yt(e.follow_up_questions),citations:Yr(e.citations),citationStatus:v(e.citation_status),urgencyLevel:Vr(e.urgency_level),urgencyReason:v(e.urgency_reason),urgencyProvided:Gt(e),resultId:v(e.result_id),lastEventId:r},n);if(o==="accepted"||e.status==="reasoning")return Br(v(e.stream_id),r,n);if(o==="heartbeat"||e.heartbeat===true)return jr(r,n);if(o==="text.delta"||"delta"in e||"token"in e){let a=v(e.delta)??v(e.token)??"";return Ur(a,r,n)}return i==="analysis_started"?Hr(v(e.request_id),r,n):i==="analysis_complete"?Kr({resultId:v(e.result_id),analysisType:v(e.analysis_type),modelVersion:v(e.model_version),confidence:Wt(e.confidence),detections:Yr(e.detections),interpretation:v(e.interpretation),lastEventId:r},n):$r(e,r,n)}t($t,"frameFromWire");function v(e){return typeof e=="string"?e:null}t(v,"asString");function Wt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}t(Wt,"asNumber");function Vr(e){return typeof e=="string"&&Kt.includes(e)?e:null}t(Vr,"asUrgency");function Gt(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let r=e.urgency_level;return r===null||Vr(r)!==null}t(Gt,"urgencySlotProvided");function Yt(e){return Array.isArray(e)?e.map(r=>typeof r=="string"?r:String(r)):[]}t(Yt,"asStringList");function Vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}t(Vt,"isPlainObject");function Yr(e){return Array.isArray(e)?e.filter(Vt):[]}t(Yr,"asMapList");var Xt=3e4,Jr="x-request-id";async function*Be(e){if(!e)return;let r=e.getReader();try{for(;;){let{done:n,value:o}=await r.read();if(n)break;o&&o.length>0&&(yield o);}}finally{await r.cancel?.();}}t(Be,"fetchByteSource");async function*Ds(e,r=[]){let n=new TextEncoder().encode(e),o=[...new Set(r)].filter(a=>a>0&&a<n.length).sort((a,s)=>a-s),i=0;for(let a of o)yield n.subarray(i,a),i=a;yield n.subarray(i);}t(Ds,"bufferedTextByteSource");function Qt(e){let r=new TextEncoder,n=Zt(),o=false,i=t(u=>{let d="";u.lastEventId&&(d+=`id: ${u.lastEventId}
|
|
6
|
+
`);let f=u.data??"";for(let c of f.split(`
|
|
7
|
+
`))d+=`data: ${c}
|
|
8
|
+
`;d+=`
|
|
9
|
+
`,n.push(r.encode(d));},"onMessage"),a=t(()=>{l(),n.end();},"onDone"),s=t(u=>{let d=typeof u.xhrStatus=="number"?u.xhrStatus:0;if(d>=400){let f=en(d),c=z(X(f));n.push(r.encode(`data: ${JSON.stringify({type:"error",code:f,retryable:c})}
|
|
31
10
|
|
|
32
|
-
// src/client/errors/contract.ts
|
|
33
|
-
var NORMALIZED_FOLD = Object.freeze({
|
|
34
|
-
// the default status-mapped envelope
|
|
35
|
-
ValidationException: "validationFailed",
|
|
36
|
-
AuthorizationException: "authRejected",
|
|
37
|
-
PaymentRequiredException: "paymentRequired",
|
|
38
|
-
AccessDeniedException: "accessDenied",
|
|
39
|
-
ResourceNotFoundException: "resourceNotFound",
|
|
40
|
-
ConflictException: "conflict",
|
|
41
|
-
ThrottlingException: "rateLimited",
|
|
42
|
-
InternalFailureException: "internalError",
|
|
43
|
-
NotImplementedException: "notImplemented",
|
|
44
|
-
ServiceUnavailableException: "serviceUnavailable",
|
|
45
|
-
// dict-detail codes on the widget surface
|
|
46
|
-
authExpired: "authExpired",
|
|
47
|
-
unavailable: "serviceUnavailable",
|
|
48
|
-
session_required: "sessionRequired",
|
|
49
|
-
accessDenied: "accessDenied",
|
|
50
|
-
invalidRequest: "sdkUpdateRequired",
|
|
51
|
-
// typed codes
|
|
52
|
-
IDEMPOTENCY_KEY_IN_FLIGHT: "idempotencyInFlight",
|
|
53
|
-
IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST: "idempotencyConflict",
|
|
54
|
-
DAILY_QUOTA_EXCEEDED: "quotaExceeded",
|
|
55
|
-
TIER_UPGRADE_REQUIRED: "paymentRequired",
|
|
56
|
-
// SSE error frames
|
|
57
|
-
not_found: "conversationNotFound",
|
|
58
|
-
timeout: "streamTimeout",
|
|
59
|
-
internal_error: "internalError"
|
|
60
|
-
});
|
|
61
|
-
var CONTRACT_ERROR_ROWS = Object.freeze(
|
|
62
|
-
CONTRACT_RETRYABILITY.map(
|
|
63
|
-
(generated) => Object.freeze({
|
|
64
|
-
wireCode: generated.wireCode,
|
|
65
|
-
envelope: generated.envelope,
|
|
66
|
-
retryable: generated.retryable,
|
|
67
|
-
normalized: NORMALIZED_FOLD[generated.wireCode]
|
|
68
|
-
})
|
|
69
|
-
)
|
|
70
|
-
);
|
|
71
|
-
var BY_UPPER = new Map(
|
|
72
|
-
CONTRACT_ERROR_ROWS.map((r) => [r.wireCode.toUpperCase(), r])
|
|
73
|
-
);
|
|
74
|
-
function contractErrorFor(wireCode) {
|
|
75
|
-
if (typeof wireCode !== "string") return void 0;
|
|
76
|
-
const key = wireCode.trim().toUpperCase();
|
|
77
|
-
return key.length > 0 ? BY_UPPER.get(key) : void 0;
|
|
78
|
-
}
|
|
79
|
-
function contractDocUrl(entry) {
|
|
80
|
-
return entry.envelope === "sse_frame" ? `/errors#sse-${entry.wireCode}` : `/errors#${entry.wireCode}`;
|
|
81
|
-
}
|
|
82
|
-
var DOC_SITE_ORIGIN = null;
|
|
83
|
-
function publishedDocUrl(entry) {
|
|
84
|
-
return null ;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// src/client/errors/codes.ts
|
|
88
|
-
var EVERFUR_ERROR_CODES = Object.freeze([
|
|
89
|
-
"authExpired",
|
|
90
|
-
"authRejected",
|
|
91
|
-
"sessionRequired",
|
|
92
|
-
"accessDenied",
|
|
93
|
-
"paymentRequired",
|
|
94
|
-
"quotaExceeded",
|
|
95
|
-
"rateLimited",
|
|
96
|
-
"validationFailed",
|
|
97
|
-
"sdkUpdateRequired",
|
|
98
|
-
"conflict",
|
|
99
|
-
"idempotencyConflict",
|
|
100
|
-
"idempotencyInFlight",
|
|
101
|
-
"conversationNotFound",
|
|
102
|
-
"petNotFound",
|
|
103
|
-
"resourceNotFound",
|
|
104
|
-
"streamTimeout",
|
|
105
|
-
"mediaUploadFailed",
|
|
106
|
-
"moderationBlocked",
|
|
107
|
-
"upstreamLlmTimeout",
|
|
108
|
-
"internalError",
|
|
109
|
-
"notImplemented",
|
|
110
|
-
"serviceUnavailable",
|
|
111
|
-
"streamIncomplete",
|
|
112
|
-
"unknown"
|
|
113
|
-
]);
|
|
114
|
-
var EVERFUR_ERROR_CATEGORIES = Object.freeze([
|
|
115
|
-
"authentication",
|
|
116
|
-
"authorization",
|
|
117
|
-
"entitlement",
|
|
118
|
-
"rateLimit",
|
|
119
|
-
"invalidRequest",
|
|
120
|
-
"notFound",
|
|
121
|
-
"conflict",
|
|
122
|
-
"connection",
|
|
123
|
-
"server",
|
|
124
|
-
"media",
|
|
125
|
-
"policy",
|
|
126
|
-
"unknown"
|
|
127
|
-
]);
|
|
128
|
-
var CATEGORY_OF = Object.freeze({
|
|
129
|
-
// the caller's sign-in state is wrong and a credential change is the remedy
|
|
130
|
-
authExpired: "authentication",
|
|
131
|
-
authRejected: "authentication",
|
|
132
|
-
sessionRequired: "authentication",
|
|
133
|
-
// signed in, correctly identified, and still not allowed
|
|
134
|
-
accessDenied: "authorization",
|
|
135
|
-
// a plan gate, not a permission failure: the remedy is commercial
|
|
136
|
-
paymentRequired: "entitlement",
|
|
137
|
-
// slow down / come back later
|
|
138
|
-
quotaExceeded: "rateLimit",
|
|
139
|
-
rateLimited: "rateLimit",
|
|
140
|
-
// the request itself was wrong; retrying it unchanged can never succeed
|
|
141
|
-
validationFailed: "invalidRequest",
|
|
142
|
-
sdkUpdateRequired: "invalidRequest",
|
|
143
|
-
// the target is gone, hidden, or was never visible to this caller
|
|
144
|
-
conversationNotFound: "notFound",
|
|
145
|
-
petNotFound: "notFound",
|
|
146
|
-
resourceNotFound: "notFound",
|
|
147
|
-
// something else already holds the thing
|
|
148
|
-
conflict: "conflict",
|
|
149
|
-
idempotencyConflict: "conflict",
|
|
150
|
-
idempotencyInFlight: "conflict",
|
|
151
|
-
// the pipe, not the request: timeouts, drops, a briefly unreachable dependency
|
|
152
|
-
streamTimeout: "connection",
|
|
153
|
-
streamIncomplete: "connection",
|
|
154
|
-
upstreamLlmTimeout: "connection",
|
|
155
|
-
serviceUnavailable: "connection",
|
|
156
|
-
// the server admits fault
|
|
157
|
-
internalError: "server",
|
|
158
|
-
notImplemented: "server",
|
|
159
|
-
mediaUploadFailed: "media",
|
|
160
|
-
moderationBlocked: "policy",
|
|
161
|
-
unknown: "unknown"
|
|
162
|
-
});
|
|
163
|
-
function categoryFor(code) {
|
|
164
|
-
return CATEGORY_OF[code];
|
|
165
|
-
}
|
|
166
|
-
function fromWire(wire) {
|
|
167
|
-
const contractRow = contractErrorFor(wire);
|
|
168
|
-
if (contractRow) return contractRow.normalized;
|
|
169
|
-
const upper = (wire ?? "").trim().toUpperCase();
|
|
170
|
-
const canonical = upper.replace(/[^A-Z0-9]/g, "");
|
|
171
|
-
if (canonical === "AUTHREJECTED") return "authRejected";
|
|
172
|
-
if (upper.startsWith("AUTH")) return "authExpired";
|
|
173
|
-
switch (canonical) {
|
|
174
|
-
case "DAILYQUOTAEXCEEDED":
|
|
175
|
-
case "QUOTAEXCEEDED":
|
|
176
|
-
return "quotaExceeded";
|
|
177
|
-
case "RATELIMITED":
|
|
178
|
-
case "TOOMANYREQUESTS":
|
|
179
|
-
return "rateLimited";
|
|
180
|
-
case "IDEMPOTENCYKEYCONFLICT":
|
|
181
|
-
case "IDEMPOTENCYCONFLICT":
|
|
182
|
-
return "idempotencyConflict";
|
|
183
|
-
case "ACCESSDENIED":
|
|
184
|
-
case "FORBIDDEN":
|
|
185
|
-
return "accessDenied";
|
|
186
|
-
case "NOTFOUND":
|
|
187
|
-
case "CONVERSATIONNOTFOUND":
|
|
188
|
-
return "conversationNotFound";
|
|
189
|
-
case "PETNOTFOUND":
|
|
190
|
-
return "petNotFound";
|
|
191
|
-
case "TIMEOUT":
|
|
192
|
-
case "STREAMTIMEOUT":
|
|
193
|
-
return "streamTimeout";
|
|
194
|
-
// Analysis-domain deterministic 400s (NON-retryable). Additive per SPEC-00 §3.1 / SPEC-11b §2.6:
|
|
195
|
-
// fold to a NON-retried target so the SDK never retries a permanently-failing bad-input request.
|
|
196
|
-
// (Comment above the group so the empty fall-through cases stay lint-clean under no-fallthrough.)
|
|
197
|
-
case "MEDIAUPLOADFAILED":
|
|
198
|
-
case "UNRECOGNIZEDVIDEOFORMAT":
|
|
199
|
-
case "FILETOOSMALL":
|
|
200
|
-
return "mediaUploadFailed";
|
|
201
|
-
case "MODERATIONBLOCKED":
|
|
202
|
-
return "moderationBlocked";
|
|
203
|
-
case "UPSTREAMLLMTIMEOUT":
|
|
204
|
-
return "upstreamLlmTimeout";
|
|
205
|
-
case "INTERNALERROR":
|
|
206
|
-
case "INTERNALSERVERERROR":
|
|
207
|
-
return "internalError";
|
|
208
|
-
case "STREAMINCOMPLETE":
|
|
209
|
-
case "CHATSTREAMINCOMPLETE":
|
|
210
|
-
return "streamIncomplete";
|
|
211
|
-
// Deterministic 400s that can only come from an SDK bug -> unknown (NON-retryable). NEVER internalError
|
|
212
|
-
// (which IS auto-retried): mapping a bad-input 400 to a retryable code retries a request that never succeeds.
|
|
213
|
-
case "INVALIDANALYSISTYPE":
|
|
214
|
-
case "INVALIDUPLOADPURPOSE":
|
|
215
|
-
return "unknown";
|
|
216
|
-
default:
|
|
217
|
-
return "unknown";
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
function fromHttpStatus(status) {
|
|
221
|
-
if (status === 401) return "authExpired";
|
|
222
|
-
if (status === 403) return "accessDenied";
|
|
223
|
-
if (status === 404) return "conversationNotFound";
|
|
224
|
-
if (status === 409) return "idempotencyConflict";
|
|
225
|
-
if (status === 421) return "unknown";
|
|
226
|
-
if (status === 429) return "rateLimited";
|
|
227
|
-
if (status === 400 || status === 422) return "unknown";
|
|
228
|
-
if (status >= 500) return "internalError";
|
|
229
|
-
return "unknown";
|
|
230
|
-
}
|
|
231
|
-
var AUTO_RETRYABLE_CODES = /* @__PURE__ */ new Set([
|
|
232
|
-
"streamTimeout",
|
|
233
|
-
"rateLimited",
|
|
234
|
-
"internalError",
|
|
235
|
-
"upstreamLlmTimeout",
|
|
236
|
-
"streamIncomplete"
|
|
237
|
-
]);
|
|
238
|
-
function isAutoRetryable(code) {
|
|
239
|
-
return AUTO_RETRYABLE_CODES.has(code);
|
|
240
|
-
}
|
|
241
|
-
var RETRYABLE_CONTRACT_CODES = /* @__PURE__ */ new Set([
|
|
242
|
-
"serviceUnavailable",
|
|
243
|
-
"conflict",
|
|
244
|
-
"idempotencyInFlight"
|
|
245
|
-
]);
|
|
246
|
-
function isRetryableCode(code) {
|
|
247
|
-
return isAutoRetryable(code) || RETRYABLE_CONTRACT_CODES.has(code);
|
|
248
|
-
}
|
|
249
|
-
function shouldRetry(code, frameRetryable = false) {
|
|
250
|
-
return frameRetryable || isAutoRetryable(code);
|
|
251
|
-
}
|
|
252
|
-
var BACKOFF_BASE_MS = 500;
|
|
253
|
-
var BACKOFF_CAP_MS = 8e3;
|
|
254
|
-
var MAX_RETRY_ATTEMPTS = 4;
|
|
255
|
-
function backoffDelayMs(attempt, rng = Math.random) {
|
|
256
|
-
const bounded = Math.max(0, attempt);
|
|
257
|
-
const ceiling = Math.min(BACKOFF_BASE_MS * 2 ** bounded, BACKOFF_CAP_MS);
|
|
258
|
-
return Math.floor(rng() * ceiling);
|
|
259
|
-
}
|
|
260
|
-
function canRecreateOnNotFound(code) {
|
|
261
|
-
return code === "conversationNotFound";
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
// src/client/errors/EverfurError.ts
|
|
265
|
-
var USER_FACING_COPY = Object.freeze({
|
|
266
|
-
authExpired: "Please sign in again to continue.",
|
|
267
|
-
authRejected: "Please sign in again to continue.",
|
|
268
|
-
sessionRequired: "This app needs to be updated to keep using Everfur.",
|
|
269
|
-
accessDenied: "This feature isn't available on your account right now.",
|
|
270
|
-
paymentRequired: "This is part of a paid plan.",
|
|
271
|
-
quotaExceeded: "You have used today's messages. This resets tomorrow.",
|
|
272
|
-
rateLimited: "You are sending messages quickly. Try again in a few seconds.",
|
|
273
|
-
validationFailed: "Something in that request was not right. Check the details and try again.",
|
|
274
|
-
sdkUpdateRequired: "This app needs to be updated to keep using Everfur.",
|
|
275
|
-
conflict: "That is already running. Wait for it to finish, then try again.",
|
|
276
|
-
idempotencyConflict: "That message was already delivered.",
|
|
277
|
-
idempotencyInFlight: "That is still processing. Give it a moment.",
|
|
278
|
-
conversationNotFound: "This conversation is no longer available.",
|
|
279
|
-
petNotFound: "We could not find that pet. Please pick a pet and try again.",
|
|
280
|
-
resourceNotFound: "We could not find that.",
|
|
281
|
-
streamTimeout: "The response timed out. Tap retry to try again.",
|
|
282
|
-
mediaUploadFailed: "We could not upload that photo. Please attach it again.",
|
|
283
|
-
moderationBlocked: "This request cannot be answered here.",
|
|
284
|
-
upstreamLlmTimeout: "The response timed out. Tap retry to try again.",
|
|
285
|
-
internalError: "We hit a snag on our end. Please try again.",
|
|
286
|
-
notImplemented: "That is not available yet.",
|
|
287
|
-
serviceUnavailable: "That service is briefly unavailable. Try again shortly.",
|
|
288
|
-
streamIncomplete: "The connection dropped mid-answer. Tap retry to continue.",
|
|
289
|
-
unknown: "Something went wrong. Please try again."
|
|
290
|
-
});
|
|
291
|
-
function userFacingError(code) {
|
|
292
|
-
return USER_FACING_COPY[code];
|
|
293
|
-
}
|
|
294
|
-
function defineHidden(target, key, value) {
|
|
295
|
-
Object.defineProperty(target, key, {
|
|
296
|
-
value,
|
|
297
|
-
enumerable: false,
|
|
298
|
-
writable: false,
|
|
299
|
-
configurable: false
|
|
300
|
-
});
|
|
301
|
-
}
|
|
302
|
-
function makeEverfurError(code, opts) {
|
|
303
|
-
contractErrorFor(opts?.wireCode);
|
|
304
|
-
const error = {
|
|
305
|
-
code,
|
|
306
|
-
category: categoryFor(code),
|
|
307
|
-
retryable: opts?.retryable ?? isRetryableCode(code),
|
|
308
|
-
displayMessage: userFacingError(code)
|
|
309
|
-
};
|
|
310
|
-
if (opts?.httpStatus !== void 0) error.httpStatus = opts.httpStatus;
|
|
311
|
-
if (opts?.requestId) error.requestId = opts.requestId;
|
|
312
|
-
if (opts?.wireMessage) defineHidden(error, "wireMessage", opts.wireMessage);
|
|
313
|
-
if (opts?.raw !== void 0 && opts.raw !== null) defineHidden(error, "raw", opts.raw);
|
|
314
|
-
return Object.freeze(error);
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
// src/client/errors/EverfurResult.ts
|
|
318
|
-
function ok(value, warning) {
|
|
319
|
-
return Object.freeze(
|
|
320
|
-
warning === void 0 ? { ok: true, value } : { ok: true, value, warning }
|
|
321
|
-
);
|
|
322
|
-
}
|
|
323
|
-
function err(error) {
|
|
324
|
-
return Object.freeze({ ok: false, error });
|
|
325
|
-
}
|
|
326
|
-
function isOk(r) {
|
|
327
|
-
return r.ok;
|
|
328
|
-
}
|
|
329
|
-
function isErr(r) {
|
|
330
|
-
return !r.ok;
|
|
331
|
-
}
|
|
332
|
-
var EverfurThrownError = class _EverfurThrownError extends Error {
|
|
333
|
-
constructor(error) {
|
|
334
|
-
super(`${error.code}: ${error.displayMessage}`);
|
|
335
|
-
this.name = "EverfurThrownError";
|
|
336
|
-
this.error = error;
|
|
337
|
-
this.code = error.code;
|
|
338
|
-
this.category = error.category;
|
|
339
|
-
Object.setPrototypeOf(this, _EverfurThrownError.prototype);
|
|
340
|
-
}
|
|
341
|
-
};
|
|
342
|
-
function unwrap(r) {
|
|
343
|
-
if (r.ok) return r.value;
|
|
344
|
-
throw new EverfurThrownError(r.error);
|
|
345
|
-
}
|
|
346
|
-
var EverfurConfigError = class _EverfurConfigError extends Error {
|
|
347
|
-
constructor(kind, message) {
|
|
348
|
-
super(message);
|
|
349
|
-
this.name = "EverfurConfigError";
|
|
350
|
-
this.kind = kind;
|
|
351
|
-
Object.setPrototypeOf(this, _EverfurConfigError.prototype);
|
|
352
|
-
}
|
|
353
|
-
};
|
|
354
|
-
|
|
355
|
-
// src/client/config.ts
|
|
356
|
-
var SDK_VERSION = "0.1.0";
|
|
357
|
-
var SDK_PLATFORM = "react-native";
|
|
358
|
-
var DEFAULT_CONTRACT_VERSION = "2026-08-01";
|
|
359
|
-
var ENV_API_BASE_URL = "EVERFUR_API_BASE_URL";
|
|
360
|
-
function configFailure(reason, message) {
|
|
361
|
-
return Object.freeze({ ok: false, failure: Object.freeze({ reason, message }) });
|
|
362
|
-
}
|
|
363
|
-
function checkPublishableKey(raw) {
|
|
364
|
-
const publishableKey = typeof raw === "string" ? raw.trim() : "";
|
|
365
|
-
if (publishableKey.length === 0) {
|
|
366
|
-
return { reason: "missing-publishable-key", message: "publishableKey is required" };
|
|
367
|
-
}
|
|
368
|
-
if (/^sk[_-]/i.test(publishableKey)) {
|
|
369
|
-
return {
|
|
370
|
-
reason: "secret-key-as-publishable-key",
|
|
371
|
-
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."
|
|
372
|
-
};
|
|
373
|
-
}
|
|
374
|
-
return null;
|
|
375
|
-
}
|
|
376
|
-
function tryResolveClientConfig(config) {
|
|
377
|
-
const keyFailure = checkPublishableKey(config?.publishableKey);
|
|
378
|
-
if (keyFailure !== null) {
|
|
379
|
-
return Object.freeze({ ok: false, failure: keyFailure });
|
|
380
|
-
}
|
|
381
|
-
const publishableKey = config.publishableKey.trim();
|
|
382
|
-
const baseUrl = tryResolveApiBaseUrl(config.apiBaseUrl);
|
|
383
|
-
if (!baseUrl.ok) {
|
|
384
|
-
return baseUrl;
|
|
385
|
-
}
|
|
386
|
-
const contractVersion = config.contractVersion?.trim() || DEFAULT_CONTRACT_VERSION;
|
|
387
|
-
return Object.freeze({
|
|
388
|
-
ok: true,
|
|
389
|
-
config: Object.freeze({
|
|
390
|
-
publishableKey,
|
|
391
|
-
apiBaseUrl: baseUrl.value,
|
|
392
|
-
contractVersion,
|
|
393
|
-
sdkVersion: SDK_VERSION,
|
|
394
|
-
platform: SDK_PLATFORM,
|
|
395
|
-
debug: config.debug === true
|
|
396
|
-
})
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
function resolveClientConfig(config) {
|
|
400
|
-
const outcome = tryResolveClientConfig(config);
|
|
401
|
-
if (!outcome.ok) {
|
|
402
|
-
throw new EverfurConfigError("invalid-argument", outcome.failure.message);
|
|
403
|
-
}
|
|
404
|
-
return outcome.config;
|
|
405
|
-
}
|
|
406
|
-
function tryResolveApiBaseUrl(apiBaseUrl) {
|
|
407
|
-
const explicit = apiBaseUrl?.trim();
|
|
408
|
-
const candidate = explicit && explicit.length > 0 ? explicit : readEnv(ENV_API_BASE_URL);
|
|
409
|
-
if (!candidate) {
|
|
410
|
-
return configFailure(
|
|
411
|
-
"missing-api-base-url",
|
|
412
|
-
`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`
|
|
413
|
-
);
|
|
414
|
-
}
|
|
415
|
-
return normalizeBaseUrl(candidate);
|
|
416
|
-
}
|
|
417
|
-
function resolveApiBaseUrl(apiBaseUrl) {
|
|
418
|
-
const outcome = tryResolveApiBaseUrl(apiBaseUrl);
|
|
419
|
-
if (!outcome.ok) {
|
|
420
|
-
throw new EverfurConfigError("invalid-argument", outcome.failure.message);
|
|
421
|
-
}
|
|
422
|
-
return outcome.value;
|
|
423
|
-
}
|
|
424
|
-
function buildBaseHeaders(cfg) {
|
|
425
|
-
return {
|
|
426
|
-
"X-Everfur-SDK-Version": cfg.sdkVersion,
|
|
427
|
-
"X-Everfur-SDK-Platform": cfg.platform,
|
|
428
|
-
"X-Everfur-Contract": cfg.contractVersion
|
|
429
|
-
};
|
|
430
|
-
}
|
|
431
|
-
var ABSOLUTE_URL = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;
|
|
432
|
-
function hostOf(authority) {
|
|
433
|
-
const afterUserinfo = authority.slice(authority.lastIndexOf("@") + 1);
|
|
434
|
-
return afterUserinfo.replace(/:\d+$/, "").toLowerCase();
|
|
435
|
-
}
|
|
436
|
-
function isPrintableHost(host) {
|
|
437
|
-
if (host.length === 0) return false;
|
|
438
|
-
if (host.includes("@")) return false;
|
|
439
|
-
if (host.startsWith("[") && host.endsWith("]")) return true;
|
|
440
|
-
return !host.includes(":");
|
|
441
|
-
}
|
|
442
|
-
function canEchoOrigin(rawTrimmed, host) {
|
|
443
|
-
const schemeEnd = rawTrimmed.indexOf("://");
|
|
444
|
-
if (schemeEnd < 0) return false;
|
|
445
|
-
if (rawTrimmed.slice(schemeEnd + 3).includes("@")) return false;
|
|
446
|
-
return isPrintableHost(host);
|
|
447
|
-
}
|
|
448
|
-
function safeOrigin(scheme, host) {
|
|
449
|
-
return `${scheme}://${host}`;
|
|
450
|
-
}
|
|
451
|
-
function normalizeBaseUrl(raw) {
|
|
452
|
-
const trimmed = raw.trim();
|
|
453
|
-
const match = ABSOLUTE_URL.exec(trimmed);
|
|
454
|
-
if (match === null || match[2] === void 0 || match[2].length === 0) {
|
|
455
|
-
return configFailure("malformed-api-base-url", "apiBaseUrl is not a valid absolute URL");
|
|
456
|
-
}
|
|
457
|
-
const scheme = (match[1] ?? "").toLowerCase();
|
|
458
|
-
const host = hostOf(match[2]);
|
|
459
|
-
if (host.length === 0) {
|
|
460
|
-
return configFailure("malformed-api-base-url", "apiBaseUrl is not a valid absolute URL");
|
|
461
|
-
}
|
|
462
|
-
const shown = canEchoOrigin(trimmed, host) ? `: ${safeOrigin(scheme, host)}` : "";
|
|
463
|
-
if (scheme === "https") ; else if (scheme === "http" && isLoopbackHost(host)) ; else if (scheme === "http") {
|
|
464
|
-
return configFailure(
|
|
465
|
-
"insecure-api-base-url",
|
|
466
|
-
`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`
|
|
467
|
-
);
|
|
468
|
-
} else {
|
|
469
|
-
return configFailure("unsupported-api-base-url-scheme", `apiBaseUrl must be http(s)${shown}`);
|
|
470
|
-
}
|
|
471
|
-
const value = trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
|
|
472
|
-
return Object.freeze({ ok: true, value });
|
|
473
|
-
}
|
|
474
|
-
function isLoopbackHost(hostname) {
|
|
475
|
-
const host = hostname.toLowerCase();
|
|
476
|
-
return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
|
|
477
|
-
}
|
|
478
|
-
function readEnv(name) {
|
|
479
|
-
const g = globalThis;
|
|
480
|
-
const value = g.process?.env?.[name];
|
|
481
|
-
return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
// src/client/text.ts
|
|
485
|
-
function hasLoneSurrogate(value) {
|
|
486
|
-
for (let i = 0; i < value.length; i += 1) {
|
|
487
|
-
const code = value.charCodeAt(i);
|
|
488
|
-
if (code >= 55296 && code <= 56319) {
|
|
489
|
-
const low = value.charCodeAt(i + 1);
|
|
490
|
-
if (!(low >= 56320 && low <= 57343)) return true;
|
|
491
|
-
i += 1;
|
|
492
|
-
} else if (code >= 56320 && code <= 57343) {
|
|
493
|
-
return true;
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
return false;
|
|
497
|
-
}
|
|
498
|
-
function serverLength(value) {
|
|
499
|
-
return [...value].length;
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
// src/client/ids.ts
|
|
503
|
-
var MAX_USER_REF_LEN = 128;
|
|
504
|
-
var MAX_PET_REF_LEN = 128;
|
|
505
|
-
var CONTROL_CHAR = /[\u0000-\u001F\u007F]/;
|
|
506
|
-
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
507
|
-
function petRef(raw) {
|
|
508
|
-
const v = raw;
|
|
509
|
-
const length = serverLength(v);
|
|
510
|
-
if (length === 0 || length > MAX_PET_REF_LEN) {
|
|
511
|
-
throw new EverfurConfigError(
|
|
512
|
-
"invalid-argument",
|
|
513
|
-
`petRef must be 1..${MAX_PET_REF_LEN} characters`
|
|
514
|
-
);
|
|
515
|
-
}
|
|
516
|
-
if (CONTROL_CHAR.test(v)) {
|
|
517
|
-
throw new EverfurConfigError("invalid-argument", "petRef must be printable (no control characters)");
|
|
518
|
-
}
|
|
519
|
-
return v;
|
|
520
|
-
}
|
|
521
|
-
function userRef(raw) {
|
|
522
|
-
const v = raw;
|
|
523
|
-
const length = serverLength(v);
|
|
524
|
-
if (length === 0 || length > MAX_USER_REF_LEN) {
|
|
525
|
-
throw new EverfurConfigError(
|
|
526
|
-
"invalid-argument",
|
|
527
|
-
`userRef must be 1..${MAX_USER_REF_LEN} characters`
|
|
528
|
-
);
|
|
529
|
-
}
|
|
530
|
-
if (v.includes("@")) {
|
|
531
|
-
throw new EverfurConfigError("invalid-argument", "userRef must not contain '@'");
|
|
532
|
-
}
|
|
533
|
-
if (CONTROL_CHAR.test(v)) {
|
|
534
|
-
throw new EverfurConfigError("invalid-argument", "userRef must be printable (no control characters)");
|
|
535
|
-
}
|
|
536
|
-
return v;
|
|
537
|
-
}
|
|
538
|
-
function conversationId(raw) {
|
|
539
|
-
if (!UUID_RE.test(raw)) {
|
|
540
|
-
throw new EverfurConfigError("invalid-argument", "conversationId must be a UUID");
|
|
541
|
-
}
|
|
542
|
-
return raw;
|
|
543
|
-
}
|
|
544
|
-
function unsafePetRef(raw) {
|
|
545
|
-
return raw;
|
|
546
|
-
}
|
|
547
|
-
function unsafeUserRef(raw) {
|
|
548
|
-
return raw;
|
|
549
|
-
}
|
|
550
|
-
function unsafeConversationId(raw) {
|
|
551
|
-
return raw;
|
|
552
|
-
}
|
|
553
|
-
function unsafeResponseId(raw) {
|
|
554
|
-
return raw;
|
|
555
|
-
}
|
|
556
|
-
function unsafeClientId(raw) {
|
|
557
|
-
return raw;
|
|
558
|
-
}
|
|
559
|
-
function unsafeDocumentId(raw) {
|
|
560
|
-
return raw;
|
|
561
|
-
}
|
|
562
|
-
function unsafeJobId(raw) {
|
|
563
|
-
return raw;
|
|
564
|
-
}
|
|
565
|
-
function unsafeRecordsRequestId(raw) {
|
|
566
|
-
return raw;
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
// src/client/identity.ts
|
|
570
|
-
function createIdentityProvider(userRef2, getToken) {
|
|
571
|
-
let cached = null;
|
|
572
|
-
let inFlight = null;
|
|
573
|
-
let revoked = false;
|
|
574
|
-
const load = () => {
|
|
575
|
-
if (inFlight) return inFlight;
|
|
576
|
-
inFlight = (async () => {
|
|
577
|
-
try {
|
|
578
|
-
const token = await getToken();
|
|
579
|
-
if (typeof token !== "string" || token.length === 0) {
|
|
580
|
-
throw new EverfurConfigError("invalid-argument", "TokenProvider returned an empty token");
|
|
581
|
-
}
|
|
582
|
-
cached = token;
|
|
583
|
-
return token;
|
|
584
|
-
} finally {
|
|
585
|
-
inFlight = null;
|
|
586
|
-
}
|
|
587
|
-
})();
|
|
588
|
-
return inFlight;
|
|
589
|
-
};
|
|
590
|
-
return {
|
|
591
|
-
userRef: userRef2,
|
|
592
|
-
async currentToken(opts) {
|
|
593
|
-
if (revoked) {
|
|
594
|
-
throw new EverfurConfigError("not-initialized", "This identity was cleared (sign-out); mint a new one.");
|
|
595
|
-
}
|
|
596
|
-
if (opts?.forceRefresh) cached = null;
|
|
597
|
-
if (cached !== null) return cached;
|
|
598
|
-
return load();
|
|
599
|
-
},
|
|
600
|
-
hasToken() {
|
|
601
|
-
return !revoked && cached !== null;
|
|
602
|
-
},
|
|
603
|
-
clear() {
|
|
604
|
-
revoked = true;
|
|
605
|
-
cached = null;
|
|
606
|
-
}
|
|
607
|
-
};
|
|
608
|
-
}
|
|
609
|
-
function newSessionId() {
|
|
610
|
-
const bytes = new Uint8Array(16);
|
|
611
|
-
const cryptoObj = globalThis.crypto;
|
|
612
|
-
if (typeof cryptoObj?.getRandomValues === "function") {
|
|
613
|
-
cryptoObj.getRandomValues(bytes);
|
|
614
|
-
} else {
|
|
615
|
-
for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
|
|
616
|
-
}
|
|
617
|
-
bytes[6] = bytes[6] & 15 | 64;
|
|
618
|
-
bytes[8] = bytes[8] & 63 | 128;
|
|
619
|
-
const hex = [];
|
|
620
|
-
for (let i = 0; i < bytes.length; i += 1) hex.push(bytes[i].toString(16).padStart(2, "0"));
|
|
621
|
-
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("");
|
|
622
|
-
}
|
|
623
|
-
function authHeaders(auth) {
|
|
624
|
-
const headers = {};
|
|
625
|
-
if (auth.mode === "personalized") {
|
|
626
|
-
headers.authorization = `Bearer ${auth.token}`;
|
|
627
|
-
} else {
|
|
628
|
-
headers["x-everfur-partner-key"] = auth.publishableKey;
|
|
629
|
-
}
|
|
630
|
-
if (auth.userRef) headers["x-everfur-user-ref"] = auth.userRef;
|
|
631
|
-
if (auth.sessionId) headers["x-everfur-session-id"] = auth.sessionId;
|
|
632
|
-
return headers;
|
|
633
|
-
}
|
|
634
|
-
function withAuthHeaders(req, auth) {
|
|
635
|
-
return { ...req, headers: { ...stripAuthHeaders(req.headers), ...authHeaders(auth) } };
|
|
636
|
-
}
|
|
637
|
-
function stripAuthHeaders(headers) {
|
|
638
|
-
if (!headers) return {};
|
|
639
|
-
const out = {};
|
|
640
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
641
|
-
const lower = key.toLowerCase();
|
|
642
|
-
if (lower === "authorization" || lower === "x-everfur-partner-key") continue;
|
|
643
|
-
out[key] = value;
|
|
644
|
-
}
|
|
645
|
-
return out;
|
|
646
|
-
}
|
|
647
|
-
async function authedSend(req, ctx) {
|
|
648
|
-
if (ctx.mode === "anonymous") {
|
|
649
|
-
return ctx.transport.request(
|
|
650
|
-
withAuthHeaders(req, {
|
|
651
|
-
mode: "anonymous",
|
|
652
|
-
publishableKey: ctx.publishableKey,
|
|
653
|
-
userRef: ctx.userRef,
|
|
654
|
-
...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
|
|
655
|
-
})
|
|
656
|
-
);
|
|
657
|
-
}
|
|
658
|
-
let token;
|
|
659
|
-
try {
|
|
660
|
-
token = await ctx.identity.currentToken();
|
|
661
|
-
} catch {
|
|
662
|
-
return err(authRejectedError());
|
|
663
|
-
}
|
|
664
|
-
const first = await ctx.transport.request(
|
|
665
|
-
withAuthHeaders(req, {
|
|
666
|
-
mode: "personalized",
|
|
667
|
-
token,
|
|
668
|
-
userRef: ctx.userRef,
|
|
669
|
-
...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
|
|
670
|
-
})
|
|
671
|
-
);
|
|
672
|
-
if (first.ok || first.error.httpStatus !== 401) return first;
|
|
673
|
-
let refreshed;
|
|
674
|
-
try {
|
|
675
|
-
refreshed = await ctx.identity.currentToken({ forceRefresh: true });
|
|
676
|
-
} catch {
|
|
677
|
-
return err(authRejectedError());
|
|
678
|
-
}
|
|
679
|
-
const retry = await ctx.transport.request(
|
|
680
|
-
withAuthHeaders(req, {
|
|
681
|
-
mode: "personalized",
|
|
682
|
-
token: refreshed,
|
|
683
|
-
userRef: ctx.userRef,
|
|
684
|
-
...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
|
|
685
|
-
})
|
|
686
|
-
);
|
|
687
|
-
if (!retry.ok && retry.error.httpStatus === 401) {
|
|
688
|
-
return err(authRejectedError(retry.error.httpStatus));
|
|
689
|
-
}
|
|
690
|
-
return retry;
|
|
691
|
-
}
|
|
692
|
-
function authRejectedError(httpStatus) {
|
|
693
|
-
return makeEverfurError("authRejected", {
|
|
694
|
-
retryable: false,
|
|
695
|
-
...httpStatus !== void 0 ? { httpStatus } : {}
|
|
696
|
-
});
|
|
697
|
-
}
|
|
698
|
-
|
|
699
|
-
// src/client/protocol/frames.ts
|
|
700
|
-
function assertNever(x) {
|
|
701
|
-
throw new Error(
|
|
702
|
-
`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`
|
|
703
|
-
);
|
|
704
|
-
}
|
|
705
|
-
var EMPTY_STRINGS = Object.freeze([]);
|
|
706
|
-
var EMPTY_MAPS = Object.freeze([]);
|
|
707
|
-
function acceptedFrame(streamId, lastEventId, serverRequestId = null) {
|
|
708
|
-
return Object.freeze({ kind: "accepted", streamId, lastEventId, serverRequestId, terminal: false });
|
|
709
|
-
}
|
|
710
|
-
function heartbeatFrame(lastEventId, serverRequestId = null) {
|
|
711
|
-
return Object.freeze({ kind: "heartbeat", lastEventId, serverRequestId, terminal: false });
|
|
712
|
-
}
|
|
713
|
-
function deltaFrame(delta, lastEventId, serverRequestId = null) {
|
|
714
|
-
return Object.freeze({ kind: "delta", delta, lastEventId, serverRequestId, terminal: false });
|
|
715
|
-
}
|
|
716
|
-
function doneFrame(fields, serverRequestId = null) {
|
|
717
|
-
return Object.freeze({
|
|
718
|
-
kind: "done",
|
|
719
|
-
terminal: true,
|
|
720
|
-
conversationId: fields.conversationId,
|
|
721
|
-
messageId: fields.messageId,
|
|
722
|
-
title: fields.title,
|
|
723
|
-
followUpQuestions: Object.freeze([...fields.followUpQuestions]),
|
|
724
|
-
citations: Object.freeze([...fields.citations]),
|
|
725
|
-
citationStatus: fields.citationStatus,
|
|
726
|
-
urgencyLevel: fields.urgencyLevel,
|
|
727
|
-
urgencyReason: fields.urgencyReason,
|
|
728
|
-
resultId: fields.resultId,
|
|
729
|
-
lastEventId: fields.lastEventId,
|
|
730
|
-
serverRequestId
|
|
731
|
-
});
|
|
732
|
-
}
|
|
733
|
-
function errorFrame(fields) {
|
|
734
|
-
return Object.freeze({
|
|
735
|
-
kind: "error",
|
|
736
|
-
terminal: true,
|
|
737
|
-
code: fields.code,
|
|
738
|
-
retryable: fields.retryable,
|
|
739
|
-
wireMessage: fields.wireMessage,
|
|
740
|
-
synthesized: fields.synthesized,
|
|
741
|
-
lastEventId: fields.lastEventId,
|
|
742
|
-
serverRequestId: fields.serverRequestId ?? null
|
|
743
|
-
});
|
|
744
|
-
}
|
|
745
|
-
function analysisStartedFrame(requestId, lastEventId, serverRequestId = null) {
|
|
746
|
-
return Object.freeze({
|
|
747
|
-
kind: "analysisStarted",
|
|
748
|
-
requestId,
|
|
749
|
-
lastEventId,
|
|
750
|
-
serverRequestId,
|
|
751
|
-
terminal: false
|
|
752
|
-
});
|
|
753
|
-
}
|
|
754
|
-
function analysisCompleteFrame(fields, serverRequestId = null) {
|
|
755
|
-
return Object.freeze({
|
|
756
|
-
kind: "analysisComplete",
|
|
757
|
-
terminal: false,
|
|
758
|
-
resultId: fields.resultId,
|
|
759
|
-
analysisType: fields.analysisType,
|
|
760
|
-
modelVersion: fields.modelVersion,
|
|
761
|
-
confidence: fields.confidence,
|
|
762
|
-
detections: Object.freeze([...fields.detections]),
|
|
763
|
-
interpretation: fields.interpretation,
|
|
764
|
-
lastEventId: fields.lastEventId,
|
|
765
|
-
serverRequestId
|
|
766
|
-
});
|
|
767
|
-
}
|
|
768
|
-
function unknownFrame(raw, lastEventId, serverRequestId = null) {
|
|
769
|
-
return Object.freeze({
|
|
770
|
-
kind: "unknown",
|
|
771
|
-
raw: { ...raw },
|
|
772
|
-
lastEventId,
|
|
773
|
-
serverRequestId,
|
|
774
|
-
terminal: false
|
|
775
|
-
});
|
|
776
|
-
}
|
|
777
|
-
var EMPTY_FRAME_ARRAYS = Object.freeze({
|
|
778
|
-
strings: EMPTY_STRINGS,
|
|
779
|
-
maps: EMPTY_MAPS
|
|
780
|
-
});
|
|
781
|
-
var BLOCK_SEPARATOR = "\n\n";
|
|
782
|
-
var MAX_PENDING_BLOCK_CHARS = 1048576;
|
|
783
|
-
var wireObjectSchema = z.record(z.string(), z.unknown());
|
|
784
|
-
var URGENCY_LEVELS = ["emergency", "schedule_soon", "home_care"];
|
|
785
|
-
async function* parseSse(bytes, serverRequestId = null) {
|
|
786
|
-
let resolvedRequestId = null;
|
|
787
|
-
const requestIdNow = () => {
|
|
788
|
-
if (resolvedRequestId !== null) return resolvedRequestId;
|
|
789
|
-
resolvedRequestId = typeof serverRequestId === "function" ? serverRequestId() : serverRequestId;
|
|
790
|
-
return resolvedRequestId;
|
|
791
|
-
};
|
|
792
|
-
const decoder = new TextDecoder("utf-8");
|
|
793
|
-
let buffer = "";
|
|
794
|
-
let scanFrom = 0;
|
|
795
|
-
let sawDelta = false;
|
|
796
|
-
for await (const chunk of bytes) {
|
|
797
|
-
buffer += decoder.decode(chunk, { stream: true });
|
|
798
|
-
for (; ; ) {
|
|
799
|
-
const sep = buffer.indexOf(BLOCK_SEPARATOR, scanFrom);
|
|
800
|
-
if (sep === -1) break;
|
|
801
|
-
const block = buffer.slice(0, sep);
|
|
802
|
-
buffer = buffer.slice(sep + BLOCK_SEPARATOR.length);
|
|
803
|
-
scanFrom = 0;
|
|
804
|
-
const frame = parseBlock(block, requestIdNow());
|
|
805
|
-
if (frame === null) continue;
|
|
806
|
-
if (frame.kind === "delta") sawDelta = true;
|
|
807
|
-
yield frame;
|
|
808
|
-
if (frame.terminal) return;
|
|
809
|
-
}
|
|
810
|
-
scanFrom = buffer.length > 0 ? buffer.length - 1 : 0;
|
|
811
|
-
if (buffer.length > MAX_PENDING_BLOCK_CHARS) {
|
|
812
|
-
yield errorFrame({
|
|
813
|
-
code: sawDelta ? "CHAT_STREAM_INCOMPLETE" : "internal_error",
|
|
814
|
-
retryable: true,
|
|
815
|
-
wireMessage: null,
|
|
816
|
-
synthesized: true,
|
|
817
|
-
lastEventId: null,
|
|
818
|
-
serverRequestId: requestIdNow()
|
|
819
|
-
});
|
|
820
|
-
return;
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
buffer += decoder.decode();
|
|
824
|
-
if (buffer.trim().length > 0) {
|
|
825
|
-
const frame = parseBlock(buffer, requestIdNow());
|
|
826
|
-
if (frame !== null) {
|
|
827
|
-
if (frame.kind === "delta") sawDelta = true;
|
|
828
|
-
yield frame;
|
|
829
|
-
if (frame.terminal) return;
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
yield errorFrame({
|
|
833
|
-
code: sawDelta ? "CHAT_STREAM_INCOMPLETE" : "internal_error",
|
|
834
|
-
retryable: true,
|
|
835
|
-
wireMessage: null,
|
|
836
|
-
synthesized: true,
|
|
837
|
-
lastEventId: null,
|
|
838
|
-
serverRequestId: requestIdNow()
|
|
839
|
-
});
|
|
840
|
-
}
|
|
841
|
-
function parseBlock(block, serverRequestId) {
|
|
842
|
-
let id = null;
|
|
843
|
-
const dataLines = [];
|
|
844
|
-
for (const rawLine of block.split("\n")) {
|
|
845
|
-
const line = rawLine.replace(/\s+$/, "");
|
|
846
|
-
if (line.length === 0 || line.startsWith(":")) continue;
|
|
847
|
-
if (line.startsWith("id:")) {
|
|
848
|
-
id = line.slice(3).trim();
|
|
849
|
-
} else if (line.startsWith("data:")) {
|
|
850
|
-
dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
851
|
-
}
|
|
852
|
-
}
|
|
853
|
-
if (dataLines.length === 0) return null;
|
|
854
|
-
let decoded;
|
|
855
|
-
try {
|
|
856
|
-
decoded = JSON.parse(dataLines.join("\n"));
|
|
857
|
-
} catch {
|
|
858
|
-
return null;
|
|
859
|
-
}
|
|
860
|
-
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) return null;
|
|
861
|
-
const parsed = wireObjectSchema.safeParse(decoded);
|
|
862
|
-
if (!parsed.success) return null;
|
|
863
|
-
return frameFromWire(parsed.data, id, serverRequestId);
|
|
864
|
-
}
|
|
865
|
-
function frameFromWire(json, lastEventId, serverRequestId) {
|
|
866
|
-
const type = json["type"];
|
|
867
|
-
const event = json["event"];
|
|
868
|
-
if (type === "error" || "error" in json) {
|
|
869
|
-
return errorFrame({
|
|
870
|
-
code: asString(json["code"]) ?? "unknown",
|
|
871
|
-
retryable: json["retryable"] === true,
|
|
872
|
-
wireMessage: asString(json["error"]),
|
|
873
|
-
synthesized: false,
|
|
874
|
-
lastEventId,
|
|
875
|
-
serverRequestId
|
|
876
|
-
});
|
|
877
|
-
}
|
|
878
|
-
if (type === "done" || json["done"] === true) {
|
|
879
|
-
return doneFrame({
|
|
880
|
-
conversationId: asString(json["conversation_id"]) ?? "",
|
|
881
|
-
messageId: asString(json["message_id"]),
|
|
882
|
-
title: asString(json["title"]),
|
|
883
|
-
followUpQuestions: asStringList(json["follow_up_questions"]),
|
|
884
|
-
citations: asMapList(json["citations"]),
|
|
885
|
-
citationStatus: asString(json["citation_status"]),
|
|
886
|
-
urgencyLevel: asUrgency(json["urgency_level"]),
|
|
887
|
-
urgencyReason: asString(json["urgency_reason"]),
|
|
888
|
-
resultId: asString(json["result_id"]),
|
|
889
|
-
lastEventId
|
|
890
|
-
}, serverRequestId);
|
|
891
|
-
}
|
|
892
|
-
if (type === "accepted" || json["status"] === "reasoning") {
|
|
893
|
-
return acceptedFrame(asString(json["stream_id"]), lastEventId, serverRequestId);
|
|
894
|
-
}
|
|
895
|
-
if (type === "heartbeat" || json["heartbeat"] === true) {
|
|
896
|
-
return heartbeatFrame(lastEventId, serverRequestId);
|
|
897
|
-
}
|
|
898
|
-
if (type === "text.delta" || "delta" in json || "token" in json) {
|
|
899
|
-
const delta = asString(json["delta"]) ?? asString(json["token"]) ?? "";
|
|
900
|
-
return deltaFrame(delta, lastEventId, serverRequestId);
|
|
901
|
-
}
|
|
902
|
-
if (event === "analysis_started") {
|
|
903
|
-
return analysisStartedFrame(asString(json["request_id"]), lastEventId, serverRequestId);
|
|
904
|
-
}
|
|
905
|
-
if (event === "analysis_complete") {
|
|
906
|
-
return analysisCompleteFrame({
|
|
907
|
-
resultId: asString(json["result_id"]),
|
|
908
|
-
analysisType: asString(json["analysis_type"]),
|
|
909
|
-
modelVersion: asString(json["model_version"]),
|
|
910
|
-
confidence: asNumber(json["confidence"]),
|
|
911
|
-
detections: asMapList(json["detections"]),
|
|
912
|
-
interpretation: asString(json["interpretation"]),
|
|
913
|
-
lastEventId
|
|
914
|
-
}, serverRequestId);
|
|
915
|
-
}
|
|
916
|
-
return unknownFrame(json, lastEventId, serverRequestId);
|
|
917
|
-
}
|
|
918
|
-
function asString(v) {
|
|
919
|
-
return typeof v === "string" ? v : null;
|
|
920
|
-
}
|
|
921
|
-
function asNumber(v) {
|
|
922
|
-
return typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
923
|
-
}
|
|
924
|
-
function asUrgency(v) {
|
|
925
|
-
return typeof v === "string" && URGENCY_LEVELS.includes(v) ? v : null;
|
|
926
|
-
}
|
|
927
|
-
function asStringList(v) {
|
|
928
|
-
if (!Array.isArray(v)) return [];
|
|
929
|
-
return v.map((e) => typeof e === "string" ? e : String(e));
|
|
930
|
-
}
|
|
931
|
-
function isPlainObject(v) {
|
|
932
|
-
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
933
|
-
}
|
|
934
|
-
function asMapList(v) {
|
|
935
|
-
if (!Array.isArray(v)) return [];
|
|
936
|
-
return v.filter(isPlainObject);
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
// src/client/transport.ts
|
|
940
|
-
var UNARY_TIMEOUT_MS = 3e4;
|
|
941
|
-
var REQUEST_ID_HEADER = "x-request-id";
|
|
942
|
-
async function* fetchByteSource(body) {
|
|
943
|
-
if (!body) return;
|
|
944
|
-
const reader = body.getReader();
|
|
945
|
-
try {
|
|
946
|
-
for (; ; ) {
|
|
947
|
-
const { done, value } = await reader.read();
|
|
948
|
-
if (done) break;
|
|
949
|
-
if (value && value.length > 0) yield value;
|
|
950
|
-
}
|
|
951
|
-
} finally {
|
|
952
|
-
await reader.cancel?.();
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
async function* bufferedTextByteSource(text, splitAt = []) {
|
|
956
|
-
const bytes = new TextEncoder().encode(text);
|
|
957
|
-
const points = [...new Set(splitAt)].filter((n) => n > 0 && n < bytes.length).sort((a, b) => a - b);
|
|
958
|
-
let start = 0;
|
|
959
|
-
for (const point of points) {
|
|
960
|
-
yield bytes.subarray(start, point);
|
|
961
|
-
start = point;
|
|
962
|
-
}
|
|
963
|
-
yield bytes.subarray(start);
|
|
964
|
-
}
|
|
965
|
-
function eventSourceByteSource(es) {
|
|
966
|
-
const enc = new TextEncoder();
|
|
967
|
-
const queue = createByteQueue();
|
|
968
|
-
let cleaned = false;
|
|
969
|
-
const onMessage = (ev) => {
|
|
970
|
-
let block = "";
|
|
971
|
-
if (ev.lastEventId) block += `id: ${ev.lastEventId}
|
|
972
|
-
`;
|
|
973
|
-
const data = ev.data ?? "";
|
|
974
|
-
for (const line of data.split("\n")) block += `data: ${line}
|
|
975
|
-
`;
|
|
976
|
-
block += "\n";
|
|
977
|
-
queue.push(enc.encode(block));
|
|
978
|
-
};
|
|
979
|
-
const onDone = () => {
|
|
980
|
-
cleanup();
|
|
981
|
-
queue.end();
|
|
982
|
-
};
|
|
983
|
-
const onError = (ev) => {
|
|
984
|
-
const status = typeof ev.xhrStatus === "number" ? ev.xhrStatus : 0;
|
|
985
|
-
if (status >= 400) {
|
|
986
|
-
const wireCode = statusToWireCode(status);
|
|
987
|
-
const retryable = isAutoRetryable(fromWire(wireCode));
|
|
988
|
-
queue.push(enc.encode(`data: ${JSON.stringify({ type: "error", code: wireCode, retryable })}
|
|
989
|
-
|
|
990
|
-
`));
|
|
991
|
-
}
|
|
992
|
-
cleanup();
|
|
993
|
-
queue.end();
|
|
994
|
-
};
|
|
995
|
-
es.addEventListener("message", onMessage);
|
|
996
|
-
es.addEventListener("done", onDone);
|
|
997
|
-
es.addEventListener("error", onError);
|
|
998
|
-
function cleanup() {
|
|
999
|
-
if (cleaned) return;
|
|
1000
|
-
cleaned = true;
|
|
1001
|
-
es.removeEventListener("message", onMessage);
|
|
1002
|
-
es.removeEventListener("done", onDone);
|
|
1003
|
-
es.removeEventListener("error", onError);
|
|
1004
|
-
try {
|
|
1005
|
-
es.close();
|
|
1006
|
-
} catch {
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
return sourceWithCleanup(queue.source, cleanup);
|
|
1010
|
-
}
|
|
1011
|
-
async function* sourceWithCleanup(source, cleanup) {
|
|
1012
|
-
try {
|
|
1013
|
-
yield* source;
|
|
1014
|
-
} finally {
|
|
1015
|
-
cleanup();
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
function createByteQueue() {
|
|
1019
|
-
const buffer = [];
|
|
1020
|
-
let done = false;
|
|
1021
|
-
let wake = null;
|
|
1022
|
-
const signal = () => {
|
|
1023
|
-
if (wake) {
|
|
1024
|
-
const fn = wake;
|
|
1025
|
-
wake = null;
|
|
1026
|
-
fn();
|
|
1027
|
-
}
|
|
1028
|
-
};
|
|
1029
|
-
async function* gen() {
|
|
1030
|
-
for (; ; ) {
|
|
1031
|
-
const next = buffer.shift();
|
|
1032
|
-
if (next !== void 0) {
|
|
1033
|
-
yield next;
|
|
1034
|
-
continue;
|
|
1035
|
-
}
|
|
1036
|
-
if (done) return;
|
|
1037
|
-
await new Promise((resolve) => {
|
|
1038
|
-
wake = resolve;
|
|
1039
|
-
});
|
|
1040
|
-
}
|
|
1041
|
-
}
|
|
1042
|
-
return {
|
|
1043
|
-
source: gen(),
|
|
1044
|
-
push: (u) => {
|
|
1045
|
-
buffer.push(u);
|
|
1046
|
-
signal();
|
|
1047
|
-
},
|
|
1048
|
-
end: () => {
|
|
1049
|
-
done = true;
|
|
1050
|
-
signal();
|
|
1051
|
-
}
|
|
1052
|
-
};
|
|
1053
|
-
}
|
|
1054
|
-
async function requestJson(req, deps) {
|
|
1055
|
-
const fetchImpl = deps.fetchImpl ?? getGlobalFetch();
|
|
1056
|
-
const url = buildUrl(deps.config.apiBaseUrl, req.path, req.query);
|
|
1057
|
-
const headers = mergeHeaders(deps.config, req.headers, "application/json", req.body !== void 0 && req.multipart === void 0);
|
|
1058
|
-
const deadline = timeoutSignal(UNARY_TIMEOUT_MS);
|
|
1059
|
-
const signal = mergeAbortSignals(deadline.signal, req.signal);
|
|
1060
|
-
let res;
|
|
1061
|
-
try {
|
|
1062
|
-
res = await fetchImpl(url, buildInit({ ...req, signal }, headers));
|
|
1063
|
-
} catch (cause) {
|
|
1064
|
-
return err(networkError(cause));
|
|
1065
|
-
} finally {
|
|
1066
|
-
deadline.cancel();
|
|
1067
|
-
}
|
|
1068
|
-
const bodyJson = await safeJson(res);
|
|
1069
|
-
if (!res.ok) return err(errorFromResponse(res.status, bodyJson, requestIdOf(res)));
|
|
1070
|
-
return ok(bodyJson);
|
|
1071
|
-
}
|
|
1072
|
-
async function requestRaw(req, deps, byteSourceFor) {
|
|
1073
|
-
const fetchImpl = deps.fetchImpl ?? getGlobalFetch();
|
|
1074
|
-
const url = buildUrl(deps.config.apiBaseUrl, req.path, req.query);
|
|
1075
|
-
const headers = mergeHeaders(deps.config, req.headers, "text/event-stream", req.body !== void 0 && req.multipart === void 0);
|
|
1076
|
-
let res;
|
|
1077
|
-
try {
|
|
1078
|
-
res = await fetchImpl(url, buildInit(req, headers));
|
|
1079
|
-
} catch (cause) {
|
|
1080
|
-
return err(networkError(cause));
|
|
1081
|
-
}
|
|
1082
|
-
if (!res.ok) return err(errorFromResponse(res.status, await safeJson(res), requestIdOf(res)));
|
|
1083
|
-
const bytes = byteSourceFor ? byteSourceFor(res) : fetchByteSource(res.body);
|
|
1084
|
-
return ok({ ok: res.ok, status: res.status, headers: collectHeaders(res), bytes });
|
|
1085
|
-
}
|
|
1086
|
-
function createHttpTransport(deps) {
|
|
1087
|
-
return {
|
|
1088
|
-
request: (req) => requestJson(req, deps),
|
|
1089
|
-
stream: (req, signal) => streamFrames(withSignal(req, signal), deps)
|
|
1090
|
-
};
|
|
1091
|
-
}
|
|
1092
|
-
async function* streamFrames(req, deps) {
|
|
1093
|
-
const url = buildUrl(deps.config.apiBaseUrl, req.path, req.query);
|
|
1094
|
-
const headers = mergeHeaders(deps.config, req.headers, "text/event-stream", req.body !== void 0 && req.multipart === void 0);
|
|
1095
|
-
if (deps.eventSourceFactory) {
|
|
1096
|
-
const es = deps.eventSourceFactory(url, buildEventSourceInit(req, headers));
|
|
1097
|
-
yield* parseSse(eventSourceByteSource(es), () => eventSourceRequestId(es));
|
|
1098
|
-
return;
|
|
1099
|
-
}
|
|
1100
|
-
const fetchImpl = deps.fetchImpl ?? getGlobalFetch();
|
|
1101
|
-
let res;
|
|
1102
|
-
try {
|
|
1103
|
-
res = await fetchImpl(url, buildInit(req, headers));
|
|
1104
|
-
} catch (cause) {
|
|
1105
|
-
yield syntheticErrorFrame("", true, describeCause(cause));
|
|
1106
|
-
return;
|
|
1107
|
-
}
|
|
1108
|
-
const requestId = requestIdOf(res);
|
|
1109
|
-
if (!res.ok) {
|
|
1110
|
-
const body = await safeJson(res);
|
|
1111
|
-
const wireCode = extractWireCode(body) ?? statusToWireCode(res.status);
|
|
1112
|
-
const retryable = extractRetryable(body) || isAutoRetryable(fromWire(wireCode));
|
|
1113
|
-
yield syntheticErrorFrame(wireCode, retryable, extractWireMessage(body), requestId);
|
|
1114
|
-
return;
|
|
1115
|
-
}
|
|
1116
|
-
if (res.body) {
|
|
1117
|
-
yield* parseSse(fetchByteSource(res.body), requestId);
|
|
1118
|
-
return;
|
|
1119
|
-
}
|
|
1120
|
-
yield* parseSse(fetchByteSource(null), requestId);
|
|
1121
|
-
}
|
|
1122
|
-
function buildEventSourceInit(req, headers) {
|
|
1123
|
-
return {
|
|
1124
|
-
method: req.method,
|
|
1125
|
-
headers,
|
|
1126
|
-
pollingInterval: 0,
|
|
1127
|
-
...req.body !== void 0 ? { body: JSON.stringify(req.body) } : {}
|
|
1128
|
-
};
|
|
1129
|
-
}
|
|
1130
|
-
function errorFromResponse(status, body, requestId) {
|
|
1131
|
-
const wireCode = extractWireCode(body);
|
|
1132
|
-
const code = wireCode ? fromWire(wireCode) : fromHttpStatus(status);
|
|
1133
|
-
const wireMessage = extractWireMessage(body);
|
|
1134
|
-
return makeEverfurError(code, {
|
|
1135
|
-
httpStatus: status,
|
|
1136
|
-
...extractRetryable(body) ? { retryable: true } : {},
|
|
1137
|
-
...requestId ? { requestId } : {},
|
|
1138
|
-
...wireCode ? { wireCode } : {},
|
|
1139
|
-
...wireMessage ? { wireMessage } : {},
|
|
1140
|
-
...body !== null && body !== void 0 ? { raw: body } : {}
|
|
1141
|
-
});
|
|
1142
|
-
}
|
|
1143
|
-
function networkError(cause) {
|
|
1144
|
-
return makeEverfurError("internalError", { retryable: true, wireMessage: describeCause(cause) });
|
|
1145
|
-
}
|
|
1146
|
-
function requestIdOf(res) {
|
|
1147
|
-
const value = res.headers.get(REQUEST_ID_HEADER);
|
|
1148
|
-
return typeof value === "string" && value.length > 0 ? value : null;
|
|
1149
|
-
}
|
|
1150
|
-
function eventSourceRequestId(es) {
|
|
1151
|
-
if (typeof es.getResponseHeader !== "function") return null;
|
|
1152
|
-
let value;
|
|
1153
|
-
try {
|
|
1154
|
-
value = es.getResponseHeader(REQUEST_ID_HEADER);
|
|
1155
|
-
} catch {
|
|
1156
|
-
return null;
|
|
1157
|
-
}
|
|
1158
|
-
return typeof value === "string" && value.length > 0 ? value : null;
|
|
1159
|
-
}
|
|
1160
|
-
function statusToWireCode(status) {
|
|
1161
|
-
if (status === 401) return "AUTH_EXPIRED";
|
|
1162
|
-
if (status === 403) return "ACCESS_DENIED";
|
|
1163
|
-
if (status === 404) return "NOT_FOUND";
|
|
1164
|
-
if (status === 409) return "IDEMPOTENCY_CONFLICT";
|
|
1165
|
-
if (status === 421) return "MISDIRECTED_REQUEST";
|
|
1166
|
-
if (status === 429) return "RATE_LIMITED";
|
|
1167
|
-
if (status === 400 || status === 422) return "INVALID_REQUEST";
|
|
1168
|
-
if (status === 503) return "INTERNAL_ERROR";
|
|
1169
|
-
if (status >= 500) return "INTERNAL_ERROR";
|
|
1170
|
-
return "";
|
|
1171
|
-
}
|
|
1172
|
-
function syntheticErrorFrame(code, retryable, wireMessage, serverRequestId = null) {
|
|
1173
|
-
return errorFrame({ code, retryable, wireMessage, synthesized: true, lastEventId: null, serverRequestId });
|
|
1174
|
-
}
|
|
1175
|
-
function getGlobalFetch() {
|
|
1176
|
-
const candidate = globalThis.fetch;
|
|
1177
|
-
if (typeof candidate !== "function") {
|
|
1178
|
-
throw new EverfurConfigError(
|
|
1179
|
-
"missing-peer-dependency",
|
|
1180
|
-
"global fetch is unavailable; provide config.transport or an injected fetch implementation"
|
|
1181
|
-
);
|
|
1182
|
-
}
|
|
1183
|
-
return candidate;
|
|
1184
|
-
}
|
|
1185
|
-
function buildUrl(base, path, query) {
|
|
1186
|
-
const rel = path.startsWith("/") ? path : `/${path}`;
|
|
1187
|
-
let url = `${base}${rel}`;
|
|
1188
|
-
if (query) {
|
|
1189
|
-
const qs = Object.entries(query).filter((entry) => entry[1] !== void 0).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
|
|
1190
|
-
if (qs) url += `?${qs}`;
|
|
1191
|
-
}
|
|
1192
|
-
return url;
|
|
1193
|
-
}
|
|
1194
|
-
function mergeHeaders(config, reqHeaders, accept, hasJsonBody) {
|
|
1195
|
-
const headers = { ...buildBaseHeaders(config), accept };
|
|
1196
|
-
if (hasJsonBody) headers["content-type"] = "application/json";
|
|
1197
|
-
if (reqHeaders) Object.assign(headers, reqHeaders);
|
|
1198
|
-
return headers;
|
|
1199
|
-
}
|
|
1200
|
-
function buildInit(req, headers) {
|
|
1201
|
-
const init = { method: req.method, headers };
|
|
1202
|
-
if (req.multipart !== void 0) init.body = req.multipart;
|
|
1203
|
-
else if (req.body !== void 0) init.body = JSON.stringify(req.body);
|
|
1204
|
-
if (req.signal) init.signal = req.signal;
|
|
1205
|
-
return init;
|
|
1206
|
-
}
|
|
1207
|
-
function withSignal(req, signal) {
|
|
1208
|
-
return req.signal ? req : { ...req, signal };
|
|
1209
|
-
}
|
|
1210
|
-
function timeoutSignal(ms) {
|
|
1211
|
-
const ctrl = new AbortController();
|
|
1212
|
-
const handle = setTimeout(() => ctrl.abort(), ms);
|
|
1213
|
-
return {
|
|
1214
|
-
signal: ctrl.signal,
|
|
1215
|
-
cancel: () => clearTimeout(handle)
|
|
1216
|
-
};
|
|
1217
|
-
}
|
|
1218
|
-
function mergeAbortSignals(deadline, caller) {
|
|
1219
|
-
if (!caller) return deadline;
|
|
1220
|
-
const ctrl = new AbortController();
|
|
1221
|
-
if (deadline.aborted || caller.aborted) {
|
|
1222
|
-
ctrl.abort();
|
|
1223
|
-
return ctrl.signal;
|
|
1224
|
-
}
|
|
1225
|
-
const onAbort = () => ctrl.abort();
|
|
1226
|
-
deadline.addEventListener("abort", onAbort, { once: true });
|
|
1227
|
-
caller.addEventListener("abort", onAbort, { once: true });
|
|
1228
|
-
return ctrl.signal;
|
|
1229
|
-
}
|
|
1230
|
-
async function safeJson(res) {
|
|
1231
|
-
try {
|
|
1232
|
-
return await res.json();
|
|
1233
|
-
} catch {
|
|
1234
|
-
return null;
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
function collectHeaders(res) {
|
|
1238
|
-
const out = {};
|
|
1239
|
-
res.headers.forEach?.((value, key) => {
|
|
1240
|
-
out[key.toLowerCase()] = value;
|
|
1241
|
-
});
|
|
1242
|
-
return out;
|
|
1243
|
-
}
|
|
1244
|
-
function extractWireCode(body) {
|
|
1245
|
-
const b = body;
|
|
1246
|
-
const code = b?.error?.code ?? b?.code;
|
|
1247
|
-
return typeof code === "string" && code.length > 0 ? code : null;
|
|
1248
|
-
}
|
|
1249
|
-
function extractWireMessage(body) {
|
|
1250
|
-
const b = body;
|
|
1251
|
-
const message = b?.error?.message ?? b?.message;
|
|
1252
|
-
return typeof message === "string" && message.length > 0 ? message : null;
|
|
1253
|
-
}
|
|
1254
|
-
function extractRetryable(body) {
|
|
1255
|
-
const b = body;
|
|
1256
|
-
return b?.error?.retryable === true || b?.retryable === true;
|
|
1257
|
-
}
|
|
1258
|
-
function describeCause(cause) {
|
|
1259
|
-
if (cause instanceof Error) return cause.message;
|
|
1260
|
-
return typeof cause === "string" ? cause : "network request failed";
|
|
1261
|
-
}
|
|
1262
|
-
|
|
1263
|
-
// src/client/entitlements/resolve.ts
|
|
1264
|
-
function resolveEntitlements(levels) {
|
|
1265
|
-
if (levels.length === 0) {
|
|
1266
|
-
return freezeResolved({ granted: [], asGrant: { allow: [], deny: [] } });
|
|
1267
|
-
}
|
|
1268
|
-
let allowed = null;
|
|
1269
|
-
const denied = /* @__PURE__ */ new Set();
|
|
1270
|
-
for (const level of levels) {
|
|
1271
|
-
const allow = new Set(level.allow);
|
|
1272
|
-
allowed = allowed === null ? allow : intersect(allowed, allow);
|
|
1273
|
-
for (const key of level.deny) denied.add(key);
|
|
1274
|
-
}
|
|
1275
|
-
const granted = [...allowed ?? /* @__PURE__ */ new Set()].filter((key) => !denied.has(key)).sort();
|
|
1276
|
-
return freezeResolved({ granted, asGrant: { allow: granted, deny: [] } });
|
|
1277
|
-
}
|
|
1278
|
-
function intersect(a, b) {
|
|
1279
|
-
const out = /* @__PURE__ */ new Set();
|
|
1280
|
-
for (const key of a) if (b.has(key)) out.add(key);
|
|
1281
|
-
return out;
|
|
1282
|
-
}
|
|
1283
|
-
function freezeResolved(r) {
|
|
1284
|
-
return Object.freeze({
|
|
1285
|
-
granted: Object.freeze([...r.granted]),
|
|
1286
|
-
asGrant: Object.freeze({
|
|
1287
|
-
allow: Object.freeze([...r.asGrant.allow]),
|
|
1288
|
-
deny: Object.freeze([...r.asGrant.deny])
|
|
1289
|
-
})
|
|
1290
|
-
});
|
|
1291
|
-
}
|
|
1292
|
-
var REQUIRES = Object.freeze({
|
|
1293
|
-
chat: Object.freeze(["chat.message.create"]),
|
|
1294
|
-
records: Object.freeze(["records.upload.create", "records.record.read"]),
|
|
1295
|
-
video: Object.freeze(["video.gait.execute"]),
|
|
1296
|
-
photo: Object.freeze(["photo.checkup.execute"]),
|
|
1297
|
-
animations: Object.freeze(["animations.state.read"])
|
|
1298
|
-
});
|
|
1299
|
-
function requires(name) {
|
|
1300
|
-
return REQUIRES[name];
|
|
1301
|
-
}
|
|
1302
|
-
function deniedDecisionsFor(level, reason) {
|
|
1303
|
-
const disabled = Object.freeze({ reason, level, recoverable: false });
|
|
1304
|
-
const rows = [];
|
|
1305
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1306
|
-
for (const name of Object.keys(REQUIRES)) {
|
|
1307
|
-
for (const resource of REQUIRES[name]) {
|
|
1308
|
-
if (seen.has(resource)) continue;
|
|
1309
|
-
seen.add(resource);
|
|
1310
|
-
rows.push(Object.freeze({ resource, granted: false, disabled }));
|
|
1311
|
-
}
|
|
1312
|
-
}
|
|
1313
|
-
return Object.freeze(rows);
|
|
1314
|
-
}
|
|
1315
|
-
function decideCapability(name, decisions, opts) {
|
|
1316
|
-
if (opts?.isPending === true) {
|
|
1317
|
-
return freezeDecision({ name, enabled: false, isPending: true, limits: {} });
|
|
1318
|
-
}
|
|
1319
|
-
const keys = requires(name);
|
|
1320
|
-
const byResource = /* @__PURE__ */ new Map();
|
|
1321
|
-
for (const decision of decisions) byResource.set(decision.resource, decision);
|
|
1322
|
-
const limits = mergeLimits(keys, byResource);
|
|
1323
|
-
const missing = keys.filter((key) => byResource.get(key)?.granted !== true);
|
|
1324
|
-
if (missing.length === 0) {
|
|
1325
|
-
return freezeDecision({ name, enabled: true, isPending: false, limits });
|
|
1326
|
-
}
|
|
1327
|
-
return freezeDecision({
|
|
1328
|
-
name,
|
|
1329
|
-
enabled: false,
|
|
1330
|
-
isPending: false,
|
|
1331
|
-
limits,
|
|
1332
|
-
disabled: disabledFor(keys, byResource)
|
|
1333
|
-
});
|
|
1334
|
-
}
|
|
1335
|
-
function mergeLimits(keys, byResource) {
|
|
1336
|
-
const out = {};
|
|
1337
|
-
for (const key of keys) {
|
|
1338
|
-
const decisionLimits = byResource.get(key)?.limits;
|
|
1339
|
-
if (!decisionLimits) continue;
|
|
1340
|
-
for (const [limitKey, limitValue] of Object.entries(decisionLimits)) {
|
|
1341
|
-
const existing = out[limitKey];
|
|
1342
|
-
out[limitKey] = existing === void 0 ? limitValue : Math.min(existing, limitValue);
|
|
1343
|
-
}
|
|
1344
|
-
}
|
|
1345
|
-
return out;
|
|
1346
|
-
}
|
|
1347
|
-
function disabledFor(keys, byResource) {
|
|
1348
|
-
for (const key of keys) {
|
|
1349
|
-
const explicit = byResource.get(key)?.disabled;
|
|
1350
|
-
if (explicit) {
|
|
1351
|
-
return Object.freeze({
|
|
1352
|
-
reason: explicit.reason,
|
|
1353
|
-
level: explicit.level,
|
|
1354
|
-
recoverable: explicit.recoverable
|
|
1355
|
-
});
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
return Object.freeze({
|
|
1359
|
-
reason: userFacingError("accessDenied"),
|
|
1360
|
-
level: "user_entitlement",
|
|
1361
|
-
recoverable: false
|
|
1362
|
-
});
|
|
1363
|
-
}
|
|
1364
|
-
function freezeDecision(d) {
|
|
1365
|
-
const base = {
|
|
1366
|
-
name: d.name,
|
|
1367
|
-
enabled: d.enabled,
|
|
1368
|
-
isPending: d.isPending,
|
|
1369
|
-
limits: Object.freeze({ ...d.limits })
|
|
1370
|
-
};
|
|
1371
|
-
if (d.disabled !== void 0) base.disabled = d.disabled;
|
|
1372
|
-
return Object.freeze(base);
|
|
1373
|
-
}
|
|
1374
|
-
|
|
1375
|
-
// src/client/funnel/requestFunnel.ts
|
|
1376
|
-
var FUNNEL_UNARY_TIMEOUT_MS = 3e4;
|
|
1377
|
-
var RETRY_OVERRIDE_MAX_MS = BACKOFF_CAP_MS * 2;
|
|
1378
|
-
var IDEMPOTENCY_HEADER = "idempotency-key";
|
|
1379
|
-
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1380
|
-
var NOOP_OBSERVER = Object.freeze({
|
|
1381
|
-
onEvent() {
|
|
1382
|
-
}
|
|
1383
|
-
});
|
|
1384
|
-
var defaultFunnelTimers = Object.freeze({
|
|
1385
|
-
setTimeout: (handler, ms) => setTimeout(handler, ms),
|
|
1386
|
-
clearTimeout: (handle) => clearTimeout(handle),
|
|
1387
|
-
now: () => Date.now()
|
|
1388
|
-
});
|
|
1389
|
-
function createRequestFunnel(deps) {
|
|
1390
|
-
const observer = deps.observer ?? NOOP_OBSERVER;
|
|
1391
|
-
const timers = deps.timers ?? defaultFunnelTimers;
|
|
1392
|
-
const rng = deps.rng ?? Math.random;
|
|
1393
|
-
const sleep = deps.sleep ?? ((ms, signal) => delayAbortable(ms, timers, signal));
|
|
1394
|
-
const ceiling = deps.maxAttempts ?? MAX_RETRY_ATTEMPTS;
|
|
1395
|
-
const timeoutMs = deps.unaryTimeoutMs ?? FUNNEL_UNARY_TIMEOUT_MS;
|
|
1396
|
-
const mintKey = deps.newIdempotencyKey ?? defaultIdempotencyKeyFactory();
|
|
1397
|
-
const emit = (event) => {
|
|
1398
|
-
try {
|
|
1399
|
-
observer.onEvent(event);
|
|
1400
|
-
} catch {
|
|
1401
|
-
}
|
|
1402
|
-
};
|
|
1403
|
-
async function send(call, req, opts) {
|
|
1404
|
-
const perCallMaxAttempts = opts?.maxAttempts;
|
|
1405
|
-
const maxAttempts = Math.max(1, perCallMaxAttempts ?? ceiling);
|
|
1406
|
-
const idempotent = opts?.idempotent ?? MUTATING_METHODS.has(req.method);
|
|
1407
|
-
const idempotencyKey = idempotent ? mintKey() : null;
|
|
1408
|
-
const base = assembleHeaders(req, idempotencyKey);
|
|
1409
|
-
let attempt = 0;
|
|
1410
|
-
for (; ; ) {
|
|
1411
|
-
const stamp = (extra) => Object.freeze({
|
|
1412
|
-
call,
|
|
1413
|
-
method: req.method,
|
|
1414
|
-
path: req.path,
|
|
1415
|
-
attempt,
|
|
1416
|
-
...idempotencyKey ? { idempotencyKey } : {},
|
|
1417
|
-
...extra
|
|
1418
|
-
});
|
|
1419
|
-
emit(stamp({ phase: "attempt" }));
|
|
1420
|
-
const deadline = boundedSignal(timeoutMs, timers);
|
|
1421
|
-
const merged = mergeSignals(deadline.signal, req.signal);
|
|
1422
|
-
let settled;
|
|
1423
|
-
try {
|
|
1424
|
-
settled = await authedSend({ ...base, signal: merged.signal }, deps.auth);
|
|
1425
|
-
} catch (cause) {
|
|
1426
|
-
settled = err(networkError(cause));
|
|
1427
|
-
} finally {
|
|
1428
|
-
merged.dispose();
|
|
1429
|
-
deadline.cancel();
|
|
1430
|
-
}
|
|
1431
|
-
if (settled.ok) {
|
|
1432
|
-
emit(stamp({ phase: "settled", ok: true, reason: "ok" }));
|
|
1433
|
-
return settled;
|
|
1434
|
-
}
|
|
1435
|
-
const error = settled.error;
|
|
1436
|
-
const decision = decideRetry(error, attempt, {
|
|
1437
|
-
maxAttempts,
|
|
1438
|
-
rng,
|
|
1439
|
-
now: timers.now(),
|
|
1440
|
-
aborted: req.signal?.aborted === true,
|
|
1441
|
-
...perCallMaxAttempts !== void 0 ? { perCallMaxAttempts } : {},
|
|
1442
|
-
...deps.errorPolicy !== void 0 ? { policy: deps.errorPolicy } : {}
|
|
1443
|
-
});
|
|
1444
|
-
const settledEvent = {
|
|
1445
|
-
ok: false,
|
|
1446
|
-
code: error.code,
|
|
1447
|
-
reason: decision.reason,
|
|
1448
|
-
...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {},
|
|
1449
|
-
...error.requestId !== void 0 ? { requestId: error.requestId } : {}
|
|
1450
|
-
};
|
|
1451
|
-
if (!decision.retry) {
|
|
1452
|
-
emit(stamp({ phase: "settled", ...settledEvent }));
|
|
1453
|
-
return err(error);
|
|
1454
|
-
}
|
|
1455
|
-
emit(stamp({ phase: "retry", ...settledEvent, delayMs: decision.delayMs }));
|
|
1456
|
-
await sleep(decision.delayMs, req.signal);
|
|
1457
|
-
if (req.signal?.aborted === true) {
|
|
1458
|
-
emit(stamp({ phase: "settled", ...settledEvent, reason: "aborted" }));
|
|
1459
|
-
return err(error);
|
|
1460
|
-
}
|
|
1461
|
-
attempt += 1;
|
|
1462
|
-
}
|
|
1463
|
-
}
|
|
1464
|
-
async function authorize(req) {
|
|
1465
|
-
return withAuthHeaders(req, await resolveDeviceAuth(deps.auth));
|
|
1466
|
-
}
|
|
1467
|
-
async function* stream(call, req, signal) {
|
|
1468
|
-
emit(
|
|
1469
|
-
Object.freeze({
|
|
1470
|
-
call,
|
|
1471
|
-
phase: "stream.open",
|
|
1472
|
-
method: req.method,
|
|
1473
|
-
path: req.path,
|
|
1474
|
-
attempt: 0
|
|
1475
|
-
})
|
|
1476
|
-
);
|
|
1477
|
-
try {
|
|
1478
|
-
yield* deps.auth.transport.stream(req, signal);
|
|
1479
|
-
} catch {
|
|
1480
|
-
yield errorFrame({
|
|
1481
|
-
// The same wire spelling sse.ts synthesizes, so `fromWire` folds it to the retryable `internalError`
|
|
1482
|
-
// like any other transport failure. wireMessage stays null: it is the SERVER's text, and a thrown
|
|
1483
|
-
// host exception's `.message` is not that.
|
|
1484
|
-
code: "internal_error",
|
|
1485
|
-
retryable: true,
|
|
1486
|
-
wireMessage: null,
|
|
1487
|
-
synthesized: true,
|
|
1488
|
-
lastEventId: null,
|
|
1489
|
-
serverRequestId: null
|
|
1490
|
-
});
|
|
1491
|
-
}
|
|
1492
|
-
}
|
|
1493
|
-
return Object.freeze({ send, authorize, stream });
|
|
1494
|
-
}
|
|
1495
|
-
function assembleHeaders(req, idempotencyKey) {
|
|
1496
|
-
const headers = {};
|
|
1497
|
-
for (const [key, value] of Object.entries(req.headers ?? {})) {
|
|
1498
|
-
if (key.toLowerCase() === IDEMPOTENCY_HEADER) continue;
|
|
1499
|
-
headers[key] = value;
|
|
1500
|
-
}
|
|
1501
|
-
if (idempotencyKey !== null) headers["Idempotency-Key"] = idempotencyKey;
|
|
1502
|
-
return { ...req, headers };
|
|
1503
|
-
}
|
|
1504
|
-
function defaultIdempotencyKeyFactory() {
|
|
1505
|
-
let counter = 0;
|
|
1506
|
-
return () => `efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
|
|
1507
|
-
}
|
|
1508
|
-
var POLICY_MAX_ATTEMPTS_CAP = 10;
|
|
1509
|
-
function decideRetry(error, attempt, ctx) {
|
|
1510
|
-
if (ctx.aborted) return { retry: false, reason: "aborted" };
|
|
1511
|
-
const throttle = throttleKind(error);
|
|
1512
|
-
if (throttle === "quota") {
|
|
1513
|
-
return { retry: false, reason: "daily-quota-exhausted" };
|
|
1514
|
-
}
|
|
1515
|
-
if (throttle !== "burst" && !isAutoRetryable(error.code)) {
|
|
1516
|
-
return { retry: false, reason: "terminal-code" };
|
|
1517
|
-
}
|
|
1518
|
-
const reason = throttle === "burst" ? "burst-throttle" : "retryable-code";
|
|
1519
|
-
const policyVetoedRetry = () => {
|
|
1520
|
-
if (ctx.policy === void 0) return false;
|
|
1521
|
-
try {
|
|
1522
|
-
return !ctx.policy.shouldRetry(error.code, attempt);
|
|
1523
|
-
} catch {
|
|
1524
|
-
return false;
|
|
1525
|
-
}
|
|
1526
|
-
};
|
|
1527
|
-
if (policyVetoedRetry()) return { retry: false, reason: "terminal-code" };
|
|
1528
|
-
const policyCeiling = () => {
|
|
1529
|
-
if (ctx.policy === void 0) return null;
|
|
1530
|
-
let raw;
|
|
1531
|
-
try {
|
|
1532
|
-
raw = ctx.policy.maxAttempts(error.code);
|
|
1533
|
-
} catch {
|
|
1534
|
-
return null;
|
|
1535
|
-
}
|
|
1536
|
-
if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
|
|
1537
|
-
return Math.max(1, Math.min(POLICY_MAX_ATTEMPTS_CAP, Math.floor(raw)));
|
|
1538
|
-
};
|
|
1539
|
-
const ceiling = ctx.perCallMaxAttempts ?? policyCeiling() ?? ctx.maxAttempts;
|
|
1540
|
-
if (attempt + 1 >= ceiling) return { retry: false, reason: "attempts-exhausted" };
|
|
1541
|
-
const override = retryOverrideMs(error, ctx.now);
|
|
1542
|
-
if (override !== null) {
|
|
1543
|
-
if (override > RETRY_OVERRIDE_MAX_MS) {
|
|
1544
|
-
return { retry: false, reason: "server-reset-beyond-budget" };
|
|
1545
|
-
}
|
|
1546
|
-
return { retry: true, reason, delayMs: override };
|
|
1547
|
-
}
|
|
1548
|
-
return { retry: true, reason, delayMs: backoffDelayMs(attempt, ctx.rng) };
|
|
1549
|
-
}
|
|
1550
|
-
function throttleKind(error) {
|
|
1551
|
-
const code = error.code === "unknown" ? fromWire(rawWireCode(error.raw)) : error.code;
|
|
1552
|
-
if (code === "quotaExceeded") return "quota";
|
|
1553
|
-
if (code === "rateLimited") return "burst";
|
|
1554
|
-
if (error.httpStatus === 429) {
|
|
1555
|
-
return "burst";
|
|
1556
|
-
}
|
|
1557
|
-
return null;
|
|
1558
|
-
}
|
|
1559
|
-
function retryOverrideMs(error, now) {
|
|
1560
|
-
const at = findResetsAt(error.raw);
|
|
1561
|
-
if (at === null) return null;
|
|
1562
|
-
const delta = at - now;
|
|
1563
|
-
return delta > 0 ? delta : 0;
|
|
1564
|
-
}
|
|
1565
|
-
function findResetsAt(raw) {
|
|
1566
|
-
for (const scope of candidateScopes(raw)) {
|
|
1567
|
-
const value = scope["resets_at"];
|
|
1568
|
-
const parsed = parseInstantMs(value);
|
|
1569
|
-
if (parsed !== null) return parsed;
|
|
1570
|
-
}
|
|
1571
|
-
return null;
|
|
1572
|
-
}
|
|
1573
|
-
function candidateScopes(raw) {
|
|
1574
|
-
if (!isRecord(raw)) return [];
|
|
1575
|
-
const out = [raw];
|
|
1576
|
-
for (const nested of ["error", "detail"]) {
|
|
1577
|
-
const value = raw[nested];
|
|
1578
|
-
if (isRecord(value)) out.push(value);
|
|
1579
|
-
}
|
|
1580
|
-
return out;
|
|
1581
|
-
}
|
|
1582
|
-
function parseInstantMs(value) {
|
|
1583
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
1584
|
-
return value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
|
|
1585
|
-
}
|
|
1586
|
-
if (typeof value === "string" && value.trim().length > 0) {
|
|
1587
|
-
const parsed = Date.parse(value);
|
|
1588
|
-
return Number.isFinite(parsed) ? parsed : null;
|
|
1589
|
-
}
|
|
1590
|
-
return null;
|
|
1591
|
-
}
|
|
1592
|
-
function rawWireCode(raw) {
|
|
1593
|
-
for (const scope of candidateScopes(raw)) {
|
|
1594
|
-
const code = scope["code"];
|
|
1595
|
-
if (typeof code === "string" && code.length > 0) return code;
|
|
1596
|
-
}
|
|
1597
|
-
return null;
|
|
1598
|
-
}
|
|
1599
|
-
function isRecord(value) {
|
|
1600
|
-
return typeof value === "object" && value !== null;
|
|
1601
|
-
}
|
|
1602
|
-
async function resolveDeviceAuth(auth) {
|
|
1603
|
-
if (auth.mode === "anonymous") {
|
|
1604
|
-
return {
|
|
1605
|
-
mode: "anonymous",
|
|
1606
|
-
publishableKey: auth.publishableKey,
|
|
1607
|
-
userRef: auth.userRef,
|
|
1608
|
-
...auth.sessionId ? { sessionId: auth.sessionId } : {}
|
|
1609
|
-
};
|
|
1610
|
-
}
|
|
1611
|
-
return {
|
|
1612
|
-
mode: "personalized",
|
|
1613
|
-
token: await auth.identity.currentToken(),
|
|
1614
|
-
userRef: auth.userRef,
|
|
1615
|
-
...auth.sessionId ? { sessionId: auth.sessionId } : {}
|
|
1616
|
-
};
|
|
1617
|
-
}
|
|
1618
|
-
function boundedSignal(ms, timers) {
|
|
1619
|
-
const ctrl = new AbortController();
|
|
1620
|
-
const handle = timers.setTimeout(() => ctrl.abort(), ms);
|
|
1621
|
-
return { signal: ctrl.signal, cancel: () => timers.clearTimeout(handle) };
|
|
1622
|
-
}
|
|
1623
|
-
function mergeSignals(deadline, caller) {
|
|
1624
|
-
const noop = () => void 0;
|
|
1625
|
-
if (!caller) return { signal: deadline, dispose: noop };
|
|
1626
|
-
const ctrl = new AbortController();
|
|
1627
|
-
if (deadline.aborted || caller.aborted) {
|
|
1628
|
-
ctrl.abort();
|
|
1629
|
-
return { signal: ctrl.signal, dispose: noop };
|
|
1630
|
-
}
|
|
1631
|
-
const onAbort = () => ctrl.abort();
|
|
1632
|
-
deadline.addEventListener("abort", onAbort, { once: true });
|
|
1633
|
-
caller.addEventListener("abort", onAbort, { once: true });
|
|
1634
|
-
return {
|
|
1635
|
-
signal: ctrl.signal,
|
|
1636
|
-
dispose: () => {
|
|
1637
|
-
deadline.removeEventListener("abort", onAbort);
|
|
1638
|
-
caller.removeEventListener("abort", onAbort);
|
|
1639
|
-
}
|
|
1640
|
-
};
|
|
1641
|
-
}
|
|
1642
|
-
function delayAbortable(ms, timers, signal) {
|
|
1643
|
-
if (ms <= 0 || signal?.aborted === true) return Promise.resolve();
|
|
1644
|
-
return new Promise((resolve) => {
|
|
1645
|
-
const handle = timers.setTimeout(() => {
|
|
1646
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1647
|
-
resolve();
|
|
1648
|
-
}, ms);
|
|
1649
|
-
const onAbort = () => {
|
|
1650
|
-
timers.clearTimeout(handle);
|
|
1651
|
-
resolve();
|
|
1652
|
-
};
|
|
1653
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1654
|
-
});
|
|
1655
|
-
}
|
|
1656
|
-
|
|
1657
|
-
// src/client/theme/tokens.ts
|
|
1658
|
-
function deepFreeze(value) {
|
|
1659
|
-
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
1660
|
-
Object.freeze(value);
|
|
1661
|
-
for (const key of Object.keys(value)) {
|
|
1662
|
-
deepFreeze(value[key]);
|
|
1663
|
-
}
|
|
1664
|
-
}
|
|
1665
|
-
return value;
|
|
1666
|
-
}
|
|
1667
|
-
var SPACE = { xs: 4, sm: 8, md: 12, lg: 16, xl: 24, xxl: 32 };
|
|
1668
|
-
var RADIUS = { tile: 5, xs: 6, sm: 10, md: 14, lg: 20, xl: 28, pill: 500 };
|
|
1669
|
-
var TYPE_SIZE = {
|
|
1670
|
-
nano: 8,
|
|
1671
|
-
small: 9,
|
|
1672
|
-
micro: 10,
|
|
1673
|
-
tiny: 11,
|
|
1674
|
-
caption: 12,
|
|
1675
|
-
bodyTight: 13,
|
|
1676
|
-
body: 14,
|
|
1677
|
-
subtitle: 16,
|
|
1678
|
-
heading: 18,
|
|
1679
|
-
verdict: 24
|
|
1680
|
-
};
|
|
1681
|
-
var LINE_HEIGHT = { tight: 1.15, snug: 1.3, normal: 1.4, relaxed: 1.55 };
|
|
1682
|
-
var WEIGHT = { regular: "400", medium: "500", bold: "700" };
|
|
1683
|
-
var LETTER_SPACING = {
|
|
1684
|
-
eyebrow: 1,
|
|
1685
|
-
monoWide: 0.9,
|
|
1686
|
-
headerBrand: -0.42,
|
|
1687
|
-
tight: -0.35
|
|
1688
|
-
};
|
|
1689
|
-
function baseType() {
|
|
1690
|
-
return {
|
|
1691
|
-
family: "System",
|
|
1692
|
-
mono: "monospace",
|
|
1693
|
-
fontUrl: null,
|
|
1694
|
-
size: TYPE_SIZE,
|
|
1695
|
-
lineHeight: LINE_HEIGHT,
|
|
1696
|
-
weight: WEIGHT,
|
|
1697
|
-
letterSpacing: LETTER_SPACING
|
|
1698
|
-
};
|
|
1699
|
-
}
|
|
1700
|
-
var MOTION = {
|
|
1701
|
-
duration: { instant: 80, fast: 140, normal: 220, slow: 320 },
|
|
1702
|
-
spring: { gentle: { damping: 18, stiffness: 200 } },
|
|
1703
|
-
easing: { standard: "cubic-bezier(0.4, 0, 0.2, 1)" },
|
|
1704
|
-
reducedMotion: false
|
|
1705
|
-
};
|
|
1706
|
-
var LIGHT_COLOR = {
|
|
1707
|
-
brand: "#10462E",
|
|
1708
|
-
brandSoft: "rgba(16,70,46,0.10)",
|
|
1709
|
-
brandSofter: "rgba(16,70,46,0.15)",
|
|
1710
|
-
brandBorder: "rgba(16,70,46,0.18)",
|
|
1711
|
-
borderHairlineGreen: "rgba(16,70,46,0.25)",
|
|
1712
|
-
surface: "#FFFFFF",
|
|
1713
|
-
surfaceCream: "#FDFBF8",
|
|
1714
|
-
surfaceSubtle: "#EFE9E3",
|
|
1715
|
-
background: "#FFFFFF",
|
|
1716
|
-
borderRingCream: "#D8D2C8",
|
|
1717
|
-
text: {
|
|
1718
|
-
primary: "#111111",
|
|
1719
|
-
secondary: "#0E462E",
|
|
1720
|
-
muted: "#6E6660",
|
|
1721
|
-
placeholder: "rgba(0,0,0,0.30)",
|
|
1722
|
-
onBrand: "#FFFFFF",
|
|
1723
|
-
metaCool: "#3D3D3D"
|
|
1724
|
-
},
|
|
1725
|
-
primary: "#10462E",
|
|
1726
|
-
onPrimary: "#FFFFFF",
|
|
1727
|
-
accent: "#10462E",
|
|
1728
|
-
onAccent: "#FFFFFF",
|
|
1729
|
-
accentEdge: "#07C168",
|
|
1730
|
-
success: "#07C168",
|
|
1731
|
-
danger: "#B91C1C",
|
|
1732
|
-
errorRed: "#FF1B00",
|
|
1733
|
-
warningStrong: "#A45610",
|
|
1734
|
-
cautionAccent: "#D9821D",
|
|
1735
|
-
riskConcern: "#EFA700",
|
|
1736
|
-
badgeBgPositive: "rgba(7,193,104,0.12)",
|
|
1737
|
-
badgeBgCaution: "rgba(217,130,29,0.14)",
|
|
1738
|
-
badgeBgCritical: "rgba(185,28,28,0.12)",
|
|
1739
|
-
badgeBgNeutral: "rgba(110,102,96,0.12)",
|
|
1740
|
-
bubbleUser: "#10462E",
|
|
1741
|
-
bubbleAssistant: "#FFFFFF",
|
|
1742
|
-
skeleton: "#EFE9E3",
|
|
1743
|
-
scanButtonPink: "#FFC3BC",
|
|
1744
|
-
checkupCardLowRiskBg: "rgba(7,193,104,0.10)",
|
|
1745
|
-
checkupCardConcernBg: "rgba(239,167,0,0.10)"
|
|
1746
|
-
};
|
|
1747
|
-
var EVERFUR_LIGHT = deepFreeze({
|
|
1748
|
-
brightness: "light",
|
|
1749
|
-
meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
|
|
1750
|
-
color: LIGHT_COLOR,
|
|
1751
|
-
space: SPACE,
|
|
1752
|
-
radius: RADIUS,
|
|
1753
|
-
type: baseType(),
|
|
1754
|
-
motion: MOTION
|
|
1755
|
-
});
|
|
1756
|
-
var DARK_COLOR = {
|
|
1757
|
-
brand: "#6BD39A",
|
|
1758
|
-
brandSoft: "rgba(107,211,154,0.12)",
|
|
1759
|
-
brandSofter: "rgba(107,211,154,0.18)",
|
|
1760
|
-
brandBorder: "rgba(107,211,154,0.22)",
|
|
1761
|
-
borderHairlineGreen: "rgba(107,211,154,0.28)",
|
|
1762
|
-
surface: "#1C1F23",
|
|
1763
|
-
surfaceCream: "#23272C",
|
|
1764
|
-
surfaceSubtle: "#23272C",
|
|
1765
|
-
background: "#15171A",
|
|
1766
|
-
borderRingCream: "#3A3F45",
|
|
1767
|
-
text: {
|
|
1768
|
-
primary: "#F5F3F0",
|
|
1769
|
-
secondary: "#A9E4C4",
|
|
1770
|
-
muted: "#9A938C",
|
|
1771
|
-
placeholder: "rgba(255,255,255,0.35)",
|
|
1772
|
-
onBrand: "#0E1F17",
|
|
1773
|
-
metaCool: "#C9C9C9"
|
|
1774
|
-
},
|
|
1775
|
-
primary: "#6BD39A",
|
|
1776
|
-
onPrimary: "#0E1F17",
|
|
1777
|
-
accent: "#6BD39A",
|
|
1778
|
-
onAccent: "#0E1F17",
|
|
1779
|
-
accentEdge: "#34D888",
|
|
1780
|
-
success: "#07C168",
|
|
1781
|
-
danger: "#B91C1C",
|
|
1782
|
-
errorRed: "#FF1B00",
|
|
1783
|
-
warningStrong: "#A45610",
|
|
1784
|
-
cautionAccent: "#D9821D",
|
|
1785
|
-
riskConcern: "#EFA700",
|
|
1786
|
-
badgeBgPositive: "rgba(7,193,104,0.18)",
|
|
1787
|
-
badgeBgCaution: "rgba(217,130,29,0.20)",
|
|
1788
|
-
badgeBgCritical: "rgba(185,28,28,0.22)",
|
|
1789
|
-
badgeBgNeutral: "rgba(255,255,255,0.10)",
|
|
1790
|
-
bubbleUser: "#6BD39A",
|
|
1791
|
-
bubbleAssistant: "#1C1F23",
|
|
1792
|
-
skeleton: "#23272C",
|
|
1793
|
-
scanButtonPink: "#FFC3BC",
|
|
1794
|
-
checkupCardLowRiskBg: "rgba(7,193,104,0.16)",
|
|
1795
|
-
checkupCardConcernBg: "rgba(239,167,0,0.16)"
|
|
1796
|
-
};
|
|
1797
|
-
var EVERFUR_DARK = deepFreeze({
|
|
1798
|
-
brightness: "dark",
|
|
1799
|
-
meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
|
|
1800
|
-
color: DARK_COLOR,
|
|
1801
|
-
space: SPACE,
|
|
1802
|
-
radius: RADIUS,
|
|
1803
|
-
type: baseType(),
|
|
1804
|
-
motion: MOTION
|
|
1805
|
-
});
|
|
1806
|
-
|
|
1807
|
-
// src/client/theme/resolve.ts
|
|
1808
|
-
function isEmptyBranding(b) {
|
|
1809
|
-
return b.displayName === null && b.logoUrl === null && b.primaryColor === null && b.accentColor === null && b.brightness === null && b.fontFamily === null && b.fontUrl === null && b.placeholder === null && b.hidePoweredBy === null;
|
|
1810
|
-
}
|
|
1811
|
-
function parseClientBranding(json) {
|
|
1812
|
-
if (json === null || typeof json !== "object") return null;
|
|
1813
|
-
const raw = json;
|
|
1814
|
-
const branding = {
|
|
1815
|
-
displayName: parseNonEmptyString(pick(raw, "display_name", "displayName")),
|
|
1816
|
-
logoUrl: parseNonEmptyString(pick(raw, "logo_url", "logoUrl")),
|
|
1817
|
-
primaryColor: parseColor(pick(raw, "primary_color", "primaryColor")),
|
|
1818
|
-
accentColor: parseColor(pick(raw, "accent_color", "accentColor")),
|
|
1819
|
-
brightness: parseBrightness(pick(raw, "brightness")),
|
|
1820
|
-
fontFamily: parseNonEmptyString(pick(raw, "font_family", "fontFamily")),
|
|
1821
|
-
fontUrl: parseNonEmptyString(pick(raw, "font_url", "fontUrl")),
|
|
1822
|
-
placeholder: parseNonEmptyString(pick(raw, "chat_placeholder", "placeholder", "chatPlaceholder")),
|
|
1823
|
-
hidePoweredBy: parseBool(pick(raw, "hide_powered_by", "hidePoweredBy"))
|
|
1824
|
-
};
|
|
1825
|
-
return isEmptyBranding(branding) ? null : Object.freeze(branding);
|
|
1826
|
-
}
|
|
1827
|
-
function parseBool(value) {
|
|
1828
|
-
if (typeof value === "boolean") return value;
|
|
1829
|
-
if (typeof value === "string") {
|
|
1830
|
-
const lower = value.trim().toLowerCase();
|
|
1831
|
-
if (lower === "true") return true;
|
|
1832
|
-
if (lower === "false") return false;
|
|
1833
|
-
}
|
|
1834
|
-
return null;
|
|
1835
|
-
}
|
|
1836
|
-
function pick(raw, ...keys) {
|
|
1837
|
-
for (const key of keys) {
|
|
1838
|
-
if (Object.prototype.hasOwnProperty.call(raw, key)) {
|
|
1839
|
-
const value = raw[key];
|
|
1840
|
-
if (value !== void 0) return value;
|
|
1841
|
-
}
|
|
1842
|
-
}
|
|
1843
|
-
return void 0;
|
|
1844
|
-
}
|
|
1845
|
-
function parseNonEmptyString(value) {
|
|
1846
|
-
if (typeof value !== "string") return null;
|
|
1847
|
-
const trimmed = value.trim();
|
|
1848
|
-
return trimmed.length === 0 ? null : trimmed;
|
|
1849
|
-
}
|
|
1850
|
-
function parseBrightness(value) {
|
|
1851
|
-
if (typeof value !== "string") return null;
|
|
1852
|
-
const lower = value.trim().toLowerCase();
|
|
1853
|
-
return lower === "light" || lower === "dark" ? lower : null;
|
|
1854
|
-
}
|
|
1855
|
-
function parseColor(value) {
|
|
1856
|
-
const rgba = toRgba(value);
|
|
1857
|
-
return rgba === null ? null : normalizeRgba(rgba);
|
|
1858
|
-
}
|
|
1859
|
-
function toRgba(value) {
|
|
1860
|
-
if (typeof value === "number") return argbIntToRgba(value);
|
|
1861
|
-
if (typeof value !== "string") return null;
|
|
1862
|
-
const s = value.trim();
|
|
1863
|
-
if (s.length === 0) return null;
|
|
1864
|
-
if (s.startsWith("#")) return fromHex(s.slice(1));
|
|
1865
|
-
if (s.toLowerCase().startsWith("0x")) return fromArgbHex(s.slice(2));
|
|
1866
|
-
if (s.toLowerCase().startsWith("rgb")) return fromRgbFunc(s);
|
|
1867
|
-
if (/^[0-9a-fA-F]+$/.test(s)) {
|
|
1868
|
-
const hex = fromHex(s);
|
|
1869
|
-
if (hex !== null) return hex;
|
|
1870
|
-
}
|
|
1871
|
-
if (/^\d+$/.test(s)) return argbIntToRgba(Number.parseInt(s, 10));
|
|
1872
|
-
return null;
|
|
1873
|
-
}
|
|
1874
|
-
function fromHex(hex) {
|
|
1875
|
-
const h = hex.trim();
|
|
1876
|
-
if (!/^[0-9a-fA-F]+$/.test(h)) return null;
|
|
1877
|
-
if (h.length === 3) {
|
|
1878
|
-
const r = dup(h[0]);
|
|
1879
|
-
const g = dup(h[1]);
|
|
1880
|
-
const b = dup(h[2]);
|
|
1881
|
-
return { r, g, b, a: 1 };
|
|
1882
|
-
}
|
|
1883
|
-
if (h.length === 6) {
|
|
1884
|
-
return { r: byte(h, 0), g: byte(h, 2), b: byte(h, 4), a: 1 };
|
|
1885
|
-
}
|
|
1886
|
-
if (h.length === 8) {
|
|
1887
|
-
const a = byte(h, 0);
|
|
1888
|
-
return { r: byte(h, 2), g: byte(h, 4), b: byte(h, 6), a: a / 255 };
|
|
1889
|
-
}
|
|
1890
|
-
return null;
|
|
1891
|
-
}
|
|
1892
|
-
function fromArgbHex(hex) {
|
|
1893
|
-
return fromHex(hex);
|
|
1894
|
-
}
|
|
1895
|
-
function fromRgbFunc(input) {
|
|
1896
|
-
const open = input.indexOf("(");
|
|
1897
|
-
const close = input.indexOf(")");
|
|
1898
|
-
if (open < 0 || close < 0 || close < open) return null;
|
|
1899
|
-
const parts = input.slice(open + 1, close).split(",").map((p) => p.trim());
|
|
1900
|
-
if (parts.length < 3) return null;
|
|
1901
|
-
const r = clampByte(Number(parts[0]));
|
|
1902
|
-
const g = clampByte(Number(parts[1]));
|
|
1903
|
-
const b = clampByte(Number(parts[2]));
|
|
1904
|
-
if (r === null || g === null || b === null) return null;
|
|
1905
|
-
let a = 1;
|
|
1906
|
-
if (parts.length >= 4) {
|
|
1907
|
-
const alpha = Number(parts[3]);
|
|
1908
|
-
if (!Number.isFinite(alpha)) return null;
|
|
1909
|
-
a = Math.min(1, Math.max(0, alpha));
|
|
1910
|
-
}
|
|
1911
|
-
return { r, g, b, a };
|
|
1912
|
-
}
|
|
1913
|
-
function argbIntToRgba(n) {
|
|
1914
|
-
if (!Number.isFinite(n)) return null;
|
|
1915
|
-
const int = Math.trunc(n) >>> 0;
|
|
1916
|
-
const a = int >>> 24 & 255;
|
|
1917
|
-
return {
|
|
1918
|
-
r: int >>> 16 & 255,
|
|
1919
|
-
g: int >>> 8 & 255,
|
|
1920
|
-
b: int & 255,
|
|
1921
|
-
// A 0x00RRGGBB with no alpha byte reads as fully transparent; treat a zero alpha byte as opaque so a
|
|
1922
|
-
// bare 0xRRGGBB (or small decimal) is not silently invisible.
|
|
1923
|
-
a: a === 0 ? 1 : a / 255
|
|
1924
|
-
};
|
|
1925
|
-
}
|
|
1926
|
-
function byte(hex, at) {
|
|
1927
|
-
return Number.parseInt(hex.slice(at, at + 2), 16);
|
|
1928
|
-
}
|
|
1929
|
-
function dup(nibble) {
|
|
1930
|
-
return Number.parseInt(`${nibble ?? "0"}${nibble ?? "0"}`, 16);
|
|
1931
|
-
}
|
|
1932
|
-
function clampByte(n) {
|
|
1933
|
-
if (!Number.isFinite(n)) return null;
|
|
1934
|
-
return Math.min(255, Math.max(0, Math.round(n)));
|
|
1935
|
-
}
|
|
1936
|
-
function normalizeRgba(rgba) {
|
|
1937
|
-
if (rgba.a >= 1) {
|
|
1938
|
-
return `#${hex2(rgba.r)}${hex2(rgba.g)}${hex2(rgba.b)}`.toUpperCase();
|
|
1939
|
-
}
|
|
1940
|
-
const a = Math.round(rgba.a * 1e3) / 1e3;
|
|
1941
|
-
return `rgba(${rgba.r},${rgba.g},${rgba.b},${a})`;
|
|
1942
|
-
}
|
|
1943
|
-
function hex2(n) {
|
|
1944
|
-
return n.toString(16).padStart(2, "0");
|
|
1945
|
-
}
|
|
1946
|
-
var NEAR_BLACK = "#111111";
|
|
1947
|
-
var WHITE = "#FFFFFF";
|
|
1948
|
-
function readableOn(background) {
|
|
1949
|
-
const rgba = toRgba(background);
|
|
1950
|
-
if (rgba === null) return WHITE;
|
|
1951
|
-
const bg = relativeLuminance(rgba);
|
|
1952
|
-
const black = relativeLuminance({ r: 17, g: 17, b: 17});
|
|
1953
|
-
const white = relativeLuminance({ r: 255, g: 255, b: 255});
|
|
1954
|
-
const contrastBlack = contrastRatio(bg, black);
|
|
1955
|
-
const contrastWhite = contrastRatio(bg, white);
|
|
1956
|
-
return contrastWhite >= contrastBlack ? WHITE : NEAR_BLACK;
|
|
1957
|
-
}
|
|
1958
|
-
function relativeLuminance(rgba) {
|
|
1959
|
-
const r = linearize(rgba.r / 255);
|
|
1960
|
-
const g = linearize(rgba.g / 255);
|
|
1961
|
-
const b = linearize(rgba.b / 255);
|
|
1962
|
-
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
|
1963
|
-
}
|
|
1964
|
-
function linearize(channel) {
|
|
1965
|
-
return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4);
|
|
1966
|
-
}
|
|
1967
|
-
function contrastRatio(l1, l2) {
|
|
1968
|
-
const lighter = Math.max(l1, l2);
|
|
1969
|
-
const darker = Math.min(l1, l2);
|
|
1970
|
-
return (lighter + 0.05) / (darker + 0.05);
|
|
1971
|
-
}
|
|
1972
|
-
function hardenHttpsUrl(url) {
|
|
1973
|
-
if (url === null) return null;
|
|
1974
|
-
const trimmed = url.trim();
|
|
1975
|
-
if (trimmed.length === 0) return null;
|
|
1976
|
-
return /^https:\/\/\S+$/i.test(trimmed) ? trimmed : null;
|
|
1977
|
-
}
|
|
1978
|
-
function withServerBranding(base, b) {
|
|
1979
|
-
if (b === null || isEmptyBranding(b)) return base;
|
|
1980
|
-
const palette = b.brightness !== null && b.brightness !== base.brightness ? b.brightness === "dark" ? EVERFUR_DARK : EVERFUR_LIGHT : base;
|
|
1981
|
-
const primary = b.primaryColor ?? palette.color.primary;
|
|
1982
|
-
const accent = b.accentColor ?? palette.color.accent;
|
|
1983
|
-
const pr = b.primaryColor !== null ? toRgba(primary) : null;
|
|
1984
|
-
const lift = (c) => Math.round(c + (255 - c) * 0.4);
|
|
1985
|
-
const brandFamily = pr !== null ? {
|
|
1986
|
-
brand: primary,
|
|
1987
|
-
bubbleUser: primary,
|
|
1988
|
-
text: { ...palette.color.text, secondary: primary },
|
|
1989
|
-
brandSoft: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.10)`,
|
|
1990
|
-
brandSofter: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.15)`,
|
|
1991
|
-
brandBorder: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.20)`,
|
|
1992
|
-
borderHairlineGreen: `rgba(${pr.r}, ${pr.g}, ${pr.b}, 0.28)`,
|
|
1993
|
-
accentEdge: `rgb(${lift(pr.r)}, ${lift(pr.g)}, ${lift(pr.b)})`
|
|
1994
|
-
} : {};
|
|
1995
|
-
const next = {
|
|
1996
|
-
brightness: palette.brightness,
|
|
1997
|
-
meta: {
|
|
1998
|
-
displayName: b.displayName ?? palette.meta.displayName,
|
|
1999
|
-
logoUrl: b.logoUrl ?? palette.meta.logoUrl,
|
|
2000
|
-
placeholder: b.placeholder ?? palette.meta.placeholder,
|
|
2001
|
-
hidePoweredBy: b.hidePoweredBy ?? palette.meta.hidePoweredBy
|
|
2002
|
-
},
|
|
2003
|
-
color: {
|
|
2004
|
-
...palette.color,
|
|
2005
|
-
...brandFamily,
|
|
2006
|
-
primary,
|
|
2007
|
-
accent,
|
|
2008
|
-
// onPrimary/onAccent are recomputed by resolveTheme; carry the palette defaults for a standalone call.
|
|
2009
|
-
onPrimary: palette.color.onPrimary,
|
|
2010
|
-
onAccent: palette.color.onAccent
|
|
2011
|
-
},
|
|
2012
|
-
space: palette.space,
|
|
2013
|
-
radius: palette.radius,
|
|
2014
|
-
type: {
|
|
2015
|
-
...palette.type,
|
|
2016
|
-
family: b.fontFamily ?? palette.type.family,
|
|
2017
|
-
fontUrl: b.fontUrl ?? palette.type.fontUrl
|
|
2018
|
-
},
|
|
2019
|
-
motion: palette.motion
|
|
2020
|
-
};
|
|
2021
|
-
return deepFreeze(next);
|
|
2022
|
-
}
|
|
2023
|
-
var DEFAULT_DISPLAY_NAME = "Everfur";
|
|
2024
|
-
function resolveTheme(input) {
|
|
2025
|
-
const scheme = input?.colorScheme === "dark" ? "dark" : "light";
|
|
2026
|
-
const systemBase = scheme === "dark" ? EVERFUR_DARK : EVERFUR_LIGHT;
|
|
2027
|
-
const withClient = withServerBranding(systemBase, input?.clientOverride ?? null);
|
|
2028
|
-
const merged = withServerBranding(withClient, input?.branding ?? null);
|
|
2029
|
-
return finalize(merged, input?.reducedMotion === true);
|
|
2030
|
-
}
|
|
2031
|
-
function finalize(theme, reducedMotion) {
|
|
2032
|
-
const primary = theme.color.primary;
|
|
2033
|
-
const accent = theme.color.accent;
|
|
2034
|
-
const displayName = theme.meta.displayName.trim().length === 0 ? DEFAULT_DISPLAY_NAME : theme.meta.displayName;
|
|
2035
|
-
const logoUrl = hardenHttpsUrl(theme.meta.logoUrl);
|
|
2036
|
-
const fontUrl = hardenHttpsUrl(theme.type.fontUrl);
|
|
2037
|
-
const motion = reducedMotion ? {
|
|
2038
|
-
duration: { instant: 0, fast: 0, normal: 0, slow: 0 },
|
|
2039
|
-
// Stiffen the spring so it settles immediately with no perceptible bounce.
|
|
2040
|
-
spring: { gentle: { damping: 100, stiffness: 1e3 } },
|
|
2041
|
-
easing: theme.motion.easing,
|
|
2042
|
-
reducedMotion: true
|
|
2043
|
-
} : theme.motion;
|
|
2044
|
-
const finalized = {
|
|
2045
|
-
brightness: theme.brightness,
|
|
2046
|
-
meta: { displayName, logoUrl, placeholder: theme.meta.placeholder, hidePoweredBy: theme.meta.hidePoweredBy },
|
|
2047
|
-
color: {
|
|
2048
|
-
...theme.color,
|
|
2049
|
-
primary,
|
|
2050
|
-
accent,
|
|
2051
|
-
onPrimary: readableOn(primary),
|
|
2052
|
-
onAccent: readableOn(accent)
|
|
2053
|
-
},
|
|
2054
|
-
space: theme.space,
|
|
2055
|
-
radius: theme.radius,
|
|
2056
|
-
type: { ...theme.type, fontUrl },
|
|
2057
|
-
motion
|
|
2058
|
-
};
|
|
2059
|
-
return deepFreeze(finalized);
|
|
2060
|
-
}
|
|
2061
|
-
|
|
2062
|
-
// src/client/entitlements/entitlementRepository.ts
|
|
2063
|
-
var ENTITLEMENTS_PATH = "/widget/v1/entitlements";
|
|
2064
|
-
var HTTP_NOT_MODIFIED = 304;
|
|
2065
|
-
var NOT_MODIFIED = Object.freeze({ kind: "notModified" });
|
|
2066
|
-
async function fetchEntitlements(auth, args = {}, funnel = createRequestFunnel({ auth })) {
|
|
2067
|
-
const result = await funnel.send(
|
|
2068
|
-
"entitlements.fetch",
|
|
2069
|
-
buildRequest(args)
|
|
2070
|
-
);
|
|
2071
|
-
if (!result.ok) {
|
|
2072
|
-
if (result.error.httpStatus === HTTP_NOT_MODIFIED) return NOT_MODIFIED;
|
|
2073
|
-
return { kind: "failed", error: result.error };
|
|
2074
|
-
}
|
|
2075
|
-
return parseUpdated(result.value);
|
|
2076
|
-
}
|
|
2077
|
-
var REGION_MAX = 64;
|
|
2078
|
-
function buildRequest(args) {
|
|
2079
|
-
const headers = {};
|
|
2080
|
-
if (isFiniteNumber(args.cachedRevision)) {
|
|
2081
|
-
headers["if-none-match"] = `"${args.cachedRevision}"`;
|
|
2082
|
-
}
|
|
2083
|
-
if (args.region && args.region.length <= REGION_MAX) {
|
|
2084
|
-
return { method: "GET", path: ENTITLEMENTS_PATH, headers, query: { region: args.region } };
|
|
2085
|
-
}
|
|
2086
|
-
return { method: "GET", path: ENTITLEMENTS_PATH, headers };
|
|
2087
|
-
}
|
|
2088
|
-
function parseUpdated(body) {
|
|
2089
|
-
if (body === null || typeof body !== "object") return malformed();
|
|
2090
|
-
if (!isFiniteNumber(body.revision)) return malformed();
|
|
2091
|
-
const region = typeof body.region === "string" ? body.region : "";
|
|
2092
|
-
const ttlSeconds = isFiniteNumber(body.ttl_seconds) ? body.ttl_seconds : 0;
|
|
2093
|
-
return Object.freeze({
|
|
2094
|
-
kind: "updated",
|
|
2095
|
-
revision: body.revision,
|
|
2096
|
-
region,
|
|
2097
|
-
ttlSeconds,
|
|
2098
|
-
decisions: mapCapabilities(body.capabilities),
|
|
2099
|
-
// Branding is ADDITIVE and orthogonal to capabilities: a parse fault here NEVER affects the decisions and
|
|
2100
|
-
// fails closed to null (the compiled default theme). It cannot make a granted capability un-render.
|
|
2101
|
-
branding: parseBranding(body)
|
|
2102
|
-
});
|
|
2103
|
-
}
|
|
2104
|
-
function parseBranding(body) {
|
|
2105
|
-
const direct = parseClientBranding(body.branding);
|
|
2106
|
-
if (direct !== null) return direct;
|
|
2107
|
-
const hints = body.render_hints;
|
|
2108
|
-
if (hints !== null && typeof hints === "object") {
|
|
2109
|
-
const nested = parseClientBranding(hints.branding);
|
|
2110
|
-
if (nested !== null) return nested;
|
|
2111
|
-
return parseClientBranding(hints);
|
|
2112
|
-
}
|
|
2113
|
-
return null;
|
|
2114
|
-
}
|
|
2115
|
-
function mapCapabilities(capabilities) {
|
|
2116
|
-
if (capabilities === null || typeof capabilities !== "object") return Object.freeze([]);
|
|
2117
|
-
const out = [];
|
|
2118
|
-
for (const [resource, value] of Object.entries(capabilities)) {
|
|
2119
|
-
if (isEnabled(value)) out.push(Object.freeze({ resource, granted: true }));
|
|
2120
|
-
}
|
|
2121
|
-
return Object.freeze(out);
|
|
2122
|
-
}
|
|
2123
|
-
function isEnabled(value) {
|
|
2124
|
-
return typeof value === "object" && value !== null && value.enabled === true;
|
|
2125
|
-
}
|
|
2126
|
-
function malformed() {
|
|
2127
|
-
return {
|
|
2128
|
-
kind: "failed",
|
|
2129
|
-
error: makeEverfurError("internalError", {
|
|
2130
|
-
retryable: true,
|
|
2131
|
-
wireMessage: "malformed entitlements response"
|
|
2132
|
-
})
|
|
2133
|
-
};
|
|
2134
|
-
}
|
|
2135
|
-
function isFiniteNumber(value) {
|
|
2136
|
-
return typeof value === "number" && Number.isFinite(value);
|
|
2137
|
-
}
|
|
2138
|
-
|
|
2139
|
-
// src/client/pets/petsRepository.ts
|
|
2140
|
-
var PET_NAME_MAX = 100;
|
|
2141
|
-
var PET_SPECIES_MAX = 50;
|
|
2142
|
-
var PET_BREED_MAX = 100;
|
|
2143
|
-
var PET_AGE_YEARS_MAX = 50;
|
|
2144
|
-
var PET_WEIGHT_KG_MAX = 500;
|
|
2145
|
-
var PET_REF_MAX = 128;
|
|
2146
|
-
function invalid(wireMessage) {
|
|
2147
|
-
return makeEverfurError("validationFailed", { retryable: false, wireMessage });
|
|
2148
|
-
}
|
|
2149
|
-
function checkString(field, value, max) {
|
|
2150
|
-
if (typeof value !== "string") return invalid(`${field} must be a string`);
|
|
2151
|
-
const length = serverLength(value);
|
|
2152
|
-
if (length <= max) return null;
|
|
2153
|
-
return invalid(`${field} is ${length} characters; the server accepts at most ${max}`);
|
|
2154
|
-
}
|
|
2155
|
-
function outOfRange(field, value, max) {
|
|
2156
|
-
if (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max) return null;
|
|
2157
|
-
return invalid(`${field} must be a finite number between 0 and ${max}`);
|
|
2158
|
-
}
|
|
2159
|
-
function validate(petRef2, profile) {
|
|
2160
|
-
if (typeof petRef2 !== "string") return invalid("pet_ref must be a string");
|
|
2161
|
-
if (petRef2.trim().length === 0) return invalid("pet_ref must not be blank");
|
|
2162
|
-
if (hasLoneSurrogate(petRef2)) return invalid("pet_ref contains an unpaired surrogate and cannot be encoded");
|
|
2163
|
-
if (profile !== void 0 && profile !== null && typeof profile !== "object") {
|
|
2164
|
-
return invalid("profile must be an object");
|
|
2165
|
-
}
|
|
2166
|
-
const checks = [checkString("pet_ref", petRef2, PET_REF_MAX)];
|
|
2167
|
-
if (profile?.name !== void 0) checks.push(checkString("name", profile.name, PET_NAME_MAX));
|
|
2168
|
-
if (profile?.species !== void 0) checks.push(checkString("species", profile.species, PET_SPECIES_MAX));
|
|
2169
|
-
if (profile?.breed !== void 0) checks.push(checkString("breed", profile.breed, PET_BREED_MAX));
|
|
2170
|
-
if (profile?.ageYears !== void 0) checks.push(outOfRange("age_years", profile.ageYears, PET_AGE_YEARS_MAX));
|
|
2171
|
-
if (profile?.weightKg !== void 0) checks.push(outOfRange("weight_kg", profile.weightKg, PET_WEIGHT_KG_MAX));
|
|
2172
|
-
return checks.find((c) => c !== null) ?? null;
|
|
2173
|
-
}
|
|
2174
|
-
function toWire(profile) {
|
|
2175
|
-
if (profile === void 0 || profile === null) return {};
|
|
2176
|
-
return {
|
|
2177
|
-
...profile.name !== void 0 ? { name: profile.name } : {},
|
|
2178
|
-
...profile.species !== void 0 ? { species: profile.species } : {},
|
|
2179
|
-
...profile.breed !== void 0 ? { breed: profile.breed } : {},
|
|
2180
|
-
...profile.ageYears !== void 0 ? { age_years: profile.ageYears } : {},
|
|
2181
|
-
...profile.weightKg !== void 0 ? { weight_kg: profile.weightKg } : {}
|
|
2182
|
-
};
|
|
2183
|
-
}
|
|
2184
|
-
function fromWire2(raw, petRef2) {
|
|
2185
|
-
const o = typeof raw === "object" && raw !== null ? raw : {};
|
|
2186
|
-
const str = (v) => typeof v === "string" ? v : null;
|
|
2187
|
-
const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
2188
|
-
return Object.freeze({
|
|
2189
|
-
petRef: str(o["pet_ref"]) ?? petRef2,
|
|
2190
|
-
name: str(o["name"]),
|
|
2191
|
-
species: str(o["species"]),
|
|
2192
|
-
breed: str(o["breed"]),
|
|
2193
|
-
ageYears: num(o["age_years"]),
|
|
2194
|
-
weightKg: num(o["weight_kg"])
|
|
2195
|
-
});
|
|
2196
|
-
}
|
|
2197
|
-
function createPetsRepository(auth) {
|
|
2198
|
-
return createPetsRepositoryOver(createRequestFunnel({ auth }));
|
|
2199
|
-
}
|
|
2200
|
-
function createPetsRepositoryOver(funnel) {
|
|
2201
|
-
return {
|
|
2202
|
-
async registerPet(petRef2, profile, opts) {
|
|
2203
|
-
const invalid2 = validate(petRef2, profile);
|
|
2204
|
-
if (invalid2 !== null) return err(invalid2);
|
|
2205
|
-
const path = `/widget/v1/pets/${encodeURIComponent(petRef2)}`;
|
|
2206
|
-
const base = { method: "POST", path, body: toWire(profile) };
|
|
2207
|
-
const res = await funnel.send(
|
|
2208
|
-
"pets.registerPet",
|
|
2209
|
-
opts?.signal ? { ...base, signal: opts.signal } : base
|
|
2210
|
-
);
|
|
2211
|
-
if (!res.ok) return err(res.error);
|
|
2212
|
-
return ok(fromWire2(res.value, petRef2));
|
|
2213
|
-
}
|
|
2214
|
-
};
|
|
2215
|
-
}
|
|
2216
|
-
|
|
2217
|
-
export { AUTO_RETRYABLE_CODES, BACKOFF_BASE_MS, BACKOFF_CAP_MS, CONTRACT_ERROR_ROWS, DEFAULT_CONTRACT_VERSION, DOC_SITE_ORIGIN, EMPTY_FRAME_ARRAYS, ENTITLEMENTS_PATH, ENV_API_BASE_URL, EVERFUR_DARK, EVERFUR_ERROR_CATEGORIES, EVERFUR_ERROR_CODES, EVERFUR_LIGHT, EverfurConfigError, EverfurThrownError, MAX_RETRY_ATTEMPTS, PET_AGE_YEARS_MAX, PET_BREED_MAX, PET_NAME_MAX, PET_SPECIES_MAX, PET_WEIGHT_KG_MAX, RETRYABLE_CONTRACT_CODES, SDK_PLATFORM, SDK_VERSION, acceptedFrame, analysisCompleteFrame, analysisStartedFrame, assertNever, authHeaders, authedSend, backoffDelayMs, bufferedTextByteSource, buildBaseHeaders, canRecreateOnNotFound, categoryFor, checkPublishableKey, contractDocUrl, contractErrorFor, conversationId, createHttpTransport, createIdentityProvider, createPetsRepository, decideCapability, deepFreeze, deltaFrame, deniedDecisionsFor, doneFrame, err, errorFrame, errorFromResponse, eventSourceByteSource, eventSourceRequestId, fetchByteSource, fetchEntitlements, fromHttpStatus, fromWire, getGlobalFetch, hardenHttpsUrl, heartbeatFrame, isAutoRetryable, isEmptyBranding, isErr, isOk, isRetryableCode, makeEverfurError, networkError, newSessionId, ok, parseClientBranding, parseColor, parseSse, petRef, publishedDocUrl, readableOn, requestIdOf, requestJson, requestRaw, requires, resolveApiBaseUrl, resolveClientConfig, resolveEntitlements, resolveTheme, shouldRetry, tryResolveApiBaseUrl, tryResolveClientConfig, unknownFrame, unsafeClientId, unsafeConversationId, unsafeDocumentId, unsafeJobId, unsafePetRef, unsafeRecordsRequestId, unsafeResponseId, unsafeUserRef, unwrap, userFacingError, userRef, withAuthHeaders, withServerBranding };
|
|
11
|
+
`));}l(),n.end();},"onError");e.addEventListener("message",i),e.addEventListener("done",a),e.addEventListener("error",s);function l(){if(!o){o=true,e.removeEventListener("message",i),e.removeEventListener("done",a),e.removeEventListener("error",s);try{e.close();}catch{}}}return t(l,"cleanup"),Jt(n.source,l)}t(Qt,"eventSourceByteSource");async function*Jt(e,r){try{yield*e;}finally{r();}}t(Jt,"sourceWithCleanup");function Zt(){let e=[],r=false,n=null,o=t(()=>{if(n){let a=n;n=null,a();}},"signal");async function*i(){for(;;){let a=e.shift();if(a!==void 0){yield a;continue}if(r)return;await new Promise(s=>{n=s;});}}return t(i,"gen"),{source:i(),push:t(a=>{e.push(a),o();},"push"),end:t(()=>{r=true,o();},"end")}}t(Zt,"createByteQueue");async function eo(e,r){let n=r.fetchImpl??Ue(),o=qe(r.config.apiBaseUrl,e.path,e.query),i=He(r.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),a=io(Xt),s=ao(a.signal,e.signal),l;try{l=await n(o,Ke({...e,signal:s},i));}catch(d){return y(ve(d))}finally{a.cancel();}let u=await $e(l);return l.ok?k(u):y(Zr(l.status,u,je(l)))}t(eo,"requestJson");async function Ms(e,r,n){let o=r.fetchImpl??Ue(),i=qe(r.config.apiBaseUrl,e.path,e.query),a=He(r.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0),s;try{s=await o(i,Ke(e,a));}catch(u){return y(ve(u))}if(!s.ok)return y(Zr(s.status,await $e(s),je(s)));let l=n?n(s):Be(s.body);return k({ok:s.ok,status:s.status,headers:so(s),bytes:l})}t(Ms,"requestRaw");function Ls(e){return {request:t(r=>eo(r,e),"request"),stream:t((r,n)=>ro(oo(r,n),e),"stream")}}t(Ls,"createHttpTransport");async function*ro(e,r){let n=qe(r.config.apiBaseUrl,e.path,e.query),o=He(r.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(r.eventSourceFactory){let l=r.eventSourceFactory(n,no(e,o));yield*Ee(Qt(l),()=>to(l));return}let i=r.fetchImpl??Ue(),a;try{a=await i(n,Ke(e,o));}catch(l){yield Xr("",true,on(l));return}let s=je(a);if(!a.ok){let l=await $e(a),u=rn(l)??en(a.status),d=tn(l)||z(X(u));yield Xr(u,d,nn(l),s);return}if(a.body){yield*Ee(Be(a.body),s);return}yield*Ee(Be(null),s);}t(ro,"streamFrames");function no(e,r){return {method:e.method,headers:r,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}t(no,"buildEventSourceInit");function Zr(e,r,n){let o=rn(r),i=o?X(o):Fr(e),a=nn(r);return C(i,{httpStatus:e,...tn(r)?{retryable:true}:{},...n?{requestId:n}:{},...o?{wireCode:o}:{},...Qr(r)?{reasonCode:Qr(r)}:{},...a?{wireMessage:a}:{},...r!=null?{raw:r}:{}})}t(Zr,"errorFromResponse");function ve(e){return C("internalError",{retryable:true,wireMessage:on(e)})}t(ve,"networkError");function je(e){let r=e.headers.get(Jr);return typeof r=="string"&&r.length>0?r:null}t(je,"requestIdOf");function to(e){if(typeof e.getResponseHeader!="function")return null;let r;try{r=e.getResponseHeader(Jr);}catch{return null}return typeof r=="string"&&r.length>0?r:null}t(to,"eventSourceRequestId");function en(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}t(en,"statusToWireCode");function Xr(e,r,n,o=null){return D({code:e,retryable:r,wireMessage:n,synthesized:true,lastEventId:null,serverRequestId:o})}t(Xr,"syntheticErrorFrame");function Ue(){let e=globalThis.fetch;if(typeof e!="function")throw new E("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}t(Ue,"getGlobalFetch");function qe(e,r,n){let o=r.startsWith("/")?r:`/${r}`,i=`${e}${o}`;if(n){let a=Object.entries(n).filter(s=>s[1]!==void 0).map(([s,l])=>`${encodeURIComponent(s)}=${encodeURIComponent(String(l))}`).join("&");a&&(i+=`?${a}`);}return i}t(qe,"buildUrl");function He(e,r,n,o){let i={...Dr(e),accept:n};return o&&(i["content-type"]="application/json"),r&&Object.assign(i,r),i}t(He,"mergeHeaders");function Ke(e,r){let n={method:e.method,headers:r};return e.multipart!==void 0?n.body=e.multipart:e.body!==void 0&&(n.body=JSON.stringify(e.body)),e.signal&&(n.signal=e.signal),n}t(Ke,"buildInit");function oo(e,r){return e.signal?e:{...e,signal:r}}t(oo,"withSignal");function io(e){let r=new AbortController,n=setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:t(()=>clearTimeout(n),"cancel")}}t(io,"timeoutSignal");function ao(e,r){if(!r)return e;let n=new AbortController;if(e.aborted||r.aborted)return n.abort(),n.signal;let o=t(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true}),n.signal}t(ao,"mergeAbortSignals");async function $e(e){try{return await e.json()}catch{return null}}t($e,"safeJson");function so(e){let r={};return e.headers.forEach?.((n,o)=>{r[o.toLowerCase()]=n;}),r}t(so,"collectHeaders");function Qr(e){let r=e,n=r?.error?.reason_code??r?.reason_code;return typeof n=="string"&&n.length>0?n:null}t(Qr,"extractReasonCode");function rn(e){let r=e,n=r?.error?.code??r?.code;return typeof n=="string"&&n.length>0?n:null}t(rn,"extractWireCode");function nn(e){let r=e,n=r?.error?.message??r?.message;return typeof n=="string"&&n.length>0?n:null}t(nn,"extractWireMessage");function tn(e){let r=e;return r?.error?.retryable===true||r?.retryable===true}t(tn,"extractRetryable");function on(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}t(on,"describeCause");function js(e){if(e.length===0)return an({granted:[],asGrant:{allow:[],deny:[]}});let r=null,n=new Set;for(let i of e){let a=new Set(i.allow);r=r===null?a:lo(r,a);for(let s of i.deny)n.add(s);}let o=[...r??new Set].filter(i=>!n.has(i)).sort();return an({granted:o,asGrant:{allow:o,deny:[]}})}t(js,"resolveEntitlements");function lo(e,r){let n=new Set;for(let o of e)r.has(o)&&n.add(o);return n}t(lo,"intersect");function an(e){return Object.freeze({granted:Object.freeze([...e.granted]),asGrant:Object.freeze({allow:Object.freeze([...e.asGrant.allow]),deny:Object.freeze([...e.asGrant.deny])})})}t(an,"freezeResolved");var Ge=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function uo(e){return Ge[e]}t(uo,"requires");function Us(e,r){let n=Object.freeze({reason:r,level:e,recoverable:false}),o=[],i=new Set;for(let a of Object.keys(Ge))for(let s of Ge[a])i.has(s)||(i.add(s),o.push(Object.freeze({resource:s,granted:false,disabled:n})));return Object.freeze(o)}t(Us,"deniedDecisionsFor");function qs(e,r,n){let o=uo(e),i=new Map;for(let l of r)i.set(l.resource,l);if(n?.isPending===true&&o.some(l=>!i.has(l)))return We({name:e,enabled:false,isPending:true,limits:{}});let a=co(o,i);return o.filter(l=>i.get(l)?.granted!==true).length===0?We({name:e,enabled:true,isPending:false,limits:a}):We({name:e,enabled:false,isPending:false,limits:a,disabled:fo(o,i)})}t(qs,"decideCapability");function co(e,r){let n={};for(let o of e){let i=r.get(o)?.limits;if(i)for(let[a,s]of Object.entries(i)){let l=n[a];n[a]=l===void 0?s:Math.min(l,s);}}return n}t(co,"mergeLimits");function fo(e,r){for(let n of e){let o=r.get(n)?.disabled;if(o)return Object.freeze({reason:o.reason,level:o.level,recoverable:o.recoverable})}return Object.freeze({reason:Me("accessDenied"),level:"user_entitlement",recoverable:false})}t(fo,"disabledFor");function We(e){let r={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(r.disabled=e.disabled),Object.freeze(r)}t(We,"freezeDecision");var po=3e4,yo=De*2,mo="idempotency-key",go=new Set(["POST","PUT","PATCH","DELETE"]),bo=Object.freeze({onEvent(){}}),ho=Object.freeze({setTimeout:t((e,r)=>setTimeout(e,r),"setTimeout"),clearTimeout:t(e=>clearTimeout(e),"clearTimeout"),now:t(()=>Date.now(),"now")});function Eo(e){let r=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return r.length===0?null:`efs_${r}`.slice(0,128)}t(Eo,"seededIdempotencyKey");function M(e){let r=e.observer??bo,n=e.timers??ho,o=e.rng??Math.random,i=e.sleep??((p,m)=>Io(p,n,m)),a=e.maxAttempts??wr,s=e.unaryTimeoutMs??po,l=e.newIdempotencyKey??_o(),u=t(p=>{try{r.onEvent(p);}catch{}},"emit");async function d(p,m,h){let F=h?.maxAttempts,ce=Math.max(1,F??a),fe=h?.idempotent??go.has(m.method),pe=h?.idempotencyKey===void 0?null:Eo(h.idempotencyKey),V=fe?pe??l():null,ye=vo(m,V),Oe=0;for(;;){let ee=t(Ie=>Object.freeze({call:p,method:m.method,path:m.path,attempt:Oe,...V?{idempotencyKey:V}:{},...Ie}),"stamp");u(ee({phase:"attempt"}));let _r=Oo(s,n),Rr=Ao(_r.signal,m.signal),re;try{re=await zr({...ye,signal:Rr.signal},e.auth);}catch(Ie){re=y(ve(Ie));}finally{Rr.dispose(),_r.cancel();}if(re.ok)return u(ee({phase:"settled",ok:true,reason:"ok"})),re;let P=re.error,me=Co(P,Oe,{maxAttempts:ce,rng:o,now:n.now(),aborted:m.signal?.aborted===true,...F!==void 0?{perCallMaxAttempts:F}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),Ae={ok:false,code:P.code,reason:me.reason,...P.httpStatus!==void 0?{httpStatus:P.httpStatus}:{},...P.requestId!==void 0?{requestId:P.requestId}:{}};if(!me.retry)return u(ee({phase:"settled",...Ae})),y(P);if(u(ee({phase:"retry",...Ae,delayMs:me.delayMs})),await i(me.delayMs,m.signal),m.signal?.aborted===true)return u(ee({phase:"settled",...Ae,reason:"aborted"})),y(P);Oe+=1;}}t(d,"send");async function f(p){return te(p,await wo(e.auth))}t(f,"authorize");async function*c(p,m,h){u(Object.freeze({call:p,phase:"stream.open",method:m.method,path:m.path,attempt:0}));try{yield*e.auth.transport.stream(m,h);}catch{yield D({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return t(c,"stream"),Object.freeze({send:d,authorize:f,stream:c})}t(M,"createRequestFunnel");function vo(e,r){let n={};for(let[o,i]of Object.entries(e.headers??{}))o.toLowerCase()!==mo&&(n[o]=i);return r!==null&&(n["Idempotency-Key"]=r),{...e,headers:n}}t(vo,"assembleHeaders");function _o(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}t(_o,"defaultIdempotencyKeyFactory");var Ro=10;function Co(e,r,n){if(n.aborted)return {retry:false,reason:"aborted"};let o=To(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!z(e.code))return {retry:false,reason:"terminal-code"};let i=o==="burst"?"burst-throttle":"retryable-code";if(t(()=>{if(n.policy===void 0)return false;try{return !n.policy.shouldRetry(e.code,r)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let s=t(()=>{if(n.policy===void 0)return null;let d;try{d=n.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(Ro,Math.floor(d)))},"policyCeiling"),l=n.perCallMaxAttempts??s()??n.maxAttempts;if(r+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=ko(e,n.now);return u!==null?u>yo?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:i,delayMs:u}:{retry:true,reason:i,delayMs:Or(r,n.rng)}}t(Co,"decideRetry");function To(e){let r=e.code==="unknown"?X(xo(e.raw)):e.code;return r==="quotaExceeded"?"quota":r==="rateLimited"||e.httpStatus===429?"burst":null}t(To,"throttleKind");function ko(e,r){let n=So(e.raw);if(n===null)return null;let o=n-r;return o>0?o:0}t(ko,"retryOverrideMs");function So(e){for(let r of ln(e)){let n=r.resets_at,o=Fo(n);if(o!==null)return o}return null}t(So,"findResetsAt");function ln(e){if(!sn(e))return [];let r=[e];for(let n of ["error","detail"]){let o=e[n];sn(o)&&r.push(o);}return r}t(ln,"candidateScopes");function Fo(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let r=Date.parse(e);return Number.isFinite(r)?r:null}return null}t(Fo,"parseInstantMs");function xo(e){for(let r of ln(e)){let n=r.code;if(typeof n=="string"&&n.length>0)return n}return null}t(xo,"rawWireCode");function sn(e){return typeof e=="object"&&e!==null}t(sn,"isRecord");async function wo(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}t(wo,"resolveDeviceAuth");function Oo(e,r){let n=new AbortController,o=r.setTimeout(()=>n.abort(),e);return {signal:n.signal,cancel:t(()=>r.clearTimeout(o),"cancel")}}t(Oo,"boundedSignal");function Ao(e,r){let n=t(()=>{},"noop");if(!r)return {signal:e,dispose:n};let o=new AbortController;if(e.aborted||r.aborted)return o.abort(),{signal:o.signal,dispose:n};let i=t(()=>o.abort(),"onAbort");return e.addEventListener("abort",i,{once:true}),r.addEventListener("abort",i,{once:true}),{signal:o.signal,dispose:t(()=>{e.removeEventListener("abort",i),r.removeEventListener("abort",i);},"dispose")}}t(Ao,"mergeSignals");function Io(e,r,n){return e<=0||n?.aborted===true?Promise.resolve():new Promise(o=>{let i=r.setTimeout(()=>{n?.removeEventListener("abort",a),o();},e),a=t(()=>{r.clearTimeout(i),o();},"onAbort");n?.addEventListener("abort",a,{once:true});})}t(Io,"delayAbortable");function T(e){let r=_(e);return r===null?null:Do(r)}t(T,"parseColor");function _(e){if(typeof e=="number")return un(e);if(typeof e!="string")return null;let r=e.trim();if(r.length===0)return null;if(r.startsWith("#"))return Ye(r.slice(1));if(r.toLowerCase().startsWith("0x"))return Ye(r.slice(2));if(r.toLowerCase().startsWith("rgb"))return Po(r);if(/^[0-9a-fA-F]+$/.test(r)){let n=Ye(r);if(n!==null)return n}return /^\d+$/.test(r)?un(Number.parseInt(r,10)):null}t(_,"toRgba");function Ye(e){let r=e.trim();if(!/^[0-9a-fA-F]+$/.test(r))return null;if(r.length===3)return {r:Ve(r[0]),g:Ve(r[1]),b:Ve(r[2]),a:1};if(r.length===6)return {r:j(r,0),g:j(r,2),b:j(r,4),a:1};if(r.length===8){let n=j(r,0);return {r:j(r,2),g:j(r,4),b:j(r,6),a:n/255}}return null}t(Ye,"fromHex");function Po(e){let r=e.indexOf("("),n=e.indexOf(")");if(r<0||n<0||n<r)return null;let o=e.slice(r+1,n).split(",").map(u=>u.trim());if(o.length<3)return null;let i=Xe(Number(o[0])),a=Xe(Number(o[1])),s=Xe(Number(o[2]));if(i===null||a===null||s===null)return null;let l=1;if(o.length>=4){let u=Number(o[3]);if(!Number.isFinite(u))return null;l=Math.min(1,Math.max(0,u));}return {r:i,g:a,b:s,a:l}}t(Po,"fromRgbFunc");function un(e){if(!Number.isFinite(e))return null;let r=Math.trunc(e)>>>0,n=r>>>24&255;return {r:r>>>16&255,g:r>>>8&255,b:r&255,a:n===0?1:n/255}}t(un,"argbIntToRgba");function j(e,r){return Number.parseInt(e.slice(r,r+2),16)}t(j,"byte");function Ve(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}t(Ve,"dup");function Xe(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}t(Xe,"clampByte");function Do(e){if(e.a>=1)return q(e.r,e.g,e.b);let r=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${r})`}t(Do,"normalizeRgba");function q(e,r,n){return `#${Qe(e)}${Qe(r)}${Qe(n)}`.toUpperCase()}t(q,"rgbToHex");function Qe(e){return e.toString(16).padStart(2,"0")}t(Qe,"hex2");var Mo="#111111",J="#FFFFFF",_e="#000000";function cn(e){let r=_(e);if(r===null)return J;let n=U(r),o=U({r:17,g:17,b:17}),i=U({r:255,g:255,b:255});return er(n,i)>=er(n,o)?J:Mo}t(cn,"readableOn");function oe(e,r){let n=cn(e);return R(n,e)>=r?n:R(J,e)>=R(_e,e)?J:_e}t(oe,"legibleOn");function ie(e){let r=t(n=>e.reduce((o,i)=>Math.min(o,R(n,i)),Number.POSITIVE_INFINITY),"worst");return r(J)>=r(_e)?J:_e}t(ie,"poleForGrounds");function U(e){let r=Je(e.r/255),n=Je(e.g/255),o=Je(e.b/255);return .2126*r+.7152*n+.0722*o}t(U,"relativeLuminance");function Je(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}t(Je,"linearize");function er(e,r){let n=Math.max(e,r),o=Math.min(e,r);return (n+.05)/(o+.05)}t(er,"luminanceContrast");function R(e,r){let n=_(e),o=_(r);if(n===null||o===null)return 1;let i=o.a>=1?o:{...o},a=n.a>=1?n:fn(n,i);return er(U(a),U(i))}t(R,"contrastRatio");function fn(e,r){let n=e.a,o=t((i,a)=>Math.round(i*n+a*(1-n)),"mix");return {r:o(e.r,r.r),g:o(e.g,r.g),b:o(e.b,r.b),a:1}}t(fn,"composite");function H(e,r){let n=_(e),o=_(r);if(n===null||o===null)return null;let i=n.a>=1?n:fn(n,{...o});return q(i.r,i.g,i.b)}t(H,"flattenOnto");var dn=.05;function K(e,r,n,o){let i=r[0];if(i===void 0)return n;let a=t(d=>r.every(f=>R(d,f)>=o),"reads");if(_(e)===null)return n;if(a(e))return e;let s=H(e,i),l=s===null?null:_(s),u=_(n);if(l===null||u===null)return n;for(let d=1;d<1/dn;d+=1){let f=d*dn,c=t((m,h)=>Math.round(m+(h-m)*f),"mix"),p=q(c(l.r,u.r),c(l.g,u.g),c(l.b,u.b));if(a(p))return p}return n}t(K,"pushToContrast");function pn(e,r,n){let o=e/255,i=r/255,a=n/255,s=Math.max(o,i,a),l=Math.min(o,i,a),u=(s+l)/2;if(s===l)return {h:0,s:0,l:u};let d=s-l,f=d/(1-Math.abs(2*u-1)),c;return s===o?(c=(i-a)/d*60,c<0&&(c=c+360)):s===i?c=((a-o)/d+2)*60:c=((o-i)/d+4)*60,{h:c,s:f,l:u}}t(pn,"rgbToHsl");function rr(e){let{h:r,s:n,l:o}=e,i=(1-Math.abs(2*o-1))*n,a=r/60,s=i*(1-Math.abs(a%2-1)),l=o-i/2,u=Math.floor(a)%6,d=[[i,s,0],[s,i,0],[0,i,s],[0,s,i],[s,0,i],[i,0,s]],[f,c,p]=d[u];return {r:Ze(f+l),g:Ze(c+l),b:Ze(p+l)}}t(rr,"hslToRgb");function Ze(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}t(Ze,"channel");function A(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let r of Object.keys(e))A(e[r]);}return e}t(A,"deepFreeze");var Re=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),mn={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},gn={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},yn={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Lo={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},No={regular:"400",medium:"500",bold:"700"},zo={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},or=0,$="System",L="monospace",Bo=["content","heading","control","compact","badge"];function jo(e){let r={};for(let n of Bo)r[n]=e;return r}t(jo,"authoredTierSizes");function bn(){return {family:$,mono:L,fontUrl:null,families:{regular:$,medium:$,bold:$,mono:L,monoMedium:L,monoBold:L},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:yn,tierSizes:jo(yn),lineHeight:Lo,weight:No,letterSpacing:zo,scale:1,maxScale:or,scaleCaps:Re}}t(bn,"baseType");var hn={},nr=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function tr(e){return `cubic-bezier(${e.join(", ")})`}t(tr,"cssCubicBezier");var En={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:tr(nr.standard),emphasized:tr(nr.emphasized),exit:tr(nr.exit)},reducedMotion:false},Uo={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#B91C1C",errorRed:"#FF1B00",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},ae=A({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Uo,space:mn,radius:gn,type:bn(),motion:En,slots:hn}),qo={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A938C",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},Ce=A({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:qo,space:mn,radius:gn,type:bn(),motion:En,slots:hn});var Ho="#23272C",vn=4.5,Ko=.6,ir=.9,$o=.02,Wo="#FFFFFF",Go="#111111";function Yo(e){return R(e,Ho)>=vn&&Math.max(R(e,Wo),R(e,Go))>=vn}t(Yo,"readsOnDark");function Cn(e){let r=_(e);if(r===null)return null;let{h:n,s:o,l:i}=pn(r.r,r.g,r.b),a=Math.min(Math.max(i,Ko),ir);for(let l=0;;l+=1){let u=a+l*$o;if(u>ir)break;let d=rr({h:n,s:o,l:u}),f=q(d.r,d.g,d.b);if(Yo(f))return f}let s=rr({h:n,s:o,l:ir});return q(s.r,s.g,s.b)}t(Cn,"deriveDarkVariant");var Vo=7,_n=.05,Xo="#000000",Qo="#FFFFFF";function Jo(e,r,n,o){let i=H(e,r);if(i===null)return n;if(R(i,r)>=o)return i;let a=_(i),s=_(n);if(a===null||s===null)return n;for(let l=1;l<1/_n;l+=1){let u=l*_n,d=t((c,p)=>Math.round(c+(p-c)*u),"mix"),f=q(d(a.r,s.r),d(a.g,s.g),d(a.b,s.b));if(R(f,r)>=o)return f}return n}t(Jo,"pushContrast");function Zo(e,r){let n=[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill],o=n[0],i=Rn(o);for(let a of n){let s=Rn(a);(r?s>i:s<i)&&(o=a,i=s);}return o}t(Zo,"hardestGround");function Rn(e){let r=_(e);return r===null?0:U(r)}t(Rn,"luminanceOf");function N(e,r){return H(e,r)??T(e)??r}t(N,"solid");function Tn(e){let r=e.color,n=e.brightness==="dark",o=n?Qo:Xo,i=Zo(r,n),a=t(l=>Jo(l,i,o,Vo),"text"),s={...r,brandSoft:N(r.brandSoft,r.surface),brandSofter:N(r.brandSofter,r.surface),brandBorder:a(r.brandBorder),borderHairlineGreen:a(r.borderHairlineGreen),brandBorderStrong:a(r.brandBorderStrong),brandInk:a(r.brandInk),linkInk:a(r.linkInk),borderRingCream:a(r.borderRingCream),composerBorder:a(r.composerBorder),text:{primary:a(r.text.primary),secondary:a(r.text.secondary),muted:a(r.text.muted),placeholder:a(r.text.placeholder),onBrand:r.text.onBrand,metaCool:a(r.text.metaCool),timestamp:a(r.text.timestamp)},badgeBgPositive:N(r.badgeBgPositive,r.surface),badgeBgCaution:N(r.badgeBgCaution,r.surface),badgeBgCritical:N(r.badgeBgCritical,r.surface),badgeBgNeutral:N(r.badgeBgNeutral,r.surface),checkupCardLowRiskBg:N(r.checkupCardLowRiskBg,r.surface),checkupCardConcernBg:N(r.checkupCardConcernBg,r.surface)};return A({...e,highContrast:true,color:s})}t(Tn,"deriveHighContrast");var Z=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]),sl=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),S=4.5,ei=Object.freeze({});function ri(e){return Z.includes(e)}t(ri,"isSlotName");function ni(e){let r=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(r)?Math.max(0,r):null}t(ni,"parseRadius");function kn(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let r={},n=false;for(let[o,i]of Object.entries(e)){if(!ri(o)||i===null||typeof i!="object")continue;let a=ti(i);a!==null&&(r[o]=a,n=true);}return n?Object.freeze(r):null}t(kn,"parseThemeSlots");function Te(e,r,n){return e[r]!==void 0?e[r]:e[n]}t(Te,"pick");function ti(e){let r={},n=T(Te(e,"background_color","backgroundColor"));n!==null&&(r.backgroundColor=n);let o=T(Te(e,"border_color","borderColor"));o!==null&&(r.borderColor=o);let i=ni(Te(e,"border_radius","borderRadius"));i!==null&&(r.borderRadius=i);let a=T(Te(e,"text_color","textColor"));return a!==null&&(r.textColor=a),Object.keys(r).length===0?null:Object.freeze(r)}t(ti,"parseSlot");function Sn(e,r){return r===null||Object.keys(r).length===0?e??ei:e===null||Object.keys(e).length===0?r:Object.freeze({...e,...r})}t(Sn,"mergeThemeSlots");var oi=3;function ii(e,r){return e===void 0?r:r.length===0?[e]:r.map(n=>H(e,n)??n)}t(ii,"seatsOf");function ai(e,r){let n=ie(e);return e.every(o=>R(n,o)>=r)}t(ai,"someInkReads");function si(e,r){let n=r[0];return n===void 0?null:H(e,n)}t(si,"collapseUnsatisfiableFill");function li(e){let r=oe(e[0],S);return e.every(n=>R(r,n)>=S)?r:ie(e)}t(li,"inkFor");function Fn(e,r){let n=false,o={};for(let i of Z){let a=e[i];if(a===void 0)continue;let s=a.backgroundColor,l=r?.[i]??[],u=ii(s,l),d={...a},f=false;if(s!==void 0&&u.length>1&&!ai(u,S)){let c=si(s,l);c!==null&&(d.backgroundColor=c,u=[c],f=true);}if(u.length>0){let c=a.textColor;if(s!==void 0)(c===void 0||u.some(p=>R(c,p)<S))&&(d.textColor=li(u),f=true);else if(c!==void 0){let p=K(c,u,ie(u),S);p!==c&&(d.textColor=p,f=true);}if(a.borderColor!==void 0){let p=K(a.borderColor,u,ie(u),oi);p!==a.borderColor&&(d.borderColor=p,f=true);}}o[i]=f?Object.freeze(d):a,n=n||f;}return n?Object.freeze(o):e}t(Fn,"guardSlotContrast");var On=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),se="slots.",An=Object.freeze([1,2]);function ke(e){return Object.keys(e).every(r=>r==="schemaVersion"||(e[r]??null)===null)}t(ke,"isEmptyBranding");function In(e){let r=e?.schemaVersion??null;return r===null||An.includes(r)}t(In,"isKnownBrandingSchema");function Pn(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}t(Pn,"lockedFieldsOf");function ui(e){return e==="hide_powered_by"||On.includes(e)?true:e.startsWith(se)&&Z.includes(e.slice(se.length))}t(ui,"isThemeLockName");function G(e){if(e===null||typeof e!="object")return null;let r=e,n={displayName:W(g(r,"display_name","displayName")),logoUrl:W(g(r,"logo_url","logoUrl")),primaryColor:T(g(r,"primary_color","primaryColor")),accentColor:T(g(r,"accent_color","accentColor")),brightness:pi(g(r,"brightness","color_scheme","colorScheme")),fontFamily:W(g(r,"font_family","fontFamily")),fontUrl:W(g(r,"font_url","fontUrl")),fonts:xn(g(r,"fonts")),fontUrls:xn(g(r,"font_urls","fontUrls")),placeholder:W(g(r,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:di(g(r,"hide_powered_by","hidePoweredBy")),primaryColorDark:T(g(r,"primary_color_dark","primaryColorDark")),accentColorDark:T(g(r,"accent_color_dark","accentColorDark")),surfaceStyle:wn(g(r,"surface_style","surfaceStyle"),ci),radiusScale:wn(g(r,"radius_scale","radiusScale"),fi),logoUrlDark:W(g(r,"logo_url_dark","logoUrlDark")),slots:kn(g(r,"slots")),accessibilityMaxFontScale:mi(g(r,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:bi(g(r,"locked_fields","lockedFields")),schemaVersion:gi(g(r,"schema_version","schemaVersion"))};return ke(n)?null:Object.freeze(n)}t(G,"parseClientBranding");function di(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let r=e.trim().toLowerCase();if(r==="true")return true;if(r==="false")return false}return null}t(di,"parseBool");function g(e,...r){for(let n of r)if(Object.prototype.hasOwnProperty.call(e,n)){let o=e[n];if(o!==void 0)return o}}t(g,"pick");function W(e){if(typeof e!="string")return null;let r=e.trim();return r.length===0?null:r}t(W,"parseNonEmptyString");var le=["regular","medium","bold","mono","monoMedium","monoBold"];function xn(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let r=e,n={};for(let o of le){let i=W(g(r,o));i!==null&&(n[o]=i);}return Object.keys(n).length===0?null:Object.freeze(n)}t(xn,"parseFaceMap");var ci=["white","cream","subtle"],fi=["sharp","default","round"];function wn(e,r){if(typeof e!="string")return null;let n=e.trim().toLowerCase();return r.includes(n)?n:null}t(wn,"parseEnum");function pi(e){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return r==="light"||r==="dark"||r==="auto"?r:null}t(pi,"parseBrightness");function Dn(e){let r=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(r)&&(typeof e!="string"||e.trim().length>0)?r:null}t(Dn,"parseNumber");var yi=1,Mn=3.1;function mi(e){let r=Dn(e);return r===null?null:r<=0?0:Math.min(Mn,Math.max(yi,r))}t(mi,"parseMaxFontScale");function gi(e){if(e==null)return null;let r=Dn(e);return r!==null&&Number.isInteger(r)&&r>=1?r:0}t(gi,"parseSchemaVersion");function ar(e){let r=e.trim();return r.startsWith(se)?r:r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}t(ar,"toWireName");function bi(e){if(!Array.isArray(e))return null;let r=[];for(let n of e){if(typeof n!="string")continue;let o=ar(n);ui(o)&&!r.includes(o)&&r.push(o);}return r.length===0?null:Object.freeze(r)}t(bi,"parseLockedFields");function sr(e){if(e===null)return null;let r=e.trim();return r.length===0?null:/^https:\/\/\S+$/i.test(r)?r:null}t(sr,"hardenHttpsUrl");function Ln(e,r){if(r===null||ke(r))return e;let n=(r.brightness==="light"||r.brightness==="dark")&&r.brightness!==e.brightness?r.brightness==="dark"?Ce:ae:e,o=n.brightness==="dark"?Ce:ae,i=n.brightness==="dark",a=i?r.primaryColorDark??Nn(r.primaryColor):r.primaryColor,s=i?r.accentColorDark??Nn(r.accentColor):r.accentColor,l=a??n.color.primary,u=s??n.color.accent,d=a!==null&&Ri(r,l,o,i),f=d?o.color.primary:l,c=a!==null&&!d?_(f):null,p=t(F=>Math.round(F+(255-F)*.4),"lift"),m=c!==null?{brand:f,bubbleUser:f,brandInk:f,text:{...n.color.text,secondary:f},brandSoft:`rgba(${c.r}, ${c.g}, ${c.b}, 0.10)`,brandSofter:`rgba(${c.r}, ${c.g}, ${c.b}, 0.15)`,brandBorder:`rgba(${c.r}, ${c.g}, ${c.b}, 0.20)`,borderHairlineGreen:`rgba(${c.r}, ${c.g}, ${c.b}, 0.28)`,brandBorderStrong:`rgba(${c.r}, ${c.g}, ${c.b}, 0.55)`,composerBorder:`rgba(${c.r}, ${c.g}, ${c.b}, 0.75)`,accentEdge:`rgb(${p(c.r)}, ${p(c.g)}, ${p(c.b)})`}:d?Ci(o,n.color.text):{},h={brightness:n.brightness,highContrast:n.highContrast,meta:{displayName:r.displayName??n.meta.displayName,logoUrl:(i?r.logoUrlDark??r.logoUrl:r.logoUrl)??n.meta.logoUrl,placeholder:r.placeholder??n.meta.placeholder,hidePoweredBy:r.hidePoweredBy??n.meta.hidePoweredBy},color:{...n.color,...m,..._i(r.surfaceStyle??null,o),primary:f,accent:u,onPrimary:n.color.onPrimary,onAccent:n.color.onAccent},space:n.space,radius:ki(r.radiusScale??null,n.radius,o),type:{...n.type,...vi(n.type,r),maxScale:r.accessibilityMaxFontScale??n.type.maxScale},motion:n.motion,slots:Sn(n.slots,r.slots??null)};return A(h)}t(Ln,"withServerBranding");var hi={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},Ei=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function lr(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}t(lr,"isMonoFace");function vi(e,r){let n=r.fonts??{},o=r.fontUrls??{},i={...e.families},a={...e.namedFaces},s={...e.fontUrls};for(let l of le){let u=hi[l].map(c=>n[c]).find(c=>c!==void 0),d=lr(l)?null:r.fontFamily;u!==void 0?(i[l]=u,a[l]=true):d!==null&&(i[l]=d,a[l]=false);let f=o[l]??(l==="regular"?r.fontUrl:null)??null;f!==null?s[l]=f:u!==void 0&&delete s[l];}for(let l of Ei)for(let u of l)a[u]&&l.some(d=>d!==u&&i[d]===i[u])&&(a[u]=false);return {family:i.regular,mono:i.mono,fontUrl:s.regular??null,families:i,namedFaces:a,fontUrls:s}}t(vi,"mergeFaces");function Nn(e){return e===null?null:Cn(e)}t(Nn,"darkVariantOf");function _i(e,r){if(e===null)return {};let n=r.color;return {chatGround:e==="white"?n.surface:e==="subtle"?n.surfaceSubtle:n.surfaceCream}}t(_i,"surfaceOf");function zn(e,r){return e==null?false:T(e)===T(r)}t(zn,"sameColor");function Ri(e,r,n,o){return zn(r,n.color.primary)?true:o&&(e.primaryColorDark??null)===null&&zn(e.primaryColor,ae.color.primary)}t(Ri,"isCompiledPrimary");function Ci(e,r){let n=e.color;return {text:{...r,secondary:n.text.secondary},brand:n.brand,bubbleUser:n.bubbleUser,brandInk:n.brandInk,brandSoft:n.brandSoft,brandSofter:n.brandSofter,brandBorder:n.brandBorder,borderHairlineGreen:n.borderHairlineGreen,brandBorderStrong:n.brandBorderStrong,composerBorder:n.composerBorder,accentEdge:n.accentEdge}}t(Ci,"compiledBrandFamily");var Ti={sharp:.5,default:1,round:1.5};function ki(e,r,n){if(e===null)return r;let o=Ti[e],i=n.radius,a=t(s=>Math.round(s*o),"s");return {tile:a(i.tile),xs:a(i.xs),sm:a(i.sm),md:a(i.md),lg:a(i.lg),xl:a(i.xl),pill:i.pill}}t(ki,"radiusOf");var Si="Everfur",Fi=.5;function xi(e){let r=e?.branding??null,n=In(r)?r:null,o=Ii(e?.clientOverride??null,Pn(n)),i=e?.colorScheme==="dark"?"dark":"light",a=o?.brightness??n?.brightness??"light",u=Ln((a==="auto"?i:a)==="dark"?Ce:ae,Bn(n)),d=Ln(u,Bn(o));return Hi(d,e)}t(xi,"resolveTheme");function El(e,r,n){return xi({...n,branding:G(r),clientOverride:G(e)})}t(El,"previewTheme");function wi(e){return e==="placeholder"?"chat_placeholder":ar(e)}t(wi,"wireNameOf");var Oi={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"]};function Ai(e,r){return r.has(wi(e))?true:(Oi[e]??[]).some(n=>r.has(n))}t(Ai,"isLocked");function Ii(e,r){if(e===null)return null;let n=false,o={...e};for(let s of Object.keys(e))(e[s]??null)!==null&&(Ai(s,r)||s==="lockedFields")&&(o[s]=null,n=true);let i=o.slots??null;if(i!==null){let s={},l=false;for(let u of Z){let d=i[u];d!==void 0&&(r.has(`${se}${u}`)?l=true:s[u]=d);}l&&(o.slots=Object.keys(s).length===0?null:Object.freeze(s),n=true);}if(!n)return e;let a=Object.freeze(o);return ke(a)?null:a}t(Ii,"withoutFields");function Bn(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}t(Bn,"withoutBrightness");function Pi(e,r){if(r===1)return e;let n={};for(let[o,i]of Object.entries(e))n[o]=Math.round(i*r*10)/10;return n}t(Pi,"scaledSizes");function Di(e){return e===void 0||!Number.isFinite(e)?1:Math.max(Fi,e)}t(Di,"effectiveScale");var jn=["content","heading","control","compact","badge"];function Mi(e){if(!(e>0))return Re;let r={};for(let n of jn){let o=Re[n];r[n]=o===0?0:Math.min(o,e);}return r}t(Mi,"tierCaps");function Li(e,r){return r>0?Math.min(e,r):e}t(Li,"capped");function Ni(e,r,n,o){let i={};for(let a of jn)i[a]=o?Pi(e,Li(r,n[a])):e;return i}t(Ni,"sizesByTier");function zi(e){return e==="dark"?"#FFFFFF":"#000000"}t(zi,"inkPole");function Bi(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}t(Bi,"textGrounds");function Un(e){return [e.chatGround,e.surface,e.surfaceCream]}t(Un,"linkGrounds");function ji(e){return {composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Un(e)}}t(ji,"slotGrounds");function Ui(e,r){try{let n=e(r);return n===!0||n===!1?n:null}catch{return null}}t(Ui,"registration");function qi(e,r){let n=r?.isFontRegistered,o=r?.platformMonoFamily?.trim()||null;if(n===void 0&&o===null)return {family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces};let i={...e.families},a={...e.namedFaces};for(let s of le)!(i[s]===$||i[s]===L)&&n!==void 0&&Ui(n,i[s])===false&&(i[s]=lr(s)?L:$,a[s]=false),o!==null&&lr(s)&&i[s]===L&&(i[s]=o);return {family:i.regular,mono:i.mono,families:i,namedFaces:a}}t(qi,"platformFaces");function Hi(e,r){let n=e.color.primary,o=e.color.accent,i=e.meta.displayName.trim().length===0?Si:e.meta.displayName,a=sr(e.meta.logoUrl),s={};for(let V of le){let ye=e.type.fontUrls[V];ye!==void 0&&(s[V]=sr(ye));}let l=s.regular??null,d=r?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,f=Number.isFinite(e.type.maxScale)?e.type.maxScale:or,c=Di(r?.textScale),p=Mi(f),m=Ni(e.type.size,c,p,r?.scaleTypeSizes===true),h=e.color,F=zi(e.brightness),ce=Bi(h),fe={...h,primary:n,accent:o,onPrimary:oe(n,S),onAccent:oe(o,S),brandInk:K(h.brandInk,ce,F,S),linkInk:K(e.slots.link?.textColor??o,Un(h),F,S),text:{...h.text,secondary:K(h.text.secondary,ce,F,S)}},pe={brightness:e.brightness,highContrast:false,meta:{displayName:i,logoUrl:a,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:fe,space:e.space,radius:e.radius,type:{...e.type,...qi(e.type,r),fontUrl:l,fontUrls:s,size:m.content,tierSizes:m,scale:c,maxScale:f,scaleCaps:p},motion:d,slots:Fn(e.slots,ji(fe))};return r?.highContrast===true?Tn(A(pe)):A(pe)}t(Hi,"finalize");var qn="/widget/v1/entitlements",Ki=304,$i=Object.freeze({kind:"notModified"});async function kl(e,r={},n=M({auth:e})){let o=await n.send("entitlements.fetch",Gi(r));return o.ok?Yi(o.value):o.error.httpStatus===Ki?$i:{kind:"failed",error:o.error}}t(kl,"fetchEntitlements");var Wi=64;function Gi(e){let r={};return ur(e.cachedRevision)&&(r["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Wi?{method:"GET",path:qn,headers:r,query:{region:e.region}}:{method:"GET",path:qn,headers:r}}t(Gi,"buildRequest");function Yi(e){if(e===null||typeof e!="object"||!ur(e.revision))return Hn();let r=typeof e.region=="string"?e.region:"",n=ur(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:r,ttlSeconds:n,decisions:Xi(e.capabilities),branding:Vi(e)})}t(Yi,"parseUpdated");function Vi(e){let r=G(e.branding);if(r!==null)return r;let n=e.render_hints;if(n!==null&&typeof n=="object"){let o=G(n.branding);return o!==null?o:G(n)}return null}t(Vi,"parseBranding");function Xi(e){if(e===null||typeof e!="object")return Object.freeze([]);let r=[];for(let[n,o]of Object.entries(e))Qi(o)&&r.push(Object.freeze({resource:n,granted:true}));return Object.freeze(r)}t(Xi,"mapCapabilities");function Qi(e){return typeof e=="object"&&e!==null&&e.enabled===true}t(Qi,"isEnabled");function Hn(){return {kind:"failed",error:C("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}t(Hn,"malformed");function ur(e){return typeof e=="number"&&Number.isFinite(e)}t(ur,"isFiniteNumber");var Ji=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function Zi(e,r){let n=e.type,o=n.families[r];return r==="mono"||n.namedFaces[r]?{fontFamily:o}:{fontFamily:o,fontWeight:n.weight[Ji[r]]}}t(Zi,"face");var Kn=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function $n(e){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Kn,r)?Kn[r]:null}t($n,"canonicalPetSpecies");var Wn=50,ea=128,dr=120,Gn=120,ra=2e3,Yn=120,na=80,Qn=new Set(["male","female","unknown"]),Jn=new Set(["day","month","year"]),Zn=new Set(["low","medium","high","athletic"]),et=new Set(["indoor","outdoor","both"]),rt=new Set(["mild","moderate","severe"]),ta=/^(\d{4})-(\d{2})-(\d{2})$/,nt=[["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"]],tt=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...nt,...tt].map(([e])=>e));function oa(e){let r=ta.exec(e);if(r===null)return false;let[n,o,i]=[Number(r[1]),Number(r[2]),Number(r[3])],a=new Date(Date.UTC(n,o-1,i));return a.getUTCFullYear()===n&&a.getUTCMonth()===o-1&&a.getUTCDate()===i}t(oa,"isRealDate");var de=t(e=>(r,n)=>typeof n=="string"&&e.has(n)?null:`${r} must be one of ${[...e].join(", ")}`,"oneOf"),ia=t((e,r)=>typeof r=="boolean"?null:`${e} must be true or false`,"boolean"),Fe=t((e,r)=>typeof r=="string"&&oa(r)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),x=t((e,r={})=>(n,o)=>{if(typeof o!="string")return `${n} must be a string`;if(Q(o))return `${n} contains an unpaired surrogate and cannot be encoded`;let i=r.trimmed?o.trim():o;if(r.required&&i.length===0)return `${n} is required and must not be blank`;let a=B(i);return a<=e?null:`${n} is ${a} characters; the server accepts at most ${e}`},"text"),aa={sex:de(Qn),spayedNeutered:ia,birthDate:Fe,birthDatePrecision:de(Jn),activityLevel:de(Zn),indoorOutdoor:de(et),foodBrand:x(Yn),foodType:x(Yn),microchipId:x(na)},cr=["ref","ref",false,x(ea,{required:true,trimmed:true})],fr=["notes","notes",false,x(ra,{trimmed:true})],Vn=[cr,["name","name",true,x(dr,{required:true,trimmed:true})],["dose","dose",false,x(Gn,{trimmed:true})],["frequency","frequency",false,x(Gn,{trimmed:true})],["startDate","start_date",false,Fe],["endDate","end_date",false,Fe],fr],sa={allergies:[cr,["allergen","allergen",true,x(dr,{required:true,trimmed:true})],["severity","severity",false,de(rt)],fr],medications:Vn,supplements:Vn,conditions:[cr,["conditionName","condition_name",true,x(dr,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Fe],fr]};function la(e,r,n){let o=`${e}[${r}]`;if(typeof n!="object"||n===null||Array.isArray(n))return {error:`${o} must be an object`};let i=n,a={};for(let[u,d,f,c]of sa[e]){let p=i[u];if(p==null){if(f)return {error:`${o}.${u} is required`};p===null&&(a[d]=null);continue}let m=c(`${o}.${u}`,p);if(m!==null)return {error:m};a[d]=p;}let s=a.start_date,l=a.end_date;return typeof s=="string"&&typeof l=="string"&&l<s?{error:`${o}.endDate must not be before startDate`}:{item:a}}t(la,"itemToWire");function ua(e,r){if(!Array.isArray(r))return {error:`${e} must be an array (send [] to clear it)`};if(r.length>Wn)return {error:`${e} has ${r.length} items; the server accepts at most ${Wn}`};let n=[],o=new Set;for(let i=0;i<r.length;i+=1){let a=la(e,i,r[i]);if("error"in a)return a;let s=a.item.ref;if(typeof s=="string"){let l=s.trim();if(o.has(l))return {error:`${e}: ref ${JSON.stringify(l)} is used twice; a ref names one item`};o.add(l);}n.push(a.item);}return {items:n}}t(ua,"listToWire");function ot(e,r){let n=e,o={};for(let[s,l]of nt){let u=n[s];if(u!==void 0){if(u!==null){let d=aa[s](s,u);if(d!==null)return {error:d}}o[l]=u;}}let i=n.birthDate!==void 0,a=n.birthDatePrecision!==void 0;if(i!==a||i&&n.birthDate===null!=(n.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[s,l]of tt){let u=n[s];if(u===void 0)continue;let d=ua(s,u);if("error"in d)return d;o[l]=d.items;}return Object.keys(o).length>0&&r!==void 0&&$n(r)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:o}}t(ot,"petHealthToWire");var b=t(e=>typeof e=="string"?e:null,"str"),ue=t((e,r)=>typeof r=="string"&&e.has(r)?r:null,"pick"),da=t(e=>typeof e=="boolean"?e:null,"bool");function Se(e,r){return Array.isArray(e)?Object.freeze(e.flatMap(n=>{if(typeof n!="object"||n===null||Array.isArray(n))return [];let o=r(n);return o===null?[]:[o]})):Object.freeze([])}t(Se,"itemsFromWire");function Xn(e){let r=b(e.name);return r===null||r.length===0?null:Object.freeze({ref:b(e.ref),name:r,dose:b(e.dose),frequency:b(e.frequency),startDate:b(e.start_date),endDate:b(e.end_date),notes:b(e.notes)})}t(Xn,"medicationFromWire");function it(e){let r=e.profile_version;return Object.freeze({profileVersion:typeof r=="number"&&Number.isInteger(r)&&r>=0?r:0,sex:ue(Qn,e.sex),spayedNeutered:da(e.spayed_neutered),birthDate:b(e.birth_date),birthDatePrecision:ue(Jn,e.birth_date_precision),activityLevel:ue(Zn,e.activity_level),indoorOutdoor:ue(et,e.indoor_outdoor),foodBrand:b(e.food_brand),foodType:b(e.food_type),microchipId:b(e.microchip_id),allergies:Se(e.allergies,n=>{let o=b(n.allergen);return o===null||o.length===0?null:Object.freeze({ref:b(n.ref),allergen:o,severity:ue(rt,n.severity),notes:b(n.notes)})}),medications:Se(e.medications,Xn),supplements:Se(e.supplements,Xn),conditions:Se(e.conditions,n=>{let o=b(n.condition_name);return o===null||o.length===0?null:Object.freeze({ref:b(n.ref),conditionName:o,diagnosedDate:b(n.diagnosed_date),notes:b(n.notes)})})})}t(it,"petHealthFromWire");var pr=100,yr=50,mr=100,gr=50,br=500,ca=128,fa=6e4;function O(e){return C("validationFailed",{retryable:false,wireMessage:e})}t(O,"invalid");function Y(e,r,n){if(typeof r!="string")return O(`${e} must be a string`);let o=B(r);return o<=n?null:O(`${e} is ${o} characters; the server accepts at most ${n}`)}t(Y,"checkString");function xe(e,r,n){return typeof r=="number"&&Number.isFinite(r)&&r>=0&&r<=n?null:O(`${e} must be a finite number between 0 and ${n}`)}t(xe,"outOfRange");function at(e,r){if(typeof e!="string")return O("pet_ref must be a string");if(e.trim().length===0)return O("pet_ref must not be blank");if(Q(e))return O("pet_ref contains an unpaired surrogate and cannot be encoded");if(r!=null&&typeof r!="object")return O("profile must be an object");let n=[Y("pet_ref",e,ca)];return r?.name!==void 0&&n.push(Y("name",r.name,pr)),r?.species!==void 0&&n.push(Y("species",r.species,yr)),r?.breed!==void 0&&n.push(Y("breed",r.breed,mr)),r?.ageYears!==void 0&&n.push(xe("age_years",r.ageYears,gr)),r?.weightKg!==void 0&&n.push(xe("weight_kg",r.weightKg,br)),n.find(o=>o!==null)??null}t(at,"validate");function lt(e,r){let n=ot(e,r);return "error"in n?{error:O(n.error)}:n}t(lt,"healthToWire");function pa(e){if(typeof e!="object"||e===null)return {error:O("patch must be an object")};let r=e,n=[["name","name",a=>Y("name",a,pr)],["species","species",a=>Y("species",a,yr)],["breed","breed",a=>Y("breed",a,mr)],["ageYears","age_years",a=>xe("age_years",a,gr)],["weightKg","weight_kg",a=>xe("weight_kg",a,br)]],o={};for(let[a,s,l]of n){let u=r[a];if(u!==void 0){if(u!==null){let d=l(u);if(d!==null)return {error:d}}o[s]=u;}}let i=lt(r,r.species);return "error"in i?i:(Object.assign(o,i.body),Object.keys(o).length===0?{error:O("patch must change at least one field")}:{body:o})}t(pa,"patchToWire");function ya(e){if(e==null)return {body:{}};let r=lt(e,e.species);return "error"in r?r:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...r.body}}}t(ya,"toWire");var w=t(e=>typeof e=="string"?e:null,"str"),we=t(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function st(e,r){let n=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:w(n.pet_ref)??r,name:w(n.name),species:w(n.species),breed:w(n.breed),ageYears:we(n.age_years),weightKg:we(n.weight_kg)})}t(st,"fromWire");function hr(e){if(typeof e!="object"||e===null)return null;let r=e,n=w(r.pet_ref);return n===null||n.length===0?null:Object.freeze({petId:w(r.pet_id),petRef:n,name:w(r.name),species:w(r.species),breed:w(r.breed),ageYears:we(r.age_years),weightKg:we(r.weight_kg),updatedAt:w(r.updated_at)})}t(hr,"widgetPetFromWire");function ma(e){let r=hr(e);return r===null?null:Object.freeze({...r,...it(e)})}t(ma,"widgetPetProfileFromWire");function ga(e){let r=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(r.flatMap(n=>{let o=hr(n);return o===null?[]:[o]}))}t(ga,"petListFromWire");function ba(e){return ha(M({auth:e}),M({auth:e,unaryTimeoutMs:fa}))}t(ba,"createPetsRepository");function ha(e,r=e){let n=t((i,a)=>a?{...i,signal:a}:i,"withSignal"),o=t(i=>at(i,void 0)??`/widget/v1/pets/${encodeURIComponent(i)}`,"petPath");return {async list(i){let a=await e.send("pets.list",n({method:"GET",path:"/widget/v1/pets"},i?.signal));return a.ok?k(ga(a.value)):y(a.error)},async registerPet(i,a,s){let l=at(i,a);if(l!==null)return y(l);let u=ya(a);if("error"in u)return y(u.error);let f={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(i)}`,body:u.body},c=await e.send("pets.registerPet",s?.signal?{...f,signal:s.signal}:f);return c.ok?k(st(c.value,i)):y(c.error)},async updatePet(i,a,s){let l=o(i);if(typeof l!="string")return y(l);let u=pa(a);if("error"in u)return y(u.error);let d=await e.send("pets.updatePet",n({method:"PATCH",path:l,body:u.body},s?.signal));return d.ok?k(st(d.value,i)):y(d.error)},async getPetProfile(i,a){let s=o(i);if(typeof s!="string")return y(s);let l=await e.send("pets.getPetProfile",n({method:"GET",path:`${s}/profile`},a?.signal));if(!l.ok)return y(l.error);let u=ma(l.value);return u===null?y(C("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):k(u)},async deletePet(i,a){let s=o(i);if(typeof s!="string")return y(s);let l=await e.send("pets.deletePet",n({method:"DELETE",path:s},a?.signal));return l.ok?k(void 0):y(l.error)},async eraseUserData(i){let a=await r.send("pets.eraseUserData",n({method:"DELETE",path:"/widget/v1/me"},i?.signal),{maxAttempts:1});return a.ok?k(void 0):y(a.error)}}}t(ha,"createPetsRepositoryOver");var vr=Object.freeze(["better","same","worse"]),Ea=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ut(e){return y(C("validationFailed",{retryable:false,wireMessage:e}))}t(ut,"invalid");function Er(){return y(C("internalError",{retryable:false}))}t(Er,"malformed");function dt(e){return typeof e!="string"||e.trim().length===0?C("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):Q(e)?C("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}t(dt,"petPath");var I=t(e=>typeof e=="string"?e:null,"str");function ct(e){if(typeof e!="object"||e===null)return null;let r=e,n=I(r.case_id),o=I(r.status);if(n===null||o===null)return null;let i=I(r.last_response);return Object.freeze({caseId:n,status:o,bodyLocation:I(r.body_location),lastResponse:i!==null&&vr.includes(i)?i:null,checkInDueAt:I(r.check_in_due_at),openedAt:I(r.opened_at),resolvedAt:I(r.resolved_at),resolutionText:I(r.resolution_text)})}t(ct,"caseFromWire");function va(e){return _a(M({auth:e}))}t(va,"createCasesRepository");function _a(e){return {async list(r,n){let o=dt(r);if(typeof o!="string")return y(o);let i=await e.send("cases.list",{method:"GET",path:o,...n?.signal?{signal:n.signal}:{}});if(!i.ok)return y(i.error);let a=typeof i.value=="object"&&i.value!==null?i.value.cases:null;if(!Array.isArray(a))return Er();let s=a.map(ct);return s.every(l=>l!==null)?k(Object.freeze(s)):Er()},async checkin(r,n,o,i){let a=dt(r);if(typeof a!="string")return y(a);if(typeof n!="string"||!Ea.test(n))return ut("case_id must be a UUID");if(!vr.includes(o))return ut("response must be one of better, same, worse");let s=await e.send("cases.checkin",{method:"POST",path:`${a}/${n}/checkin`,body:{response:o},...i?.signal?{signal:i.signal}:{}});if(!s.ok)return y(s.error);let l=typeof s.value=="object"&&s.value!==null?s.value:{},u=ct(l.case);return u===null?Er():k(Object.freeze({case:u,ctaDeepLink:I(l.cta_deep_link)}))}}}t(_a,"createCasesRepositoryOver");export{ht as AUTO_RETRYABLE_CODES,vt as BACKOFF_BASE_MS,De as BACKOFF_CAP_MS,vr as CHECKIN_ANSWERS,Tr as CONTRACT_ERROR_ROWS,Ho as DARK_VARIANT_GROUND,ir as DARK_VARIANT_LIGHTNESS_CEILING,Ko as DARK_VARIANT_LIGHTNESS_FLOOR,$o as DARK_VARIANT_LIGHTNESS_STEP,vn as DARK_VARIANT_TARGET_RATIO,kt as DEFAULT_CONTRACT_VERSION,or as DEFAULT_MAX_FONT_SCALE,Cr as DOC_SITE_ORIGIN,nr as EASING_CURVES,vs as EMPTY_FRAME_ARRAYS,qn as ENTITLEMENTS_PATH,Ir as ENV_API_BASE_URL,Ce as EVERFUR_DARK,Aa as EVERFUR_ERROR_CATEGORIES,Oa as EVERFUR_ERROR_CODES,ae as EVERFUR_LIGHT,E as EverfurConfigError,Le as EverfurThrownError,Vo as HIGH_CONTRAST_TARGET_RATIO,On as LOCKABLE_THEME_FIELDS,Mn as MAX_FONT_SCALE_CEILING,wr as MAX_RETRY_ATTEMPTS,gr as PET_AGE_YEARS_MAX,mr as PET_BREED_MAX,pr as PET_NAME_MAX,yr as PET_SPECIES_MAX,br as PET_WEIGHT_KG_MAX,Et as RETRYABLE_CONTRACT_CODES,Tt as SDK_PLATFORM,Ct as SDK_VERSION,se as SLOT_LOCK_PREFIX,oi as SLOT_MIN_BORDER_CONTRAST,S as SLOT_MIN_CONTRAST,$ as SYSTEM_FONT_FAMILY,L as SYSTEM_MONO_FAMILY,Fi as TEXT_SCALE_FLOOR,Re as TEXT_SCALE_TIER_CAPS,An as THEME_SCHEMA_VERSIONS,sl as THEME_SLOT_KEYS,Z as THEME_SLOT_NAMES,Br as acceptedFrame,Kr as analysisCompleteFrame,Hr as analysisStartedFrame,Es as assertNever,zt as authHeaders,zr as authedSend,Or as backoffDelayMs,Ds as bufferedTextByteSource,Dr as buildBaseHeaders,Pa as canRecreateOnNotFound,Sr as categoryFor,St as checkPublishableKey,gt as contractDocUrl,ge as contractErrorFor,R as contrastRatio,ns as conversationId,va as createCasesRepository,Ls as createHttpTransport,ms as createIdentityProvider,ba as createPetsRepository,M as createRequestFunnel,tr as cssCubicBezier,qs as decideCapability,A as deepFreeze,Ur as deltaFrame,Us as deniedDecisionsFor,Cn as deriveDarkVariant,Tn as deriveHighContrast,qr as doneFrame,y as err,D as errorFrame,Zr as errorFromResponse,Qt as eventSourceByteSource,to as eventSourceRequestId,Zi as face,Be as fetchByteSource,kl as fetchEntitlements,Fr as fromHttpStatus,X as fromWire,Ue as getGlobalFetch,Fn as guardSlotContrast,sr as hardenHttpsUrl,jr as heartbeatFrame,z as isAutoRetryable,ke as isEmptyBranding,Ua as isErr,In as isKnownBrandingSchema,ja as isOk,xr as isRetryableCode,Pn as lockedFieldsOf,C as makeEverfurError,Sn as mergeThemeSlots,ve as networkError,gs as newSessionId,k as ok,G as parseClientBranding,T as parseColor,Ee as parseSse,kn as parseThemeSlots,es as petRef,El as previewTheme,kr as publishedDocUrl,cn as readableOn,je as requestIdOf,eo as requestJson,Ms as requestRaw,uo as requires,Ga as resolveApiBaseUrl,Wa as resolveClientConfig,js as resolveEntitlements,xi as resolveTheme,Ia as shouldRetry,Pr as tryResolveApiBaseUrl,Ft as tryResolveClientConfig,$r as unknownFrame,ss as unsafeClientId,is as unsafeConversationId,ls as unsafeDocumentId,us as unsafeJobId,ts as unsafePetRef,ds as unsafeRecordsRequestId,as as unsafeResponseId,os as unsafeUserRef,qa as unwrap,Me as userFacingError,rs as userRef,hr as widgetPetFromWire,te as withAuthHeaders,Ln as withServerBranding};
|