@reopt-ai/brandapp-sdk 3.1.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +39 -14
  3. package/dist/abort--nOBFN4M.js +50 -0
  4. package/dist/ai/index.d.ts +2 -314
  5. package/dist/ai/index.js +3 -7
  6. package/dist/ai-provider/index.d.ts +79 -163
  7. package/dist/ai-provider/index.js +752 -671
  8. package/dist/auth/index.d.ts +27 -27
  9. package/dist/auth/index.js +41 -33
  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 -133
  14. package/dist/client-B1q5P8rv.js +83 -0
  15. package/dist/client-B9QHVhdM.js +77 -0
  16. package/dist/client-BGGd_cpV.d.ts +103 -0
  17. package/dist/client-BJcy1V1a.js +140 -0
  18. package/dist/client-Beivhucf.js +55 -0
  19. package/dist/client-BruP5_nU.d.ts +147 -0
  20. package/dist/client-D-yNxNfk.js +28 -0
  21. package/dist/client-D0eBxh8j.d.ts +284 -0
  22. package/dist/client-D3RHHUUW.d.ts +207 -0
  23. package/dist/client-D6gs61w8.d.ts +53 -0
  24. package/dist/client-DBnK7ooQ.js +86 -0
  25. package/dist/client-DDw5yz_h.d.ts +53 -0
  26. package/dist/client-DPmoKuR9.js +305 -0
  27. package/dist/client-DsdakibF.js +503 -0
  28. package/dist/client-Dxg8_DIH.d.ts +71 -0
  29. package/dist/client-EbhUIhHq.js +53 -0
  30. package/dist/client-lk6wBu_0.d.ts +48 -0
  31. package/dist/client-p49ol9pg.d.ts +124 -0
  32. package/dist/cms/index.d.ts +52 -108
  33. package/dist/cms/index.js +105 -84
  34. package/dist/config-CRytOPPl.d.ts +394 -0
  35. package/dist/config-Cw0a3-C8.js +487 -0
  36. package/dist/dev/index.d.ts +2 -509
  37. package/dist/dev/index.js +2740 -2873
  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 -125
  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-DIAS8Rsl.d.ts → errors-CRCcErNC.d.ts} +55 -53
  48. package/dist/feedback/index.d.ts +2 -132
  49. package/dist/feedback/index.js +3 -5
  50. package/dist/files/index.d.ts +14 -14
  51. package/dist/files/index.js +41 -24
  52. package/dist/http-client-QKUvvirs.js +386 -0
  53. package/dist/index-DrVaKfhs.d.ts +456 -0
  54. package/dist/index-Z6OGcurJ.d.ts +169 -0
  55. package/dist/index.d.ts +6 -221
  56. package/dist/index.js +119 -70
  57. package/dist/logout/index.d.ts +109 -0
  58. package/dist/logout/index.js +264 -0
  59. package/dist/plans/index.d.ts +2 -236
  60. package/dist/plans/index.js +3 -5
  61. package/dist/push/index.d.ts +2 -79
  62. package/dist/push/index.js +3 -5
  63. package/dist/query-BvbCiGWb.js +35 -0
  64. package/dist/react/hooks.d.ts +97 -95
  65. package/dist/react/hooks.js +742 -356
  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 -5
  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 -47
  76. package/dist/webhooks/index.js +150 -127
  77. package/docs/api-reference.md +179 -2
  78. package/docs/dev-server.md +19 -18
  79. package/docs/errors.md +72 -15
  80. package/docs/logout.md +166 -0
  81. package/package.json +10 -5
  82. package/dist/chunk-2Q654O63.js +0 -350
  83. package/dist/chunk-F7BXBTZI.js +0 -54
  84. package/dist/chunk-IJOXTBIE.js +0 -599
  85. package/dist/chunk-JWXUVQRC.js +0 -157
  86. package/dist/chunk-L4DHB36G.js +0 -75
  87. package/dist/chunk-MRQY45U5.js +0 -465
  88. package/dist/chunk-N5JVE4WX.js +0 -449
  89. package/dist/chunk-O3PUWIDJ.js +0 -105
  90. package/dist/chunk-POLKEOYH.js +0 -63
  91. package/dist/chunk-R5CCGDUH.js +0 -49
  92. package/dist/chunk-RBHP7IZF.js +0 -96
  93. package/dist/chunk-REIKXSMY.js +0 -7
  94. package/dist/chunk-T7YTITRJ.js +0 -112
  95. package/dist/chunk-V73GORO3.js +0 -81
  96. package/dist/chunk-VRNBYSWU.js +0 -32
  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
