@reopt-ai/brandapp-sdk 3.0.0 → 3.3.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 (47) hide show
  1. package/CHANGELOG.md +111 -3
  2. package/README.md +29 -13
  3. package/dist/ai/index.js +4 -3
  4. package/dist/ai-provider/index.js +16 -2
  5. package/dist/auth/index.js +4 -3
  6. package/dist/better-auth/index.d.ts +1 -1
  7. package/dist/better-auth/index.js +35 -24
  8. package/dist/chunk-2LSCQHAU.js +21 -0
  9. package/dist/{chunk-E457LO5A.js → chunk-4U4ZPPL4.js} +4 -4
  10. package/dist/{chunk-K3YVJE6E.js → chunk-55KHY5GH.js} +3 -3
  11. package/dist/{chunk-J5Y2GSJF.js → chunk-C5VTRZWX.js} +43 -28
  12. package/dist/{chunk-KU2LN5SE.js → chunk-FJUCWXX3.js} +4 -4
  13. package/dist/{chunk-TUKIYH4Q.js → chunk-H33OTQEN.js} +3 -3
  14. package/dist/chunk-OG7R3UAR.js +105 -0
  15. package/dist/{chunk-6FLYVNZI.js → chunk-PF24XU54.js} +3 -3
  16. package/dist/{chunk-6KPKZ7ZB.js → chunk-QN3QD67K.js} +3 -3
  17. package/dist/{chunk-YRGLBM6V.js → chunk-UGBBXCZE.js} +6 -6
  18. package/dist/{chunk-WSEROZVO.js → chunk-UVT2E6KD.js} +6 -6
  19. package/dist/{chunk-PJZB4VP7.js → chunk-YPLT3RFL.js} +3 -3
  20. package/dist/{chunk-DI6QJPTQ.js → chunk-YTKSAWV2.js} +20 -6
  21. package/dist/cms/index.js +10 -6
  22. package/dist/dev/index.d.ts +19 -0
  23. package/dist/dev/index.js +107 -4
  24. package/dist/eav/index.d.ts +1 -1
  25. package/dist/eav/index.js +5 -4
  26. package/dist/{errors-5hd5ZR-M.d.ts → errors-BjDFIyA6.d.ts} +25 -3
  27. package/dist/feedback/index.js +4 -3
  28. package/dist/files/index.js +4 -3
  29. package/dist/index.d.ts +10 -1
  30. package/dist/index.js +14 -13
  31. package/dist/logout/index.d.ts +106 -0
  32. package/dist/logout/index.js +321 -0
  33. package/dist/plans/index.d.ts +107 -11
  34. package/dist/plans/index.js +4 -3
  35. package/dist/push/index.js +4 -3
  36. package/dist/react/hooks.d.ts +5 -1
  37. package/dist/react/hooks.js +63 -15
  38. package/dist/terms/index.js +4 -3
  39. package/dist/testing/index.d.ts +1 -1
  40. package/dist/webhooks/index.d.ts +6 -3
  41. package/docs/api-reference.md +99 -3
  42. package/docs/cms.md +0 -1
  43. package/docs/dev-server.md +19 -18
  44. package/docs/errors.md +72 -15
  45. package/docs/logout.md +166 -0
  46. package/package.json +7 -1
  47. package/dist/chunk-T2WXHAAC.js +0 -54
