@everfur/sdk 0.18.1 → 0.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +7 -5
  3. package/dist/{Chat.d-C2ddC2u7.d.cts → Chat.d-BEbRI8FZ.d.cts} +1 -1
  4. package/dist/{Chat.d-Bz4iJ7d2.d.ts → Chat.d-CKKuXVw5.d.ts} +1 -1
  5. package/dist/{DepthViews.d-Chjs8H9V.d.cts → DepthViews.d-BiePRa3Z.d.cts} +1 -1
  6. package/dist/{DepthViews.d-pFL_ZBZT.d.cts → DepthViews.d-Chn2xwZu.d.cts} +1 -1
  7. package/dist/{DepthViews.d-qXt9OMgz.d.ts → DepthViews.d-CiU4f98J.d.ts} +1 -1
  8. package/dist/{DepthViews.d-C6-Kzs6H.d.ts → DepthViews.d-_WMIpymE.d.ts} +1 -1
  9. package/dist/{IntakeMedia.d-4a89XrP7.d.ts → IntakeMedia.d-B_ZVDxh3.d.ts} +1 -1
  10. package/dist/{IntakeMedia.d-JJCUvQu7.d.cts → IntakeMedia.d-CnGzpllr.d.cts} +1 -1
  11. package/dist/{IntakeMedia.d-DGxrhgIW.d.ts → IntakeMedia.d-DNUAks9E.d.ts} +1 -1
  12. package/dist/{IntakeMedia.d-DUPR4lVM.d.cts → IntakeMedia.d-Dqc5V_YH.d.cts} +1 -1
  13. package/dist/{RecordsPage.d-sNRolVdy.d.ts → RecordsPage.d-CRRJM35Q.d.ts} +1 -1
  14. package/dist/{RecordsPage.d-Cmny6Q7g.d.cts → RecordsPage.d-CtNzoxre.d.cts} +1 -1
  15. package/dist/animations/index.d.cts +3 -3
  16. package/dist/animations/index.d.ts +3 -3
  17. package/dist/{appStateLifecycle.d-Bt70TQog.d.cts → appStateLifecycle.d-BQcy4J5O.d.cts} +3 -3
  18. package/dist/{appStateLifecycle.d-Jdg9_PFt.d.ts → appStateLifecycle.d-JuPhh7Oy.d.ts} +3 -3
  19. package/dist/{attachments.d-CF4_n-DZ.d.cts → attachments.d-BLEOCUU7.d.cts} +2 -2
  20. package/dist/{attachments.d-BVp3r6Ms.d.cts → attachments.d-CeXw6R7_.d.cts} +5 -5
  21. package/dist/{attachments.d-DsUZpMad.d.ts → attachments.d-DRkqNR-o.d.ts} +2 -2
  22. package/dist/{attachments.d-DnSCMjH0.d.ts → attachments.d-d1rWAw9K.d.ts} +5 -5
  23. package/dist/{bookingCopy.d-BHqE9Ozq.d.cts → bookingCopy.d-CoiNXrY8.d.cts} +10 -3
  24. package/dist/{bookingCopy.d-Ca4AQGZ7.d.ts → bookingCopy.d-CrUufdoE.d.ts} +10 -3
  25. package/dist/{casesRepository.d-VzxEyq2N.d.ts → casesRepository.d-DhI69yuj.d.ts} +1 -1
  26. package/dist/{casesRepository.d-DFwD2kiS.d.cts → casesRepository.d-OyZOSNNv.d.cts} +1 -1
  27. package/dist/chat/index.d.cts +10 -10
  28. package/dist/chat/index.d.ts +10 -10
  29. package/dist/chat/lite/index.d.cts +10 -10
  30. package/dist/chat/lite/index.d.ts +10 -10
  31. package/dist/client/index.cjs +2 -2
  32. package/dist/client/index.d.cts +6 -6
  33. package/dist/client/index.d.ts +6 -6
  34. package/dist/client/index.js +2 -2
  35. package/dist/{clinicBatch.d-DXDIL1lC.d.ts → clinicBatch.d-CcqnQ7-d.d.ts} +2 -2
  36. package/dist/{clinicBatch.d-CLqaih2C.d.cts → clinicBatch.d-DVahpaN3.d.cts} +2 -2
  37. package/dist/{config.d-cqyvpzDb.d.ts → config.d-KX-EkQ9j.d.ts} +1 -1
  38. package/dist/{config.d-7bCXvOGn.d.cts → config.d-Z_fyOZke.d.cts} +1 -1
  39. package/dist/consent/index.d.cts +5 -5
  40. package/dist/consent/index.d.ts +5 -5
  41. package/dist/{context.d-BeRanUXQ.d.cts → context.d-DV5E_2Fs.d.cts} +5 -5
  42. package/dist/{context.d-DAnmDYGr.d.ts → context.d-DY6d4qXG.d.ts} +5 -5
  43. package/dist/{copy.d-CxFzeuvo.d.ts → copy.d-BPzpKGGc.d.ts} +2 -2
  44. package/dist/{copy.d-BPqs8swm.d.cts → copy.d-CMY9OoCC.d.cts} +2 -2
  45. package/dist/core/index.cjs +1 -1
  46. package/dist/core/index.d.cts +13 -13
  47. package/dist/core/index.d.ts +13 -13
  48. package/dist/core/index.js +1 -1
  49. package/dist/{depth.d-C6XbnFig.d.ts → depth.d-B_qNSgXr.d.ts} +2 -2
  50. package/dist/{depth.d-qHdXHDd-.d.cts → depth.d-qVYPByPb.d.cts} +2 -2
  51. package/dist/{entitlementRepository.d-D_cc7g4l.d.ts → entitlementRepository.d-BXDWPyP8.d.ts} +2 -2
  52. package/dist/{entitlementRepository.d-C6uTDswj.d.cts → entitlementRepository.d-CwTVi7he.d.cts} +2 -2
  53. package/dist/{focus.d-DiWvQR2j.d.ts → focus.d-BPofD7ow.d.ts} +2 -2
  54. package/dist/{focus.d-HSkMHd-i.d.cts → focus.d-DJD4lWFB.d.cts} +2 -2
  55. package/dist/health-plan/index.d.cts +9 -9
  56. package/dist/health-plan/index.d.ts +9 -9
  57. package/dist/{idempotency.d-CF5AvlYp.d.ts → idempotency.d-BVO0mU2R.d.ts} +1 -1
  58. package/dist/{idempotency.d-DrO2zEZO.d.cts → idempotency.d-BmYuCb-n.d.cts} +1 -1
  59. package/dist/{identity.d-84x0dV7-.d.cts → identity.d-3ROlHbnP.d.cts} +1 -1
  60. package/dist/{identity.d-BXztMVYM.d.ts → identity.d-CRVNfZzQ.d.ts} +1 -1
  61. package/dist/index.cjs +1 -1
  62. package/dist/index.d.cts +13 -13
  63. package/dist/index.d.ts +13 -13
  64. package/dist/index.js +1 -1
  65. package/dist/{introEvents.d-Cwv72ER-.d.cts → introEvents.d-DGQDEPJi.d.cts} +1 -1
  66. package/dist/{introEvents.d-DYU3znJs.d.ts → introEvents.d-cvMxJfYd.d.ts} +1 -1
  67. package/dist/notifications/index.d.cts +4 -4
  68. package/dist/notifications/index.d.ts +4 -4
  69. package/dist/{optInView.d-4Hl4HbQh.d.cts → optInView.d-CU1U_K-B.d.cts} +2 -2
  70. package/dist/{optInView.d-pq8tUTf6.d.ts → optInView.d-DIGu47Lz.d.ts} +2 -2
  71. package/dist/{parse.d-D0v06qxx.d.cts → parse.d-GzZJYu__.d.cts} +1 -1
  72. package/dist/{parse.d-BJhhYfkv.d.ts → parse.d-icynBIS-.d.ts} +1 -1
  73. package/dist/{pets.d-C4n-MDC4.d.cts → pets.d-5SMtOAwB.d.cts} +1 -1
  74. package/dist/{pets.d-1_CHpfgB.d.ts → pets.d-BRsbR8QU.d.ts} +1 -1
  75. package/dist/{petsRepository.d-Dd95xh-M.d.cts → petsRepository.d-DEnoZn92.d.cts} +1 -1
  76. package/dist/{petsRepository.d-BuomdFjZ.d.ts → petsRepository.d-DWsChqAS.d.ts} +1 -1
  77. package/dist/{ports.d-Bf3tp7Pn.d.cts → ports.d--OjPUqPb.d.cts} +4 -4
  78. package/dist/{ports.d-ChZHFd-q.d.ts → ports.d-CIfa_XF6.d.ts} +4 -4
  79. package/dist/records/depth/index.d.cts +9 -9
  80. package/dist/records/depth/index.d.ts +9 -9
  81. package/dist/records/index.cjs +1 -1
  82. package/dist/records/index.d.cts +10 -10
  83. package/dist/records/index.d.ts +10 -10
  84. package/dist/records/index.js +1 -1
  85. package/dist/{requestFunnel.d-CWI2pD3V.d.cts → requestFunnel.d-CQX_Z1Hi.d.cts} +2 -2
  86. package/dist/{requestFunnel.d-DcQIAs45.d.ts → requestFunnel.d-DSvCGf4J.d.ts} +2 -2
  87. package/dist/{runtimeTypes.d-rbuONrIv.d.ts → runtimeTypes.d-Be_vhOER.d.ts} +4 -4
  88. package/dist/{runtimeTypes.d-CIOVzjEK.d.cts → runtimeTypes.d-sXpNYnJp.d.cts} +4 -4
  89. package/dist/{screenProps.d-CFZe27oI.d.cts → screenProps.d-BW6PZh5k.d.cts} +1 -1
  90. package/dist/{screenProps.d-yUA4k6yK.d.ts → screenProps.d-DpMK2_gi.d.ts} +1 -1
  91. package/dist/server/events/index.cjs +2 -2
  92. package/dist/server/events/index.d.cts +36 -5
  93. package/dist/server/events/index.d.ts +36 -5
  94. package/dist/server/events/index.js +2 -2
  95. package/dist/server/index.cjs +1 -1
  96. package/dist/server/index.d.cts +3 -3
  97. package/dist/server/index.d.ts +3 -3
  98. package/dist/server/index.js +1 -1
  99. package/dist/shop/index.d.cts +3 -3
  100. package/dist/shop/index.d.ts +3 -3
  101. package/dist/tabs/index.d.cts +6 -6
  102. package/dist/tabs/index.d.ts +6 -6
  103. package/dist/televet/booking/index.cjs +11 -10
  104. package/dist/televet/booking/index.d.cts +13 -11
  105. package/dist/televet/booking/index.d.ts +13 -11
  106. package/dist/televet/booking/index.js +11 -10
  107. package/dist/televet/index.d.cts +3 -3
  108. package/dist/televet/index.d.ts +3 -3
  109. package/dist/{televetGlobal.d-CC-DrqkQ.d.ts → televetGlobal.d-B0_jbCtC.d.ts} +7 -0
  110. package/dist/{televetGlobal.d-CKwDCbmN.d.cts → televetGlobal.d-BWYJR391.d.cts} +7 -0
  111. package/dist/testing/index.cjs +1 -1
  112. package/dist/testing/index.d.cts +1 -1
  113. package/dist/testing/index.d.ts +1 -1
  114. package/dist/testing/index.js +1 -1
  115. package/dist/testing/rn/index.d.cts +7 -7
  116. package/dist/testing/rn/index.d.ts +7 -7
  117. package/dist/testing/web/index.d.cts +7 -7
  118. package/dist/testing/web/index.d.ts +7 -7
  119. package/dist/texting/index.d.cts +5 -5
  120. package/dist/texting/index.d.ts +5 -5
  121. package/dist/{threadOptions.d-CRbFXnlq.d.cts → threadOptions.d-Csmb-XgL.d.cts} +2 -2
  122. package/dist/{threadOptions.d-aK8FkszA.d.ts → threadOptions.d-DMOn3mmj.d.ts} +2 -2
  123. package/dist/{timelineRows.d-BbCLvjy1.d.ts → timelineRows.d-B0XZevKx.d.ts} +1 -1
  124. package/dist/{timelineRows.d-BvA_BoOe.d.cts → timelineRows.d-Kllr7Mcu.d.cts} +1 -1
  125. package/dist/{useHealthPlanSubscription.d-BN40CVK6.d.cts → useHealthPlanSubscription.d-C-c_mQ4u.d.cts} +2 -2
  126. package/dist/{useHealthPlanSubscription.d-BYehTI7R.d.ts → useHealthPlanSubscription.d-bNRntgWe.d.ts} +2 -2
  127. package/dist/{usePresentation.d-C39kKhoO.d.cts → usePresentation.d-BHKhBKQn.d.cts} +1 -1
  128. package/dist/{usePresentation.d-BfcyAEFt.d.ts → usePresentation.d-CmQgbrZr.d.ts} +1 -1
  129. package/dist/{useRecordsDepth.d-B2ewVbRm.d.ts → useRecordsDepth.d-BilHZaR4.d.ts} +1 -1
  130. package/dist/{useRecordsDepth.d-CKXAAHXI.d.cts → useRecordsDepth.d-WW_2cWwU.d.cts} +1 -1
  131. package/dist/{view.d-DTNPjiZ1.d.cts → view.d-BTnjZu2S.d.cts} +3 -3
  132. package/dist/{view.d-BnUDSQXz.d.ts → view.d-BtN_L_UF.d.ts} +3 -3
  133. package/dist/web/consent/index.d.cts +5 -5
  134. package/dist/web/consent/index.d.ts +5 -5
  135. package/dist/web/health-plan/index.d.cts +11 -11
  136. package/dist/web/health-plan/index.d.ts +11 -11
  137. package/dist/web/index.cjs +1 -1
  138. package/dist/web/index.d.cts +23 -23
  139. package/dist/web/index.d.ts +23 -23
  140. package/dist/web/index.js +1 -1
  141. package/dist/web/intro/index.d.cts +6 -6
  142. package/dist/web/intro/index.d.ts +6 -6
  143. package/dist/web/notifications/index.d.cts +3 -3
  144. package/dist/web/notifications/index.d.ts +3 -3
  145. package/dist/web/records/depth/index.d.cts +9 -9
  146. package/dist/web/records/depth/index.d.ts +9 -9
  147. package/dist/web/records/index.d.cts +11 -11
  148. package/dist/web/records/index.d.ts +11 -11
  149. package/dist/web/records-sheet/index.cjs +1 -1
  150. package/dist/web/records-sheet/index.js +1 -1
  151. package/dist/web/shop/index.d.cts +3 -3
  152. package/dist/web/shop/index.d.ts +3 -3
  153. package/dist/web/televet/booking/index.cjs +9 -9
  154. package/dist/web/televet/booking/index.d.cts +18 -11
  155. package/dist/web/televet/booking/index.d.ts +18 -11
  156. package/dist/web/televet/booking/index.js +9 -9
  157. package/dist/web/televet/index.d.cts +3 -3
  158. package/dist/web/televet/index.d.ts +3 -3
  159. package/dist/web/texting/index.d.cts +5 -5
  160. package/dist/web/texting/index.d.ts +5 -5
  161. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
