@everfur/sdk 0.1.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/CHANGELOG.md +703 -4
  2. package/README.md +63 -23
  3. package/consent/package.json +8 -0
  4. package/dist/Chat-BZZ-Py5l.d.ts +128 -0
  5. package/dist/Chat-Dq4fffIO.d.cts +128 -0
  6. package/dist/DepthViews-BG3E25MD.d.ts +16 -0
  7. package/dist/DepthViews-B_hIypI6.d.cts +19 -0
  8. package/dist/DepthViews-CL75jyRA.d.cts +16 -0
  9. package/dist/DepthViews-CkYri51q.d.ts +19 -0
  10. package/dist/ErrorPolicyPort-CNf4uQZP.d.cts +22 -0
  11. package/dist/ErrorPolicyPort-CwbfmxzJ.d.ts +22 -0
  12. package/dist/{EverfurResult-D92-uL82.d.cts → EverfurResult-DN9pL2Ab.d.cts} +11 -10
  13. package/dist/{EverfurResult-D92-uL82.d.ts → EverfurResult-DN9pL2Ab.d.ts} +11 -10
  14. package/dist/{PhotoController-BItt5M7u.d.cts → PhotoController-3l7MT9jA.d.cts} +1 -1
  15. package/dist/{PhotoController-D8zMTdcW.d.ts → PhotoController-vzY5bfY_.d.ts} +1 -1
  16. package/dist/animations/index.cjs +1 -1997
  17. package/dist/animations/index.d.cts +35 -35
  18. package/dist/animations/index.d.ts +35 -35
  19. package/dist/animations/index.js +1 -1972
  20. package/dist/attachments-BorG422I.d.cts +146 -0
  21. package/dist/attachments-BrUWQYNK.d.ts +257 -0
  22. package/dist/attachments-D_SECjr1.d.cts +257 -0
  23. package/dist/attachments-DpldrvIW.d.ts +146 -0
  24. package/dist/bookingCopy-CqtDYvCR.d.ts +732 -0
  25. package/dist/bookingCopy-SREvkG19.d.cts +732 -0
  26. package/dist/branding-CsRdeNwK.d.cts +566 -0
  27. package/dist/branding-CsRdeNwK.d.ts +566 -0
  28. package/dist/callCopy-DoQKG3-L.d.cts +40 -0
  29. package/dist/callCopy-DoQKG3-L.d.ts +40 -0
  30. package/dist/casesRepository-DwtZVsbj.d.cts +51 -0
  31. package/dist/casesRepository-v6QczS9N.d.ts +51 -0
  32. package/dist/chat/index.cjs +1 -1170
  33. package/dist/chat/index.d.cts +32 -53
  34. package/dist/chat/index.d.ts +32 -53
  35. package/dist/chat/index.js +1 -1167
  36. package/dist/client/index.cjs +9 -2315
  37. package/dist/client/index.d.cts +80 -16
  38. package/dist/client/index.d.ts +80 -16
  39. package/dist/client/index.js +9 -2215
  40. package/dist/{config-CiJ0PVBB.d.ts → config--Wu1Umhd.d.cts} +64 -26
  41. package/dist/{config-BSjBdxrZ.d.cts → config-C7eb_IMD.d.ts} +64 -26
  42. package/dist/consent/index.cjs +1 -0
  43. package/dist/consent/index.d.cts +33 -0
  44. package/dist/consent/index.d.ts +33 -0
  45. package/dist/consent/index.js +1 -0
  46. package/dist/context-CL3lyuy1.d.cts +159 -0
  47. package/dist/context-CahAEha8.d.ts +159 -0
  48. package/dist/copy-DdVFDL01.d.ts +198 -0
  49. package/dist/copy-UeUJVk8X.d.cts +198 -0
  50. package/dist/core/index.cjs +13 -3178
  51. package/dist/core/index.d.cts +164 -29
  52. package/dist/core/index.d.ts +164 -29
  53. package/dist/core/index.js +13 -3166
  54. package/dist/depth-D5HwcvKC.d.cts +533 -0
  55. package/dist/depth-DvPwPuT_.d.ts +533 -0
  56. package/dist/entitlementRepository-B7egEdW6.d.ts +43 -0
  57. package/dist/entitlementRepository-BpJ7tiwl.d.cts +43 -0
  58. package/dist/{identity-Brl-lDd6.d.cts → identity-C2-08BZW.d.cts} +20 -7
  59. package/dist/{identity-DK9zORrG.d.ts → identity-CEi9GRFZ.d.ts} +20 -7
  60. package/dist/{ids-CJ1S6adf.d.cts → ids-B2GAAifq.d.cts} +1 -1
  61. package/dist/{ids-CJ1S6adf.d.ts → ids-B2GAAifq.d.ts} +1 -1
  62. package/dist/index.cjs +12 -4494
  63. package/dist/index.d.cts +30 -121
  64. package/dist/index.d.ts +30 -121
  65. package/dist/index.js +12 -4470
  66. package/dist/models-B-Uh2LTf.d.ts +214 -0
  67. package/dist/models-D2EUxPZY.d.cts +214 -0
  68. package/dist/notifications/index.cjs +2 -0
  69. package/dist/notifications/index.d.cts +17 -0
  70. package/dist/notifications/index.d.ts +17 -0
  71. package/dist/notifications/index.js +2 -0
  72. package/dist/optionalModule-DbJmsq5f.d.cts +21 -0
  73. package/dist/optionalModule-DbJmsq5f.d.ts +21 -0
  74. package/dist/pets-DJv2sj2H.d.ts +92 -0
  75. package/dist/pets-JVCXgRgR.d.cts +92 -0
  76. package/dist/petsRepository-B_gKbAzJ.d.cts +142 -0
  77. package/dist/petsRepository-Bk6GDwLs.d.ts +142 -0
  78. package/dist/photo/index.cjs +1 -2189
  79. package/dist/photo/index.d.cts +6 -6
  80. package/dist/photo/index.d.ts +6 -6
  81. package/dist/photo/index.js +1 -2186
  82. package/dist/ports-BN6RHF9W.d.cts +48 -0
  83. package/dist/ports-BN6RHF9W.d.ts +48 -0
  84. package/dist/ports-BY2ph0_y.d.cts +376 -0
  85. package/dist/ports-D7YW8qz9.d.ts +376 -0
  86. package/dist/profile-CSs1wlXT.d.cts +93 -0
  87. package/dist/profile-CSs1wlXT.d.ts +93 -0
  88. package/dist/records/depth/index.cjs +2 -0
  89. package/dist/records/depth/index.d.cts +13 -0
  90. package/dist/records/depth/index.d.ts +13 -0
  91. package/dist/records/depth/index.js +2 -0
  92. package/dist/records/index.cjs +3 -2839
  93. package/dist/records/index.d.cts +137 -203
  94. package/dist/records/index.d.ts +137 -203
  95. package/dist/records/index.js +3 -2833
  96. package/dist/requestFunnel-BjDpqqvm.d.cts +110 -0
  97. package/dist/requestFunnel-DFMGcluw.d.ts +110 -0
  98. package/dist/{resolve-Dq_4_agU.d.ts → resolve-D4Ywz5OS.d.cts} +10 -4
  99. package/dist/{resolve-Dq_4_agU.d.cts → resolve-D4Ywz5OS.d.ts} +10 -4
  100. package/dist/{runtime-Bvr8yqXm.d.cts → runtimeTypes-gZEJu-da.d.cts} +104 -132
  101. package/dist/{runtime-BIYzf9cK.d.ts → runtimeTypes-w5KqBMcs.d.ts} +104 -132
  102. package/dist/server/events/index.cjs +2 -0
  103. package/dist/server/events/index.d.cts +550 -0
  104. package/dist/server/events/index.d.ts +550 -0
  105. package/dist/server/events/index.js +2 -0
  106. package/dist/server/index.cjs +2 -533
  107. package/dist/server/index.d.cts +73 -18
  108. package/dist/server/index.d.ts +73 -18
  109. package/dist/server/index.js +2 -530
  110. package/dist/species-BXAIMh7I.d.cts +9 -0
  111. package/dist/species-BXAIMh7I.d.ts +9 -0
  112. package/dist/televet/booking/index.cjs +1 -0
  113. package/dist/televet/booking/index.d.cts +294 -0
  114. package/dist/televet/booking/index.d.ts +294 -0
  115. package/dist/televet/booking/index.js +1 -0
  116. package/dist/televet/call/index.cjs +1 -0
  117. package/dist/televet/call/index.d.cts +141 -0
  118. package/dist/televet/call/index.d.ts +141 -0
  119. package/dist/televet/call/index.js +1 -0
  120. package/dist/televet/index.cjs +1 -0
  121. package/dist/televet/index.d.cts +142 -0
  122. package/dist/televet/index.d.ts +142 -0
  123. package/dist/televet/index.js +1 -0
  124. package/dist/testing/index.cjs +5 -823
  125. package/dist/testing/index.d.cts +18 -4
  126. package/dist/testing/index.d.ts +18 -4
  127. package/dist/testing/index.js +5 -820
  128. package/dist/testing/rn/index.cjs +1 -449
  129. package/dist/testing/rn/index.d.cts +18 -29
  130. package/dist/testing/rn/index.d.ts +18 -29
  131. package/dist/testing/rn/index.js +1 -444
  132. package/dist/testing/web/index.cjs +1 -0
  133. package/dist/testing/web/index.d.cts +132 -0
  134. package/dist/testing/web/index.d.ts +132 -0
  135. package/dist/testing/web/index.js +1 -0
  136. package/dist/timelineRows-C15jxFFH.d.ts +19 -0
  137. package/dist/timelineRows-odO8g9r2.d.cts +19 -0
  138. package/dist/typeStyle-CKqVYD6L.d.cts +111 -0
  139. package/dist/typeStyle-DmoyacDG.d.ts +111 -0
  140. package/dist/uploadTransport-D0M0T4hN.d.ts +38 -0
  141. package/dist/uploadTransport-DKJHs3Yj.d.cts +38 -0
  142. package/dist/useRecordsDepth-C6rjEaLn.d.cts +237 -0
  143. package/dist/useRecordsDepth-crhBllQK.d.ts +237 -0
  144. package/dist/useVetVisit-Bc84hWUU.d.cts +187 -0
  145. package/dist/useVetVisit-CjmMa896.d.ts +187 -0
  146. package/dist/video/index.cjs +1 -1941
  147. package/dist/video/index.d.cts +4 -4
  148. package/dist/video/index.d.ts +4 -4
  149. package/dist/video/index.js +1 -1938
  150. package/dist/view-Bxwxp4xD.d.ts +310 -0
  151. package/dist/view-DyitEO0m.d.cts +310 -0
  152. package/dist/visitIntent-D7_yVp1I.d.cts +8 -0
  153. package/dist/visitIntent-D7_yVp1I.d.ts +8 -0
  154. package/dist/web/consent/index.cjs +1 -0
  155. package/dist/web/consent/index.d.cts +34 -0
  156. package/dist/web/consent/index.d.ts +34 -0
  157. package/dist/web/consent/index.js +1 -0
  158. package/dist/web/index.cjs +14 -0
  159. package/dist/web/index.d.cts +218 -0
  160. package/dist/web/index.d.ts +218 -0
  161. package/dist/web/index.js +14 -0
  162. package/dist/web/notifications/index.cjs +2 -0
  163. package/dist/web/notifications/index.d.cts +213 -0
  164. package/dist/web/notifications/index.d.ts +213 -0
  165. package/dist/web/notifications/index.js +2 -0
  166. package/dist/web/records/depth/index.cjs +2 -0
  167. package/dist/web/records/depth/index.d.cts +12 -0
  168. package/dist/web/records/depth/index.d.ts +12 -0
  169. package/dist/web/records/depth/index.js +2 -0
  170. package/dist/web/records/index.cjs +4 -0
  171. package/dist/web/records/index.d.cts +285 -0
  172. package/dist/web/records/index.d.ts +285 -0
  173. package/dist/web/records/index.js +4 -0
  174. package/dist/web/televet/booking/index.cjs +1 -0
  175. package/dist/web/televet/booking/index.d.cts +349 -0
  176. package/dist/web/televet/booking/index.d.ts +349 -0
  177. package/dist/web/televet/booking/index.js +1 -0
  178. package/dist/web/televet/call/index.cjs +1 -0
  179. package/dist/web/televet/call/index.d.cts +142 -0
  180. package/dist/web/televet/call/index.d.ts +142 -0
  181. package/dist/web/televet/call/index.js +1 -0
  182. package/dist/web/televet/index.cjs +1 -0
  183. package/dist/web/televet/index.d.cts +136 -0
  184. package/dist/web/televet/index.d.ts +136 -0
  185. package/dist/web/televet/index.js +1 -0
  186. package/notifications/package.json +8 -0
  187. package/package.json +266 -10
  188. package/records/depth/package.json +8 -0
  189. package/server/events/device-blocked.cjs +15 -0
  190. package/server/events/package.json +9 -0
  191. package/televet/booking/package.json +8 -0
  192. package/televet/call/package.json +8 -0
  193. package/televet/package.json +8 -0
  194. package/testing/web/native-blocked.cjs +12 -0
  195. package/testing/web/package.json +8 -0
  196. package/web/consent/native-blocked.cjs +12 -0
  197. package/web/consent/package.json +8 -0
  198. package/web/native-blocked.cjs +12 -0
  199. package/web/notifications/native-blocked.cjs +12 -0
  200. package/web/notifications/package.json +8 -0
  201. package/web/package.json +8 -0
  202. package/web/records/depth/native-blocked.cjs +12 -0
  203. package/web/records/depth/package.json +8 -0
  204. package/web/records/native-blocked.cjs +12 -0
  205. package/web/records/package.json +8 -0
  206. package/web/televet/booking/native-blocked.cjs +12 -0
  207. package/web/televet/booking/package.json +8 -0
  208. package/web/televet/call/native-blocked.cjs +12 -0
  209. package/web/televet/call/package.json +8 -0
  210. package/web/televet/native-blocked.cjs +12 -0
  211. package/web/televet/package.json +8 -0
  212. package/dist/ChatController-CKdBvPj2.d.ts +0 -146
  213. package/dist/ChatController-CpUMvvZf.d.cts +0 -146
  214. package/dist/FilePort-BabWrv7I.d.cts +0 -22
  215. package/dist/FilePort-BabWrv7I.d.ts +0 -22
  216. package/dist/petsRepository-BEGb97M9.d.cts +0 -326
  217. package/dist/petsRepository-Bu18r2kK.d.ts +0 -326
  218. package/dist/requestFunnel-DuUH-kAe.d.cts +0 -28
  219. package/dist/requestFunnel-dio5OmR9.d.ts +0 -28