package/CHANGELOG.md CHANGED
@@ -5,9 +5,117 @@ All notable changes to `@reopt-ai/brandapp-sdk` are documented here.
5
5
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
6
  This project adheres to [Semantic Versioning](https://semver.org/).
7
7
 
8
+ ## [3.3.0] — 2026-07-24
9
+
10
+ 리뷰(멀티에이전트 교차검증) 후속 하드닝 — 로그아웃 보안·코어 정확성·AI/React/CMS
11
+ 견고성·문서 정합. 전부 backward-compatible(minor). 새 테스트 +33.
12
+
13
+ ### Security — OIDC 로그아웃 (`@reopt-ai/brandapp-sdk/logout`)
14
+
15
+ - **JWKS 강제 refetch 스로틀 + in-flight 병합** — 공개(무인증) back-channel 엔드포인트에서
16
+ 서명 불일치마다 무제한으로 JWKS를 재조회하던 것을 jwks_uri별 쿨다운(30s)과 동시 요청
17
+ 병합으로 상한. 위조 토큰 폭주가 공유 JWKS 엔드포인트로 부하를 반사시키는 벡터 차단.
18
+ 초기 캐시 채우기 fetch는 쿨다운에 포함되지 않아 키 로테이션 복구는 단일 검증 내 유지.
19
+ - **discovery/JWKS fetch 타임아웃(5s, fail-closed)** — 느린 IdP가 공개 로그아웃 핸들러를
20
+ 붙잡지 못하게 `AbortSignal.timeout` 적용.
21
+ - **인프라 실패와 토큰 검증 실패 분리 (§2.8)** — discovery/JWKS 일시 불가는 새 코드
22
+ `logout_verification_unavailable`로 던지고 핸들러가 **HTTP 503(retryable)** 반환. 잘못된
23
+ 토큰만 400. 정상 토큰을 일시 JWKS 장애 때 영구 거부(400)하던 문제 해소.
24
+
25
+ ### Security — 코어
26
+
27
+ - **`assertBrowserSafe` Web/Service Worker 감지** — `window` 없이 실행되는 worker에서도
28
+ `clientSecret` 사용을 차단(publicly-served worker JS로의 admin 자격 유출 방지).
29
+
30
+ ### Fixed
31
+
32
+ - **에러 `requestId` 유실** — `RateLimitError`/`ServerError`가 재시도 소진 후 `context`(및
33
+ `requestId`)를 실제로 보유하도록 수정(이전엔 임시 객체에 써서 버려짐). 지원 티켓용
34
+ X-Request-Id를 항상 읽을 수 있음.
35
+ - **whitespace 토큰 → `Bearer <whitespace>`** — `createAuthHeader`가 `validateConfig`와 동일한
36
+ `token.trim()` 의미를 따라, 공백뿐인 토큰은 Basic으로 폴백하고 유효 토큰의 주변 공백도 제거.
37
+ - **AI 이미지 2-hop 파손 이미지** — Blob URL이 비-2xx면 오류 페이지 바이트를 base64로 반환하던
38
+ 것을 typed provider 에러로 승격(`response.ok` 가드).
39
+ - **AI provider body 전송 무한 대기** — `fetchWithTimeout`이 헤더뿐 아니라 body 전송까지
40
+ 타임아웃 창 안에서 커버(헤더 도착 즉시 타이머 해제하던 문제).
41
+ - **React `useEavRecordsInfinite` 캐시 충돌** — finite/infinite 레코드 리스트가 같은 queryKey를
42
+ 공유해 shape가 충돌하던 것을, `recordsInfinite` 네임스페이스 분리로 해소. 뮤테이션 무효화는
43
+ 길이-3 prefix로 바꿔 쿼리 객체 유무와 무관하게 finite·infinite·count 리스트를 모두 무효화
44
+ (trailing-undefined 키가 필터된 리스트를 못 지우던 잠복 버그 동반 수정).
45
+ - **RSS 피드 XML-불법 제어문자** — `toRssFeed`가 XML 1.0에서 표현 불가한 C0 제어문자를 제거해,
46
+ 한 글자로 피드 전체가 not-well-formed가 되던 것 방지(escapeXml·CDATA 양 경로).
47
+ - **cms/files 경로 ID 미인코딩** — `cms.posts.get`/`cms.postGroups.get`/`files.get`/`files.delete`가
48
+ 경로 ID를 `encodeURIComponent`로 감싸, `/`·`?`·`#`·`..` 포함 id가 다른 엔드포인트로 새는 것 방지.
49
+
50
+ ### Added
51
+
52
+ - **`FetchOptions.idempotent`** — POST/PATCH로 터널링된 read를 per-call로 재시도 대상에 편입
53
+ (client 전역 `retryNonIdempotent` 없이). Better Auth 어댑터의 `findOne`/`findMany`/`count`가
54
+ 이를 사용해 인증 hot path의 일시적 5xx를 재시도(뮤테이션은 그대로 비재시도).
55
+ - **Caller-cancel = `CANCELLED`** — 외부 `AbortSignal` 취소가 이제 `TIMEOUT`(408)이 아니라
56
+ `name: "AbortError"`인 `CANCELLED` 에러로 즉시 종료(재시도 소진하지 않음). 내부 타임아웃만
57
+ `TIMEOUT`.
58
+ - **Dev 서버 faithful OIDC mock** — dev 서버가 인메모리 Ed25519 키페어로 실 EdDSA `id_token`을
59
+ 서명하고 `/api/auth/jwks`·`/api/auth/oauth2/end-session`을 실제로 마운트. 새
60
+ `dev.mintLogoutToken({ clientId, sessionId, userId })`로 소비자가 back-channel 로그아웃 핸들러를
61
+ dev 서버 대상 end-to-end로 검증 가능. discovery는 서명이 불가한 런타임에선 해당 능력을 광고하지
62
+ 않음(reduced-but-coherent).
63
+
64
+ ### Changed
65
+
66
+ - 로그아웃 검증 캐시 리셋(`clearLogoutTokenCaches`)이 새 refetch 스로틀 상태도 비운다.
67
+
68
+ ## [3.2.0] — 2026-07-24
69
+
70
+ OIDC **Single Logout** 상호운용 — reopt와 외부 앱 사이 세션 종료를 양방향으로 연결한다
71
+ (RFC-0016 세션 표면 스코핑). 새 sub-path `@reopt-ai/brandapp-sdk/logout`. 전부 additive(minor).
72
+
73
+ ### Added — `@reopt-ai/brandapp-sdk/logout`
74
+
75
+ - **`createBackchannelLogoutHandler({ onLogout })`** — OIDC Back-Channel Logout 수신 핸들러
76
+ (`Request → Response`). reopt가 IdP 세션 폐기(로그아웃·차단·삭제·기기 종료) 시 보내는
77
+ `logout_token`을 검증하고 `onLogout({ sid, sub })`로 앱의 파생 세션을 종료하게 한다.
78
+ Next.js Route Handler·Hono·Fetch 서버 어디에나 마운트 가능.
79
+ - **`verifyBackchannelLogoutToken(token, opts)`** — HTTP 래퍼 없이 logout_token만 검증
80
+ (커스텀 전송·테스트용). 실패 시 `ReoptSDKError(code: "invalid_logout_token")`.
81
+ - **`buildEndSessionUrl({ idToken, postLogoutRedirectUri, state })`** — RP-Initiated Logout
82
+ URL 조립. 사용자를 reopt `end_session_endpoint`로 보내 IdP 세션(및 전 파생 세션)까지 종료.
83
+
84
+ 서명 검증은 **Web Crypto(Ed25519)** — 외부 의존 없음(Node 20+ / Deno / Workers / 최신 브라우저).
85
+ 스펙(OIDC Back-Channel Logout 1.0) 전 검증 적용: 서명·iss·aud·iat·events·sid·nonce 금지·alg 고정.
86
+ 상세: [docs/logout.md](./docs/logout.md).
87
+
88
+ ## [3.1.0] — 2026-07-15
89
+
90
+ 플랜 구독 결제를 SDK로 완결 — `plans`가 read-only에서 **hosted checkout**(구독·결제·취소)까지
91
+ 확장. 실 결제(Toss/Paddle) 미설정 시 id.reopt.ai 가상 결제(샌드박스) 흐름으로 "카탈로그 →
92
+ 구독 → 결제 → 엔타이틀먼트" 전 과정을 코드 설정 없이 테스트할 수 있다. 전부 additive(minor).
93
+
94
+ ### Added — `sdk.plans` checkout
95
+
96
+ - **`plans.createCheckout({ planId, successUrl, cancelUrl }, accessToken)`** — hosted checkout
97
+ 세션을 만들고 `CheckoutSession`을 반환한다. `checkoutUrl`로 브라우저를 리다이렉트하면 샌드박스
98
+ 모드에서 id.reopt.ai 가상 결제 페이지가 구독을 활성화하고 `successUrl`/`cancelUrl`로 복귀시킨다.
99
+ - **`plans.getCheckout(checkoutId, accessToken)`** — 체크아웃 세션 상태 폴링(복귀 페이지에서 확인).
100
+ - **`plans.cancel(accessToken)`** — 현재 샌드박스 구독 취소(결제 기간까지 접근 유지).
101
+ - 새 타입: `CheckoutSession`, `CreateCheckoutInput`, `CheckoutStatus`, `CancelSubscriptionResult`
102
+ (`@reopt-ai/brandapp-sdk/plans`).
103
+
104
+ ### Added — `RequiredTermsError`
105
+
106
+ - **`RequiredTermsError`**(`isRequiredTermsError` 가드 동반) — `createCheckout`가 플랜 필수 약관
107
+ 미동의 시 던진다. `error.missingTermsIds`로 어떤 약관인지 알아내 `sdk.terms.list()`+
108
+ `sdk.terms.consent()`로 동의를 수집한 뒤 재시도한다. HTTP 422 `REQUIRED_TERMS` 매핑.
109
+
110
+ ### Notes
111
+
112
+ - 실 Toss/Paddle checkout은 아직 SDK로 구동하지 않는다(브라우저 SDK+호스트 콜백 필요 →
113
+ first-party brandfront 흐름 유지). 브랜드앱이 live 결제로 설정되면 `createCheckout`는 409
114
+ `LIVE_MODE_UNSUPPORTED`를 반환한다. usage 미터는 여전히 read-only 메타데이터.
115
+
8
116
  ## [3.0.0] — 2026-06-26
9
117
 
10
- 보안 리뷰(BRANDAPP_SDK_REVIEW.md) 후속 — 인증·자격증명·웹훅 강화. 웹훅 검증 계약과
118
+ 보안 리뷰(docs/reviews/BRANDAPP_SDK_REVIEW.md) 후속 — 인증·자격증명·웹훅 강화. 웹훅 검증 계약과
11
119
  `verifySignature` 시그니처가 바뀌어 메이저 범프.
12
120
 
13
121
  ### BREAKING — 웹훅 검증을 실제 플랫폼 송신부에 정렬 (F-2)
@@ -360,8 +468,8 @@ EAV 에러 분기를 ergonomic하게 — 1:1 메타 충돌, authUser 미등록,
360
468
  > `cms.postGroups.{create,update,delete}` + 동일 이름의 React 훅과 입력 타입)이