2
  "use strict";var crypto=require("crypto");function ok(value,warning){/* @__PURE__ */
3
3
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
4
- return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var EVERFUR_SIGNATURE_HEADER="Everfur-Signature",DEFAULT_WEBHOOK_TOLERANCE_SECONDS=300,SIGNATURE_SCHEME="v1",MAX_HEADER_LENGTH=4096,HEX_SHA256_LENGTH=64,DIGITS=/^[0-9]+$/,EverfurWebhookVerificationError=class _EverfurWebhookVerificationError extends Error{constructor(code){super(`Everfur webhook verification failed: ${code}`),this.name="EverfurWebhookVerificationError",this.code=code,Object.setPrototypeOf(this,_EverfurWebhookVerificationError.prototype)}};function constructEvent(payload,signatureHeader,secrets,options={}){let body=rawBodyBytes(payload),keys=requireSecrets(secrets),tolerance=options.toleranceSeconds??DEFAULT_WEBHOOK_TOLERANCE_SECONDS;if(!Number.isInteger(tolerance)||tolerance<0)throw new EverfurConfigError("invalid-argument","toleranceSeconds must be a non-negative integer");let parsed=parseSignatureHeader(signatureHeader),now=options.nowSeconds??Math.floor(Date.now()/1e3);if(Math.abs(now-parsed.timestamp)>tolerance)throw new EverfurWebhookVerificationError("timestamp_outside_tolerance");let matched=false;for(let key of keys){let expected=Buffer.from(computeSignature(key,parsed.timestamp,body),"ascii");for(let candidate of parsed.signatures){if(candidate.length!==HEX_SHA256_LENGTH)continue;let actual=Buffer.from(candidate,"utf8");actual.length===expected.length&&crypto.timingSafeEqual(expected,actual)&&(matched=true)}}if(!matched)throw new EverfurWebhookVerificationError("no_matching_signature");return parseEnvelope(body)}function generateTestSignatureHeader(params){let body=rawBodyBytes(params.payload),keys=requireSecrets(params.secrets),timestamp=params.timestamp??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(timestamp)||timestamp<0)throw new EverfurConfigError("invalid-argument","timestamp must be a non-negative integer (unix seconds)");return[`t=${timestamp}`,...keys.map(key=>`${SIGNATURE_SCHEME}=${computeSignature(key,timestamp,body)}`)].join(",")}function computeSignature(secret,timestamp,body){return crypto.createHmac("sha256",Buffer.from(secret,"utf8")).update(`${timestamp}.`,"ascii").update(body).digest("hex")}function rawBodyBytes(payload){if(typeof payload=="string")return Buffer.from(payload,"utf8");if(payload instanceof Uint8Array)return payload;throw new EverfurConfigError("invalid-argument","constructEvent needs the raw request body (a string or a Buffer), not parsed JSON: re-serialised JSON does not reproduce the signed bytes.")}function requireSecrets(secrets){let list=typeof secrets=="string"?[secrets]:Array.isArray(secrets)?secrets:[];if(list.length===0||list.some(s=>typeof s!="string"||s.length===0))throw new EverfurConfigError("invalid-argument","at least one non-empty webhook signing secret is required");return list}function parseSignatureHeader(header){if(typeof header!="string"||header.length===0||header.length>MAX_HEADER_LENGTH)throw new EverfurWebhookVerificationError("malformed_header");let timestamp=null,signatures=[];for(let item of header.split(",")){let trimmed=item.trim(),at=trimmed.indexOf("=");if(at<0)throw new EverfurWebhookVerificationError("malformed_header");let key=trimmed.slice(0,at),value=trimmed.slice(at+1);if(key==="t"){if(timestamp!==null||!DIGITS.test(value))throw new EverfurWebhookVerificationError("malformed_header");let parsed=Number(value);if(!Number.isSafeInteger(parsed))throw new EverfurWebhookVerificationError("malformed_header");timestamp=parsed}else key===SIGNATURE_SCHEME&&signatures.push(value)}if(timestamp===null||signatures.length===0)throw new EverfurWebhookVerificationError("malformed_header");return{timestamp:timestamp,signatures:signatures}}function parseEnvelope(body){let json;try{json=JSON.parse(Buffer.from(body.buffer,body.byteOffset,body.byteLength).toString("utf8"))}catch{throw new EverfurWebhookVerificationError("malformed_payload")}if(!isRecord(json))throw new EverfurWebhookVerificationError("malformed_payload");let{id:id,object:object,type:type,api_version:apiVersion,created:created,livemode:livemode,data:data}=json;if(typeof id!="string"||id.length===0||object!=="event"||typeof type!="string"||type.length===0||typeof apiVersion!="string"||typeof created!="number"||typeof livemode!="boolean"||!isRecord(data)||!isRecord(data.object))throw new EverfurWebhookVerificationError("malformed_payload");return json}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;var SDK_VERSION="0.18.1",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
4
+ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var EVERFUR_SIGNATURE_HEADER="Everfur-Signature",DEFAULT_WEBHOOK_TOLERANCE_SECONDS=300,SIGNATURE_SCHEME="v1",MAX_HEADER_LENGTH=4096,HEX_SHA256_LENGTH=64,DIGITS=/^[0-9]+$/,EverfurWebhookVerificationError=class _EverfurWebhookVerificationError extends Error{constructor(code){super(`Everfur webhook verification failed: ${code}`),this.name="EverfurWebhookVerificationError",this.code=code,Object.setPrototypeOf(this,_EverfurWebhookVerificationError.prototype)}};function constructEvent(payload,signatureHeader,secrets,options={}){let body=rawBodyBytes(payload),keys=requireSecrets(secrets),tolerance=options.toleranceSeconds??DEFAULT_WEBHOOK_TOLERANCE_SECONDS;if(!Number.isInteger(tolerance)||tolerance<0)throw new EverfurConfigError("invalid-argument","toleranceSeconds must be a non-negative integer");let parsed=parseSignatureHeader(signatureHeader),now=options.nowSeconds??Math.floor(Date.now()/1e3);if(Math.abs(now-parsed.timestamp)>tolerance)throw new EverfurWebhookVerificationError("timestamp_outside_tolerance");let matched=false;for(let key of keys){let expected=Buffer.from(computeSignature(key,parsed.timestamp,body),"ascii");for(let candidate of parsed.signatures){if(candidate.length!==HEX_SHA256_LENGTH)continue;let actual=Buffer.from(candidate,"utf8");actual.length===expected.length&&crypto.timingSafeEqual(expected,actual)&&(matched=true)}}if(!matched)throw new EverfurWebhookVerificationError("no_matching_signature");return parseEnvelope(body)}function generateTestSignatureHeader(params){let body=rawBodyBytes(params.payload),keys=requireSecrets(params.secrets),timestamp=params.timestamp??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(timestamp)||timestamp<0)throw new EverfurConfigError("invalid-argument","timestamp must be a non-negative integer (unix seconds)");return[`t=${timestamp}`,...keys.map(key=>`${SIGNATURE_SCHEME}=${computeSignature(key,timestamp,body)}`)].join(",")}function computeSignature(secret,timestamp,body){return crypto.createHmac("sha256",Buffer.from(secret,"utf8")).update(`${timestamp}.`,"ascii").update(body).digest("hex")}function rawBodyBytes(payload){if(typeof payload=="string")return Buffer.from(payload,"utf8");if(payload instanceof Uint8Array)return payload;throw new EverfurConfigError("invalid-argument","constructEvent needs the raw request body (a string or a Buffer), not parsed JSON: re-serialised JSON does not reproduce the signed bytes.")}function requireSecrets(secrets){let list=typeof secrets=="string"?[secrets]:Array.isArray(secrets)?secrets:[];if(list.length===0||list.some(s=>typeof s!="string"||s.length===0))throw new EverfurConfigError("invalid-argument","at least one non-empty webhook signing secret is required");return list}function parseSignatureHeader(header){if(typeof header!="string"||header.length===0||header.length>MAX_HEADER_LENGTH)throw new EverfurWebhookVerificationError("malformed_header");let timestamp=null,signatures=[];for(let item of header.split(",")){let trimmed=item.trim(),at=trimmed.indexOf("=");if(at<0)throw new EverfurWebhookVerificationError("malformed_header");let key=trimmed.slice(0,at),value=trimmed.slice(at+1);if(key==="t"){if(timestamp!==null||!DIGITS.test(value))throw new EverfurWebhookVerificationError("malformed_header");let parsed=Number(value);if(!Number.isSafeInteger(parsed))throw new EverfurWebhookVerificationError("malformed_header");timestamp=parsed}else key===SIGNATURE_SCHEME&&signatures.push(value)}if(timestamp===null||signatures.length===0)throw new EverfurWebhookVerificationError("malformed_header");return{timestamp:timestamp,signatures:signatures}}function parseEnvelope(body){let json;try{json=JSON.parse(Buffer.from(body.buffer,body.byteOffset,body.byteLength).toString("utf8"))}catch{throw new EverfurWebhookVerificationError("malformed_payload")}if(!isRecord(json))throw new EverfurWebhookVerificationError("malformed_payload");let{id:id,object:object,type:type,api_version:apiVersion,created:created,livemode:livemode,data:data}=json;if(typeof id!="string"||id.length===0||object!=="event"||typeof type!="string"||type.length===0||typeof apiVersion!="string"||typeof created!="number"||typeof livemode!="boolean"||!isRecord(data)||!isRecord(data.object))throw new EverfurWebhookVerificationError("malformed_payload");return json}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;var SDK_VERSION="0.18.3",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
5
5
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function resolveApiBaseUrl(apiBaseUrl){let outcome=tryResolveApiBaseUrl(apiBaseUrl);if(!outcome.ok)throw new EverfurConfigError("invalid-argument",outcome.failure.message);return outcome.value}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
6
6
  return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
