@reopt-ai/brandapp-sdk 3.3.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/README.md +10 -1
  3. package/dist/abort--nOBFN4M.js +50 -0
  4. package/dist/ai/index.d.ts +2 -314
  5. package/dist/ai/index.js +3 -8
  6. package/dist/ai-provider/index.d.ts +79 -163
  7. package/dist/ai-provider/index.js +752 -685
  8. package/dist/auth/index.d.ts +27 -27
  9. package/dist/auth/index.js +41 -34
  10. package/dist/better-auth/client.d.ts +6 -5
  11. package/dist/better-auth/client.js +28 -5
  12. package/dist/better-auth/index.d.ts +19 -17
  13. package/dist/better-auth/index.js +180 -144
  14. package/dist/client-61ldOHMz.js +503 -0
  15. package/dist/client-7PCoxVhZ.js +28 -0
  16. package/dist/client-B7rZQ8Zi.d.ts +272 -0
  17. package/dist/client-BGGd_cpV.d.ts +103 -0
  18. package/dist/client-BoIuyx4S.js +273 -0
  19. package/dist/client-BruP5_nU.d.ts +147 -0
  20. package/dist/client-BxtZt405.js +305 -0
  21. package/dist/client-ByN3EQdk.js +83 -0
  22. package/dist/client-CAghoGD_.js +53 -0
  23. package/dist/client-C_pHsPlj.js +81 -0
  24. package/dist/client-D0eBxh8j.d.ts +284 -0
  25. package/dist/client-D6gs61w8.d.ts +53 -0
  26. package/dist/client-DDw5yz_h.d.ts +53 -0
  27. package/dist/client-Dxg8_DIH.d.ts +71 -0
  28. package/dist/client-aMR4CRB8.d.ts +211 -0
  29. package/dist/client-lk6wBu_0.d.ts +48 -0
  30. package/dist/client-wEVKLdly.js +55 -0
  31. package/dist/client-zF1RG2uA.js +86 -0
  32. package/dist/cms/index.d.ts +52 -108
  33. package/dist/cms/index.js +103 -86
  34. package/dist/config-CRytOPPl.d.ts +394 -0
  35. package/dist/config-aml9oQpX.js +487 -0
  36. package/dist/dev/index.d.ts +2 -528
  37. package/dist/dev/index.js +3047 -2967
  38. package/dist/eav/coerce.d.ts +3 -1
  39. package/dist/eav/coerce.js +72 -46
  40. package/dist/eav/index.d.ts +72 -100
  41. package/dist/eav/index.js +158 -126
  42. package/dist/eav/migrate.d.ts +112 -109
  43. package/dist/eav/migrate.js +230 -196
  44. package/dist/eav/schema.d.ts +111 -150
  45. package/dist/eav/schema.js +624 -603
  46. package/dist/encoding-Bwfm3iaE.js +21 -0
  47. package/dist/{errors-BjDFIyA6.d.ts → errors-CRCcErNC.d.ts} +55 -53
  48. package/dist/feedback/index.d.ts +2 -132
  49. package/dist/feedback/index.js +3 -6
  50. package/dist/files/index.d.ts +14 -14
  51. package/dist/files/index.js +41 -25
  52. package/dist/http-client-BZc2mngq.js +386 -0
  53. package/dist/index-1j_738qk.d.ts +470 -0
  54. package/dist/index-CeOLGdyL.d.ts +169 -0
  55. package/dist/index.d.ts +6 -230
  56. package/dist/index.js +119 -71
  57. package/dist/logout/index.d.ts +56 -53
  58. package/dist/logout/index.js +232 -289
  59. package/dist/plans/index.d.ts +2 -236
  60. package/dist/plans/index.js +3 -6
  61. package/dist/push/index.d.ts +2 -79
  62. package/dist/push/index.js +3 -6
  63. package/dist/query-xWqtfkvR.js +35 -0
  64. package/dist/react/hooks.d.ts +157 -100
  65. package/dist/react/hooks.js +862 -406
  66. package/dist/sse-parser-FMjxM7sY.js +86 -0
  67. package/dist/terms/index.d.ts +3 -79
  68. package/dist/terms/index.js +3 -6
  69. package/dist/testing/index.d.ts +52 -104
  70. package/dist/testing/index.js +94 -72
  71. package/dist/types-B-SMkH6s.d.ts +26 -0
  72. package/dist/types-BXDcoJHG.d.ts +131 -0
  73. package/dist/types-BrghN2rJ.d.ts +105 -0
  74. package/dist/types-DjDRszNj.js +11 -0
  75. package/dist/webhooks/index.d.ts +77 -50
  76. package/dist/webhooks/index.js +150 -127
  77. package/docs/api-reference.md +121 -8
  78. package/docs/errors.md +19 -0
  79. package/docs/files.md +165 -7
  80. package/package.json +7 -6
  81. package/dist/chunk-2LSCQHAU.js +0 -21
  82. package/dist/chunk-4U4ZPPL4.js +0 -599
  83. package/dist/chunk-55KHY5GH.js +0 -96
  84. package/dist/chunk-C5VTRZWX.js +0 -458
  85. package/dist/chunk-F7BXBTZI.js +0 -54
  86. package/dist/chunk-FJUCWXX3.js +0 -350
  87. package/dist/chunk-H33OTQEN.js +0 -112
  88. package/dist/chunk-L4DHB36G.js +0 -75
  89. package/dist/chunk-OG7R3UAR.js +0 -105
  90. package/dist/chunk-PF24XU54.js +0 -32
  91. package/dist/chunk-QN3QD67K.js +0 -49
  92. package/dist/chunk-REIKXSMY.js +0 -7
  93. package/dist/chunk-UGBBXCZE.js +0 -157
  94. package/dist/chunk-UVT2E6KD.js +0 -81
  95. package/dist/chunk-YPLT3RFL.js +0 -63
  96. package/dist/chunk-YTKSAWV2.js +0 -463
  97. package/dist/client-BkcO-0C2.d.ts +0 -216
  98. package/dist/client-CN5_tNOC.d.ts +0 -147
  99. package/dist/client-DttyeM_h.d.ts +0 -102
  100. package/dist/config-CtxyJsDR.d.ts +0 -397
  101. package/dist/typed-client-BxOVIiMU.d.ts +0 -40
  102. package/dist/types-6E3ZLL9X.d.ts +0 -24
  103. package/dist/types-DskYLVb8.d.ts +0 -104
  104. package/dist/types-ckmDDW3N.d.ts +0 -129