361
469
  > 제거됐다. 1.7.x에서도 production 백엔드는 해당 endpoint를 노출하지 않았고
362
470
  > dev 서버에서만 동작했기 때문에 사실상 dead surface였으며, 알려진 외부 npm
363
- > 소비자가 없어 minor bump로 처리한다. cms를 호출하는 reopt-ai 내부 패키지(
364
- > `apps/brandapp-playground` 등)는 본 릴리즈에 함께 정렬됐다. 외부 소비자가
471
+ > 소비자가 없어 minor bump로 처리한다. 당시 cms를 호출하던 reopt-ai 내부
472
+ > 소비 앱도 본 릴리즈에 함께 정렬됐다. 외부 소비자가
365
473
  > write 호출에 의존하고 있다면 [`docs/migration.md`](./docs/migration.md)의
366
474
  > 1.7 → 1.8 가이드를 따라 read-only로 전환하거나 1.7.x에 핀 고정.
367
475
 
package/README.md CHANGED
@@ -280,21 +280,37 @@ const meta = asJson<Meta>(record.values.meta); // Meta | undefined
280
280
 
281
281
  ## Exports
282
282
 
283
- | Path | Main Exports | Requires `better-auth` |
284
- | ------------------------ | --------------------------------------------------------------------------------- | ---------------------- |
285
- | `"."` | `createReoptSDK`, `createLazySDK`, `initReoptSDK`, `getReoptSDK`, errors | No |
286
- | `"./better-auth"` | `createReoptBetterAuth`, `createReoptAdapter`, `createReoptOAuth` | Yes |
287
- | `"./better-auth/client"` | `createReoptOAuthClient`, `REOPT_PROVIDER_ID` | Yes |
288
- | `"./eav"` | `createReoptEavClient`, `collectAll`, EAV types, `TypedEavRecord`, `EntityClient` | No |
289
- | `"./eav/schema"` | `defineEntity`, `defineSchema`, `syncSchema`, `computeDiff`, schema/sync types | No |
290
- | `"./eav/coerce"` | `asString`, `asNumber`, `asBoolean`, `asDate`, `asJson`, `asStringArray` | No |
283
+ | Path | Main Exports | Requires `better-auth` |
284
+ | ---------------------------- | -------------------------------------------------------------------------------------- | ---------------------- |
285
+ | `"."` | `createReoptSDK`, `createLazySDK`, `initReoptSDK`, `getReoptSDK`, errors | No |
286
+ | `"./better-auth"` | `createReoptBetterAuth`, `createReoptAdapter`, `createReoptOAuth` | Yes |
287
+ | `"./better-auth/client"` | `createReoptOAuthClient`, `REOPT_PROVIDER_ID` | Yes |
288
+ | `"./eav"` | `createReoptEavClient`, `collectAll`, EAV types, `TypedEavRecord`, `EntityClient` | No |
289
+ | `"./eav/schema"` | `defineEntity`, `defineSchema`, `syncSchema`, `computeDiff`, schema/sync types | No |
290
+ | `"./eav/coerce"` | `asString`, `asNumber`, `asBoolean`, `asDate`, `asJson`, `asStringArray` | No |
291
+ | `"./eav/migrate"` | `defineMigration`, `runMigrations`, migration types | No |
292
+ | `"./ai"` / `"./ai-provider"` | `ReoptAiClient` / `createBrandappProvider` (Vercel AI SDK) | No |
293
+ | `"./auth"` | `getSessionFromCookies`, `verifySession`, `sdk.auth` client | No |
294
+ | `"./cms"` | `sdk.cms` types + `toMetadata` / `toSitemapItems` / `toRssFeed` / `EditorSpec` | No |
295
+ | `"./files"` | file client types + `optimizeUrl`, `createImageLoader` | No |
296
+ | `"./terms"` | Terms list / consent / withdraw types | No |
297
+ | `"./plans"` | `createReoptPlansClient`, `Plan` / `CheckoutSession` / `CurrentPlan` types | No |
298
+ | `"./push"` | Customer device token register / unregister / list types | No |
299
+ | `"./feedback"` | Customer feedback submission types | No |
300
+ | `"./logout"` | `createBackchannelLogoutHandler`, `verifyBackchannelLogoutToken`, `buildEndSessionUrl` | No |
301
+ | `"./webhooks"` | `createWebhookHandler`, `verifySignature` | No |
302
+ | `"./react/hooks"` | TanStack Query hooks (`useAiCredits`, `useEavRecords`, …) | No |
303
+ | `"./dev"` / `"./testing"` | `createDevServer` / `createTestSDK` (local dev + fixtures) | No |
304
+
305
+ > Full signatures for every sub-path: [`docs/api-reference.md`](./docs/api-reference.md).
291
306
 
