@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.
- package/CHANGELOG.md +74 -0
- package/LICENSE +21 -0
- package/README.md +161 -0
- package/animations/package.json +8 -0
- package/chat/package.json +8 -0
- package/client/package.json +8 -0
- package/core/package.json +8 -0
- package/dist/CameraPort-Cv31Pz7g.d.cts +29 -0
- package/dist/CameraPort-Cv31Pz7g.d.ts +29 -0
- package/dist/ChatController-CKdBvPj2.d.ts +146 -0
- package/dist/ChatController-CpUMvvZf.d.cts +146 -0
- package/dist/EverfurResult-D92-uL82.d.cts +240 -0
- package/dist/EverfurResult-D92-uL82.d.ts +240 -0
- package/dist/FilePort-BabWrv7I.d.cts +22 -0
- package/dist/FilePort-BabWrv7I.d.ts +22 -0
- package/dist/PhotoController-BItt5M7u.d.cts +43 -0
- package/dist/PhotoController-D8zMTdcW.d.ts +43 -0
- package/dist/TelemetryPort-BDNr00hu.d.cts +12 -0
- package/dist/TelemetryPort-BDNr00hu.d.ts +12 -0
- package/dist/animations/index.cjs +1997 -0
- package/dist/animations/index.d.cts +517 -0
- package/dist/animations/index.d.ts +517 -0
- package/dist/animations/index.js +1972 -0
- package/dist/cacheEpoch-DknKn3S0.d.cts +36 -0
- package/dist/cacheEpoch-DknKn3S0.d.ts +36 -0
- package/dist/chat/index.cjs +1170 -0
- package/dist/chat/index.d.cts +59 -0
- package/dist/chat/index.d.ts +59 -0
- package/dist/chat/index.js +1167 -0
- package/dist/client/index.cjs +2317 -0
- package/dist/client/index.d.cts +65 -0
- package/dist/client/index.d.ts +65 -0
- package/dist/client/index.js +2217 -0
- package/dist/config-BSjBdxrZ.d.cts +501 -0
- package/dist/config-CiJ0PVBB.d.ts +501 -0
- package/dist/core/index.cjs +3175 -0
- package/dist/core/index.d.cts +70 -0
- package/dist/core/index.d.ts +70 -0
- package/dist/core/index.js +3163 -0
- package/dist/identity-Brl-lDd6.d.cts +91 -0
- package/dist/identity-DK9zORrG.d.ts +91 -0
- package/dist/ids-CJ1S6adf.d.cts +46 -0
- package/dist/ids-CJ1S6adf.d.ts +46 -0
- package/dist/index.cjs +4488 -0
- package/dist/index.d.cts +156 -0
- package/dist/index.d.ts +156 -0
- package/dist/index.js +4464 -0
- package/dist/petsRepository-BEGb97M9.d.cts +326 -0
- package/dist/petsRepository-Bu18r2kK.d.ts +326 -0
- package/dist/photo/index.cjs +2189 -0
- package/dist/photo/index.d.cts +43 -0
- package/dist/photo/index.d.ts +43 -0
- package/dist/photo/index.js +2186 -0
- package/dist/projection-CeIUsbSk.d.cts +8 -0
- package/dist/projection-CeIUsbSk.d.ts +8 -0
- package/dist/records/index.cjs +2840 -0
- package/dist/records/index.d.cts +224 -0
- package/dist/records/index.d.ts +224 -0
- package/dist/records/index.js +2834 -0
- package/dist/requestFunnel-DuUH-kAe.d.cts +28 -0
- package/dist/requestFunnel-dio5OmR9.d.ts +28 -0
- package/dist/resolve-Dq_4_agU.d.cts +86 -0
- package/dist/resolve-Dq_4_agU.d.ts +86 -0
- package/dist/runtime-BgQnA594.d.cts +349 -0
- package/dist/runtime-CBA-LvdM.d.ts +349 -0
- package/dist/server/index.cjs +533 -0
- package/dist/server/index.d.cts +48 -0
- package/dist/server/index.d.ts +48 -0
- package/dist/server/index.js +530 -0
- package/dist/testing/index.cjs +825 -0
- package/dist/testing/index.d.cts +113 -0
- package/dist/testing/index.d.ts +113 -0
- package/dist/testing/index.js +822 -0
- package/dist/testing/rn/index.cjs +449 -0
- package/dist/testing/rn/index.d.cts +49 -0
- package/dist/testing/rn/index.d.ts +49 -0
- package/dist/testing/rn/index.js +444 -0
- package/dist/video/index.cjs +1941 -0
- package/dist/video/index.d.cts +66 -0
- package/dist/video/index.d.ts +66 -0
- package/dist/video/index.js +1938 -0
- package/package.json +311 -0
- package/photo/package.json +8 -0
- package/records/package.json +8 -0
- package/server/device-blocked.cjs +15 -0
- package/server/package.json +9 -0
- package/testing/package.json +8 -0
- package/testing/rn/package.json +8 -0
- package/video/package.json +8 -0
|
@@ -0,0 +1,3175 @@
|
|
|
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;
|
|
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
|
+
/**
|
|
2916
|
+
* Build the entitlement poller. `authFor` re-derives the device AuthContext each poll (so a token refresh /
|
|
2917
|
+
* re-scope is reflected), and `update` feeds the resolved decisions into the render store. The SERVER stays
|
|
2918
|
+
* authoritative; this only populates what the SDK renders.
|
|
2919
|
+
*/
|
|
2920
|
+
buildPoller(scheduler) {
|
|
2921
|
+
return createEntitlementPoller({
|
|
2922
|
+
authFor: () => this.buildAuth(this.currentUser?.userRef ?? null),
|
|
2923
|
+
update: (decisions, branding) => this.updateEntitlements({ decisions, isPending: false, branding }),
|
|
2924
|
+
telemetry: this.telemetry,
|
|
2925
|
+
...scheduler ? { scheduler } : {}
|
|
2926
|
+
});
|
|
2927
|
+
}
|
|
2928
|
+
// ---- ref-counted acquire / release (epoch-keyed) -----------------------
|
|
2929
|
+
acquireInternal(kind, scopeKey, create, destroy) {
|
|
2930
|
+
const key = `${this.epoch}|${kind}|${scopeKey}`;
|
|
2931
|
+
const existing = this.entries.get(key);
|
|
2932
|
+
if (existing) {
|
|
2933
|
+
existing.refCount += 1;
|
|
2934
|
+
return existing.controller;
|
|
2935
|
+
}
|
|
2936
|
+
const controller = create();
|
|
2937
|
+
this.entries.set(key, { controller, refCount: 1 });
|
|
2938
|
+
this.destroyers.set(controller, destroy);
|
|
2939
|
+
return controller;
|
|
2940
|
+
}
|
|
2941
|
+
releaseInternal(controller) {
|
|
2942
|
+
for (const [key, entry] of this.entries) {
|
|
2943
|
+
if (entry.controller !== controller) continue;
|
|
2944
|
+
entry.refCount -= 1;
|
|
2945
|
+
if (entry.refCount <= 0) {
|
|
2946
|
+
this.runDestroyer(controller);
|
|
2947
|
+
this.entries.delete(key);
|
|
2948
|
+
}
|
|
2949
|
+
return;
|
|
2950
|
+
}
|
|
2951
|
+
}
|
|
2952
|
+
runDestroyer(controller) {
|
|
2953
|
+
const destroy = this.destroyers.get(controller);
|
|
2954
|
+
this.destroyers.delete(controller);
|
|
2955
|
+
if (destroy) destroy(controller);
|
|
2956
|
+
}
|
|
2957
|
+
// ---- controller construction (only the spine capability is built here) -
|
|
2958
|
+
buildChatController(scope) {
|
|
2959
|
+
const controller = createChatController({
|
|
2960
|
+
auth: this.buildAuth(scope.userRef),
|
|
2961
|
+
telemetry: this.telemetry,
|
|
2962
|
+
...this.errorPolicy ? { errorPolicy: this.errorPolicy } : {},
|
|
2963
|
+
initialConversationId: scope.conversationId
|
|
2964
|
+
});
|
|
2965
|
+
const input = {};
|
|
2966
|
+
if (scope.petRef !== null) input.petRef = scope.petRef;
|
|
2967
|
+
if (scope.conversationId !== null) input.resumeConversationId = scope.conversationId;
|
|
2968
|
+
void bootstrapChat(input, { controller }).then((result) => controller.adoptPrompts(result.suggestedPrompts)).catch(() => {
|
|
2969
|
+
});
|
|
2970
|
+
return controller;
|
|
2971
|
+
}
|
|
2972
|
+
buildAuth(scopeUserRef) {
|
|
2973
|
+
if (this.identity !== null && this.currentUser !== null) {
|
|
2974
|
+
return {
|
|
2975
|
+
mode: "personalized",
|
|
2976
|
+
transport: this.transport,
|
|
2977
|
+
identity: this.identity,
|
|
2978
|
+
userRef: this.currentUser.userRef,
|
|
2979
|
+
sessionId: this.sessionId
|
|
2980
|
+
};
|
|
2981
|
+
}
|
|
2982
|
+
return {
|
|
2983
|
+
mode: "anonymous",
|
|
2984
|
+
transport: this.transport,
|
|
2985
|
+
publishableKey: this.publishableKey,
|
|
2986
|
+
// Only name a user while one is actually signed in. `scopeUserRef` is the REGISTRY scope key,
|
|
2987
|
+
// taken from the host's `user` prop, which a `logout()` call does not touch — so carrying it here
|
|
2988
|
+
// meant that after sign-out the SDK kept sending `x-everfur-user-ref` for the signed-out user
|
|
2989
|
+
// alongside the publishable key, and the widget plane resolves identity from exactly that pair.
|
|
2990
|
+
userRef: this.currentUser === null ? null : scopeUserRef,
|
|
2991
|
+
sessionId: this.sessionId
|
|
2992
|
+
};
|
|
2993
|
+
}
|
|
2994
|
+
// ---- imperative verbs (re-scope in one commit; SPEC-10 §3) -------------
|
|
2995
|
+
setUser(user) {
|
|
2996
|
+
if (this.disposed) return;
|
|
2997
|
+
const nextRef = user?.userRef ?? null;
|
|
2998
|
+
const currentRef = this.currentUser?.userRef ?? null;
|
|
2999
|
+
if (nextRef === currentRef) {
|
|
3000
|
+
this.currentUser = user;
|
|
3001
|
+
if (user && this.identity === null) {
|
|
3002
|
+
this.identity = createIdentityProvider(user.userRef, user.getToken);
|
|
3003
|
+
}
|
|
3004
|
+
return;
|
|
3005
|
+
}
|
|
3006
|
+
this.identity?.clear();
|
|
3007
|
+
this.currentUser = user;
|
|
3008
|
+
this.identity = user ? createIdentityProvider(user.userRef, user.getToken) : null;
|
|
3009
|
+
this.rescopeAll();
|
|
3010
|
+
}
|
|
3011
|
+
async logout() {
|
|
3012
|
+
if (this.disposed) return;
|
|
3013
|
+
const wasAnonymous = this.currentUser === null;
|
|
3014
|
+
this.sessionId = newSessionId();
|
|
3015
|
+
this.setUser(null);
|
|
3016
|
+
if (wasAnonymous) this.rescopeAll();
|
|
3017
|
+
await this.sweepPerUserKv();
|
|
3018
|
+
}
|
|
3019
|
+
async sweepPerUserKv() {
|
|
3020
|
+
if (PER_USER_KV_KEYS.length === 0) return;
|
|
3021
|
+
const results = await Promise.allSettled(
|
|
3022
|
+
PER_USER_KV_KEYS.map((key) => this.kv.removeItem(key))
|
|
3023
|
+
);
|
|
3024
|
+
const failedCount = results.filter((result) => result.status === "rejected").length;
|
|
3025
|
+
if (failedCount > 0) {
|
|
3026
|
+
this.telemetry.track("sdk.logout.sweepPartialFailure", {
|
|
3027
|
+
failedCount,
|
|
3028
|
+
totalCount: results.length
|
|
3029
|
+
});
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
async registerPet(pet, profile) {
|
|
3033
|
+
if (this.disposed) {
|
|
3034
|
+
return err(
|
|
3035
|
+
makeEverfurError("validationFailed", {
|
|
3036
|
+
retryable: false,
|
|
3037
|
+
wireMessage: "the Everfur runtime is disposed; registerPet was called after unmount"
|
|
3038
|
+
})
|
|
3039
|
+
);
|
|
3040
|
+
}
|
|
3041
|
+
const repo = createPetsRepository(this.buildAuth(this.currentUser?.userRef ?? null));
|
|
3042
|
+
return profile === void 0 ? repo.registerPet(pet) : repo.registerPet(pet, profile);
|
|
3043
|
+
}
|
|
3044
|
+
setActivePet(pet) {
|
|
3045
|
+
if (this.disposed) return;
|
|
3046
|
+
const next = pet ?? null;
|
|
3047
|
+
if (next === this.activePet) return;
|
|
3048
|
+
this.activePet = next;
|
|
3049
|
+
this.rescopeAll();
|
|
3050
|
+
}
|
|
3051
|
+
updateEntitlements(next) {
|
|
3052
|
+
if (this.disposed) return;
|
|
3053
|
+
if (this.configFailure !== null) return;
|
|
3054
|
+
this.store.set(next);
|
|
3055
|
+
}
|
|
3056
|
+
open(capability) {
|
|
3057
|
+
this.telemetry.track("sdk.open", { capability });
|
|
3058
|
+
}
|
|
3059
|
+
dispose() {
|
|
3060
|
+
if (this.disposed) return;
|
|
3061
|
+
this.disposed = true;
|
|
3062
|
+
this.epoch += 1;
|
|
3063
|
+
this.poller?.stop();
|
|
3064
|
+
this.identity?.clear();
|
|
3065
|
+
this.disposeAllControllers();
|
|
3066
|
+
}
|
|
3067
|
+
rescopeAll() {
|
|
3068
|
+
this.epoch += 1;
|
|
3069
|
+
this.disposeAllControllers();
|
|
3070
|
+
this.store.reset();
|
|
3071
|
+
this.poller?.refresh();
|
|
3072
|
+
}
|
|
3073
|
+
disposeAllControllers() {
|
|
3074
|
+
for (const entry of this.entries.values()) this.runDestroyer(entry.controller);
|
|
3075
|
+
this.entries.clear();
|
|
3076
|
+
this.destroyers.clear();
|
|
3077
|
+
}
|
|
3078
|
+
};
|
|
3079
|
+
function tryResolveClient(cfg) {
|
|
3080
|
+
const clientCfg = {
|
|
3081
|
+
publishableKey: cfg.publishableKey,
|
|
3082
|
+
...cfg.apiBaseUrl !== void 0 ? { apiBaseUrl: cfg.apiBaseUrl } : {},
|
|
3083
|
+
...cfg.contractVersion !== void 0 ? { contractVersion: cfg.contractVersion } : {},
|
|
3084
|
+
...cfg.debug !== void 0 ? { debug: cfg.debug } : {}
|
|
3085
|
+
};
|
|
3086
|
+
return tryResolveClientConfig(clientCfg);
|
|
3087
|
+
}
|
|
3088
|
+
function reportConfigFailure(failure, telemetry) {
|
|
3089
|
+
try {
|
|
3090
|
+
telemetry.trackExpectedFailure("sdk.config.invalid", { reason: failure.reason });
|
|
3091
|
+
} catch {
|
|
3092
|
+
}
|
|
3093
|
+
const globalConsole = globalThis.console;
|
|
3094
|
+
globalConsole?.error?.(
|
|
3095
|
+
`[everfur] SDK disabled: ${failure.message}
|
|
3096
|
+
[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.`
|
|
3097
|
+
);
|
|
3098
|
+
}
|
|
3099
|
+
function refusingTransport(failure) {
|
|
3100
|
+
const build = () => (
|
|
3101
|
+
// NOT `internalError`: the funnel's `decideRetry` keys on `isAutoRetryable(code)` and deliberately
|
|
3102
|
+
// ignores `error.retryable`, so `internalError` would be retried with backoff on every call even though
|
|
3103
|
+
// it can never succeed; and `categoryFor('internalError')` is `server`, i.e. "the server admits fault",
|
|
3104
|
+
// which would blame Everfur's backend for the partner's own config defect on their dashboards. The
|
|
3105
|
+
// whole point of the `sdk_config` level is to attribute this correctly. `validationFailed` is terminal
|
|
3106
|
+
// (`invalidRequest`: "retrying it unchanged can never succeed"), which is exactly true here.
|
|
3107
|
+
makeEverfurError("validationFailed", {
|
|
3108
|
+
retryable: false,
|
|
3109
|
+
// Developer-facing only: `wireMessage` is NON-ENUMERABLE and never rendered (EverfurError.ts).
|
|
3110
|
+
wireMessage: `Everfur SDK is not configured: ${failure.message}`
|
|
3111
|
+
})
|
|
3112
|
+
);
|
|
3113
|
+
return Object.freeze({
|
|
3114
|
+
request() {
|
|
3115
|
+
return Promise.resolve(err(build()));
|
|
3116
|
+
},
|
|
3117
|
+
stream(_req, signal) {
|
|
3118
|
+
const frame = errorFrame({
|
|
3119
|
+
code: "sdk_not_configured",
|
|
3120
|
+
retryable: false,
|
|
3121
|
+
wireMessage: `Everfur SDK is not configured: ${failure.message}`,
|
|
3122
|
+
synthesized: true,
|
|
3123
|
+
lastEventId: null
|
|
3124
|
+
});
|
|
3125
|
+
return {
|
|
3126
|
+
async *[Symbol.asyncIterator]() {
|
|
3127
|
+
if (signal.aborted) return;
|
|
3128
|
+
yield frame;
|
|
3129
|
+
}
|
|
3130
|
+
};
|
|
3131
|
+
}
|
|
3132
|
+
});
|
|
3133
|
+
}
|
|
3134
|
+
function createInMemoryKv() {
|
|
3135
|
+
const map = /* @__PURE__ */ new Map();
|
|
3136
|
+
return {
|
|
3137
|
+
async getItem(key) {
|
|
3138
|
+
return map.get(key) ?? null;
|
|
3139
|
+
},
|
|
3140
|
+
async setItem(key, value) {
|
|
3141
|
+
map.set(key, value);
|
|
3142
|
+
},
|
|
3143
|
+
async removeItem(key) {
|
|
3144
|
+
map.delete(key);
|
|
3145
|
+
},
|
|
3146
|
+
async keys(prefix) {
|
|
3147
|
+
return [...map.keys()].filter((k) => k.startsWith(prefix));
|
|
3148
|
+
}
|
|
3149
|
+
};
|
|
3150
|
+
}
|
|
3151
|
+
var unavailableUploadTransport = Object.freeze({
|
|
3152
|
+
postMultipart() {
|
|
3153
|
+
return Promise.reject(
|
|
3154
|
+
new Error("UploadTransport is unavailable; no records upload adapter was injected")
|
|
3155
|
+
);
|
|
3156
|
+
}
|
|
3157
|
+
});
|
|
3158
|
+
var noopImageCache = Object.freeze({
|
|
3159
|
+
clearMemoryCache() {
|
|
3160
|
+
},
|
|
3161
|
+
clearDiskCache() {
|
|
3162
|
+
}
|
|
3163
|
+
});
|
|
3164
|
+
|
|
3165
|
+
exports.MESSAGE_MAX_CHARS = MESSAGE_MAX_CHARS;
|
|
3166
|
+
exports.MIN_POLL_INTERVAL_SECONDS = MIN_POLL_INTERVAL_SECONDS;
|
|
3167
|
+
exports.NULL_SECURE_STORE = NULL_SECURE_STORE;
|
|
3168
|
+
exports.bootstrapChat = bootstrapChat;
|
|
3169
|
+
exports.createChatController = createChatController;
|
|
3170
|
+
exports.createEntitlementPoller = createEntitlementPoller;
|
|
3171
|
+
exports.createEverfurRuntime = createEverfurRuntime;
|
|
3172
|
+
exports.defaultErrorPolicy = defaultErrorPolicy;
|
|
3173
|
+
exports.noopTelemetry = noopTelemetry;
|
|
3174
|
+
exports.optionalModule = optionalModule;
|
|
3175
|
+
exports.unavailableCamera = unavailableCamera;
|