7
7
  /* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
@@ -96,4 +96,4 @@ return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){le
96
96
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
97
97
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
98
98
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
99
- /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"unknown"}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var REQUEST_ID_HEADER="x-request-id";function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?foldDailyQuotaWireCode(code,body):null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var EVERFUR_WEBHOOK_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","visit.booked","visit.cancelled","visit.completed","visit.no_show","record_request.updated","record.ready","webhook_endpoint.test","chat.follow_up_due","chat.urgency.flagged","pet.vaccination.due","visit.rescheduled","visit.reminder","visit.followup_sent","chat.reminder_due","record.activation","visit.message_received","visit.ended","contact.exported","health_plan.box_due","health_plan.one_box_ordered","claim.evidence_returned","claim.evidence_updated","claim.records_requested","claim.failed","claim.duplicate","claim.decided","claim.inbound_refused","insured_pet.profile.ready","insured_pet.profile.updated"]),EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","chat.urgency.flagged","webhook_endpoint.test","contact.exported","health_plan.box_due","health_plan.one_box_ordered","claim.evidence_returned","claim.evidence_updated","claim.records_requested","claim.failed","claim.duplicate","claim.decided","claim.inbound_refused","insured_pet.profile.ready","insured_pet.profile.updated"]);function isEverfurWebhookEventType(type){return typeof type=="string"&&EVERFUR_WEBHOOK_EVENT_TYPES.includes(type)}function isEverfurWebhookEvent(event){return isEverfurWebhookEventType(event.type)}var PARTNER_INBOUND_EVENT_TYPES=/* @__PURE__ */Object.freeze(["pet.profile.updated","pet.incident.reported","pet.behavior_note.added","pet.service_score.recorded","pet.deleted","member.status_changed","member.deleted"]);var SECRET_KEY_PREFIXES=["sk_partner_","rk_partner_"];function assertServerSecretKey(value,action){if(typeof value!="string"||value.length===0)throw new EverfurConfigError("invalid-argument","partnerSecretKey is required");if(value.startsWith("pk_"))throw new EverfurConfigError("invalid-argument",`partnerSecretKey is a publishable key (pk_...): ${action} needs your secret key, server side only`);if(!SECRET_KEY_PREFIXES.some(prefix=>value.startsWith(prefix)))throw new EverfurConfigError("invalid-argument","partnerSecretKey must be an sk_partner_ secret key or an rk_partner_ restricted key")}var USER_REF_MAX=128;function assertValidUserRef(raw){let length=typeof raw=="string"?[...raw].length:0;if(typeof raw!="string"||length<1||length>USER_REF_MAX)throw new EverfurConfigError("invalid-argument",`user_ref must be 1..${USER_REF_MAX} characters`);if(raw.trim().length===0)throw new EverfurConfigError("invalid-argument","user_ref must not be blank: the server strips surrounding whitespace before validating, so a whitespace-only value arrives empty and is rejected as required.");if(raw!==raw.trim())throw new EverfurConfigError("invalid-argument","user_ref must not have leading or trailing whitespace: the server strips it, so padded and unpadded forms of the same id resolve to ONE user. Pass the exact id you want to key on.");if(raw.includes("@"))throw new EverfurConfigError("invalid-argument","user_ref must not contain '@'");if(!isPrintable(raw))throw new EverfurConfigError("invalid-argument","user_ref must be printable (no control characters)");return raw}function isPrintable(value){return!NON_PRINTABLE.test(value)}var NON_PRINTABLE=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}]|(?!\u0020)[\p{Zs}]/u;function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var PROFILE_FIELDS=[["name","name"],["species","species"],["breed","breed"],["ageYears","age_years"],["weightKg","weight_kg"],["partnerLabelInstructions","partner_label_instructions"]];function partnerPetProfileBody(profile){if(typeof profile!="object"||profile===null||Array.isArray(profile))throw new EverfurConfigError("invalid-argument","the pet profile must be an object");let body={};for(let[key,wire]of PROFILE_FIELDS)profile[key]!==void 0&&(body[wire]=profile[key]);let health=petHealthToWire(profile,profile.species);if("error"in health)throw new EverfurConfigError("invalid-argument",health.error);return Object.assign(body,health.body)}var IDEMPOTENCY_KEY_SHAPE=/^[\x21-\x7e]{1,255}$/,MAX_BODY_BYTES=32*1024,DATE_TIME_WITH_OFFSET=/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})$/,SEND_TIMEOUT_MS=3e4,INBOUND_RULES=/* @__PURE__ */Object.freeze({"pet.profile.updated":{subject:"pet",schemaVersions:[1,2]},"pet.incident.reported":{subject:"pet",schemaVersions:[1]},"pet.behavior_note.added":{subject:"pet",schemaVersions:[1]},"pet.service_score.recorded":{subject:"pet",schemaVersions:[1]},"pet.deleted":{subject:"pet",schemaVersions:[1]},"member.status_changed":{subject:"member",schemaVersions:[1]},"member.deleted":{subject:"member",schemaVersions:[1]}});async function sendPartnerEvent(client,event,idempotencyKey){let key=idempotencyKey??crypto.randomUUID();if(typeof key!="string"||!IDEMPOTENCY_KEY_SHAPE.test(key))throw new EverfurConfigError("invalid-argument","idempotencyKey must be 1 to 255 visible ASCII characters (no spaces, no control or non-ASCII characters)");assertServerSecretKey(client.partnerSecretKey,"sending events");let payload=serialize(buildBody(event)),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}/partners/events`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","idempotency-key":key,"x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),SEND_TIMEOUT_MS),res;try{res=await fetchImpl(url,{method:"POST",headers:headers,body:payload,signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=null;try{json=await res.json()}catch{json=null}let requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let receipt=parseReceipt(json,key);return receipt?ok(receipt):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function isInboundType(value){return typeof value=="string"&&PARTNER_INBOUND_EVENT_TYPES.includes(value)}function buildBody(event){if(typeof event!="object"||event===null)throw new EverfurConfigError("invalid-argument","event is required");if(!isInboundType(event.type))throw new EverfurConfigError("invalid-argument",`event.type must be one of ${PARTNER_INBOUND_EVENT_TYPES.join(", ")}`);let rule=INBOUND_RULES[event.type],schemaVersion=event.schemaVersion??1;if(typeof schemaVersion!="number"||!rule.schemaVersions.includes(schemaVersion))throw new EverfurConfigError("invalid-argument",`event.schemaVersion must be one of ${rule.schemaVersions.join(", ")} for ${event.type}`);let userRef=assertValidUserRef(event.userRef);if(rule.subject==="pet"&&event.petRef===void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is required for ${event.type}`);if(rule.subject==="member"&&event.petRef!==void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is not accepted on ${event.type}`);let petRef=event.petRef===void 0?void 0:assertValidPetRef(event.petRef);if(typeof event.data!="object"||event.data===null||Array.isArray(event.data))throw new EverfurConfigError("invalid-argument","event.data must be an object");let data=event.type==="pet.profile.updated"&&schemaVersion===2?partnerPetProfileBody(event.data):event.data,body={type:event.type,schema_version:schemaVersion,user_ref:userRef,occurred_at:occurredAtIso(event.occurredAt),data:data};return petRef!==void 0&&(body.pet_ref=petRef),body}function assertValidPetRef(raw){try{return assertValidUserRef(raw)}catch(cause){throw cause instanceof EverfurConfigError?new EverfurConfigError("invalid-argument",`event.petRef follows the user_ref rule: ${cause.message}`):cause}}function occurredAtIso(value){if(typeof value=="string"&&!DATE_TIME_WITH_OFFSET.test(value))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");let date2=value instanceof Date?value:typeof value=="string"?new Date(value):new Date(Number.NaN);if(Number.isNaN(date2.getTime()))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");return date2.toISOString()}function serialize(body){let payload;try{payload=JSON.stringify(body)}catch{throw new EverfurConfigError("invalid-argument","event.data must be JSON-serialisable")}let bytes=(new TextEncoder).encode(payload).byteLength;if(bytes>MAX_BODY_BYTES)throw new EverfurConfigError("invalid-argument",`the event is ${bytes} bytes once serialised; Everfur accepts at most ${MAX_BODY_BYTES} (32 KB)`);return payload}function parseReceipt(json,idempotencyKey){if(typeof json!="object"||json===null)return null;let obj=json,id=obj.id,type=obj.type,schemaVersion=obj.schema_version,userRef=obj.user_ref,petRef=obj.pet_ref??null,occurredAt=obj.occurred_at,receivedAt=obj.received_at,status=obj.status,livemode=obj.livemode;return typeof id!="string"||id.length===0||!isInboundType(type)||typeof schemaVersion!="number"||typeof userRef!="string"||petRef!==null&&typeof petRef!="string"||typeof occurredAt!="string"||typeof receivedAt!="string"||typeof status!="string"||typeof livemode!="boolean"?null:/* @__PURE__ */Object.freeze({id:id,type:type,schemaVersion:schemaVersion,userRef:userRef,petRef:petRef,occurredAt:occurredAt,receivedAt:receivedAt,status:status,livemode:livemode,idempotencyKey:idempotencyKey})}exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS=DEFAULT_WEBHOOK_TOLERANCE_SECONDS;exports.EVERFUR_SIGNATURE_HEADER=EVERFUR_SIGNATURE_HEADER;exports.EVERFUR_WEBHOOK_EVENT_TYPES=EVERFUR_WEBHOOK_EVENT_TYPES;exports.EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=EVERFUR_WEBHOOK_ONLY_EVENT_TYPES;exports.EverfurWebhookVerificationError=EverfurWebhookVerificationError;exports.PARTNER_INBOUND_EVENT_TYPES=PARTNER_INBOUND_EVENT_TYPES;exports.constructEvent=constructEvent;exports.generateTestSignatureHeader=generateTestSignatureHeader;exports.isEverfurWebhookEvent=isEverfurWebhookEvent;exports.isEverfurWebhookEventType=isEverfurWebhookEventType;exports.sendPartnerEvent=sendPartnerEvent;
99
+ /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"unknown"}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var REQUEST_ID_HEADER="x-request-id";function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?foldDailyQuotaWireCode(code,body):null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var EVERFUR_WEBHOOK_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","visit.booked","visit.cancelled","visit.completed","visit.no_show","record_request.updated","record.ready","webhook_endpoint.test","chat.follow_up_due","chat.urgency.flagged","pet.vaccination.due","visit.rescheduled","visit.reminder","visit.followup_sent","chat.reminder_due","record.activation","visit.message_received","visit.ended","contact.exported","health_plan.box_due","health_plan.one_box_ordered","claim.evidence_returned","claim.evidence_updated","claim.records_requested","claim.failed","claim.duplicate","claim.decided","claim.inbound_refused","insured_pet.profile.ready","insured_pet.profile.updated","chat.engagement_message"]),EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","chat.urgency.flagged","webhook_endpoint.test","contact.exported","health_plan.box_due","health_plan.one_box_ordered","claim.evidence_returned","claim.evidence_updated","claim.records_requested","claim.failed","claim.duplicate","claim.decided","claim.inbound_refused","insured_pet.profile.ready","insured_pet.profile.updated","chat.engagement_message"]);function isEverfurWebhookEventType(type){return typeof type=="string"&&EVERFUR_WEBHOOK_EVENT_TYPES.includes(type)}function isEverfurWebhookEvent(event){return isEverfurWebhookEventType(event.type)}var PARTNER_INBOUND_EVENT_TYPES=/* @__PURE__ */Object.freeze(["pet.profile.updated","pet.incident.reported","pet.behavior_note.added","pet.service_score.recorded","pet.deleted","member.status_changed","member.deleted"]);var SECRET_KEY_PREFIXES=["sk_partner_","rk_partner_"];function assertServerSecretKey(value,action){if(typeof value!="string"||value.length===0)throw new EverfurConfigError("invalid-argument","partnerSecretKey is required");if(value.startsWith("pk_"))throw new EverfurConfigError("invalid-argument",`partnerSecretKey is a publishable key (pk_...): ${action} needs your secret key, server side only`);if(!SECRET_KEY_PREFIXES.some(prefix=>value.startsWith(prefix)))throw new EverfurConfigError("invalid-argument","partnerSecretKey must be an sk_partner_ secret key or an rk_partner_ restricted key")}var USER_REF_MAX=128;function assertValidUserRef(raw){let length=typeof raw=="string"?[...raw].length:0;if(typeof raw!="string"||length<1||length>USER_REF_MAX)throw new EverfurConfigError("invalid-argument",`user_ref must be 1..${USER_REF_MAX} characters`);if(raw.trim().length===0)throw new EverfurConfigError("invalid-argument","user_ref must not be blank: the server strips surrounding whitespace before validating, so a whitespace-only value arrives empty and is rejected as required.");if(raw!==raw.trim())throw new EverfurConfigError("invalid-argument","user_ref must not have leading or trailing whitespace: the server strips it, so padded and unpadded forms of the same id resolve to ONE user. Pass the exact id you want to key on.");if(raw.includes("@"))throw new EverfurConfigError("invalid-argument","user_ref must not contain '@'");if(!isPrintable(raw))throw new EverfurConfigError("invalid-argument","user_ref must be printable (no control characters)");return raw}function isPrintable(value){return!NON_PRINTABLE.test(value)}var NON_PRINTABLE=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}]|(?!\u0020)[\p{Zs}]/u;function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var PROFILE_FIELDS=[["name","name"],["species","species"],["breed","breed"],["ageYears","age_years"],["weightKg","weight_kg"],["partnerLabelInstructions","partner_label_instructions"]];function partnerPetProfileBody(profile){if(typeof profile!="object"||profile===null||Array.isArray(profile))throw new EverfurConfigError("invalid-argument","the pet profile must be an object");let body={};for(let[key,wire]of PROFILE_FIELDS)profile[key]!==void 0&&(body[wire]=profile[key]);let health=petHealthToWire(profile,profile.species);if("error"in health)throw new EverfurConfigError("invalid-argument",health.error);return Object.assign(body,health.body)}var IDEMPOTENCY_KEY_SHAPE=/^[\x21-\x7e]{1,255}$/,MAX_BODY_BYTES=32*1024,DATE_TIME_WITH_OFFSET=/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})$/,SEND_TIMEOUT_MS=3e4,INBOUND_RULES=/* @__PURE__ */Object.freeze({"pet.profile.updated":{subject:"pet",schemaVersions:[1,2]},"pet.incident.reported":{subject:"pet",schemaVersions:[1]},"pet.behavior_note.added":{subject:"pet",schemaVersions:[1]},"pet.service_score.recorded":{subject:"pet",schemaVersions:[1]},"pet.deleted":{subject:"pet",schemaVersions:[1]},"member.status_changed":{subject:"member",schemaVersions:[1]},"member.deleted":{subject:"member",schemaVersions:[1]}});async function sendPartnerEvent(client,event,idempotencyKey){let key=idempotencyKey??crypto.randomUUID();if(typeof key!="string"||!IDEMPOTENCY_KEY_SHAPE.test(key))throw new EverfurConfigError("invalid-argument","idempotencyKey must be 1 to 255 visible ASCII characters (no spaces, no control or non-ASCII characters)");assertServerSecretKey(client.partnerSecretKey,"sending events");let payload=serialize(buildBody(event)),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}/partners/events`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","idempotency-key":key,"x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),SEND_TIMEOUT_MS),res;try{res=await fetchImpl(url,{method:"POST",headers:headers,body:payload,signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=null;try{json=await res.json()}catch{json=null}let requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let receipt=parseReceipt(json,key);return receipt?ok(receipt):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function isInboundType(value){return typeof value=="string"&&PARTNER_INBOUND_EVENT_TYPES.includes(value)}function buildBody(event){if(typeof event!="object"||event===null)throw new EverfurConfigError("invalid-argument","event is required");if(!isInboundType(event.type))throw new EverfurConfigError("invalid-argument",`event.type must be one of ${PARTNER_INBOUND_EVENT_TYPES.join(", ")}`);let rule=INBOUND_RULES[event.type],schemaVersion=event.schemaVersion??1;if(typeof schemaVersion!="number"||!rule.schemaVersions.includes(schemaVersion))throw new EverfurConfigError("invalid-argument",`event.schemaVersion must be one of ${rule.schemaVersions.join(", ")} for ${event.type}`);let userRef=assertValidUserRef(event.userRef);if(rule.subject==="pet"&&event.petRef===void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is required for ${event.type}`);if(rule.subject==="member"&&event.petRef!==void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is not accepted on ${event.type}`);let petRef=event.petRef===void 0?void 0:assertValidPetRef(event.petRef);if(typeof event.data!="object"||event.data===null||Array.isArray(event.data))throw new EverfurConfigError("invalid-argument","event.data must be an object");let data=event.type==="pet.profile.updated"&&schemaVersion===2?partnerPetProfileBody(event.data):event.data,body={type:event.type,schema_version:schemaVersion,user_ref:userRef,occurred_at:occurredAtIso(event.occurredAt),data:data};return petRef!==void 0&&(body.pet_ref=petRef),body}function assertValidPetRef(raw){try{return assertValidUserRef(raw)}catch(cause){throw cause instanceof EverfurConfigError?new EverfurConfigError("invalid-argument",`event.petRef follows the user_ref rule: ${cause.message}`):cause}}function occurredAtIso(value){if(typeof value=="string"&&!DATE_TIME_WITH_OFFSET.test(value))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");let date2=value instanceof Date?value:typeof value=="string"?new Date(value):new Date(Number.NaN);if(Number.isNaN(date2.getTime()))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");return date2.toISOString()}function serialize(body){let payload;try{payload=JSON.stringify(body)}catch{throw new EverfurConfigError("invalid-argument","event.data must be JSON-serialisable")}let bytes=(new TextEncoder).encode(payload).byteLength;if(bytes>MAX_BODY_BYTES)throw new EverfurConfigError("invalid-argument",`the event is ${bytes} bytes once serialised; Everfur accepts at most ${MAX_BODY_BYTES} (32 KB)`);return payload}function parseReceipt(json,idempotencyKey){if(typeof json!="object"||json===null)return null;let obj=json,id=obj.id,type=obj.type,schemaVersion=obj.schema_version,userRef=obj.user_ref,petRef=obj.pet_ref??null,occurredAt=obj.occurred_at,receivedAt=obj.received_at,status=obj.status,livemode=obj.livemode;return typeof id!="string"||id.length===0||!isInboundType(type)||typeof schemaVersion!="number"||typeof userRef!="string"||petRef!==null&&typeof petRef!="string"||typeof occurredAt!="string"||typeof receivedAt!="string"||typeof status!="string"||typeof livemode!="boolean"?null:/* @__PURE__ */Object.freeze({id:id,type:type,schemaVersion:schemaVersion,userRef:userRef,petRef:petRef,occurredAt:occurredAt,receivedAt:receivedAt,status:status,livemode:livemode,idempotencyKey:idempotencyKey})}exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS=DEFAULT_WEBHOOK_TOLERANCE_SECONDS;exports.EVERFUR_SIGNATURE_HEADER=EVERFUR_SIGNATURE_HEADER;exports.EVERFUR_WEBHOOK_EVENT_TYPES=EVERFUR_WEBHOOK_EVENT_TYPES;exports.EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=EVERFUR_WEBHOOK_ONLY_EVENT_TYPES;exports.EverfurWebhookVerificationError=EverfurWebhookVerificationError;exports.PARTNER_INBOUND_EVENT_TYPES=PARTNER_INBOUND_EVENT_TYPES;exports.constructEvent=constructEvent;exports.generateTestSignatureHeader=generateTestSignatureHeader;exports.isEverfurWebhookEvent=isEverfurWebhookEvent;exports.isEverfurWebhookEventType=isEverfurWebhookEventType;exports.sendPartnerEvent=sendPartnerEvent;
@@ -1,12 +1,12 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
- import { P as PartnerPetProfile } from '../../pets.d-C4n-MDC4.cjs';
2
+ import { P as PartnerPetProfile } from '../../pets.d-5SMtOAwB.cjs';
3
3
  import { E as EverfurResult } from '../../EverfurResult.d-BFH-3s6E.cjs';
4
- import { j as FetchLike } from '../../config.d-7bCXvOGn.cjs';
4
+ import { j as FetchLike } from '../../config.d-Z_fyOZke.cjs';
5
5
  export { b as PetActivityLevel, c as PetAllergy, d as PetAllergySeverity, e as PetBirthDatePrecision, f as PetCondition, P as PetHealthProfileInput, g as PetIndoorOutdoor, h as PetMedication, i as PetSex } from '../../profile.d-CSs1wlXT.cjs';
6
6
  import '../../EverfurError.d-8NHtlgzA.cjs';
7
7
 
8
8
  /** Every outbound event type in the catalog. Order matches EFBackend `OUTBOUND_EVENT_TYPES`. */
9
- declare const EVERFUR_WEBHOOK_EVENT_TYPES: readonly ["member.linked", "member.unlinked", "visit.booked", "visit.cancelled", "visit.completed", "visit.no_show", "record_request.updated", "record.ready", "webhook_endpoint.test", "chat.follow_up_due", "chat.urgency.flagged", "pet.vaccination.due", "visit.rescheduled", "visit.reminder", "visit.followup_sent", "chat.reminder_due", "record.activation", "visit.message_received", "visit.ended", "contact.exported", "health_plan.box_due", "health_plan.one_box_ordered", "claim.evidence_returned", "claim.evidence_updated", "claim.records_requested", "claim.failed", "claim.duplicate", "claim.decided", "claim.inbound_refused", "insured_pet.profile.ready", "insured_pet.profile.updated"];
9
+ declare const EVERFUR_WEBHOOK_EVENT_TYPES: readonly ["member.linked", "member.unlinked", "visit.booked", "visit.cancelled", "visit.completed", "visit.no_show", "record_request.updated", "record.ready", "webhook_endpoint.test", "chat.follow_up_due", "chat.urgency.flagged", "pet.vaccination.due", "visit.rescheduled", "visit.reminder", "visit.followup_sent", "chat.reminder_due", "record.activation", "visit.message_received", "visit.ended", "contact.exported", "health_plan.box_due", "health_plan.one_box_ordered", "claim.evidence_returned", "claim.evidence_updated", "claim.records_requested", "claim.failed", "claim.duplicate", "claim.decided", "claim.inbound_refused", "insured_pet.profile.ready", "insured_pet.profile.updated", "chat.engagement_message"];
10
10
  /** One outbound event type name. */
11
11
  type EverfurWebhookEventType = (typeof EVERFUR_WEBHOOK_EVENT_TYPES)[number];
12
12
  /**
@@ -28,7 +28,7 @@ type EverfurWebhookEventType = (typeof EVERFUR_WEBHOOK_EVENT_TYPES)[number];
28
28
  * `visit.ended`, have a target but no consumer copy, so in practice no push is sent for them either).
29
29
  * Read this list when you decide which events your own backend must act on rather than leave to the device.
30
30
  */
31
- declare const EVERFUR_WEBHOOK_ONLY_EVENT_TYPES: readonly ["member.linked", "member.unlinked", "chat.urgency.flagged", "webhook_endpoint.test", "contact.exported", "health_plan.box_due", "health_plan.one_box_ordered", "claim.evidence_returned", "claim.evidence_updated", "claim.records_requested", "claim.failed", "claim.duplicate", "claim.decided", "claim.inbound_refused", "insured_pet.profile.ready", "insured_pet.profile.updated"];
31
+ declare const EVERFUR_WEBHOOK_ONLY_EVENT_TYPES: readonly ["member.linked", "member.unlinked", "chat.urgency.flagged", "webhook_endpoint.test", "contact.exported", "health_plan.box_due", "health_plan.one_box_ordered", "claim.evidence_returned", "claim.evidence_updated", "claim.records_requested", "claim.failed", "claim.duplicate", "claim.decided", "claim.inbound_refused", "insured_pet.profile.ready", "insured_pet.profile.updated", "chat.engagement_message"];
32
32
  /** One type that never reaches a device. */
33
33
  type EverfurWebhookOnlyEventType = (typeof EVERFUR_WEBHOOK_ONLY_EVENT_TYPES)[number];
34
34
  /** Fields any payload may carry beyond the ones typed here (forward compatible). */
@@ -209,6 +209,36 @@ interface ChatReminderDuePayload extends OpenEventPayload {
209
209
  /** ISO 8601. When the nudge became due. */
210
210
  readonly due_at: string;
211
211
  }
212
+ /**
213
+ * What a `chat.engagement_message` is about (`partner_engagement_signals.SIGNAL_KINDS`). A closed code that can
214
+ * grow; treat one you do not know as a generic chat message.
215
+ */
216
+ type EverfurChatEngagementKind = 'watch_case_checkin' | 'symptom_check' | 'medication_due' | 'recent_visit' | 'lab_value_moved' | 'new_problem' | 'new_medication' | 'weight_changed' | 'records_arrived' | 'vaccine_due' | 'plan_item' | 'records_connect';
217
+ /**
218
+ * `chat.engagement_message`: Everfur sent the member one proactive message about a pet, in the chat thread, by the
219
+ * tenant's approved text, or both (a text that is also in the thread). One event per message
220
+ * (`ledger_id`), whichever channels carried it. Never the words: they are in the thread or the text.
221
+ *
222
+ * `push` is true when Everfur also sent a push saying a thread line waits; that happens only for a thread line no
223
+ * text carried, and only for a tenant Everfur pushes for. If you send your own pushes, act on `thread && !text`
224
+ * and tell Everfur, so the member is not told twice.
225
+ */
226
+ interface ChatEngagementMessagePayload extends OpenEventPayload {
227
+ readonly object: 'chat_engagement';
228
+ readonly user_ref: string;
229
+ readonly pet_ref: string;
230
+ readonly kind: EverfurChatEngagementKind;
231
+ /** The message's id in Everfur's engagement ledger: dedupe on it. */
232
+ readonly ledger_id: string;
233
+ /** True when the message waits in the pet's chat thread. */
234
+ readonly thread: boolean;
235
+ /** True when the tenant's approved text carried it. */
236
+ readonly text: boolean;
237
+ /** True when an Everfur push told the member a thread line waits. */
238
+ readonly push: boolean;
239
+ /** ISO 8601. When the message went out. */
240
+ readonly at: string;
241
+ }
212
242
  /**
213
243
  * The closed classes of thing a parsed record can hold (`copy/records_activation.py` RECORD_CLASSES), in the
214
244
  * order the platform counts them. A `record.activation` event names exactly one of these.
@@ -415,6 +445,7 @@ interface EverfurWebhookPayloadMap {
415
445
  readonly 'visit.reminder': VisitReminderPayload;
416
446
  readonly 'visit.followup_sent': VisitFollowupSentPayload;
417
447
  readonly 'chat.reminder_due': ChatReminderDuePayload;
448
+ readonly 'chat.engagement_message': ChatEngagementMessagePayload;
418
449
  readonly 'record.activation': RecordActivationPayload;
419
450
  readonly 'visit.message_received': VisitMessageReceivedPayload;
420
451
  readonly 'visit.ended': VisitEndedPayload;
@@ -719,4 +750,4 @@ interface PartnerEventReceipt {
719
750
  */
720
751
  declare function sendPartnerEvent(client: PartnerEventsClient, event: PartnerInboundEvent, idempotencyKey?: string): Promise<EverfurResult<PartnerEventReceipt>>;
721
752
 
722
- export { type ChatFollowUpDuePayload, type ChatReminderDuePayload, type ChatUrgencyFlaggedPayload, type ClaimDecidedPayload, type ClaimDecision, type ClaimDuplicatePayload, type ClaimEventPayload, type ClaimEvidencePayload, type ClaimFailedPayload, type ClaimInboundRefusedPayload, type ClaimRecordsRequestedPayload, type ConstructEventOptions, type ContactExportedPayload, type ContactExportedPet, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, EVERFUR_SIGNATURE_HEADER, EVERFUR_WEBHOOK_EVENT_TYPES, EVERFUR_WEBHOOK_ONLY_EVENT_TYPES, type EverfurChatReminderKind, type EverfurContactIdentifierType, type EverfurRecordClass, type EverfurVaccinationDueStage, type EverfurVaccine, type EverfurVisitReminderStage, type EverfurVisitStatus, type EverfurWebhookEvent, type EverfurWebhookEventOf, type EverfurWebhookEventType, type EverfurWebhookOnlyEventType, type EverfurWebhookPayloadMap, EverfurWebhookVerificationError, type HealthPlanBoxDuePayload, type HealthPlanOneBoxOrderedPayload, type InsuredPetProfilePayload, type MemberDeletedData, type MemberLinkPayload, type MemberStatusChangedData, type OpenEventPayload, PARTNER_INBOUND_EVENT_TYPES, type PartnerEventReceipt, type PartnerEventsClient, type PartnerInboundEvent, type PartnerInboundEventDataMap, type PartnerInboundEventOf, type PartnerInboundEventType, PartnerPetProfile, type PetBehaviorNoteAddedData, type PetDeletedData, type PetIncidentReportedData, type PetProfileUpdatedData, type PetProfileUpdatedV2Event, type PetServiceScoreRecordedData, type PetVaccinationDuePayload, type RecordActivationPayload, type RecordReadyPayload, type RecordRequestSimpleStatus, type RecordRequestUpdatedPayload, type TestSignatureHeaderParams, type UnrecognizedEverfurWebhookEvent, type VisitEndedPayload, type VisitFollowupSentPayload, type VisitMessageReceivedPayload, type VisitPayload, type VisitReminderPayload, type VisitRescheduledPayload, type WebhookEndpointTestPayload, type WebhookPayload, type WebhookVerificationFailure, constructEvent, generateTestSignatureHeader, isEverfurWebhookEvent, isEverfurWebhookEventType, sendPartnerEvent };
753
+ export { type ChatEngagementMessagePayload, type ChatFollowUpDuePayload, type ChatReminderDuePayload, type ChatUrgencyFlaggedPayload, type ClaimDecidedPayload, type ClaimDecision, type ClaimDuplicatePayload, type ClaimEventPayload, type ClaimEvidencePayload, type ClaimFailedPayload, type ClaimInboundRefusedPayload, type ClaimRecordsRequestedPayload, type ConstructEventOptions, type ContactExportedPayload, type ContactExportedPet, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, EVERFUR_SIGNATURE_HEADER, EVERFUR_WEBHOOK_EVENT_TYPES, EVERFUR_WEBHOOK_ONLY_EVENT_TYPES, type EverfurChatEngagementKind, type EverfurChatReminderKind, type EverfurContactIdentifierType, type EverfurRecordClass, type EverfurVaccinationDueStage, type EverfurVaccine, type EverfurVisitReminderStage, type EverfurVisitStatus, type EverfurWebhookEvent, type EverfurWebhookEventOf, type EverfurWebhookEventType, type EverfurWebhookOnlyEventType, type EverfurWebhookPayloadMap, EverfurWebhookVerificationError, type HealthPlanBoxDuePayload, type HealthPlanOneBoxOrderedPayload, type InsuredPetProfilePayload, type MemberDeletedData, type MemberLinkPayload, type MemberStatusChangedData, type OpenEventPayload, PARTNER_INBOUND_EVENT_TYPES, type PartnerEventReceipt, type PartnerEventsClient, type PartnerInboundEvent, type PartnerInboundEventDataMap, type PartnerInboundEventOf, type PartnerInboundEventType, PartnerPetProfile, type PetBehaviorNoteAddedData, type PetDeletedData, type PetIncidentReportedData, type PetProfileUpdatedData, type PetProfileUpdatedV2Event, type PetServiceScoreRecordedData, type PetVaccinationDuePayload, type RecordActivationPayload, type RecordReadyPayload, type RecordRequestSimpleStatus, type RecordRequestUpdatedPayload, type TestSignatureHeaderParams, type UnrecognizedEverfurWebhookEvent, type VisitEndedPayload, type VisitFollowupSentPayload, type VisitMessageReceivedPayload, type VisitPayload, type VisitReminderPayload, type VisitRescheduledPayload, type WebhookEndpointTestPayload, type WebhookPayload, type WebhookVerificationFailure, constructEvent, generateTestSignatureHeader, isEverfurWebhookEvent, isEverfurWebhookEventType, sendPartnerEvent };
@@ -1,12 +1,12 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
- import { P as PartnerPetProfile } from '../../pets.d-1_CHpfgB.js';
2
+ import { P as PartnerPetProfile } from '../../pets.d-BRsbR8QU.js';
3
3
  import { E as EverfurResult } from '../../EverfurResult.d-D_-254ZY.js';
4
- import { j as FetchLike } from '../../config.d-cqyvpzDb.js';
4
+ import { j as FetchLike } from '../../config.d-KX-EkQ9j.js';
5
5
  export { b as PetActivityLevel, c as PetAllergy, d as PetAllergySeverity, e as PetBirthDatePrecision, f as PetCondition, P as PetHealthProfileInput, g as PetIndoorOutdoor, h as PetMedication, i as PetSex } from '../../profile.d-CSs1wlXT.js';
6
6
  import '../../EverfurError.d-8NHtlgzA.js';
7
7
 
8
8
  /** Every outbound event type in the catalog. Order matches EFBackend `OUTBOUND_EVENT_TYPES`. */
9
- declare const EVERFUR_WEBHOOK_EVENT_TYPES: readonly ["member.linked", "member.unlinked", "visit.booked", "visit.cancelled", "visit.completed", "visit.no_show", "record_request.updated", "record.ready", "webhook_endpoint.test", "chat.follow_up_due", "chat.urgency.flagged", "pet.vaccination.due", "visit.rescheduled", "visit.reminder", "visit.followup_sent", "chat.reminder_due", "record.activation", "visit.message_received", "visit.ended", "contact.exported", "health_plan.box_due", "health_plan.one_box_ordered", "claim.evidence_returned", "claim.evidence_updated", "claim.records_requested", "claim.failed", "claim.duplicate", "claim.decided", "claim.inbound_refused", "insured_pet.profile.ready", "insured_pet.profile.updated"];
9
+ declare const EVERFUR_WEBHOOK_EVENT_TYPES: readonly ["member.linked", "member.unlinked", "visit.booked", "visit.cancelled", "visit.completed", "visit.no_show", "record_request.updated", "record.ready", "webhook_endpoint.test", "chat.follow_up_due", "chat.urgency.flagged", "pet.vaccination.due", "visit.rescheduled", "visit.reminder", "visit.followup_sent", "chat.reminder_due", "record.activation", "visit.message_received", "visit.ended", "contact.exported", "health_plan.box_due", "health_plan.one_box_ordered", "claim.evidence_returned", "claim.evidence_updated", "claim.records_requested", "claim.failed", "claim.duplicate", "claim.decided", "claim.inbound_refused", "insured_pet.profile.ready", "insured_pet.profile.updated", "chat.engagement_message"];
10
10
  /** One outbound event type name. */
11
11
  type EverfurWebhookEventType = (typeof EVERFUR_WEBHOOK_EVENT_TYPES)[number];
12
12
  /**
@@ -28,7 +28,7 @@ type EverfurWebhookEventType = (typeof EVERFUR_WEBHOOK_EVENT_TYPES)[number];
28
28
  * `visit.ended`, have a target but no consumer copy, so in practice no push is sent for them either).
29
29
  * Read this list when you decide which events your own backend must act on rather than leave to the device.
30
30
  */
31
- declare const EVERFUR_WEBHOOK_ONLY_EVENT_TYPES: readonly ["member.linked", "member.unlinked", "chat.urgency.flagged", "webhook_endpoint.test", "contact.exported", "health_plan.box_due", "health_plan.one_box_ordered", "claim.evidence_returned", "claim.evidence_updated", "claim.records_requested", "claim.failed", "claim.duplicate", "claim.decided", "claim.inbound_refused", "insured_pet.profile.ready", "insured_pet.profile.updated"];
31
+ declare const EVERFUR_WEBHOOK_ONLY_EVENT_TYPES: readonly ["member.linked", "member.unlinked", "chat.urgency.flagged", "webhook_endpoint.test", "contact.exported", "health_plan.box_due", "health_plan.one_box_ordered", "claim.evidence_returned", "claim.evidence_updated", "claim.records_requested", "claim.failed", "claim.duplicate", "claim.decided", "claim.inbound_refused", "insured_pet.profile.ready", "insured_pet.profile.updated", "chat.engagement_message"];
32
32
  /** One type that never reaches a device. */
33
33
  type EverfurWebhookOnlyEventType = (typeof EVERFUR_WEBHOOK_ONLY_EVENT_TYPES)[number];
34
34
  /** Fields any payload may carry beyond the ones typed here (forward compatible). */
@@ -209,6 +209,36 @@ interface ChatReminderDuePayload extends OpenEventPayload {
209
209
  /** ISO 8601. When the nudge became due. */
210
210
  readonly due_at: string;
211
211
  }
212
+ /**
213
+ * What a `chat.engagement_message` is about (`partner_engagement_signals.SIGNAL_KINDS`). A closed code that can
214
+ * grow; treat one you do not know as a generic chat message.
215
+ */
216
+ type EverfurChatEngagementKind = 'watch_case_checkin' | 'symptom_check' | 'medication_due' | 'recent_visit' | 'lab_value_moved' | 'new_problem' | 'new_medication' | 'weight_changed' | 'records_arrived' | 'vaccine_due' | 'plan_item' | 'records_connect';
217
+ /**
218
+ * `chat.engagement_message`: Everfur sent the member one proactive message about a pet, in the chat thread, by the
219
+ * tenant's approved text, or both (a text that is also in the thread). One event per message
220
+ * (`ledger_id`), whichever channels carried it. Never the words: they are in the thread or the text.
221
+ *
222
+ * `push` is true when Everfur also sent a push saying a thread line waits; that happens only for a thread line no
223
+ * text carried, and only for a tenant Everfur pushes for. If you send your own pushes, act on `thread && !text`
224
+ * and tell Everfur, so the member is not told twice.
225
+ */
226
+ interface ChatEngagementMessagePayload extends OpenEventPayload {
227
+ readonly object: 'chat_engagement';
228
+ readonly user_ref: string;
229
+ readonly pet_ref: string;
230
+ readonly kind: EverfurChatEngagementKind;
231
+ /** The message's id in Everfur's engagement ledger: dedupe on it. */
232
+ readonly ledger_id: string;
233
+ /** True when the message waits in the pet's chat thread. */
234
+ readonly thread: boolean;
235
+ /** True when the tenant's approved text carried it. */
236
+ readonly text: boolean;
237
+ /** True when an Everfur push told the member a thread line waits. */
238
+ readonly push: boolean;
239
+ /** ISO 8601. When the message went out. */
240
+ readonly at: string;
241
+ }
212
242
  /**
213
243
  * The closed classes of thing a parsed record can hold (`copy/records_activation.py` RECORD_CLASSES), in the
214
244
  * order the platform counts them. A `record.activation` event names exactly one of these.
@@ -415,6 +445,7 @@ interface EverfurWebhookPayloadMap {
415
445
  readonly 'visit.reminder': VisitReminderPayload;
416
446
  readonly 'visit.followup_sent': VisitFollowupSentPayload;
417
447
  readonly 'chat.reminder_due': ChatReminderDuePayload;
448
+ readonly 'chat.engagement_message': ChatEngagementMessagePayload;
418
449
  readonly 'record.activation': RecordActivationPayload;
419
450
  readonly 'visit.message_received': VisitMessageReceivedPayload;
420
451
  readonly 'visit.ended': VisitEndedPayload;
@@ -719,4 +750,4 @@ interface PartnerEventReceipt {
719
750
  */
720
751
  declare function sendPartnerEvent(client: PartnerEventsClient, event: PartnerInboundEvent, idempotencyKey?: string): Promise<EverfurResult<PartnerEventReceipt>>;
721
752
 
722
- export { type ChatFollowUpDuePayload, type ChatReminderDuePayload, type ChatUrgencyFlaggedPayload, type ClaimDecidedPayload, type ClaimDecision, type ClaimDuplicatePayload, type ClaimEventPayload, type ClaimEvidencePayload, type ClaimFailedPayload, type ClaimInboundRefusedPayload, type ClaimRecordsRequestedPayload, type ConstructEventOptions, type ContactExportedPayload, type ContactExportedPet, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, EVERFUR_SIGNATURE_HEADER, EVERFUR_WEBHOOK_EVENT_TYPES, EVERFUR_WEBHOOK_ONLY_EVENT_TYPES, type EverfurChatReminderKind, type EverfurContactIdentifierType, type EverfurRecordClass, type EverfurVaccinationDueStage, type EverfurVaccine, type EverfurVisitReminderStage, type EverfurVisitStatus, type EverfurWebhookEvent, type EverfurWebhookEventOf, type EverfurWebhookEventType, type EverfurWebhookOnlyEventType, type EverfurWebhookPayloadMap, EverfurWebhookVerificationError, type HealthPlanBoxDuePayload, type HealthPlanOneBoxOrderedPayload, type InsuredPetProfilePayload, type MemberDeletedData, type MemberLinkPayload, type MemberStatusChangedData, type OpenEventPayload, PARTNER_INBOUND_EVENT_TYPES, type PartnerEventReceipt, type PartnerEventsClient, type PartnerInboundEvent, type PartnerInboundEventDataMap, type PartnerInboundEventOf, type PartnerInboundEventType, PartnerPetProfile, type PetBehaviorNoteAddedData, type PetDeletedData, type PetIncidentReportedData, type PetProfileUpdatedData, type PetProfileUpdatedV2Event, type PetServiceScoreRecordedData, type PetVaccinationDuePayload, type RecordActivationPayload, type RecordReadyPayload, type RecordRequestSimpleStatus, type RecordRequestUpdatedPayload, type TestSignatureHeaderParams, type UnrecognizedEverfurWebhookEvent, type VisitEndedPayload, type VisitFollowupSentPayload, type VisitMessageReceivedPayload, type VisitPayload, type VisitReminderPayload, type VisitRescheduledPayload, type WebhookEndpointTestPayload, type WebhookPayload, type WebhookVerificationFailure, constructEvent, generateTestSignatureHeader, isEverfurWebhookEvent, isEverfurWebhookEventType, sendPartnerEvent };
753
+ export { type ChatEngagementMessagePayload, type ChatFollowUpDuePayload, type ChatReminderDuePayload, type ChatUrgencyFlaggedPayload, type ClaimDecidedPayload, type ClaimDecision, type ClaimDuplicatePayload, type ClaimEventPayload, type ClaimEvidencePayload, type ClaimFailedPayload, type ClaimInboundRefusedPayload, type ClaimRecordsRequestedPayload, type ConstructEventOptions, type ContactExportedPayload, type ContactExportedPet, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, EVERFUR_SIGNATURE_HEADER, EVERFUR_WEBHOOK_EVENT_TYPES, EVERFUR_WEBHOOK_ONLY_EVENT_TYPES, type EverfurChatEngagementKind, type EverfurChatReminderKind, type EverfurContactIdentifierType, type EverfurRecordClass, type EverfurVaccinationDueStage, type EverfurVaccine, type EverfurVisitReminderStage, type EverfurVisitStatus, type EverfurWebhookEvent, type EverfurWebhookEventOf, type EverfurWebhookEventType, type EverfurWebhookOnlyEventType, type EverfurWebhookPayloadMap, EverfurWebhookVerificationError, type HealthPlanBoxDuePayload, type HealthPlanOneBoxOrderedPayload, type InsuredPetProfilePayload, type MemberDeletedData, type MemberLinkPayload, type MemberStatusChangedData, type OpenEventPayload, PARTNER_INBOUND_EVENT_TYPES, type PartnerEventReceipt, type PartnerEventsClient, type PartnerInboundEvent, type PartnerInboundEventDataMap, type PartnerInboundEventOf, type PartnerInboundEventType, PartnerPetProfile, type PetBehaviorNoteAddedData, type PetDeletedData, type PetIncidentReportedData, type PetProfileUpdatedData, type PetProfileUpdatedV2Event, type PetServiceScoreRecordedData, type PetVaccinationDuePayload, type RecordActivationPayload, type RecordReadyPayload, type RecordRequestSimpleStatus, type RecordRequestUpdatedPayload, type TestSignatureHeaderParams, type UnrecognizedEverfurWebhookEvent, type VisitEndedPayload, type VisitFollowupSentPayload, type VisitMessageReceivedPayload, type VisitPayload, type VisitReminderPayload, type VisitRescheduledPayload, type WebhookEndpointTestPayload, type WebhookPayload, type WebhookVerificationFailure, constructEvent, generateTestSignatureHeader, isEverfurWebhookEvent, isEverfurWebhookEventType, sendPartnerEvent };
@@ -1,7 +1,7 @@
1
1
  /*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
2
2
  import{timingSafeEqual,createHmac,randomUUID}from"crypto";function ok(value,warning){/* @__PURE__ */
3
3
  return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
4
- return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var EVERFUR_SIGNATURE_HEADER="Everfur-Signature",DEFAULT_WEBHOOK_TOLERANCE_SECONDS=300,SIGNATURE_SCHEME="v1",MAX_HEADER_LENGTH=4096,HEX_SHA256_LENGTH=64,DIGITS=/^[0-9]+$/,EverfurWebhookVerificationError=class _EverfurWebhookVerificationError extends Error{constructor(code){super(`Everfur webhook verification failed: ${code}`),this.name="EverfurWebhookVerificationError",this.code=code,Object.setPrototypeOf(this,_EverfurWebhookVerificationError.prototype)}};function constructEvent(payload,signatureHeader,secrets,options={}){let body=rawBodyBytes(payload),keys=requireSecrets(secrets),tolerance=options.toleranceSeconds??DEFAULT_WEBHOOK_TOLERANCE_SECONDS;if(!Number.isInteger(tolerance)||tolerance<0)throw new EverfurConfigError("invalid-argument","toleranceSeconds must be a non-negative integer");let parsed=parseSignatureHeader(signatureHeader),now=options.nowSeconds??Math.floor(Date.now()/1e3);if(Math.abs(now-parsed.timestamp)>tolerance)throw new EverfurWebhookVerificationError("timestamp_outside_tolerance");let matched=false;for(let key of keys){let expected=Buffer.from(computeSignature(key,parsed.timestamp,body),"ascii");for(let candidate of parsed.signatures){if(candidate.length!==HEX_SHA256_LENGTH)continue;let actual=Buffer.from(candidate,"utf8");actual.length===expected.length&&timingSafeEqual(expected,actual)&&(matched=true)}}if(!matched)throw new EverfurWebhookVerificationError("no_matching_signature");return parseEnvelope(body)}function generateTestSignatureHeader(params){let body=rawBodyBytes(params.payload),keys=requireSecrets(params.secrets),timestamp=params.timestamp??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(timestamp)||timestamp<0)throw new EverfurConfigError("invalid-argument","timestamp must be a non-negative integer (unix seconds)");return[`t=${timestamp}`,...keys.map(key=>`${SIGNATURE_SCHEME}=${computeSignature(key,timestamp,body)}`)].join(",")}function computeSignature(secret,timestamp,body){return createHmac("sha256",Buffer.from(secret,"utf8")).update(`${timestamp}.`,"ascii").update(body).digest("hex")}function rawBodyBytes(payload){if(typeof payload=="string")return Buffer.from(payload,"utf8");if(payload instanceof Uint8Array)return payload;throw new EverfurConfigError("invalid-argument","constructEvent needs the raw request body (a string or a Buffer), not parsed JSON: re-serialised JSON does not reproduce the signed bytes.")}function requireSecrets(secrets){let list=typeof secrets=="string"?[secrets]:Array.isArray(secrets)?secrets:[];if(list.length===0||list.some(s=>typeof s!="string"||s.length===0))throw new EverfurConfigError("invalid-argument","at least one non-empty webhook signing secret is required");return list}function parseSignatureHeader(header){if(typeof header!="string"||header.length===0||header.length>MAX_HEADER_LENGTH)throw new EverfurWebhookVerificationError("malformed_header");let timestamp=null,signatures=[];for(let item of header.split(",")){let trimmed=item.trim(),at=trimmed.indexOf("=");if(at<0)throw new EverfurWebhookVerificationError("malformed_header");let key=trimmed.slice(0,at),value=trimmed.slice(at+1);if(key==="t"){if(timestamp!==null||!DIGITS.test(value))throw new EverfurWebhookVerificationError("malformed_header");let parsed=Number(value);if(!Number.isSafeInteger(parsed))throw new EverfurWebhookVerificationError("malformed_header");timestamp=parsed}else key===SIGNATURE_SCHEME&&signatures.push(value)}if(timestamp===null||signatures.length===0)throw new EverfurWebhookVerificationError("malformed_header");return{timestamp:timestamp,signatures:signatures}}function parseEnvelope(body){let json;try{json=JSON.parse(Buffer.from(body.buffer,body.byteOffset,body.byteLength).toString("utf8"))}catch{throw new EverfurWebhookVerificationError("malformed_payload")}if(!isRecord(json))throw new EverfurWebhookVerificationError("malformed_payload");let{id:id,object:object,type:type,api_version:apiVersion,created:created,livemode:livemode,data:data}=json;if(typeof id!="string"||id.length===0||object!=="event"||typeof type!="string"||type.length===0||typeof apiVersion!="string"||typeof created!="number"||typeof livemode!="boolean"||!isRecord(data)||!isRecord(data.object))throw new EverfurWebhookVerificationError("malformed_payload");return json}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;var SDK_VERSION="0.18.1",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
4
+ return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var EVERFUR_SIGNATURE_HEADER="Everfur-Signature",DEFAULT_WEBHOOK_TOLERANCE_SECONDS=300,SIGNATURE_SCHEME="v1",MAX_HEADER_LENGTH=4096,HEX_SHA256_LENGTH=64,DIGITS=/^[0-9]+$/,EverfurWebhookVerificationError=class _EverfurWebhookVerificationError extends Error{constructor(code){super(`Everfur webhook verification failed: ${code}`),this.name="EverfurWebhookVerificationError",this.code=code,Object.setPrototypeOf(this,_EverfurWebhookVerificationError.prototype)}};function constructEvent(payload,signatureHeader,secrets,options={}){let body=rawBodyBytes(payload),keys=requireSecrets(secrets),tolerance=options.toleranceSeconds??DEFAULT_WEBHOOK_TOLERANCE_SECONDS;if(!Number.isInteger(tolerance)||tolerance<0)throw new EverfurConfigError("invalid-argument","toleranceSeconds must be a non-negative integer");let parsed=parseSignatureHeader(signatureHeader),now=options.nowSeconds??Math.floor(Date.now()/1e3);if(Math.abs(now-parsed.timestamp)>tolerance)throw new EverfurWebhookVerificationError("timestamp_outside_tolerance");let matched=false;for(let key of keys){let expected=Buffer.from(computeSignature(key,parsed.timestamp,body),"ascii");for(let candidate of parsed.signatures){if(candidate.length!==HEX_SHA256_LENGTH)continue;let actual=Buffer.from(candidate,"utf8");actual.length===expected.length&&timingSafeEqual(expected,actual)&&(matched=true)}}if(!matched)throw new EverfurWebhookVerificationError("no_matching_signature");return parseEnvelope(body)}function generateTestSignatureHeader(params){let body=rawBodyBytes(params.payload),keys=requireSecrets(params.secrets),timestamp=params.timestamp??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(timestamp)||timestamp<0)throw new EverfurConfigError("invalid-argument","timestamp must be a non-negative integer (unix seconds)");return[`t=${timestamp}`,...keys.map(key=>`${SIGNATURE_SCHEME}=${computeSignature(key,timestamp,body)}`)].join(",")}function computeSignature(secret,timestamp,body){return createHmac("sha256",Buffer.from(secret,"utf8")).update(`${timestamp}.`,"ascii").update(body).digest("hex")}function rawBodyBytes(payload){if(typeof payload=="string")return Buffer.from(payload,"utf8");if(payload instanceof Uint8Array)return payload;throw new EverfurConfigError("invalid-argument","constructEvent needs the raw request body (a string or a Buffer), not parsed JSON: re-serialised JSON does not reproduce the signed bytes.")}function requireSecrets(secrets){let list=typeof secrets=="string"?[secrets]:Array.isArray(secrets)?secrets:[];if(list.length===0||list.some(s=>typeof s!="string"||s.length===0))throw new EverfurConfigError("invalid-argument","at least one non-empty webhook signing secret is required");return list}function parseSignatureHeader(header){if(typeof header!="string"||header.length===0||header.length>MAX_HEADER_LENGTH)throw new EverfurWebhookVerificationError("malformed_header");let timestamp=null,signatures=[];for(let item of header.split(",")){let trimmed=item.trim(),at=trimmed.indexOf("=");if(at<0)throw new EverfurWebhookVerificationError("malformed_header");let key=trimmed.slice(0,at),value=trimmed.slice(at+1);if(key==="t"){if(timestamp!==null||!DIGITS.test(value))throw new EverfurWebhookVerificationError("malformed_header");let parsed=Number(value);if(!Number.isSafeInteger(parsed))throw new EverfurWebhookVerificationError("malformed_header");timestamp=parsed}else key===SIGNATURE_SCHEME&&signatures.push(value)}if(timestamp===null||signatures.length===0)throw new EverfurWebhookVerificationError("malformed_header");return{timestamp:timestamp,signatures:signatures}}function parseEnvelope(body){let json;try{json=JSON.parse(Buffer.from(body.buffer,body.byteOffset,body.byteLength).toString("utf8"))}catch{throw new EverfurWebhookVerificationError("malformed_payload")}if(!isRecord(json))throw new EverfurWebhookVerificationError("malformed_payload");let{id:id,object:object,type:type,api_version:apiVersion,created:created,livemode:livemode,data:data}=json;if(typeof id!="string"||id.length===0||object!=="event"||typeof type!="string"||type.length===0||typeof apiVersion!="string"||typeof created!="number"||typeof livemode!="boolean"||!isRecord(data)||!isRecord(data.object))throw new EverfurWebhookVerificationError("malformed_payload");return json}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;var SDK_VERSION="0.18.3",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
5
5
  return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function resolveApiBaseUrl(apiBaseUrl){let outcome=tryResolveApiBaseUrl(apiBaseUrl);if(!outcome.ok)throw new EverfurConfigError("invalid-argument",outcome.failure.message);return outcome.value}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