292
307
  > **Bundle tip.** `createReoptSDK()` eagerly wires every client (ai, auth, cms,
293
- > eav, files, terms), so importing it pulls all of them into your bundle. If you
294
- > only use one domain, import its factory or sub-path directly so tree-shaking
295
- > drops the rest — e.g. `import { createReoptEavClient } from "@reopt-ai/brandapp-sdk/eav"`
296
- > instead of the unified `createReoptSDK`. The core is edge-safe (no Node
297
- > built-ins) and `sideEffects: false`, so unused sub-paths cost nothing.
308
+ > eav, feedback, files, plans, push, terms), so importing it pulls all of them
309
+ > into your bundle. If you only use one domain, import its factory or sub-path
310
+ > directly so tree-shaking drops the rest — e.g.
311
+ > `import { createReoptEavClient } from "@reopt-ai/brandapp-sdk/eav"` instead of
312
+ > the unified `createReoptSDK`. The core is edge-safe (no Node built-ins) and
313
+ > `sideEffects: false`, so unused sub-paths cost nothing.
298
314
 
299
315
  ## Configuration
300
316
 
package/dist/ai/index.js CHANGED
@@ -1,7 +1,8 @@
1
- export { ReoptAiClient, createReoptAiClient } from '../chunk-KU2LN5SE.js';
1
+ export { ReoptAiClient, createReoptAiClient } from '../chunk-FJUCWXX3.js';
2
2
  import '../chunk-L4DHB36G.js';
3
3
  import '../chunk-F7BXBTZI.js';
4
- import '../chunk-DI6QJPTQ.js';
5
- import '../chunk-J5Y2GSJF.js';
4
+ import '../chunk-YTKSAWV2.js';
5
+ import '../chunk-2LSCQHAU.js';
6
+ import '../chunk-C5VTRZWX.js';
6
7
  //# sourceMappingURL=index.js.map