@@ -1,463 +0,0 @@
1
- import { createAuthHeader } from './chunk-2LSCQHAU.js';
2
- import { validateConfig, resolveIdBaseUrl, resolveBaseUrl, SDK_VERSION, mapHttpStatusToError, ReoptSDKError, RateLimitError, ServerError } from './chunk-C5VTRZWX.js';
3
-
4
- // src/core/debug.ts
5
- function resolveLevel(configDebug) {
6
- if (configDebug === true) return "info";
7
- if (configDebug === false || configDebug === void 0) ; else if (typeof configDebug === "string") {
8
- return configDebug;
9
- }
10
- try {
11
- if (typeof process !== "undefined" && process.env) {
12
- const v = process.env.BRANDAPP_SDK_DEBUG;
13
- if (v === "trace") return "trace";
14
- if (v === "info" || v === "1") return "info";
15
- if (process.env.DEBUG?.includes("brandapp")) return "info";
16
- }
17
- } catch {
18
- }
19
- return "off";
20
- }
21
- var SAFE_QUERY_KEYS = /* @__PURE__ */ new Set([
22
- "page",
23
- "limit",
24
- "sort",
25
- "sortBy",
26
- "sortOrder",
27
- "order",
28
- "cursor",
29
- "offset"
30
- ]);
31
- function maskUrl(url) {
32
- const qIndex = url.indexOf("?");
33
- if (qIndex === -1) return url;
34
- const base = url.slice(0, qIndex);
35
- const query = url.slice(qIndex + 1);
36
- if (!query) return base;
37
- const masked = query.split("&").map((pair) => {
38
- const eq = pair.indexOf("=");
39
- if (eq === -1) return pair;
40
- const key = pair.slice(0, eq);
41
- return SAFE_QUERY_KEYS.has(key) ? pair : `${key}=***`;
42
- }).join("&");
43
- return `${base}?${masked}`;
44
- }
45
- var SENSITIVE_KEYS = /(?:^authorization$)|(?:(secret|password|credential|token|apikey)$)/i;
46
- function redactBody(value, depth = 0) {
47
- if (value == null || depth > 4) return value;
48
- if (Array.isArray(value)) {
49
- return value.slice(0, 20).map((v) => redactBody(v, depth + 1));
50
- }
51
- if (typeof value === "object") {
52
- const out = {};
53
- for (const [k, v] of Object.entries(value)) {
54
- out[k] = SENSITIVE_KEYS.test(k) ? "***" : redactBody(v, depth + 1);
55
- }
56
- return out;
57
- }
58
- if (typeof value === "string" && value.length > 500) {
59
- return `${value.slice(0, 500)}\u2026(${value.length - 500} more chars)`;
60
- }
61
- return value;
62
- }
63
- function isStructuredMode() {
64
- try {
65
- return typeof process !== "undefined" && process.env?.BRANDAPP_SDK_LOG_FORMAT === "json";
66
- } catch {
67
- return false;
68
- }
69
- }
70
- function createDebugLogger(configDebug) {
71
- const level = resolveLevel(configDebug);
72
- if (level === "off") {
73
- return {
74
- level,
75
- request: () => {
76
- },
77
- response: () => {
78
- },
79
- retry: () => {
80
- },
81
- error: () => {
82
- }
83
- };
84
- }
85
- return isStructuredMode() ? createStructuredLogger(level) : createHumanLogger(level);
86
- }
87
- function createHumanLogger(level) {
88
- const prefix = "[brandapp-sdk]";
89
- return {
90
- level,
91
- request(method, url, requestId, body) {
92
- console.debug(
93
- `${prefix} \u2192 ${method} ${maskUrl(url)} (req ${requestId.slice(0, 8)})`
94
- );
95
- if (level === "trace" && body !== void 0) {
96
- console.debug(`${prefix} body:`, redactBody(body));
97
- }
98
- },
99
- response(method, url, status, durationMs, requestId, body) {
100
- console.debug(
101
- `${prefix} \u2190 ${method} ${maskUrl(url)} ${status} (${durationMs}ms, req ${requestId.slice(
102
- 0,
103
- 8
104
- )})`
105
- );
106
- if (level === "trace" && body !== void 0) {
107
- console.debug(`${prefix} body:`, redactBody(body));
108
- }
109
- },
110
- retry(method, url, attempt, reason) {
111
- console.debug(
112
- `${prefix} \u21BB ${method} ${maskUrl(url)} retry #${attempt} (${reason})`
113
- );
114
- },
115
- error(method, url, error, requestId) {
116
- console.debug(
117
- `${prefix} \u2715 ${method} ${maskUrl(url)} ${error} (req ${requestId.slice(
118
- 0,
119
- 8
120
- )})`
121
- );
122
- }
123
- };
124
- }
125
- function createStructuredLogger(level) {
126
- const log = (entry) => {
127
- console.debug(JSON.stringify({ sdk: "brandapp-sdk", ...entry }));
128
- };
129
- return {
130
- level,
131
- request(method, url, requestId, body) {
132
- log({
133
- level: "debug",
134
- event: "request",
135
- method,
136
- url: maskUrl(url),
137
- requestId,
138
- ...level === "trace" && body !== void 0 ? { body: redactBody(body) } : {}
139
- });
140
- },
141
- response(method, url, status, durationMs, requestId, body) {
142
- log({
143
- level: "debug",
144
- event: "response",
145
- method,
146
- url: maskUrl(url),
147
- status,
148
- durationMs,
149
- requestId,
150
- ...level === "trace" && body !== void 0 ? { body: redactBody(body) } : {}
151
- });
152
- },
153
- retry(method, url, attempt, reason) {
154
- log({
155
- level: "warn",
156
- event: "retry",
157
- method,
158
- url: maskUrl(url),
159
- attempt,
160
- reason
161
- });
162
- },
163
- error(method, url, error, requestId) {
164
- log({
165
- level: "error",
166
- event: "error",
167
- method,
168
- url: maskUrl(url),
169
- error,
170
- requestId
171
- });
172
- }
173
- };
174
- }
175
-
176
- // src/core/http-client.ts
177
- function parseRetryAfter(value) {
178
- if (!value) return null;
179
- const seconds = Number(value);
180
- if (!Number.isNaN(seconds) && seconds >= 0) {
181
- return seconds * 1e3;
182
- }
183
- const date = Date.parse(value);
184
- if (!Number.isNaN(date)) {
185
- const ms = date - Date.now();
186
- return ms > 0 ? ms : 0;
187
- }
188
- return null;
189
- }
190
- function detectRuntime() {
191
- if (typeof globalThis.EdgeRuntime === "string") return "edge";
192
- if (typeof window !== "undefined") return "browser";
193
- return "node";
194
- }
195
- var RUNTIME = detectRuntime();
196
- var DEFAULT_TIMEOUT = 15e3;
197
- var DEFAULT_MAX_RETRIES = 3;
198
- var INITIAL_RETRY_DELAY = 1e3;
199
- var MAX_RETRY_DELAY = 3e4;
200
- var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
201
- function isIdempotentMethod(method) {
202
- return IDEMPOTENT_METHODS.has(method.toUpperCase());
203
- }
204
- function backoffDelay(attempt) {
205
- const base = Math.min(
206
- INITIAL_RETRY_DELAY * Math.pow(2, attempt),
207
- MAX_RETRY_DELAY
208
- );
209
- return base * (0.5 + Math.random() * 0.5);
210
- }
211
- function abortableSleep(ms, signal) {
212
- return new Promise((resolve) => {
213
- if (signal?.aborted) return resolve();
214
- const onAbort = () => {
215
- clearTimeout(timer);
216
- resolve();
217
- };
218
- const timer = setTimeout(() => {
219
- signal?.removeEventListener("abort", onAbort);
220
- resolve();
221
- }, ms);
222
- signal?.addEventListener("abort", onAbort, { once: true });
223
- });
224
- }
225
- function parseErrorBody(errorBody) {
226
- if (typeof errorBody?.error === "string") {
227
- return {
228
- code: void 0,
229
- message: errorBody.error
230
- };
231
- }
232
- return {
233
- code: errorBody?.error?.code,
234
- message: errorBody?.error?.message
235
- };
236
- }
237
- var BaseHttpClient = class {
238
- baseUrl;
239
- authHeader;
240
- timeout;
241
- maxRetries;
242
- retryNonIdempotent;
243
- debug;
244
- constructor(config, pathPrefix, options) {
245
- validateConfig(config);
246
- const base = options?.useIdServer ? resolveIdBaseUrl(config) : resolveBaseUrl(config);
247
- this.baseUrl = base + pathPrefix;
248
- this.authHeader = createAuthHeader(config);
249
- this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
250
- this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
251
- this.retryNonIdempotent = config.retryNonIdempotent ?? false;
252
- this.debug = createDebugLogger(config.debug ?? false);
253
- }
254
- /**
255
- * Resolved request origin + path prefix
256
- * (e.g. `https://brandapp.reopt.ai/api/v1/brandapp/{id}/ai`). Exposed so domain
257
- * clients that must hand-roll `fetch` (SSE streaming, multipart upload) reuse
258
- * the same resolved host instead of re-deriving it.
259
- */
260
- get requestBaseUrl() {
261
- return this.baseUrl;
262
- }
263
- /** The default `Authorization` header value (Basic or pre-minted Bearer). */
264
- get authorizationHeader() {
265
- return this.authHeader;
266
- }
267
- /** Configured request timeout in ms. */
268
- get timeoutMs() {
269
- return this.timeout;
270
- }
271
- async fetch(method, path, body, options) {
272
- const url = `${this.baseUrl}${path}`;
273
- const requestId = crypto.randomUUID();
274
- const timeout = options?.timeout ?? this.timeout;
275
- const methodRetryable = this.retryNonIdempotent || isIdempotentMethod(method) || options?.idempotent === true;
276
- let lastError;
277
- this.debug.request(method, url, requestId, body);
278
- const startTime = Date.now();
279
- for (let attempt = 0; attempt < this.maxRetries; attempt++) {
280
- const ctx = { method, url, attempt, requestId };
281
- let canRetry = false;
282
- const controller = new AbortController();
283
- const timeoutId = setTimeout(() => controller.abort(), timeout);
284
- const externalSignal = options?.signal;
285
- const onExternalAbort = () => controller.abort();
286
- if (externalSignal) {
287
- if (externalSignal.aborted) {
288
- controller.abort();
289
- } else {
290
- externalSignal.addEventListener("abort", onExternalAbort, {
291
- once: true
292
- });
293
- }
294
- }
295
- try {
296
- const headers = {
297
- Authorization: options?.bearerToken ? `Bearer ${options.bearerToken}` : this.authHeader,
298
- "X-SDK-Version": `brandapp-sdk/${SDK_VERSION}`,
299
- "X-SDK-Runtime": RUNTIME,
300
- "X-Request-Id": requestId
301
- };
302
- if (body !== void 0) {
303
- headers["Content-Type"] = "application/json";
304
- }
305
- if (!isIdempotentMethod(method)) {
306
- headers["Idempotency-Key"] = requestId;
307
- }
308
- const response = await globalThis.fetch(url, {
309
- method,
310
- headers,
311
- body: body !== void 0 ? JSON.stringify(body) : void 0,
312
- signal: controller.signal
313
- });
314
- if (response.ok) {
315
- const durationMs = Date.now() - startTime;
316
- if (response.status === 204 || response.headers.get("content-length") === "0") {
317
- this.debug.response(
318
- method,
319
- url,
320
- response.status,
321
- durationMs,
322
- requestId
323
- );
324
- return void 0;
325
- }
326
- if (this.debug.level === "trace") {
327
- const parsed = await response.json();
328
- this.debug.response(
329
- method,
330
- url,
331
- response.status,
332
- durationMs,
333
- requestId,
334
- parsed
335
- );
336
- return parsed;
337
- }
338
- this.debug.response(
339
- method,
340
- url,
341
- response.status,
342
- durationMs,
343
- requestId
344
- );
345
- return await response.json();
346
- }
347
- const errorBody = await response.json().catch(() => ({}));
348
- const { code: errorCode, message: errorMessage } = parseErrorBody(errorBody);
349
- const fieldErrors = response.status === 422 ? parseFieldErrors(errorBody) : [];
350
- const mapped = mapHttpStatusToError(
351
- response.status,
352
- errorCode,
353
- errorMessage,
354
- ctx,
355
- fieldErrors
356
- );
357
- if (response.status === 429) {
358
- lastError = mapped;
359
- canRetry = true;
360
- const retryAfter = parseRetryAfter(
361
- response.headers.get("retry-after")
362
- );
363
- if (retryAfter !== null && attempt < this.maxRetries - 1) {
364
- await abortableSleep(
365
- Math.min(retryAfter, MAX_RETRY_DELAY),
366
- externalSignal
367
- );
368
- continue;
369
- }
370
- } else if (response.status >= 500) {
371
- lastError = mapped;
372
- canRetry = methodRetryable;
373
- } else {
374
- throw mapped;
375
- }
376
- } catch (error) {
377
- if (error instanceof ReoptSDKError) {
378
- if (!(error instanceof RateLimitError) && !(error instanceof ServerError)) {
379
- throw error;
380
- }
381
- lastError = error;
382
- canRetry = methodRetryable;
383
- } else if (error instanceof Error && error.name === "AbortError") {
384
- if (externalSignal?.aborted) {
385
- const cancelled = new ReoptSDKError(
386
- "Request aborted by caller",
387
- 0,
388
- "CANCELLED",
389
- ctx
390
- );
391
- cancelled.name = "AbortError";
392
- throw cancelled;
393
- }
394
- lastError = new ReoptSDKError(
395
- "Request timed out",
396
- 408,
397
- "TIMEOUT",
398
- ctx
399
- );
400
- canRetry = methodRetryable;
401
- } else {
402
- lastError = error instanceof Error ? error : new Error(String(error));
403
- canRetry = methodRetryable;
404
- }
405
- } finally {
406
- clearTimeout(timeoutId);
407
- if (externalSignal) {
408
- externalSignal.removeEventListener("abort", onExternalAbort);
409
- }
410
- }
411
- if (!canRetry) break;
412
- if (attempt < this.maxRetries - 1) {
413
- this.debug.retry(
414
- method,
415
- url,
416
- attempt + 1,
417
- lastError?.message ?? "unknown"
418
- );
419
- await abortableSleep(backoffDelay(attempt), externalSignal);
420
- }
421
- }
422
- this.debug.error(method, url, lastError?.message ?? "unknown", requestId);
423
- if (lastError instanceof ReoptSDKError && !lastError.context?.requestId) {
424
- lastError.context = {
425
- ...lastError.context ?? {},
426
- requestId
427
- };
428
- }
429
- throw lastError ?? new ServerError("All retry attempts failed", { requestId });
430
- }
431
- };
432
- function parseFieldErrors(body) {
433
- if (!body?.error || typeof body.error !== "object") return [];
434
- const err = body.error;
435
- if (Array.isArray(err.fields)) {
436
- return err.fields.filter(
437
- (f) => f && typeof f === "object" && "field" in f
438
- ).map((f) => ({
439
- field: f.field,
440
- message: f.message ?? "Validation failed",
441
- code: f.code
442
- }));
443
- }
444
- if (err.fields && typeof err.fields === "object" && !Array.isArray(err.fields)) {
445
- return Object.entries(err.fields).map(
446
- ([field, message]) => ({ field, message })
447
- );
448
- }
449
- if (Array.isArray(err.issues)) {
450
- return err.issues.filter(
451
- (i) => i && typeof i === "object" && "path" in i
452
- ).map((i) => ({
453
- field: i.path?.join(".") ?? "unknown",
454
- message: i.message ?? "Validation failed",
455
- code: i.code
456
- }));
457
- }
458
- return [];
459
- }
460
-
461
- export { BaseHttpClient, parseFieldErrors };
462
- //# sourceMappingURL=chunk-YTKSAWV2.js.map
463
- //# sourceMappingURL=chunk-YTKSAWV2.js.map
@@ -1,216 +0,0 @@
1
- import { S as SchemaDef, q as ReoptSDKConfig, l as EavEntity, f as CreateEntityInput, E as EavAttribute, r as UpdateEntityInput, e as CreateAttributeInput, U as UpdateAttributeInput, L as ListRecordsQuery, P as PaginatedResponse, m as EavRecord, g as CreateRecordInput, s as UpdateRecordInput, C as CountRecordsQuery, d as BulkUpdateItem, t as UpsertRecordInput, u as UpsertRecordResult, i as DeleteWhereInput, B as BackfillOptions, c as BackfillResult, p as EntityDef } from './config-CtxyJsDR.js';
2
- import { E as EntityClient } from './typed-client-BxOVIiMU.js';
3
-
4
- /**
5
- * Reopt EAV Client
6
- *
7
- * @example
8
- * ```ts
9
- * import { createReoptEavClient } from "@reopt-ai/brandapp-sdk/eav";
10
- *
11
- * const eav = createReoptEavClient({
12
- * clientId: process.env.BRANDAPP_CLIENT_ID!,
13
- * clientSecret: process.env.BRANDAPP_CLIENT_SECRET!,
14
- * brandappId: process.env.BRANDAPP_ID!,
15
- * });
16
- *
17
- * const entity = await eav.entities.create({ name: "agent_configs" });
18
- * ```
19
- */
20
- type ReoptEavClient<S extends SchemaDef = SchemaDef> = ReturnType<typeof createReoptEavClient<S>>;
21
- declare function createReoptEavClient<S extends SchemaDef = SchemaDef>(config: ReoptSDKConfig<S>): {
22
- entities: {
23
- list(): Promise<EavEntity[]>;
24
- create(input: CreateEntityInput): Promise<EavEntity>;
25
- get(entityId: string): Promise<EavEntity & {
26
- attributes: EavAttribute[];
27
- }>;
28
- update(entityId: string, input: UpdateEntityInput): Promise<EavEntity>;
29
- delete(entityId: string): Promise<void>;
30
- };
31
- attributes: {
32
- create(entityId: string, input: CreateAttributeInput): Promise<EavAttribute>;
33
- update(entityId: string, attributeId: string, input: UpdateAttributeInput): Promise<EavAttribute>;
34
- delete(entityId: string, attributeId: string): Promise<void>;
35
- };
36
- records: {
37
- /** List records with pagination, filtering, and sorting.
38
- * @example
39
- * ```ts
40
- * const result = await eav.records.list(entityId, {
41
- * authUserId: userId,
42
- * filters: [{ attributeId: "status-attr-id", operator: "eq", value: "active" }],
43
- * sortBy: "createdAt",
44
- * sortOrder: "desc",
45
- * page: 1,
46
- * limit: 50,
47
- * });
48
- * ```
49
- */
50
- list(entityId: string, query?: ListRecordsQuery): Promise<PaginatedResponse<EavRecord>>;
51
- /** Create a new record with attribute values.
52
- * @example
53
- * ```ts
54
- * const record = await eav.records.create(entityId, {
55
- * authUserId: userId,
56
- * values: { [attrs.name]: "John", [attrs.email]: "john@example.com" },
57
- * });
58
- * ```
59
- */
60
- create(entityId: string, input: CreateRecordInput): Promise<EavRecord>;
61
- /** Get a single record by ID.
62
- * @example
63
- * ```ts
64
- * const record = await eav.records.get(entityId, recordId);
65
- * ```
66
- */
67
- get(entityId: string, recordId: string): Promise<EavRecord>;
68
- /** Update a record's attribute values. Only specified values are changed.
69
- * @example
70
- * ```ts
71
- * const updated = await eav.records.update(entityId, recordId, {
72
- * values: { [attrs.status]: "completed" },
73
- * });
74
- * ```
75
- */
76
- update(entityId: string, recordId: string, input: UpdateRecordInput): Promise<EavRecord>;
77
- /** Delete a single record by ID. */
78
- delete(entityId: string, recordId: string): Promise<void>;
79
- /** Count records matching filters without fetching bodies.
80
- * @example
81
- * ```ts
82
- * // Count active tasks
83
- * const count = await eav.records.count(entityId, {
84
- * authUserId: userId,
85
- * filters: [{ attributeId: attrs.deleted_at, operator: "is_null" }],
86
- * });
87
- * ```
88
- */
89
- count(entityId: string, query?: CountRecordsQuery): Promise<number>;
90
- /** Delete multiple records by ID (max 100). Returns count of deleted records. */
91
- bulkDelete(entityId: string, ids: string[]): Promise<number>;
92
- /** Update multiple records in a single transaction (max 100).
93
- * @example
94
- * ```ts
95
- * const updated = await eav.records.bulkUpdate(entityId, [
96
- * { id: "record-1", values: { [attrs.is_active]: false } },
97
- * { id: "record-2", values: { [attrs.is_active]: false } },
98
- * ]);
99
- * ```
100
- */
101
- bulkUpdate(entityId: string, updates: BulkUpdateItem[]): Promise<EavRecord[]>;
102
- /** Find a single record matching filters. Returns null if not found.
103
- * Prefer this over list() + filter when you need exactly one record.
104
- * @example
105
- * ```ts
106
- * // Find setting by key
107
- * const record = await eav.records.findOne(entityId, {
108
- * authUserId: userId,
109
- * filters: [{ attributeId: attrs.key, operator: "eq", value: "theme" }],
110
- * });
111
- * ```
112
- */
113
- findOne(entityId: string, query?: Omit<ListRecordsQuery, "page">): Promise<EavRecord | null>;
114
- /** Find a record by filters -- update if exists, create if not. Atomic operation.
115
- * @returns `{ data: EavRecord, created: boolean }`
116
- * @example
117
- * ```ts
118
- * // Upsert a user setting
119
- * const { data, created } = await eav.records.upsert(entityId, {
120
- * authUserId: userId,
121
- * filters: [{ attributeId: attrs.key, operator: "eq", value: "theme" }],
122
- * values: { [attrs.key]: "theme", [attrs.value]: "dark" },
123
- * });
124
- * ```
125
- */
126
- upsert(entityId: string, input: UpsertRecordInput): Promise<UpsertRecordResult<EavRecord>>;
127
- /** Create multiple records in a single transaction (max 100).
128
- * @example
129
- * ```ts
130
- * const records = await eav.records.bulkCreate(entityId, [
131
- * { values: { [attrs.name]: "Alice" } },
132
- * { values: { [attrs.name]: "Bob" } },
133
- * ]);
134
- * ```
135
- */
136
- bulkCreate(entityId: string, records: CreateRecordInput[]): Promise<EavRecord[]>;
137
- /** Delete all records matching filters. Returns count of deleted records.
138
- * @example
139
- * ```ts
140
- * // Delete all inactive records
141
- * const count = await eav.records.deleteWhere(entityId, {
142
- * authUserId: userId,
143
- * filters: [{ attributeId: attrs.status, operator: "eq", value: "inactive" }],
144
- * });
145
- * ```
146
- */
147
- deleteWhere(entityId: string, input: DeleteWhereInput): Promise<number>;
148
- /** Iterate all records across pages as an AsyncGenerator.
149
- * @example
150
- * ```ts
151
- * // Stream all records
152
- * for await (const record of eav.records.listAll(entityId, { authUserId: userId })) {
153
- * process.stdout.write(".");
154
- * }
155
- *
156
- * // Or collect to array
157
- * import { collectAll } from "@reopt-ai/brandapp-sdk/eav";
158
- * const all = await collectAll(eav.records.listAll(entityId));
159
- * ```
160
- */
161
- listAll(entityId: string, query?: Omit<ListRecordsQuery, "page">): AsyncGenerator<EavRecord>;
162
- /**
163
- * Backfill records by streaming through pages, calling `transform` per
164
- * record, and applying `update` for each non-null result.
165
- *
166
- * Designed for the "expand-contract" middle step of an EAV migration —
167
- * e.g. copy values from a soon-to-be-deleted attribute to a new one.
168
- *
169
- * @example
170
- * ```ts
171
- * await sdk.eav.records.backfill(entityId, {
172
- * filters: [{ attributeId: levelAttrId, operator: "is_null" }],
173
- * concurrency: 10,
174
- * transform: (r) => ({ level: r.values.tier ?? "free" }),
175
- * onProgress: ({ processed, total }) =>
176
- * console.log(`${processed}/${total}`),
177
- * });
178
- * ```
179
- *
180
- * Failed updates are collected in `result.failed[]` rather than aborting
181
- * the run — inspect that array after the call to retry or escalate.
182
- */
183
- backfill(entityId: string, opts: BackfillOptions): Promise<BackfillResult>;
184
- };
185
- users: {
186
- getRecords(authUserId: string, query?: Omit<ListRecordsQuery, "authUserId">): Promise<PaginatedResponse<EavRecord>>;
187
- };
188
- /**
189
- * Fetch the server's current EAV schema fingerprint (Phase C, RFC-0005).
190
- *
191
- * Pair with `verifyEavSchema(localHash, client)` to detect drift between
192
- * a deployed bundle and the live schema. Cacheable for ~60s — the server
193
- * recomputes on every schema mutation.
194
- */
195
- schemaHash(): Promise<{
196
- hash: string;
197
- schemaCount: number;
198
- fieldCount: number;
199
- generatedAt: string;
200
- }>;
201
- /** Create a type-safe entity-scoped client. Resolves entity name to ID automatically.
202
- * Requires `schema` in SDK config for type inference.
203
- * @example
204
- * ```ts
205
- * const contacts = sdk.eav.entity("contacts");
206
- * const record = await contacts.records.create({
207
- * values: { name: "John", email: "john@example.com" }, // typed!
208
- * });
209
- * ```
210
- */
211
- entity<K extends string & keyof S["entities"]>(name: K): EntityClient<S["entities"][K] extends EntityDef ? S["entities"][K] : EntityDef>;
212
- /** Clear the entity name → ID cache and schema cache. Call after creating/deleting entities externally. */
213
- invalidateCache(): void;
214
- };
215
-
216
- export { type ReoptEavClient as R, createReoptEavClient as c };