@@ -1,3178 +1,13 @@
1
- 'use strict';
2
-
3
- var zod = require('zod');
4
-
5
- // src/client/errors/EverfurResult.ts
6
- function ok(value, warning) {
7
- return Object.freeze(
8
- { ok: true, value }
9
- );
10
- }
11
- function err(error) {
12
- return Object.freeze({ ok: false, error });
13
- }
14
- var EverfurConfigError = class _EverfurConfigError extends Error {
15
- constructor(kind, message) {
16
- super(message);
17
- this.name = "EverfurConfigError";
18
- this.kind = kind;
19
- Object.setPrototypeOf(this, _EverfurConfigError.prototype);
20
- }
21
- };
22
-
23
- // src/core/ports/SecureStorePort.ts
24
- var NULL_SECURE_STORE = Object.freeze({
25
- isAvailable: false,
26
- async getSecret() {
27
- return null;
28
- },
29
- async setSecret() {
30
- throw new EverfurConfigError(
31
- "not-initialized",
32
- "EF_NO_SECURE_STORE: token persistence requires an explicit SecureStorePort"
33
- );
34
- },
35
- async deleteSecret() {
36
- }
37
- });
38
-
39
- // src/core/ports/TelemetryPort.ts
40
- var noopTelemetry = Object.freeze({
41
- track() {
42
- },
43
- trackExpectedFailure() {
44
- }
45
- });
46
- var CONTRACT_RETRYABILITY = Object.freeze([
47
- Object.freeze({ wireCode: "AccessDeniedException", envelope: "http_envelope", httpStatus: 403, retryable: false }),
48
- Object.freeze({ wireCode: "AuthorizationException", envelope: "http_envelope", httpStatus: 401, retryable: false }),
49
- Object.freeze({ wireCode: "ConflictException", envelope: "http_envelope", httpStatus: 409, retryable: true }),
50
- Object.freeze({ wireCode: "DAILY_QUOTA_EXCEEDED", envelope: "http_envelope", httpStatus: 429, retryable: true }),
51
- Object.freeze({ wireCode: "IDEMPOTENCY_KEY_IN_FLIGHT", envelope: "http_envelope", httpStatus: 409, retryable: true }),
52
- Object.freeze({ wireCode: "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST", envelope: "http_envelope", httpStatus: 409, retryable: false }),
53
- Object.freeze({ wireCode: "InternalFailureException", envelope: "http_envelope", httpStatus: 500, retryable: true }),
54
- Object.freeze({ wireCode: "NotImplementedException", envelope: "http_envelope", httpStatus: 501, retryable: false }),
55
- Object.freeze({ wireCode: "PaymentRequiredException", envelope: "http_envelope", httpStatus: 402, retryable: false }),
56
- Object.freeze({ wireCode: "ResourceNotFoundException", envelope: "http_envelope", httpStatus: 404, retryable: false }),
57
- Object.freeze({ wireCode: "ServiceUnavailableException", envelope: "http_envelope", httpStatus: 503, retryable: true }),
58
- Object.freeze({ wireCode: "TIER_UPGRADE_REQUIRED", envelope: "http_envelope", httpStatus: 402, retryable: false }),
59
- Object.freeze({ wireCode: "ThrottlingException", envelope: "http_envelope", httpStatus: 429, retryable: true }),
60
- Object.freeze({ wireCode: "ValidationException", envelope: "http_envelope", httpStatus: 400, retryable: false }),
61
- Object.freeze({ wireCode: "accessDenied", envelope: "http_envelope", httpStatus: 403, retryable: false }),
62
- Object.freeze({ wireCode: "authExpired", envelope: "http_envelope", httpStatus: 401, retryable: true }),
63
- Object.freeze({ wireCode: "internal_error", envelope: "sse_frame", httpStatus: 200, retryable: false }),
64
- Object.freeze({ wireCode: "invalidRequest", envelope: "http_envelope", httpStatus: 400, retryable: false }),
65
- Object.freeze({ wireCode: "not_found", envelope: "sse_frame", httpStatus: 200, retryable: false }),
66
- Object.freeze({ wireCode: "session_required", envelope: "http_envelope", httpStatus: 403, retryable: false }),
67
- Object.freeze({ wireCode: "timeout", envelope: "sse_frame", httpStatus: 200, retryable: true }),
68
- Object.freeze({ wireCode: "unavailable", envelope: "http_envelope", httpStatus: 503, retryable: true })
69
- ]);
70
- Object.freeze(
71
- CONTRACT_RETRYABILITY.map((row) => row.wireCode)
72
- );
73
-
74
- // src/client/errors/contract.ts
75
- var NORMALIZED_FOLD = Object.freeze({
76
- // the default status-mapped envelope
77
- ValidationException: "validationFailed",
78
- AuthorizationException: "authRejected",
79
- PaymentRequiredException: "paymentRequired",
80
- AccessDeniedException: "accessDenied",
81
- ResourceNotFoundException: "resourceNotFound",
82
- ConflictException: "conflict",
83
- ThrottlingException: "rateLimited",
84
- InternalFailureException: "internalError",
85
- NotImplementedException: "notImplemented",
86
- ServiceUnavailableException: "serviceUnavailable",
87
- // dict-detail codes on the widget surface
88
- authExpired: "authExpired",
89
- unavailable: "serviceUnavailable",
90
- session_required: "sessionRequired",
91
- accessDenied: "accessDenied",
92
- invalidRequest: "sdkUpdateRequired",
93
- // typed codes
94
- IDEMPOTENCY_KEY_IN_FLIGHT: "idempotencyInFlight",
95
- IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST: "idempotencyConflict",
96
- DAILY_QUOTA_EXCEEDED: "quotaExceeded",
97
- TIER_UPGRADE_REQUIRED: "paymentRequired",
98
- // SSE error frames
99
- not_found: "conversationNotFound",
100
- timeout: "streamTimeout",
101
- internal_error: "internalError"
102
- });
103
- var CONTRACT_ERROR_ROWS = Object.freeze(
104
- CONTRACT_RETRYABILITY.map(
105
- (generated) => Object.freeze({
106
- wireCode: generated.wireCode,
107
- envelope: generated.envelope,
108
- retryable: generated.retryable,
109
- normalized: NORMALIZED_FOLD[generated.wireCode]
110
- })
111
- )
112
- );
113
- var BY_UPPER = new Map(
114
- CONTRACT_ERROR_ROWS.map((r) => [r.wireCode.toUpperCase(), r])
115
- );
116
- function contractErrorFor(wireCode) {
117
- if (typeof wireCode !== "string") return void 0;
118
- const key = wireCode.trim().toUpperCase();
119
- return key.length > 0 ? BY_UPPER.get(key) : void 0;
120
- }
121
- var CATEGORY_OF = Object.freeze({
122
- // the caller's sign-in state is wrong and a credential change is the remedy
123
- authExpired: "authentication",
124
- authRejected: "authentication",
125
- sessionRequired: "authentication",
126
- // signed in, correctly identified, and still not allowed
127
- accessDenied: "authorization",
128
- // a plan gate, not a permission failure: the remedy is commercial
129
- paymentRequired: "entitlement",
130
- // slow down / come back later
131
- quotaExceeded: "rateLimit",
132
- rateLimited: "rateLimit",
133
- // the request itself was wrong; retrying it unchanged can never succeed
134
- validationFailed: "invalidRequest",
135
- sdkUpdateRequired: "invalidRequest",
136
- // the target is gone, hidden, or was never visible to this caller
137
- conversationNotFound: "notFound",
138
- petNotFound: "notFound",
139
- resourceNotFound: "notFound",
140
- // something else already holds the thing
141
- conflict: "conflict",
142
- idempotencyConflict: "conflict",
143
- idempotencyInFlight: "conflict",
144
- // the pipe, not the request: timeouts, drops, a briefly unreachable dependency
145
- streamTimeout: "connection",
146
- streamIncomplete: "connection",
147
- upstreamLlmTimeout: "connection",
148
- serviceUnavailable: "connection",
149
- // the server admits fault
150
- internalError: "server",
151
- notImplemented: "server",
152
- mediaUploadFailed: "media",
153
- moderationBlocked: "policy",
154
- unknown: "unknown"
155
- });
156
- function categoryFor(code) {
157
- return CATEGORY_OF[code];
158
- }
159
- function fromWire(wire) {
160
- const contractRow = contractErrorFor(wire);
161
- if (contractRow) return contractRow.normalized;
162
- const upper = (wire ?? "").trim().toUpperCase();
163
- const canonical = upper.replace(/[^A-Z0-9]/g, "");
164
- if (canonical === "AUTHREJECTED") return "authRejected";
165
- if (upper.startsWith("AUTH")) return "authExpired";
166
- switch (canonical) {
167
- case "DAILYQUOTAEXCEEDED":
168
- case "QUOTAEXCEEDED":
169
- return "quotaExceeded";
170
- case "RATELIMITED":
171
- case "TOOMANYREQUESTS":
172
- return "rateLimited";
173
- case "IDEMPOTENCYKEYCONFLICT":
174
- case "IDEMPOTENCYCONFLICT":
175
- return "idempotencyConflict";
176
- case "ACCESSDENIED":
177
- case "FORBIDDEN":
178
- return "accessDenied";
179
- case "NOTFOUND":
180
- case "CONVERSATIONNOTFOUND":
181
- return "conversationNotFound";
182
- case "PETNOTFOUND":
183
- return "petNotFound";
184
- case "TIMEOUT":
185
- case "STREAMTIMEOUT":
186
- return "streamTimeout";
187
- // Analysis-domain deterministic 400s (NON-retryable). Additive per SPEC-00 §3.1 / SPEC-11b §2.6:
188
- // fold to a NON-retried target so the SDK never retries a permanently-failing bad-input request.
189
- // (Comment above the group so the empty fall-through cases stay lint-clean under no-fallthrough.)
190
- case "MEDIAUPLOADFAILED":
191
- case "UNRECOGNIZEDVIDEOFORMAT":
192
- case "FILETOOSMALL":
193
- return "mediaUploadFailed";
194
- case "MODERATIONBLOCKED":
195
- return "moderationBlocked";
196
- case "UPSTREAMLLMTIMEOUT":
197
- return "upstreamLlmTimeout";
198
- case "INTERNALERROR":
199
- case "INTERNALSERVERERROR":
200
- return "internalError";
201
- case "STREAMINCOMPLETE":
202
- case "CHATSTREAMINCOMPLETE":
203
- return "streamIncomplete";
204
- // Deterministic 400s that can only come from an SDK bug -> unknown (NON-retryable). NEVER internalError
205
- // (which IS auto-retried): mapping a bad-input 400 to a retryable code retries a request that never succeeds.
206
- case "INVALIDANALYSISTYPE":
207
- case "INVALIDUPLOADPURPOSE":
208
- return "unknown";
209
- default:
210
- return "unknown";
211
- }
212
- }
213
- function fromHttpStatus(status) {
214
- if (status === 401) return "authExpired";
215
- if (status === 403) return "accessDenied";
216
- if (status === 404) return "conversationNotFound";
217
- if (status === 409) return "idempotencyConflict";
218
- if (status === 421) return "unknown";
219
- if (status === 429) return "rateLimited";
220
- if (status === 400 || status === 422) return "unknown";
221
- if (status >= 500) return "internalError";
222
- return "unknown";
223
- }
224
- var AUTO_RETRYABLE_CODES = /* @__PURE__ */ new Set([
225
- "streamTimeout",
226
- "rateLimited",
227
- "internalError",
228
- "upstreamLlmTimeout",
229
- "streamIncomplete"
230
- ]);
231
- function isAutoRetryable(code) {
232
- return AUTO_RETRYABLE_CODES.has(code);
233
- }
234
- var RETRYABLE_CONTRACT_CODES = /* @__PURE__ */ new Set([
235
- "serviceUnavailable",
236
- "conflict",
237
- "idempotencyInFlight"
238
- ]);
239
- function isRetryableCode(code) {
240
- return isAutoRetryable(code) || RETRYABLE_CONTRACT_CODES.has(code);
241
- }
242
- function shouldRetry(code, frameRetryable = false) {
243
- return frameRetryable || isAutoRetryable(code);
244
- }
245
- var BACKOFF_BASE_MS = 500;
246
- var BACKOFF_CAP_MS = 8e3;
247
- var MAX_RETRY_ATTEMPTS = 4;
248
- function backoffDelayMs(attempt, rng = Math.random) {
249
- const bounded = Math.max(0, attempt);
250
- const ceiling = Math.min(BACKOFF_BASE_MS * 2 ** bounded, BACKOFF_CAP_MS);
251
- return Math.floor(rng() * ceiling);
252
- }
253
- function canRecreateOnNotFound(code) {
254
- return code === "conversationNotFound";
255
- }
256
-
257
- // src/core/ports/ErrorPolicyPort.ts
258
- var defaultErrorPolicy = Object.freeze({
259
- shouldRetry(code, attempt) {
260
- return isAutoRetryable(code) && attempt < MAX_RETRY_ATTEMPTS;
261
- },
262
- maxAttempts() {
263
- return MAX_RETRY_ATTEMPTS;
264
- }
265
- });
266
-
267
- // src/core/ports/CameraPort.ts
268
- var unavailableCamera = Object.freeze({
269
- isAvailable: false,
270
- async capture() {
271
- return Promise.reject(
272
- new Error("CameraPort is unavailable; check isAvailable before calling capture")
273
- );
274
- }
275
- });
276
-
277
- // src/core/ports/optionalModule.ts
278
- function optionalModule(name, load, validate2) {
279
- let candidate;
280
- try {
281
- candidate = load();
282
- } catch (cause) {
283
- return frozenUnavailable(`optional peer '${name}' is not installed: ${describe(cause)}`);
284
- }
285
- const resolved = unwrapDefault(candidate);
286
- if (resolved === null || resolved === void 0) {
287
- return frozenUnavailable(`optional peer '${name}' resolved to no module`);
288
- }
289
- if (validate2 && !validate2(resolved)) {
290
- return frozenUnavailable(`optional peer '${name}' is present but failed its shape check`);
291
- }
292
- return Object.freeze({ available: true, module: resolved });
293
- }
294
- function unwrapDefault(candidate) {
295
- if (typeof candidate === "object" && candidate !== null && "default" in candidate && Object.keys(candidate).length <= 2) {
296
- return candidate.default;
297
- }
298
- return candidate;
299
- }
300
- function frozenUnavailable(reason) {
301
- return Object.freeze({ available: false, module: null, reason });
302
- }
303
- function describe(cause) {
304
- if (cause instanceof Error) return cause.message;
305
- return typeof cause === "string" ? cause : "unknown load error";
306
- }
307
-
308
- // src/client/protocol/frames.ts
309
- function assertNever(x) {
310
- throw new Error(
311
- `assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`
312
- );
313
- }
314
- function acceptedFrame(streamId, lastEventId, serverRequestId = null) {
315
- return Object.freeze({ kind: "accepted", streamId, lastEventId, serverRequestId, terminal: false });
316
- }
317
- function heartbeatFrame(lastEventId, serverRequestId = null) {
318
- return Object.freeze({ kind: "heartbeat", lastEventId, serverRequestId, terminal: false });
319
- }
320
- function deltaFrame(delta, lastEventId, serverRequestId = null) {
321
- return Object.freeze({ kind: "delta", delta, lastEventId, serverRequestId, terminal: false });
322
- }
323
- function doneFrame(fields, serverRequestId = null) {
324
- return Object.freeze({
325
- kind: "done",
326
- terminal: true,
327
- conversationId: fields.conversationId,
328
- messageId: fields.messageId,
329
- title: fields.title,
330
- followUpQuestions: Object.freeze([...fields.followUpQuestions]),
331
- citations: Object.freeze([...fields.citations]),
332
- citationStatus: fields.citationStatus,
333
- urgencyLevel: fields.urgencyLevel,
334
- urgencyReason: fields.urgencyReason,
335
- resultId: fields.resultId,
336
- lastEventId: fields.lastEventId,
337
- serverRequestId
338
- });
339
- }
340
- function errorFrame(fields) {
341
- return Object.freeze({
342
- kind: "error",
343
- terminal: true,
344
- code: fields.code,
345
- retryable: fields.retryable,
346
- wireMessage: fields.wireMessage,
347
- synthesized: fields.synthesized,
348
- lastEventId: fields.lastEventId,
349
- serverRequestId: fields.serverRequestId ?? null
350
- });
351
- }
352
- function analysisStartedFrame(requestId, lastEventId, serverRequestId = null) {
353
- return Object.freeze({
354
- kind: "analysisStarted",
355
- requestId,
356
- lastEventId,
357
- serverRequestId,
358
- terminal: false
359
- });
360
- }
361
- function analysisCompleteFrame(fields, serverRequestId = null) {
362
- return Object.freeze({
363
- kind: "analysisComplete",
364
- terminal: false,
365
- resultId: fields.resultId,
366
- analysisType: fields.analysisType,
367
- modelVersion: fields.modelVersion,
368
- confidence: fields.confidence,
369
- detections: Object.freeze([...fields.detections]),
370
- interpretation: fields.interpretation,
371
- lastEventId: fields.lastEventId,
372
- serverRequestId
373
- });
374
- }
375
- function unknownFrame(raw, lastEventId, serverRequestId = null) {
376
- return Object.freeze({
377
- kind: "unknown",
378
- raw: { ...raw },
379
- lastEventId,
380
- serverRequestId,
381
- terminal: false
382
- });
383
- }
384
-
385
- // src/client/errors/EverfurError.ts
386
- var USER_FACING_COPY = Object.freeze({
387
- authExpired: "Please sign in again to continue.",
388
- authRejected: "Please sign in again to continue.",
389
- sessionRequired: "This app needs to be updated to keep using Everfur.",
390
- accessDenied: "This feature isn't available on your account right now.",
391
- paymentRequired: "This is part of a paid plan.",
392
- quotaExceeded: "You have used today's messages. This resets tomorrow.",
393
- rateLimited: "You are sending messages quickly. Try again in a few seconds.",
394
- validationFailed: "Something in that request was not right. Check the details and try again.",
395
- sdkUpdateRequired: "This app needs to be updated to keep using Everfur.",
396
- conflict: "That is already running. Wait for it to finish, then try again.",
397
- idempotencyConflict: "That message was already delivered.",
398
- idempotencyInFlight: "That is still processing. Give it a moment.",
399
- conversationNotFound: "This conversation is no longer available.",
400
- petNotFound: "We could not find that pet. Please pick a pet and try again.",
401
- resourceNotFound: "We could not find that.",
402
- streamTimeout: "The response timed out. Tap retry to try again.",
403
- mediaUploadFailed: "We could not upload that photo. Please attach it again.",
404
- moderationBlocked: "This request cannot be answered here.",
405
- upstreamLlmTimeout: "The response timed out. Tap retry to try again.",
406
- internalError: "We hit a snag on our end. Please try again.",
407
- notImplemented: "That is not available yet.",
408
- serviceUnavailable: "That service is briefly unavailable. Try again shortly.",
409
- streamIncomplete: "The connection dropped mid-answer. Tap retry to continue.",
410
- unknown: "Something went wrong. Please try again."
411
- });
412
- function userFacingError(code) {
413
- return USER_FACING_COPY[code];
414
- }
415
- function defineHidden(target, key, value) {
416
- Object.defineProperty(target, key, {
417
- value,
418
- enumerable: false,
419
- writable: false,
420
- configurable: false
421
- });
422
- }
423
- function makeEverfurError(code, opts) {
424
- contractErrorFor(opts?.wireCode);
425
- const error = {
426
- code,
427
- category: categoryFor(code),
428
- retryable: opts?.retryable ?? isRetryableCode(code),
429
- displayMessage: userFacingError(code)
430
- };
431
- if (opts?.httpStatus !== void 0) error.httpStatus = opts.httpStatus;
432
- if (opts?.requestId) error.requestId = opts.requestId;
433
- if (opts?.wireMessage) defineHidden(error, "wireMessage", opts.wireMessage);
434
- if (opts?.raw !== void 0 && opts.raw !== null) defineHidden(error, "raw", opts.raw);
435
- return Object.freeze(error);
436
- }
437
-
438
- // src/client/identity.ts
439
- function createIdentityProvider(userRef, getToken) {
440
- let cached = null;
441
- let inFlight = null;
442
- let revoked = false;
443
- const load = () => {
444
- if (inFlight) return inFlight;
445
- inFlight = (async () => {
446
- try {
447
- const token = await getToken();
448
- if (typeof token !== "string" || token.length === 0) {
449
- throw new EverfurConfigError("invalid-argument", "TokenProvider returned an empty token");
450
- }
451
- cached = token;
452
- return token;
453
- } finally {
454
- inFlight = null;
455
- }
456
- })();
457
- return inFlight;
458
- };
459
- return {
460
- userRef,
461
- async currentToken(opts) {
462
- if (revoked) {
463
- throw new EverfurConfigError("not-initialized", "This identity was cleared (sign-out); mint a new one.");
464
- }
465
- if (opts?.forceRefresh) cached = null;
466
- if (cached !== null) return cached;
467
- return load();
468
- },
469
- hasToken() {
470
- return !revoked && cached !== null;
471
- },
472
- clear() {
473
- revoked = true;
474
- cached = null;
475
- }
476
- };
477
- }
478
- function newSessionId() {
479
- const bytes = new Uint8Array(16);
480
- const cryptoObj = globalThis.crypto;
481
- if (typeof cryptoObj?.getRandomValues === "function") {
482
- cryptoObj.getRandomValues(bytes);
483
- } else {
484
- for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
485
- }
486
- bytes[6] = bytes[6] & 15 | 64;
487
- bytes[8] = bytes[8] & 63 | 128;
488
- const hex = [];
489
- for (let i = 0; i < bytes.length; i += 1) hex.push(bytes[i].toString(16).padStart(2, "0"));
490
- return hex.slice(0, 4).join("") + "-" + hex.slice(4, 6).join("") + "-" + hex.slice(6, 8).join("") + "-" + hex.slice(8, 10).join("") + "-" + hex.slice(10, 16).join("");
491
- }
492
- function authHeaders(auth) {
493
- const headers = {};
494
- if (auth.mode === "personalized") {
495
- headers.authorization = `Bearer ${auth.token}`;
496
- } else {
497
- headers["x-everfur-partner-key"] = auth.publishableKey;
498
- }
499
- if (auth.userRef) headers["x-everfur-user-ref"] = auth.userRef;
500
- if (auth.sessionId) headers["x-everfur-session-id"] = auth.sessionId;
501
- return headers;
502
- }
503
- function withAuthHeaders(req, auth) {
504
- return { ...req, headers: { ...stripAuthHeaders(req.headers), ...authHeaders(auth) } };
505
- }
506
- function stripAuthHeaders(headers) {
507
- if (!headers) return {};
508
- const out = {};
509
- for (const [key, value] of Object.entries(headers)) {
510
- const lower = key.toLowerCase();
511
- if (lower === "authorization" || lower === "x-everfur-partner-key") continue;
512
- out[key] = value;
513
- }
514
- return out;
515
- }
516
- async function authedSend(req, ctx) {
517
- if (ctx.mode === "anonymous") {
518
- return ctx.transport.request(
519
- withAuthHeaders(req, {
520
- mode: "anonymous",
521
- publishableKey: ctx.publishableKey,
522
- userRef: ctx.userRef,
523
- ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
524
- })
525
- );
526
- }
527
- let token;
528
- try {
529
- token = await ctx.identity.currentToken();
530
- } catch {
531
- return err(authRejectedError());
532
- }
533
- const first = await ctx.transport.request(
534
- withAuthHeaders(req, {
535
- mode: "personalized",
536
- token,
537
- userRef: ctx.userRef,
538
- ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
539
- })
540
- );
541
- if (first.ok || first.error.httpStatus !== 401) return first;
542
- let refreshed;
543
- try {
544
- refreshed = await ctx.identity.currentToken({ forceRefresh: true });
545
- } catch {
546
- return err(authRejectedError());
547
- }
548
- const retry = await ctx.transport.request(
549
- withAuthHeaders(req, {
550
- mode: "personalized",
551
- token: refreshed,
552
- userRef: ctx.userRef,
553
- ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
554
- })
555
- );
556
- if (!retry.ok && retry.error.httpStatus === 401) {
557
- return err(authRejectedError(retry.error.httpStatus));
558
- }
559
- return retry;
560
- }
561
- function authRejectedError(httpStatus) {
562
- return makeEverfurError("authRejected", {
563
- retryable: false,
564
- ...httpStatus !== void 0 ? { httpStatus } : {}
565
- });
566
- }
567
- var BLOCK_SEPARATOR = "\n\n";
568
- var MAX_PENDING_BLOCK_CHARS = 1048576;
569
- var wireObjectSchema = zod.z.record(zod.z.string(), zod.z.unknown());
570
- var URGENCY_LEVELS = ["emergency", "schedule_soon", "home_care"];
571
- async function* parseSse(bytes, serverRequestId = null) {
572
- let resolvedRequestId = null;
573
- const requestIdNow = () => {
574
- if (resolvedRequestId !== null) return resolvedRequestId;
575
- resolvedRequestId = typeof serverRequestId === "function" ? serverRequestId() : serverRequestId;
576
- return resolvedRequestId;
577
- };
578
- const decoder = new TextDecoder("utf-8");
579
- let buffer = "";
580
- let scanFrom = 0;
581
- let sawDelta = false;
582
- for await (const chunk of bytes) {
583
- buffer += decoder.decode(chunk, { stream: true });
584
- for (; ; ) {
585
- const sep = buffer.indexOf(BLOCK_SEPARATOR, scanFrom);
586
- if (sep === -1) break;
587
- const block = buffer.slice(0, sep);
588
- buffer = buffer.slice(sep + BLOCK_SEPARATOR.length);
589
- scanFrom = 0;
590
- const frame = parseBlock(block, requestIdNow());
591
- if (frame === null) continue;
592
- if (frame.kind === "delta") sawDelta = true;
593
- yield frame;
594
- if (frame.terminal) return;
595
- }
596
- scanFrom = buffer.length > 0 ? buffer.length - 1 : 0;
597
- if (buffer.length > MAX_PENDING_BLOCK_CHARS) {
598
- yield errorFrame({
599
- code: sawDelta ? "CHAT_STREAM_INCOMPLETE" : "internal_error",
600
- retryable: true,
601
- wireMessage: null,
602
- synthesized: true,
603
- lastEventId: null,
604
- serverRequestId: requestIdNow()
605
- });
606
- return;
607
- }
608
- }
609
- buffer += decoder.decode();
610
- if (buffer.trim().length > 0) {
611
- const frame = parseBlock(buffer, requestIdNow());
612
- if (frame !== null) {
613
- if (frame.kind === "delta") sawDelta = true;
614
- yield frame;
615
- if (frame.terminal) return;
616
- }
617
- }
618
- yield errorFrame({
619
- code: sawDelta ? "CHAT_STREAM_INCOMPLETE" : "internal_error",
620
- retryable: true,
621
- wireMessage: null,
622
- synthesized: true,
623
- lastEventId: null,
624
- serverRequestId: requestIdNow()
625
- });
626
- }
627
- function parseBlock(block, serverRequestId) {
628
- let id = null;
629
- const dataLines = [];
630
- for (const rawLine of block.split("\n")) {
631
- const line = rawLine.replace(/\s+$/, "");
632
- if (line.length === 0 || line.startsWith(":")) continue;
633
- if (line.startsWith("id:")) {
634
- id = line.slice(3).trim();
635
- } else if (line.startsWith("data:")) {
636
- dataLines.push(line.slice(5).replace(/^ /, ""));
637
- }
638
- }
639
- if (dataLines.length === 0) return null;
640
- let decoded;
641
- try {
642
- decoded = JSON.parse(dataLines.join("\n"));
643
- } catch {
644
- return null;
645
- }
646
- if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) return null;
647
- const parsed = wireObjectSchema.safeParse(decoded);
648
- if (!parsed.success) return null;
649
- return frameFromWire(parsed.data, id, serverRequestId);
650
- }
651
- function frameFromWire(json, lastEventId, serverRequestId) {
652
- const type = json["type"];
653
- const event = json["event"];
654
- if (type === "error" || "error" in json) {
655
- return errorFrame({
656
- code: asString(json["code"]) ?? "unknown",
657
- retryable: json["retryable"] === true,
658
- wireMessage: asString(json["error"]),
659
- synthesized: false,
660
- lastEventId,
661
- serverRequestId
662
- });
663
- }
664
- if (type === "done" || json["done"] === true) {
665
- return doneFrame({
666
- conversationId: asString(json["conversation_id"]) ?? "",
667
- messageId: asString(json["message_id"]),
668
- title: asString(json["title"]),
669
- followUpQuestions: asStringList(json["follow_up_questions"]),
670
- citations: asMapList(json["citations"]),
671
- citationStatus: asString(json["citation_status"]),
672
- urgencyLevel: asUrgency(json["urgency_level"]),
673
- urgencyReason: asString(json["urgency_reason"]),
674
- resultId: asString(json["result_id"]),
675
- lastEventId
676
- }, serverRequestId);
677
- }
678
- if (type === "accepted" || json["status"] === "reasoning") {
679
- return acceptedFrame(asString(json["stream_id"]), lastEventId, serverRequestId);
680
- }
681
- if (type === "heartbeat" || json["heartbeat"] === true) {
682
- return heartbeatFrame(lastEventId, serverRequestId);
683
- }
684
- if (type === "text.delta" || "delta" in json || "token" in json) {
685
- const delta = asString(json["delta"]) ?? asString(json["token"]) ?? "";
686
- return deltaFrame(delta, lastEventId, serverRequestId);
687
- }
688
- if (event === "analysis_started") {
689
- return analysisStartedFrame(asString(json["request_id"]), lastEventId, serverRequestId);
690
- }
691
- if (event === "analysis_complete") {
692
- return analysisCompleteFrame({
693
- resultId: asString(json["result_id"]),
694
- analysisType: asString(json["analysis_type"]),
695
- modelVersion: asString(json["model_version"]),
696
- confidence: asNumber(json["confidence"]),
697
- detections: asMapList(json["detections"]),
698
- interpretation: asString(json["interpretation"]),
699
- lastEventId
700
- }, serverRequestId);
701
- }
702
- return unknownFrame(json, lastEventId, serverRequestId);
703
- }
704
- function asString(v) {
705
- return typeof v === "string" ? v : null;
706
- }
707
- function asNumber(v) {
708
- return typeof v === "number" && Number.isFinite(v) ? v : null;
709
- }
710
- function asUrgency(v) {
711
- return typeof v === "string" && URGENCY_LEVELS.includes(v) ? v : null;
712
- }
713
- function asStringList(v) {
714
- if (!Array.isArray(v)) return [];
715
- return v.map((e) => typeof e === "string" ? e : String(e));
716
- }
717
- function isPlainObject(v) {
718
- return typeof v === "object" && v !== null && !Array.isArray(v);
719
- }
720
- function asMapList(v) {
721
- if (!Array.isArray(v)) return [];
722
- return v.filter(isPlainObject);
723
- }
724
-
725
- // src/client/config.ts
726
- var SDK_VERSION = "0.1.0";
727
- var SDK_PLATFORM = "react-native";
728
- var DEFAULT_CONTRACT_VERSION = "2026-08-01";
729
- var ENV_API_BASE_URL = "EVERFUR_API_BASE_URL";
730
- function configFailure(reason, message) {
731
- return Object.freeze({ ok: false, failure: Object.freeze({ reason, message }) });
732
- }
733
- function checkPublishableKey(raw) {
734
- const publishableKey = typeof raw === "string" ? raw.trim() : "";
735
- if (publishableKey.length === 0) {
736
- return { reason: "missing-publishable-key", message: "publishableKey is required" };
737
- }
738
- if (/^sk[_-]/i.test(publishableKey)) {
739
- return {
740
- reason: "secret-key-as-publishable-key",
741
- message: "publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."
742
- };
743
- }
744
- return null;
745
- }
746
- function tryResolveClientConfig(config) {
747
- const keyFailure = checkPublishableKey(config?.publishableKey);
748
- if (keyFailure !== null) {
749
- return Object.freeze({ ok: false, failure: keyFailure });
750
- }
751
- const publishableKey = config.publishableKey.trim();
752
- const baseUrl = tryResolveApiBaseUrl(config.apiBaseUrl);
753
- if (!baseUrl.ok) {
754
- return baseUrl;
755
- }
756
- const contractVersion = config.contractVersion?.trim() || DEFAULT_CONTRACT_VERSION;
757
- return Object.freeze({
758
- ok: true,
759
- config: Object.freeze({
760
- publishableKey,
761
- apiBaseUrl: baseUrl.value,
762
- contractVersion,
763
- sdkVersion: SDK_VERSION,
764
- platform: SDK_PLATFORM,
765
- debug: config.debug === true
766
- })
767
- });
768
- }
769
- function tryResolveApiBaseUrl(apiBaseUrl) {
770
- const explicit = apiBaseUrl?.trim();
771
- const candidate = explicit && explicit.length > 0 ? explicit : readEnv(ENV_API_BASE_URL);
772
- if (!candidate) {
773
- return configFailure(
774
- "missing-api-base-url",
775
- `apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`
776
- );
777
- }
778
- return normalizeBaseUrl(candidate);
779
- }
780
- function buildBaseHeaders(cfg) {
781
- return {
782
- "X-Everfur-SDK-Version": cfg.sdkVersion,
783
- "X-Everfur-SDK-Platform": cfg.platform,
784
- "X-Everfur-Contract": cfg.contractVersion
785
- };
786
- }
787
- var ABSOLUTE_URL = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;
788
- function hostOf(authority) {
789
- const afterUserinfo = authority.slice(authority.lastIndexOf("@") + 1);
790
- return afterUserinfo.replace(/:\d+$/, "").toLowerCase();
791
- }
792
- function isPrintableHost(host) {
793
- if (host.length === 0) return false;
794
- if (host.includes("@")) return false;
795
- if (host.startsWith("[") && host.endsWith("]")) return true;
796
- return !host.includes(":");
797
- }
798
- function canEchoOrigin(rawTrimmed, host) {
799
- const schemeEnd = rawTrimmed.indexOf("://");
800
- if (schemeEnd < 0) return false;
801
- if (rawTrimmed.slice(schemeEnd + 3).includes("@")) return false;
802
- return isPrintableHost(host);
803
- }
804
- function safeOrigin(scheme, host) {
805
- return `${scheme}://${host}`;
806
- }
807
- function normalizeBaseUrl(raw) {
808
- const trimmed = raw.trim();
809
- const match = ABSOLUTE_URL.exec(trimmed);
810
- if (match === null || match[2] === void 0 || match[2].length === 0) {
811
- return configFailure("malformed-api-base-url", "apiBaseUrl is not a valid absolute URL");
812
- }
813
- const scheme = (match[1] ?? "").toLowerCase();
814
- const host = hostOf(match[2]);
815
- if (host.length === 0) {
816
- return configFailure("malformed-api-base-url", "apiBaseUrl is not a valid absolute URL");
817
- }
818
- const shown = canEchoOrigin(trimmed, host) ? `: ${safeOrigin(scheme, host)}` : "";
819
- if (scheme === "https") ; else if (scheme === "http" && isLoopbackHost(host)) ; else if (scheme === "http") {
820
- return configFailure(
821
- "insecure-api-base-url",
822
- `apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`
823
- );
824
- } else {
825
- return configFailure("unsupported-api-base-url-scheme", `apiBaseUrl must be http(s)${shown}`);
826
- }
827
- const value = trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
828
- return Object.freeze({ ok: true, value });
829
- }
830
- function isLoopbackHost(hostname) {
831
- const host = hostname.toLowerCase();
832
- return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
833
- }
834
- function readEnv(name) {
835
- const g = globalThis;
836
- const value = g.process?.env?.[name];
837
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
838
- }
839
-
840
- // src/client/transport.ts
841
- var UNARY_TIMEOUT_MS = 3e4;
842
- var REQUEST_ID_HEADER = "x-request-id";
843
- async function* fetchByteSource(body) {
844
- if (!body) return;
845
- const reader = body.getReader();
846
- try {
847
- for (; ; ) {
848
- const { done, value } = await reader.read();
849
- if (done) break;
850
- if (value && value.length > 0) yield value;
851
- }
852
- } finally {
853
- await reader.cancel?.();
854
- }
855
- }
856
- function eventSourceByteSource(es) {
857
- const enc = new TextEncoder();
858
- const queue = createByteQueue();
859
- let cleaned = false;
860
- const onMessage = (ev) => {
861
- let block = "";
862
- if (ev.lastEventId) block += `id: ${ev.lastEventId}
863
- `;
864
- const data = ev.data ?? "";
865
- for (const line of data.split("\n")) block += `data: ${line}
866
- `;
867
- block += "\n";
868
- queue.push(enc.encode(block));
869
- };
870
- const onDone = () => {
871
- cleanup();
872
- queue.end();
873
- };
874
- const onError = (ev) => {
875
- const status = typeof ev.xhrStatus === "number" ? ev.xhrStatus : 0;
876
- if (status >= 400) {
877
- const wireCode = statusToWireCode(status);
878
- const retryable = isAutoRetryable(fromWire(wireCode));
879
- queue.push(enc.encode(`data: ${JSON.stringify({ type: "error", code: wireCode, retryable })}
880
-
881
- `));
882
- }
883
- cleanup();
884
- queue.end();
885
- };
886
- es.addEventListener("message", onMessage);
887
- es.addEventListener("done", onDone);
888
- es.addEventListener("error", onError);
889
- function cleanup() {
890
- if (cleaned) return;
891
- cleaned = true;
892
- es.removeEventListener("message", onMessage);
893
- es.removeEventListener("done", onDone);
894
- es.removeEventListener("error", onError);
895
- try {
896
- es.close();
897
- } catch {
898
- }
899
- }
900
- return sourceWithCleanup(queue.source, cleanup);
901
- }
902
- async function* sourceWithCleanup(source, cleanup) {
903
- try {
904
- yield* source;
905
- } finally {
906
- cleanup();
907
- }
908
- }
909
- function createByteQueue() {
910
- const buffer = [];
911
- let done = false;
912
- let wake = null;
913
- const signal = () => {
914
- if (wake) {
915
- const fn = wake;
916
- wake = null;
917
- fn();
918
- }
919
- };
920
- async function* gen() {
921
- for (; ; ) {
922
- const next = buffer.shift();
923
- if (next !== void 0) {
924
- yield next;
925
- continue;
926
- }
927
- if (done) return;
928
- await new Promise((resolve) => {
929
- wake = resolve;
930
- });
931
- }
932
- }
933
- return {
934
- source: gen(),
935
- push: (u) => {
936
- buffer.push(u);
937
- signal();
938
- },
939
- end: () => {
940
- done = true;
941
- signal();
942
- }
943
- };
944
- }
945
- async function requestJson(req, deps) {
946
- const fetchImpl = deps.fetchImpl ?? getGlobalFetch();
947
- const url = buildUrl(deps.config.apiBaseUrl, req.path, req.query);
948
- const headers = mergeHeaders(deps.config, req.headers, "application/json", req.body !== void 0 && req.multipart === void 0);
949
- const deadline2 = timeoutSignal(UNARY_TIMEOUT_MS);
950
- const signal = mergeAbortSignals(deadline2.signal, req.signal);
951
- let res;
952
- try {
953
- res = await fetchImpl(url, buildInit({ ...req, signal }, headers));
954
- } catch (cause) {
955
- return err(networkError(cause));
956
- } finally {
957
- deadline2.cancel();
958
- }
959
- const bodyJson = await safeJson(res);
960
- if (!res.ok) return err(errorFromResponse(res.status, bodyJson, requestIdOf(res)));
961
- return ok(bodyJson);
962
- }
963
- function createHttpTransport(deps) {
964
- return {
965
- request: (req) => requestJson(req, deps),
966
- stream: (req, signal) => streamFrames(withSignal(req, signal), deps)
967
- };
968
- }
969
- async function* streamFrames(req, deps) {
970
- const url = buildUrl(deps.config.apiBaseUrl, req.path, req.query);
971
- const headers = mergeHeaders(deps.config, req.headers, "text/event-stream", req.body !== void 0 && req.multipart === void 0);
972
- if (deps.eventSourceFactory) {
973
- const es = deps.eventSourceFactory(url, buildEventSourceInit(req, headers));
974
- yield* parseSse(eventSourceByteSource(es), () => eventSourceRequestId(es));
975
- return;
976
- }
977
- const fetchImpl = deps.fetchImpl ?? getGlobalFetch();
978
- let res;
979
- try {
980
- res = await fetchImpl(url, buildInit(req, headers));
981
- } catch (cause) {
982
- yield syntheticErrorFrame("", true, describeCause(cause));
983
- return;
984
- }
985
- const requestId = requestIdOf(res);
986
- if (!res.ok) {
987
- const body = await safeJson(res);
988
- const wireCode = extractWireCode(body) ?? statusToWireCode(res.status);
989
- const retryable = extractRetryable(body) || isAutoRetryable(fromWire(wireCode));
990
- yield syntheticErrorFrame(wireCode, retryable, extractWireMessage(body), requestId);
991
- return;
992
- }
993
- if (res.body) {
994
- yield* parseSse(fetchByteSource(res.body), requestId);
995
- return;
996
- }
997
- yield* parseSse(fetchByteSource(null), requestId);
998
- }
999
- function buildEventSourceInit(req, headers) {
1000
- return {
1001
- method: req.method,
1002
- headers,
1003
- pollingInterval: 0,
1004
- ...req.body !== void 0 ? { body: JSON.stringify(req.body) } : {}
1005
- };
1006
- }
1007
- function errorFromResponse(status, body, requestId) {
1008
- const wireCode = extractWireCode(body);
1009
- const code = wireCode ? fromWire(wireCode) : fromHttpStatus(status);
1010
- const wireMessage = extractWireMessage(body);
1011
- return makeEverfurError(code, {
1012
- httpStatus: status,
1013
- ...extractRetryable(body) ? { retryable: true } : {},
1014
- ...requestId ? { requestId } : {},
1015
- ...wireCode ? { wireCode } : {},
1016
- ...wireMessage ? { wireMessage } : {},
1017
- ...body !== null && body !== void 0 ? { raw: body } : {}
1018
- });
1019
- }
1020
- function networkError(cause) {
1021
- return makeEverfurError("internalError", { retryable: true, wireMessage: describeCause(cause) });
1022
- }
1023
- function requestIdOf(res) {
1024
- const value = res.headers.get(REQUEST_ID_HEADER);
1025
- return typeof value === "string" && value.length > 0 ? value : null;
1026
- }
1027
- function eventSourceRequestId(es) {
1028
- if (typeof es.getResponseHeader !== "function") return null;
1029
- let value;
1030
- try {
1031
- value = es.getResponseHeader(REQUEST_ID_HEADER);
1032
- } catch {
1033
- return null;
1034
- }
1035
- return typeof value === "string" && value.length > 0 ? value : null;
1036
- }
1037
- function statusToWireCode(status) {
1038
- if (status === 401) return "AUTH_EXPIRED";
1039
- if (status === 403) return "ACCESS_DENIED";
1040
- if (status === 404) return "NOT_FOUND";
1041
- if (status === 409) return "IDEMPOTENCY_CONFLICT";
1042
- if (status === 421) return "MISDIRECTED_REQUEST";
1043
- if (status === 429) return "RATE_LIMITED";
1044
- if (status === 400 || status === 422) return "INVALID_REQUEST";
1045
- if (status === 503) return "INTERNAL_ERROR";
1046
- if (status >= 500) return "INTERNAL_ERROR";
1047
- return "";
1048
- }
1049
- function syntheticErrorFrame(code, retryable, wireMessage, serverRequestId = null) {
1050
- return errorFrame({ code, retryable, wireMessage, synthesized: true, lastEventId: null, serverRequestId });
1051
- }
1052
- function getGlobalFetch() {
1053
- const candidate = globalThis.fetch;
1054
- if (typeof candidate !== "function") {
1055
- throw new EverfurConfigError(
1056
- "missing-peer-dependency",
1057
- "global fetch is unavailable; provide config.transport or an injected fetch implementation"
1058
- );
1059
- }
1060
- return candidate;
1061
- }
1062
- function buildUrl(base, path, query) {
1063
- const rel = path.startsWith("/") ? path : `/${path}`;
1064
- let url = `${base}${rel}`;
1065
- if (query) {
1066
- const qs = Object.entries(query).filter((entry) => entry[1] !== void 0).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
1067
- if (qs) url += `?${qs}`;
1068
- }
1069
- return url;
1070
- }
1071
- function mergeHeaders(config, reqHeaders, accept, hasJsonBody) {
1072
- const headers = { ...buildBaseHeaders(config), accept };
1073
- if (hasJsonBody) headers["content-type"] = "application/json";
1074
- if (reqHeaders) Object.assign(headers, reqHeaders);
1075
- return headers;
1076
- }
1077
- function buildInit(req, headers) {
1078
- const init = { method: req.method, headers };
1079
- if (req.multipart !== void 0) init.body = req.multipart;
1080
- else if (req.body !== void 0) init.body = JSON.stringify(req.body);
1081
- if (req.signal) init.signal = req.signal;
1082
- return init;
1083
- }
1084
- function withSignal(req, signal) {
1085
- return req.signal ? req : { ...req, signal };
1086
- }
1087
- function timeoutSignal(ms) {
1088
- const ctrl = new AbortController();
1089
- const handle = setTimeout(() => ctrl.abort(), ms);
1090
- return {
1091
- signal: ctrl.signal,
1092
- cancel: () => clearTimeout(handle)
1093
- };
1094
- }
1095
- function mergeAbortSignals(deadline2, caller) {
1096
- if (!caller) return deadline2;
1097
- const ctrl = new AbortController();
1098
- if (deadline2.aborted || caller.aborted) {
1099
- ctrl.abort();
1100
- return ctrl.signal;
1101
- }
1102
- const onAbort = () => ctrl.abort();
1103
- deadline2.addEventListener("abort", onAbort, { once: true });
1104
- caller.addEventListener("abort", onAbort, { once: true });
1105
- return ctrl.signal;
1106
- }
1107
- async function safeJson(res) {
1108
- try {
1109
- return await res.json();
1110
- } catch {
1111
- return null;
1112
- }
1113
- }
1114
- function extractWireCode(body) {
1115
- const b = body;
1116
- const code = b?.error?.code ?? b?.code;
1117
- return typeof code === "string" && code.length > 0 ? code : null;
1118
- }
1119
- function extractWireMessage(body) {
1120
- const b = body;
1121
- const message = b?.error?.message ?? b?.message;
1122
- return typeof message === "string" && message.length > 0 ? message : null;
1123
- }
1124
- function extractRetryable(body) {
1125
- const b = body;
1126
- return b?.error?.retryable === true || b?.retryable === true;
1127
- }
1128
- function describeCause(cause) {
1129
- if (cause instanceof Error) return cause.message;
1130
- return typeof cause === "string" ? cause : "network request failed";
1131
- }
1132
-
1133
- // src/client/funnel/requestFunnel.ts
1134
- var FUNNEL_UNARY_TIMEOUT_MS = 3e4;
1135
- var RETRY_OVERRIDE_MAX_MS = BACKOFF_CAP_MS * 2;
1136
- var IDEMPOTENCY_HEADER = "idempotency-key";
1137
- var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1138
- var NOOP_OBSERVER = Object.freeze({
1139
- onEvent() {
1140
- }
1141
- });
1142
- var defaultFunnelTimers = Object.freeze({
1143
- setTimeout: (handler, ms) => setTimeout(handler, ms),
1144
- clearTimeout: (handle) => clearTimeout(handle),
1145
- now: () => Date.now()
1146
- });
1147
- function createRequestFunnel(deps) {
1148
- const observer = deps.observer ?? NOOP_OBSERVER;
1149
- const timers = deps.timers ?? defaultFunnelTimers;
1150
- const rng = deps.rng ?? Math.random;
1151
- const sleep = deps.sleep ?? ((ms, signal) => delayAbortable(ms, timers, signal));
1152
- const ceiling = deps.maxAttempts ?? MAX_RETRY_ATTEMPTS;
1153
- const timeoutMs = deps.unaryTimeoutMs ?? FUNNEL_UNARY_TIMEOUT_MS;
1154
- const mintKey = deps.newIdempotencyKey ?? defaultIdempotencyKeyFactory();
1155
- const emit = (event) => {
1156
- try {
1157
- observer.onEvent(event);
1158
- } catch {
1159
- }
1160
- };
1161
- async function send(call, req, opts) {
1162
- const perCallMaxAttempts = opts?.maxAttempts;
1163
- const maxAttempts = Math.max(1, perCallMaxAttempts ?? ceiling);
1164
- const idempotent = opts?.idempotent ?? MUTATING_METHODS.has(req.method);
1165
- const idempotencyKey = idempotent ? mintKey() : null;
1166
- const base = assembleHeaders(req, idempotencyKey);
1167
- let attempt = 0;
1168
- for (; ; ) {
1169
- const stamp = (extra) => Object.freeze({
1170
- call,
1171
- method: req.method,
1172
- path: req.path,
1173
- attempt,
1174
- ...idempotencyKey ? { idempotencyKey } : {},
1175
- ...extra
1176
- });
1177
- emit(stamp({ phase: "attempt" }));
1178
- const deadline2 = boundedSignal(timeoutMs, timers);
1179
- const merged = mergeSignals(deadline2.signal, req.signal);
1180
- let settled;
1181
- try {
1182
- settled = await authedSend({ ...base, signal: merged.signal }, deps.auth);
1183
- } catch (cause) {
1184
- settled = err(networkError(cause));
1185
- } finally {
1186
- merged.dispose();
1187
- deadline2.cancel();
1188
- }
1189
- if (settled.ok) {
1190
- emit(stamp({ phase: "settled", ok: true, reason: "ok" }));
1191
- return settled;
1192
- }
1193
- const error = settled.error;
1194
- const decision = decideRetry(error, attempt, {
1195
- maxAttempts,
1196
- rng,
1197
- now: timers.now(),
1198
- aborted: req.signal?.aborted === true,
1199
- ...perCallMaxAttempts !== void 0 ? { perCallMaxAttempts } : {},
1200
- ...deps.errorPolicy !== void 0 ? { policy: deps.errorPolicy } : {}
1201
- });
1202
- const settledEvent = {
1203
- ok: false,
1204
- code: error.code,
1205
- reason: decision.reason,
1206
- ...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {},
1207
- ...error.requestId !== void 0 ? { requestId: error.requestId } : {}
1208
- };
1209
- if (!decision.retry) {
1210
- emit(stamp({ phase: "settled", ...settledEvent }));
1211
- return err(error);
1212
- }
1213
- emit(stamp({ phase: "retry", ...settledEvent, delayMs: decision.delayMs }));
1214
- await sleep(decision.delayMs, req.signal);
1215
- if (req.signal?.aborted === true) {
1216
- emit(stamp({ phase: "settled", ...settledEvent, reason: "aborted" }));
1217
- return err(error);
1218
- }
1219
- attempt += 1;
1220
- }
1221
- }
1222
- async function authorize(req) {
1223
- return withAuthHeaders(req, await resolveDeviceAuth(deps.auth));
1224
- }
1225
- async function* stream(call, req, signal) {
1226
- emit(
1227
- Object.freeze({
1228
- call,
1229
- phase: "stream.open",
1230
- method: req.method,
1231
- path: req.path,
1232
- attempt: 0
1233
- })
1234
- );
1235
- try {
1236
- yield* deps.auth.transport.stream(req, signal);
1237
- } catch {
1238
- yield errorFrame({
1239
- // The same wire spelling sse.ts synthesizes, so `fromWire` folds it to the retryable `internalError`
1240
- // like any other transport failure. wireMessage stays null: it is the SERVER's text, and a thrown
1241
- // host exception's `.message` is not that.
1242
- code: "internal_error",
1243
- retryable: true,
1244
- wireMessage: null,
1245
- synthesized: true,
1246
- lastEventId: null,
1247
- serverRequestId: null
1248
- });
1249
- }
1250
- }
1251
- return Object.freeze({ send, authorize, stream });
1252
- }
1253
- function assembleHeaders(req, idempotencyKey) {
1254
- const headers = {};
1255
- for (const [key, value] of Object.entries(req.headers ?? {})) {
1256
- if (key.toLowerCase() === IDEMPOTENCY_HEADER) continue;
1257
- headers[key] = value;
1258
- }
1259
- if (idempotencyKey !== null) headers["Idempotency-Key"] = idempotencyKey;
1260
- return { ...req, headers };
1261
- }
1262
- function defaultIdempotencyKeyFactory() {
1263
- let counter = 0;
1264
- return () => `efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
1265
- }
1266
- var POLICY_MAX_ATTEMPTS_CAP = 10;
1267
- function decideRetry(error, attempt, ctx) {
1268
- if (ctx.aborted) return { retry: false, reason: "aborted" };
1269
- const throttle = throttleKind(error);
1270
- if (throttle === "quota") {
1271
- return { retry: false, reason: "daily-quota-exhausted" };
1272
- }
1273
- if (throttle !== "burst" && !isAutoRetryable(error.code)) {
1274
- return { retry: false, reason: "terminal-code" };
1275
- }
1276
- const reason = throttle === "burst" ? "burst-throttle" : "retryable-code";
1277
- const policyVetoedRetry = () => {
1278
- if (ctx.policy === void 0) return false;
1279
- try {
1280
- return !ctx.policy.shouldRetry(error.code, attempt);
1281
- } catch {
1282
- return false;
1283
- }
1284
- };
1285
- if (policyVetoedRetry()) return { retry: false, reason: "terminal-code" };
1286
- const policyCeiling = () => {
1287
- if (ctx.policy === void 0) return null;
1288
- let raw;
1289
- try {
1290
- raw = ctx.policy.maxAttempts(error.code);
1291
- } catch {
1292
- return null;
1293
- }
1294
- if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
1295
- return Math.max(1, Math.min(POLICY_MAX_ATTEMPTS_CAP, Math.floor(raw)));
1296
- };
1297
- const ceiling = ctx.perCallMaxAttempts ?? policyCeiling() ?? ctx.maxAttempts;
1298
- if (attempt + 1 >= ceiling) return { retry: false, reason: "attempts-exhausted" };
1299
- const override = retryOverrideMs(error, ctx.now);
1300
- if (override !== null) {
1301
- if (override > RETRY_OVERRIDE_MAX_MS) {
1302
- return { retry: false, reason: "server-reset-beyond-budget" };
1303
- }
1304
- return { retry: true, reason, delayMs: override };
1305
- }
1306
- return { retry: true, reason, delayMs: backoffDelayMs(attempt, ctx.rng) };
1307
- }
1308
- function throttleKind(error) {
1309
- const code = error.code === "unknown" ? fromWire(rawWireCode(error.raw)) : error.code;
1310
- if (code === "quotaExceeded") return "quota";
1311
- if (code === "rateLimited") return "burst";
1312
- if (error.httpStatus === 429) {
1313
- return "burst";
1314
- }
1315
- return null;
1316
- }
1317
- function retryOverrideMs(error, now) {
1318
- const at = findResetsAt(error.raw);
1319
- if (at === null) return null;
1320
- const delta = at - now;
1321
- return delta > 0 ? delta : 0;
1322
- }
1323
- function findResetsAt(raw) {
1324
- for (const scope of candidateScopes(raw)) {
1325
- const value = scope["resets_at"];
1326
- const parsed = parseInstantMs(value);
1327
- if (parsed !== null) return parsed;
1328
- }
1329
- return null;
1330
- }
1331
- function candidateScopes(raw) {
1332
- if (!isRecord(raw)) return [];
1333
- const out = [raw];
1334
- for (const nested of ["error", "detail"]) {
1335
- const value = raw[nested];
1336
- if (isRecord(value)) out.push(value);
1337
- }
1338
- return out;
1339
- }
1340
- function parseInstantMs(value) {
1341
- if (typeof value === "number" && Number.isFinite(value)) {
1342
- return value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
1343
- }
1344
- if (typeof value === "string" && value.trim().length > 0) {
1345
- const parsed = Date.parse(value);
1346
- return Number.isFinite(parsed) ? parsed : null;
1347
- }
1348
- return null;
1349
- }
1350
- function rawWireCode(raw) {
1351
- for (const scope of candidateScopes(raw)) {
1352
- const code = scope["code"];
1353
- if (typeof code === "string" && code.length > 0) return code;
1354
- }
1355
- return null;
1356
- }
1357
- function isRecord(value) {
1358
- return typeof value === "object" && value !== null;
1359
- }
1360
- async function resolveDeviceAuth(auth) {
1361
- if (auth.mode === "anonymous") {
1362
- return {
1363
- mode: "anonymous",
1364
- publishableKey: auth.publishableKey,
1365
- userRef: auth.userRef,
1366
- ...auth.sessionId ? { sessionId: auth.sessionId } : {}
1367
- };
1368
- }
1369
- return {
1370
- mode: "personalized",
1371
- token: await auth.identity.currentToken(),
1372
- userRef: auth.userRef,
1373
- ...auth.sessionId ? { sessionId: auth.sessionId } : {}
1374
- };
1375
- }
1376
- function boundedSignal(ms, timers) {
1377
- const ctrl = new AbortController();
1378
- const handle = timers.setTimeout(() => ctrl.abort(), ms);
1379
- return { signal: ctrl.signal, cancel: () => timers.clearTimeout(handle) };
1380
- }
1381
- function mergeSignals(deadline2, caller) {
1382
- const noop = () => void 0;
1383
- if (!caller) return { signal: deadline2, dispose: noop };
1384
- const ctrl = new AbortController();
1385
- if (deadline2.aborted || caller.aborted) {
1386
- ctrl.abort();
1387
- return { signal: ctrl.signal, dispose: noop };
1388
- }
1389
- const onAbort = () => ctrl.abort();
1390
- deadline2.addEventListener("abort", onAbort, { once: true });
1391
- caller.addEventListener("abort", onAbort, { once: true });
1392
- return {
1393
- signal: ctrl.signal,
1394
- dispose: () => {
1395
- deadline2.removeEventListener("abort", onAbort);
1396
- caller.removeEventListener("abort", onAbort);
1397
- }
1398
- };
1399
- }
1400
- function delayAbortable(ms, timers, signal) {
1401
- if (ms <= 0 || signal?.aborted === true) return Promise.resolve();
1402
- return new Promise((resolve) => {
1403
- const handle = timers.setTimeout(() => {
1404
- signal?.removeEventListener("abort", onAbort);
1405
- resolve();
1406
- }, ms);
1407
- const onAbort = () => {
1408
- timers.clearTimeout(handle);
1409
- resolve();
1410
- };
1411
- signal?.addEventListener("abort", onAbort, { once: true });
1412
- });
1413
- }
1414
-
1415
- // src/client/text.ts
1416
- function hasLoneSurrogate(value) {
1417
- for (let i = 0; i < value.length; i += 1) {
1418
- const code = value.charCodeAt(i);
1419
- if (code >= 55296 && code <= 56319) {
1420
- const low = value.charCodeAt(i + 1);
1421
- if (!(low >= 56320 && low <= 57343)) return true;
1422
- i += 1;
1423
- } else if (code >= 56320 && code <= 57343) {
1424
- return true;
1425
- }
1426
- }
1427
- return false;
1428
- }
1429
- function serverLength(value) {
1430
- return [...value].length;
1431
- }
1432
-
1433
- // src/core/media/ports.ts
1434
- var unavailableUpload = Object.freeze({
1435
- async presignedPut() {
1436
- return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"));
1437
- }
1438
- });
1439
- function delayAbortable2(ms, signal, timers) {
1440
- return new Promise((resolve) => {
1441
- if (signal.aborted) {
1442
- resolve();
1443
- return;
1444
- }
1445
- const holder = { handle: void 0 };
1446
- const done = () => {
1447
- timers.clearTimeout(holder.handle);
1448
- signal.removeEventListener("abort", done);
1449
- resolve();
1450
- };
1451
- holder.handle = timers.setTimeout(done, ms);
1452
- signal.addEventListener("abort", done, { once: true });
1453
- });
1454
- }
1455
- function mergeSignals2(a, b) {
1456
- if (!b) return a;
1457
- const ctrl = new AbortController();
1458
- if (a.aborted || b.aborted) {
1459
- ctrl.abort();
1460
- return ctrl.signal;
1461
- }
1462
- const onAbort = () => ctrl.abort();
1463
- a.addEventListener("abort", onAbort, { once: true });
1464
- b.addEventListener("abort", onAbort, { once: true });
1465
- return ctrl.signal;
1466
- }
1467
- var MediaStore = class {
1468
- constructor(initial) {
1469
- this.listeners = /* @__PURE__ */ new Set();
1470
- this.epoch = 0;
1471
- this.inFlight = null;
1472
- this.snapshot = Object.freeze({ ...initial });
1473
- }
1474
- subscribe(listener) {
1475
- this.listeners.add(listener);
1476
- return () => {
1477
- this.listeners.delete(listener);
1478
- };
1479
- }
1480
- getSnapshot() {
1481
- return this.snapshot;
1482
- }
1483
- patch(partial) {
1484
- this.snapshot = Object.freeze({ ...this.snapshot, ...partial });
1485
- for (const listener of this.listeners) listener();
1486
- }
1487
- beginOperation(external) {
1488
- this.inFlight?.abort();
1489
- const ctrl = new AbortController();
1490
- this.inFlight = ctrl;
1491
- const epoch = this.epoch;
1492
- const signal = external ? mergeSignals2(ctrl.signal, external) : ctrl.signal;
1493
- return {
1494
- signal,
1495
- epoch,
1496
- settle: () => {
1497
- if (this.inFlight === ctrl) this.inFlight = null;
1498
- }
1499
- };
1500
- }
1501
- alive(epoch) {
1502
- return epoch === this.epoch;
1503
- }
1504
- /** Re-scope on user/pet switch: aborts in-flight and bumps the epoch so a late write drops. */
1505
- rescope() {
1506
- this.epoch += 1;
1507
- this.inFlight?.abort();
1508
- this.inFlight = null;
1509
- }
1510
- /** Idempotent teardown: aborts in-flight, bumps the epoch, drops every listener. */
1511
- dispose() {
1512
- this.epoch += 1;
1513
- this.inFlight?.abort();
1514
- this.inFlight = null;
1515
- this.listeners.clear();
1516
- }
1517
- };
1518
-
1519
- // src/core/chat/chatMappers.ts
1520
- function makeUser(id, text) {
1521
- return Object.freeze({ id, role: "user", text, pending: true });
1522
- }
1523
- function makeAssistant(id, text) {
1524
- return Object.freeze({ id, role: "assistant", text });
1525
- }
1526
- function stripPending(m) {
1527
- return Object.freeze({ id: m.id, role: m.role, text: m.text });
1528
- }
1529
- function appendText(m, text) {
1530
- const next = {
1531
- id: m.id,
1532
- role: m.role,
1533
- text: m.text + text
1534
- };
1535
- if (m.citations) next.citations = m.citations;
1536
- if (m.responseId) next.responseId = m.responseId;
1537
- return Object.freeze(next);
1538
- }
1539
- function finalizeAssistant(m, done) {
1540
- const next = {
1541
- id: done.messageId ? done.messageId : m.id,
1542
- role: "assistant",
1543
- text: m.text
1544
- };
1545
- if (done.citations.length > 0) next.citations = done.citations;
1546
- if (done.messageId) next.responseId = brandResponseId(done.messageId);
1547
- return Object.freeze(next);
1548
- }
1549
- function freezeSnapshot(s) {
1550
- return Object.freeze({
1551
- status: s.status,
1552
- messages: Object.freeze([...s.messages]),
1553
- conversationId: s.conversationId,
1554
- error: s.error,
1555
- isStreaming: s.isStreaming,
1556
- isBootstrapping: s.isBootstrapping,
1557
- suggestedPrompts: Object.freeze([...s.suggestedPrompts])
1558
- });
1559
- }
1560
- function makeError(code, retryable, wireMessage) {
1561
- return makeEverfurError(code, { retryable, ...wireMessage ? { wireMessage } : {} });
1562
- }
1563
- function errorFromFrame(frame) {
1564
- const code = fromWire(frame.code);
1565
- return makeEverfurError(code, {
1566
- retryable: frame.retryable || shouldRetry(code),
1567
- wireCode: frame.code,
1568
- ...frame.serverRequestId ? { requestId: frame.serverRequestId } : {},
1569
- ...frame.wireMessage ? { wireMessage: frame.wireMessage } : {},
1570
- raw: frame
1571
- });
1572
- }
1573
- function synthErrorFrame(error) {
1574
- return errorFrame({
1575
- code: canonicalWireCode(error.code),
1576
- retryable: error.retryable,
1577
- wireMessage: error.wireMessage ?? null,
1578
- synthesized: true,
1579
- lastEventId: null,
1580
- serverRequestId: error.requestId ?? null
1581
- });
1582
- }
1583
- function canonicalWireCode(code) {
1584
- switch (code) {
1585
- case "authExpired":
1586
- return "AUTH_EXPIRED";
1587
- case "authRejected":
1588
- return "AuthorizationException";
1589
- case "sessionRequired":
1590
- return "session_required";
1591
- case "accessDenied":
1592
- return "ACCESS_DENIED";
1593
- case "paymentRequired":
1594
- return "TIER_UPGRADE_REQUIRED";
1595
- case "quotaExceeded":
1596
- return "QUOTA_EXCEEDED";
1597
- case "rateLimited":
1598
- return "RATE_LIMITED";
1599
- case "validationFailed":
1600
- return "ValidationException";
1601
- case "sdkUpdateRequired":
1602
- return "invalidRequest";
1603
- case "conflict":
1604
- return "ConflictException";
1605
- case "idempotencyConflict":
1606
- return "IDEMPOTENCY_CONFLICT";
1607
- case "idempotencyInFlight":
1608
- return "IDEMPOTENCY_KEY_IN_FLIGHT";
1609
- case "conversationNotFound":
1610
- return "CONVERSATION_NOT_FOUND";
1611
- case "petNotFound":
1612
- return "PET_NOT_FOUND";
1613
- case "resourceNotFound":
1614
- return "ResourceNotFoundException";
1615
- case "streamTimeout":
1616
- return "STREAM_TIMEOUT";
1617
- case "mediaUploadFailed":
1618
- return "MEDIA_UPLOAD_FAILED";
1619
- case "moderationBlocked":
1620
- return "MODERATION_BLOCKED";
1621
- case "upstreamLlmTimeout":
1622
- return "UPSTREAM_LLM_TIMEOUT";
1623
- case "internalError":
1624
- return "INTERNAL_ERROR";
1625
- case "notImplemented":
1626
- return "NotImplementedException";
1627
- case "serviceUnavailable":
1628
- return "ServiceUnavailableException";
1629
- case "streamIncomplete":
1630
- return "STREAM_INCOMPLETE";
1631
- case "unknown":
1632
- return "UNKNOWN";
1633
- default:
1634
- return assertNever(code);
1635
- }
1636
- }
1637
- function parsePromptCategories(raw) {
1638
- const list = Array.isArray(raw) ? raw : isPlainObject2(raw) && Array.isArray(raw["categories"]) ? raw["categories"] : [];
1639
- const out = [];
1640
- for (const entry of list) {
1641
- if (!isPlainObject2(entry)) continue;
1642
- const category = asStr(entry["category"]) ?? asStr(entry["title"]) ?? "";
1643
- const prompts = asPromptTextList(entry["prompts"] ?? entry["questions"]);
1644
- if (category.length === 0 && prompts.length === 0) continue;
1645
- out.push(Object.freeze({ category, prompts: Object.freeze(prompts) }));
1646
- }
1647
- return Object.freeze(out);
1648
- }
1649
- function flattenPrompts(categories) {
1650
- const seen = /* @__PURE__ */ new Set();
1651
- const out = [];
1652
- for (const category of categories) {
1653
- for (const prompt of category.prompts) {
1654
- const trimmed = prompt.trim();
1655
- if (trimmed.length === 0 || seen.has(trimmed)) continue;
1656
- seen.add(trimmed);
1657
- out.push(trimmed);
1658
- }
1659
- }
1660
- return out;
1661
- }
1662
- function isPlainObject2(v) {
1663
- return typeof v === "object" && v !== null && !Array.isArray(v);
1664
- }
1665
- function asStr(v) {
1666
- return typeof v === "string" ? v : null;
1667
- }
1668
- function asPromptTextList(v) {
1669
- if (!Array.isArray(v)) return [];
1670
- const out = [];
1671
- for (const entry of v) {
1672
- if (typeof entry === "string") {
1673
- out.push(entry);
1674
- } else if (isPlainObject2(entry)) {
1675
- const text = asStr(entry["text"]) ?? asStr(entry["prompt"]) ?? asStr(entry["title"]);
1676
- if (text !== null) out.push(text);
1677
- }
1678
- }
1679
- return out;
1680
- }
1681
- function defaultIdFactory() {
1682
- let counter = 0;
1683
- return () => `m-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1684
- }
1685
- function defaultIdempotencyFactory() {
1686
- let counter = 0;
1687
- return () => `chat-send-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1688
- }
1689
- function brandConversationId(raw) {
1690
- return raw;
1691
- }
1692
- function brandResponseId(raw) {
1693
- return raw;
1694
- }
1695
-
1696
- // src/core/chat/watchdog.ts
1697
- var defaultTimers2 = {
1698
- setTimeout: (handler, ms) => setTimeout(handler, ms),
1699
- clearTimeout: (handle) => clearTimeout(handle),
1700
- now: () => Date.now()
1701
- };
1702
- async function* withWatchdog(source, budget, signal, timers) {
1703
- const it = source[Symbol.asyncIterator]();
1704
- const overall = deadline(budget.overallMs, timers);
1705
- const idle = deadline(budget.idleMs, timers);
1706
- const abort = abortPromise(signal);
1707
- try {
1708
- for (; ; ) {
1709
- if (signal.aborted) return;
1710
- const nextTagged = it.next().then(
1711
- (value) => ({ tag: "next", value }),
1712
- // A rejected it.next() is a RAW mid-stream transport drop (WiFi->cellular, backgrounding), NOT a clean
1713
- // end-of-stream. The prior code coerced it to { done: true }, which silently short-circuited the SDK's
1714
- // own retry ladder (SPEC-10 §7). Tag it so the loop can emit a retryable frame instead.
1715
- () => ({ tag: "streamError" })
1716
- );
1717
- const outcome = await Promise.race([
1718
- nextTagged,
1719
- idle.promise.then(() => ({ tag: "idle" })),
1720
- overall.promise.then(() => ({ tag: "overall" })),
1721
- abort.then(() => ({ tag: "abort" }))
1722
- ]);
1723
- if (outcome.tag === "abort") return;
1724
- if (outcome.tag === "streamError") {
1725
- if (signal.aborted) return;
1726
- yield synthStreamErrorFrame();
1727
- return;
1728
- }
1729
- if (outcome.tag === "idle" || outcome.tag === "overall") {
1730
- yield synthTimeoutFrame();
1731
- return;
1732
- }
1733
- const result = outcome.value;
1734
- if (result.done) return;
1735
- idle.reset(budget.idleMs);
1736
- yield result.value;
1737
- if (result.value.terminal) return;
1738
- }
1739
- } finally {
1740
- idle.cancel();
1741
- overall.cancel();
1742
- void Promise.resolve(it.return?.(void 0)).catch(() => {
1743
- });
1744
- }
1745
- }
1746
- function synthTimeoutFrame() {
1747
- return errorFrame({
1748
- code: "STREAM_TIMEOUT",
1749
- retryable: true,
1750
- wireMessage: null,
1751
- synthesized: true,
1752
- lastEventId: null
1753
- });
1754
- }
1755
- function synthStreamErrorFrame() {
1756
- return errorFrame({
1757
- code: "STREAM_INCOMPLETE",
1758
- retryable: true,
1759
- wireMessage: null,
1760
- synthesized: true,
1761
- lastEventId: null
1762
- });
1763
- }
1764
- function deadline(ms, timers) {
1765
- let resolveFn = () => {
1766
- };
1767
- const promise = new Promise((resolve) => {
1768
- resolveFn = resolve;
1769
- });
1770
- let handle = timers.setTimeout(() => resolveFn(), ms);
1771
- return {
1772
- promise,
1773
- reset(next) {
1774
- timers.clearTimeout(handle);
1775
- handle = timers.setTimeout(() => resolveFn(), next);
1776
- },
1777
- cancel() {
1778
- timers.clearTimeout(handle);
1779
- }
1780
- };
1781
- }
1782
- function abortPromise(signal) {
1783
- return new Promise((resolve) => {
1784
- if (signal.aborted) {
1785
- resolve();
1786
- return;
1787
- }
1788
- signal.addEventListener("abort", () => resolve(), { once: true });
1789
- });
1790
- }
1791
-
1792
- // src/core/chat/ChatController.ts
1793
- var DEFAULT_IDLE_MS = 6e4;
1794
- var DEFAULT_OVERALL_MS = 18e4;
1795
- var DELTA_FLUSH_MS = 24;
1796
- var DELTA_FLUSH_CHARS = 512;
1797
- var SEND_IS_SERVER_DEDUPED = false;
1798
- function createChatController(deps) {
1799
- return new ChatControllerImpl(deps);
1800
- }
1801
- var ChatControllerImpl = class extends MediaStore {
1802
- constructor(deps) {
1803
- super(
1804
- freezeSnapshot({
1805
- status: "idle",
1806
- messages: [],
1807
- conversationId: deps.initialConversationId ?? null,
1808
- error: null,
1809
- isStreaming: false,
1810
- isBootstrapping: false,
1811
- suggestedPrompts: []
1812
- })
1813
- );
1814
- this.handlerTeardowns = /* @__PURE__ */ new Set();
1815
- this.lastTurn = null;
1816
- this.lastResponseIdValue = null;
1817
- /** Delta coalescing buffer (PERF1): accumulated assistant text not yet flushed to the snapshot. */
1818
- this.pendingDelta = "";
1819
- this.flushHandle = null;
1820
- this.auth = deps.auth;
1821
- this.funnel = deps.funnel ?? createRequestFunnel({
1822
- auth: deps.auth,
1823
- ...deps.errorPolicy ? { errorPolicy: deps.errorPolicy } : {}
1824
- });
1825
- this.telemetry = deps.telemetry ?? noopTelemetry;
1826
- this.errorPolicy = deps.errorPolicy ?? defaultErrorPolicy;
1827
- this.timers = deps.timers ?? defaultTimers2;
1828
- this.rng = deps.rng ?? Math.random;
1829
- this.newId = deps.newId ?? defaultIdFactory();
1830
- this.makeIdempotencyKey = deps.makeIdempotencyKey ?? defaultIdempotencyFactory();
1831
- this.budget = {
1832
- idleMs: deps.budget?.idleMs ?? DEFAULT_IDLE_MS,
1833
- overallMs: deps.budget?.overallMs ?? DEFAULT_OVERALL_MS
1834
- };
1835
- }
1836
- // ---- store ------------------------------------------------------------
1837
- // subscribe / getSnapshot / beginOperation / alive are inherited from MediaStore. patch is overridden so the
1838
- // messages array stays deep-frozen (the base freezes only the snapshot object).
1839
- patch(partial) {
1840
- if (partial.messages !== void 0) {
1841
- const frozen = Object.freeze([...partial.messages]);
1842
- super.patch({ ...partial, messages: frozen });
1843
- return;
1844
- }
1845
- super.patch(partial);
1846
- }
1847
- send(text, opts, handlers) {
1848
- const options = opts ?? {};
1849
- const invalid2 = validateMessageText(text);
1850
- if (invalid2 !== null) {
1851
- this.telemetry.track("chat.send.rejected", { reason: invalid2.reason });
1852
- this.patch({ status: "error", isStreaming: false, error: invalid2.error });
1853
- if (handlers) {
1854
- handlers.onError(invalid2.error);
1855
- return () => {
1856
- };
1857
- }
1858
- return singleFrameStream(synthErrorFrame(invalid2.error));
1859
- }
1860
- if (handlers) return this.driveWithHandlers(text, options, handlers);
1861
- const turn = this.beginTurn(text, options);
1862
- return this.runTurn(turn, options.signal);
1863
- }
1864
- retryLast() {
1865
- const turn = this.lastTurn;
1866
- if (turn === null) return emptyStream();
1867
- turn.assistantMessageId = null;
1868
- turn.sawDelta = false;
1869
- turn.conversationIdOverride = null;
1870
- this.discardPendingDelta();
1871
- const hasUser = this.snapshot.messages.some((m) => m.id === turn.userMessageId);
1872
- const messages = hasUser ? this.snapshot.messages : [...this.snapshot.messages, makeUser(turn.userMessageId, turn.text)];
1873
- this.patch({ error: null, messages });
1874
- return this.runTurn(turn, void 0);
1875
- }
1876
- stop() {
1877
- this.inFlight?.abort();
1878
- this.inFlight = null;
1879
- this.discardPendingDelta();
1880
- this.telemetry.track("chat.cancel", {});
1881
- const messages = this.snapshot.messages.filter((m) => !(m.role === "user" && m.pending === true));
1882
- const changed = messages.length !== this.snapshot.messages.length;
1883
- if (this.snapshot.status === "streaming" || changed) {
1884
- this.patch({ status: "idle", isStreaming: false, ...changed ? { messages } : {} });
1885
- }
1886
- }
1887
- rescope() {
1888
- super.rescope();
1889
- this.discardPendingDelta();
1890
- if (this.snapshot.status === "streaming") this.patch({ status: "idle", isStreaming: false });
1891
- }
1892
- dispose() {
1893
- this.discardPendingDelta();
1894
- for (const teardown of this.handlerTeardowns) teardown();
1895
- this.handlerTeardowns.clear();
1896
- super.dispose();
1897
- }
1898
- adoptConversation(id) {
1899
- if (this.snapshot.conversationId === id) return;
1900
- this.patch({ conversationId: id });
1901
- }
1902
- adoptPrompts(categories) {
1903
- const prompts = flattenPrompts(categories);
1904
- if (prompts.length === 0 && this.snapshot.suggestedPrompts.length === 0) return;
1905
- this.patch({ suggestedPrompts: Object.freeze(prompts) });
1906
- }
1907
- // ---- unary bootstrap helpers (§8) -------------------------------------
1908
- async createConversation(opts) {
1909
- return this.createConversationBounded(opts?.petRef ?? null);
1910
- }
1911
- /** The bounded create used by both the public helper and the turn pipeline (a caller signal ties it to op). */
1912
- async createConversationBounded(petRef, signal) {
1913
- const req = {
1914
- method: "POST",
1915
- path: "/widget/v1/conversations",
1916
- body: petRef ? { pet_ref: petRef } : {}
1917
- };
1918
- const res = await this.authedUnary(
1919
- "chat.createConversation",
1920
- req,
1921
- signal,
1922
- // The widget lane does NOT read `Idempotency-Key`: its router is a plain APIRouter with no
1923
- // idempotency route class, so a replay is a second CREATE, not a dedup, and retrying leaves the
1924
- // partner with orphan threads nobody asked for. `maxAttempts: 1` stops the replay.
1925
- //
1926
- // The key itself is deliberately STILL SENT (no `idempotent: false`): it costs nothing on the wire,
1927
- // it is what the funnel would mint anyway, and it starts working by itself the day the route dedups.
1928
- // Deleting this one option is then the whole reversal.
1929
- { maxAttempts: 1 }
1930
- );
1931
- if (!res.ok) return err(res.error);
1932
- const raw = res.value?.conversation_id ?? res.value?.id;
1933
- if (typeof raw !== "string" || raw.length === 0) {
1934
- return err(makeError("internalError", true));
1935
- }
1936
- return ok(brandConversationId(raw));
1937
- }
1938
- async getPrompts(opts) {
1939
- const petRef = opts?.petRef ?? null;
1940
- if (petRef !== null && hasLoneSurrogate(petRef)) {
1941
- return err(
1942
- makeEverfurError("validationFailed", {
1943
- retryable: false,
1944
- wireMessage: "pet_ref contains an unpaired surrogate and cannot be encoded"
1945
- })
1946
- );
1947
- }
1948
- const query = petRef !== null ? `?pet_ref=${encodeURIComponent(petRef)}` : "";
1949
- const res = await this.authedUnary("chat.getPrompts", {
1950
- method: "GET",
1951
- path: `/widget/v1/suggested-prompts${query}`
1952
- });
1953
- if (!res.ok) return err(res.error);
1954
- return ok(parsePromptCategories(res.value));
1955
- }
1956
- /**
1957
- * A unary authed hop, through the ONE REQUEST FUNNEL. The funnel owns the per-attempt deadline (PERF2:
1958
- * a stalled connection settles to a retryable error instead of hanging the spinner forever), the auth
1959
- * spine, retry with full jitter, the client-minted idempotency key, and telemetry. Settles; never throws.
1960
- */
1961
- async authedUnary(call, req, external, opts) {
1962
- return this.funnel.send(call, external ? { ...req, signal: external } : req, opts);
1963
- }
1964
- // ---- imperative escape hatch ------------------------------------------
1965
- driveWithHandlers(text, opts, handlers) {
1966
- const cancel = new AbortController();
1967
- const signal = mergeSignals2(cancel.signal, opts.signal);
1968
- const turn = this.beginTurn(text, opts);
1969
- const iterable = this.runTurn(turn, signal);
1970
- let torn = false;
1971
- const teardown = () => {
1972
- if (torn) return;
1973
- torn = true;
1974
- cancel.abort();
1975
- this.handlerTeardowns.delete(teardown);
1976
- };
1977
- this.handlerTeardowns.add(teardown);
1978
- void (async () => {
1979
- for await (const frame of iterable) {
1980
- if (torn) break;
1981
- handlers.onFrame(frame);
1982
- if (frame.kind === "done") handlers.onDone(this.lastResponseIdValue);
1983
- }
1984
- if (!torn && this.snapshot.status === "error" && this.snapshot.error !== null) {
1985
- handlers.onError(this.snapshot.error);
1986
- }
1987
- this.handlerTeardowns.delete(teardown);
1988
- })();
1989
- return teardown;
1990
- }
1991
- // ---- the turn pipeline ------------------------------------------------
1992
- beginTurn(text, opts) {
1993
- const turn = {
1994
- epoch: this.epoch,
1995
- text,
1996
- petRef: opts.petRef ?? null,
1997
- idempotencyKey: opts.idempotencyKey ?? this.makeIdempotencyKey(),
1998
- userMessageId: this.newId(),
1999
- assistantMessageId: null,
2000
- sawDelta: false,
2001
- conversationIdOverride: opts.conversationId ?? null
2002
- };
2003
- this.patch({
2004
- error: null,
2005
- messages: [...this.snapshot.messages, makeUser(turn.userMessageId, text)]
2006
- });
2007
- return turn;
2008
- }
2009
- async *runTurn(turn, external) {
2010
- const op = this.beginOperation(external);
2011
- turn.epoch = op.epoch;
2012
- this.patch({ status: "streaming", isStreaming: true, error: null });
2013
- this.lastTurn = turn;
2014
- let retries = 0;
2015
- let recreated = false;
2016
- let refreshedOnce = false;
2017
- try {
2018
- for (; ; ) {
2019
- if (op.signal.aborted || !this.alive(op.epoch)) return;
2020
- const needsConversation = turn.conversationIdOverride === null && this.snapshot.conversationId === null;
2021
- if (needsConversation) {
2022
- const created = await this.createConversationBounded(turn.petRef, op.signal);
2023
- if (op.signal.aborted || !this.alive(op.epoch)) return;
2024
- if (!created.ok) {
2025
- yield* this.emitTerminal(turn, created.error, synthErrorFrame(created.error));
2026
- return;
2027
- }
2028
- this.adoptConversation(created.value);
2029
- }
2030
- const convId = turn.conversationIdOverride ?? this.snapshot.conversationId;
2031
- if (convId === null) {
2032
- const e = makeError("internalError", true);
2033
- yield* this.emitTerminal(turn, e, synthErrorFrame(e));
2034
- return;
2035
- }
2036
- this.clearAssistantInProgress(turn);
2037
- const attemptCtrl = new AbortController();
2038
- const attemptSignal = mergeSignals2(op.signal, attemptCtrl.signal);
2039
- let terminalError = null;
2040
- try {
2041
- let authedReq;
2042
- try {
2043
- authedReq = await this.funnel.authorize(this.buildSendRequest(turn, convId));
2044
- } catch {
2045
- const e = this.authRejected();
2046
- yield* this.emitTerminal(turn, e, synthErrorFrame(e));
2047
- return;
2048
- }
2049
- if (op.signal.aborted || !this.alive(op.epoch)) return;
2050
- const source = this.funnel.stream("chat.send", authedReq, attemptSignal);
2051
- for await (const frame of withWatchdog(source, this.budget, attemptSignal, this.timers)) {
2052
- if (!this.alive(op.epoch)) return;
2053
- if (frame.kind === "error" && frame.terminal) {
2054
- terminalError = frame;
2055
- break;
2056
- }
2057
- this.applyFrame(frame, turn);
2058
- yield frame;
2059
- if (frame.terminal) {
2060
- op.settle();
2061
- return;
2062
- }
2063
- }
2064
- } finally {
2065
- attemptCtrl.abort();
2066
- }
2067
- if (op.signal.aborted || !this.alive(op.epoch)) return;
2068
- if (terminalError === null) {
2069
- if (this.snapshot.status === "complete") return;
2070
- const e = makeError("streamIncomplete", true);
2071
- yield* this.emitTerminal(turn, e, synthErrorFrame(e));
2072
- return;
2073
- }
2074
- const code = fromWire(terminalError.code);
2075
- if (code === "authExpired" && this.auth.mode === "personalized" && !refreshedOnce) {
2076
- refreshedOnce = true;
2077
- this.telemetry.track("chat.auth.refresh", {});
2078
- const refreshed = await this.tryForceRefresh();
2079
- if (op.signal.aborted || !this.alive(op.epoch)) return;
2080
- if (!refreshed) {
2081
- const e = this.authRejected();
2082
- yield* this.emitTerminal(turn, e, terminalError);
2083
- return;
2084
- }
2085
- continue;
2086
- }
2087
- if (code === "authExpired") {
2088
- this.telemetry.track("chat.auth.rejected", {});
2089
- const e = this.authRejected();
2090
- yield* this.emitTerminal(turn, e, terminalError);
2091
- return;
2092
- }
2093
- if (code === "accessDenied") {
2094
- this.telemetry.track("chat.access_denied", {});
2095
- yield* this.emitTerminal(turn, errorFromFrame(terminalError), terminalError);
2096
- return;
2097
- }
2098
- if (canRecreateOnNotFound(code) && !recreated) {
2099
- recreated = true;
2100
- this.telemetry.track("chat.conv.recreate", {});
2101
- this.adoptConversation(null);
2102
- turn.conversationIdOverride = null;
2103
- continue;
2104
- }
2105
- const framedRetry = terminalError.retryable && shouldRetry(code, true);
2106
- if (SEND_IS_SERVER_DEDUPED && framedRetry && retries + 1 < this.errorPolicy.maxAttempts(code)) ;
2107
- yield* this.emitTerminal(turn, errorFromFrame(terminalError), terminalError);
2108
- return;
2109
- }
2110
- } finally {
2111
- op.settle();
2112
- }
2113
- }
2114
- *emitTerminal(turn, error, frame) {
2115
- this.applyError(turn, error);
2116
- yield frame;
2117
- }
2118
- // ---- frame -> state ---------------------------------------------------
2119
- applyFrame(frame, turn) {
2120
- switch (frame.kind) {
2121
- case "accepted":
2122
- if (!this.snapshot.isStreaming) this.patch({ status: "streaming", isStreaming: true });
2123
- return;
2124
- case "heartbeat":
2125
- return;
2126
- // silent; the watchdog resets its idle timer on any frame
2127
- case "delta":
2128
- this.applyDelta(frame.delta, turn);
2129
- return;
2130
- case "done":
2131
- this.applyDone(frame, turn);
2132
- return;
2133
- case "analysisStarted":
2134
- case "analysisComplete":
2135
- return;
2136
- // not part of chat render (analyze streams project elsewhere)
2137
- case "unknown":
2138
- this.telemetry.track("chat.frame.unknown", {});
2139
- return;
2140
- // forward-compat: ignore for render, keep streaming, never crash
2141
- case "error":
2142
- return;
2143
- // terminal errors are driven by the recovery switch, never here
2144
- default:
2145
- return assertNever(frame);
2146
- }
2147
- }
2148
- applyDelta(text, turn) {
2149
- if (turn.assistantMessageId === null) {
2150
- const assistantId = this.newId();
2151
- turn.assistantMessageId = assistantId;
2152
- turn.sawDelta = true;
2153
- const cleared = this.snapshot.messages.map(
2154
- (m) => m.id === turn.userMessageId && m.pending === true ? stripPending(m) : m
2155
- );
2156
- this.patch({
2157
- status: "streaming",
2158
- isStreaming: true,
2159
- messages: [...cleared, makeAssistant(assistantId, text)]
2160
- });
2161
- return;
2162
- }
2163
- this.pendingDelta += text;
2164
- if (this.pendingDelta.length >= DELTA_FLUSH_CHARS) {
2165
- this.flushPendingDelta(turn);
2166
- return;
2167
- }
2168
- this.scheduleDeltaFlush(turn);
2169
- }
2170
- scheduleDeltaFlush(turn) {
2171
- if (this.flushHandle !== null) return;
2172
- const scheduledEpoch = this.epoch;
2173
- this.flushHandle = this.timers.setTimeout(() => {
2174
- this.flushHandle = null;
2175
- if (!this.alive(scheduledEpoch)) {
2176
- this.pendingDelta = "";
2177
- return;
2178
- }
2179
- this.flushPendingDelta(turn);
2180
- }, DELTA_FLUSH_MS);
2181
- }
2182
- /** Fold the buffered deltas into the streaming assistant message as ONE patch (one listener notification). */
2183
- flushPendingDelta(turn) {
2184
- this.clearFlushTimer();
2185
- if (this.pendingDelta.length === 0) return;
2186
- const chunk = this.pendingDelta;
2187
- this.pendingDelta = "";
2188
- const assistantId = turn.assistantMessageId;
2189
- if (assistantId === null) return;
2190
- const messages = this.snapshot.messages.map((m) => m.id === assistantId ? appendText(m, chunk) : m);
2191
- this.patch({ messages });
2192
- }
2193
- /** Drop a buffered-but-unflushed delta (cancel / rescope / dispose / retry): no stale text leaks forward. */
2194
- discardPendingDelta() {
2195
- this.clearFlushTimer();
2196
- this.pendingDelta = "";
2197
- }
2198
- clearFlushTimer() {
2199
- if (this.flushHandle !== null) {
2200
- this.timers.clearTimeout(this.flushHandle);
2201
- this.flushHandle = null;
2202
- }
2203
- }
2204
- applyDone(done, turn) {
2205
- this.flushPendingDelta(turn);
2206
- this.lastResponseIdValue = done.messageId ? brandResponseId(done.messageId) : null;
2207
- const nextConv = done.conversationId ? brandConversationId(done.conversationId) : this.snapshot.conversationId;
2208
- let messages;
2209
- if (turn.assistantMessageId !== null) {
2210
- messages = this.snapshot.messages.map(
2211
- (m) => m.id === turn.assistantMessageId ? finalizeAssistant(m, done) : m
2212
- );
2213
- } else {
2214
- const assistantId = this.newId();
2215
- turn.assistantMessageId = assistantId;
2216
- turn.sawDelta = true;
2217
- const cleared = this.snapshot.messages.map(
2218
- (m) => m.id === turn.userMessageId && m.pending === true ? stripPending(m) : m
2219
- );
2220
- messages = [...cleared, finalizeAssistant(makeAssistant(assistantId, ""), done)];
2221
- }
2222
- this.patch({
2223
- status: "complete",
2224
- isStreaming: false,
2225
- error: null,
2226
- conversationId: nextConv,
2227
- messages
2228
- });
2229
- }
2230
- applyError(turn, error) {
2231
- this.flushPendingDelta(turn);
2232
- this.errorPolicy.onExpectedFailure?.(error);
2233
- const messages = turn.sawDelta ? this.snapshot.messages : this.snapshot.messages.filter((m) => m.id !== turn.userMessageId);
2234
- this.patch({ status: "error", isStreaming: false, error, messages });
2235
- }
2236
- clearAssistantInProgress(turn) {
2237
- this.discardPendingDelta();
2238
- if (turn.assistantMessageId === null) return;
2239
- const assistantId = turn.assistantMessageId;
2240
- turn.assistantMessageId = null;
2241
- turn.sawDelta = false;
2242
- const messages = this.snapshot.messages.filter((m) => m.id !== assistantId);
2243
- if (messages.length !== this.snapshot.messages.length) this.patch({ messages });
2244
- }
2245
- // ---- auth + request build --------------------------------------------
2246
- buildSendRequest(turn, convId) {
2247
- const body = { message: turn.text };
2248
- return {
2249
- method: "POST",
2250
- path: `/widget/v1/conversations/${convId}/messages`,
2251
- body,
2252
- // The TURN's own key, not a funnel mint. This is the streaming path, which the funnel deliberately
2253
- // leaves alone, and the key is the identity of one logical turn: the same value is replayed by the
2254
- // 404 recreate-and-resend and by the mid-stream refresh replay, so neither duplicates the user's
2255
- // message. It is SDK-minted (`defaultIdempotencyFactory`), never taken from partner code.
2256
- headers: { "Idempotency-Key": turn.idempotencyKey }
2257
- };
2258
- }
2259
- async tryForceRefresh() {
2260
- if (this.auth.mode !== "personalized") return false;
2261
- try {
2262
- await this.auth.identity.currentToken({ forceRefresh: true });
2263
- return true;
2264
- } catch {
2265
- return false;
2266
- }
2267
- }
2268
- authRejected() {
2269
- return makeError("authRejected", false);
2270
- }
2271
- };
2272
- var MESSAGE_MAX_CHARS = 4e3;
2273
- function validateMessageText(text) {
2274
- const raw = typeof text === "string" ? text : "";
2275
- if (raw.trim().length === 0) {
2276
- return { reason: "empty", error: makeError("validationFailed", false, "message is empty or whitespace-only") };
2277
- }
2278
- const codePoints = [...raw].length;
2279
- if (codePoints > MESSAGE_MAX_CHARS) {
2280
- return {
2281
- reason: "too_long",
2282
- error: makeError(
2283
- "validationFailed",
2284
- false,
2285
- `message is ${codePoints} characters; the server accepts at most ${MESSAGE_MAX_CHARS}`
2286
- )
2287
- };
2288
- }
2289
- return null;
2290
- }
2291
- async function* singleFrameStream(frame) {
2292
- yield frame;
2293
- }
2294
- async function* emptyStream() {
2295
- }
2296
-
2297
- // src/core/bootstrap.ts
2298
- async function bootstrapChat(input, deps) {
2299
- const { controller } = deps;
2300
- const petRef = input.petRef ?? null;
2301
- const resume = input.resumeConversationId ?? null;
2302
- const candidateConversationIds = [];
2303
- let sawForbidden = false;
2304
- let sawUnauthorized = false;
2305
- let sawConversationInitFailure = false;
2306
- let authBlock = null;
2307
- const conversationPromise = resume ? Promise.resolve(ok(resume)) : controller.createConversation(petRef ? { petRef } : void 0);
2308
- const promptsPromise = controller.getPrompts(petRef !== null ? { petRef } : void 0);
2309
- const [conversationRes, initialPromptsRes] = await Promise.all([conversationPromise, promptsPromise]);
2310
- let conversationId = null;
2311
- if (conversationRes.ok) {
2312
- conversationId = conversationRes.value;
2313
- candidateConversationIds.push(conversationRes.value);
2314
- controller.adoptConversation(conversationRes.value);
2315
- } else {
2316
- const e = conversationRes.error;
2317
- if (isUnauthorized(e)) {
2318
- sawUnauthorized = true;
2319
- authBlock = e;
2320
- } else if (isForbidden(e)) {
2321
- sawForbidden = true;
2322
- sawConversationInitFailure = true;
2323
- } else {
2324
- sawConversationInitFailure = true;
2325
- }
2326
- }
2327
- let suggestedPrompts = [];
2328
- if (initialPromptsRes.ok) {
2329
- suggestedPrompts = initialPromptsRes.value;
2330
- } else {
2331
- recordAuthSignals(initialPromptsRes.error);
2332
- }
2333
- function recordAuthSignals(e) {
2334
- if (isUnauthorized(e)) {
2335
- sawUnauthorized = true;
2336
- if (authBlock === null) authBlock = e;
2337
- } else if (isForbidden(e)) {
2338
- sawForbidden = true;
2339
- }
2340
- }
2341
- const error = authBlock !== null ? authBlock.displayMessage : null;
2342
- const warning = error === null && conversationId === null && sawConversationInitFailure ? CONVERSATION_NOT_PRIMED_WARNING : null;
2343
- return Object.freeze({
2344
- conversationId,
2345
- petRef,
2346
- suggestedPrompts,
2347
- error,
2348
- warning,
2349
- diagnostics: Object.freeze({
2350
- candidateConversationIds: Object.freeze([...candidateConversationIds]),
2351
- sawForbidden,
2352
- sawUnauthorized,
2353
- sawConversationInitFailure
2354
- })
2355
- });
2356
- }
2357
- var CONVERSATION_NOT_PRIMED_WARNING = "Chat is ready. Your first message will start the conversation.";
2358
- function isUnauthorized(e) {
2359
- return e.httpStatus === 401 || e.code === "authExpired" || e.code === "authRejected";
2360
- }
2361
- function isForbidden(e) {
2362
- return e.httpStatus === 403 || e.code === "accessDenied";
2363
- }
2364
-
2365
- // src/client/pets/petsRepository.ts
2366
- var PET_NAME_MAX = 100;
2367
- var PET_SPECIES_MAX = 50;
2368
- var PET_BREED_MAX = 100;
2369
- var PET_AGE_YEARS_MAX = 50;
2370
- var PET_WEIGHT_KG_MAX = 500;
2371
- var PET_REF_MAX = 128;
2372
- function invalid(wireMessage) {
2373
- return makeEverfurError("validationFailed", { retryable: false, wireMessage });
2374
- }
2375
- function checkString(field, value, max) {
2376
- if (typeof value !== "string") return invalid(`${field} must be a string`);
2377
- const length = serverLength(value);
2378
- if (length <= max) return null;
2379
- return invalid(`${field} is ${length} characters; the server accepts at most ${max}`);
2380
- }
2381
- function outOfRange(field, value, max) {
2382
- if (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max) return null;
2383
- return invalid(`${field} must be a finite number between 0 and ${max}`);
2384
- }
2385
- function validate(petRef, profile) {
2386
- if (typeof petRef !== "string") return invalid("pet_ref must be a string");
2387
- if (petRef.trim().length === 0) return invalid("pet_ref must not be blank");
2388
- if (hasLoneSurrogate(petRef)) return invalid("pet_ref contains an unpaired surrogate and cannot be encoded");
2389
- if (profile !== void 0 && profile !== null && typeof profile !== "object") {
2390
- return invalid("profile must be an object");
2391
- }
2392
- const checks = [checkString("pet_ref", petRef, PET_REF_MAX)];
2393
- if (profile?.name !== void 0) checks.push(checkString("name", profile.name, PET_NAME_MAX));
2394
- if (profile?.species !== void 0) checks.push(checkString("species", profile.species, PET_SPECIES_MAX));
2395
- if (profile?.breed !== void 0) checks.push(checkString("breed", profile.breed, PET_BREED_MAX));
2396
- if (profile?.ageYears !== void 0) checks.push(outOfRange("age_years", profile.ageYears, PET_AGE_YEARS_MAX));
2397
- if (profile?.weightKg !== void 0) checks.push(outOfRange("weight_kg", profile.weightKg, PET_WEIGHT_KG_MAX));
2398
- return checks.find((c) => c !== null) ?? null;
2399
- }
2400
- function toWire(profile) {
2401
- if (profile === void 0 || profile === null) return {};
2402
- return {
2403
- ...profile.name !== void 0 ? { name: profile.name } : {},
2404
- ...profile.species !== void 0 ? { species: profile.species } : {},
2405
- ...profile.breed !== void 0 ? { breed: profile.breed } : {},
2406
- ...profile.ageYears !== void 0 ? { age_years: profile.ageYears } : {},
2407
- ...profile.weightKg !== void 0 ? { weight_kg: profile.weightKg } : {}
2408
- };
2409
- }
2410
- function fromWire2(raw, petRef) {
2411
- const o = typeof raw === "object" && raw !== null ? raw : {};
2412
- const str = (v) => typeof v === "string" ? v : null;
2413
- const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
2414
- return Object.freeze({
2415
- petRef: str(o["pet_ref"]) ?? petRef,
2416
- name: str(o["name"]),
2417
- species: str(o["species"]),
2418
- breed: str(o["breed"]),
2419
- ageYears: num(o["age_years"]),
2420
- weightKg: num(o["weight_kg"])
2421
- });
2422
- }
2423
- function createPetsRepository(auth) {
2424
- return createPetsRepositoryOver(createRequestFunnel({ auth }));
2425
- }
2426
- function createPetsRepositoryOver(funnel) {
2427
- return {
2428
- async registerPet(petRef, profile, opts) {
2429
- const invalid2 = validate(petRef, profile);
2430
- if (invalid2 !== null) return err(invalid2);
2431
- const path = `/widget/v1/pets/${encodeURIComponent(petRef)}`;
2432
- const base = { method: "POST", path, body: toWire(profile) };
2433
- const res = await funnel.send(
2434
- "pets.registerPet",
2435
- opts?.signal ? { ...base, signal: opts.signal } : base
2436
- );
2437
- if (!res.ok) return err(res.error);
2438
- return ok(fromWire2(res.value, petRef));
2439
- }
2440
- };
2441
- }
2442
-
2443
- // src/client/entitlements/resolve.ts
2444
- var REQUIRES = Object.freeze({
2445
- chat: Object.freeze(["chat.message.create"]),
2446
- records: Object.freeze(["records.upload.create", "records.record.read"]),
2447
- video: Object.freeze(["video.gait.execute"]),
2448
- photo: Object.freeze(["photo.checkup.execute"]),
2449
- animations: Object.freeze(["animations.state.read"])
2450
- });
2451
- function deniedDecisionsFor(level, reason) {
2452
- const disabled = Object.freeze({ reason, level, recoverable: false });
2453
- const rows = [];
2454
- const seen = /* @__PURE__ */ new Set();
2455
- for (const name of Object.keys(REQUIRES)) {
2456
- for (const resource of REQUIRES[name]) {
2457
- if (seen.has(resource)) continue;
2458
- seen.add(resource);
2459
- rows.push(Object.freeze({ resource, granted: false, disabled }));
2460
- }
2461
- }
2462
- return Object.freeze(rows);
2463
- }
2464
-
2465
- // src/client/theme/resolve.ts
2466
- function isEmptyBranding(b) {
2467
- return b.displayName === null && b.logoUrl === null && b.primaryColor === null && b.accentColor === null && b.brightness === null && b.fontFamily === null && b.fontUrl === null && b.placeholder === null && b.hidePoweredBy === null;
2468
- }
2469
- function parseClientBranding(json) {
2470
- if (json === null || typeof json !== "object") return null;
2471
- const raw = json;
2472
- const branding = {
2473
- displayName: parseNonEmptyString(pick(raw, "display_name", "displayName")),
2474
- logoUrl: parseNonEmptyString(pick(raw, "logo_url", "logoUrl")),
2475
- primaryColor: parseColor(pick(raw, "primary_color", "primaryColor")),
2476
- accentColor: parseColor(pick(raw, "accent_color", "accentColor")),
2477
- brightness: parseBrightness(pick(raw, "brightness")),
2478
- fontFamily: parseNonEmptyString(pick(raw, "font_family", "fontFamily")),
2479
- fontUrl: parseNonEmptyString(pick(raw, "font_url", "fontUrl")),
2480
- placeholder: parseNonEmptyString(pick(raw, "chat_placeholder", "placeholder", "chatPlaceholder")),
2481
- hidePoweredBy: parseBool(pick(raw, "hide_powered_by", "hidePoweredBy"))
2482
- };
2483
- return isEmptyBranding(branding) ? null : Object.freeze(branding);
2484
- }
2485
- function parseBool(value) {
2486
- if (typeof value === "boolean") return value;
2487
- if (typeof value === "string") {
2488
- const lower = value.trim().toLowerCase();
2489
- if (lower === "true") return true;
2490
- if (lower === "false") return false;
2491
- }
2492
- return null;
2493
- }
2494
- function pick(raw, ...keys) {
2495
- for (const key of keys) {
2496
- if (Object.prototype.hasOwnProperty.call(raw, key)) {
2497
- const value = raw[key];
2498
- if (value !== void 0) return value;
2499
- }
2500
- }
2501
- return void 0;
2502
- }
2503
- function parseNonEmptyString(value) {
2504
- if (typeof value !== "string") return null;
2505
- const trimmed = value.trim();
2506
- return trimmed.length === 0 ? null : trimmed;
2507
- }
2508
- function parseBrightness(value) {
2509
- if (typeof value !== "string") return null;
2510
- const lower = value.trim().toLowerCase();
2511
- return lower === "light" || lower === "dark" ? lower : null;
2512
- }
2513
- function parseColor(value) {
2514
- const rgba = toRgba(value);
2515
- return rgba === null ? null : normalizeRgba(rgba);
2516
- }
2517
- function toRgba(value) {
2518
- if (typeof value === "number") return argbIntToRgba(value);
2519
- if (typeof value !== "string") return null;
2520
- const s = value.trim();
2521
- if (s.length === 0) return null;
2522
- if (s.startsWith("#")) return fromHex(s.slice(1));
2523
- if (s.toLowerCase().startsWith("0x")) return fromArgbHex(s.slice(2));
2524
- if (s.toLowerCase().startsWith("rgb")) return fromRgbFunc(s);
2525
- if (/^[0-9a-fA-F]+$/.test(s)) {
2526
- const hex = fromHex(s);
2527
- if (hex !== null) return hex;
2528
- }
2529
- if (/^\d+$/.test(s)) return argbIntToRgba(Number.parseInt(s, 10));
2530
- return null;
2531
- }
2532
- function fromHex(hex) {
2533
- const h = hex.trim();
2534
- if (!/^[0-9a-fA-F]+$/.test(h)) return null;
2535
- if (h.length === 3) {
2536
- const r = dup(h[0]);
2537
- const g = dup(h[1]);
2538
- const b = dup(h[2]);
2539
- return { r, g, b, a: 1 };
2540
- }
2541
- if (h.length === 6) {
2542
- return { r: byte(h, 0), g: byte(h, 2), b: byte(h, 4), a: 1 };
2543
- }
2544
- if (h.length === 8) {
2545
- const a = byte(h, 0);
2546
- return { r: byte(h, 2), g: byte(h, 4), b: byte(h, 6), a: a / 255 };
2547
- }
2548
- return null;
2549
- }
2550
- function fromArgbHex(hex) {
2551
- return fromHex(hex);
2552
- }
2553
- function fromRgbFunc(input) {
2554
- const open = input.indexOf("(");
2555
- const close = input.indexOf(")");
2556
- if (open < 0 || close < 0 || close < open) return null;
2557
- const parts = input.slice(open + 1, close).split(",").map((p) => p.trim());
2558
- if (parts.length < 3) return null;
2559
- const r = clampByte(Number(parts[0]));
2560
- const g = clampByte(Number(parts[1]));
2561
- const b = clampByte(Number(parts[2]));
2562
- if (r === null || g === null || b === null) return null;
2563
- let a = 1;
2564
- if (parts.length >= 4) {
2565
- const alpha = Number(parts[3]);
2566
- if (!Number.isFinite(alpha)) return null;
2567
- a = Math.min(1, Math.max(0, alpha));
2568
- }
2569
- return { r, g, b, a };
2570
- }
2571
- function argbIntToRgba(n) {
2572
- if (!Number.isFinite(n)) return null;
2573
- const int = Math.trunc(n) >>> 0;
2574
- const a = int >>> 24 & 255;
2575
- return {
2576
- r: int >>> 16 & 255,
2577
- g: int >>> 8 & 255,
2578
- b: int & 255,
2579
- // A 0x00RRGGBB with no alpha byte reads as fully transparent; treat a zero alpha byte as opaque so a
2580
- // bare 0xRRGGBB (or small decimal) is not silently invisible.
2581
- a: a === 0 ? 1 : a / 255
2582
- };
2583
- }
2584
- function byte(hex, at) {
2585
- return Number.parseInt(hex.slice(at, at + 2), 16);
2586
- }
2587
- function dup(nibble) {
2588
- return Number.parseInt(`${nibble ?? "0"}${nibble ?? "0"}`, 16);
2589
- }
2590
- function clampByte(n) {
2591
- if (!Number.isFinite(n)) return null;
2592
- return Math.min(255, Math.max(0, Math.round(n)));
2593
- }
2594
- function normalizeRgba(rgba) {
2595
- if (rgba.a >= 1) {
2596
- return `#${hex2(rgba.r)}${hex2(rgba.g)}${hex2(rgba.b)}`.toUpperCase();
2597
- }
2598
- const a = Math.round(rgba.a * 1e3) / 1e3;
2599
- return `rgba(${rgba.r},${rgba.g},${rgba.b},${a})`;
2600
- }
2601
- function hex2(n) {
2602
- return n.toString(16).padStart(2, "0");
2603
- }
2604
-
2605
- // src/client/entitlements/entitlementRepository.ts
2606
- var ENTITLEMENTS_PATH = "/widget/v1/entitlements";
2607
- var HTTP_NOT_MODIFIED = 304;
2608
- var NOT_MODIFIED = Object.freeze({ kind: "notModified" });
2609
- async function fetchEntitlements(auth, args = {}, funnel = createRequestFunnel({ auth })) {
2610
- const result = await funnel.send(
2611
- "entitlements.fetch",
2612
- buildRequest(args)
2613
- );
2614
- if (!result.ok) {
2615
- if (result.error.httpStatus === HTTP_NOT_MODIFIED) return NOT_MODIFIED;
2616
- return { kind: "failed", error: result.error };
2617
- }
2618
- return parseUpdated(result.value);
2619
- }
2620
- var REGION_MAX = 64;
2621
- function buildRequest(args) {
2622
- const headers = {};
2623
- if (isFiniteNumber(args.cachedRevision)) {
2624
- headers["if-none-match"] = `"${args.cachedRevision}"`;
2625
- }
2626
- if (args.region && args.region.length <= REGION_MAX) {
2627
- return { method: "GET", path: ENTITLEMENTS_PATH, headers, query: { region: args.region } };
2628
- }
2629
- return { method: "GET", path: ENTITLEMENTS_PATH, headers };
2630
- }
2631
- function parseUpdated(body) {
2632
- if (body === null || typeof body !== "object") return malformed();
2633
- if (!isFiniteNumber(body.revision)) return malformed();
2634
- const region = typeof body.region === "string" ? body.region : "";
2635
- const ttlSeconds = isFiniteNumber(body.ttl_seconds) ? body.ttl_seconds : 0;
2636
- return Object.freeze({
2637
- kind: "updated",
2638
- revision: body.revision,
2639
- region,
2640
- ttlSeconds,
2641
- decisions: mapCapabilities(body.capabilities),
2642
- // Branding is ADDITIVE and orthogonal to capabilities: a parse fault here NEVER affects the decisions and
2643
- // fails closed to null (the compiled default theme). It cannot make a granted capability un-render.
2644
- branding: parseBranding(body)
2645
- });
2646
- }
2647
- function parseBranding(body) {
2648
- const direct = parseClientBranding(body.branding);
2649
- if (direct !== null) return direct;
2650
- const hints = body.render_hints;
2651
- if (hints !== null && typeof hints === "object") {
2652
- const nested = parseClientBranding(hints.branding);
2653
- if (nested !== null) return nested;
2654
- return parseClientBranding(hints);
2655
- }
2656
- return null;
2657
- }
2658
- function mapCapabilities(capabilities) {
2659
- if (capabilities === null || typeof capabilities !== "object") return Object.freeze([]);
2660
- const out = [];
2661
- for (const [resource, value] of Object.entries(capabilities)) {
2662
- if (isEnabled(value)) out.push(Object.freeze({ resource, granted: true }));
2663
- }
2664
- return Object.freeze(out);
2665
- }
2666
- function isEnabled(value) {
2667
- return typeof value === "object" && value !== null && value.enabled === true;
2668
- }
2669
- function malformed() {
2670
- return {
2671
- kind: "failed",
2672
- error: makeEverfurError("internalError", {
2673
- retryable: true,
2674
- wireMessage: "malformed entitlements response"
2675
- })
2676
- };
2677
- }
2678
- function isFiniteNumber(value) {
2679
- return typeof value === "number" && Number.isFinite(value);
2680
- }
2681
-
2682
- // src/core/entitlements/entitlementPoller.ts
2683
- var MIN_POLL_INTERVAL_SECONDS = 30;
2684
- function createEntitlementPoller(deps) {
2685
- const scheduler = deps.scheduler ?? defaultScheduler;
2686
- const resolve = deps.resolve ?? fetchEntitlements;
2687
- const floorSeconds = Math.max(1, deps.floorSeconds ?? MIN_POLL_INTERVAL_SECONDS);
2688
- const rng = deps.rng ?? Math.random;
2689
- const jitteredFloorSeconds = () => floorSeconds + rng() * floorSeconds;
2690
- let started = false;
2691
- let stopped = false;
2692
- let timer = null;
2693
- let cachedRevision = null;
2694
- let lastCadenceSeconds = floorSeconds;
2695
- let generation = 0;
2696
- const clearTimer = () => {
2697
- if (timer !== null) {
2698
- scheduler.clear(timer);
2699
- timer = null;
2700
- }
2701
- };
2702
- const schedule = (seconds) => {
2703
- if (stopped) return;
2704
- lastCadenceSeconds = Math.max(floorSeconds, seconds);
2705
- timer = scheduler.set(() => {
2706
- timer = null;
2707
- void tick();
2708
- }, lastCadenceSeconds * 1e3);
2709
- };
2710
- const tick = async () => {
2711
- if (stopped) return;
2712
- const myGen = generation;
2713
- const args = deps.region ? { cachedRevision, region: deps.region } : { cachedRevision };
2714
- let resolution;
2715
- try {
2716
- resolution = await resolve(deps.authFor(), args);
2717
- } catch (cause) {
2718
- deps.telemetry?.track("sdk.entitlements.poll_error", { reason: describe2(cause) });
2719
- if (!stopped && myGen === generation) schedule(jitteredFloorSeconds());
2720
- return;
2721
- }
2722
- if (stopped || myGen !== generation) return;
2723
- switch (resolution.kind) {
2724
- case "updated":
2725
- cachedRevision = resolution.revision;
2726
- deps.update(resolution.decisions, resolution.branding ?? null);
2727
- schedule(resolution.ttlSeconds);
2728
- return;
2729
- case "notModified":
2730
- schedule(lastCadenceSeconds);
2731
- return;
2732
- case "failed":
2733
- deps.telemetry?.track("sdk.entitlements.poll_failed", { code: resolution.error.code });
2734
- schedule(jitteredFloorSeconds());
2735
- return;
2736
- default:
2737
- schedule(jitteredFloorSeconds());
2738
- }
2739
- };
2740
- return {
2741
- start() {
2742
- if (started || stopped) return;
2743
- started = true;
2744
- void tick();
2745
- },
2746
- stop() {
2747
- if (stopped) return;
2748
- stopped = true;
2749
- generation++;
2750
- clearTimer();
2751
- },
2752
- refresh() {
2753
- if (stopped || !started) return;
2754
- generation++;
2755
- cachedRevision = null;
2756
- clearTimer();
2757
- void tick();
2758
- }
2759
- };
2760
- }
2761
- var defaultScheduler = {
2762
- set(callback, ms) {
2763
- const handle = setTimeout(callback, ms);
2764
- handle.unref?.();
2765
- return handle;
2766
- },
2767
- clear(handle) {
2768
- clearTimeout(handle);
2769
- }
2770
- };
2771
- function describe2(cause) {
2772
- return cause instanceof Error ? cause.message : "poll failed";
2773
- }
2774
-
2775
- // src/core/runtime.ts
2776
- function compiledDefaultDecisions() {
2777
- return Object.freeze([Object.freeze({ resource: "chat.message.create", granted: true })]);
2778
- }
2779
- function createEntitlementStore(floorDecisions = compiledDefaultDecisions) {
2780
- const listeners = /* @__PURE__ */ new Set();
2781
- let snapshot = Object.freeze({
2782
- decisions: floorDecisions(),
2783
- isPending: false,
2784
- branding: null
2785
- });
2786
- const emit = () => {
2787
- for (const listener of listeners) listener();
2788
- };
2789
- return {
2790
- subscribe(listener) {
2791
- listeners.add(listener);
2792
- return () => {
2793
- listeners.delete(listener);
2794
- };
2795
- },
2796
- getSnapshot() {
2797
- return snapshot;
2798
- },
2799
- set(next) {
2800
- snapshot = Object.freeze({
2801
- decisions: Object.freeze([...next.decisions]),
2802
- isPending: next.isPending,
2803
- // Branding is additive; default to null (the compiled Everfur theme) when a caller omits it.
2804
- branding: next.branding ?? null
2805
- });
2806
- emit();
2807
- },
2808
- reset() {
2809
- snapshot = Object.freeze({
2810
- decisions: floorDecisions(),
2811
- isPending: false,
2812
- branding: null
2813
- });
2814
- emit();
2815
- }
2816
- };
2817
- }
2818
- function createEverfurRuntime(input, opts) {
2819
- return new EverfurRuntimeImpl(input, opts);
2820
- }
2821
- var PER_USER_KV_KEYS = Object.freeze([]);
2822
- var EverfurRuntimeImpl = class {
2823
- constructor(input, opts) {
2824
- /**
2825
- * One `x-everfur-session-id` for the life of this runtime. It MUST be stable across requests: the server
2826
- * derives the anonymous identity from it, so a per-request value makes every call a different user and the
2827
- * create/send pair can never agree. Minted here, never persisted, never a credential.
2828
- */
2829
- /**
2830
- * Rotated on sign-out. The server derives the ANONYMOUS identity from this
2831
- * (`user_ref = f"anon-{session_id}"`), so keeping it across a logout would leave the next anonymous
2832
- * session inheriting the previous user's server-side conversation history.
2833
- */
2834
- this.sessionId = newSessionId();
2835
- // ONE ref-counted controller table keyed by `${epoch}|${kind}|${scopeKey}`, plus each controller's
2836
- // destroyer, so a re-scope / dispose can tear every open controller down without naming its type.
2837
- this.entries = /* @__PURE__ */ new Map();
2838
- this.destroyers = /* @__PURE__ */ new Map();
2839
- this.epoch = 0;
2840
- this.disposed = false;
2841
- const cfg = input.config;
2842
- if (cfg.secureStore !== void 0 && cfg.secureStore.isAvailable === true) {
2843
- throw new EverfurConfigError(
2844
- "invalid-argument",
2845
- "config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3)."
2846
- );
2847
- }
2848
- this.telemetry = cfg.telemetry ?? noopTelemetry;
2849
- const publishableKey = typeof cfg?.publishableKey === "string" ? cfg.publishableKey.trim() : "";
2850
- let failure = checkPublishableKey(cfg?.publishableKey);
2851
- const transportInjected = cfg.transport !== void 0;
2852
- let resolvedTransport;
2853
- if (failure !== null) {
2854
- resolvedTransport = refusingTransport(failure);
2855
- } else if (cfg.transport !== void 0) {
2856
- resolvedTransport = cfg.transport;
2857
- } else {
2858
- const resolved = tryResolveClient(cfg);
2859
- if (resolved.ok) {
2860
- resolvedTransport = createHttpTransport({
2861
- config: resolved.config,
2862
- ...opts?.eventSourceFactory ? { eventSourceFactory: opts.eventSourceFactory } : {}
2863
- });
2864
- } else {
2865
- failure = resolved.failure;
2866
- resolvedTransport = refusingTransport(resolved.failure);
2867
- }
2868
- }
2869
- this.configFailure = failure;
2870
- this.publishableKey = failure === null ? publishableKey : "";
2871
- this.transport = resolvedTransport;
2872
- if (failure !== null) {
2873
- reportConfigFailure(failure, this.telemetry);
2874
- }
2875
- this.errorPolicy = cfg.errorPolicy;
2876
- this.camera = cfg.camera ?? unavailableCamera;
2877
- this.upload = cfg.upload ?? unavailableUpload;
2878
- this.uploadTransport = cfg.uploadTransport ?? unavailableUploadTransport;
2879
- this.imageCache = cfg.imageCache ?? noopImageCache;
2880
- this.kv = cfg.storage ?? createInMemoryKv();
2881
- this.currentUser = input.user ?? null;
2882
- this.identity = input.user ? createIdentityProvider(input.user.userRef, input.user.getToken) : null;
2883
- this.activePet = input.activePet;
2884
- this.store = failure === null ? createEntitlementStore() : createEntitlementStore(() => deniedDecisionsFor("sdk_config", userFacingError("accessDenied")));
2885
- this.services = {
2886
- authFor: (userRef) => this.buildAuth(userRef),
2887
- telemetry: this.telemetry,
2888
- errorPolicy: this.errorPolicy,
2889
- camera: this.camera,
2890
- upload: this.upload,
2891
- uploadTransport: this.uploadTransport,
2892
- imageCache: this.imageCache,
2893
- kv: this.kv
2894
- };
2895
- this.registry = {
2896
- services: this.services,
2897
- acquireChat: (scope) => this.acquireInternal(
2898
- "chat",
2899
- `${scope.userRef ?? ""}|${scope.petRef ?? ""}|${scope.conversationId ?? ""}`,
2900
- () => this.buildChatController(scope),
2901
- (controller) => controller.dispose()
2902
- ),
2903
- releaseChat: (controller) => this.releaseInternal(controller),
2904
- acquire: (kind, scopeKey, create, destroy) => this.acquireInternal(kind, scopeKey, create, destroy),
2905
- release: (controller) => this.releaseInternal(controller)
2906
- };
2907
- this.entitlements = this.store;
2908
- const shouldPoll = failure === null && (opts?.startEntitlementPolling ?? !transportInjected);
2909
- this.poller = shouldPoll ? this.buildPoller(opts?.pollScheduler) : null;
2910
- this.poller?.start();
2911
- }
2912
- get isDisposed() {
2913
- return this.disposed;
2914
- }
2915
- get scopeEpoch() {
2916
- return this.epoch;
2917
- }
2918
- /**
2919
- * Build the entitlement poller. `authFor` re-derives the device AuthContext each poll (so a token refresh /
2920
- * re-scope is reflected), and `update` feeds the resolved decisions into the render store. The SERVER stays
2921
- * authoritative; this only populates what the SDK renders.
2922
- */
2923
- buildPoller(scheduler) {
2924
- return createEntitlementPoller({
2925
- authFor: () => this.buildAuth(this.currentUser?.userRef ?? null),
2926
- update: (decisions, branding) => this.updateEntitlements({ decisions, isPending: false, branding }),
2927
- telemetry: this.telemetry,
2928
- ...scheduler ? { scheduler } : {}
2929
- });
2930
- }
2931
- // ---- ref-counted acquire / release (epoch-keyed) -----------------------
2932
- acquireInternal(kind, scopeKey, create, destroy) {
2933
- const key = `${this.epoch}|${kind}|${scopeKey}`;
2934
- const existing = this.entries.get(key);
2935
- if (existing) {
2936
- existing.refCount += 1;
2937
- return existing.controller;
2938
- }
2939
- const controller = create();
2940
- this.entries.set(key, { controller, refCount: 1 });
2941
- this.destroyers.set(controller, destroy);
2942
- return controller;
2943
- }
2944
- releaseInternal(controller) {
2945
- for (const [key, entry] of this.entries) {
2946
- if (entry.controller !== controller) continue;
2947
- entry.refCount -= 1;
2948
- if (entry.refCount <= 0) {
2949
- this.runDestroyer(controller);
2950
- this.entries.delete(key);
2951
- }
2952
- return;
2953
- }
2954
- }
2955
- runDestroyer(controller) {
2956
- const destroy = this.destroyers.get(controller);
2957
- this.destroyers.delete(controller);
2958
- if (destroy) destroy(controller);
2959
- }
2960
- // ---- controller construction (only the spine capability is built here) -
2961
- buildChatController(scope) {
2962
- const controller = createChatController({
2963
- auth: this.buildAuth(scope.userRef),
2964
- telemetry: this.telemetry,
2965
- ...this.errorPolicy ? { errorPolicy: this.errorPolicy } : {},
2966
- initialConversationId: scope.conversationId
2967
- });
2968
- const input = {};
2969
- if (scope.petRef !== null) input.petRef = scope.petRef;
2970
- if (scope.conversationId !== null) input.resumeConversationId = scope.conversationId;
2971
- void bootstrapChat(input, { controller }).then((result) => controller.adoptPrompts(result.suggestedPrompts)).catch(() => {
2972
- });
2973
- return controller;
2974
- }
2975
- buildAuth(scopeUserRef) {
2976
- if (this.identity !== null && this.currentUser !== null) {
2977
- return {
2978
- mode: "personalized",
2979
- transport: this.transport,
2980
- identity: this.identity,
2981
- userRef: this.currentUser.userRef,
2982
- sessionId: this.sessionId
2983
- };
2984
- }
2985
- return {
2986
- mode: "anonymous",
2987
- transport: this.transport,
2988
- publishableKey: this.publishableKey,
2989
- // Only name a user while one is actually signed in. `scopeUserRef` is the REGISTRY scope key,
2990
- // taken from the host's `user` prop, which a `logout()` call does not touch — so carrying it here
2991
- // meant that after sign-out the SDK kept sending `x-everfur-user-ref` for the signed-out user
2992
- // alongside the publishable key, and the widget plane resolves identity from exactly that pair.
2993
- userRef: this.currentUser === null ? null : scopeUserRef,
2994
- sessionId: this.sessionId
2995
- };
2996
- }
2997
- // ---- imperative verbs (re-scope in one commit; SPEC-10 §3) -------------
2998
- setUser(user) {
2999
- if (this.disposed) return;
3000
- const nextRef = user?.userRef ?? null;
3001
- const currentRef = this.currentUser?.userRef ?? null;
3002
- if (nextRef === currentRef) {
3003
- this.currentUser = user;
3004
- if (user && this.identity === null) {
3005
- this.identity = createIdentityProvider(user.userRef, user.getToken);
3006
- }
3007
- return;
3008
- }
3009
- this.identity?.clear();
3010
- this.currentUser = user;
3011
- this.identity = user ? createIdentityProvider(user.userRef, user.getToken) : null;
3012
- this.rescopeAll();
3013
- }
3014
- async logout() {
3015
- if (this.disposed) return;
3016
- const wasAnonymous = this.currentUser === null;
3017
- this.sessionId = newSessionId();
3018
- this.setUser(null);
3019
- if (wasAnonymous) this.rescopeAll();
3020
- await this.sweepPerUserKv();
3021
- }
3022
- async sweepPerUserKv() {
3023
- if (PER_USER_KV_KEYS.length === 0) return;
3024
- const results = await Promise.allSettled(
3025
- PER_USER_KV_KEYS.map((key) => this.kv.removeItem(key))
3026
- );
3027
- const failedCount = results.filter((result) => result.status === "rejected").length;
3028
- if (failedCount > 0) {
3029
- this.telemetry.track("sdk.logout.sweepPartialFailure", {
3030
- failedCount,
3031
- totalCount: results.length
3032
- });
3033
- }
3034
- }
3035
- async registerPet(pet, profile) {
3036
- if (this.disposed) {
3037
- return err(
3038
- makeEverfurError("validationFailed", {
3039
- retryable: false,
3040
- wireMessage: "the Everfur runtime is disposed; registerPet was called after unmount"
3041
- })
3042
- );
3043
- }
3044
- const repo = createPetsRepository(this.buildAuth(this.currentUser?.userRef ?? null));
3045
- return profile === void 0 ? repo.registerPet(pet) : repo.registerPet(pet, profile);
3046
- }
3047
- setActivePet(pet) {
3048
- if (this.disposed) return;
3049
- const next = pet ?? null;
3050
- if (next === this.activePet) return;
3051
- this.activePet = next;
3052
- this.rescopeAll();
3053
- }
3054
- updateEntitlements(next) {
3055
- if (this.disposed) return;
3056
- if (this.configFailure !== null) return;
3057
- this.store.set(next);
3058
- }
3059
- open(capability) {
3060
- this.telemetry.track("sdk.open", { capability });
3061
- }
3062
- dispose() {
3063
- if (this.disposed) return;
3064
- this.disposed = true;
3065
- this.epoch += 1;
3066
- this.poller?.stop();
3067
- this.identity?.clear();
3068
- this.disposeAllControllers();
3069
- }
3070
- rescopeAll() {
3071
- this.epoch += 1;
3072
- this.disposeAllControllers();
3073
- this.store.reset();
3074
- this.poller?.refresh();
3075
- }
3076
- disposeAllControllers() {
3077
- for (const entry of this.entries.values()) this.runDestroyer(entry.controller);
3078
- this.entries.clear();
3079
- this.destroyers.clear();
3080
- }
3081
- };
3082
- function tryResolveClient(cfg) {
3083
- const clientCfg = {
3084
- publishableKey: cfg.publishableKey,
3085
- ...cfg.apiBaseUrl !== void 0 ? { apiBaseUrl: cfg.apiBaseUrl } : {},
3086
- ...cfg.contractVersion !== void 0 ? { contractVersion: cfg.contractVersion } : {},
3087
- ...cfg.debug !== void 0 ? { debug: cfg.debug } : {}
3088
- };
3089
- return tryResolveClientConfig(clientCfg);
3090
- }
3091
- function reportConfigFailure(failure, telemetry) {
3092
- try {
3093
- telemetry.trackExpectedFailure("sdk.config.invalid", { reason: failure.reason });
3094
- } catch {
3095
- }
3096
- const globalConsole = globalThis.console;
3097
- globalConsole?.error?.(
3098
- `[everfur] SDK disabled: ${failure.message}
3099
- [everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`
3100
- );
3101
- }
3102
- function refusingTransport(failure) {
3103
- const build = () => (
3104
- // NOT `internalError`: the funnel's `decideRetry` keys on `isAutoRetryable(code)` and deliberately
3105
- // ignores `error.retryable`, so `internalError` would be retried with backoff on every call even though
3106
- // it can never succeed; and `categoryFor('internalError')` is `server`, i.e. "the server admits fault",
3107
- // which would blame Everfur's backend for the partner's own config defect on their dashboards. The
3108
- // whole point of the `sdk_config` level is to attribute this correctly. `validationFailed` is terminal
3109
- // (`invalidRequest`: "retrying it unchanged can never succeed"), which is exactly true here.
3110
- makeEverfurError("validationFailed", {
3111
- retryable: false,
3112
- // Developer-facing only: `wireMessage` is NON-ENUMERABLE and never rendered (EverfurError.ts).
3113
- wireMessage: `Everfur SDK is not configured: ${failure.message}`
3114
- })
3115
- );
3116
- return Object.freeze({
3117
- request() {
3118
- return Promise.resolve(err(build()));
3119
- },
3120
- stream(_req, signal) {
3121
- const frame = errorFrame({
3122
- code: "sdk_not_configured",
3123
- retryable: false,
3124
- wireMessage: `Everfur SDK is not configured: ${failure.message}`,
3125
- synthesized: true,
3126
- lastEventId: null
3127
- });
3128
- return {
3129
- async *[Symbol.asyncIterator]() {
3130
- if (signal.aborted) return;
3131
- yield frame;
3132
- }
3133
- };
3134
- }
3135
- });
3136
- }
3137
- function createInMemoryKv() {
3138
- const map = /* @__PURE__ */ new Map();
3139
- return {
3140
- async getItem(key) {
3141
- return map.get(key) ?? null;
3142
- },
3143
- async setItem(key, value) {
3144
- map.set(key, value);
3145
- },
3146
- async removeItem(key) {
3147
- map.delete(key);
3148
- },
3149
- async keys(prefix) {
3150
- return [...map.keys()].filter((k) => k.startsWith(prefix));
3151
- }
3152
- };
3153
- }
3154
- var unavailableUploadTransport = Object.freeze({
3155
- postMultipart() {
3156
- return Promise.reject(
3157
- new Error("UploadTransport is unavailable; no records upload adapter was injected")
3158
- );
3159
- }
3160
- });
3161
- var noopImageCache = Object.freeze({
3162
- clearMemoryCache() {
3163
- },
3164
- clearDiskCache() {
3165
- }
3166
- });
3167
-
3168
- exports.MESSAGE_MAX_CHARS = MESSAGE_MAX_CHARS;
3169
- exports.MIN_POLL_INTERVAL_SECONDS = MIN_POLL_INTERVAL_SECONDS;
3170
- exports.NULL_SECURE_STORE = NULL_SECURE_STORE;
3171
- exports.bootstrapChat = bootstrapChat;
3172
- exports.createChatController = createChatController;
3173
- exports.createEntitlementPoller = createEntitlementPoller;
3174
- exports.createEverfurRuntime = createEverfurRuntime;
3175
- exports.defaultErrorPolicy = defaultErrorPolicy;
3176
- exports.noopTelemetry = noopTelemetry;
3177
- exports.optionalModule = optionalModule;
3178
- exports.unavailableCamera = unavailableCamera;
1
+ 'use strict';var zod=require('zod');var si=Object.defineProperty;var i=(e,t)=>si(e,"name",{value:t,configurable:true});function _(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(_,"ok");function p(e){return Object.freeze({ok:false,error:e})}i(p,"err");var Fe=class Fe extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Fe.prototype);}};i(Fe,"EverfurConfigError");var K=Fe;var iu=Object.freeze({isAvailable:false,async getSecret(){return null},async setSecret(){throw new K("not-initialized","EF_NO_SECURE_STORE: token persistence requires an explicit SecureStorePort")},async deleteSecret(){}});var Me=Object.freeze({track(){},trackExpectedFailure(){}});var tt=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(tt.map(e=>e.wireCode));var ai=Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),dr=Object.freeze(tt.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:ai[e.wireCode]}))),li=new Map(dr.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),ui=Object.freeze(["http_envelope",...[...new Set(dr.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function De(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...ui]){let o=li.get(n+r);if(o)return o}}i(De,"contractErrorFor");function di(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(di,"contractDocUrl");function cr(e){return null}i(cr,"publishedDocUrl");var ci=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function pr(e){return ci[e]}i(pr,"categoryFor");function Y(e){let t=De(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(n){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Y,"fromWire");function fr(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(fr,"fromHttpStatus");var pi=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function ee(e){return pi.has(e)}i(ee,"isAutoRetryable");var fi=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function mr(e){return ee(e)||fi.has(e)}i(mr,"isRetryableCode");function je(e,t=false){return t||ee(e)}i(je,"shouldRetry");var mi=500,rt=8e3,pe=4;function ze(e,t=Math.random){let r=Math.max(0,e),n=Math.min(mi*2**r,rt);return Math.floor(t()*n)}i(ze,"backoffDelayMs");function yr(e){return e==="conversationNotFound"}i(yr,"canRecreateOnNotFound");var gr=Object.freeze({shouldRetry(e,t){return ee(e)&&t<pe},maxAttempts(){return pe}});var hr=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Eu(e,t,r){let n;try{n=t();}catch(s){return nt(`optional peer '${e}' is not installed: ${gi(s)}`)}let o=yi(n);return o==null?nt(`optional peer '${e}' resolved to no module`):r&&!r(o)?nt(`optional peer '${e}' is present but failed its shape check`):Object.freeze({available:true,module:o})}i(Eu,"optionalModule");function yi(e){return typeof e=="object"&&e!==null&&"default"in e&&Object.keys(e).length<=2?e.default:e}i(yi,"unwrapDefault");function nt(e){return Object.freeze({available:false,module:null,reason:e})}i(nt,"frozenUnavailable");function gi(e){return e instanceof Error?e.message:typeof e=="string"?e:"unknown load error"}i(gi,"describe");function Le(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Le,"assertNever");function br(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(br,"acceptedFrame");function vr(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(vr,"heartbeatFrame");function _r(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(_r,"deltaFrame");function Rr(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(Rr,"doneFrame");function N(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(N,"errorFrame");function Er(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Er,"analysisStartedFrame");function Cr(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(Cr,"analysisCompleteFrame");function Sr(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Sr,"unknownFrame");var vi=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function ot(e){return vi[e]}i(ot,"userFacingError");function wr(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(wr,"defineHidden");var _i=/^[a-z][a-z0-9_]{0,63}$/;function S(e,t){let r=De(t?.wireCode,t?.wireEnvelope),n={code:e,category:pr(e),retryable:t?.retryable??mr(e),displayMessage:ot(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&_i.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&wr(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&wr(n,"raw",t.raw),Object.freeze(n)}i(S,"makeEverfurError");function kr(e,t,r){let n=null,o=null,s=false,l=i(()=>o||(o=(async()=>{try{let u=await t(),a=typeof u=="string"?u:u?.token;if(typeof a!="string"||a.length===0)throw new K("invalid-argument","TokenProvider returned an empty token");return n=a,r?.(typeof u=="string"?null:Ri(u.expiresAt)),a}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(u){if(s)throw new K("not-initialized","This identity was cleared (sign-out); mint a new one.");return u?.forceRefresh&&(n=null),n!==null?n:l()},hasToken(){return !s&&n!==null},clear(){s=true,n=null;}}}i(kr,"createIdentityProvider");function Ri(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(Ri,"expiryMs");function st(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(st,"newSessionId");function Ei(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(Ei,"authHeaders");function fe(e,t){return {...e,headers:{...Ci(e.headers),...Ei(t)}}}i(fe,"withAuthHeaders");function Ci(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i(Ci,"stripAuthHeaders");async function Tr(e,t){if(t.mode==="anonymous")return t.transport.request(fe(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return p(it())}let n=await t.transport.request(fe(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return p(it())}let s=await t.transport.request(fe(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !s.ok&&s.error.httpStatus===401?p(it(s.error.httpStatus)):s}i(Tr,"authedSend");function it(e){return S("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(it,"authRejectedError");var Pr=`
2
+
3
+ `,Si=1048576,wi=zod.z.record(zod.z.string(),zod.z.unknown()),ki=["emergency","schedule_soon","home_care"];async function*Ue(e,t=null){let r=null,n=i(()=>(r!==null||(r=typeof t=="function"?t():t),r),"requestIdNow"),o=new TextDecoder("utf-8"),s="",l=0,u=false;for await(let a of e){for(s+=o.decode(a,{stream:true});;){let d=s.indexOf(Pr,l);if(d===-1)break;let c=s.slice(0,d);s=s.slice(d+Pr.length),l=0;let m=xr(c,n());if(m!==null&&(m.kind==="delta"&&(u=true),yield m,m.terminal))return}if(l=s.length>0?s.length-1:0,s.length>Si){yield N({code:u?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(s+=o.decode(),s.trim().length>0){let a=xr(s,n());if(a!==null&&(a.kind==="delta"&&(u=true),yield a,a.terminal))return}yield N({code:u?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(Ue,"parseSse");function xr(e,t){let r=null,n=[];for(let l of e.split(`
4
+ `)){let u=l.replace(/\s+$/,"");u.length===0||u.startsWith(":")||(u.startsWith("id:")?r=u.slice(3).trim():u.startsWith("data:")&&n.push(u.slice(5).replace(/^ /,"")));}if(n.length===0)return null;let o;try{o=JSON.parse(n.join(`
5
+ `));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=wi.safeParse(o);return s.success?Ti(s.data,r,t):null}i(xr,"parseBlock");function Ti(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return N({code:z(e.code)??"unknown",retryable:e.retryable===true,wireMessage:z(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return Rr({conversationId:z(e.conversation_id)??"",messageId:z(e.message_id),title:z(e.title),followUpQuestions:Ii(e.follow_up_questions),citations:Ir(e.citations),citationStatus:z(e.citation_status),urgencyLevel:Or(e.urgency_level),urgencyReason:z(e.urgency_reason),urgencyProvided:xi(e),resultId:z(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return br(z(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return vr(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let s=z(e.delta)??z(e.token)??"";return _r(s,t,r)}return o==="analysis_started"?Er(z(e.request_id),t,r):o==="analysis_complete"?Cr({resultId:z(e.result_id),analysisType:z(e.analysis_type),modelVersion:z(e.model_version),confidence:Pi(e.confidence),detections:Ir(e.detections),interpretation:z(e.interpretation),lastEventId:t},r):Sr(e,t,r)}i(Ti,"frameFromWire");function z(e){return typeof e=="string"?e:null}i(z,"asString");function Pi(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(Pi,"asNumber");function Or(e){return typeof e=="string"&&ki.includes(e)?e:null}i(Or,"asUrgency");function xi(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Or(t)!==null}i(xi,"urgencySlotProvided");function Ii(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(Ii,"asStringList");function Oi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Oi,"isPlainObject");function Ir(e){return Array.isArray(e)?e.filter(Oi):[]}i(Ir,"asMapList");var Ai="0.4.0",Fi="react-native",Mi="2026-09-19",Ar="EVERFUR_API_BASE_URL";function me(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i(me,"configFailure");function lt(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}i(lt,"checkPublishableKey");function Fr(e,t){let r=lt(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=Di(e.apiBaseUrl);if(!o.ok)return o;let s=e.contractVersion?.trim()||Mi;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:s,sdkVersion:Ai,platform:t?.platform??Fi,debug:e.debug===true})})}i(Fr,"tryResolveClientConfig");function Di(e){let t=e?.trim(),r=t&&t.length>0?t:Hi(Ar);return r?Bi(r):me("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Ar}. The SDK never ships a hardcoded host.`)}i(Di,"tryResolveApiBaseUrl");function Mr(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(Mr,"buildBaseHeaders");var ji=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function zi(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(zi,"hostOf");function Li(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(Li,"isPrintableHost");function Ui(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Li(t)}i(Ui,"canEchoOrigin");function Ni(e,t){return `${e}://${t}`}i(Ni,"safeOrigin");function Bi(e){let t=e.trim(),r=ji.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return me("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=zi(r[2]);if(o.length===0)return me("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=Ui(t,o)?`: ${Ni(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&qi(o)))return n==="http"?me("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):me("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${s}`)}let l=t.endsWith("/")?t.slice(0,-1):t;return Object.freeze({ok:true,value:l})}i(Bi,"normalizeBaseUrl");function qi(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(qi,"isLoopbackHost");function Hi(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i(Hi,"readEnv");var Ki=3e4,Lr="x-request-id";async function*Dr(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;n&&n.length>0&&(yield n);}}finally{await t.cancel?.();}}i(Dr,"fetchByteSource");function $i(e){let t=new TextEncoder,r=Wi(),n=false,o=i(a=>{let d="";a.lastEventId&&(d+=`id: ${a.lastEventId}
6
+ `);let c=a.data??"";for(let m of c.split(`
7
+ `))d+=`data: ${m}
8
+ `;d+=`
9
+ `,r.push(t.encode(d));},"onMessage"),s=i(()=>{u(),r.end();},"onDone"),l=i(a=>{let d=typeof a.xhrStatus=="number"?a.xhrStatus:0;if(d>=400){let c=Br(d),m=ee(Y(c));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:c,retryable:m})}
10
+
11
+ `));}u(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",s),e.addEventListener("error",l);function u(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",s),e.removeEventListener("error",l);try{e.close();}catch{}}}return i(u,"cleanup"),Vi(r.source,u)}i($i,"eventSourceByteSource");async function*Vi(e,t){try{yield*e;}finally{t();}}i(Vi,"sourceWithCleanup");function Wi(){let e=[],t=false,r=null,n=i(()=>{if(r){let s=r;r=null,s();}},"signal");async function*o(){for(;;){let s=e.shift();if(s!==void 0){yield s;continue}if(t)return;await new Promise(l=>{r=l;});}}return i(o,"gen"),{source:o(),push:i(s=>{e.push(s),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(Wi,"createByteQueue");async function Gi(e,t){let r=t.fetchImpl??qr(),n=Hr(t.config.apiBaseUrl,e.path,e.query),o=Kr(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),s=es(Ki),l=ts(s.signal,e.signal),u;try{u=await r(n,$r({...e,signal:l},o));}catch(d){return p(ut(d))}finally{s.cancel();}let a=await Vr(u);return u.ok?_(a):p(Qi(u.status,a,Nr(u)))}i(Gi,"requestJson");function Ur(e){return {request:i(t=>Gi(t,e),"request"),stream:i((t,r)=>Yi(Zi(t,r),e),"stream")}}i(Ur,"createHttpTransport");async function*Yi(e,t){let r=Hr(t.config.apiBaseUrl,e.path,e.query),n=Kr(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let u=t.eventSourceFactory(r,Xi(e,n));yield*Ue($i(u),()=>Ji(u));return}let o=t.fetchImpl??qr(),s;try{s=await o(r,$r(e,n));}catch(u){yield jr("",true,Xr(u));return}let l=Nr(s);if(!s.ok){let u=await Vr(s),a=Wr(u)??Br(s.status),d=Yr(u)||ee(Y(a));yield jr(a,d,Gr(u),l);return}if(s.body){yield*Ue(Dr(s.body),l);return}yield*Ue(Dr(null),l);}i(Yi,"streamFrames");function Xi(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Xi,"buildEventSourceInit");function Qi(e,t,r){let n=Wr(t),o=n?Y(n):fr(e),s=Gr(t);return S(o,{httpStatus:e,...Yr(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...zr(t)?{reasonCode:zr(t)}:{},...s?{wireMessage:s}:{},...t!=null?{raw:t}:{}})}i(Qi,"errorFromResponse");function ut(e){return S("internalError",{retryable:true,wireMessage:Xr(e)})}i(ut,"networkError");function Nr(e){let t=e.headers.get(Lr);return typeof t=="string"&&t.length>0?t:null}i(Nr,"requestIdOf");function Ji(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Lr);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(Ji,"eventSourceRequestId");function Br(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(Br,"statusToWireCode");function jr(e,t,r,n=null){return N({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(jr,"syntheticErrorFrame");function qr(){let e=globalThis.fetch;if(typeof e!="function")throw new K("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(qr,"getGlobalFetch");function Hr(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let s=Object.entries(r).filter(l=>l[1]!==void 0).map(([l,u])=>`${encodeURIComponent(l)}=${encodeURIComponent(String(u))}`).join("&");s&&(o+=`?${s}`);}return o}i(Hr,"buildUrl");function Kr(e,t,r,n){let o={...Mr(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(Kr,"mergeHeaders");function $r(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i($r,"buildInit");function Zi(e,t){return e.signal?e:{...e,signal:t}}i(Zi,"withSignal");function es(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(es,"timeoutSignal");function ts(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(ts,"mergeAbortSignals");async function Vr(e){try{return await e.json()}catch{return null}}i(Vr,"safeJson");function zr(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(zr,"extractReasonCode");function Wr(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(Wr,"extractWireCode");function Gr(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(Gr,"extractWireMessage");function Yr(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Yr,"extractRetryable");function Xr(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Xr,"describeCause");var rs=3e4,ns=rt*2,os="idempotency-key",is=new Set(["POST","PUT","PATCH","DELETE"]),ss=Object.freeze({onEvent(){}}),as=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function ls(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(ls,"seededIdempotencyKey");function $(e){let t=e.observer??ss,r=e.timers??as,n=e.rng??Math.random,o=e.sleep??((h,g)=>Rs(h,r,g)),s=e.maxAttempts??pe,l=e.unaryTimeoutMs??rs,u=e.newIdempotencyKey??ds(),a=i(h=>{try{t.onEvent(h);}catch{}},"emit");async function d(h,g,E){let T=E?.maxAttempts,C=Math.max(1,T??s),P=E?.idempotent??is.has(g.method),O=E?.idempotencyKey===void 0?null:ls(E.idempotencyKey),D=P?O??u():null,A=us(g,D),v=0;for(;;){let w=i(ue=>Object.freeze({call:h,method:g.method,path:g.path,attempt:v,...D?{idempotencyKey:D}:{},...ue}),"stamp");a(w({phase:"attempt"}));let j=vs(l,r),B=_s(j.signal,g.signal),q;try{q=await Tr({...A,signal:B.signal},e.auth);}catch(ue){q=p(ut(ue));}finally{B.dispose(),j.cancel();}if(q.ok)return a(w({phase:"settled",ok:true,reason:"ok"})),q;let H=q.error,ie=ps(H,v,{maxAttempts:C,rng:n,now:r.now(),aborted:g.signal?.aborted===true,...T!==void 0?{perCallMaxAttempts:T}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),ce={ok:false,code:H.code,reason:ie.reason,...H.httpStatus!==void 0?{httpStatus:H.httpStatus}:{},...H.requestId!==void 0?{requestId:H.requestId}:{}};if(!ie.retry)return a(w({phase:"settled",...ce})),p(H);if(a(w({phase:"retry",...ce,delayMs:ie.delayMs})),await o(ie.delayMs,g.signal),g.signal?.aborted===true)return a(w({phase:"settled",...ce,reason:"aborted"})),p(H);v+=1;}}i(d,"send");async function c(h){return fe(h,await bs(e.auth))}i(c,"authorize");async function*m(h,g,E){a(Object.freeze({call:h,phase:"stream.open",method:g.method,path:g.path,attempt:0}));try{yield*e.auth.transport.stream(g,E);}catch{yield N({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(m,"stream"),Object.freeze({send:d,authorize:c,stream:m})}i($,"createRequestFunnel");function us(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==os&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(us,"assembleHeaders");function ds(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(ds,"defaultIdempotencyKeyFactory");var cs=10;function ps(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=fs(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!ee(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let l=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(cs,Math.floor(d)))},"policyCeiling"),u=r.perCallMaxAttempts??l()??r.maxAttempts;if(t+1>=u)return {retry:false,reason:"attempts-exhausted"};let a=ms(e,r.now);return a!==null?a>ns?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:a}:{retry:true,reason:o,delayMs:ze(t,r.rng)}}i(ps,"decideRetry");function fs(e){let t=e.code==="unknown"?Y(hs(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(fs,"throttleKind");function ms(e,t){let r=ys(e.raw);if(r===null)return null;let n=r-t;return n>0?n:0}i(ms,"retryOverrideMs");function ys(e){for(let t of Jr(e)){let r=t.resets_at,n=gs(r);if(n!==null)return n}return null}i(ys,"findResetsAt");function Jr(e){if(!Qr(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Qr(n)&&t.push(n);}return t}i(Jr,"candidateScopes");function gs(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(gs,"parseInstantMs");function hs(e){for(let t of Jr(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(hs,"rawWireCode");function Qr(e){return typeof e=="object"&&e!==null}i(Qr,"isRecord");async function bs(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(bs,"resolveDeviceAuth");function vs(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(vs,"boundedSignal");function _s(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(_s,"mergeSignals");function Rs(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",s),n();},e),s=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",s,{once:true});})}i(Rs,"delayAbortable");function L(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(L,"hasLoneSurrogate");function Ne(e){return [...e].length}i(Ne,"serverLength");var rn=Object.freeze(["better","same","worse"]),ct=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Zr(e){return p(S("validationFailed",{retryable:false,wireMessage:e}))}i(Zr,"invalid");function dt(){return p(S("internalError",{retryable:false}))}i(dt,"malformed");function en(e){return typeof e!="string"||e.trim().length===0?S("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):L(e)?S("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(en,"petPath");var te=i(e=>typeof e=="string"?e:null,"str");function tn(e){if(typeof e!="object"||e===null)return null;let t=e,r=te(t.case_id),n=te(t.status);if(r===null||n===null)return null;let o=te(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:te(t.body_location),lastResponse:o!==null&&rn.includes(o)?o:null,checkInDueAt:te(t.check_in_due_at),openedAt:te(t.opened_at),resolvedAt:te(t.resolved_at),resolutionText:te(t.resolution_text)})}i(tn,"caseFromWire");function nn(e){return {async list(t,r){let n=en(t);if(typeof n!="string")return p(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return p(o.error);let s=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(s))return dt();let l=s.map(tn);return l.every(u=>u!==null)?_(Object.freeze(l)):dt()},async checkin(t,r,n,o){let s=en(t);if(typeof s!="string")return p(s);if(typeof r!="string"||!ct.test(r))return Zr("case_id must be a UUID");if(!rn.includes(n))return Zr("response must be one of better, same, worse");let l=await e.send("cases.checkin",{method:"POST",path:`${s}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!l.ok)return p(l.error);let u=typeof l.value=="object"&&l.value!==null?l.value:{},a=tn(u.case);return a===null?dt():_(Object.freeze({case:a,ctaDeepLink:te(u.cta_deep_link)}))}}}i(nn,"createCasesRepositoryOver");var on=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var sn=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function qe(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},s=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",s),n();},"done");o.handle=r.setTimeout(s,e),t.addEventListener("abort",s,{once:true});})}i(qe,"delayAbortable");function He(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(He,"mergeSignals");var pt=class pt{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?He(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(pt,"MediaStore");var Be=pt;function mt(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(mt,"makeUser");function yt(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(yt,"makeAssistant");function ge(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(ge,"stripPending");function an(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(an,"appendText");function gt(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(gt,"finalizeAssistant");function ln(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(ln,"freezeSnapshot");function R(e,t,r){return S(e,{retryable:t,...r?{wireMessage:r}:{}})}i(R,"makeError");function ht(e){let t=Y(e.code);return S(t,{retryable:e.retryable||je(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(ht,"errorFromFrame");function X(e){return N({code:Es(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(X,"synthErrorFrame");function Es(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return Le(e)}}i(Es,"canonicalWireCode");function un(e){let t=Array.isArray(e)?e:ft(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!ft(n))continue;let o=ye(n.category)??ye(n.title)??"",s=Cs(n.prompts??n.questions);o.length===0&&s.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(s)}));}return Object.freeze(r)}i(un,"parsePromptCategories");function bt(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let s=o.trim();s.length===0||t.has(s)||(t.add(s),r.push(s));}return r}i(bt,"flattenPrompts");function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ft,"isPlainObject");function ye(e){return typeof e=="string"?e:null}i(ye,"asStr");function Cs(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(ft(r)){let n=ye(r.text)??ye(r.prompt)??ye(r.title);n!==null&&t.push(n);}return t}i(Cs,"asPromptTextList");function dn(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(dn,"defaultIdFactory");function cn(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(cn,"defaultIdempotencyFactory");var fn={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*mn(e,t,r,n){let o=e[Symbol.asyncIterator](),s=pn(t.overallMs,n),l=pn(t.idleMs,n),u=ks(r);try{for(;;){if(r.aborted)return;let a=o.next().then(m=>({tag:"next",value:m}),()=>({tag:"streamError"})),d=await Promise.race([a,l.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),u.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield ws();return}if(d.tag==="idle"||d.tag==="overall"){yield Ss();return}let c=d.value;if(c.done||(l.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{l.cancel(),s.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(mn,"withWatchdog");function Ss(){return N({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Ss,"synthTimeoutFrame");function ws(){return N({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(ws,"synthStreamErrorFrame");function pn(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(s=>{r=s;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(s){t.clearTimeout(o),o=t.setTimeout(()=>r(),s);},cancel(){t.clearTimeout(o);}}}i(pn,"deadline");function ks(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(ks,"abortPromise");var Ts="checkin",Ps=/^\d{4}-\d{2}-\d{2}$/,he="watching";function xs(e){return e.status!=null&&e.status!==he}i(xs,"isCheckinSettled");function yn(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Ts||n===void 0||o===void 0||!ct.test(n)||!Ps.test(o)?null:n}i(yn,"parseCheckinOriginRef");function vt(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return p(S("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||L(o))return p(S("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),_(r.length?`?${r.join("&")}`:"")}i(vt,"historyQuery");function _e(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(_e,"validConversationId");function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(ve,"object");function gn(e){return e==null||typeof e=="string"&&e.length>0&&!L(e)}i(gn,"cursor");function be(){return p(S("internalError",{retryable:false}))}i(be,"malformed");function hn(e){let t=ve(e);if(!t||!Array.isArray(t.conversations)||!gn(t.next_cursor))return be();let r=[];for(let n of t.conversations){let o=ve(n);if(!o||typeof o.conversation_id!="string"||!_e(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return be();let s=o.unread_message_count;if(!(s==null||Number.isInteger(s)&&s>=0))return be();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:s??null}));}return _(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(hn,"mapConversationPage");function bn(e){let t=ve(e);if(!t||!Array.isArray(t.messages)||!gn(t.next_cursor))return be();let r=[],n=new Set;for(let o of t.messages){let s=ve(o);if(!s||typeof s.message_id!="string"||!_e(s.message_id)||typeof s.role!="string"||typeof s.content!="string"||typeof s.created_at!="string")return be();if(s.role!=="user"&&s.role!=="assistant"||n.has(s.message_id))continue;n.add(s.message_id);let l=typeof s.proactive_origin_ref=="string"?s.proactive_origin_ref:null,u=s.role==="assistant"?yn(l):null;r.push(Object.freeze({id:s.message_id,role:s.role,text:s.content,createdAt:s.created_at,...s.role==="assistant"?{responseId:s.message_id}:{},...s.urgency_level!==void 0?{urgencyLevel:Is(s.urgency_level)}:{},...Array.isArray(s.citations)?{citations:Os(s.citations)}:{},...l!==null?{proactiveOriginRef:l}:{},...u!==null?{checkin:Object.freeze({caseId:u,answer:null,resolutionText:null,status:null})}:{}}));}return _(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(bn,"mapMessagePage");function Is(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Is,"normalizeUrgency");function Os(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=ve(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let s of t){let l=n[s];(typeof l=="string"||l===null)&&(o[s]=l);}return [Object.freeze(o)]}))}i(Os,"historyCitations");var Ke=5,_t=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Rt=4e3;var Et=4e3;function vn(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:R("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:R("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(vn,"validateImageKeys");function Ct(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:R("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Et?{reason:"too_long",error:R("validationFailed",false,`message is ${r} characters; the server accepts at most ${Et}`)}:null}i(Ct,"validateMessageText");function _n(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(_n,"urgencyTier");async function*Re(e){yield e;}i(Re,"singleFrameStream");async function*Rn(){}i(Rn,"emptyStream");var As=6e4,Fs=18e4,Ms=24,Ds=512,js=false;function En(e){return new St(e)}i(En,"createChatController");var wt=class wt extends Be{constructor(r){super(ln({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??$({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=nn(this.funnel),this.telemetry=r.telemetry??Me,this.errorPolicy=r.errorPolicy??gr,this.timers=r.timers??fn,this.rng=r.rng??Math.random,this.newId=r.newId??dn(),this.makeIdempotencyKey=r.makeIdempotencyKey??cn(),this.budget={idleMs:r.budget?.idleMs??As,overallMs:r.budget?.overallMs??Fs};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let s=n??{};if(this.disposed||this.snapshot.isBootstrapping){let a=R(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(a),()=>{}):Re(X(a))}let l=Ct(r)??vn(s.imageS3Keys);if(l!==null)return this.telemetry.track("chat.send.rejected",{reason:l.reason}),this.patch({status:"error",isStreaming:false,error:l.error}),o?(o.onError(l.error),()=>{}):Re(X(l.error));if(o)return this.driveWithHandlers(r,s,o);let u=this.beginTurn(r,s);return this.runTurn(u,s.signal)}askEverfur(r,n){if(this.disposed)return Re(X(R("accessDenied",false)));let o=Ct(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),Re(X(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let s=this.snapshot.conversationId;return s!==null&&this.snapshot.status==="error"?this.retryHistory(s):Rn()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(s=>s.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,mt(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?ge(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=[],this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:[],historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(bt(r));this.bootstrapPrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=vt(r,100);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return p(R("accessDenied",false));let l=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(s)||this.disposed)return p(R("accessDenied",false));if(!l.ok)return l;let u=hn(l.value);if(u.ok){for(let c of u.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let a=this.snapshot.conversationId,d=a===null?void 0:this.unreadByConversation.get(a);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return u}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return p(R("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let a=await this.resumeConversation(n);return a.ok?_(n):p(a.error)}let o=r?.petRef??this.petRef,s=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!s.ok)return p(s.error);let l=s.value.conversations[0];if(l===void 0)return _(null);let u=await this.resumeConversation(l.id);return u.ok?_(l.id):p(u.error)}async markRead(r){if(this.disposed)return p(R("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return _(void 0);let o=this.epoch,s=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?p(R("accessDenied",false)):s.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),_(void 0)):p(s.error)}async submitFeedback(r,n,o,s){if(this.disposed)return p(R("accessDenied",false));if(typeof r!="string"||r.trim().length===0||L(r))return p(R("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!_t.includes(n))return p(R("validationFailed",false,`feedback_type must be one of ${_t.join(", ")}`));let l=typeof o=="string"?o.trim():"";if([...l].length>Rt)return p(R("validationFailed",false,`notes is over ${Rt} characters`));let u={feedback_type:n};l.length>0&&(u.notes=l);let a=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:u},s?.signal);if(!this.alive(a)||this.disposed)return p(R("accessDenied",false));if(!d.ok)return p(d.error);let c=d.value?.feedback_id;return _(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return p(R("accessDenied",false));let s=o?.petRef??this.petRef;if(s===null)return p(R("validationFailed",false,"a check-in needs the pet the case belongs to"));let l=this.epoch,u=await this.cases.checkin(s,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(l)||this.disposed)return p(R("accessDenied",false));if(!u.ok)return u;let a=Object.freeze({caseId:r,answer:n,resolutionText:u.value.case.resolutionText,status:u.value.case.status??null}),d=i(c=>c.checkin?.caseId===r,"carries");return this.snapshot.messages.some(d)&&this.patch({messages:this.snapshot.messages.map(c=>d(c)?Object.freeze({...c,checkin:a}):c)}),u}async getMessages(r,n){if(!_e(r))return p(R("validationFailed",false));let o=vt(n,200);if(!o.ok)return o;let s=this.epoch;if(this.disposed)return p(R("accessDenied",false));let l=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(s)||this.disposed?p(R("accessDenied",false)):l.ok?bn(l.value):l}async resumeConversation(r){if(this.disposed)return p(R("accessDenied",false));if(!_e(r))return p(R("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return p(R("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let s=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:s}),this.stampCheckinStatuses(n),s!==null&&s>0&&this.markRead(),_(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let s=new Set(o.value.filter(d=>d.status===he).map(d=>d.caseId)),l=new Map(o.value.map(d=>[d.caseId,d])),u=false,a=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;u=true;let m=l.get(c.caseId);return Object.freeze({...d,checkin:Object.freeze({...c,status:s.has(c.caseId)?he:m?.status??"resolved",answer:c.answer??m?.lastResponse??null,resolutionText:c.resolutionText??m?.resolutionText??null})})});u&&this.patch({messages:a});}async refreshActiveThread(){if(this.disposed)return p(R("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return _(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return p(R("accessDenied",false));if(!o.ok)return p(o.error);let s=new Set(this.snapshot.messages.map(u=>u.id)),l=o.value.messages.filter(u=>!s.has(u.id));return l.length>0&&this.patch({messages:[...this.snapshot.messages,...l]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),_(void 0)}async loadOlderMessages(){if(this.disposed)return p(R("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return _(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let s=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return p(R("accessDenied",false));if(this.patch({isLoadingHistory:false}),!s.ok)return s;let l=new Set(this.snapshot.messages.map(a=>a.id)),u=s.value.messages.filter(a=>!l.has(a.id));return this.patch({messages:[...u,...this.snapshot.messages],historyCursor:s.value.nextCursor===n?null:s.value.nextCursor}),_(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield X(n.error));}async primeConversation(r){if(this.disposed)return p(R("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let s=await o.settled;return this.disposed?p(R("accessDenied",false)):(!s.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),s)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return _(n);let o=this.snapshot.conversationId;return o!==null?_(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?null:o.id}async createConversation(r){let n=this.epoch;if(this.disposed)return p(R("accessDenied",false));let o=r?.petRef??null,s={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=s;let l=await s.settled;return !this.alive(n)||this.disposed?p(R("accessDenied",false)):(!l.ok&&this.unadoptedCreate===s&&(this.unadoptedCreate=null),l)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},s=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!s.ok)return p(s.error);let l=s.value?.conversation_id??s.value?.id;return typeof l!="string"||l.length===0?p(R("internalError",true)):_(l)}async getPrompts(r){let n=this.epoch;if(this.disposed)return p(R("accessDenied",false));let o=r?.petRef??null;if(o!==null&&L(o))return p(S("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let s=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",l=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${s}`});return !this.alive(n)||this.disposed?p(R("accessDenied",false)):l.ok?_(un(l.value)):p(l.error)}async authedUnary(r,n,o,s){return this.funnel.send(r,o?{...n,signal:o}:n,s)}driveWithHandlers(r,n,o){let s=new AbortController,l=He(s.signal,n.signal),u=this.beginTurn(r,n),a=this.runTurn(u,l),d=false,c=i(()=>{d||(d=true,s.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let m of a){if(d)break;o.onFrame(m),m.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,mt(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let s=0,l=false,u=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let a=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=a?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let C=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;C.ok&&this.snapshot.conversationId===null&&this.adoptConversation(C.value);}if(a&&this.snapshot.conversationId===null){let C=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!C.ok){yield*this.emitTerminal(r,C.error,X(C.error));return}this.adoptConversation(C.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let C=R("internalError",!0);yield*this.emitTerminal(r,C,X(C));return}this.clearAssistantInProgress(r);let m=new AbortController,h=He(o.signal,m.signal),g=null;try{let C;try{C=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let O=this.authRejected();yield*this.emitTerminal(r,O,X(O));return}if(o.signal.aborted||!this.alive(o.epoch))return;let P=this.funnel.stream("chat.send",C,h);for await(let O of mn(P,this.budget,h,this.timers)){if(!this.alive(o.epoch))return;if(O.kind==="error"&&O.terminal){g=O;break}if(this.applyFrame(O,r),yield O,O.terminal){o.settle();return}}}finally{m.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(g===null){if(this.snapshot.status==="complete")return;let C=R("streamIncomplete",!0);yield*this.emitTerminal(r,C,X(C));return}let E=Y(g.code);if(E==="authExpired"&&this.auth.mode==="personalized"&&!u){u=!0,this.telemetry.track("chat.auth.refresh",{});let C=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!C){let P=this.authRejected();yield*this.emitTerminal(r,P,g);return}this.patch({reconnecting:!0});continue}if(E==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let C=this.authRejected();yield*this.emitTerminal(r,C,g);return}if(E==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,ht(g),g);return}if(yr(E)&&!l){l=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let T=g.retryable&&je(E,!0);if(js&&T&&s+1<this.errorPolicy.maxAttempts(E));yield*this.emitTerminal(r,ht(g),g);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return Le(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let s=this.snapshot.messages.map(l=>l.id===n.userMessageId&&l.pending===true?ge(l):l);this.patch({status:"streaming",isStreaming:true,messages:[...s,yt(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=Ds){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},Ms);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let s=this.snapshot.messages.map(l=>l.id===o?an(l,n):l);this.patch({messages:s});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,s;if(n.assistantMessageId!==null)s=this.snapshot.messages.map(u=>u.id===n.assistantMessageId?gt(u,r):u);else {let u=this.newId();n.assistantMessageId=u,n.sawDelta=true,s=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?ge(d):d),gt(yt(u,"",this.stamp()),r)];}let l=bt([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=l.length>0?Object.freeze(l):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:s,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let s=this.epoch,l=this.historyGeneration,u=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!u.ok||!this.alive(s)||this.disposed||l!==this.historyGeneration||this.snapshot.conversationId!==r)return;let a=_n(u.value?.urgency),d=typeof u.value?.reason=="string"?u.value.reason:null,c=i(m=>m.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(m=>c(m)?Object.freeze({...m,urgencyLevel:a,urgencyReason:d,urgencyProvided:true}):m)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(s=>s.id===r.userMessageId&&s.pending===true?ge(s):s);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(s=>s.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return R("authRejected",false)}};i(wt,"ChatControllerImpl");var St=wt;async function wn(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,s=[],l=false,u=false,a=false,d=null,c=null,m=o?r.resumeConversation(o).then(A=>A.ok?_(o):A):r.primeConversation(n?{petRef:n}:void 0),h=r.getPrompts(n!==null?{petRef:n}:void 0),[g,E]=await Promise.all([m,h]),T=null;if(g.ok)T=g.value,s.push(g.value),r.getSnapshot().conversationId===null&&r.adoptConversation(g.value);else {let A=g.error;c=A,Cn(A)?(u=true,d=A):(Sn(A)&&(l=true),a=true);}let C=[];E.ok?C=E.value:P(E.error);function P(A){Cn(A)?(u=true,d===null&&(d=A)):Sn(A)&&(l=true);}i(P,"recordAuthSignals");let O=d!==null?d.displayMessage:null;return Object.freeze({conversationId:T,petRef:n,suggestedPrompts:C,error:O,warning:O===null&&T===null&&a?zs:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...s]),sawForbidden:l,sawUnauthorized:u,sawConversationInitFailure:a})})}i(wn,"bootstrapChat");var zs="Chat is ready. Your first message will start the conversation.";function Cn(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(Cn,"isUnauthorized");function Sn(e){return e.httpStatus===403||e.code==="accessDenied"}i(Sn,"isForbidden");var kt=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function kn(e){return e!==kt}i(kn,"isUploadTransportAvailable");var Tn=128,oe=128;var Ls=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]),dc="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",xn=10*1024*1024,Us=5,Ee=120,Ns="/widget/v1/uploads/initiate";function Bs(e){return typeof e=="string"&&Ls.includes(e.trim().toLowerCase())}i(Bs,"isAttachmentMime");function qs(e){if(!e)return "attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return "attachment";if(t.length<=Ee)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Ee);let n=t.slice(r);return n.length>=Ee?t.slice(0,Ee):`${t.slice(0,r).slice(0,Ee-n.length)}${n}`}i(qs,"sanitizeFilename");function cc(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(cc,"formatBytes");var Ce=i(e=>Object.freeze({ok:true,value:e}),"ok"),V=i(e=>Object.freeze({ok:false,error:e}),"err");function M(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(M,"failure");function Hs(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}i(Hs,"attachmentSize");function Ks(e){let t=qs(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!Bs(r))return V(M("unsupported_type",false,t));let n=Hs(e);return n===null?V(M("unknown",false,t)):n>xn?V(M("too_large",false,t,{sizeBytes:n})):Ce(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Ks,"validateAttachment");function $s(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d:null,"num"),o=r(t.upload_id),s=r(t.upload_url),l=r(t.s3_key);if(o===null||s===null||l===null)return null;let u={},a=t.upload_fields;if(typeof a=="object"&&a!==null)for(let[d,c]of Object.entries(a))typeof c=="string"&&(u[d]=c);return Object.freeze({upload_id:o,upload_url:s,upload_fields:Object.freeze(u),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??xn,s3_key:l,purpose:r(t.purpose)})}i($s,"parsePolicy");function Vs(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return M("quota_exceeded",false,t,{cause:e});case "rateLimited":return M("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return M("idempotency_conflict",true,t,{cause:e});case "validationFailed":return M("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return M("network",true,t,{cause:e});default:return r===429?M("rate_limited",true,t,{cause:e}):r===503?M("network",true,t,{cause:e}):r===void 0?M("network",true,t,{cause:e}):M("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Vs,"initiateFailure");async function Ws(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Ns,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return V(Vs(n.error,t.filename));let o=$s(n.value);return o===null?V(M("server",false,t.filename)):Ce(o)}i(Ws,"initiateAttachmentUpload");async function Gs(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return V(M("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),Ce(void 0)}catch{return o()?V(M("cancelled",true,r.filename)):V(M("server",true,r.filename))}}i(Gs,"uploadAttachmentBytes");var Ys=2,Xs=3,Qs=Object.freeze([1e3,2e3,4e3]),Pn=0;function Js(){return Pn+=1,`attachment-${Pn}`}i(Js,"defaultNewId");function pc(e){let t=Math.max(1,e.concurrency??Ys),r=Math.max(1,e.maxAttempts??Xs),n=e.backoffMs??Qs,o=Math.max(1,e.maxPerMessage??Us),s=e.timers??sn,l=e.newId??Js,u=kn(e.transport),a=new Map,d=[],c=[],m=new Set,h=new Set,g=Object.freeze({attachments:Object.freeze([])}),E=false,T=i(()=>{g=Object.freeze({attachments:Object.freeze(d.flatMap(v=>{let w=a.get(v);return w===void 0?[]:[w.state]}))});for(let v of h)v();},"publish"),C=i((v,w)=>{v.state=Object.freeze({...v.state,...w}),T();},"patch"),P=i(()=>{for(;!E&&m.size<t&&c.length>0;){let v=c.shift(),w=a.get(v);w!==void 0&&(m.add(v),O(w).finally(()=>{m.delete(v),P();}));}},"pump"),O=i(async v=>{let{attachment:w}=v;for(;v.attempts<r;){if(E||v.controller.signal.aborted)return;v.attempts+=1;let j=v.controller.signal;C(v,{status:"uploading",error:null,progress:0});let B=await Ws(e.funnel,w,{signal:j});if(E||j.aborted)return;let q;if(!B.ok)q=V(B.error);else {let ue=await Gs(e.transport,B.value,w,{signal:j,onProgress:i(ii=>{!j.aborted&&v.state.status==="uploading"&&C(v,{progress:Zs(ii)});},"onProgress")});if(E||j.aborted)return;q=ue.ok?Ce(B.value.s3_key):V(ue.error);}if(q.ok){C(v,{status:"uploaded",s3Key:q.value,error:null,progress:1});return}let H=q.error,ie=H.retryable&&v.attempts<r;if(C(v,{status:ie?"uploading":"failed",error:H,progress:0}),!ie)return;let ce=n[Math.min(v.attempts-1,n.length-1)]??0;await qe(ce,j,s);}},"run"),D=i(v=>{c.push(v.state.id),P();},"enqueue"),A={available:u,subscribe(v){return h.add(v),()=>{h.delete(v);}},getSnapshot:i(()=>g,"getSnapshot"),get uploading(){return g.attachments.some(v=>v.status==="uploading")},get s3Keys(){return g.attachments.flatMap(v=>v.status==="uploaded"&&v.s3Key!==null?[v.s3Key]:[])},add(v){let w=Ks(v);if(!w.ok)return w;if(E||d.length>=o)return V(M("too_many",false,w.value.filename));let j=l(),B={attachment:w.value,controller:new AbortController,attempts:0,state:Object.freeze({id:j,filename:w.value.filename,previewUri:v.uri,contentType:w.value.contentType,sizeBytes:w.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return a.set(j,B),d.push(j),T(),D(B),Ce(B.state)},retry(v){let w=a.get(v);w===void 0||E||w.state.status!=="failed"||(w.controller=new AbortController,w.attempts=0,C(w,{status:"uploading",error:null,progress:0,s3Key:null}),D(w));},remove(v){let w=a.get(v);if(w===void 0)return;w.controller.abort(),a.delete(v);let j=d.indexOf(v);j>=0&&d.splice(j,1);let B=c.indexOf(v);B>=0&&c.splice(B,1),T();},clear(){for(let v of [...d])A.remove(v);},dispose(){E=true;for(let v of a.values())v.controller.abort();a.clear(),d.length=0,c.length=0,h.clear(),g=Object.freeze({attachments:Object.freeze([])});}};return A}i(pc,"createAttachmentQueue");function Zs(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(Zs,"clamp");var In=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function On(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(In,t)?In[t]:null}i(On,"canonicalPetSpecies");var An=50,ea=128,Tt=120,Fn=120,ta=2e3,Mn=120,ra=80,zn=new Set(["male","female","unknown"]),Ln=new Set(["day","month","year"]),Un=new Set(["low","medium","high","athletic"]),Nn=new Set(["indoor","outdoor","both"]),Bn=new Set(["mild","moderate","severe"]),na=/^(\d{4})-(\d{2})-(\d{2})$/,qn=[["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"]],Hn=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...qn,...Hn].map(([e])=>e));function oa(e){let t=na.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],s=new Date(Date.UTC(r,n-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===n-1&&s.getUTCDate()===o}i(oa,"isRealDate");var we=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),ia=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),Ve=i((e,t)=>typeof t=="string"&&oa(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Q=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(L(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let s=Ne(o);return s<=e?null:`${r} is ${s} characters; the server accepts at most ${e}`},"text"),sa={sex:we(zn),spayedNeutered:ia,birthDate:Ve,birthDatePrecision:we(Ln),activityLevel:we(Un),indoorOutdoor:we(Nn),foodBrand:Q(Mn),foodType:Q(Mn),microchipId:Q(ra)},Pt=["ref","ref",false,Q(ea,{required:true,trimmed:true})],xt=["notes","notes",false,Q(ta,{trimmed:true})],Dn=[Pt,["name","name",true,Q(Tt,{required:true,trimmed:true})],["dose","dose",false,Q(Fn,{trimmed:true})],["frequency","frequency",false,Q(Fn,{trimmed:true})],["startDate","start_date",false,Ve],["endDate","end_date",false,Ve],xt],aa={allergies:[Pt,["allergen","allergen",true,Q(Tt,{required:true,trimmed:true})],["severity","severity",false,we(Bn)],xt],medications:Dn,supplements:Dn,conditions:[Pt,["conditionName","condition_name",true,Q(Tt,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Ve],xt]};function la(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,s={};for(let[a,d,c,m]of aa[e]){let h=o[a];if(h==null){if(c)return {error:`${n}.${a} is required`};h===null&&(s[d]=null);continue}let g=m(`${n}.${a}`,h);if(g!==null)return {error:g};s[d]=h;}let l=s.start_date,u=s.end_date;return typeof l=="string"&&typeof u=="string"&&u<l?{error:`${n}.endDate must not be before startDate`}:{item:s}}i(la,"itemToWire");function ua(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>An)return {error:`${e} has ${t.length} items; the server accepts at most ${An}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let s=la(e,o,t[o]);if("error"in s)return s;let l=s.item.ref;if(typeof l=="string"){let u=l.trim();if(n.has(u))return {error:`${e}: ref ${JSON.stringify(u)} is used twice; a ref names one item`};n.add(u);}r.push(s.item);}return {items:r}}i(ua,"listToWire");function Kn(e,t){let r=e,n={};for(let[l,u]of qn){let a=r[l];if(a!==void 0){if(a!==null){let d=sa[l](l,a);if(d!==null)return {error:d}}n[u]=a;}}let o=r.birthDate!==void 0,s=r.birthDatePrecision!==void 0;if(o!==s||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[l,u]of Hn){let a=r[l];if(a===void 0)continue;let d=ua(l,a);if("error"in d)return d;n[u]=d.items;}return Object.keys(n).length>0&&t!==void 0&&On(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}i(Kn,"petHealthToWire");var F=i(e=>typeof e=="string"?e:null,"str"),Se=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),da=i(e=>typeof e=="boolean"?e:null,"bool");function $e(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i($e,"itemsFromWire");function jn(e){let t=F(e.name);return t===null||t.length===0?null:Object.freeze({ref:F(e.ref),name:t,dose:F(e.dose),frequency:F(e.frequency),startDate:F(e.start_date),endDate:F(e.end_date),notes:F(e.notes)})}i(jn,"medicationFromWire");function $n(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:Se(zn,e.sex),spayedNeutered:da(e.spayed_neutered),birthDate:F(e.birth_date),birthDatePrecision:Se(Ln,e.birth_date_precision),activityLevel:Se(Un,e.activity_level),indoorOutdoor:Se(Nn,e.indoor_outdoor),foodBrand:F(e.food_brand),foodType:F(e.food_type),microchipId:F(e.microchip_id),allergies:$e(e.allergies,r=>{let n=F(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:F(r.ref),allergen:n,severity:Se(Bn,r.severity),notes:F(r.notes)})}),medications:$e(e.medications,jn),supplements:$e(e.supplements,jn),conditions:$e(e.conditions,r=>{let n=F(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:F(r.ref),conditionName:n,diagnosedDate:F(r.diagnosed_date),notes:F(r.notes)})})})}i($n,"petHealthFromWire");var Gn=100,Yn=50,Xn=100,Qn=50,Jn=500,ca=128,pa=6e4;function Z(e){return S("validationFailed",{retryable:false,wireMessage:e})}i(Z,"invalid");function se(e,t,r){if(typeof t!="string")return Z(`${e} must be a string`);let n=Ne(t);return n<=r?null:Z(`${e} is ${n} characters; the server accepts at most ${r}`)}i(se,"checkString");function We(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Z(`${e} must be a finite number between 0 and ${r}`)}i(We,"outOfRange");function Vn(e,t){if(typeof e!="string")return Z("pet_ref must be a string");if(e.trim().length===0)return Z("pet_ref must not be blank");if(L(e))return Z("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Z("profile must be an object");let r=[se("pet_ref",e,ca)];return t?.name!==void 0&&r.push(se("name",t.name,Gn)),t?.species!==void 0&&r.push(se("species",t.species,Yn)),t?.breed!==void 0&&r.push(se("breed",t.breed,Xn)),t?.ageYears!==void 0&&r.push(We("age_years",t.ageYears,Qn)),t?.weightKg!==void 0&&r.push(We("weight_kg",t.weightKg,Jn)),r.find(n=>n!==null)??null}i(Vn,"validate");function Zn(e,t){let r=Kn(e,t);return "error"in r?{error:Z(r.error)}:r}i(Zn,"healthToWire");function fa(e){if(typeof e!="object"||e===null)return {error:Z("patch must be an object")};let t=e,r=[["name","name",s=>se("name",s,Gn)],["species","species",s=>se("species",s,Yn)],["breed","breed",s=>se("breed",s,Xn)],["ageYears","age_years",s=>We("age_years",s,Qn)],["weightKg","weight_kg",s=>We("weight_kg",s,Jn)]],n={};for(let[s,l,u]of r){let a=t[s];if(a!==void 0){if(a!==null){let d=u(a);if(d!==null)return {error:d}}n[l]=a;}}let o=Zn(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Z("patch must change at least one field")}:{body:n})}i(fa,"patchToWire");function ma(e){if(e==null)return {body:{}};let t=Zn(e,e.species);return "error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}i(ma,"toWire");var J=i(e=>typeof e=="string"?e:null,"str"),Ge=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Wn(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:J(r.pet_ref)??t,name:J(r.name),species:J(r.species),breed:J(r.breed),ageYears:Ge(r.age_years),weightKg:Ge(r.weight_kg)})}i(Wn,"fromWire");function eo(e){if(typeof e!="object"||e===null)return null;let t=e,r=J(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:J(t.pet_id),petRef:r,name:J(t.name),species:J(t.species),breed:J(t.breed),ageYears:Ge(t.age_years),weightKg:Ge(t.weight_kg),updatedAt:J(t.updated_at)})}i(eo,"widgetPetFromWire");function ya(e){let t=eo(e);return t===null?null:Object.freeze({...t,...$n(e)})}i(ya,"widgetPetProfileFromWire");function ga(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=eo(r);return n===null?[]:[n]}))}i(ga,"petListFromWire");function to(e){return ha($({auth:e}),$({auth:e,unaryTimeoutMs:pa}))}i(to,"createPetsRepository");function ha(e,t=e){let r=i((o,s)=>s?{...o,signal:s}:o,"withSignal"),n=i(o=>Vn(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let s=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return s.ok?_(ga(s.value)):p(s.error)},async registerPet(o,s,l){let u=Vn(o,s);if(u!==null)return p(u);let a=ma(s);if("error"in a)return p(a.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:a.body},m=await e.send("pets.registerPet",l?.signal?{...c,signal:l.signal}:c);return m.ok?_(Wn(m.value,o)):p(m.error)},async updatePet(o,s,l){let u=n(o);if(typeof u!="string")return p(u);let a=fa(s);if("error"in a)return p(a.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:u,body:a.body},l?.signal));return d.ok?_(Wn(d.value,o)):p(d.error)},async getPetProfile(o,s){let l=n(o);if(typeof l!="string")return p(l);let u=await e.send("pets.getPetProfile",r({method:"GET",path:`${l}/profile`},s?.signal));if(!u.ok)return p(u.error);let a=ya(u.value);return a===null?p(S("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):_(a)},async deletePet(o,s){let l=n(o);if(typeof l!="string")return p(l);let u=await e.send("pets.deletePet",r({method:"DELETE",path:l},s?.signal));return u.ok?_(void 0):p(u.error)},async eraseUserData(o){let s=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return s.ok?_(void 0):p(s.error)}}}i(ha,"createPetsRepositoryOver");var ro=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function no(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let s of Object.keys(ro))for(let l of ro[s])o.has(l)||(o.add(l),n.push(Object.freeze({resource:l,granted:false,disabled:r})));return Object.freeze(n)}i(no,"deniedDecisionsFor");function re(e){let t=ba(e);return t===null?null:_a(t)}i(re,"parseColor");function ba(e){if(typeof e=="number")return oo(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return It(t.slice(1));if(t.toLowerCase().startsWith("0x"))return It(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return va(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=It(t);if(r!==null)return r}return /^\d+$/.test(t)?oo(Number.parseInt(t,10)):null}i(ba,"toRgba");function It(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:Ot(t[0]),g:Ot(t[1]),b:Ot(t[2]),a:1};if(t.length===6)return {r:ae(t,0),g:ae(t,2),b:ae(t,4),a:1};if(t.length===8){let r=ae(t,0);return {r:ae(t,2),g:ae(t,4),b:ae(t,6),a:r/255}}return null}i(It,"fromHex");function va(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(a=>a.trim());if(n.length<3)return null;let o=At(Number(n[0])),s=At(Number(n[1])),l=At(Number(n[2]));if(o===null||s===null||l===null)return null;let u=1;if(n.length>=4){let a=Number(n[3]);if(!Number.isFinite(a))return null;u=Math.min(1,Math.max(0,a));}return {r:o,g:s,b:l,a:u}}i(va,"fromRgbFunc");function oo(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return {r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}i(oo,"argbIntToRgba");function ae(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(ae,"byte");function Ot(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(Ot,"dup");function At(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(At,"clampByte");function _a(e){if(e.a>=1)return Ra(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(_a,"normalizeRgba");function Ra(e,t,r){return `#${Ft(e)}${Ft(t)}${Ft(r)}`.toUpperCase()}i(Ra,"rgbToHex");function Ft(e){return e.toString(16).padStart(2,"0")}i(Ft,"hex2");var Mt=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]);function Ea(e){return Mt.includes(e)}i(Ea,"isSlotName");function Ca(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(Ca,"parseRadius");function io(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!Ea(n)||o===null||typeof o!="object")continue;let s=Sa(o);s!==null&&(t[n]=s,r=true);}return r?Object.freeze(t):null}i(io,"parseThemeSlots");function Ye(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(Ye,"pick");function Sa(e){let t={},r=re(Ye(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=re(Ye(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Ca(Ye(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let s=re(Ye(e,"text_color","textColor"));return s!==null&&(t.textColor=s),Object.keys(t).length===0?null:Object.freeze(t)}i(Sa,"parseSlot");var lo=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),Xe="slots.";function uo(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(uo,"isEmptyBranding");function ka(e){return e==="hide_powered_by"||lo.includes(e)?true:e.startsWith(Xe)&&Mt.includes(e.slice(Xe.length))}i(ka,"isThemeLockName");function ke(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:le(x(t,"display_name","displayName")),logoUrl:le(x(t,"logo_url","logoUrl")),primaryColor:re(x(t,"primary_color","primaryColor")),accentColor:re(x(t,"accent_color","accentColor")),brightness:Ia(x(t,"brightness","color_scheme","colorScheme")),fontFamily:le(x(t,"font_family","fontFamily")),fontUrl:le(x(t,"font_url","fontUrl")),fonts:so(x(t,"fonts")),fontUrls:so(x(t,"font_urls","fontUrls")),placeholder:le(x(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Ta(x(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:re(x(t,"primary_color_dark","primaryColorDark")),accentColorDark:re(x(t,"accent_color_dark","accentColorDark")),surfaceStyle:ao(x(t,"surface_style","surfaceStyle"),Pa),radiusScale:ao(x(t,"radius_scale","radiusScale"),xa),logoUrlDark:le(x(t,"logo_url_dark","logoUrlDark")),slots:io(x(t,"slots")),accessibilityMaxFontScale:Aa(x(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Ma(x(t,"locked_fields","lockedFields")),schemaVersion:Fa(x(t,"schema_version","schemaVersion"))};return uo(r)?null:Object.freeze(r)}i(ke,"parseClientBranding");function Ta(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(Ta,"parseBool");function x(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i(x,"pick");function le(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(le,"parseNonEmptyString");var co=["regular","medium","bold","mono","monoMedium","monoBold"];function so(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of co){let o=le(x(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(so,"parseFaceMap");var Pa=["white","cream","subtle"],xa=["sharp","default","round"];function ao(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(ao,"parseEnum");function Ia(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(Ia,"parseBrightness");function po(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(po,"parseNumber");var Oa=1,fo=3.1;function Aa(e){let t=po(e);return t===null?null:t<=0?0:Math.min(fo,Math.max(Oa,t))}i(Aa,"parseMaxFontScale");function Fa(e){if(e==null)return null;let t=po(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(Fa,"parseSchemaVersion");function mo(e){let t=e.trim();return t.startsWith(Xe)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(mo,"toWireName");function Ma(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=mo(r);ka(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(Ma,"parseLockedFields");var yo="/widget/v1/entitlements",Da=304,ja=Object.freeze({kind:"notModified"});async function ho(e,t={},r=$({auth:e})){let n=await r.send("entitlements.fetch",La(t));return n.ok?Ua(n.value):n.error.httpStatus===Da?ja:{kind:"failed",error:n.error}}i(ho,"fetchEntitlements");var za=64;function La(e){let t={};return Dt(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=za?{method:"GET",path:yo,headers:t,query:{region:e.region}}:{method:"GET",path:yo,headers:t}}i(La,"buildRequest");function Ua(e){if(e===null||typeof e!="object"||!Dt(e.revision))return go();let t=typeof e.region=="string"?e.region:"",r=Dt(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Ba(e.capabilities),branding:Na(e)})}i(Ua,"parseUpdated");function Na(e){let t=ke(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=ke(r.branding);return n!==null?n:ke(r)}return null}i(Na,"parseBranding");function Ba(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))qa(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(Ba,"mapCapabilities");function qa(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(qa,"isEnabled");function go(){return {kind:"failed",error:S("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(go,"malformed");function Dt(e){return typeof e=="number"&&Number.isFinite(e)}i(Dt,"isFiniteNumber");var Ha=30;function bo(e){let t=e.scheduler??Ka,r=e.resolve??ho,n=Math.max(1,e.floorSeconds??Ha),o=e.rng??Math.random,s=i(()=>n+o()*n,"jitteredFloorSeconds"),l=false,u=false,a=null,d=null,c=n,m=0,h=i(()=>{a!==null&&(t.clear(a),a=null);},"clearTimer"),g=i(P=>{u||!l||(c=Math.max(n,P),a=t.set(()=>{a=null,C();},c*1e3));},"schedule"),E=null,T=i(async()=>{if(u)return null;let P=m;e.onFetch?.();let O=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},D;try{D=await r(e.authFor(),O);}catch(A){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:$a(A)}),!u&&P===m&&(e.onSettled?.(),g(s())),null}if(u||P!==m)return null;switch(D.kind){case "updated":d=D.revision,e.update(D.decisions,D.branding??null),g(D.ttlSeconds);break;case "notModified":g(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:D.error.code}),g(s());break;default:g(s());}return e.onSettled?.(),D},"tick"),C=i(()=>{let P=T().finally(()=>{E===P&&(E=null);});return E=P,P},"run");return {start(){l||u||(l=true,C());},prime(){return u?Promise.resolve(null):E??C()},stop(){u||(u=true,m++,h());},refresh(){u||!l||(m++,d=null,h(),C());}}}i(bo,"createEntitlementPoller");var Ka={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function $a(e){return e instanceof Error?e.message:"poll failed"}i($a,"describe");var vo="everfur.notifications.device";var Ro=3e3,_o=Object.freeze([vo]);function Eo(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let s=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),l=[...n].map(d=>{try{return Promise.resolve(d(s))}catch(c){return Promise.reject(c)}}),u=i((d,c)=>{try{o.track("sdk.logout.hookFailed",{reason:d,count:c,totalCount:l.length});}catch{}},"report"),a=Promise.allSettled(l).then(d=>{let c=d.filter(m=>m.status==="rejected").length;c>0&&u("failed",c);});return new Promise(d=>{let c=false,m=i(()=>{c||(c=true,clearTimeout(h),d());},"finish"),h=setTimeout(()=>{c||u("timeout",l.length),m();},Ro);a.then(m,m);})}i(Eo,"startBeforeLogoutHooks");function Co(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,s=r.currentToken();s.catch(()=>{});let l={userRef:t.userRef,currentToken:i(()=>s,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:l,userRef:t.userRef,sessionId:o}}i(Co,"graceAuth");async function So(e,t){if(_o.length===0)return;let r=await Promise.allSettled(_o.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(So,"sweepPerUserKv");function Va(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Va,"compiledDefaultDecisions");function jt(e=Va){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(jt,"createEntitlementStore");function zt(e){return S("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(zt,"notConfiguredError");function wo(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return Fr(r,t===void 0?void 0:{platform:t})}i(wo,"tryResolveClient");function ko(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(ko,"guardTelemetry");function To(e,t){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
12
+ [everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(To,"reportConfigFailure");function Lt(e){return Object.freeze({request(){return Promise.resolve(p(zt(e)))},stream(t,r){let n=N({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(Lt,"refusingTransport");function Po(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(Po,"createInMemoryKv");var xo=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function jp(e,t){return new Nt(e,t)}i(jp,"createEverfurRuntime");var Wa=6e4,Bt=class Bt{constructor(t,r){this.sessionId=st();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new K("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?ko(n.telemetry):Me;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",s=lt(n?.publishableKey),l=n.transport!==void 0,u,a=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(s!==null)u=Lt(s);else if(n.transport!==void 0)u=n.transport;else {let c=wo(n,r?.platform);c.ok?(a=c.config.apiBaseUrl,u=Ur({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(s=c.failure,u=Lt(c.failure));}this.configFailure=s,this.publishableKey=s===null?o:"",this.transport=u,s!==null&&To(s,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??hr,this.upload=n.upload??on,this.uploadTransport=n.uploadTransport??kt,this.imageCache=n.imageCache??xo,this.kv=n.storage??Po(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=s===null?jt():jt(()=>no("sdk_config",ot("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:a},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",Ut(c),()=>this.buildChatController(c),Io),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${Ut(c)}`)?.controller??null,"peekChat"),acquire:i((c,m,h,g)=>this.acquireInternal(c,m,h,g),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=s===null&&(r?.startEntitlementPolling??!l);this.poller=s===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=kr(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-Wa,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return bo({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,s=false){let l=`${this.epoch}|${t}|${r}`,u=this.entries.get(l);if(u)return s||(u.warm?u.warm=false:u.refCount+=1),u.controller;let a=n();return this.entries.set(l,{controller:a,refCount:1,warm:s}),this.destroyers.set(a,o),a}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=En({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=wn(n,{controller:t});return o.then(s=>t.adoptPrompts(s.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=st(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await So(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return Eo({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>Co({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?p(Oo(t)):r(to(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let s={key:n,result:null,promise:this.runPrepare(r).then(l=>(s.result=l,l))};return this.prepared=s,s.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?Oo("prepare"):n===null?null:zt(n),s=this.identity,[l,u,a]=await Promise.all([o?p(o):s===null?_(void 0):s.currentToken().then(()=>_(void 0),()=>p(S("authRejected",{retryable:false}))),o?p(o):this.primeEntitlements(),t===null?void 0:o?p(o):this.primeChat(t)]),d=l.ok?u.ok&&(a?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:l,entitlements:u,...a?{chat:a}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?p(t.error):_(void 0):p(S("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",Ut(r),()=>this.buildChatController(r),Io,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?p(o.cause):_(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(Bt,"EverfurRuntimeImpl");var Nt=Bt;function Ut(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(Ut,"chatScopeKey");function Io(e){e.dispose();}i(Io,"disposeChat");function Oo(e){return S("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Oo,"disposedError");var Mo=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),Ao=Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function Ga(e){let t=Object.prototype.hasOwnProperty.call(Ao,e)?Ao[e]:void 0;if(t!==void 0)return t;let r=e;return Mo.has(r)?r:"parsing"}i(Ga,"normalizeStatus");function Ya(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Ya,"normalizeOrigin");var Xa=zod.z.object({request_id:zod.z.string().min(1),pet_ref:zod.z.string().min(1),status:zod.z.string(),simple_status:zod.z.string().nullish(),simple_status_detail:zod.z.string().nullish(),status_label:zod.z.string().optional(),dispatch_status:zod.z.string().nullish(),can_retry_send:zod.z.boolean().optional(),can_revoke:zod.z.boolean().optional(),can_convert_to_upload:zod.z.boolean().optional(),can_update_clinic_email:zod.z.boolean().optional(),reminder_count:zod.z.number().int().nonnegative().optional(),last_reminder_at:zod.z.string().nullish(),waiting_expectation:zod.z.string().nullish(),document_count:zod.z.number().optional(),held_item_count:zod.z.number().optional(),received_at:zod.z.string().nullish(),parsing_started_at:zod.z.string().nullish(),review_started_at:zod.z.string().nullish(),created_at:zod.z.string().optional(),updated_at:zod.z.string().optional(),source:zod.z.string().nullish().catch(null),action_needed_label:zod.z.string().nullish().catch(null),failure_reason:zod.z.string().nullish().catch(null),failure_code:zod.z.string().nullish().catch(null),recovery_stage:zod.z.string().nullish().catch(null),show_clinic_phone:zod.z.boolean().optional().catch(void 0),clinic_name:zod.z.string().nullish().catch(null),clinic_email:zod.z.string().nullish().catch(null),clinic_phone:zod.z.string().nullish().catch(null),converted_to_upload_at:zod.z.string().nullish().catch(null),request_group_id:zod.z.string().nullish().catch(null)}).passthrough();function Do(e){let t=Xa.safeParse(e);if(!t.success)return null;let r=t.data,n=Qa(r.simple_status),o=n==="requested"&&(r.status==="awaiting_upload"||r.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":n==="parsing"&&(r.simple_status_detail==="in_review"||r.simple_status_detail==="review_email_failed")?"in_review":n??Ga(r.status);return Object.freeze({id:r.request_id,petRef:r.pet_ref,status:o,simpleStatus:n,simpleStatusDetail:r.simple_status_detail??null,statusLabel:r.status_label??"",dispatchStatus:r.dispatch_status??null,canRetrySend:r.can_retry_send===true,canRevoke:r.can_revoke===true,canConvertToUpload:r.can_convert_to_upload===true,canUpdateClinicEmail:r.can_update_clinic_email===true,reminderCount:r.reminder_count??0,lastReminderAt:r.last_reminder_at??null,waitingExpectation:r.waiting_expectation??null,documentCount:Fo(r.document_count,0),heldItemCount:Fo(r.held_item_count,0),receivedAt:r.received_at??null,parsingStartedAt:r.parsing_started_at??null,reviewStartedAt:r.review_started_at??null,createdAt:r.created_at??"",updatedAt:r.updated_at??"",wireStatus:r.status,source:r.source??null,actionNeededLabel:r.action_needed_label??null,failureReason:r.failure_reason??null,failureCode:r.failure_code??null,recoveryStage:r.recovery_stage??null,showClinicPhone:r.show_clinic_phone===true,clinicName:r.clinic_name??null,clinicEmail:r.clinic_email??null,clinicPhone:r.clinic_phone??null,convertedToUploadAt:r.converted_to_upload_at??null,requestGroupId:r.request_group_id??null})}i(Do,"mapRequestView");zod.z.object({request_group_id:zod.z.string().min(1),pet_ref:zod.z.string().min(1),total:zod.z.number().int().nonnegative(),responded:zod.z.number().int().nonnegative(),pending:zod.z.number().int().nonnegative(),members:zod.z.array(zod.z.unknown())});function Qa(e){return !e||e==="awaiting_upload"||e==="in_review"?null:Mo.has(e)?e:null}i(Qa,"normalizeSimpleStatus");zod.z.object({source_doc_id:zod.z.string().min(1),request_id:zod.z.string().min(1)});var Ja=zod.z.object({label:zod.z.string(),value:zod.z.string()}),qt=zod.z.object({key:zod.z.string(),category:zod.z.string().optional(),label:zod.z.string().optional(),value:zod.z.string().nullish(),unit:zod.z.string().nullish(),observed_at:zod.z.string().nullish(),status:zod.z.string().nullish(),origin:zod.z.string().nullish(),canonical_key:zod.z.string().nullish()}),Za=zod.z.object({at:zod.z.string(),value:zod.z.number().nullish(),display:zod.z.string().nullish(),origin:zod.z.string().nullish()}),el=zod.z.object({key:zod.z.string(),label:zod.z.string().optional(),points:zod.z.array(Za).optional()}),tl=zod.z.object({title:zod.z.string(),detail:zod.z.string().nullish(),due_at:zod.z.string().nullish()}),Ht=zod.z.object({doc_id:zod.z.string(),title:zod.z.string().nullish(),page_count:zod.z.number().nullish(),received_at:zod.z.string().nullish()});function jo(e){return Object.freeze({key:e.key,category:e.category??"",label:e.label??e.key,value:e.value??null,unit:e.unit??null,observedAt:e.observed_at??null,status:e.status??null,origin:Ya(e.origin),canonicalKey:e.canonical_key??null})}i(jo,"mapEntityRow");function zo(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(zo,"mapDocumentRow");zod.z.object({identity:zod.z.array(Ja).optional(),entities:zod.z.array(qt).optional(),entity_series:zod.z.array(el).optional(),forward_looking:zod.z.array(tl).optional(),documents:zod.z.array(Ht).optional()});zod.z.object({pet_ref:zod.z.string().optional(),granted:zod.z.boolean().optional(),version:zod.z.string().nullish(),granted_at:zod.z.string().nullish()});function Fo(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(Fo,"numberOr");var Uo=10,Qe=zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Te=i((e,t=1)=>zod.z.string().refine(r=>!L(r)&&[...r].length>=t&&[...r].length<=e),"text"),No=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),rl=zod.z.object({clinicId:Qe.optional(),clinicFreeText:Te(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Te(320,3).refine(e=>!No(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Qe.optional(),signaturePngBase64:zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0)),nl=zod.z.object({petRef:Te(128),ownerName:Te(200).refine(e=>e.trim().length>0&&!No(e)),authorizationVersion:Te(64),clinics:zod.z.array(rl).min(1).max(Uo)}).strict(),ol=zod.z.object({request_group_id:Qe,pet_ref:zod.z.string(),created_count:zod.z.number().int().nonnegative(),failed_count:zod.z.number().int().nonnegative(),results:zod.z.array(zod.z.object({idempotency_key:zod.z.string(),clinic_id:Qe.nullable().optional(),clinic_free_text:zod.z.string().nullable().optional(),created:zod.z.boolean(),request:zod.z.unknown().optional(),failure_code:zod.z.string().nullable().optional(),failure_reason:zod.z.string().nullable().optional()}))});function il(e){let t=e.funnel??$({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!nl.safeParse(r).success)return p(S("validationFailed",{retryable:false}));let n=await t.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:r.petRef,owner_name:r.ownerName,authorization_version:r.authorizationVersion,clinics:r.clinics.map(l=>({...l.clinicId!==void 0?{clinic_id:l.clinicId}:{clinic_free_text:l.clinicFreeText},...l.clinicEmail!==void 0?{clinic_email:l.clinicEmail}:{},...l.signatureId!==void 0?{signature_id:l.signatureId}:{signature_png_base64:l.signaturePngBase64},idempotency_key:l.idempotencyKey}))}});if(!n.ok)return n;let o=ol.safeParse(n.value);if(!o.success||o.data.pet_ref!==r.petRef)return Lo();let s=[];for(let l of o.data.results){let u=l.request===void 0||l.request===null?null:Do(l.request);if(l.created!==(u!==null))return Lo();s.push(Object.freeze({idempotencyKey:l.idempotency_key,clinicId:l.clinic_id??null,clinicFreeText:l.clinic_free_text??null,created:l.created,request:u,failureCode:l.failure_code??null,failureReason:l.failure_reason??null}));}return _(Object.freeze({requestGroupId:o.data.request_group_id,petRef:o.data.pet_ref,results:Object.freeze(s),createdCount:o.data.created_count,failedCount:o.data.failed_count}))}}}i(il,"createRecordsClinicBatchClient");function Lo(){return p(S("internalError",{retryable:false}))}i(Lo,"malformed");var sl="records_consent_required";function al(e){let t=e.raw;if(t===null||typeof t!="object")return null;let r=t,n=typeof r.error=="object"&&r.error!==null?r.error.code:r.code;return typeof n=="string"&&n.length>0?n:null}i(al,"recordsWireCodeOf");function Bo(e){return e===null||e.httpStatus!==409?false:al(e)===sl}i(Bo,"isRecordsConsentRequired");var Kt="value_text",qo=64,Ho=512;function ll(e){return e!==null&&e.httpStatus===409&&!Bo(e)}i(ll,"isFactReviewerLocked");function ul(e){return Object.freeze({[Kt]:e.trim()})}i(ul,"factValueCorrection");var Pe=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:Kt}),Ko=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,$o=/^\d{4}-\d{2}-\d{2}$/;function Vo(e){if(e==null)return "text";let t=e.trim();return Ko.test(t)?"num":$o.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(Vo,"inferFactValueKind");function dl(e,t){let r=t.trim(),n=Vo(e);if(n==="num"&&Ko.test(r)){let o=Number(r);if(Number.isFinite(o))return Object.freeze({[Pe.num]:o})}return n==="date"&&$o.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[Pe.date]:r}):Object.freeze(n==="bool"&&(r==="true"||r==="false")?{[Pe.bool]:r==="true"}:{[Pe.text]:r})}i(dl,"factCorrectionFor");var k=zod.z.string().nullish(),Je=zod.z.number().nullish(),cl=zod.z.object({collected_at:k,at:k,value:Je,unit:k,qualitative_result:k,ref_low:Je,ref_high:Je,status:k,source_clinic:k,source_doc_id:k,doc_id:k,reviewed:zod.z.boolean().nullish()}),pl=zod.z.object({collected_at:k,at:k,value:Je,unit:k,qualitative_result:k,status:k}),fl=zod.z.object({marker_id:zod.z.string().min(1),canonical_name:k,name:k,loinc_code:k,canonical_unit:k,unit:k,panel_name:k,panel:k,meaning_text:k,meaning:k,latest:pl.nullish(),trajectory:k,points:zod.z.array(cl).optional()}),ml=zod.z.object({total_markers:zod.z.number().int().nonnegative(),in_range_count:zod.z.number().int().nonnegative(),out_of_range_count:zod.z.number().int().nonnegative(),unknown_count:zod.z.number().int().nonnegative()}),yl=zod.z.object({markers:zod.z.array(fl).optional(),summary:ml.nullish(),disclaimer:zod.z.string().optional(),featured_marker_id:k});function gl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(gl,"isObject");function Wo(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(Wo,"withheldMarkers");function $t(e,t){let r=gl(t)?t:{},n=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Wo(n);let o=yl.safeParse(r);if(!o.success)return Wo(n);let s=o.data,l=i(a=>Object.freeze({at:a.collected_at??a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,sourceClinic:a.source_clinic??null,docId:a.source_doc_id??a.doc_id??null,reviewed:a.reviewed===true}),"point"),u=(s.markers??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.canonical_name??a.name??a.marker_id,loincCode:a.loinc_code??null,unit:a.canonical_unit??a.unit??null,panel:a.panel_name??a.panel??null,meaning:a.meaning_text??a.meaning??null,latest:a.latest?Object.freeze({at:a.latest.collected_at??a.latest.at??null,value:a.latest.value??null,unit:a.latest.unit??null,qualitativeResult:a.latest.qualitative_result??null,status:a.latest.status??null}):null,trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(l))}));return Object.freeze({petRef:n,withheld:false,markers:Object.freeze(u),summary:s.summary?Object.freeze({totalMarkers:s.summary.total_markers,inRangeCount:s.summary.in_range_count,outOfRangeCount:s.summary.out_of_range_count,unknownCount:s.summary.unknown_count}):null,disclaimer:s.disclaimer??"",featuredMarkerId:s.featured_marker_id??null})}i($t,"mapRecordMarkers");var hl=zod.z.string().min(1).refine(e=>e.startsWith("https://")),bl=zod.z.object({source_doc_id:zod.z.string().min(1),file_name:zod.z.string().nullish(),doc_format:zod.z.string().nullish(),byte_size:zod.z.number().int().nonnegative().nullish(),received_at:zod.z.string().nullish(),download_url:hl,expires_in_seconds:zod.z.number().int().nonnegative().nullish()}),vl=zod.z.object({items:zod.z.array(zod.z.unknown()).optional()});function Go(e){let t=vl.safeParse(e);if(!t.success)return null;let r=[];for(let n of t.data.items??[]){let o=bl.safeParse(n);o.success&&r.push(Object.freeze({sourceDocId:o.data.source_doc_id,fileName:o.data.file_name??null,docFormat:o.data.doc_format??null,byteSize:o.data.byte_size??null,receivedAt:o.data.received_at??null,downloadUrl:o.data.download_url,expiresInSeconds:o.data.expires_in_seconds??0}));}return Object.freeze(r)}i(Go,"mapRequestDocuments");var _l=zod.z.string().min(1).refine(e=>e.startsWith("https://")),xe=zod.z.string().nullish(),Rl=zod.z.object({share_id:zod.z.string().min(1),share_url:zod.z.string().min(1),expires_at:xe}),El=zod.z.object({shares:zod.z.array(zod.z.object({share_id:zod.z.string().min(1),expires_at:xe,created_at:xe,view_count:zod.z.number().int().nonnegative().nullish(),last_viewed_at:xe})).optional()}),Cl=zod.z.object({download_url:_l,expires_at:xe});function Yo(e,t){let r=e.trim();if(r.length===0)return null;try{let n=/^[a-z][a-z0-9+.-]*:/i.test(r)?new URL(r):t!==void 0?new URL(r,t):null;return n===null||n.protocol!=="https:"?null:n.toString()}catch{return null}}i(Yo,"resolveShareUrl");function Vt(e,t){let r=Rl.safeParse(e);if(!r.success)return null;let n=Yo(r.data.share_url,t);return n===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:n,expiresAt:r.data.expires_at??null})}i(Vt,"mapRecordShareLink");function Wt(e){let t=El.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null}))):null}i(Wt,"mapRecordShareList");function Gt(e){let t=Cl.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(Gt,"mapRecordPdfLink");var Sl=zod.z.object({signatures:zod.z.array(zod.z.object({signature_id:zod.z.string().min(1),preview_url:zod.z.string().min(1).refine(e=>e.startsWith("https://")),created_at:zod.z.string().nullish()})).optional()});function Yt(e){let t=Sl.safeParse(e);return t.success?Object.freeze((t.data.signatures??[]).map(r=>Object.freeze({signatureId:r.signature_id,previewUrl:r.preview_url,createdAt:r.created_at??null}))):null}i(Yt,"mapSignatureSuggestions");var b=zod.z.string().nullish(),Ie=zod.z.number().nullish(),wl=zod.z.object({at:b,value:Ie,unit:b,qualitative_result:b,ref_low:Ie,ref_high:Ie,status:b,doc_id:b}),kl=zod.z.object({marker_id:zod.z.string(),name:zod.z.string(),loinc_code:b,unit:b,panel:b,meaning:b,latest:zod.z.object({at:b,value:Ie,unit:b,qualitative_result:b,status:b}).nullish(),trajectory:b,points:zod.z.array(wl).optional()}),Tl=zod.z.object({encounter_id:zod.z.string(),date:b,type:b,clinic_name:b,veterinarian:b,doc_id:b}),Pl=zod.z.object({note_id:zod.z.string(),encounter_id:b,observed_on:b,sections:zod.z.array(zod.z.object({section:zod.z.string(),text:zod.z.string()})).optional()}),xl=zod.z.object({exam_id:zod.z.string(),encounter_id:b,observed_on:b,doc_id:b,systems:zod.z.record(zod.z.object({finding_status:b,finding:b})).optional()}),Il=zod.z.object({has_lab_history:zod.z.boolean().optional(),has_vaccination_history:zod.z.boolean().optional(),has_weight_history:zod.z.boolean().optional(),has_vitals_history:zod.z.boolean().optional(),has_physical_exam_history:zod.z.boolean().optional(),has_procedure_history:zod.z.boolean().optional(),has_genetic_history:zod.z.boolean().optional(),has_reproductive_history:zod.z.boolean().optional(),has_parasite_prevention_history:zod.z.boolean().optional(),earliest_record_at:b,latest_record_at:b,documents_ingested:zod.z.number().int().nonnegative().optional(),documents_in_review:zod.z.number().int().nonnegative().optional(),entities_pending_review:zod.z.record(zod.z.number().int().nonnegative()).optional(),held_total:zod.z.number().int().nonnegative().optional()}),Ol=zod.z.object({conflict_id:zod.z.string(),entity_type:zod.z.string(),field:b,severity:b,candidates:zod.z.array(zod.z.object({value:zod.z.string(),source_doc_id:b,doc_id:b,collected_at:b})).optional()}),Al=zod.z.object({lab_results:zod.z.array(kl).optional(),encounters:zod.z.array(Tl).optional(),clinician_notes:zod.z.array(Pl).optional(),physical_exams:zod.z.array(xl).optional(),completeness:Il.nullish(),conflicts:zod.z.array(Ol).optional()}),Fl=zod.z.object({visits:zod.z.array(zod.z.object({visit_id:zod.z.string(),visit_date:b,veterinarian:b,summary:b,doc_id:b})),vaccines:zod.z.array(zod.z.object({vaccine_id:zod.z.string(),product:b,lot:b,administered_on:b,expires_on:b,doc_id:b})),weights:zod.z.array(zod.z.object({weight_id:zod.z.string(),observed_on:b,weight_kg:Ie,doc_id:b})),medications:zod.z.array(zod.z.object({medication_id:zod.z.string(),drug_name:b,dose:b,route:b,frequency:b,sig:b,rx_number:b,started_on:b,stopped_on:b,doc_id:b})),disclaimer:zod.z.string().optional()}),Ml=zod.z.object({document:Ht,contributions:zod.z.array(qt),contribution_count:zod.z.number().int().nonnegative().optional()});function Qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Qt,"isObject");function Jt(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(Jt,"petOf");function Xt(e,t){return Object.freeze({petRef:e,available:false,withheld:t,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(Xt,"emptyDepth");function Qo(e,t){let r=Qt(t)?t:{},n=Jt(r,e);if(r.withheld===true)return Xt(n,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return Xt(n,false);let s=Al.safeParse(r);if(!s.success)return Xt(n,true);let l=s.data,u=i(a=>Object.freeze({at:a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,docId:a.doc_id??null}),"point");return Object.freeze({petRef:n,available:true,withheld:false,labResults:Object.freeze((l.lab_results??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.name,loincCode:a.loinc_code??null,unit:a.unit??null,panel:a.panel??null,meaning:a.meaning??null,latest:Object.freeze({at:a.latest?.at??null,value:a.latest?.value??null,unit:a.latest?.unit??null,qualitativeResult:a.latest?.qualitative_result??null,status:a.latest?.status??null}),trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(u))}))),encounters:Object.freeze((l.encounters??[]).map(a=>Object.freeze({encounterId:a.encounter_id,date:a.date??null,type:a.type??null,clinicName:a.clinic_name??null,veterinarian:a.veterinarian??null,docId:a.doc_id??null}))),clinicianNotes:Object.freeze((l.clinician_notes??[]).map(a=>Object.freeze({noteId:a.note_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,sections:Object.freeze((a.sections??[]).map(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((l.physical_exams??[]).map(a=>Object.freeze({examId:a.exam_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,docId:a.doc_id??null,systems:Object.freeze(Object.entries(a.systems??{}).map(([d,c])=>Object.freeze({system:d,findingStatus:c.finding_status??null,finding:c.finding??null})))}))),completeness:l.completeness?Object.freeze({hasLabHistory:l.completeness.has_lab_history===true,hasVaccinationHistory:l.completeness.has_vaccination_history===true,hasWeightHistory:l.completeness.has_weight_history===true,hasVitalsHistory:l.completeness.has_vitals_history===true,hasPhysicalExamHistory:l.completeness.has_physical_exam_history===true,hasProcedureHistory:l.completeness.has_procedure_history===true,hasGeneticHistory:l.completeness.has_genetic_history===true,hasReproductiveHistory:l.completeness.has_reproductive_history===true,hasParasitePreventionHistory:l.completeness.has_parasite_prevention_history===true,earliestRecordAt:l.completeness.earliest_record_at??null,latestRecordAt:l.completeness.latest_record_at??null,documentsIngested:l.completeness.documents_ingested??0,documentsInReview:l.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...l.completeness.entities_pending_review??{}}),heldTotal:l.completeness.held_total??0}):null,conflicts:Object.freeze((l.conflicts??[]).map(a=>Object.freeze({conflictId:a.conflict_id,entityType:a.entity_type,field:a.field??null,severity:a.severity??"needs_review",candidates:Object.freeze((a.candidates??[]).map(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(Qo,"mapRecordDepth");function Xo(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(Xo,"withheldTimeline");function Jo(e,t){let r=Qt(t)?t:{},n=Jt(r,e);if(r.withheld===true)return Xo(n);let o=Fl.safeParse(r);if(!o.success)return Xo(n);let s=o.data,l=s.visits.map(c=>Object.freeze({visitId:c.visit_id,visitDate:c.visit_date??null,veterinarian:c.veterinarian??null,summary:c.summary??null,docId:c.doc_id??null})),u=s.vaccines.map(c=>Object.freeze({vaccineId:c.vaccine_id,product:c.product??null,lot:c.lot??null,administeredOn:c.administered_on??null,expiresOn:c.expires_on??null,docId:c.doc_id??null})),a=s.weights.map(c=>Object.freeze({weightId:c.weight_id,observedOn:c.observed_on??null,weightKg:c.weight_kg??null,docId:c.doc_id??null})),d=s.medications.map(c=>Object.freeze({medicationId:c.medication_id,drugName:c.drug_name??null,dose:c.dose??null,route:c.route??null,frequency:c.frequency??null,sig:c.sig??null,rxNumber:c.rx_number??null,startedOn:c.started_on??null,stoppedOn:c.stopped_on??null,docId:c.doc_id??null}));return Object.freeze({petRef:n,withheld:false,isEmpty:l.length===0&&u.length===0&&a.length===0&&d.length===0,visits:Object.freeze(l),vaccines:Object.freeze(u),weights:Object.freeze(a),medications:Object.freeze(d),disclaimer:s.disclaimer??""})}i(Jo,"mapRecordsTimeline");function Zo(e,t){let r=Qt(t)?t:{},n=Jt(r,e),o=i(()=>Object.freeze({petRef:n,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(r.withheld===true)return o();let s=Ml.safeParse(r);if(!s.success)return o();let l=Object.freeze(s.data.contributions.map(jo));return Object.freeze({petRef:n,withheld:false,document:zo(s.data.document),contributions:l,contributionCount:s.data.contribution_count??l.length})}i(Zo,"mapDocumentContributions");var Dl="/widget/v1/records/pets";function jl(e){let t=e.funnel??$({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!L(a)&&[...a].length<=d,"segment"),n=i(async(a,d,c,m)=>{if(!r(d,oe))return ne();let h=await t.send(a,{method:"GET",path:c});if(!h.ok)return h;let g=m(h.value);return g.petRef===d?_(g):p(S("internalError",{retryable:false}))},"read"),o=i(a=>`${Dl}/${encodeURIComponent(a)}`,"pet"),s=i(a=>`${o(a)}/everfur_record`,"record"),l=i(async(a,d,c)=>{let m=await t.send(a,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!m.ok)return m;let h=c(m.value);return h===null?p(S("internalError",{retryable:false})):_(h)},"parsed"),u=i((a,d)=>!r(a.entityType,qo)||!r(a.canonicalKey,Ho)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,Tn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:a.entityType,canonical_key:a.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...a.idempotencyKey!==void 0?{idempotency_key:a.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(a=>n("records.depth.record",a,`${o(a)}/record`,d=>Qo(a,d)),"getRecordDepth"),getTimeline:i(a=>n("records.depth.timeline",a,`${o(a)}/timeline`,d=>Jo(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?n("records.depth.contributions",a,`${o(a)}/documents/${encodeURIComponent(d)}/contributions`,c=>Zo(a,c)):ne()},getMarkers:i(a=>n("records.depth.markers",a,`${o(a)}/markers`,d=>$t(a,d)),"getMarkers"),createShare(a){return r(a,oe)?l("records.share.create",{method:"POST",path:`${s(a)}/share`},d=>Vt(d,e.apiBaseUrl)):ne()},listShares(a){return r(a,oe)?l("records.share.list",{method:"GET",path:`${s(a)}/shares`},Wt):ne()},async revokeShare(a,d){if(!r(a,oe)||!r(d,64))return ne();let c=await t.send("records.share.revoke",{method:"DELETE",path:`${s(a)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return c.ok?_(void 0):c},getPdfLink(a){return r(a,oe)?l("records.pdf.link",{method:"GET",path:`${s(a)}/pdf-link`},Gt):ne()},async editFact(a,d){let c=r(a,oe)?u(d,d.correctedFields):null;if(c===null)return ne();let m=await t.send("records.fact.edit",{method:"POST",path:`${s(a)}/facts/edit`,body:c},{idempotent:false,maxAttempts:1});return m.ok?_(void 0):m},async removeFact(a,d){let c=r(a,oe)?u(d):null;if(c===null)return ne();let m=await t.send("records.fact.remove",{method:"POST",path:`${s(a)}/facts/remove`,body:c},{idempotent:false,maxAttempts:1});return m.ok?_(void 0):m},listRequestDocuments(a){return r(a,64)?l("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(a)}/documents`},Go):ne()},listAuthorizationSignatures:i(()=>l("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},Yt),"listAuthorizationSignatures")}}i(jl,"createRecordsDepthClient");function ne(){return Promise.resolve(p(S("validationFailed",{retryable:false})))}i(ne,"invalid");var Ae=Object.freeze({width:360,height:120});function ni(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(ni,"blank");function oi(e,t,r,n){for(let o=-n;o<=n;o+=1)for(let s=-n;s<=n;s+=1){if(s*s+o*o>n*n+n)continue;let l=t+s,u=r+o;l<0||u<0||l>=e.width||u>=e.height||(e.pixels[u*e.width+l]=1);}}i(oi,"stamp");var zl=16384;function Ll(e,t){let[r,n]=e;if(!Number.isFinite(r)||!Number.isFinite(n))return null;let o=Math.min(2*t.width,Math.max(-t.width,Math.round(r))),s=Math.min(2*t.height,Math.max(-t.height,Math.round(n)));return [o,s]}i(Ll,"padPoint");function Ul(e,t,r,n,o){let[s,l]=t,[u,a]=r,d=Math.abs(u-s),c=-Math.abs(a-l),m=s<u?1:-1,h=l<a?1:-1,g=d+c,E=0;for(;E<o&&(oi(e,s,l,n),E+=1,!(s===u&&l===a));){let T=2*g;T>=c&&(g+=c,s+=m),T<=d&&(g+=d,l+=h);}return E}i(Ul,"line");function Nl(e,t=1){let r=ni(Ae.width,Ae.height);for(let n of e){let o=[];for(let l of n){let u=Ll(l,r);u!==null&&o.push(u);}if(o.length===0)continue;if(o.length===1){let[l,u]=o[0];oi(r,l,u,t);continue}let s=zl;for(let l=1;l<o.length&&s>0;l+=1)s-=Ul(r,o[l-1],o[l],t,s);}return r}i(Nl,"rasterizeStrokes");var Bl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",ql="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",Hl="0123456789abcdefghijklmnopqrstuv",or=5,ir=7,Zt=or+1;function Kl(e,t){let r=Bl.indexOf(e);return r<0?0:Hl.indexOf(ql.charAt(r*ir+t))}i(Kl,"glyphRow");function $l(e){let t=ni(Ae.width,Ae.height),r=e.trim();if(r.length===0)return t;let n=[...r],o=4;for(;o>1&&(n.length*Zt-1)*o>t.width-8;)o-=1;let s=(n.length*Zt-1)*o,l=Math.max(0,Math.floor((t.width-s)/2)),u=Math.floor((t.height-ir*o)/2);return n.forEach((a,d)=>{let c=l+d*Zt*o;for(let m=0;m<ir;m+=1){let h=Kl(a,m);for(let g=0;g<or;g+=1)if((h>>or-1-g&1)!==0)for(let E=0;E<o;E+=1)for(let T=0;T<o;T+=1){let C=c+g*o+T,P=u+m*o+E;C<t.width&&P<t.height&&(t.pixels[P*t.width+C]=1);}}}),t}i($l,"rasterizeTypedName");var lr=class lr{constructor(){this.bytes=[];this.acc=0;this.count=0;}writeBits(t,r){for(this.acc|=t<<this.count,this.count+=r;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8;}writeCode(t,r){let n=0;for(let o=0;o<r;o+=1)n=n<<1|t>>o&1;this.writeBits(n,r);}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};i(lr,"BitWriter");var sr=lr;function ar(e,t){t<144?e.writeCode(48+t,8):t<256?e.writeCode(400+(t-144),9):t<280?e.writeCode(t-256,7):e.writeCode(192+(t-280),8);}i(ar,"writeLiteral");var er=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],ei=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],tr=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ti=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function Vl(e,t,r){let n=er.length-1;for(;er[n]>t;)n-=1;ar(e,257+n),ei[n]>0&&e.writeBits(t-er[n],ei[n]);let o=tr.length-1;for(;tr[o]>r;)o-=1;e.writeCode(o,5),ti[o]>0&&e.writeBits(r-tr[o],ti[o]);}i(Vl,"writeMatch");var Wl=32768,rr=3,Gl=258,ri=15,Yl=64;function Xl(e){let t=new sr;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<ri).fill(-1),n=new Int32Array(e.length).fill(-1),o=i(u=>(e[u]<<10^e[u+1]<<5^e[u+2])&(1<<ri)-1,"hashAt"),s=i(u=>{if(u+rr>e.length)return;let a=o(u);n[u]=r[a],r[a]=u;},"insert"),l=0;for(;l<e.length;){let u=0,a=0;if(l+rr<=e.length){let d=r[o(l)],c=0,m=Math.min(Gl,e.length-l);for(;d>=0&&c<Yl&&l-d<=Wl;){let h=0;for(;h<m&&e[d+h]===e[l+h];)h+=1;if(h>u&&(u=h,a=l-d,h===m))break;d=n[d],c+=1;}}if(u>=rr){Vl(t,u,a);for(let d=0;d<u;d+=1)s(l+d);l+=u;}else ar(t,e[l]),s(l),l+=1;}return ar(t,256),t.finish()}i(Xl,"deflate");function Ql(e){let t=1,r=0;for(let n of e)t=(t+n)%65521,r=(r+t)%65521;return (r<<16|t)>>>0}i(Ql,"adler32");var Ze=null;function Jl(e){if(Ze===null){Ze=new Uint32Array(256);for(let r=0;r<256;r+=1){let n=r;for(let o=0;o<8;o+=1)n=n&1?3988292384^n>>>1:n>>>1;Ze[r]=n>>>0;}}let t=4294967295;for(let r of e)t=Ze[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(Jl,"crc32");function Oe(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(Oe,"u32");function nr(e,t){let r=Uint8Array.from([...e].map(o=>o.charCodeAt(0))),n=new Uint8Array(r.length+t.length);return n.set(r,0),n.set(t,r.length),[...Oe(t.length),...n,...Oe(Jl(n))]}i(nr,"chunk");var et="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Zl(e){let t="";for(let r=0;r<e.length;r+=3){let n=e[r],o=r+1<e.length?e[r+1]:0,s=r+2<e.length?e[r+2]:0,l=n<<16|o<<8|s;t+=et.charAt(l>>18&63)+et.charAt(l>>12&63),t+=r+1<e.length?et.charAt(l>>6&63):"=",t+=r+2<e.length?et.charAt(l&63):"=";}return t}i(Zl,"toBase64");function eu(e){let{width:t,height:r,pixels:n}=e,o=Math.ceil(t/8)+1,s=new Uint8Array(o*r);for(let c=0;c<r;c+=1){let m=c*o;s[m]=0,s.fill(255,m+1,m+o);for(let h=0;h<t;h+=1)if(n[c*t+h]===1){let g=m+1+(h>>3);s[g]=s[g]&~(128>>(h&7));}}let l=Xl(s),u=new Uint8Array(2+l.length+4);u[0]=120,u[1]=1,u.set(l,2),u.set(Oe(Ql(s)),2+l.length);let a=Uint8Array.from([...Oe(t),...Oe(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...nr("IHDR",a),...nr("IDAT",u),...nr("IEND",new Uint8Array(0))]);return Zl(d)}i(eu,"encodeSignaturePng");
13
+ exports.ATTACHMENT_ACCEPT=dc;exports.ATTACHMENT_BACKOFF_MS=Qs;exports.ATTACHMENT_INITIATE_PATH=Ns;exports.ATTACHMENT_MAX_ATTEMPTS=Xs;exports.ATTACHMENT_MIME_TYPES=Ls;exports.ATTACHMENT_QUEUE_CONCURRENCY=Ys;exports.CHAT_FEEDBACK_TYPES=_t;exports.CHECKIN_ANSWERABLE_STATUS=he;exports.FACT_FIELD_BY_KIND=Pe;exports.FACT_VALUE_FIELD=Kt;exports.FEEDBACK_NOTES_MAX_CHARS=Rt;exports.LOGOUT_HOOK_BUDGET_MS=Ro;exports.MAX_ATTACHMENTS_PER_MESSAGE=Us;exports.MAX_ATTACHMENT_BYTES=xn;exports.MAX_FILENAME_LENGTH=Ee;exports.MAX_IMAGE_KEYS_PER_MESSAGE=Ke;exports.MESSAGE_MAX_CHARS=Et;exports.MIN_POLL_INTERVAL_SECONDS=Ha;exports.NULL_SECURE_STORE=iu;exports.RECORDS_CLINIC_BATCH_MAX=Uo;exports.SIGNATURE_CANVAS=Ae;exports.attachmentSize=Hs;exports.bootstrapChat=wn;exports.createAttachmentQueue=pc;exports.createChatController=En;exports.createEntitlementPoller=bo;exports.createEverfurRuntime=jp;exports.createRecordsClinicBatchClient=il;exports.createRecordsDepthClient=jl;exports.defaultErrorPolicy=gr;exports.encodeSignaturePng=eu;exports.factCorrectionFor=dl;exports.factValueCorrection=ul;exports.formatBytes=cc;exports.inferFactValueKind=Vo;exports.initiateAttachmentUpload=Ws;exports.isAttachmentMime=Bs;exports.isCheckinSettled=xs;exports.isFactReviewerLocked=ll;exports.mapDocumentContributions=Zo;exports.mapRecordDepth=Qo;exports.mapRecordMarkers=$t;exports.mapRecordPdfLink=Gt;exports.mapRecordShareLink=Vt;exports.mapRecordShareList=Wt;exports.mapRecordsTimeline=Jo;exports.mapSignatureSuggestions=Yt;exports.noopTelemetry=Me;exports.optionalModule=Eu;exports.rasterizeStrokes=Nl;exports.rasterizeTypedName=$l;exports.resolveShareUrl=Yo;exports.sanitizeFilename=qs;exports.unavailableCamera=hr;exports.uploadAttachmentBytes=Gs;exports.validateAttachment=Ks;