@@ -0,0 +1,386 @@
1
+ import { A as mapHttpStatusToError, C as ServerError, a as resolveIdBaseUrl, b as RateLimitError, i as resolveBaseUrl, n as SDK_VERSION, o as validateConfig, x as ReoptSDKError } from "./config-Cw0a3-C8.js";
2
+ import { t as createAuthHeader } from "./encoding-Bwfm3iaE.js";
3
+
4
+ //#region 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") return configDebug;
8
+ try {
9
+ if (typeof process !== "undefined" && process.env) {
10
+ const v = process.env.BRANDAPP_SDK_DEBUG;
11
+ if (v === "trace") return "trace";
12
+ if (v === "info" || v === "1") return "info";
13
+ if (process.env.DEBUG?.includes("brandapp")) return "info";
14
+ }
15
+ } catch {}
16
+ return "off";
17
+ }
18
+ const SAFE_QUERY_KEYS = /* @__PURE__ */ new Set([
19
+ "page",
20
+ "limit",
21
+ "sort",
22
+ "sortBy",
23
+ "sortOrder",
24
+ "order",
25
+ "cursor",
26
+ "offset"
27
+ ]);
28
+ function maskUrl(url) {
29
+ const qIndex = url.indexOf("?");
30
+ if (qIndex === -1) return url;
31
+ const base = url.slice(0, qIndex);
32
+ const query = url.slice(qIndex + 1);
33
+ if (!query) return base;
34
+ return `${base}?${query.split("&").map((pair) => {
35
+ const eq = pair.indexOf("=");
36
+ if (eq === -1) return pair;
37
+ const key = pair.slice(0, eq);
38
+ return SAFE_QUERY_KEYS.has(key) ? pair : `${key}=***`;
39
+ }).join("&")}`;
40
+ }
41
+ const SENSITIVE_KEYS = /(?:^authorization$)|(?:(secret|password|credential|token|apikey)$)/i;
42
+ function redactBody(value, depth = 0) {
43
+ if (value == null || depth > 4) return value;
44
+ if (Array.isArray(value)) return value.slice(0, 20).map((v) => redactBody(v, depth + 1));
45
+ if (typeof value === "object") {
46
+ const out = {};
47
+ for (const [k, v] of Object.entries(value)) out[k] = SENSITIVE_KEYS.test(k) ? "***" : redactBody(v, depth + 1);
48
+ return out;
49
+ }
50
+ if (typeof value === "string" && value.length > 500) return `${value.slice(0, 500)}…(${value.length - 500} more chars)`;
51
+ return value;
52
+ }
53
+ function isStructuredMode() {
54
+ try {
55
+ return typeof process !== "undefined" && process.env?.BRANDAPP_SDK_LOG_FORMAT === "json";
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+ function createDebugLogger(configDebug) {
61
+ const level = resolveLevel(configDebug);
62
+ if (level === "off") return {
63
+ level,
64
+ request: () => {},
65
+ response: () => {},
66
+ retry: () => {},
67
+ error: () => {}
68
+ };
69
+ return isStructuredMode() ? createStructuredLogger(level) : createHumanLogger(level);
70
+ }
71
+ function createHumanLogger(level) {
72
+ const prefix = "[brandapp-sdk]";
73
+ return {
74
+ level,
75
+ request(method, url, requestId, body) {
76
+ console.debug(`${prefix} → ${method} ${maskUrl(url)} (req ${requestId.slice(0, 8)})`);
77
+ if (level === "trace" && body !== void 0) console.debug(`${prefix} body:`, redactBody(body));
78
+ },
79
+ response(method, url, status, durationMs, requestId, body) {
80
+ console.debug(`${prefix} ← ${method} ${maskUrl(url)} ${status} (${durationMs}ms, req ${requestId.slice(0, 8)})`);
81
+ if (level === "trace" && body !== void 0) console.debug(`${prefix} body:`, redactBody(body));
82
+ },
83
+ retry(method, url, attempt, reason) {
84
+ console.debug(`${prefix} ↻ ${method} ${maskUrl(url)} retry #${attempt} (${reason})`);
85
+ },
86
+ error(method, url, error, requestId) {
87
+ console.debug(`${prefix} ✕ ${method} ${maskUrl(url)} ${error} (req ${requestId.slice(0, 8)})`);
88
+ }
89
+ };
90
+ }
91
+ function createStructuredLogger(level) {
92
+ const log = (entry) => {
93
+ console.debug(JSON.stringify({
94
+ sdk: "brandapp-sdk",
95
+ ...entry
96
+ }));
97
+ };
98
+ return {
99
+ level,
100
+ request(method, url, requestId, body) {
101
+ log({
102
+ level: "debug",
103
+ event: "request",
104
+ method,
105
+ url: maskUrl(url),
106
+ requestId,
107
+ ...level === "trace" && body !== void 0 ? { body: redactBody(body) } : {}
108
+ });
109
+ },
110
+ response(method, url, status, durationMs, requestId, body) {
111
+ log({
112
+ level: "debug",
113
+ event: "response",
114
+ method,
115
+ url: maskUrl(url),
116
+ status,
117
+ durationMs,
118
+ requestId,
119
+ ...level === "trace" && body !== void 0 ? { body: redactBody(body) } : {}
120
+ });
121
+ },
122
+ retry(method, url, attempt, reason) {
123
+ log({
124
+ level: "warn",
125
+ event: "retry",
126
+ method,
127
+ url: maskUrl(url),
128
+ attempt,
129
+ reason
130
+ });
131
+ },
132
+ error(method, url, error, requestId) {
133
+ log({
134
+ level: "error",
135
+ event: "error",
136
+ method,
137
+ url: maskUrl(url),
138
+ error,
139
+ requestId
140
+ });
141
+ }
142
+ };
143
+ }
144
+
145
+ //#endregion
146
+ //#region src/core/http-client.ts
147
+ /** Parse Retry-After header value to milliseconds. Returns null if invalid. */
148
+ function parseRetryAfter(value) {
149
+ if (!value) return null;
150
+ const seconds = Number(value);
151
+ if (!Number.isNaN(seconds) && seconds >= 0) return seconds * 1e3;
152
+ const date = Date.parse(value);
153
+ if (!Number.isNaN(date)) {
154
+ const ms = date - Date.now();
155
+ return ms > 0 ? ms : 0;
156
+ }
157
+ return null;
158
+ }
159
+ /** Detect JS runtime environment */
160
+ function detectRuntime() {
161
+ if (typeof globalThis.EdgeRuntime === "string") return "edge";
162
+ if (typeof window !== "undefined") return "browser";
163
+ return "node";
164
+ }
165
+ const RUNTIME = detectRuntime();
166
+ const DEFAULT_TIMEOUT = 15e3;
167
+ const DEFAULT_MAX_RETRIES = 3;
168
+ const INITIAL_RETRY_DELAY = 1e3;
169
+ /** Cap on the exponential backoff so large `maxRetries` can't run away. */
170
+ const MAX_RETRY_DELAY = 3e4;
171
+ /**
172
+ * Methods safe to retry on 5xx / network / timeout failures. POST and PATCH are
173
+ * excluded by default: the server may have already applied the mutation, so a
174
+ * blind retry risks duplicate side effects. 429 is handled separately (always
175
+ * retryable — the request was rate-limited, never processed).
176
+ */
177
+ const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
178
+ "GET",
179
+ "HEAD",
180
+ "PUT",
181
+ "DELETE",
182
+ "OPTIONS"
183
+ ]);
184
+ function isIdempotentMethod(method) {
185
+ return IDEMPOTENT_METHODS.has(method.toUpperCase());
186
+ }
187
+ /** Full-jitter backoff: a random delay in `[base/2, base]`, capped. */
188
+ function backoffDelay(attempt) {
189
+ return Math.min(INITIAL_RETRY_DELAY * Math.pow(2, attempt), MAX_RETRY_DELAY) * (.5 + Math.random() * .5);
190
+ }
191
+ /**
192
+ * Sleep that resolves early when `signal` aborts, so a cancelled request never
193
+ * hangs for the full backoff / Retry-After window. On abort the next loop
194
+ * iteration re-checks `signal.aborted` and aborts the fetch immediately.
195
+ */
196
+ function abortableSleep(ms, signal) {
197
+ return new Promise((resolve) => {
198
+ if (signal?.aborted) return resolve();
199
+ const onAbort = () => {
200
+ clearTimeout(timer);
201
+ resolve();
202
+ };
203
+ const timer = setTimeout(() => {
204
+ signal?.removeEventListener("abort", onAbort);
205
+ resolve();
206
+ }, ms);
207
+ signal?.addEventListener("abort", onAbort, { once: true });
208
+ });
209
+ }
210
+ function parseErrorBody(errorBody) {
211
+ if (typeof errorBody?.error === "string") return {
212
+ code: void 0,
213
+ message: errorBody.error
214
+ };
215
+ return {
216
+ code: errorBody?.error?.code,
217
+ message: errorBody?.error?.message
218
+ };
219
+ }
220
+ var BaseHttpClient = class {
221
+ baseUrl;
222
+ authHeader;
223
+ timeout;
224
+ maxRetries;
225
+ retryNonIdempotent;
226
+ debug;
227
+ constructor(config, pathPrefix, options) {
228
+ validateConfig(config);
229
+ const base = options?.useIdServer ? resolveIdBaseUrl(config) : resolveBaseUrl(config);
230
+ this.baseUrl = base + pathPrefix;
231
+ this.authHeader = createAuthHeader(config);
232
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
233
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
234
+ this.retryNonIdempotent = config.retryNonIdempotent ?? false;
235
+ this.debug = createDebugLogger(config.debug ?? false);
236
+ }
237
+ /**
238
+ * Resolved request origin + path prefix
239
+ * (e.g. `https://brandapp.reopt.ai/api/v1/brandapp/{id}/ai`). Exposed so domain
240
+ * clients that must hand-roll `fetch` (SSE streaming, multipart upload) reuse
241
+ * the same resolved host instead of re-deriving it.
242
+ */
243
+ get requestBaseUrl() {
244
+ return this.baseUrl;
245
+ }
246
+ /** The default `Authorization` header value (Basic or pre-minted Bearer). */
247
+ get authorizationHeader() {
248
+ return this.authHeader;
249
+ }
250
+ /** Configured request timeout in ms. */
251
+ get timeoutMs() {
252
+ return this.timeout;
253
+ }
254
+ async fetch(method, path, body, options) {
255
+ const url = `${this.baseUrl}${path}`;
256
+ const requestId = crypto.randomUUID();
257
+ const timeout = options?.timeout ?? this.timeout;
258
+ const methodRetryable = this.retryNonIdempotent || isIdempotentMethod(method) || options?.idempotent === true;
259
+ let lastError;
260
+ this.debug.request(method, url, requestId, body);
261
+ const startTime = Date.now();
262
+ for (let attempt = 0; attempt < this.maxRetries; attempt++) {
263
+ const ctx = {
264
+ method,
265
+ url,
266
+ attempt,
267
+ requestId
268
+ };
269
+ let canRetry = false;
270
+ const controller = new AbortController();
271
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
272
+ const externalSignal = options?.signal;
273
+ const onExternalAbort = () => controller.abort();
274
+ if (externalSignal) if (externalSignal.aborted) controller.abort();
275
+ else externalSignal.addEventListener("abort", onExternalAbort, { once: true });
276
+ try {
277
+ const headers = {
278
+ Authorization: options?.bearerToken ? `Bearer ${options.bearerToken}` : this.authHeader,
279
+ "X-SDK-Version": `brandapp-sdk/${SDK_VERSION}`,
280
+ "X-SDK-Runtime": RUNTIME,
281
+ "X-Request-Id": requestId
282
+ };
283
+ if (body !== void 0) headers["Content-Type"] = "application/json";
284
+ if (!isIdempotentMethod(method)) headers["Idempotency-Key"] = requestId;
285
+ const response = await globalThis.fetch(url, {
286
+ method,
287
+ headers,
288
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
289
+ signal: controller.signal
290
+ });
291
+ if (response.ok) {
292
+ const durationMs = Date.now() - startTime;
293
+ if (response.status === 204 || response.headers.get("content-length") === "0") {
294
+ this.debug.response(method, url, response.status, durationMs, requestId);
295
+ return;
296
+ }
297
+ if (this.debug.level === "trace") {
298
+ const parsed = await response.json();
299
+ this.debug.response(method, url, response.status, durationMs, requestId, parsed);
300
+ return parsed;
301
+ }
302
+ this.debug.response(method, url, response.status, durationMs, requestId);
303
+ return await response.json();
304
+ }
305
+ const errorBody = await response.json().catch(() => ({}));
306
+ const { code: errorCode, message: errorMessage } = parseErrorBody(errorBody);
307
+ const fieldErrors = response.status === 422 ? parseFieldErrors(errorBody) : [];
308
+ const mapped = mapHttpStatusToError(response.status, errorCode, errorMessage, ctx, fieldErrors);
309
+ if (response.status === 429) {
310
+ lastError = mapped;
311
+ canRetry = true;
312
+ const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
313
+ if (retryAfter !== null && attempt < this.maxRetries - 1) {
314
+ await abortableSleep(Math.min(retryAfter, MAX_RETRY_DELAY), externalSignal);
315
+ continue;
316
+ }
317
+ } else if (response.status >= 500) {
318
+ lastError = mapped;
319
+ canRetry = methodRetryable;
320
+ } else throw mapped;
321
+ } catch (error) {
322
+ if (error instanceof ReoptSDKError) {
323
+ if (!(error instanceof RateLimitError) && !(error instanceof ServerError)) throw error;
324
+ lastError = error;
325
+ canRetry = methodRetryable;
326
+ } else if (error instanceof Error && error.name === "AbortError") {
327
+ if (externalSignal?.aborted) {
328
+ const cancelled = new ReoptSDKError("Request aborted by caller", 0, "CANCELLED", ctx);
329
+ cancelled.name = "AbortError";
330
+ throw cancelled;
331
+ }
332
+ lastError = new ReoptSDKError("Request timed out", 408, "TIMEOUT", ctx);
333
+ canRetry = methodRetryable;
334
+ } else {
335
+ lastError = error instanceof Error ? error : new Error(String(error));
336
+ canRetry = methodRetryable;
337
+ }
338
+ } finally {
339
+ clearTimeout(timeoutId);
340
+ if (externalSignal) externalSignal.removeEventListener("abort", onExternalAbort);
341
+ }
342
+ if (!canRetry) break;
343
+ if (attempt < this.maxRetries - 1) {
344
+ this.debug.retry(method, url, attempt + 1, lastError?.message ?? "unknown");
345
+ await abortableSleep(backoffDelay(attempt), externalSignal);
346
+ }
347
+ }
348
+ this.debug.error(method, url, lastError?.message ?? "unknown", requestId);
349
+ if (lastError instanceof ReoptSDKError && !lastError.context?.requestId) lastError.context = {
350
+ ...lastError.context ?? {},
351
+ requestId
352
+ };
353
+ throw lastError ?? new ServerError("All retry attempts failed", { requestId });
354
+ }
355
+ };
356
+ /**
357
+ * API 에러 응답에서 필드 수준 에러를 파싱
358
+ *
359
+ * 지원 포맷:
360
+ * - { error: { fields: [{ field, message, code }] } }
361
+ * - { error: { fields: { fieldName: "message" } } }
362
+ * - { error: { issues: [{ path: ["field"], message }] } } (Zod 포맷)
363
+ */
364
+ function parseFieldErrors(body) {
365
+ if (!body?.error || typeof body.error !== "object") return [];
366
+ const err = body.error;
367
+ if (Array.isArray(err.fields)) return err.fields.filter((f) => f && typeof f === "object" && "field" in f).map((f) => ({
368
+ field: f.field,
369
+ message: f.message ?? "Validation failed",
370
+ code: f.code
371
+ }));
372
+ if (err.fields && typeof err.fields === "object" && !Array.isArray(err.fields)) return Object.entries(err.fields).map(([field, message]) => ({
373
+ field,
374
+ message
375
+ }));
376
+ if (Array.isArray(err.issues)) return err.issues.filter((i) => i && typeof i === "object" && "path" in i).map((i) => ({
377
+ field: i.path?.join(".") ?? "unknown",
378
+ message: i.message ?? "Validation failed",
379
+ code: i.code
380
+ }));
381
+ return [];
382
+ }
383
+
384
+ //#endregion
385
+ export { parseFieldErrors as n, BaseHttpClient as t };
386
+ //# sourceMappingURL=http-client-QKUvvirs.js.map