6
6
  return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
7
7
  /* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
@@ -96,4 +96,4 @@ return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){le
96
96
  /* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
97
97
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
98
98
  /* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
99
- /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"unknown"}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var REQUEST_ID_HEADER="x-request-id";function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?foldDailyQuotaWireCode(code,body):null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var EVERFUR_WEBHOOK_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","visit.booked","visit.cancelled","visit.completed","visit.no_show","record_request.updated","record.ready","webhook_endpoint.test","chat.follow_up_due","chat.urgency.flagged","pet.vaccination.due","visit.rescheduled","visit.reminder","visit.followup_sent","chat.reminder_due","record.activation","visit.message_received","visit.ended","contact.exported","health_plan.box_due","health_plan.one_box_ordered","claim.evidence_returned","claim.evidence_updated","claim.records_requested","claim.failed","claim.duplicate","claim.decided","claim.inbound_refused","insured_pet.profile.ready","insured_pet.profile.updated"]),EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","chat.urgency.flagged","webhook_endpoint.test","contact.exported","health_plan.box_due","health_plan.one_box_ordered","claim.evidence_returned","claim.evidence_updated","claim.records_requested","claim.failed","claim.duplicate","claim.decided","claim.inbound_refused","insured_pet.profile.ready","insured_pet.profile.updated"]);function isEverfurWebhookEventType(type){return typeof type=="string"&&EVERFUR_WEBHOOK_EVENT_TYPES.includes(type)}function isEverfurWebhookEvent(event){return isEverfurWebhookEventType(event.type)}var PARTNER_INBOUND_EVENT_TYPES=/* @__PURE__ */Object.freeze(["pet.profile.updated","pet.incident.reported","pet.behavior_note.added","pet.service_score.recorded","pet.deleted","member.status_changed","member.deleted"]);var SECRET_KEY_PREFIXES=["sk_partner_","rk_partner_"];function assertServerSecretKey(value,action){if(typeof value!="string"||value.length===0)throw new EverfurConfigError("invalid-argument","partnerSecretKey is required");if(value.startsWith("pk_"))throw new EverfurConfigError("invalid-argument",`partnerSecretKey is a publishable key (pk_...): ${action} needs your secret key, server side only`);if(!SECRET_KEY_PREFIXES.some(prefix=>value.startsWith(prefix)))throw new EverfurConfigError("invalid-argument","partnerSecretKey must be an sk_partner_ secret key or an rk_partner_ restricted key")}var USER_REF_MAX=128;function assertValidUserRef(raw){let length=typeof raw=="string"?[...raw].length:0;if(typeof raw!="string"||length<1||length>USER_REF_MAX)throw new EverfurConfigError("invalid-argument",`user_ref must be 1..${USER_REF_MAX} characters`);if(raw.trim().length===0)throw new EverfurConfigError("invalid-argument","user_ref must not be blank: the server strips surrounding whitespace before validating, so a whitespace-only value arrives empty and is rejected as required.");if(raw!==raw.trim())throw new EverfurConfigError("invalid-argument","user_ref must not have leading or trailing whitespace: the server strips it, so padded and unpadded forms of the same id resolve to ONE user. Pass the exact id you want to key on.");if(raw.includes("@"))throw new EverfurConfigError("invalid-argument","user_ref must not contain '@'");if(!isPrintable(raw))throw new EverfurConfigError("invalid-argument","user_ref must be printable (no control characters)");return raw}function isPrintable(value){return!NON_PRINTABLE.test(value)}var NON_PRINTABLE=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}]|(?!\u0020)[\p{Zs}]/u;function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var PROFILE_FIELDS=[["name","name"],["species","species"],["breed","breed"],["ageYears","age_years"],["weightKg","weight_kg"],["partnerLabelInstructions","partner_label_instructions"]];function partnerPetProfileBody(profile){if(typeof profile!="object"||profile===null||Array.isArray(profile))throw new EverfurConfigError("invalid-argument","the pet profile must be an object");let body={};for(let[key,wire]of PROFILE_FIELDS)profile[key]!==void 0&&(body[wire]=profile[key]);let health=petHealthToWire(profile,profile.species);if("error"in health)throw new EverfurConfigError("invalid-argument",health.error);return Object.assign(body,health.body)}var IDEMPOTENCY_KEY_SHAPE=/^[\x21-\x7e]{1,255}$/,MAX_BODY_BYTES=32*1024,DATE_TIME_WITH_OFFSET=/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})$/,SEND_TIMEOUT_MS=3e4,INBOUND_RULES=/* @__PURE__ */Object.freeze({"pet.profile.updated":{subject:"pet",schemaVersions:[1,2]},"pet.incident.reported":{subject:"pet",schemaVersions:[1]},"pet.behavior_note.added":{subject:"pet",schemaVersions:[1]},"pet.service_score.recorded":{subject:"pet",schemaVersions:[1]},"pet.deleted":{subject:"pet",schemaVersions:[1]},"member.status_changed":{subject:"member",schemaVersions:[1]},"member.deleted":{subject:"member",schemaVersions:[1]}});async function sendPartnerEvent(client,event,idempotencyKey){let key=idempotencyKey??randomUUID();if(typeof key!="string"||!IDEMPOTENCY_KEY_SHAPE.test(key))throw new EverfurConfigError("invalid-argument","idempotencyKey must be 1 to 255 visible ASCII characters (no spaces, no control or non-ASCII characters)");assertServerSecretKey(client.partnerSecretKey,"sending events");let payload=serialize(buildBody(event)),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}/partners/events`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","idempotency-key":key,"x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),SEND_TIMEOUT_MS),res;try{res=await fetchImpl(url,{method:"POST",headers:headers,body:payload,signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=null;try{json=await res.json()}catch{json=null}let requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let receipt=parseReceipt(json,key);return receipt?ok(receipt):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function isInboundType(value){return typeof value=="string"&&PARTNER_INBOUND_EVENT_TYPES.includes(value)}function buildBody(event){if(typeof event!="object"||event===null)throw new EverfurConfigError("invalid-argument","event is required");if(!isInboundType(event.type))throw new EverfurConfigError("invalid-argument",`event.type must be one of ${PARTNER_INBOUND_EVENT_TYPES.join(", ")}`);let rule=INBOUND_RULES[event.type],schemaVersion=event.schemaVersion??1;if(typeof schemaVersion!="number"||!rule.schemaVersions.includes(schemaVersion))throw new EverfurConfigError("invalid-argument",`event.schemaVersion must be one of ${rule.schemaVersions.join(", ")} for ${event.type}`);let userRef=assertValidUserRef(event.userRef);if(rule.subject==="pet"&&event.petRef===void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is required for ${event.type}`);if(rule.subject==="member"&&event.petRef!==void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is not accepted on ${event.type}`);let petRef=event.petRef===void 0?void 0:assertValidPetRef(event.petRef);if(typeof event.data!="object"||event.data===null||Array.isArray(event.data))throw new EverfurConfigError("invalid-argument","event.data must be an object");let data=event.type==="pet.profile.updated"&&schemaVersion===2?partnerPetProfileBody(event.data):event.data,body={type:event.type,schema_version:schemaVersion,user_ref:userRef,occurred_at:occurredAtIso(event.occurredAt),data:data};return petRef!==void 0&&(body.pet_ref=petRef),body}function assertValidPetRef(raw){try{return assertValidUserRef(raw)}catch(cause){throw cause instanceof EverfurConfigError?new EverfurConfigError("invalid-argument",`event.petRef follows the user_ref rule: ${cause.message}`):cause}}function occurredAtIso(value){if(typeof value=="string"&&!DATE_TIME_WITH_OFFSET.test(value))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");let date2=value instanceof Date?value:typeof value=="string"?new Date(value):new Date(Number.NaN);if(Number.isNaN(date2.getTime()))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");return date2.toISOString()}function serialize(body){let payload;try{payload=JSON.stringify(body)}catch{throw new EverfurConfigError("invalid-argument","event.data must be JSON-serialisable")}let bytes=(new TextEncoder).encode(payload).byteLength;if(bytes>MAX_BODY_BYTES)throw new EverfurConfigError("invalid-argument",`the event is ${bytes} bytes once serialised; Everfur accepts at most ${MAX_BODY_BYTES} (32 KB)`);return payload}function parseReceipt(json,idempotencyKey){if(typeof json!="object"||json===null)return null;let obj=json,id=obj.id,type=obj.type,schemaVersion=obj.schema_version,userRef=obj.user_ref,petRef=obj.pet_ref??null,occurredAt=obj.occurred_at,receivedAt=obj.received_at,status=obj.status,livemode=obj.livemode;return typeof id!="string"||id.length===0||!isInboundType(type)||typeof schemaVersion!="number"||typeof userRef!="string"||petRef!==null&&typeof petRef!="string"||typeof occurredAt!="string"||typeof receivedAt!="string"||typeof status!="string"||typeof livemode!="boolean"?null:/* @__PURE__ */Object.freeze({id:id,type:type,schemaVersion:schemaVersion,userRef:userRef,petRef:petRef,occurredAt:occurredAt,receivedAt:receivedAt,status:status,livemode:livemode,idempotencyKey:idempotencyKey})}export{DEFAULT_WEBHOOK_TOLERANCE_SECONDS,EVERFUR_SIGNATURE_HEADER,EVERFUR_WEBHOOK_EVENT_TYPES,EVERFUR_WEBHOOK_ONLY_EVENT_TYPES,EverfurWebhookVerificationError,PARTNER_INBOUND_EVENT_TYPES,constructEvent,generateTestSignatureHeader,isEverfurWebhookEvent,isEverfurWebhookEventType,sendPartnerEvent};
99
+ /* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"unknown"}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var REQUEST_ID_HEADER="x-request-id";function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?foldDailyQuotaWireCode(code,body):null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var EVERFUR_WEBHOOK_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","visit.booked","visit.cancelled","visit.completed","visit.no_show","record_request.updated","record.ready","webhook_endpoint.test","chat.follow_up_due","chat.urgency.flagged","pet.vaccination.due","visit.rescheduled","visit.reminder","visit.followup_sent","chat.reminder_due","record.activation","visit.message_received","visit.ended","contact.exported","health_plan.box_due","health_plan.one_box_ordered","claim.evidence_returned","claim.evidence_updated","claim.records_requested","claim.failed","claim.duplicate","claim.decided","claim.inbound_refused","insured_pet.profile.ready","insured_pet.profile.updated","chat.engagement_message"]),EVERFUR_WEBHOOK_ONLY_EVENT_TYPES=/* @__PURE__ */Object.freeze(["member.linked","member.unlinked","chat.urgency.flagged","webhook_endpoint.test","contact.exported","health_plan.box_due","health_plan.one_box_ordered","claim.evidence_returned","claim.evidence_updated","claim.records_requested","claim.failed","claim.duplicate","claim.decided","claim.inbound_refused","insured_pet.profile.ready","insured_pet.profile.updated","chat.engagement_message"]);function isEverfurWebhookEventType(type){return typeof type=="string"&&EVERFUR_WEBHOOK_EVENT_TYPES.includes(type)}function isEverfurWebhookEvent(event){return isEverfurWebhookEventType(event.type)}var PARTNER_INBOUND_EVENT_TYPES=/* @__PURE__ */Object.freeze(["pet.profile.updated","pet.incident.reported","pet.behavior_note.added","pet.service_score.recorded","pet.deleted","member.status_changed","member.deleted"]);var SECRET_KEY_PREFIXES=["sk_partner_","rk_partner_"];function assertServerSecretKey(value,action){if(typeof value!="string"||value.length===0)throw new EverfurConfigError("invalid-argument","partnerSecretKey is required");if(value.startsWith("pk_"))throw new EverfurConfigError("invalid-argument",`partnerSecretKey is a publishable key (pk_...): ${action} needs your secret key, server side only`);if(!SECRET_KEY_PREFIXES.some(prefix=>value.startsWith(prefix)))throw new EverfurConfigError("invalid-argument","partnerSecretKey must be an sk_partner_ secret key or an rk_partner_ restricted key")}var USER_REF_MAX=128;function assertValidUserRef(raw){let length=typeof raw=="string"?[...raw].length:0;if(typeof raw!="string"||length<1||length>USER_REF_MAX)throw new EverfurConfigError("invalid-argument",`user_ref must be 1..${USER_REF_MAX} characters`);if(raw.trim().length===0)throw new EverfurConfigError("invalid-argument","user_ref must not be blank: the server strips surrounding whitespace before validating, so a whitespace-only value arrives empty and is rejected as required.");if(raw!==raw.trim())throw new EverfurConfigError("invalid-argument","user_ref must not have leading or trailing whitespace: the server strips it, so padded and unpadded forms of the same id resolve to ONE user. Pass the exact id you want to key on.");if(raw.includes("@"))throw new EverfurConfigError("invalid-argument","user_ref must not contain '@'");if(!isPrintable(raw))throw new EverfurConfigError("invalid-argument","user_ref must be printable (no control characters)");return raw}function isPrintable(value){return!NON_PRINTABLE.test(value)}var NON_PRINTABLE=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}]|(?!\u0020)[\p{Zs}]/u;function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var PROFILE_FIELDS=[["name","name"],["species","species"],["breed","breed"],["ageYears","age_years"],["weightKg","weight_kg"],["partnerLabelInstructions","partner_label_instructions"]];function partnerPetProfileBody(profile){if(typeof profile!="object"||profile===null||Array.isArray(profile))throw new EverfurConfigError("invalid-argument","the pet profile must be an object");let body={};for(let[key,wire]of PROFILE_FIELDS)profile[key]!==void 0&&(body[wire]=profile[key]);let health=petHealthToWire(profile,profile.species);if("error"in health)throw new EverfurConfigError("invalid-argument",health.error);return Object.assign(body,health.body)}var IDEMPOTENCY_KEY_SHAPE=/^[\x21-\x7e]{1,255}$/,MAX_BODY_BYTES=32*1024,DATE_TIME_WITH_OFFSET=/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:?\d{2})$/,SEND_TIMEOUT_MS=3e4,INBOUND_RULES=/* @__PURE__ */Object.freeze({"pet.profile.updated":{subject:"pet",schemaVersions:[1,2]},"pet.incident.reported":{subject:"pet",schemaVersions:[1]},"pet.behavior_note.added":{subject:"pet",schemaVersions:[1]},"pet.service_score.recorded":{subject:"pet",schemaVersions:[1]},"pet.deleted":{subject:"pet",schemaVersions:[1]},"member.status_changed":{subject:"member",schemaVersions:[1]},"member.deleted":{subject:"member",schemaVersions:[1]}});async function sendPartnerEvent(client,event,idempotencyKey){let key=idempotencyKey??randomUUID();if(typeof key!="string"||!IDEMPOTENCY_KEY_SHAPE.test(key))throw new EverfurConfigError("invalid-argument","idempotencyKey must be 1 to 255 visible ASCII characters (no spaces, no control or non-ASCII characters)");assertServerSecretKey(client.partnerSecretKey,"sending events");let payload=serialize(buildBody(event)),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}/partners/events`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","idempotency-key":key,"x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),SEND_TIMEOUT_MS),res;try{res=await fetchImpl(url,{method:"POST",headers:headers,body:payload,signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=null;try{json=await res.json()}catch{json=null}let requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let receipt=parseReceipt(json,key);return receipt?ok(receipt):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function isInboundType(value){return typeof value=="string"&&PARTNER_INBOUND_EVENT_TYPES.includes(value)}function buildBody(event){if(typeof event!="object"||event===null)throw new EverfurConfigError("invalid-argument","event is required");if(!isInboundType(event.type))throw new EverfurConfigError("invalid-argument",`event.type must be one of ${PARTNER_INBOUND_EVENT_TYPES.join(", ")}`);let rule=INBOUND_RULES[event.type],schemaVersion=event.schemaVersion??1;if(typeof schemaVersion!="number"||!rule.schemaVersions.includes(schemaVersion))throw new EverfurConfigError("invalid-argument",`event.schemaVersion must be one of ${rule.schemaVersions.join(", ")} for ${event.type}`);let userRef=assertValidUserRef(event.userRef);if(rule.subject==="pet"&&event.petRef===void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is required for ${event.type}`);if(rule.subject==="member"&&event.petRef!==void 0)throw new EverfurConfigError("invalid-argument",`event.petRef is not accepted on ${event.type}`);let petRef=event.petRef===void 0?void 0:assertValidPetRef(event.petRef);if(typeof event.data!="object"||event.data===null||Array.isArray(event.data))throw new EverfurConfigError("invalid-argument","event.data must be an object");let data=event.type==="pet.profile.updated"&&schemaVersion===2?partnerPetProfileBody(event.data):event.data,body={type:event.type,schema_version:schemaVersion,user_ref:userRef,occurred_at:occurredAtIso(event.occurredAt),data:data};return petRef!==void 0&&(body.pet_ref=petRef),body}function assertValidPetRef(raw){try{return assertValidUserRef(raw)}catch(cause){throw cause instanceof EverfurConfigError?new EverfurConfigError("invalid-argument",`event.petRef follows the user_ref rule: ${cause.message}`):cause}}function occurredAtIso(value){if(typeof value=="string"&&!DATE_TIME_WITH_OFFSET.test(value))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");let date2=value instanceof Date?value:typeof value=="string"?new Date(value):new Date(Number.NaN);if(Number.isNaN(date2.getTime()))throw new EverfurConfigError("invalid-argument","event.occurredAt must be a Date or an ISO 8601 date-time with an explicit offset (Z or +05:30)");return date2.toISOString()}function serialize(body){let payload;try{payload=JSON.stringify(body)}catch{throw new EverfurConfigError("invalid-argument","event.data must be JSON-serialisable")}let bytes=(new TextEncoder).encode(payload).byteLength;if(bytes>MAX_BODY_BYTES)throw new EverfurConfigError("invalid-argument",`the event is ${bytes} bytes once serialised; Everfur accepts at most ${MAX_BODY_BYTES} (32 KB)`);return payload}function parseReceipt(json,idempotencyKey){if(typeof json!="object"||json===null)return null;let obj=json,id=obj.id,type=obj.type,schemaVersion=obj.schema_version,userRef=obj.user_ref,petRef=obj.pet_ref??null,occurredAt=obj.occurred_at,receivedAt=obj.received_at,status=obj.status,livemode=obj.livemode;return typeof id!="string"||id.length===0||!isInboundType(type)||typeof schemaVersion!="number"||typeof userRef!="string"||petRef!==null&&typeof petRef!="string"||typeof occurredAt!="string"||typeof receivedAt!="string"||typeof status!="string"||typeof livemode!="boolean"?null:/* @__PURE__ */Object.freeze({id:id,type:type,schemaVersion:schemaVersion,userRef:userRef,petRef:petRef,occurredAt:occurredAt,receivedAt:receivedAt,status:status,livemode:livemode,idempotencyKey:idempotencyKey})}export{DEFAULT_WEBHOOK_TOLERANCE_SECONDS,EVERFUR_SIGNATURE_HEADER,EVERFUR_WEBHOOK_EVENT_TYPES,EVERFUR_WEBHOOK_ONLY_EVENT_TYPES,EverfurWebhookVerificationError,PARTNER_INBOUND_EVENT_TYPES,constructEvent,generateTestSignatureHeader,isEverfurWebhookEvent,isEverfurWebhookEventType,sendPartnerEvent};