@reopt-ai/brandapp-sdk 3.0.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 (76) hide show
  1. package/CHANGELOG.md +574 -0
  2. package/LICENSE +21 -0
  3. package/README.md +468 -0
  4. package/dist/ai/index.d.ts +314 -0
  5. package/dist/ai/index.js +7 -0
  6. package/dist/ai-provider/index.d.ts +196 -0
  7. package/dist/ai-provider/index.js +703 -0
  8. package/dist/auth/index.d.ts +76 -0
  9. package/dist/auth/index.js +40 -0
  10. package/dist/better-auth/client.d.ts +29 -0
  11. package/dist/better-auth/client.js +10 -0
  12. package/dist/better-auth/index.d.ts +82 -0
  13. package/dist/better-auth/index.js +145 -0
  14. package/dist/chunk-6FLYVNZI.js +32 -0
  15. package/dist/chunk-6KPKZ7ZB.js +49 -0
  16. package/dist/chunk-DI6QJPTQ.js +449 -0
  17. package/dist/chunk-E457LO5A.js +599 -0
  18. package/dist/chunk-F7BXBTZI.js +54 -0
  19. package/dist/chunk-J5Y2GSJF.js +443 -0
  20. package/dist/chunk-K3YVJE6E.js +96 -0
  21. package/dist/chunk-KU2LN5SE.js +350 -0
  22. package/dist/chunk-L4DHB36G.js +75 -0
  23. package/dist/chunk-PJZB4VP7.js +63 -0
  24. package/dist/chunk-REIKXSMY.js +7 -0
  25. package/dist/chunk-T2WXHAAC.js +54 -0
  26. package/dist/chunk-TUKIYH4Q.js +112 -0
  27. package/dist/chunk-WSEROZVO.js +81 -0
  28. package/dist/chunk-YRGLBM6V.js +157 -0
  29. package/dist/client-BkcO-0C2.d.ts +216 -0
  30. package/dist/client-CN5_tNOC.d.ts +147 -0
  31. package/dist/client-DttyeM_h.d.ts +102 -0
  32. package/dist/cms/index.d.ts +137 -0
  33. package/dist/cms/index.js +101 -0
  34. package/dist/config-CtxyJsDR.d.ts +397 -0
  35. package/dist/dev/index.d.ts +509 -0
  36. package/dist/dev/index.js +3071 -0
  37. package/dist/eav/coerce.d.ts +42 -0
  38. package/dist/eav/coerce.js +65 -0
  39. package/dist/eav/index.d.ts +214 -0
  40. package/dist/eav/index.js +147 -0
  41. package/dist/eav/migrate.d.ts +236 -0
  42. package/dist/eav/migrate.js +219 -0
  43. package/dist/eav/schema.d.ts +260 -0
  44. package/dist/eav/schema.js +656 -0
  45. package/dist/errors-5hd5ZR-M.d.ts +158 -0
  46. package/dist/feedback/index.d.ts +132 -0
  47. package/dist/feedback/index.js +5 -0
  48. package/dist/files/index.d.ts +54 -0
  49. package/dist/files/index.js +31 -0
  50. package/dist/index.d.ts +221 -0
  51. package/dist/index.js +84 -0
  52. package/dist/plans/index.d.ts +140 -0
  53. package/dist/plans/index.js +5 -0
  54. package/dist/push/index.d.ts +79 -0
  55. package/dist/push/index.js +5 -0
  56. package/dist/react/hooks.d.ts +376 -0
  57. package/dist/react/hooks.js +421 -0
  58. package/dist/terms/index.d.ts +79 -0
  59. package/dist/terms/index.js +5 -0
  60. package/dist/testing/index.d.ts +154 -0
  61. package/dist/testing/index.js +81 -0
  62. package/dist/typed-client-BxOVIiMU.d.ts +40 -0
  63. package/dist/types-6E3ZLL9X.d.ts +24 -0
  64. package/dist/types-DskYLVb8.d.ts +104 -0
  65. package/dist/types-ckmDDW3N.d.ts +129 -0
  66. package/dist/webhooks/index.d.ts +140 -0
  67. package/dist/webhooks/index.js +142 -0
  68. package/docs/api-reference.md +557 -0
  69. package/docs/cms.md +318 -0
  70. package/docs/dev-server.md +164 -0
  71. package/docs/environment.md +211 -0
  72. package/docs/errors.md +290 -0
  73. package/docs/files.md +272 -0
  74. package/docs/migration.md +315 -0
  75. package/docs/testing.md +163 -0
  76. package/package.json +173 -0
