@everfur/sdk 0.1.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 (89) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/LICENSE +21 -0
  3. package/README.md +161 -0
  4. package/animations/package.json +8 -0
  5. package/chat/package.json +8 -0
  6. package/client/package.json +8 -0
  7. package/core/package.json +8 -0
  8. package/dist/CameraPort-Cv31Pz7g.d.cts +29 -0
  9. package/dist/CameraPort-Cv31Pz7g.d.ts +29 -0
  10. package/dist/ChatController-CKdBvPj2.d.ts +146 -0
  11. package/dist/ChatController-CpUMvvZf.d.cts +146 -0
  12. package/dist/EverfurResult-D92-uL82.d.cts +240 -0
  13. package/dist/EverfurResult-D92-uL82.d.ts +240 -0
  14. package/dist/FilePort-BabWrv7I.d.cts +22 -0
  15. package/dist/FilePort-BabWrv7I.d.ts +22 -0
  16. package/dist/PhotoController-BItt5M7u.d.cts +43 -0
  17. package/dist/PhotoController-D8zMTdcW.d.ts +43 -0
  18. package/dist/TelemetryPort-BDNr00hu.d.cts +12 -0
  19. package/dist/TelemetryPort-BDNr00hu.d.ts +12 -0
  20. package/dist/animations/index.cjs +1997 -0
  21. package/dist/animations/index.d.cts +517 -0
  22. package/dist/animations/index.d.ts +517 -0
  23. package/dist/animations/index.js +1972 -0
  24. package/dist/cacheEpoch-DknKn3S0.d.cts +36 -0
  25. package/dist/cacheEpoch-DknKn3S0.d.ts +36 -0
  26. package/dist/chat/index.cjs +1170 -0
  27. package/dist/chat/index.d.cts +59 -0
  28. package/dist/chat/index.d.ts +59 -0
  29. package/dist/chat/index.js +1167 -0
  30. package/dist/client/index.cjs +2317 -0
  31. package/dist/client/index.d.cts +65 -0
  32. package/dist/client/index.d.ts +65 -0
  33. package/dist/client/index.js +2217 -0
  34. package/dist/config-BSjBdxrZ.d.cts +501 -0
  35. package/dist/config-CiJ0PVBB.d.ts +501 -0
  36. package/dist/core/index.cjs +3175 -0
  37. package/dist/core/index.d.cts +70 -0
  38. package/dist/core/index.d.ts +70 -0
  39. package/dist/core/index.js +3163 -0
  40. package/dist/identity-Brl-lDd6.d.cts +91 -0
  41. package/dist/identity-DK9zORrG.d.ts +91 -0
  42. package/dist/ids-CJ1S6adf.d.cts +46 -0
  43. package/dist/ids-CJ1S6adf.d.ts +46 -0
  44. package/dist/index.cjs +4488 -0
  45. package/dist/index.d.cts +156 -0
  46. package/dist/index.d.ts +156 -0
  47. package/dist/index.js +4464 -0
  48. package/dist/petsRepository-BEGb97M9.d.cts +326 -0
  49. package/dist/petsRepository-Bu18r2kK.d.ts +326 -0
  50. package/dist/photo/index.cjs +2189 -0
  51. package/dist/photo/index.d.cts +43 -0
  52. package/dist/photo/index.d.ts +43 -0
  53. package/dist/photo/index.js +2186 -0
  54. package/dist/projection-CeIUsbSk.d.cts +8 -0
  55. package/dist/projection-CeIUsbSk.d.ts +8 -0
  56. package/dist/records/index.cjs +2840 -0
  57. package/dist/records/index.d.cts +224 -0
  58. package/dist/records/index.d.ts +224 -0
  59. package/dist/records/index.js +2834 -0
  60. package/dist/requestFunnel-DuUH-kAe.d.cts +28 -0
  61. package/dist/requestFunnel-dio5OmR9.d.ts +28 -0
  62. package/dist/resolve-Dq_4_agU.d.cts +86 -0
  63. package/dist/resolve-Dq_4_agU.d.ts +86 -0
  64. package/dist/runtime-BgQnA594.d.cts +349 -0
  65. package/dist/runtime-CBA-LvdM.d.ts +349 -0
  66. package/dist/server/index.cjs +533 -0
  67. package/dist/server/index.d.cts +48 -0
  68. package/dist/server/index.d.ts +48 -0
  69. package/dist/server/index.js +530 -0
  70. package/dist/testing/index.cjs +825 -0
  71. package/dist/testing/index.d.cts +113 -0
  72. package/dist/testing/index.d.ts +113 -0
  73. package/dist/testing/index.js +822 -0
  74. package/dist/testing/rn/index.cjs +449 -0
  75. package/dist/testing/rn/index.d.cts +49 -0
  76. package/dist/testing/rn/index.d.ts +49 -0
  77. package/dist/testing/rn/index.js +444 -0
  78. package/dist/video/index.cjs +1941 -0
  79. package/dist/video/index.d.cts +66 -0
  80. package/dist/video/index.d.ts +66 -0
  81. package/dist/video/index.js +1938 -0
  82. package/package.json +311 -0
  83. package/photo/package.json +8 -0
  84. package/records/package.json +8 -0
  85. package/server/device-blocked.cjs +15 -0
  86. package/server/package.json +9 -0
  87. package/testing/package.json +8 -0
  88. package/testing/rn/package.json +8 -0
  89. package/video/package.json +8 -0