7
8
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,7 @@
1
1
  import { createSSELineProcessor } from '../chunk-L4DHB36G.js';
2
2
  import { createManagedAbort } from '../chunk-F7BXBTZI.js';
3
- import { assertBrowserSafe, validateConfig, resolveBaseUrl, createAuthHeader, SDK_VERSION, mapHttpStatusToError } from '../chunk-J5Y2GSJF.js';
3
+ import { createAuthHeader } from '../chunk-2LSCQHAU.js';
4
+ import { assertBrowserSafe, validateConfig, resolveBaseUrl, SDK_VERSION, mapHttpStatusToError } from '../chunk-C5VTRZWX.js';
4
5
  import { NoSuchModelError, APICallError } from '@ai-sdk/provider';
5
6
 
6
7
  function newRequestId(sdkVersion) {
@@ -38,10 +39,20 @@ async function fetchWithTimeout(config, fetchFn, url, init) {
38
39
  config.timeout
39
40
  );
40
41
  try {
41
- return await fetchFn(url, {
42
+ const response = await fetchFn(url, {
42
43
  ...init,
43
44
  signal: controller.signal
44
45
  });
46
+ const hasBody = response.body !== null;
47
+ const buffer = hasBody ? await response.arrayBuffer() : null;
48
+ const headers = new Headers(response.headers);
49
+ headers.delete("content-encoding");
50
+ headers.delete("content-length");
51
+ return new Response(buffer, {
52
+ status: response.status,
53
+ statusText: response.statusText,
54
+ headers
55
+ });
45
56
  } finally {
46
57
  clearTimeout(timeoutId);
47
58
  existingSignal?.removeEventListener("abort", onAbort);
@@ -145,6 +156,9 @@ var BrandappImageModel = class {
145
156
  signal: options.abortSignal
146
157
  }
147
158
  );
159
+ if (!imageResponse.ok) {
160
+ await throwProviderApiError(imageResponse, data.url, body, requestId);
161
+ }
148
162
  const imageBuffer = await imageResponse.arrayBuffer();
149
163
  const base64 = arrayBufferToBase64(new Uint8Array(imageBuffer));
150
164
  return {
@@ -1,6 +1,7 @@
1
- export { ReoptAuthClient, createReoptAuthClient } from '../chunk-PJZB4VP7.js';
2
- import '../chunk-DI6QJPTQ.js';
3
- import '../chunk-J5Y2GSJF.js';
1
+ export { ReoptAuthClient, createReoptAuthClient } from '../chunk-YPLT3RFL.js';
2
+ import '../chunk-YTKSAWV2.js';
3
+ import '../chunk-2LSCQHAU.js';
4
+ import '../chunk-C5VTRZWX.js';
4
5
 
5
6
  // src/auth/session.ts
6
7
  async function getSessionFromCookies(cookieHeader, opts) {
@@ -3,7 +3,7 @@ import { BetterAuthOptions, BetterAuthPlugin } from 'better-auth';
3
3
  import { q as ReoptSDKConfig } from '../config-CtxyJsDR.js';
4
4
  export { R as REOPT_BASE_URLS } from '../config-CtxyJsDR.js';
5
5
  export { A as AdapterOperation, a as AdapterRequestBody, R as REOPT_DEFAULT_SCOPES, b as REOPT_PROVIDER_ID } from '../types-6E3ZLL9X.js';
6
- export { A as AuthError, R as RateLimitError, g as ReoptSDKError, S as ServerError, k as isReoptSDKError } from '../errors-5hd5ZR-M.js';
6
+ export { A as AuthError, R as RateLimitError, g as ReoptSDKError, S as ServerError, l as isReoptSDKError } from '../errors-BjDFIyA6.js';
7
7
 
8
8
  /**
9
9
  * Reopt Better Auth Remote Database Adapter
@@ -1,11 +1,13 @@
1
1
  import { REOPT_PROVIDER_ID, REOPT_DEFAULT_SCOPES } from '../chunk-REIKXSMY.js';
2
2
  export { REOPT_DEFAULT_SCOPES, REOPT_PROVIDER_ID } from '../chunk-REIKXSMY.js';
3
- import { BaseHttpClient } from '../chunk-DI6QJPTQ.js';
4
- import { resolveIdBaseUrl } from '../chunk-J5Y2GSJF.js';
5
- export { AuthError, REOPT_BASE_URLS, RateLimitError, ReoptSDKError, ServerError, isReoptSDKError } from '../chunk-J5Y2GSJF.js';
3
+ import { BaseHttpClient } from '../chunk-YTKSAWV2.js';
4
+ import '../chunk-2LSCQHAU.js';
5
+ import { resolveIdBaseUrl } from '../chunk-C5VTRZWX.js';
6
+ export { AuthError, REOPT_BASE_URLS, RateLimitError, ReoptSDKError, ServerError, isReoptSDKError } from '../chunk-C5VTRZWX.js';
6
7
  import { createAdapterFactory } from 'better-auth/adapters';
7
8
  import { genericOAuth } from 'better-auth/plugins';
8
9
 
10
+ var READ_ONLY = { idempotent: true };
9
11
  function assertServerRuntime() {
10
12
  if (typeof window !== "undefined") {
11
13
  throw new Error(
@@ -19,8 +21,8 @@ function createReoptAdapter(config) {
19
21
  config,
20
22
  `/api/v1/brandapp/${config.brandappId}/auth/adapter`
21
23
  );
22
- async function request(body) {
23
- const json = await http.fetch("POST", "", body);
24
+ async function request(body, options) {
25
+ const json = await http.fetch("POST", "", body, options);
24
26
  return json.data;
25
27
  }
26
28
  return createAdapterFactory({
@@ -43,29 +45,38 @@ function createReoptAdapter(config) {
43
45
  });
44
46
  },
45
47
  async findOne({ model, where, select }) {
46
- return request({
47
- operation: "findOne",
48
- model,
49
- where,
50
- select
51
- });
48
+ return request(
49
+ {
50
+ operation: "findOne",
51
+ model,
52
+ where,
53
+ select
54
+ },
55
+ READ_ONLY
56
+ );
52
57
  },
53
58
  async findMany({ model, where, limit, offset, sortBy }) {
54
- return request({
55
- operation: "findMany",
56
- model,
57
- where,
58
- limit,
59
- offset,
60
- sortBy
61
- });
59
+ return request(
60
+ {
61
+ operation: "findMany",
62
+ model,
63
+ where,
64
+ limit,
65
+ offset,
66
+ sortBy
67
+ },
68
+ READ_ONLY
69
+ );
62
70
  },
63
71
  async count({ model, where }) {
64
- return request({
65
- operation: "count",
66
- model,
67
- where
68
- });
72
+ return request(
73
+ {
74
+ operation: "count",
75
+ model,
76
+ where
77
+ },
78
+ READ_ONLY
79
+ );
69
80
  },
70
81
  async update({ model, where, update }) {
71
82
  return request({
@@ -0,0 +1,21 @@
1
+ // src/core/encoding.ts
2
+ function encodeBase64(str) {
3
+ const bytes = new TextEncoder().encode(str);
4
+ const binString = Array.from(bytes, (b) => String.fromCodePoint(b)).join("");
5
+ return btoa(binString);
6
+ }
7
+ function createBasicAuthHeader(clientId, clientSecret) {
8
+ return `Basic ${encodeBase64(`${clientId}:${clientSecret}`)}`;
9
+ }
10
+ function createAuthHeader(config) {
11
+ const token = config.token?.trim();
12
+ if (token) return `Bearer ${token}`;
13
+ return createBasicAuthHeader(
14
+ config.clientId ?? "",
15
+ config.clientSecret ?? ""
16
+ );
17
+ }
18
+
19
+ export { createAuthHeader };
20
+ //# sourceMappingURL=chunk-2LSCQHAU.js.map
21
+ //# sourceMappingURL=chunk-2LSCQHAU.js.map
@@ -1,5 +1,5 @@
1
- import { buildQuery } from './chunk-6FLYVNZI.js';
2
- import { BaseHttpClient } from './chunk-DI6QJPTQ.js';
1
+ import { buildQuery } from './chunk-PF24XU54.js';
2
+ import { BaseHttpClient } from './chunk-YTKSAWV2.js';
3
3
 
4
4
  // src/eav/cache.ts
5
5
  var SchemaCache = class {
@@ -595,5 +595,5 @@ function createReoptEavClient(config) {
595
595
  }
596
596
 
597
597
  export { createReoptEavClient };
598
- //# sourceMappingURL=chunk-E457LO5A.js.map
599
- //# sourceMappingURL=chunk-E457LO5A.js.map
598
+ //# sourceMappingURL=chunk-4U4ZPPL4.js.map
599
+ //# sourceMappingURL=chunk-4U4ZPPL4.js.map
@@ -1,4 +1,4 @@
1
- import { BaseHttpClient } from './chunk-DI6QJPTQ.js';
1
+ import { BaseHttpClient } from './chunk-YTKSAWV2.js';
2
2
 
3
3
  // src/feedback/client.ts
4
4
  function buildListQuery(query) {
@@ -92,5 +92,5 @@ function createReoptFeedbackClient(config) {
92
92
  }
93
93
 
94
94
  export { ReoptFeedbackClient, createReoptFeedbackClient };
95
- //# sourceMappingURL=chunk-K3YVJE6E.js.map
96
- //# sourceMappingURL=chunk-K3YVJE6E.js.map
95
+ //# sourceMappingURL=chunk-55KHY5GH.js.map
96
+ //# sourceMappingURL=chunk-55KHY5GH.js.map
@@ -25,8 +25,8 @@ var AuthError = class extends ReoptSDKError {
25
25
  }
26
26
  };
27
27
  var RateLimitError = class extends ReoptSDKError {
28
- constructor(message = "Rate limit exceeded", retryAfterMs) {
29
- super(message, 429, "RATE_LIMIT", void 0, {
28
+ constructor(message = "Rate limit exceeded", retryAfterMs, context) {
29
+ super(message, 429, "RATE_LIMIT", context, {
30
30
  cause: "\uBD84\uB2F9/\uC2DC\uAC04\uB2F9 \uC694\uCCAD \uD55C\uB3C4 \uCD08\uACFC",
31
31
  fix: retryAfterMs ? `${Math.ceil(retryAfterMs / 1e3)}\uCD08 \uD6C4 \uC7AC\uC2DC\uB3C4\uD558\uAC70\uB098, BrandApp AI \uC124\uC815\uC5D0\uC11C rateLimit \uC870\uC815` : "\uC694\uCCAD \uAC04\uACA9\uC744 \uB298\uB9AC\uAC70\uB098 BrandApp AI \uC124\uC815\uC5D0\uC11C rateLimit \uC870\uC815",
32
32
  doc: "docs/errors.md#rate_limit"
@@ -35,8 +35,8 @@ var RateLimitError = class extends ReoptSDKError {
35
35
  }
36
36
  };
37
37
  var ServerError = class extends ReoptSDKError {
38
- constructor(message = "Internal server error") {
39
- super(message, 500, "SERVER_ERROR", void 0, {
38
+ constructor(message = "Internal server error", context) {
39
+ super(message, 500, "SERVER_ERROR", context, {
40
40
  cause: "\uC11C\uBC84 \uB0B4\uBD80 \uC624\uB958",
41
41
  fix: "\uC7A0\uC2DC \uD6C4 \uC7AC\uC2DC\uB3C4. \uBC18\uBCF5\uB418\uBA74 \uC11C\uBC84 \uC0C1\uD0DC \uD655\uC778",
42
42
  doc: "docs/errors.md#server_error"
@@ -150,6 +150,21 @@ var LimitExceededError = class extends ReoptSDKError {
150
150
  this.name = "LimitExceededError";
151
151
  }
152
152
  };
153
+ var RequiredTermsError = class extends ReoptSDKError {
154
+ missingTermsIds;
155
+ constructor(message = "\uD544\uC218 \uC57D\uAD00 \uB3D9\uC758\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4", missingTermsIds = [], context) {
156
+ super(message, 422, "REQUIRED_TERMS", context, {
157
+ cause: "\uC774 \uD50C\uB79C \uAD6C\uB3C5 \uC804\uC5D0 \uB3D9\uC758\uD574\uC57C \uD558\uB294 \uD544\uC218 \uC57D\uAD00\uC774 \uB0A8\uC544 \uC788\uC74C",
158
+ fix: "sdk.terms.list()\uB85C \uC57D\uAD00\uC744 \uC870\uD68C\uD558\uACE0 sdk.terms.consent()\uB85C \uB3D9\uC758\uD55C \uB4A4 \uB2E4\uC2DC \uACB0\uC81C\uB97C \uC2DC\uC791",
159
+ doc: "docs/errors.md#required_terms"
160
+ });
161
+ this.name = "RequiredTermsError";
162
+ this.missingTermsIds = missingTermsIds;
163
+ }
164
+ };
165
+ function isRequiredTermsError(error) {
166
+ return error instanceof Error && error.name === "RequiredTermsError" && "missingTermsIds" in error;
167
+ }
153
168
  var ValidationError = class extends ReoptSDKError {
154
169
  fieldErrors;
155
170
  constructor(message, fieldErrors, context) {
@@ -241,6 +256,13 @@ function mapHttpStatusToError(status, code, message, ctx, fieldErrors) {
241
256
  }
242
257
  return new ConflictError(message ?? "Conflict", ctx, code ?? "CONFLICT");
243
258
  case 422:
259
+ if (code === "REQUIRED_TERMS") {
260
+ return new RequiredTermsError(
261
+ message ?? "\uD544\uC218 \uC57D\uAD00 \uB3D9\uC758\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4",
262
+ (fieldErrors ?? []).map((f) => f.field),
263
+ ctx
264
+ );
265
+ }
244
266
  if (fieldErrors && fieldErrors.length > 0) {
245
267
  return new ValidationError(
246
268
  message ?? "Validation failed",
@@ -275,10 +297,14 @@ function mapHttpStatusToError(status, code, message, ctx, fieldErrors) {
275
297
  ctx
276
298
  );
277
299
  case 429:
278
- return new RateLimitError(message ?? "Rate limit exceeded");
300
+ return new RateLimitError(
301
+ message ?? "Rate limit exceeded",
302
+ void 0,
303
+ ctx
304
+ );
279
305
  default:
280
306
  if (status >= 500) {
281
- return new ServerError(message ?? "Internal server error");
307
+ return new ServerError(message ?? "Internal server error", ctx);
282
308
  }
283
309
  return new ReoptSDKError(
284
310
  message ?? `Unexpected status: ${status}`,
@@ -290,7 +316,7 @@ function mapHttpStatusToError(status, code, message, ctx, fieldErrors) {
290
316
  }
291
317
 
292
318
  // src/core/config.ts
293
- var SDK_VERSION = "3.0.0" ;
319
+ var SDK_VERSION = "3.3.0" ;
294
320
  var REOPT_BASE_URLS = {
295
321
  production: "https://brandapp.reopt.ai",
296
322
  development: "https://brand.reopt.de:3443"
@@ -330,8 +356,14 @@ function validateConfig(config) {
330
356
  assertValidUrl(config.baseUrl, "baseUrl", "REOPT_BASE_URL");
331
357
  assertValidUrl(config.idBaseUrl, "idBaseUrl", "REOPT_ID_BASE_URL");
332
358
  }
359
+ function isBrowserLikeRuntime() {
360
+ if (typeof window !== "undefined") return true;
361
+ const g = globalThis;
362
+ if (g.WorkerGlobalScope && g.self instanceof g.WorkerGlobalScope) return true;
363
+ return typeof g.importScripts === "function";
364
+ }
333
365
  function assertBrowserSafe(config) {
334
- if (typeof window !== "undefined" && config.clientSecret) {
366
+ if (isBrowserLikeRuntime() && config.clientSecret) {
335
367
  throw new ReoptSDKError(
336
368
  "[@reopt-ai/brandapp-sdk] clientSecret must not be used in the browser. It is a long-lived admin credential \u2014 exposing it client-side leaks full app access. Construct the SDK on the server with clientId/clientSecret, or for client-side use mint a short-lived token on your server (POST /api/v1/brandapp/{id}/token/mint) and pass it as `{ token }`.",
337
369
  0,
@@ -421,23 +453,6 @@ function deriveIdFromBaseUrl(baseUrl) {
421
453
  }
422
454
  }
423
455
 
424
- // src/core/encoding.ts
425
- function encodeBase64(str) {
426
- const bytes = new TextEncoder().encode(str);
427
- const binString = Array.from(bytes, (b) => String.fromCodePoint(b)).join("");
428
- return btoa(binString);
429
- }
430
- function createBasicAuthHeader(clientId, clientSecret) {
431
- return `Basic ${encodeBase64(`${clientId}:${clientSecret}`)}`;
432
- }
433
- function createAuthHeader(config) {
434
- if (config.token && config.token.length > 0) return `Bearer ${config.token}`;
435
- return createBasicAuthHeader(
436
- config.clientId ?? "",
437
- config.clientSecret ?? ""
438
- );
439
- }
440
-
441
- export { AuthError, AuthUserNotFoundError, AuthUserRecordExistsError, BadRequestError, ConflictError, ContentFilterError, CreditLimitError, DuplicateAuthUserError, ForbiddenError, LimitExceededError, ModelAccessError, ModelNotFoundError, NotFoundError, REOPT_BASE_URLS, RateLimitError, ReoptSDKError, SDK_VERSION, ServerError, ValidationError, assertBrowserSafe, createAuthHeader, isCreditLimitError, isModelAccessError, isReoptSDKError, isValidationError, mapHttpStatusToError, resolveBaseUrl, resolveIdBaseUrl, validateConfig };
442
- //# sourceMappingURL=chunk-J5Y2GSJF.js.map
443
- //# sourceMappingURL=chunk-J5Y2GSJF.js.map
456
+ export { AuthError, AuthUserNotFoundError, AuthUserRecordExistsError, BadRequestError, ConflictError, ContentFilterError, CreditLimitError, DuplicateAuthUserError, ForbiddenError, LimitExceededError, ModelAccessError, ModelNotFoundError, NotFoundError, REOPT_BASE_URLS, RateLimitError, ReoptSDKError, RequiredTermsError, SDK_VERSION, ServerError, ValidationError, assertBrowserSafe, isCreditLimitError, isModelAccessError, isReoptSDKError, isRequiredTermsError, isValidationError, mapHttpStatusToError, resolveBaseUrl, resolveIdBaseUrl, validateConfig };
457
+ //# sourceMappingURL=chunk-C5VTRZWX.js.map
458
+ //# sourceMappingURL=chunk-C5VTRZWX.js.map
@@ -1,7 +1,7 @@
1
1
  import { parseSSEStream } from './chunk-L4DHB36G.js';
2
2
  import { createManagedAbort } from './chunk-F7BXBTZI.js';
3
- import { BaseHttpClient } from './chunk-DI6QJPTQ.js';
4
- import { validateConfig, ReoptSDKError, mapHttpStatusToError, SDK_VERSION } from './chunk-J5Y2GSJF.js';
3
+ import { BaseHttpClient } from './chunk-YTKSAWV2.js';
4
+ import { validateConfig, ReoptSDKError, mapHttpStatusToError, SDK_VERSION } from './chunk-C5VTRZWX.js';
5
5
 
6
6
  // src/ai/client.ts
7
7
  var ReoptAiClient = class {
@@ -346,5 +346,5 @@ function createReoptAiClient(config) {
346
346
  }
347
347
 
348
348
  export { ReoptAiClient, createReoptAiClient };
349
- //# sourceMappingURL=chunk-KU2LN5SE.js.map
350
- //# sourceMappingURL=chunk-KU2LN5SE.js.map
349
+ //# sourceMappingURL=chunk-FJUCWXX3.js.map
350
+ //# sourceMappingURL=chunk-FJUCWXX3.js.map
@@ -1,4 +1,4 @@
1
- import { BaseHttpClient } from './chunk-DI6QJPTQ.js';
1
+ import { BaseHttpClient } from './chunk-YTKSAWV2.js';
2
2
 
3
3
  // src/terms/client.ts
4
4
  function unwrap(body) {
@@ -108,5 +108,5 @@ function createReoptTermsClient(config) {
108
108
  }
109
109
 
110
110
  export { ReoptTermsClient, createReoptTermsClient };
111
- //# sourceMappingURL=chunk-TUKIYH4Q.js.map
112
- //# sourceMappingURL=chunk-TUKIYH4Q.js.map
111
+ //# sourceMappingURL=chunk-H33OTQEN.js.map
112
+ //# sourceMappingURL=chunk-H33OTQEN.js.map