@@ -0,0 +1,449 @@
1
+ import { validateConfig, resolveIdBaseUrl, resolveBaseUrl, createAuthHeader, SDK_VERSION, mapHttpStatusToError, ReoptSDKError, RateLimitError, ServerError } from './chunk-J5Y2GSJF.js';
2
+
3
+ // src/core/debug.ts
4
+ function resolveLevel(configDebug) {
5
+ if (configDebug === true) return "info";
6
+ if (configDebug === false || configDebug === void 0) ; else if (typeof configDebug === "string") {
7
+ return configDebug;
8
+ }
9
+ try {
10
+ if (typeof process !== "undefined" && process.env) {
11
+ const v = process.env.BRANDAPP_SDK_DEBUG;
12
+ if (v === "trace") return "trace";
13
+ if (v === "info" || v === "1") return "info";
14
+ if (process.env.DEBUG?.includes("brandapp")) return "info";
15
+ }
16
+ } catch {
17
+ }
18
+ return "off";
19
+ }
20
+ var SAFE_QUERY_KEYS = /* @__PURE__ */ new Set([
21
+ "page",
22
+ "limit",
23
+ "sort",
24
+ "sortBy",
25
+ "sortOrder",
26
+ "order",
27
+ "cursor",
28
+ "offset"
29
+ ]);
30
+ function maskUrl(url) {
31
+ const qIndex = url.indexOf("?");
32
+ if (qIndex === -1) return url;
33
+ const base = url.slice(0, qIndex);
34
+ const query = url.slice(qIndex + 1);
35
+ if (!query) return base;
36
+ const masked = query.split("&").map((pair) => {
37
+ const eq = pair.indexOf("=");
38
+ if (eq === -1) return pair;
39
+ const key = pair.slice(0, eq);
40
+ return SAFE_QUERY_KEYS.has(key) ? pair : `${key}=***`;
41
+ }).join("&");
42
+ return `${base}?${masked}`;
43
+ }
44
+ var SENSITIVE_KEYS = /(?:^authorization$)|(?:(secret|password|credential|token|apikey)$)/i;
45
+ function redactBody(value, depth = 0) {
46
+ if (value == null || depth > 4) return value;
47
+ if (Array.isArray(value)) {
48
+ return value.slice(0, 20).map((v) => redactBody(v, depth + 1));
49
+ }
50
+ if (typeof value === "object") {
51
+ const out = {};
52
+ for (const [k, v] of Object.entries(value)) {
53
+ out[k] = SENSITIVE_KEYS.test(k) ? "***" : redactBody(v, depth + 1);
54
+ }
55
+ return out;
56
+ }
57
+ if (typeof value === "string" && value.length > 500) {
58
+ return `${value.slice(0, 500)}\u2026(${value.length - 500} more chars)`;
59
+ }
60
+ return value;
61
+ }
62
+ function isStructuredMode() {
63
+ try {
64
+ return typeof process !== "undefined" && process.env?.BRANDAPP_SDK_LOG_FORMAT === "json";
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+ function createDebugLogger(configDebug) {
70
+ const level = resolveLevel(configDebug);
71
+ if (level === "off") {
72
+ return {
73
+ level,
74
+ request: () => {
75
+ },
76
+ response: () => {
77
+ },
78
+ retry: () => {
79
+ },
80
+ error: () => {
81
+ }
82
+ };
83
+ }
84
+ return isStructuredMode() ? createStructuredLogger(level) : createHumanLogger(level);
85
+ }
86
+ function createHumanLogger(level) {
87
+ const prefix = "[brandapp-sdk]";
88
+ return {
89
+ level,
90
+ request(method, url, requestId, body) {
91
+ console.debug(
92
+ `${prefix} \u2192 ${method} ${maskUrl(url)} (req ${requestId.slice(0, 8)})`
93
+ );
94
+ if (level === "trace" && body !== void 0) {
95
+ console.debug(`${prefix} body:`, redactBody(body));
96
+ }
97
+ },
98
+ response(method, url, status, durationMs, requestId, body) {
99
+ console.debug(
100
+ `${prefix} \u2190 ${method} ${maskUrl(url)} ${status} (${durationMs}ms, req ${requestId.slice(
101
+ 0,
102
+ 8
103
+ )})`
104
+ );
105
+ if (level === "trace" && body !== void 0) {
106
+ console.debug(`${prefix} body:`, redactBody(body));
107
+ }
108
+ },
109
+ retry(method, url, attempt, reason) {
110
+ console.debug(
111
+ `${prefix} \u21BB ${method} ${maskUrl(url)} retry #${attempt} (${reason})`
112
+ );
113
+ },
114
+ error(method, url, error, requestId) {
115
+ console.debug(
116
+ `${prefix} \u2715 ${method} ${maskUrl(url)} ${error} (req ${requestId.slice(
117
+ 0,
118
+ 8
119
+ )})`
120
+ );
121
+ }
122
+ };
123
+ }
124
+ function createStructuredLogger(level) {
125
+ const log = (entry) => {
126
+ console.debug(JSON.stringify({ sdk: "brandapp-sdk", ...entry }));
127
+ };
128
+ return {
129
+ level,
130
+ request(method, url, requestId, body) {
131
+ log({
132
+ level: "debug",
133
+ event: "request",
134
+ method,
135
+ url: maskUrl(url),
136
+ requestId,
137
+ ...level === "trace" && body !== void 0 ? { body: redactBody(body) } : {}
138
+ });
139
+ },
140
+ response(method, url, status, durationMs, requestId, body) {
141
+ log({
142
+ level: "debug",
143
+ event: "response",
144
+ method,
145
+ url: maskUrl(url),
146
+ status,
147
+ durationMs,
148
+ requestId,
149
+ ...level === "trace" && body !== void 0 ? { body: redactBody(body) } : {}
150
+ });
151
+ },
152
+ retry(method, url, attempt, reason) {
153
+ log({
154
+ level: "warn",
155
+ event: "retry",
156
+ method,
157
+ url: maskUrl(url),
158
+ attempt,
159
+ reason
160
+ });
161
+ },
162
+ error(method, url, error, requestId) {
163
+ log({
164
+ level: "error",
165
+ event: "error",
166
+ method,
167
+ url: maskUrl(url),
168
+ error,
169
+ requestId
170
+ });
171
+ }
172
+ };
173
+ }
174
+
175
+ // src/core/http-client.ts
176
+ function parseRetryAfter(value) {
177
+ if (!value) return null;
178
+ const seconds = Number(value);
179
+ if (!Number.isNaN(seconds) && seconds >= 0) {
180
+ return seconds * 1e3;
181
+ }
182
+ const date = Date.parse(value);
183
+ if (!Number.isNaN(date)) {
184
+ const ms = date - Date.now();
185
+ return ms > 0 ? ms : 0;
186
+ }
187
+ return null;
188
+ }
189
+ function detectRuntime() {
190
+ if (typeof globalThis.EdgeRuntime === "string") return "edge";
191
+ if (typeof window !== "undefined") return "browser";
192
+ return "node";
193
+ }
194
+ var RUNTIME = detectRuntime();
195
+ var DEFAULT_TIMEOUT = 15e3;
196
+ var DEFAULT_MAX_RETRIES = 3;
197
+ var INITIAL_RETRY_DELAY = 1e3;
198
+ var MAX_RETRY_DELAY = 3e4;
199
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
200
+ function isIdempotentMethod(method) {
201
+ return IDEMPOTENT_METHODS.has(method.toUpperCase());
202
+ }
203
+ function backoffDelay(attempt) {
204
+ const base = Math.min(
205
+ INITIAL_RETRY_DELAY * Math.pow(2, attempt),
206
+ MAX_RETRY_DELAY
207
+ );
208
+ return base * (0.5 + Math.random() * 0.5);
209
+ }
210
+ function abortableSleep(ms, signal) {
211
+ return new Promise((resolve) => {
212
+ if (signal?.aborted) return resolve();
213
+ const onAbort = () => {
214
+ clearTimeout(timer);
215
+ resolve();
216
+ };
217
+ const timer = setTimeout(() => {
218
+ signal?.removeEventListener("abort", onAbort);
219
+ resolve();
220
+ }, ms);
221
+ signal?.addEventListener("abort", onAbort, { once: true });
222
+ });
223
+ }
224
+ function parseErrorBody(errorBody) {
225
+ if (typeof errorBody?.error === "string") {
226
+ return {
227
+ code: void 0,
228
+ message: errorBody.error
229
+ };
230
+ }
231
+ return {
232
+ code: errorBody?.error?.code,
233
+ message: errorBody?.error?.message
234
+ };
235
+ }
236
+ var BaseHttpClient = class {
237
+ baseUrl;
238
+ authHeader;
239
+ timeout;
240
+ maxRetries;
241
+ retryNonIdempotent;
242
+ debug;
243
+ constructor(config, pathPrefix, options) {
244
+ validateConfig(config);
245
+ const base = options?.useIdServer ? resolveIdBaseUrl(config) : resolveBaseUrl(config);
246
+ this.baseUrl = base + pathPrefix;
247
+ this.authHeader = createAuthHeader(config);
248
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
249
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
250
+ this.retryNonIdempotent = config.retryNonIdempotent ?? false;
251
+ this.debug = createDebugLogger(config.debug ?? false);
252
+ }
253
+ /**
254
+ * Resolved request origin + path prefix
255
+ * (e.g. `https://brandapp.reopt.ai/api/v1/brandapp/{id}/ai`). Exposed so domain
256
+ * clients that must hand-roll `fetch` (SSE streaming, multipart upload) reuse
257
+ * the same resolved host instead of re-deriving it.
258
+ */
259
+ get requestBaseUrl() {
260
+ return this.baseUrl;
261
+ }
262
+ /** The default `Authorization` header value (Basic or pre-minted Bearer). */
263
+ get authorizationHeader() {
264
+ return this.authHeader;
265
+ }
266
+ /** Configured request timeout in ms. */
267
+ get timeoutMs() {
268
+ return this.timeout;
269
+ }
270
+ async fetch(method, path, body, options) {
271
+ const url = `${this.baseUrl}${path}`;
272
+ const requestId = crypto.randomUUID();
273
+ const timeout = options?.timeout ?? this.timeout;
274
+ const methodRetryable = this.retryNonIdempotent || isIdempotentMethod(method);
275
+ let lastError;
276
+ this.debug.request(method, url, requestId, body);
277
+ const startTime = Date.now();
278
+ for (let attempt = 0; attempt < this.maxRetries; attempt++) {
279
+ const ctx = { method, url, attempt, requestId };
280
+ let canRetry = false;
281
+ const controller = new AbortController();
282
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
283
+ const externalSignal = options?.signal;
284
+ const onExternalAbort = () => controller.abort();
285
+ if (externalSignal) {
286
+ if (externalSignal.aborted) {
287
+ controller.abort();
288
+ } else {
289
+ externalSignal.addEventListener("abort", onExternalAbort, {
290
+ once: true
291
+ });
292
+ }
293
+ }
294
+ try {
295
+ const headers = {
296
+ Authorization: options?.bearerToken ? `Bearer ${options.bearerToken}` : this.authHeader,
297
+ "X-SDK-Version": `brandapp-sdk/${SDK_VERSION}`,
298
+ "X-SDK-Runtime": RUNTIME,
299
+ "X-Request-Id": requestId
300
+ };
301
+ if (body !== void 0) {
302
+ headers["Content-Type"] = "application/json";
303
+ }
304
+ if (!isIdempotentMethod(method)) {
305
+ headers["Idempotency-Key"] = requestId;
306
+ }
307
+ const response = await globalThis.fetch(url, {
308
+ method,
309
+ headers,
310
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
311
+ signal: controller.signal
312
+ });
313
+ if (response.ok) {
314
+ const durationMs = Date.now() - startTime;
315
+ if (response.status === 204 || response.headers.get("content-length") === "0") {
316
+ this.debug.response(
317
+ method,
318
+ url,
319
+ response.status,
320
+ durationMs,
321
+ requestId
322
+ );
323
+ return void 0;
324
+ }
325
+ if (this.debug.level === "trace") {
326
+ const parsed = await response.json();
327
+ this.debug.response(
328
+ method,
329
+ url,
330
+ response.status,
331
+ durationMs,
332
+ requestId,
333
+ parsed
334
+ );
335
+ return parsed;
336
+ }
337
+ this.debug.response(
338
+ method,
339
+ url,
340
+ response.status,
341
+ durationMs,
342
+ requestId
343
+ );
344
+ return await response.json();
345
+ }
346
+ const errorBody = await response.json().catch(() => ({}));
347
+ const { code: errorCode, message: errorMessage } = parseErrorBody(errorBody);
348
+ const fieldErrors = response.status === 422 ? parseFieldErrors(errorBody) : [];
349
+ const mapped = mapHttpStatusToError(
350
+ response.status,
351
+ errorCode,
352
+ errorMessage,
353
+ ctx,
354
+ fieldErrors
355
+ );
356
+ if (response.status === 429) {
357
+ lastError = mapped;
358
+ canRetry = true;
359
+ const retryAfter = parseRetryAfter(
360
+ response.headers.get("retry-after")
361
+ );
362
+ if (retryAfter !== null && attempt < this.maxRetries - 1) {
363
+ await abortableSleep(
364
+ Math.min(retryAfter, MAX_RETRY_DELAY),
365
+ externalSignal
366
+ );
367
+ continue;
368
+ }
369
+ } else if (response.status >= 500) {
370
+ lastError = mapped;
371
+ canRetry = methodRetryable;
372
+ } else {
373
+ throw mapped;
374
+ }
375
+ } catch (error) {
376
+ if (error instanceof ReoptSDKError) {
377
+ if (!(error instanceof RateLimitError) && !(error instanceof ServerError)) {
378
+ throw error;
379
+ }
380
+ lastError = error;
381
+ canRetry = methodRetryable;
382
+ } else if (error instanceof Error && error.name === "AbortError") {
383
+ lastError = new ReoptSDKError(
384
+ "Request timed out",
385
+ 408,
386
+ "TIMEOUT",
387
+ ctx
388
+ );
389
+ canRetry = methodRetryable;
390
+ } else {
391
+ lastError = error instanceof Error ? error : new Error(String(error));
392
+ canRetry = methodRetryable;
393
+ }
394
+ } finally {
395
+ clearTimeout(timeoutId);
396
+ if (externalSignal) {
397
+ externalSignal.removeEventListener("abort", onExternalAbort);
398
+ }
399
+ }
400
+ if (!canRetry) break;
401
+ if (attempt < this.maxRetries - 1) {
402
+ this.debug.retry(
403
+ method,
404
+ url,
405
+ attempt + 1,
406
+ lastError?.message ?? "unknown"
407
+ );
408
+ await abortableSleep(backoffDelay(attempt), externalSignal);
409
+ }
410
+ }
411
+ this.debug.error(method, url, lastError?.message ?? "unknown", requestId);
412
+ if (lastError instanceof ReoptSDKError && !lastError.context?.requestId) {
413
+ Object.assign(lastError.context ?? {}, { requestId });
414
+ }
415
+ throw lastError ?? new ServerError("All retry attempts failed");
416
+ }
417
+ };
418
+ function parseFieldErrors(body) {
419
+ if (!body?.error || typeof body.error !== "object") return [];
420
+ const err = body.error;
421
+ if (Array.isArray(err.fields)) {
422
+ return err.fields.filter(
423
+ (f) => f && typeof f === "object" && "field" in f
424
+ ).map((f) => ({
425
+ field: f.field,
426
+ message: f.message ?? "Validation failed",
427
+ code: f.code
428
+ }));
429
+ }
430
+ if (err.fields && typeof err.fields === "object" && !Array.isArray(err.fields)) {
431
+ return Object.entries(err.fields).map(
432
+ ([field, message]) => ({ field, message })
433
+ );
434
+ }
435
+ if (Array.isArray(err.issues)) {
436
+ return err.issues.filter(
437
+ (i) => i && typeof i === "object" && "path" in i
438
+ ).map((i) => ({
439
+ field: i.path?.join(".") ?? "unknown",
440
+ message: i.message ?? "Validation failed",
441
+ code: i.code
442
+ }));
443
+ }
444
+ return [];
445
+ }
446
+
447
+ export { BaseHttpClient, parseFieldErrors };
448
+ //# sourceMappingURL=chunk-DI6QJPTQ.js.map
449
+ //# sourceMappingURL=chunk-DI6QJPTQ.js.map