@@ -0,0 +1,1938 @@
1
+ import { createContext, useState, useEffect, useCallback, useSyncExternalStore, useMemo, useContext } from 'react';
2
+ import 'react-native-safe-area-context';
3
+ import { View, ActivityIndicator, Pressable, Text, ScrollView, StyleSheet } from 'react-native';
4
+ import { jsx, jsxs } from 'react/jsx-runtime';
5
+
6
+ // src/rn/video/useVideo.ts
7
+ var CONTRACT_RETRYABILITY = Object.freeze([
8
+ Object.freeze({ wireCode: "AccessDeniedException", envelope: "http_envelope", httpStatus: 403, retryable: false }),
9
+ Object.freeze({ wireCode: "AuthorizationException", envelope: "http_envelope", httpStatus: 401, retryable: false }),
10
+ Object.freeze({ wireCode: "ConflictException", envelope: "http_envelope", httpStatus: 409, retryable: true }),
11
+ Object.freeze({ wireCode: "DAILY_QUOTA_EXCEEDED", envelope: "http_envelope", httpStatus: 429, retryable: true }),
12
+ Object.freeze({ wireCode: "IDEMPOTENCY_KEY_IN_FLIGHT", envelope: "http_envelope", httpStatus: 409, retryable: true }),
13
+ Object.freeze({ wireCode: "IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST", envelope: "http_envelope", httpStatus: 409, retryable: false }),
14
+ Object.freeze({ wireCode: "InternalFailureException", envelope: "http_envelope", httpStatus: 500, retryable: true }),
15
+ Object.freeze({ wireCode: "NotImplementedException", envelope: "http_envelope", httpStatus: 501, retryable: false }),
16
+ Object.freeze({ wireCode: "PaymentRequiredException", envelope: "http_envelope", httpStatus: 402, retryable: false }),
17
+ Object.freeze({ wireCode: "ResourceNotFoundException", envelope: "http_envelope", httpStatus: 404, retryable: false }),
18
+ Object.freeze({ wireCode: "ServiceUnavailableException", envelope: "http_envelope", httpStatus: 503, retryable: true }),
19
+ Object.freeze({ wireCode: "TIER_UPGRADE_REQUIRED", envelope: "http_envelope", httpStatus: 402, retryable: false }),
20
+ Object.freeze({ wireCode: "ThrottlingException", envelope: "http_envelope", httpStatus: 429, retryable: true }),
21
+ Object.freeze({ wireCode: "ValidationException", envelope: "http_envelope", httpStatus: 400, retryable: false }),
22
+ Object.freeze({ wireCode: "accessDenied", envelope: "http_envelope", httpStatus: 403, retryable: false }),
23
+ Object.freeze({ wireCode: "authExpired", envelope: "http_envelope", httpStatus: 401, retryable: true }),
24
+ Object.freeze({ wireCode: "internal_error", envelope: "sse_frame", httpStatus: 200, retryable: false }),
25
+ Object.freeze({ wireCode: "invalidRequest", envelope: "http_envelope", httpStatus: 400, retryable: false }),
26
+ Object.freeze({ wireCode: "not_found", envelope: "sse_frame", httpStatus: 200, retryable: false }),
27
+ Object.freeze({ wireCode: "session_required", envelope: "http_envelope", httpStatus: 403, retryable: false }),
28
+ Object.freeze({ wireCode: "timeout", envelope: "sse_frame", httpStatus: 200, retryable: true }),
29
+ Object.freeze({ wireCode: "unavailable", envelope: "http_envelope", httpStatus: 503, retryable: true })
30
+ ]);
31
+ Object.freeze(
32
+ CONTRACT_RETRYABILITY.map((row) => row.wireCode)
33
+ );
34
+
35
+ // src/client/errors/contract.ts
36
+ var NORMALIZED_FOLD = Object.freeze({
37
+ // the default status-mapped envelope
38
+ ValidationException: "validationFailed",
39
+ AuthorizationException: "authRejected",
40
+ PaymentRequiredException: "paymentRequired",
41
+ AccessDeniedException: "accessDenied",
42
+ ResourceNotFoundException: "resourceNotFound",
43
+ ConflictException: "conflict",
44
+ ThrottlingException: "rateLimited",
45
+ InternalFailureException: "internalError",
46
+ NotImplementedException: "notImplemented",
47
+ ServiceUnavailableException: "serviceUnavailable",
48
+ // dict-detail codes on the widget surface
49
+ authExpired: "authExpired",
50
+ unavailable: "serviceUnavailable",
51
+ session_required: "sessionRequired",
52
+ accessDenied: "accessDenied",
53
+ invalidRequest: "sdkUpdateRequired",
54
+ // typed codes
55
+ IDEMPOTENCY_KEY_IN_FLIGHT: "idempotencyInFlight",
56
+ IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST: "idempotencyConflict",
57
+ DAILY_QUOTA_EXCEEDED: "quotaExceeded",
58
+ TIER_UPGRADE_REQUIRED: "paymentRequired",
59
+ // SSE error frames
60
+ not_found: "conversationNotFound",
61
+ timeout: "streamTimeout",
62
+ internal_error: "internalError"
63
+ });
64
+ var CONTRACT_ERROR_ROWS = Object.freeze(
65
+ CONTRACT_RETRYABILITY.map(
66
+ (generated) => Object.freeze({
67
+ wireCode: generated.wireCode,
68
+ envelope: generated.envelope,
69
+ retryable: generated.retryable,
70
+ normalized: NORMALIZED_FOLD[generated.wireCode]
71
+ })
72
+ )
73
+ );
74
+ var BY_UPPER = new Map(
75
+ CONTRACT_ERROR_ROWS.map((r) => [r.wireCode.toUpperCase(), r])
76
+ );
77
+ function contractErrorFor(wireCode) {
78
+ if (typeof wireCode !== "string") return void 0;
79
+ const key = wireCode.trim().toUpperCase();
80
+ return key.length > 0 ? BY_UPPER.get(key) : void 0;
81
+ }
82
+ var CATEGORY_OF = Object.freeze({
83
+ // the caller's sign-in state is wrong and a credential change is the remedy
84
+ authExpired: "authentication",
85
+ authRejected: "authentication",
86
+ sessionRequired: "authentication",
87
+ // signed in, correctly identified, and still not allowed
88
+ accessDenied: "authorization",
89
+ // a plan gate, not a permission failure: the remedy is commercial
90
+ paymentRequired: "entitlement",
91
+ // slow down / come back later
92
+ quotaExceeded: "rateLimit",
93
+ rateLimited: "rateLimit",
94
+ // the request itself was wrong; retrying it unchanged can never succeed
95
+ validationFailed: "invalidRequest",
96
+ sdkUpdateRequired: "invalidRequest",
97
+ // the target is gone, hidden, or was never visible to this caller
98
+ conversationNotFound: "notFound",
99
+ petNotFound: "notFound",
100
+ resourceNotFound: "notFound",
101
+ // something else already holds the thing
102
+ conflict: "conflict",
103
+ idempotencyConflict: "conflict",
104
+ idempotencyInFlight: "conflict",
105
+ // the pipe, not the request: timeouts, drops, a briefly unreachable dependency
106
+ streamTimeout: "connection",
107
+ streamIncomplete: "connection",
108
+ upstreamLlmTimeout: "connection",
109
+ serviceUnavailable: "connection",
110
+ // the server admits fault
111
+ internalError: "server",
112
+ notImplemented: "server",
113
+ mediaUploadFailed: "media",
114
+ moderationBlocked: "policy",
115
+ unknown: "unknown"
116
+ });
117
+ function categoryFor(code) {
118
+ return CATEGORY_OF[code];
119
+ }
120
+ function fromWire(wire) {
121
+ const contractRow = contractErrorFor(wire);
122
+ if (contractRow) return contractRow.normalized;
123
+ const upper = (wire ?? "").trim().toUpperCase();
124
+ const canonical = upper.replace(/[^A-Z0-9]/g, "");
125
+ if (canonical === "AUTHREJECTED") return "authRejected";
126
+ if (upper.startsWith("AUTH")) return "authExpired";
127
+ switch (canonical) {
128
+ case "DAILYQUOTAEXCEEDED":
129
+ case "QUOTAEXCEEDED":
130
+ return "quotaExceeded";
131
+ case "RATELIMITED":
132
+ case "TOOMANYREQUESTS":
133
+ return "rateLimited";
134
+ case "IDEMPOTENCYKEYCONFLICT":
135
+ case "IDEMPOTENCYCONFLICT":
136
+ return "idempotencyConflict";
137
+ case "ACCESSDENIED":
138
+ case "FORBIDDEN":
139
+ return "accessDenied";
140
+ case "NOTFOUND":
141
+ case "CONVERSATIONNOTFOUND":
142
+ return "conversationNotFound";
143
+ case "PETNOTFOUND":
144
+ return "petNotFound";
145
+ case "TIMEOUT":
146
+ case "STREAMTIMEOUT":
147
+ return "streamTimeout";
148
+ // Analysis-domain deterministic 400s (NON-retryable). Additive per SPEC-00 §3.1 / SPEC-11b §2.6:
149
+ // fold to a NON-retried target so the SDK never retries a permanently-failing bad-input request.
150
+ // (Comment above the group so the empty fall-through cases stay lint-clean under no-fallthrough.)
151
+ case "MEDIAUPLOADFAILED":
152
+ case "UNRECOGNIZEDVIDEOFORMAT":
153
+ case "FILETOOSMALL":
154
+ return "mediaUploadFailed";
155
+ case "MODERATIONBLOCKED":
156
+ return "moderationBlocked";
157
+ case "UPSTREAMLLMTIMEOUT":
158
+ return "upstreamLlmTimeout";
159
+ case "INTERNALERROR":
160
+ case "INTERNALSERVERERROR":
161
+ return "internalError";
162
+ case "STREAMINCOMPLETE":
163
+ case "CHATSTREAMINCOMPLETE":
164
+ return "streamIncomplete";
165
+ // Deterministic 400s that can only come from an SDK bug -> unknown (NON-retryable). NEVER internalError
166
+ // (which IS auto-retried): mapping a bad-input 400 to a retryable code retries a request that never succeeds.
167
+ case "INVALIDANALYSISTYPE":
168
+ case "INVALIDUPLOADPURPOSE":
169
+ return "unknown";
170
+ default:
171
+ return "unknown";
172
+ }
173
+ }
174
+ var AUTO_RETRYABLE_CODES = /* @__PURE__ */ new Set([
175
+ "streamTimeout",
176
+ "rateLimited",
177
+ "internalError",
178
+ "upstreamLlmTimeout",
179
+ "streamIncomplete"
180
+ ]);
181
+ function isAutoRetryable(code) {
182
+ return AUTO_RETRYABLE_CODES.has(code);
183
+ }
184
+ var RETRYABLE_CONTRACT_CODES = /* @__PURE__ */ new Set([
185
+ "serviceUnavailable",
186
+ "conflict",
187
+ "idempotencyInFlight"
188
+ ]);
189
+ function isRetryableCode(code) {
190
+ return isAutoRetryable(code) || RETRYABLE_CONTRACT_CODES.has(code);
191
+ }
192
+ var BACKOFF_BASE_MS = 500;
193
+ var BACKOFF_CAP_MS = 8e3;
194
+ var MAX_RETRY_ATTEMPTS = 4;
195
+ function backoffDelayMs(attempt, rng = Math.random) {
196
+ const bounded = Math.max(0, attempt);
197
+ const ceiling = Math.min(BACKOFF_BASE_MS * 2 ** bounded, BACKOFF_CAP_MS);
198
+ return Math.floor(rng() * ceiling);
199
+ }
200
+
201
+ // src/client/errors/EverfurError.ts
202
+ var USER_FACING_COPY = Object.freeze({
203
+ authExpired: "Please sign in again to continue.",
204
+ authRejected: "Please sign in again to continue.",
205
+ sessionRequired: "This app needs to be updated to keep using Everfur.",
206
+ accessDenied: "This feature isn't available on your account right now.",
207
+ paymentRequired: "This is part of a paid plan.",
208
+ quotaExceeded: "You have used today's messages. This resets tomorrow.",
209
+ rateLimited: "You are sending messages quickly. Try again in a few seconds.",
210
+ validationFailed: "Something in that request was not right. Check the details and try again.",
211
+ sdkUpdateRequired: "This app needs to be updated to keep using Everfur.",
212
+ conflict: "That is already running. Wait for it to finish, then try again.",
213
+ idempotencyConflict: "That message was already delivered.",
214
+ idempotencyInFlight: "That is still processing. Give it a moment.",
215
+ conversationNotFound: "This conversation is no longer available.",
216
+ petNotFound: "We could not find that pet. Please pick a pet and try again.",
217
+ resourceNotFound: "We could not find that.",
218
+ streamTimeout: "The response timed out. Tap retry to try again.",
219
+ mediaUploadFailed: "We could not upload that photo. Please attach it again.",
220
+ moderationBlocked: "This request cannot be answered here.",
221
+ upstreamLlmTimeout: "The response timed out. Tap retry to try again.",
222
+ internalError: "We hit a snag on our end. Please try again.",
223
+ notImplemented: "That is not available yet.",
224
+ serviceUnavailable: "That service is briefly unavailable. Try again shortly.",
225
+ streamIncomplete: "The connection dropped mid-answer. Tap retry to continue.",
226
+ unknown: "Something went wrong. Please try again."
227
+ });
228
+ function userFacingError(code) {
229
+ return USER_FACING_COPY[code];
230
+ }
231
+ function defineHidden(target, key, value) {
232
+ Object.defineProperty(target, key, {
233
+ value,
234
+ enumerable: false,
235
+ writable: false,
236
+ configurable: false
237
+ });
238
+ }
239
+ function makeEverfurError(code, opts) {
240
+ contractErrorFor(opts?.wireCode);
241
+ const error = {
242
+ code,
243
+ category: categoryFor(code),
244
+ retryable: opts?.retryable ?? isRetryableCode(code),
245
+ displayMessage: userFacingError(code)
246
+ };
247
+ if (opts?.httpStatus !== void 0) error.httpStatus = opts.httpStatus;
248
+ if (opts?.requestId) error.requestId = opts.requestId;
249
+ if (opts?.wireMessage) defineHidden(error, "wireMessage", opts.wireMessage);
250
+ if (opts?.raw !== void 0 && opts.raw !== null) defineHidden(error, "raw", opts.raw);
251
+ return Object.freeze(error);
252
+ }
253
+
254
+ // src/client/errors/EverfurResult.ts
255
+ function ok(value, warning) {
256
+ return Object.freeze(
257
+ { ok: true, value }
258
+ );
259
+ }
260
+ function err(error) {
261
+ return Object.freeze({ ok: false, error });
262
+ }
263
+ var EverfurConfigError = class _EverfurConfigError extends Error {
264
+ constructor(kind, message) {
265
+ super(message);
266
+ this.name = "EverfurConfigError";
267
+ this.kind = kind;
268
+ Object.setPrototypeOf(this, _EverfurConfigError.prototype);
269
+ }
270
+ };
271
+
272
+ // src/client/protocol/frames.ts
273
+ function assertNever(x) {
274
+ throw new Error(
275
+ `assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`
276
+ );
277
+ }
278
+ function errorFrame(fields) {
279
+ return Object.freeze({
280
+ kind: "error",
281
+ terminal: true,
282
+ code: fields.code,
283
+ retryable: fields.retryable,
284
+ wireMessage: fields.wireMessage,
285
+ synthesized: fields.synthesized,
286
+ lastEventId: fields.lastEventId,
287
+ serverRequestId: null
288
+ });
289
+ }
290
+
291
+ // src/client/identity.ts
292
+ function authHeaders(auth) {
293
+ const headers = {};
294
+ if (auth.mode === "personalized") {
295
+ headers.authorization = `Bearer ${auth.token}`;
296
+ } else {
297
+ headers["x-everfur-partner-key"] = auth.publishableKey;
298
+ }
299
+ if (auth.userRef) headers["x-everfur-user-ref"] = auth.userRef;
300
+ if (auth.sessionId) headers["x-everfur-session-id"] = auth.sessionId;
301
+ return headers;
302
+ }
303
+ function withAuthHeaders(req, auth) {
304
+ return { ...req, headers: { ...stripAuthHeaders(req.headers), ...authHeaders(auth) } };
305
+ }
306
+ function stripAuthHeaders(headers) {
307
+ if (!headers) return {};
308
+ const out = {};
309
+ for (const [key, value] of Object.entries(headers)) {
310
+ const lower = key.toLowerCase();
311
+ if (lower === "authorization" || lower === "x-everfur-partner-key") continue;
312
+ out[key] = value;
313
+ }
314
+ return out;
315
+ }
316
+ async function authedSend(req, ctx) {
317
+ if (ctx.mode === "anonymous") {
318
+ return ctx.transport.request(
319
+ withAuthHeaders(req, {
320
+ mode: "anonymous",
321
+ publishableKey: ctx.publishableKey,
322
+ userRef: ctx.userRef,
323
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
324
+ })
325
+ );
326
+ }
327
+ let token;
328
+ try {
329
+ token = await ctx.identity.currentToken();
330
+ } catch {
331
+ return err(authRejectedError());
332
+ }
333
+ const first = await ctx.transport.request(
334
+ withAuthHeaders(req, {
335
+ mode: "personalized",
336
+ token,
337
+ userRef: ctx.userRef,
338
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
339
+ })
340
+ );
341
+ if (first.ok || first.error.httpStatus !== 401) return first;
342
+ let refreshed;
343
+ try {
344
+ refreshed = await ctx.identity.currentToken({ forceRefresh: true });
345
+ } catch {
346
+ return err(authRejectedError());
347
+ }
348
+ const retry = await ctx.transport.request(
349
+ withAuthHeaders(req, {
350
+ mode: "personalized",
351
+ token: refreshed,
352
+ userRef: ctx.userRef,
353
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {}
354
+ })
355
+ );
356
+ if (!retry.ok && retry.error.httpStatus === 401) {
357
+ return err(authRejectedError(retry.error.httpStatus));
358
+ }
359
+ return retry;
360
+ }
361
+ function authRejectedError(httpStatus) {
362
+ return makeEverfurError("authRejected", {
363
+ retryable: false,
364
+ ...httpStatus !== void 0 ? { httpStatus } : {}
365
+ });
366
+ }
367
+
368
+ // src/client/transport.ts
369
+ function networkError(cause) {
370
+ return makeEverfurError("internalError", { retryable: true, wireMessage: describeCause(cause) });
371
+ }
372
+ function describeCause(cause) {
373
+ if (cause instanceof Error) return cause.message;
374
+ return typeof cause === "string" ? cause : "network request failed";
375
+ }
376
+
377
+ // src/client/funnel/requestFunnel.ts
378
+ var FUNNEL_UNARY_TIMEOUT_MS = 3e4;
379
+ var RETRY_OVERRIDE_MAX_MS = BACKOFF_CAP_MS * 2;
380
+ var IDEMPOTENCY_HEADER = "idempotency-key";
381
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
382
+ var NOOP_OBSERVER = Object.freeze({
383
+ onEvent() {
384
+ }
385
+ });
386
+ var defaultFunnelTimers = Object.freeze({
387
+ setTimeout: (handler, ms) => setTimeout(handler, ms),
388
+ clearTimeout: (handle) => clearTimeout(handle),
389
+ now: () => Date.now()
390
+ });
391
+ function createRequestFunnel(deps) {
392
+ const observer = deps.observer ?? NOOP_OBSERVER;
393
+ const timers = deps.timers ?? defaultFunnelTimers;
394
+ const rng = deps.rng ?? Math.random;
395
+ const sleep = deps.sleep ?? ((ms, signal) => delayAbortable(ms, timers, signal));
396
+ const ceiling = deps.maxAttempts ?? MAX_RETRY_ATTEMPTS;
397
+ const timeoutMs = deps.unaryTimeoutMs ?? FUNNEL_UNARY_TIMEOUT_MS;
398
+ const mintKey = deps.newIdempotencyKey ?? defaultIdempotencyKeyFactory();
399
+ const emit = (event) => {
400
+ try {
401
+ observer.onEvent(event);
402
+ } catch {
403
+ }
404
+ };
405
+ async function send(call, req, opts) {
406
+ const perCallMaxAttempts = opts?.maxAttempts;
407
+ const maxAttempts = Math.max(1, perCallMaxAttempts ?? ceiling);
408
+ const idempotent = opts?.idempotent ?? MUTATING_METHODS.has(req.method);
409
+ const idempotencyKey = idempotent ? mintKey() : null;
410
+ const base = assembleHeaders(req, idempotencyKey);
411
+ let attempt = 0;
412
+ for (; ; ) {
413
+ const stamp = (extra) => Object.freeze({
414
+ call,
415
+ method: req.method,
416
+ path: req.path,
417
+ attempt,
418
+ ...idempotencyKey ? { idempotencyKey } : {},
419
+ ...extra
420
+ });
421
+ emit(stamp({ phase: "attempt" }));
422
+ const deadline = boundedSignal(timeoutMs, timers);
423
+ const merged = mergeSignals(deadline.signal, req.signal);
424
+ let settled;
425
+ try {
426
+ settled = await authedSend({ ...base, signal: merged.signal }, deps.auth);
427
+ } catch (cause) {
428
+ settled = err(networkError(cause));
429
+ } finally {
430
+ merged.dispose();
431
+ deadline.cancel();
432
+ }
433
+ if (settled.ok) {
434
+ emit(stamp({ phase: "settled", ok: true, reason: "ok" }));
435
+ return settled;
436
+ }
437
+ const error = settled.error;
438
+ const decision = decideRetry(error, attempt, {
439
+ maxAttempts,
440
+ rng,
441
+ now: timers.now(),
442
+ aborted: req.signal?.aborted === true,
443
+ ...perCallMaxAttempts !== void 0 ? { perCallMaxAttempts } : {},
444
+ ...deps.errorPolicy !== void 0 ? { policy: deps.errorPolicy } : {}
445
+ });
446
+ const settledEvent = {
447
+ ok: false,
448
+ code: error.code,
449
+ reason: decision.reason,
450
+ ...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {},
451
+ ...error.requestId !== void 0 ? { requestId: error.requestId } : {}
452
+ };
453
+ if (!decision.retry) {
454
+ emit(stamp({ phase: "settled", ...settledEvent }));
455
+ return err(error);
456
+ }
457
+ emit(stamp({ phase: "retry", ...settledEvent, delayMs: decision.delayMs }));
458
+ await sleep(decision.delayMs, req.signal);
459
+ if (req.signal?.aborted === true) {
460
+ emit(stamp({ phase: "settled", ...settledEvent, reason: "aborted" }));
461
+ return err(error);
462
+ }
463
+ attempt += 1;
464
+ }
465
+ }
466
+ async function authorize(req) {
467
+ return withAuthHeaders(req, await resolveDeviceAuth(deps.auth));
468
+ }
469
+ async function* stream(call, req, signal) {
470
+ emit(
471
+ Object.freeze({
472
+ call,
473
+ phase: "stream.open",
474
+ method: req.method,
475
+ path: req.path,
476
+ attempt: 0
477
+ })
478
+ );
479
+ try {
480
+ yield* deps.auth.transport.stream(req, signal);
481
+ } catch {
482
+ yield errorFrame({
483
+ // The same wire spelling sse.ts synthesizes, so `fromWire` folds it to the retryable `internalError`
484
+ // like any other transport failure. wireMessage stays null: it is the SERVER's text, and a thrown
485
+ // host exception's `.message` is not that.
486
+ code: "internal_error",
487
+ retryable: true,
488
+ wireMessage: null,
489
+ synthesized: true,
490
+ lastEventId: null});
491
+ }
492
+ }
493
+ return Object.freeze({ send, authorize, stream });
494
+ }
495
+ function assembleHeaders(req, idempotencyKey) {
496
+ const headers = {};
497
+ for (const [key, value] of Object.entries(req.headers ?? {})) {
498
+ if (key.toLowerCase() === IDEMPOTENCY_HEADER) continue;
499
+ headers[key] = value;
500
+ }
501
+ if (idempotencyKey !== null) headers["Idempotency-Key"] = idempotencyKey;
502
+ return { ...req, headers };
503
+ }
504
+ function defaultIdempotencyKeyFactory() {
505
+ let counter = 0;
506
+ return () => `efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
507
+ }
508
+ var POLICY_MAX_ATTEMPTS_CAP = 10;
509
+ function decideRetry(error, attempt, ctx) {
510
+ if (ctx.aborted) return { retry: false, reason: "aborted" };
511
+ const throttle = throttleKind(error);
512
+ if (throttle === "quota") {
513
+ return { retry: false, reason: "daily-quota-exhausted" };
514
+ }
515
+ if (throttle !== "burst" && !isAutoRetryable(error.code)) {
516
+ return { retry: false, reason: "terminal-code" };
517
+ }
518
+ const reason = throttle === "burst" ? "burst-throttle" : "retryable-code";
519
+ const policyVetoedRetry = () => {
520
+ if (ctx.policy === void 0) return false;
521
+ try {
522
+ return !ctx.policy.shouldRetry(error.code, attempt);
523
+ } catch {
524
+ return false;
525
+ }
526
+ };
527
+ if (policyVetoedRetry()) return { retry: false, reason: "terminal-code" };
528
+ const policyCeiling = () => {
529
+ if (ctx.policy === void 0) return null;
530
+ let raw;
531
+ try {
532
+ raw = ctx.policy.maxAttempts(error.code);
533
+ } catch {
534
+ return null;
535
+ }
536
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
537
+ return Math.max(1, Math.min(POLICY_MAX_ATTEMPTS_CAP, Math.floor(raw)));
538
+ };
539
+ const ceiling = ctx.perCallMaxAttempts ?? policyCeiling() ?? ctx.maxAttempts;
540
+ if (attempt + 1 >= ceiling) return { retry: false, reason: "attempts-exhausted" };
541
+ const override = retryOverrideMs(error, ctx.now);
542
+ if (override !== null) {
543
+ if (override > RETRY_OVERRIDE_MAX_MS) {
544
+ return { retry: false, reason: "server-reset-beyond-budget" };
545
+ }
546
+ return { retry: true, reason, delayMs: override };
547
+ }
548
+ return { retry: true, reason, delayMs: backoffDelayMs(attempt, ctx.rng) };
549
+ }
550
+ function throttleKind(error) {
551
+ const code = error.code === "unknown" ? fromWire(rawWireCode(error.raw)) : error.code;
552
+ if (code === "quotaExceeded") return "quota";
553
+ if (code === "rateLimited") return "burst";
554
+ if (error.httpStatus === 429) {
555
+ return "burst";
556
+ }
557
+ return null;
558
+ }
559
+ function retryOverrideMs(error, now) {
560
+ const at = findResetsAt(error.raw);
561
+ if (at === null) return null;
562
+ const delta = at - now;
563
+ return delta > 0 ? delta : 0;
564
+ }
565
+ function findResetsAt(raw) {
566
+ for (const scope of candidateScopes(raw)) {
567
+ const value = scope["resets_at"];
568
+ const parsed = parseInstantMs(value);
569
+ if (parsed !== null) return parsed;
570
+ }
571
+ return null;
572
+ }
573
+ function candidateScopes(raw) {
574
+ if (!isRecord(raw)) return [];
575
+ const out = [raw];
576
+ for (const nested of ["error", "detail"]) {
577
+ const value = raw[nested];
578
+ if (isRecord(value)) out.push(value);
579
+ }
580
+ return out;
581
+ }
582
+ function parseInstantMs(value) {
583
+ if (typeof value === "number" && Number.isFinite(value)) {
584
+ return value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
585
+ }
586
+ if (typeof value === "string" && value.trim().length > 0) {
587
+ const parsed = Date.parse(value);
588
+ return Number.isFinite(parsed) ? parsed : null;
589
+ }
590
+ return null;
591
+ }
592
+ function rawWireCode(raw) {
593
+ for (const scope of candidateScopes(raw)) {
594
+ const code = scope["code"];
595
+ if (typeof code === "string" && code.length > 0) return code;
596
+ }
597
+ return null;
598
+ }
599
+ function isRecord(value) {
600
+ return typeof value === "object" && value !== null;
601
+ }
602
+ async function resolveDeviceAuth(auth) {
603
+ if (auth.mode === "anonymous") {
604
+ return {
605
+ mode: "anonymous",
606
+ publishableKey: auth.publishableKey,
607
+ userRef: auth.userRef,
608
+ ...auth.sessionId ? { sessionId: auth.sessionId } : {}
609
+ };
610
+ }
611
+ return {
612
+ mode: "personalized",
613
+ token: await auth.identity.currentToken(),
614
+ userRef: auth.userRef,
615
+ ...auth.sessionId ? { sessionId: auth.sessionId } : {}
616
+ };
617
+ }
618
+ function boundedSignal(ms, timers) {
619
+ const ctrl = new AbortController();
620
+ const handle = timers.setTimeout(() => ctrl.abort(), ms);
621
+ return { signal: ctrl.signal, cancel: () => timers.clearTimeout(handle) };
622
+ }
623
+ function mergeSignals(deadline, caller) {
624
+ const noop = () => void 0;
625
+ if (!caller) return { signal: deadline, dispose: noop };
626
+ const ctrl = new AbortController();
627
+ if (deadline.aborted || caller.aborted) {
628
+ ctrl.abort();
629
+ return { signal: ctrl.signal, dispose: noop };
630
+ }
631
+ const onAbort = () => ctrl.abort();
632
+ deadline.addEventListener("abort", onAbort, { once: true });
633
+ caller.addEventListener("abort", onAbort, { once: true });
634
+ return {
635
+ signal: ctrl.signal,
636
+ dispose: () => {
637
+ deadline.removeEventListener("abort", onAbort);
638
+ caller.removeEventListener("abort", onAbort);
639
+ }
640
+ };
641
+ }
642
+ function delayAbortable(ms, timers, signal) {
643
+ if (ms <= 0 || signal?.aborted === true) return Promise.resolve();
644
+ return new Promise((resolve) => {
645
+ const handle = timers.setTimeout(() => {
646
+ signal?.removeEventListener("abort", onAbort);
647
+ resolve();
648
+ }, ms);
649
+ const onAbort = () => {
650
+ timers.clearTimeout(handle);
651
+ resolve();
652
+ };
653
+ signal?.addEventListener("abort", onAbort, { once: true });
654
+ });
655
+ }
656
+
657
+ // src/core/ports/TelemetryPort.ts
658
+ var noopTelemetry = Object.freeze({
659
+ track() {
660
+ },
661
+ trackExpectedFailure() {
662
+ }
663
+ });
664
+ function fileHandleFromMedia(source) {
665
+ const handle = {
666
+ uri: source.uri,
667
+ mimeType: source.mimeType
668
+ };
669
+ const size = mediaByteSize(source);
670
+ if (size !== null) handle.sizeBytes = size;
671
+ return Object.freeze(handle);
672
+ }
673
+ function mediaByteSize(source) {
674
+ const candidate = source.byteSize ?? source.sizeBytes;
675
+ return typeof candidate === "number" && Number.isFinite(candidate) && candidate >= 0 ? candidate : null;
676
+ }
677
+ function mediaDurationMs(source) {
678
+ const seconds = source.durationSeconds;
679
+ return typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0 ? Math.round(seconds * 1e3) : null;
680
+ }
681
+ function captureOptionsFor(mode, maxDurationSeconds) {
682
+ return maxDurationSeconds === void 0 ? Object.freeze({ mode }) : Object.freeze({ mode, maxDurationSeconds });
683
+ }
684
+ function isCaptureAvailable(camera) {
685
+ return camera != null && camera.isAvailable === true;
686
+ }
687
+ var defaultTimers = Object.freeze({
688
+ setTimeout: (handler, ms) => setTimeout(handler, ms),
689
+ clearTimeout: (handle) => clearTimeout(handle),
690
+ now: () => Date.now()
691
+ });
692
+ function delayAbortable2(ms, signal, timers) {
693
+ return new Promise((resolve) => {
694
+ if (signal.aborted) {
695
+ resolve();
696
+ return;
697
+ }
698
+ const holder = { handle: void 0 };
699
+ const done = () => {
700
+ timers.clearTimeout(holder.handle);
701
+ signal.removeEventListener("abort", done);
702
+ resolve();
703
+ };
704
+ holder.handle = timers.setTimeout(done, ms);
705
+ signal.addEventListener("abort", done, { once: true });
706
+ });
707
+ }
708
+ function mergeSignals2(a, b) {
709
+ if (!b) return a;
710
+ const ctrl = new AbortController();
711
+ if (a.aborted || b.aborted) {
712
+ ctrl.abort();
713
+ return ctrl.signal;
714
+ }
715
+ const onAbort = () => ctrl.abort();
716
+ a.addEventListener("abort", onAbort, { once: true });
717
+ b.addEventListener("abort", onAbort, { once: true });
718
+ return ctrl.signal;
719
+ }
720
+ var MediaStore = class {
721
+ constructor(initial) {
722
+ this.listeners = /* @__PURE__ */ new Set();
723
+ this.epoch = 0;
724
+ this.inFlight = null;
725
+ this.snapshot = Object.freeze({ ...initial });
726
+ }
727
+ subscribe(listener) {
728
+ this.listeners.add(listener);
729
+ return () => {
730
+ this.listeners.delete(listener);
731
+ };
732
+ }
733
+ getSnapshot() {
734
+ return this.snapshot;
735
+ }
736
+ patch(partial) {
737
+ this.snapshot = Object.freeze({ ...this.snapshot, ...partial });
738
+ for (const listener of this.listeners) listener();
739
+ }
740
+ beginOperation(external) {
741
+ this.inFlight?.abort();
742
+ const ctrl = new AbortController();
743
+ this.inFlight = ctrl;
744
+ const epoch = this.epoch;
745
+ const signal = external ? mergeSignals2(ctrl.signal, external) : ctrl.signal;
746
+ return {
747
+ signal,
748
+ epoch,
749
+ settle: () => {
750
+ if (this.inFlight === ctrl) this.inFlight = null;
751
+ }
752
+ };
753
+ }
754
+ alive(epoch) {
755
+ return epoch === this.epoch;
756
+ }
757
+ /** Re-scope on user/pet switch: aborts in-flight and bumps the epoch so a late write drops. */
758
+ rescope() {
759
+ this.epoch += 1;
760
+ this.inFlight?.abort();
761
+ this.inFlight = null;
762
+ }
763
+ /** Idempotent teardown: aborts in-flight, bumps the epoch, drops every listener. */
764
+ dispose() {
765
+ this.epoch += 1;
766
+ this.inFlight?.abort();
767
+ this.inFlight = null;
768
+ this.listeners.clear();
769
+ }
770
+ };
771
+
772
+ // src/client/text.ts
773
+ function hasLoneSurrogate(value) {
774
+ for (let i = 0; i < value.length; i += 1) {
775
+ const code = value.charCodeAt(i);
776
+ if (code >= 55296 && code <= 56319) {
777
+ const low = value.charCodeAt(i + 1);
778
+ if (!(low >= 56320 && low <= 57343)) return true;
779
+ i += 1;
780
+ } else if (code >= 56320 && code <= 57343) {
781
+ return true;
782
+ }
783
+ }
784
+ return false;
785
+ }
786
+
787
+ // src/core/media/projection.ts
788
+ var CONSUMER_SAFE_DETECTION_KEYS = Object.freeze([
789
+ "primary_label",
790
+ "primary_confidence",
791
+ "subtype_label",
792
+ "subtype_display",
793
+ "subtype_confidence",
794
+ "risk_tier",
795
+ "confidence_tier",
796
+ "copy_short",
797
+ "disease_name",
798
+ "disease_framing",
799
+ "model_version",
800
+ "skin_v2",
801
+ "eye_v2",
802
+ "llm_checkup"
803
+ ]);
804
+ var OPERATOR_INTERNAL_KEYS = Object.freeze([
805
+ "decision_audit",
806
+ "decision_thresholds",
807
+ "per_class_auroc",
808
+ "ood_layers",
809
+ "gate1_score",
810
+ "possible_conditions",
811
+ "top_class"
812
+ ]);
813
+ var BOOLEAN_KEYS = /* @__PURE__ */ new Set(["skin_v2", "eye_v2", "llm_checkup"]);
814
+ var CONFIDENCE_KEYS = /* @__PURE__ */ new Set(["primary_confidence", "subtype_confidence"]);
815
+ var RISK_TIER_VALUES = /* @__PURE__ */ new Set(["low_risk", "concern", "uncertain"]);
816
+ var CONFIDENCE_TIER_VALUES = /* @__PURE__ */ new Set(["possible", "probable"]);
817
+ var STRING_LIMITS = Object.freeze({
818
+ primary_label: 64,
819
+ subtype_label: 64,
820
+ subtype_display: 128,
821
+ copy_short: 512,
822
+ disease_name: 128,
823
+ disease_framing: 512,
824
+ model_version: 64
825
+ });
826
+ function projectDetectionMetadata(raw) {
827
+ const source = isRecord2(raw) ? raw : {};
828
+ const out = {};
829
+ for (const key of CONSUMER_SAFE_DETECTION_KEYS) {
830
+ if (!(key in source)) continue;
831
+ const value = source[key];
832
+ const accepted = acceptKey(key, value);
833
+ if (accepted !== DROP) out[key] = accepted;
834
+ }
835
+ let dropped = 0;
836
+ for (const key of OPERATOR_INTERNAL_KEYS) {
837
+ if (key in source) dropped += 1;
838
+ }
839
+ return Object.freeze({ metadata: Object.freeze(out), droppedOperatorKeys: dropped });
840
+ }
841
+ var DROP = /* @__PURE__ */ Symbol("drop");
842
+ function acceptKey(key, value) {
843
+ if (BOOLEAN_KEYS.has(key)) return typeof value === "boolean" ? value : DROP;
844
+ if (CONFIDENCE_KEYS.has(key)) return isUnitConfidence(value) ? value : DROP;
845
+ if (key === "risk_tier") return typeof value === "string" && RISK_TIER_VALUES.has(value) ? value : DROP;
846
+ if (key === "confidence_tier") {
847
+ return typeof value === "string" && CONFIDENCE_TIER_VALUES.has(value) ? value : DROP;
848
+ }
849
+ if (typeof value !== "string") return DROP;
850
+ const limit = STRING_LIMITS[key] ?? 256;
851
+ return value.length > limit ? value.slice(0, limit) : value;
852
+ }
853
+ function isUnitConfidence(value) {
854
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
855
+ }
856
+ function parseInterpretation(raw) {
857
+ if (!isRecord2(raw)) return null;
858
+ const summary = asString(raw["summary"]);
859
+ const disclaimer = asString(raw["disclaimer"]);
860
+ const recommendations = asStringList(raw["recommendations"] ?? raw["recommendation"]);
861
+ if (summary === null && disclaimer === null && recommendations.length === 0) return null;
862
+ return Object.freeze({
863
+ summary: summary ?? "",
864
+ recommendations: Object.freeze(recommendations),
865
+ disclaimer: disclaimer ?? ""
866
+ });
867
+ }
868
+ function locateDetectionMetadata(body) {
869
+ if (!isRecord2(body)) return {};
870
+ if (isRecord2(body["metadata"])) return body["metadata"];
871
+ const detections = body["detections"];
872
+ if (Array.isArray(detections) && detections.length > 0) {
873
+ const first = detections[0];
874
+ if (isRecord2(first) && isRecord2(first["metadata"])) return first["metadata"];
875
+ if (isRecord2(first)) return first;
876
+ }
877
+ return body;
878
+ }
879
+ function locateInterpretation(body) {
880
+ if (!isRecord2(body)) return null;
881
+ if (isRecord2(body["interpretation"])) return body["interpretation"];
882
+ return body;
883
+ }
884
+ function isRecord2(value) {
885
+ return typeof value === "object" && value !== null && !Array.isArray(value);
886
+ }
887
+ function asString(value) {
888
+ return typeof value === "string" && value.length > 0 ? value : null;
889
+ }
890
+ function asStringList(value) {
891
+ if (typeof value === "string") return value.length > 0 ? [value] : [];
892
+ if (!Array.isArray(value)) return [];
893
+ return value.filter((entry) => typeof entry === "string" && entry.length > 0);
894
+ }
895
+ function asUnitNumber(value) {
896
+ return isUnitConfidence(value) ? value : null;
897
+ }
898
+ function asFiniteNumber(value) {
899
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
900
+ }
901
+
902
+ // src/core/media/pipeline.ts
903
+ var ENDPOINTS = Object.freeze({
904
+ initiate: "/widget/v1/uploads/initiate",
905
+ precheck: "/widget/v1/photo/precheck",
906
+ photoAnalyze: "/widget/v1/photo/analyze",
907
+ videoAnalyze: "/widget/v1/video/analyze",
908
+ // `jobId` arrives from the WIRE, so it is not under this SDK's control, and `encodeURIComponent` throws
909
+ // URIError on a lone surrogate. Returning null lets the caller settle instead of throwing out of the
910
+ // poller. These routes are dark today, which is exactly why the guard goes in now: it costs one line and
911
+ // the gap re-opens silently the moment they land.
912
+ job: (jobId) => hasLoneSurrogate(jobId) ? null : `/widget/v1/analysis/jobs/${encodeURIComponent(jobId)}`
913
+ });
914
+ function brandJobId(raw) {
915
+ return raw;
916
+ }
917
+ async function initiateUpload(funnel, params) {
918
+ const body = { purpose: params.purpose, content_type: params.contentType };
919
+ if (params.byteSize !== null) body.byte_size = params.byteSize;
920
+ const req = {
921
+ method: "POST",
922
+ path: ENDPOINTS.initiate,
923
+ body,
924
+ ...params.signal ? { signal: params.signal } : {}
925
+ };
926
+ const res = await funnel.send("media.initiateUpload", req);
927
+ if (!res.ok) return err(res.error);
928
+ const policy = parsePresigned(res.value);
929
+ if (policy === null) return err(makeEverfurError("mediaUploadFailed", { retryable: false }));
930
+ return ok(policy);
931
+ }
932
+ function parsePresigned(raw) {
933
+ if (!isRecord2(raw)) return null;
934
+ const url = asString(raw["url"]);
935
+ const s3Key = asString(raw["s3_key"]);
936
+ if (url === null || s3Key === null) return null;
937
+ const fieldsRaw = raw["fields"];
938
+ const fields = {};
939
+ if (isRecord2(fieldsRaw)) {
940
+ for (const [key, value] of Object.entries(fieldsRaw)) {
941
+ if (typeof value === "string") fields[key] = value;
942
+ }
943
+ }
944
+ return Object.freeze({
945
+ url,
946
+ fields: Object.freeze(fields),
947
+ s3Key,
948
+ expiresAt: asFiniteNumber(raw["expires_at"])
949
+ });
950
+ }
951
+ async function stageUpload(upload, source, policy, idempotencyKey, signal) {
952
+ try {
953
+ await upload.presignedPut(fileHandleFromMedia(source), {
954
+ target: policy,
955
+ idempotencyKey,
956
+ ...signal ? { signal } : {}
957
+ });
958
+ return ok(void 0);
959
+ } catch {
960
+ return err(makeEverfurError("mediaUploadFailed", { retryable: false }));
961
+ }
962
+ }
963
+ async function submitAnalyze(funnel, path, body, detectGate, signal) {
964
+ const req = {
965
+ method: "POST",
966
+ path,
967
+ body,
968
+ ...signal ? { signal } : {}
969
+ };
970
+ const res = await funnel.send("media.analyze", req);
971
+ if (res.ok) {
972
+ const job = parseAsyncJob(res.value);
973
+ return job !== null ? { kind: "async", job } : { kind: "sync", body: res.value };
974
+ }
975
+ const gate = detectGate(res.error.httpStatus, res.error);
976
+ if (gate !== null) return { kind: "gate", gate };
977
+ return { kind: "error", error: res.error };
978
+ }
979
+ function parseAsyncJob(raw) {
980
+ if (!isRecord2(raw)) return null;
981
+ const jobId = asString(raw["job_id"]);
982
+ if (jobId === null) return null;
983
+ const status = asString(raw["status"]);
984
+ if (status !== null && isTerminalStatus(status)) return null;
985
+ return Object.freeze({
986
+ jobId: brandJobId(jobId),
987
+ estimatedSeconds: asFiniteNumber(raw["estimated_completion_seconds"])
988
+ });
989
+ }
990
+ var POLL_FIRST_DELAY_MS = 2e3;
991
+ var POLL_MAX_DELAY_MS = 5e3;
992
+ var POLL_BUDGET_MS = 9e4;
993
+ async function pollJob(funnel, jobId, deps) {
994
+ const { timers, signal, alive } = deps;
995
+ const start = timers.now();
996
+ const budget = Math.max(POLL_BUDGET_MS, (deps.estimatedSeconds ?? 0) * 1e3);
997
+ let delay = POLL_FIRST_DELAY_MS;
998
+ for (; ; ) {
999
+ if (signal.aborted || !alive()) return { kind: "aborted" };
1000
+ await delayAbortable2(delay, signal, timers);
1001
+ if (signal.aborted || !alive()) return { kind: "aborted" };
1002
+ if (timers.now() - start > budget) return { kind: "timeout" };
1003
+ const path = ENDPOINTS.job(jobId);
1004
+ if (path === null) return { kind: "notFound" };
1005
+ const res = await funnel.send(
1006
+ "media.pollJob",
1007
+ { method: "GET", path, ...signal ? { signal } : {} },
1008
+ { maxAttempts: 1 }
1009
+ );
1010
+ if (signal.aborted || !alive()) return { kind: "aborted" };
1011
+ if (!res.ok) {
1012
+ if (res.error.httpStatus === 404) return { kind: "notFound" };
1013
+ delay = Math.min(POLL_MAX_DELAY_MS, delay + 1e3);
1014
+ continue;
1015
+ }
1016
+ const status = jobStatusOf(res.value);
1017
+ if (status === "COMPLETED") return { kind: "complete", body: res.value };
1018
+ if (status === "FAILED") return { kind: "failed", error: jobFailureError(res.value) };
1019
+ delay = Math.min(POLL_MAX_DELAY_MS, delay + 1e3);
1020
+ }
1021
+ }
1022
+ function jobStatusOf(body) {
1023
+ if (!isRecord2(body)) return "PROCESSING";
1024
+ return (asString(body["status"]) ?? "PROCESSING").toUpperCase();
1025
+ }
1026
+ function isTerminalStatus(status) {
1027
+ const upper = status.toUpperCase();
1028
+ return upper === "COMPLETED" || upper === "FAILED";
1029
+ }
1030
+ function jobFailureError(body) {
1031
+ const wire = isRecord2(body) ? asString(body["error"]) ?? asString(body["error_code"]) : null;
1032
+ return makeEverfurError("internalError", { retryable: false, ...wire ? { wireMessage: wire } : {} });
1033
+ }
1034
+ function detectNoGate() {
1035
+ return null;
1036
+ }
1037
+ function analyzeBody(s3Key, extra) {
1038
+ const body = { s3_key: s3Key };
1039
+ if (extra.type !== void 0) body.type = extra.type;
1040
+ if (extra.petRef != null) body.pet_id = extra.petRef;
1041
+ if (extra.precheckToken != null) body.precheck_token = extra.precheckToken;
1042
+ return body;
1043
+ }
1044
+
1045
+ // src/core/video/VideoController.ts
1046
+ function createVideoController(deps) {
1047
+ return new VideoController(deps);
1048
+ }
1049
+ var VideoController = class extends MediaStore {
1050
+ constructor(deps) {
1051
+ super({
1052
+ status: "idle",
1053
+ job: null,
1054
+ result: null,
1055
+ error: null,
1056
+ isCaptureAvailable: isCaptureAvailable(deps.camera),
1057
+ progress: 0
1058
+ });
1059
+ this.funnel = deps.funnel ?? createRequestFunnel({
1060
+ auth: deps.auth,
1061
+ ...deps.errorPolicy ? { errorPolicy: deps.errorPolicy } : {}
1062
+ });
1063
+ this.camera = deps.camera;
1064
+ this.upload = deps.upload;
1065
+ this.defaultPetRef = deps.petRef ?? null;
1066
+ this.telemetry = deps.telemetry ?? noopTelemetry;
1067
+ this.timers = deps.timers ?? defaultTimers;
1068
+ this.makeIdempotencyKey = deps.makeIdempotencyKey ?? defaultIdempotencyFactory();
1069
+ }
1070
+ /** Open the CameraPort (video), then submit. No-op when capture is unavailable; a cancel returns to idle. */
1071
+ async capture(opts) {
1072
+ if (!isCaptureAvailable(this.camera)) {
1073
+ return err(makeEverfurError("unknown", { retryable: false }));
1074
+ }
1075
+ let source;
1076
+ try {
1077
+ source = await this.camera.capture(captureOptionsFor("video", 15));
1078
+ } catch {
1079
+ if (this.snapshot.status !== "idle") this.patch({ status: "idle", progress: 0 });
1080
+ return err(makeEverfurError("unknown", { retryable: false }));
1081
+ }
1082
+ return this.submit(source, opts?.petRef !== void 0 ? { petRef: opts.petRef } : void 0);
1083
+ }
1084
+ /** Capture -> presigned PUT -> POST /video/analyze -> poll. Returns the JobId or a domain error. */
1085
+ async submit(source, opts) {
1086
+ const op = this.beginOperation(opts?.signal);
1087
+ const petRef = opts?.petRef ?? this.defaultPetRef;
1088
+ const idempotencyKey = this.makeIdempotencyKey();
1089
+ const startedAt = this.timers.now();
1090
+ this.patch({ status: "uploading", progress: 0, error: null, result: null, job: null });
1091
+ try {
1092
+ const initiated = await initiateUpload(this.funnel, {
1093
+ purpose: "gait_video",
1094
+ contentType: source.mimeType,
1095
+ byteSize: mediaByteSize(source),
1096
+ signal: op.signal
1097
+ });
1098
+ if (op.signal.aborted || !this.alive(op.epoch)) return abortedResult();
1099
+ if (!initiated.ok) return this.fail(op, initiated.error);
1100
+ const staged = await stageUpload(this.upload, source, initiated.value, idempotencyKey, op.signal);
1101
+ if (op.signal.aborted || !this.alive(op.epoch)) return abortedResult();
1102
+ if (!staged.ok) {
1103
+ this.telemetry.track("analysis.upload", {
1104
+ capability: "video",
1105
+ purpose: "gait_video",
1106
+ outcome: "failed"
1107
+ });
1108
+ return this.fail(op, staged.error);
1109
+ }
1110
+ this.patch({ progress: 1 });
1111
+ this.telemetry.track("analysis.upload", {
1112
+ capability: "video",
1113
+ purpose: "gait_video",
1114
+ byteSize: mediaByteSize(source) ?? 0,
1115
+ durationMs: mediaDurationMs(source) ?? 0,
1116
+ outcome: "ok"
1117
+ });
1118
+ this.patch({ status: "analyzing" });
1119
+ const outcome = await submitAnalyze(
1120
+ this.funnel,
1121
+ ENDPOINTS.videoAnalyze,
1122
+ analyzeBody(initiated.value.s3Key, { petRef }),
1123
+ detectNoGate,
1124
+ op.signal
1125
+ );
1126
+ if (op.signal.aborted || !this.alive(op.epoch)) return abortedResult();
1127
+ if (outcome.kind === "error") return this.fail(op, outcome.error);
1128
+ if (outcome.kind === "gate") return this.fail(op, makeEverfurError("unknown", { retryable: false }));
1129
+ if (outcome.kind === "sync") {
1130
+ const jobId = brandJobId(resultIdOf(outcome.body) ?? "");
1131
+ return this.complete(op, outcome.body, jobId, startedAt);
1132
+ }
1133
+ const job = outcome.job;
1134
+ this.patch({ job: { id: job.jobId, state: "processing" } });
1135
+ const poll = await pollJob(this.funnel, job.jobId, {
1136
+ timers: this.timers,
1137
+ signal: op.signal,
1138
+ alive: () => this.alive(op.epoch),
1139
+ estimatedSeconds: job.estimatedSeconds
1140
+ });
1141
+ if (op.signal.aborted || !this.alive(op.epoch)) return abortedResult();
1142
+ switch (poll.kind) {
1143
+ case "aborted":
1144
+ return abortedResult();
1145
+ case "complete":
1146
+ return this.complete(op, poll.body, job.jobId, startedAt);
1147
+ case "failed":
1148
+ return this.fail(op, poll.error);
1149
+ case "timeout":
1150
+ return this.fail(op, makeEverfurError("streamTimeout", { retryable: true }));
1151
+ case "notFound":
1152
+ this.patch({ job: null });
1153
+ return this.fail(op, makeEverfurError("conversationNotFound", { retryable: false, httpStatus: 404 }));
1154
+ default:
1155
+ return this.fail(op, makeEverfurError("internalError", { retryable: false }));
1156
+ }
1157
+ } finally {
1158
+ op.settle();
1159
+ }
1160
+ }
1161
+ /** Abort upload/poll; status returns to idle (aborted !== error). */
1162
+ cancel() {
1163
+ this.inFlight?.abort();
1164
+ this.inFlight = null;
1165
+ if (this.snapshot.status === "uploading" || this.snapshot.status === "analyzing") {
1166
+ this.patch({ status: "idle", progress: 0 });
1167
+ }
1168
+ }
1169
+ // ---- terminal transitions ---------------------------------------------
1170
+ complete(op, body, jobId, startedAt) {
1171
+ if (!this.alive(op.epoch)) return abortedResult();
1172
+ const mapped = mapVideoResult(body, jobId);
1173
+ if (mapped.droppedOperatorKeys > 0) {
1174
+ this.telemetry.track("analysis.metadata_leak_guard", { droppedKeyCount: mapped.droppedOperatorKeys });
1175
+ }
1176
+ this.telemetry.track("analysis.quality_gate", {
1177
+ usable: mapped.result.quality.usable,
1178
+ reasons: mapped.result.quality.reasons
1179
+ });
1180
+ this.patch({
1181
+ status: "complete",
1182
+ progress: 1,
1183
+ result: mapped.result,
1184
+ error: null,
1185
+ job: { id: jobId, state: "complete" }
1186
+ });
1187
+ this.telemetry.track("analysis.result", {
1188
+ capability: "video",
1189
+ modelVersion: mapped.result.modelVersion ?? "",
1190
+ timeToResultMs: this.timers.now() - startedAt
1191
+ });
1192
+ return ok(jobId);
1193
+ }
1194
+ fail(op, error) {
1195
+ if (!this.alive(op.epoch)) return abortedResult();
1196
+ this.patch({ status: "error", error, progress: 0 });
1197
+ this.telemetry.trackExpectedFailure("analysis.error", {
1198
+ code: error.code,
1199
+ ...error.httpStatus !== void 0 ? { httpStatus: error.httpStatus } : {}
1200
+ });
1201
+ return err(error);
1202
+ }
1203
+ };
1204
+ function mapVideoResult(body, jobId) {
1205
+ const projection = projectDetectionMetadata(locateDetectionMetadata(body));
1206
+ const interpretation = parseInterpretation(locateInterpretation(body));
1207
+ const modelVersion = asString(projection.metadata["model_version"]) ?? (isRecord2(body) ? asString(body["model_version"]) : null);
1208
+ const result = Object.freeze({
1209
+ jobId,
1210
+ analysisType: "gait",
1211
+ detections: parseVideoDetections(body),
1212
+ interpretation,
1213
+ modelVersion,
1214
+ quality: parseQuality(body)
1215
+ });
1216
+ return { result, droppedOperatorKeys: projection.droppedOperatorKeys };
1217
+ }
1218
+ function parseVideoDetections(body) {
1219
+ const raw = isRecord2(body) ? body["detections"] : null;
1220
+ if (!Array.isArray(raw)) return Object.freeze([]);
1221
+ const out = [];
1222
+ for (const entry of raw) {
1223
+ if (!isRecord2(entry)) continue;
1224
+ const label = asString(entry["label"]) ?? asString(entry["name"]);
1225
+ if (label === null) continue;
1226
+ out.push(
1227
+ Object.freeze({
1228
+ label,
1229
+ confidence: asUnitNumber(entry["confidence"]) ?? 0,
1230
+ timestampMs: asFiniteNumber(entry["timestamp_ms"] ?? entry["timestamp"]),
1231
+ durationMs: asFiniteNumber(entry["duration_ms"] ?? entry["duration"])
1232
+ })
1233
+ );
1234
+ }
1235
+ return Object.freeze(out);
1236
+ }
1237
+ function parseQuality(body) {
1238
+ const raw = isRecord2(body) ? body["quality"] : null;
1239
+ if (!isRecord2(raw)) return Object.freeze({ usable: true, reasons: Object.freeze([]) });
1240
+ const usable = raw["usable"];
1241
+ return Object.freeze({
1242
+ usable: typeof usable === "boolean" ? usable : true,
1243
+ reasons: Object.freeze(asStringList(raw["reasons"]))
1244
+ });
1245
+ }
1246
+ function resultIdOf(body) {
1247
+ if (!isRecord2(body)) return null;
1248
+ return asString(body["result_id"]) ?? asString(body["request_id"]) ?? asString(body["job_id"]);
1249
+ }
1250
+ function abortedResult() {
1251
+ return err(makeEverfurError("unknown", { retryable: false }));
1252
+ }
1253
+ function defaultIdempotencyFactory() {
1254
+ let counter = 0;
1255
+ return () => `video-analyze-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1256
+ }
1257
+
1258
+ // src/client/entitlements/resolve.ts
1259
+ var REQUIRES = Object.freeze({
1260
+ chat: Object.freeze(["chat.message.create"]),
1261
+ records: Object.freeze(["records.upload.create", "records.record.read"]),
1262
+ video: Object.freeze(["video.gait.execute"]),
1263
+ photo: Object.freeze(["photo.checkup.execute"]),
1264
+ animations: Object.freeze(["animations.state.read"])
1265
+ });
1266
+ function requires(name) {
1267
+ return REQUIRES[name];
1268
+ }
1269
+ function decideCapability(name, decisions, opts) {
1270
+ if (opts?.isPending === true) {
1271
+ return freezeDecision({ name, enabled: false, isPending: true, limits: {} });
1272
+ }
1273
+ const keys = requires(name);
1274
+ const byResource = /* @__PURE__ */ new Map();
1275
+ for (const decision of decisions) byResource.set(decision.resource, decision);
1276
+ const limits = mergeLimits(keys, byResource);
1277
+ const missing = keys.filter((key) => byResource.get(key)?.granted !== true);
1278
+ if (missing.length === 0) {
1279
+ return freezeDecision({ name, enabled: true, isPending: false, limits });
1280
+ }
1281
+ return freezeDecision({
1282
+ name,
1283
+ enabled: false,
1284
+ isPending: false,
1285
+ limits,
1286
+ disabled: disabledFor(keys, byResource)
1287
+ });
1288
+ }
1289
+ function mergeLimits(keys, byResource) {
1290
+ const out = {};
1291
+ for (const key of keys) {
1292
+ const decisionLimits = byResource.get(key)?.limits;
1293
+ if (!decisionLimits) continue;
1294
+ for (const [limitKey, limitValue] of Object.entries(decisionLimits)) {
1295
+ const existing = out[limitKey];
1296
+ out[limitKey] = existing === void 0 ? limitValue : Math.min(existing, limitValue);
1297
+ }
1298
+ }
1299
+ return out;
1300
+ }
1301
+ function disabledFor(keys, byResource) {
1302
+ for (const key of keys) {
1303
+ const explicit = byResource.get(key)?.disabled;
1304
+ if (explicit) {
1305
+ return Object.freeze({
1306
+ reason: explicit.reason,
1307
+ level: explicit.level,
1308
+ recoverable: explicit.recoverable
1309
+ });
1310
+ }
1311
+ }
1312
+ return Object.freeze({
1313
+ reason: userFacingError("accessDenied"),
1314
+ level: "user_entitlement",
1315
+ recoverable: false
1316
+ });
1317
+ }
1318
+ function freezeDecision(d) {
1319
+ const base = {
1320
+ name: d.name,
1321
+ enabled: d.enabled,
1322
+ isPending: d.isPending,
1323
+ limits: Object.freeze({ ...d.limits })
1324
+ };
1325
+ if (d.disabled !== void 0) base.disabled = d.disabled;
1326
+ return Object.freeze(base);
1327
+ }
1328
+
1329
+ // src/client/theme/tokens.ts
1330
+ function deepFreeze(value) {
1331
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
1332
+ Object.freeze(value);
1333
+ for (const key of Object.keys(value)) {
1334
+ deepFreeze(value[key]);
1335
+ }
1336
+ }
1337
+ return value;
1338
+ }
1339
+ var SPACE = { xs: 4, sm: 8, md: 12, lg: 16, xl: 24, xxl: 32 };
1340
+ var RADIUS = { tile: 5, xs: 6, sm: 10, md: 14, lg: 20, xl: 28, pill: 500 };
1341
+ var TYPE_SIZE = {
1342
+ nano: 8,
1343
+ small: 9,
1344
+ micro: 10,
1345
+ tiny: 11,
1346
+ caption: 12,
1347
+ bodyTight: 13,
1348
+ body: 14,
1349
+ subtitle: 16,
1350
+ heading: 18,
1351
+ verdict: 24
1352
+ };
1353
+ var LINE_HEIGHT = { tight: 1.15, snug: 1.3, normal: 1.4, relaxed: 1.55 };
1354
+ var WEIGHT = { regular: "400", medium: "500", bold: "700" };
1355
+ var LETTER_SPACING = {
1356
+ eyebrow: 1,
1357
+ monoWide: 0.9,
1358
+ headerBrand: -0.42,
1359
+ tight: -0.35
1360
+ };
1361
+ function baseType() {
1362
+ return {
1363
+ family: "System",
1364
+ mono: "monospace",
1365
+ fontUrl: null,
1366
+ size: TYPE_SIZE,
1367
+ lineHeight: LINE_HEIGHT,
1368
+ weight: WEIGHT,
1369
+ letterSpacing: LETTER_SPACING
1370
+ };
1371
+ }
1372
+ var MOTION = {
1373
+ duration: { instant: 80, fast: 140, normal: 220, slow: 320 },
1374
+ spring: { gentle: { damping: 18, stiffness: 200 } },
1375
+ easing: { standard: "cubic-bezier(0.4, 0, 0.2, 1)" },
1376
+ reducedMotion: false
1377
+ };
1378
+ var LIGHT_COLOR = {
1379
+ brand: "#10462E",
1380
+ brandSoft: "rgba(16,70,46,0.10)",
1381
+ brandSofter: "rgba(16,70,46,0.15)",
1382
+ brandBorder: "rgba(16,70,46,0.18)",
1383
+ borderHairlineGreen: "rgba(16,70,46,0.25)",
1384
+ surface: "#FFFFFF",
1385
+ surfaceCream: "#FDFBF8",
1386
+ surfaceSubtle: "#EFE9E3",
1387
+ background: "#FFFFFF",
1388
+ borderRingCream: "#D8D2C8",
1389
+ text: {
1390
+ primary: "#111111",
1391
+ secondary: "#0E462E",
1392
+ muted: "#6E6660",
1393
+ placeholder: "rgba(0,0,0,0.30)",
1394
+ onBrand: "#FFFFFF",
1395
+ metaCool: "#3D3D3D"
1396
+ },
1397
+ primary: "#10462E",
1398
+ onPrimary: "#FFFFFF",
1399
+ accent: "#10462E",
1400
+ onAccent: "#FFFFFF",
1401
+ accentEdge: "#07C168",
1402
+ success: "#07C168",
1403
+ danger: "#B91C1C",
1404
+ errorRed: "#FF1B00",
1405
+ warningStrong: "#A45610",
1406
+ cautionAccent: "#D9821D",
1407
+ riskConcern: "#EFA700",
1408
+ badgeBgPositive: "rgba(7,193,104,0.12)",
1409
+ badgeBgCaution: "rgba(217,130,29,0.14)",
1410
+ badgeBgCritical: "rgba(185,28,28,0.12)",
1411
+ badgeBgNeutral: "rgba(110,102,96,0.12)",
1412
+ bubbleUser: "#10462E",
1413
+ bubbleAssistant: "#FFFFFF",
1414
+ skeleton: "#EFE9E3",
1415
+ scanButtonPink: "#FFC3BC",
1416
+ checkupCardLowRiskBg: "rgba(7,193,104,0.10)",
1417
+ checkupCardConcernBg: "rgba(239,167,0,0.10)"
1418
+ };
1419
+ var EVERFUR_LIGHT = deepFreeze({
1420
+ brightness: "light",
1421
+ meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
1422
+ color: LIGHT_COLOR,
1423
+ space: SPACE,
1424
+ radius: RADIUS,
1425
+ type: baseType(),
1426
+ motion: MOTION
1427
+ });
1428
+ var DARK_COLOR = {
1429
+ brand: "#6BD39A",
1430
+ brandSoft: "rgba(107,211,154,0.12)",
1431
+ brandSofter: "rgba(107,211,154,0.18)",
1432
+ brandBorder: "rgba(107,211,154,0.22)",
1433
+ borderHairlineGreen: "rgba(107,211,154,0.28)",
1434
+ surface: "#1C1F23",
1435
+ surfaceCream: "#23272C",
1436
+ surfaceSubtle: "#23272C",
1437
+ background: "#15171A",
1438
+ borderRingCream: "#3A3F45",
1439
+ text: {
1440
+ primary: "#F5F3F0",
1441
+ secondary: "#A9E4C4",
1442
+ muted: "#9A938C",
1443
+ placeholder: "rgba(255,255,255,0.35)",
1444
+ onBrand: "#0E1F17",
1445
+ metaCool: "#C9C9C9"
1446
+ },
1447
+ primary: "#6BD39A",
1448
+ onPrimary: "#0E1F17",
1449
+ accent: "#6BD39A",
1450
+ onAccent: "#0E1F17",
1451
+ accentEdge: "#34D888",
1452
+ success: "#07C168",
1453
+ danger: "#B91C1C",
1454
+ errorRed: "#FF1B00",
1455
+ warningStrong: "#A45610",
1456
+ cautionAccent: "#D9821D",
1457
+ riskConcern: "#EFA700",
1458
+ badgeBgPositive: "rgba(7,193,104,0.18)",
1459
+ badgeBgCaution: "rgba(217,130,29,0.20)",
1460
+ badgeBgCritical: "rgba(185,28,28,0.22)",
1461
+ badgeBgNeutral: "rgba(255,255,255,0.10)",
1462
+ bubbleUser: "#6BD39A",
1463
+ bubbleAssistant: "#1C1F23",
1464
+ skeleton: "#23272C",
1465
+ scanButtonPink: "#FFC3BC",
1466
+ checkupCardLowRiskBg: "rgba(7,193,104,0.16)",
1467
+ checkupCardConcernBg: "rgba(239,167,0,0.16)"
1468
+ };
1469
+ deepFreeze({
1470
+ brightness: "dark",
1471
+ meta: { displayName: "Everfur", logoUrl: null, placeholder: null, hidePoweredBy: false },
1472
+ color: DARK_COLOR,
1473
+ space: SPACE,
1474
+ radius: RADIUS,
1475
+ type: baseType(),
1476
+ motion: MOTION
1477
+ });
1478
+ var EVERFUR_THEME_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurThemeContext@v1");
1479
+ var globalThemeHost = globalThis;
1480
+ var EverfurThemeContext = globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] ?? (globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL] = createContext(EVERFUR_LIGHT));
1481
+ EverfurThemeContext.displayName ??= "EverfurThemeContext";
1482
+ function useEverfurTheme() {
1483
+ return useContext(EverfurThemeContext);
1484
+ }
1485
+
1486
+ // src/rn/facade.ts
1487
+ var EVERFUR_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("@everfur/sdk#EverfurContext@v1");
1488
+ var globalContextHost = globalThis;
1489
+ var EverfurContext = globalContextHost[EVERFUR_CONTEXT_SYMBOL] ?? (globalContextHost[EVERFUR_CONTEXT_SYMBOL] = createContext(null));
1490
+ EverfurContext.displayName ??= "EverfurContext";
1491
+ function useEverfurContext() {
1492
+ const ctx = useContext(EverfurContext);
1493
+ if (ctx === null) {
1494
+ throw new EverfurConfigError(
1495
+ "not-initialized",
1496
+ "Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high."
1497
+ );
1498
+ }
1499
+ return ctx;
1500
+ }
1501
+
1502
+ // src/rn/video/useVideo.ts
1503
+ var BOOTSTRAP_SNAPSHOT = Object.freeze({
1504
+ status: "idle",
1505
+ job: null,
1506
+ result: null,
1507
+ error: null,
1508
+ isCaptureAvailable: false,
1509
+ progress: 0
1510
+ });
1511
+ var NOOP_UNSUBSCRIBE = () => {
1512
+ };
1513
+ function useEverfurVideo(opts) {
1514
+ const { runtime, userRef, activePet } = useEverfurContext();
1515
+ const petRef = opts?.petRef ?? activePet ?? null;
1516
+ const [controller, setController] = useState(null);
1517
+ useEffect(() => {
1518
+ const { services } = runtime.registry;
1519
+ const acquired = runtime.registry.acquire(
1520
+ "video",
1521
+ `${userRef ?? ""}|${petRef ?? ""}`,
1522
+ () => createVideoController({
1523
+ ...services.errorPolicy ? { errorPolicy: services.errorPolicy } : {},
1524
+ auth: services.authFor(userRef),
1525
+ camera: services.camera,
1526
+ upload: services.upload,
1527
+ petRef,
1528
+ telemetry: services.telemetry
1529
+ }),
1530
+ (controller2) => controller2.dispose()
1531
+ );
1532
+ setController(acquired);
1533
+ return () => {
1534
+ setController((current) => current === acquired ? null : current);
1535
+ runtime.registry.release(acquired);
1536
+ };
1537
+ }, [runtime, userRef, petRef]);
1538
+ const subscribe = useCallback(
1539
+ (onChange) => controller ? controller.subscribe(onChange) : NOOP_UNSUBSCRIBE,
1540
+ [controller]
1541
+ );
1542
+ const getSnapshot = useCallback(
1543
+ () => controller ? controller.getSnapshot() : BOOTSTRAP_SNAPSHOT,
1544
+ [controller]
1545
+ );
1546
+ const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
1547
+ const submit = useCallback(
1548
+ (source) => controller ? controller.submit(source) : Promise.resolve(notReadyError()),
1549
+ [controller]
1550
+ );
1551
+ const capture = useCallback(
1552
+ () => controller ? controller.capture() : Promise.resolve(notReadyError()),
1553
+ [controller]
1554
+ );
1555
+ const cancel = useCallback(() => {
1556
+ controller?.cancel();
1557
+ }, [controller]);
1558
+ return useMemo(
1559
+ () => ({
1560
+ status: snapshot.status,
1561
+ job: snapshot.job,
1562
+ result: snapshot.result,
1563
+ error: snapshot.error,
1564
+ isCaptureAvailable: snapshot.isCaptureAvailable,
1565
+ progress: snapshot.progress,
1566
+ isBootstrapping: controller === null,
1567
+ submit,
1568
+ capture,
1569
+ cancel
1570
+ }),
1571
+ [snapshot, controller, submit, capture, cancel]
1572
+ );
1573
+ }
1574
+ function notReadyError() {
1575
+ return err(
1576
+ makeEverfurError("internalError", { retryable: true })
1577
+ );
1578
+ }
1579
+ function useCapability(name) {
1580
+ const { runtime } = useEverfurContext();
1581
+ const store = runtime.entitlements;
1582
+ const snapshot = useSyncExternalStore(
1583
+ store.subscribe,
1584
+ store.getSnapshot,
1585
+ store.getSnapshot
1586
+ );
1587
+ return useMemo(
1588
+ () => decideCapability(name, snapshot.decisions, { isPending: snapshot.isPending }),
1589
+ [name, snapshot]
1590
+ );
1591
+ }
1592
+ var MIN_OFFSTATE_HEIGHT = 48;
1593
+ function selectView(decision) {
1594
+ if (decision.isPending) return "pending";
1595
+ return decision.enabled ? "enabled" : "disabled";
1596
+ }
1597
+ function CapabilityGate(props) {
1598
+ const { capability, children, renderDisabled, renderPending, style } = props;
1599
+ const decision = useCapability(capability);
1600
+ const view = useMemo(() => selectView(decision), [decision]);
1601
+ switch (view) {
1602
+ case "enabled":
1603
+ return children;
1604
+ case "pending":
1605
+ return renderPending ? renderPending() : /* @__PURE__ */ jsx(PendingSkeleton, { capability, style });
1606
+ case "disabled":
1607
+ return renderDisabled ? renderDisabled(decision) : /* @__PURE__ */ jsx(OffState, { decision, style });
1608
+ default:
1609
+ return assertNever(view);
1610
+ }
1611
+ }
1612
+ function PendingSkeleton({
1613
+ capability,
1614
+ style
1615
+ }) {
1616
+ const theme = useEverfurTheme();
1617
+ const styles = useMemo(() => makeStyles(theme), [theme]);
1618
+ return /* @__PURE__ */ jsx(
1619
+ View,
1620
+ {
1621
+ style: [styles.offstate, style],
1622
+ accessible: true,
1623
+ accessibilityState: { busy: true },
1624
+ accessibilityLabel: `Loading ${capability}`,
1625
+ children: /* @__PURE__ */ jsx(View, { style: styles.skeletonBar })
1626
+ }
1627
+ );
1628
+ }
1629
+ function OffState({
1630
+ decision,
1631
+ style
1632
+ }) {
1633
+ const theme = useEverfurTheme();
1634
+ const styles = useMemo(() => makeStyles(theme), [theme]);
1635
+ const message = decision.disabled?.reason ?? "";
1636
+ return /* @__PURE__ */ jsx(
1637
+ View,
1638
+ {
1639
+ style: [styles.offstate, style],
1640
+ accessible: true,
1641
+ accessibilityRole: "text",
1642
+ accessibilityLabel: message,
1643
+ children: message.length > 0 ? /* @__PURE__ */ jsx(Text, { style: styles.offstateText, children: message }) : null
1644
+ }
1645
+ );
1646
+ }
1647
+ function makeStyles(theme) {
1648
+ const { color, space, radius, type } = theme;
1649
+ return StyleSheet.create({
1650
+ // A deliberate cream card with a soft brand hairline, never a bare grey slab.
1651
+ offstate: {
1652
+ minHeight: MIN_OFFSTATE_HEIGHT,
1653
+ justifyContent: "center",
1654
+ paddingHorizontal: space.lg,
1655
+ paddingVertical: space.md,
1656
+ backgroundColor: color.surfaceCream,
1657
+ borderRadius: radius.md,
1658
+ borderWidth: StyleSheet.hairlineWidth,
1659
+ borderColor: color.brandBorder
1660
+ },
1661
+ offstateText: {
1662
+ fontFamily: type.family,
1663
+ fontSize: type.size.body,
1664
+ lineHeight: Math.round(type.size.body * type.lineHeight.normal),
1665
+ color: color.text.muted
1666
+ },
1667
+ // A soft green shimmer bar (brand wash) that stays legible on the cream card in both light and dark,
1668
+ // where the neutral `skeleton` token would collide with the dark cream surface.
1669
+ skeletonBar: {
1670
+ height: space.md,
1671
+ borderRadius: radius.xs,
1672
+ backgroundColor: color.brandSofter
1673
+ }
1674
+ });
1675
+ }
1676
+ var CLINICAL_DISCLAIMER = Object.freeze({
1677
+ title: "For educational use only",
1678
+ body: "Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."
1679
+ });
1680
+ function ClinicalDisclaimer(props) {
1681
+ const theme = useEverfurTheme();
1682
+ const styles = useMemo(() => makeStyles2(theme), [theme]);
1683
+ return /* @__PURE__ */ jsxs(
1684
+ View,
1685
+ {
1686
+ style: [styles.container, props.style],
1687
+ accessible: true,
1688
+ accessibilityRole: "text",
1689
+ accessibilityLabel: `${CLINICAL_DISCLAIMER.title}. ${CLINICAL_DISCLAIMER.body}`,
1690
+ children: [
1691
+ /* @__PURE__ */ jsx(Text, { style: styles.title, children: CLINICAL_DISCLAIMER.title }),
1692
+ /* @__PURE__ */ jsx(Text, { style: styles.body, children: CLINICAL_DISCLAIMER.body })
1693
+ ]
1694
+ }
1695
+ );
1696
+ }
1697
+ function makeStyles2(theme) {
1698
+ const { color, space, type } = theme;
1699
+ return StyleSheet.create({
1700
+ container: {
1701
+ paddingHorizontal: space.lg,
1702
+ paddingVertical: space.md,
1703
+ borderTopWidth: StyleSheet.hairlineWidth,
1704
+ borderTopColor: color.borderHairlineGreen,
1705
+ backgroundColor: color.surfaceCream,
1706
+ gap: space.xs
1707
+ },
1708
+ title: {
1709
+ fontFamily: type.family,
1710
+ fontSize: type.size.caption,
1711
+ lineHeight: Math.round(type.size.caption * type.lineHeight.snug),
1712
+ color: color.text.secondary,
1713
+ fontWeight: type.weight.bold,
1714
+ letterSpacing: type.letterSpacing.eyebrow
1715
+ },
1716
+ body: {
1717
+ fontFamily: type.family,
1718
+ fontSize: type.size.caption,
1719
+ lineHeight: Math.round(type.size.caption * type.lineHeight.snug),
1720
+ color: color.text.muted,
1721
+ fontWeight: type.weight.regular
1722
+ }
1723
+ });
1724
+ }
1725
+ var SPINNER_DELAY_MS = 300;
1726
+ var MIN_SURFACE_HEIGHT = 120;
1727
+ var TOUCH_TARGET = 44;
1728
+ var GLYPH_SIZE = 40;
1729
+ var PROGRESS_TRACK_WIDTH = 160;
1730
+ function EverfurVideo(props) {
1731
+ const { petRef, style } = props;
1732
+ return /* @__PURE__ */ jsx(CapabilityGate, { capability: "video", style, children: /* @__PURE__ */ jsx(VideoBody, { petRef, style }) });
1733
+ }
1734
+ function selectView2(state) {
1735
+ if (state.isBootstrapping) return "loading";
1736
+ if (state.status === "uploading" || state.status === "analyzing") return "loading";
1737
+ if (state.status === "error" && state.error) return "error";
1738
+ if (state.status === "complete" && state.result) return "populated";
1739
+ if (!state.isCaptureAvailable) return "native";
1740
+ return "empty";
1741
+ }
1742
+ function VideoBody({
1743
+ petRef,
1744
+ style
1745
+ }) {
1746
+ const videoOpts = useMemo(() => petRef !== void 0 ? { petRef } : void 0, [petRef]);
1747
+ const video = useEverfurVideo(videoOpts);
1748
+ const view = selectView2(video);
1749
+ const { styles } = useVideoStyles();
1750
+ return /* @__PURE__ */ jsxs(View, { style: [styles.container, style], children: [
1751
+ /* @__PURE__ */ jsx(View, { style: styles.body, children: renderView(view, video) }),
1752
+ /* @__PURE__ */ jsx(ClinicalDisclaimer, {})
1753
+ ] });
1754
+ }
1755
+ function renderView(view, video) {
1756
+ switch (view) {
1757
+ case "loading":
1758
+ return /* @__PURE__ */ jsx(LoadingState, { progress: video.progress });
1759
+ case "native":
1760
+ return /* @__PURE__ */ jsx(NativeUnavailableState, {});
1761
+ case "empty":
1762
+ return /* @__PURE__ */ jsx(EmptyState, { onCapture: video.capture });
1763
+ case "error":
1764
+ return /* @__PURE__ */ jsx(ErrorState, { error: video.error, onRetry: video.capture });
1765
+ case "populated":
1766
+ return /* @__PURE__ */ jsx(ResultState, { result: video.result });
1767
+ default:
1768
+ return assertNever(view);
1769
+ }
1770
+ }
1771
+ function LoadingState({ progress }) {
1772
+ const { theme, styles } = useVideoStyles();
1773
+ const [visible, setVisible] = useState(false);
1774
+ useEffect(() => {
1775
+ const id = setTimeout(() => setVisible(true), SPINNER_DELAY_MS);
1776
+ return () => clearTimeout(id);
1777
+ }, []);
1778
+ const pct = Math.max(0, Math.min(1, progress));
1779
+ return /* @__PURE__ */ jsxs(View, { style: styles.centered, accessible: true, accessibilityState: { busy: true }, accessibilityLabel: "Analyzing video", children: [
1780
+ visible ? /* @__PURE__ */ jsx(ActivityIndicator, { color: theme.color.brand }) : null,
1781
+ visible && pct > 0 && pct < 1 ? /* @__PURE__ */ jsx(View, { style: styles.progressTrack, accessibilityRole: "progressbar", children: /* @__PURE__ */ jsx(View, { style: [styles.progressFill, { width: `${Math.round(pct * 100)}%` }] }) }) : null
1782
+ ] });
1783
+ }
1784
+ function NativeUnavailableState() {
1785
+ const { styles } = useVideoStyles();
1786
+ return /* @__PURE__ */ jsx(View, { style: styles.offstate, accessible: true, accessibilityRole: "text", accessibilityLabel: "Camera is unavailable", children: /* @__PURE__ */ jsx(View, { style: styles.emptyGlyph }) });
1787
+ }
1788
+ function EmptyState({ onCapture }) {
1789
+ const { styles } = useVideoStyles();
1790
+ return /* @__PURE__ */ jsx(View, { style: styles.centered, accessible: true, accessibilityRole: "summary", accessibilityLabel: "Record a short clip to check gait", children: /* @__PURE__ */ jsx(
1791
+ Pressable,
1792
+ {
1793
+ onPress: onCapture,
1794
+ accessibilityRole: "button",
1795
+ accessibilityLabel: "Record video",
1796
+ style: styles.primaryButton,
1797
+ children: /* @__PURE__ */ jsx(Text, { style: styles.primaryLabel, children: "Record video" })
1798
+ }
1799
+ ) });
1800
+ }
1801
+ function ErrorState({ error, onRetry }) {
1802
+ const { styles } = useVideoStyles();
1803
+ return /* @__PURE__ */ jsxs(View, { style: styles.centered, accessible: true, accessibilityRole: "alert", children: [
1804
+ /* @__PURE__ */ jsx(Text, { style: styles.errorText, children: error.displayMessage }),
1805
+ error.retryable ? /* @__PURE__ */ jsx(Pressable, { onPress: onRetry, accessibilityRole: "button", accessibilityLabel: "Try again", style: styles.primaryButton, children: /* @__PURE__ */ jsx(Text, { style: styles.primaryLabel, children: "Try again" }) }) : null
1806
+ ] });
1807
+ }
1808
+ function ResultState({ result }) {
1809
+ const { styles } = useVideoStyles();
1810
+ if (!result.quality.usable) {
1811
+ return /* @__PURE__ */ jsx(View, { style: styles.centered, accessible: true, accessibilityRole: "summary", accessibilityLabel: "Result uncertain", children: /* @__PURE__ */ jsx(Text, { style: styles.uncertainText, children: "We could not get a clear read from this clip. Try recording again." }) });
1812
+ }
1813
+ return /* @__PURE__ */ jsxs(ScrollView, { style: styles.list, contentContainerStyle: styles.listContent, accessibilityLabel: "Gait analysis result", children: [
1814
+ result.detections.map((detection, index) => /* @__PURE__ */ jsx(View, { style: styles.resultRow, children: /* @__PURE__ */ jsx(Text, { style: styles.resultLabel, children: detection.label }) }, `${detection.label}-${index}`)),
1815
+ result.interpretation ? /* @__PURE__ */ jsxs(View, { style: styles.interpretationBlock, children: [
1816
+ /* @__PURE__ */ jsx(Text, { style: styles.summaryText, children: result.interpretation.summary }),
1817
+ /* @__PURE__ */ jsx(Text, { style: styles.disclaimerText, children: result.interpretation.disclaimer })
1818
+ ] }) : null
1819
+ ] });
1820
+ }
1821
+ function useVideoStyles() {
1822
+ const theme = useEverfurTheme();
1823
+ return useMemo(() => ({ theme, styles: makeStyles3(theme) }), [theme]);
1824
+ }
1825
+ function makeStyles3(theme) {
1826
+ const { color, space, radius, type } = theme;
1827
+ const boldWeight = type.weight.bold;
1828
+ const mediumWeight = type.weight.medium;
1829
+ return StyleSheet.create({
1830
+ // Themed ground so the surface is never a bare/transparent region and holds contrast in both schemes.
1831
+ container: { flex: 1, minHeight: MIN_SURFACE_HEIGHT, backgroundColor: color.background },
1832
+ body: { flex: 1 },
1833
+ centered: {
1834
+ minHeight: MIN_SURFACE_HEIGHT,
1835
+ flexGrow: 1,
1836
+ alignItems: "center",
1837
+ justifyContent: "center",
1838
+ padding: space.xl
1839
+ },
1840
+ offstate: {
1841
+ minHeight: MIN_SURFACE_HEIGHT,
1842
+ alignItems: "center",
1843
+ justifyContent: "center",
1844
+ padding: space.xl
1845
+ },
1846
+ // Camera-unavailable placeholder: a cream disc ringed with the brand hairline (intentional, not a grey dot).
1847
+ emptyGlyph: {
1848
+ width: GLYPH_SIZE,
1849
+ height: GLYPH_SIZE,
1850
+ borderRadius: radius.pill,
1851
+ backgroundColor: color.surfaceCream,
1852
+ borderWidth: StyleSheet.hairlineWidth,
1853
+ borderColor: color.borderHairlineGreen
1854
+ },
1855
+ // Capture / retry CTA: brand-green pill on a soft brand shadow (alpha baked into the token color).
1856
+ primaryButton: {
1857
+ minHeight: TOUCH_TARGET,
1858
+ minWidth: TOUCH_TARGET,
1859
+ alignItems: "center",
1860
+ justifyContent: "center",
1861
+ paddingHorizontal: space.xl,
1862
+ paddingVertical: space.md,
1863
+ borderRadius: radius.pill,
1864
+ backgroundColor: color.primary,
1865
+ shadowColor: color.brandSofter,
1866
+ shadowOffset: { width: 0, height: space.xs },
1867
+ shadowOpacity: 1,
1868
+ shadowRadius: space.sm,
1869
+ elevation: space.xs
1870
+ },
1871
+ primaryLabel: {
1872
+ color: color.onPrimary,
1873
+ fontFamily: type.family,
1874
+ fontSize: type.size.body,
1875
+ fontWeight: boldWeight,
1876
+ letterSpacing: type.letterSpacing.tight
1877
+ },
1878
+ errorText: {
1879
+ color: color.danger,
1880
+ fontFamily: type.family,
1881
+ fontSize: type.size.subtitle,
1882
+ lineHeight: type.size.subtitle * type.lineHeight.normal,
1883
+ fontWeight: mediumWeight,
1884
+ textAlign: "center",
1885
+ marginBottom: space.md
1886
+ },
1887
+ uncertainText: {
1888
+ color: color.text.muted,
1889
+ fontFamily: type.family,
1890
+ fontSize: type.size.subtitle,
1891
+ lineHeight: type.size.subtitle * type.lineHeight.normal,
1892
+ textAlign: "center"
1893
+ },
1894
+ // Progress groove (skeleton wash) with a brand-green fill -- replaces the grey-track / blue-fill default.
1895
+ progressTrack: {
1896
+ marginTop: space.lg,
1897
+ height: space.sm,
1898
+ width: PROGRESS_TRACK_WIDTH,
1899
+ borderRadius: radius.pill,
1900
+ backgroundColor: color.skeleton,
1901
+ overflow: "hidden"
1902
+ },
1903
+ progressFill: { height: space.sm, borderRadius: radius.pill, backgroundColor: color.brand },
1904
+ list: { flex: 1 },
1905
+ listContent: { padding: space.lg, gap: space.md },
1906
+ // Detection rows: cream cards lifted off the ground by a hairline brand border (depth via layering).
1907
+ resultRow: {
1908
+ paddingVertical: space.sm,
1909
+ paddingHorizontal: space.md,
1910
+ borderRadius: radius.sm,
1911
+ backgroundColor: color.surfaceCream,
1912
+ borderWidth: StyleSheet.hairlineWidth,
1913
+ borderColor: color.brandBorder
1914
+ },
1915
+ resultLabel: {
1916
+ color: color.text.primary,
1917
+ fontFamily: type.family,
1918
+ fontSize: type.size.body,
1919
+ lineHeight: type.size.body * type.lineHeight.normal,
1920
+ fontWeight: mediumWeight
1921
+ },
1922
+ interpretationBlock: { marginTop: space.sm, gap: space.sm },
1923
+ summaryText: {
1924
+ color: color.text.primary,
1925
+ fontFamily: type.family,
1926
+ fontSize: type.size.subtitle,
1927
+ lineHeight: type.size.subtitle * type.lineHeight.normal
1928
+ },
1929
+ disclaimerText: {
1930
+ color: color.text.muted,
1931
+ fontFamily: type.family,
1932
+ fontSize: type.size.caption,
1933
+ lineHeight: type.size.caption * type.lineHeight.relaxed
1934
+ }
1935
+ });
1936
+ }
1937
+
1938
+ export { EverfurVideo, useEverfurVideo };