@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,315 @@
1
+ # Migration Guide
2
+
3
+ ## 2.x → 3.0.0
4
+
5
+ 보안 리뷰 후속. **Breaking** — 웹훅 검증 계약과 `verifySignature` 시그니처, 그리고
6
+ 브라우저에서의 `clientSecret` 사용이 바뀐다.
7
+
8
+ ### ⚠️ Breaking — Webhook 검증 계약을 실제 플랫폼 송신부에 정렬
9
+
10
+ **Who is affected**: `createWebhookHandler` / `verifySignature`를 쓰는 모든 consumer.
11
+ 2.x SDK는 raw-body hex 서명 + body 내 timestamp + `record.*` 이벤트 타입을 검증했는데,
12
+ 이는 실제 플랫폼 송신부와 불일치해 **프로덕션 웹훅을 전량 401 거부**했다. 3.0은 송신부와
13
+ 일치한다.
14
+
15
+ - `verifySignature(body, signature, secret)` → `verifySignature(timestamp, body, signature, secret)`.
16
+ 서명 preimage는 `"{timestamp}.{body}"`, 헤더는 `x-reopt-signature: sha256=<hex>` +
17
+ `x-reopt-timestamp: <epoch ms>`.
18
+ - `WebhookEventType`: `record.created|updated|deleted` / `entity.*` /
19
+ `subscription.changed` / `customer.created` → `contactCreated` / `contactUpdated` /
20
+ `contactDeleted` / `workflowRunCompleted` / `workflowRunFailed`.
21
+ - `WebhookPayload`: `{ id, type, brandappId, workspaceId, timestamp, data }` →
22
+ `{ id, type, entityType, entityId, createdAt, data }`.
23
+
24
+ ```ts
25
+ // Before (2.x — 프로덕션 웹훅을 받지 못함)
26
+ createWebhookHandler({ secret, handlers: { "record.created": fn } });
27
+ const ok = await verifySignature(body, sigHeader, secret);
28
+
29
+ // After (3.0)
30
+ createWebhookHandler({ secret, handlers: { contactCreated: fn } });
31
+ const ts = req.headers.get("x-reopt-timestamp")!;
32
+ const sig = req.headers.get("x-reopt-signature")!;
33
+ const ok = await verifySignature(ts, body, sig, secret);
34
+ ```
35
+
36
+ ### ⚠️ Breaking — 브라우저에서 `clientSecret` 사용 차단
37
+
38
+ **Who is affected**: 클라이언트 컴포넌트에서 `createReoptSDK`/`createBrandappProvider`를
39
+ `clientSecret`(예: `NEXT_PUBLIC_BRANDAPP_CLIENT_SECRET`)로 생성하던 코드 — 이제
40
+ `CONFIG_BROWSER_SECRET`로 throw한다(장기 admin 자격 유출 방지).
41
+
42
+ - **마이그레이션**: 서버에서 단기 스코프 토큰을 발급
43
+ (`POST /api/v1/brandapp/{id}/token/mint`)해 클라이언트로 내려보내고,
44
+ `createReoptSDK({ brandappId, token })`로 생성한다(`clientSecret` 없이). `token` 제공 시
45
+ `clientId`/`clientSecret`는 선택사항(가법 변경).
46
+ - 서버 측에서 `clientId`+`clientSecret`로 생성하던 코드는 변경 불필요.
47
+
48
+ ### Removed — deprecated 별칭 제거
49
+
50
+ 오래전 `@deprecated`였던 타입/에러 별칭을 제거했다(이름만 바꾸면 됨):
51
+
52
+ - `ReoptAdapterConfig` / `ReoptEavConfig` → `ReoptSDKConfig`
53
+ - `ReoptAdapterError` → `ReoptSDKError`
54
+
55
+ ## 1.8.x → 1.9.0
56
+
57
+ Non-breaking. 기존 코드는 변경 없이 동작한다. 새로 추가된 EAV 전용 에러 클래스를
58
+ 사용하고 싶다면 import만 추가하면 된다.
59
+
60
+ ```ts
61
+ // 1.8.x — 일반 ConflictError 분기
62
+ try {
63
+ await sdk.eav.records.create(entityId, { authUserId, values });
64
+ } catch (err) {
65
+ if (err instanceof ConflictError && err.code === "AUTH_USER_RECORD_EXISTS") {
66
+ return sdk.eav.records.upsert(entityId, { authUserId, filters, values });
67
+ }
68
+ throw err;
69
+ }
70
+
71
+ // 1.9.0 — narrowed 클래스로 한 줄 분기 (위 코드도 그대로 동작)
72
+ import { AuthUserRecordExistsError } from "@reopt-ai/brandapp-sdk/eav";
73
+
74
+ try {
75
+ await sdk.eav.records.create(entityId, { authUserId, values });
76
+ } catch (err) {
77
+ if (err instanceof AuthUserRecordExistsError) {
78
+ return sdk.eav.records.upsert(entityId, { authUserId, filters, values });
79
+ }
80
+ throw err;
81
+ }
82
+ ```
83
+
84
+ 같은 패턴으로 `DuplicateAuthUserError` / `AuthUserNotFoundError` /
85
+ `LimitExceededError`도 사용 가능. 전체 코드 카탈로그는
86
+ [`docs/errors.md`](./errors.md) 참고.
87
+
88
+ 서버 측 변경 (`REQUEST_ERROR` → 세분화된 코드)은 SDK가 자동으로 흡수한다.
89
+ `e.code === 'REQUEST_ERROR'`에 의존하던 1.8.x 코드는 같은 status에서 새 코드를
90
+ 받게 되므로, 분기 조건을 `e.code === 'LIMIT_EXCEEDED_RECORDS'` 등으로 바꾸거나
91
+ `instanceof LimitExceededError`로 옮기면 된다.
92
+
93
+ ## 1.7.x → 1.8.0
94
+
95
+ `1.8`은 외부 마케팅 사이트(블로그·약관·sitemap·세션)를 SDK만으로 운영할 수 있게
96
+ 하는 read-only 표면을 묶었다. 한 가지 ⚠️ **breaking** 변경이 있고 나머지는 모두
97
+ 가법 추가다.
98
+
99
+ ### ⚠️ Breaking — CMS write 표면 제거
100
+
101
+ 다음 메서드와 입력 타입, React 훅이 **제거**됐다.
102
+
103
+ | 1.7.x | 1.8 |
104
+ | ----------------------------------------------- | ------------------------ |
105
+ | `sdk.cms.posts.create` | (없음 — Studio에서 작성) |
106
+ | `sdk.cms.posts.update` | (없음) |
107
+ | `sdk.cms.posts.delete` | (없음) |
108
+ | `sdk.cms.postGroups.create / update / delete` | (없음) |
109
+ | `CreatePostInput / UpdatePostInput` | (없음) |
110
+ | `CreatePostGroupInput / UpdatePostGroupInput` | (없음) |
111
+ | `useCreatePost / useUpdatePost / useDeletePost` | (없음) |
112
+
113
+ 1.7.x에서도 production 백엔드는 해당 endpoint를 노출하지 않았고 dev 서버에서만
114
+ 동작했기 때문에 사실상 dead surface였다. write가 필요한 시나리오라면:
115
+
116
+ 1. **Reopt Studio**에서 컨텐츠를 작성한다 (의도된 새 워크플로우).
117
+ 2. 또는 1.7.x에 `package.json` `dependencies`를 핀 고정한 뒤 점진 이전.
118
+
119
+ ### Added (가법)
120
+
121
+ #### 신규 메서드 / 함수
122
+
123
+ ```typescript
124
+ // cms (1.8+)
125
+ sdk.cms.posts.getBySlug(slug, opts?: { groupId? }): Promise<PostDetail>
126
+ sdk.cms.tags.list(query?: { groupId? }): Promise<Tag[]>
127
+
128
+ // cms helpers — Next.js와 결합 (순수 함수, React/Next 의존 없음)
129
+ import { toMetadata, toSitemapItems, toRssFeed } from "@reopt-ai/brandapp-sdk/cms";
130
+
131
+ // auth helpers — cross-subdomain 세션 검증
132
+ import { getSessionFromCookies, verifySession } from "@reopt-ai/brandapp-sdk/auth";
133
+
134
+ // files helpers — Next.js Image 결합
135
+ import {
136
+ optimizeUrl,
137
+ createImageLoader,
138
+ REOPT_IMAGE_REMOTE_PATTERNS,
139
+ } from "@reopt-ai/brandapp-sdk/files";
140
+
141
+ // React hooks (1.8+)
142
+ import { usePostBySlug, useCmsTags } from "@reopt-ai/brandapp-sdk/react/hooks";
143
+ ```
144
+
145
+ #### 신규 타입 / 필드
146
+
147
+ | 위치 | 변경 |
148
+ | --------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------- |
149
+ | `Post` | `seo: { metaTitle, metaDescription, metaKeywords }` 추가 |
150
+ | `PostDetail.document.contentRich` | `unknown` → `EditorSpec` (opt-editor 호환) |
151
+ | `TermsVersion.contentRich` | 신규 — `EditorSpec | null`. plain `content`는 검색·법적 보존용으로 유지 |
152
+ | `cms` export | `EditorSpec`, `Tag`, `ListTagsQuery`, `PostSeo`, `SeoMetadata`, `SitemapItem`, helpers |
153
+ | `auth` export | `Session`, `GetSessionOptions` |
154
+ | `files` export | `ImageLoaderArgs`, `ImageRemotePattern`, `OptimizeUrlOptions` |
155
+
156
+ ### 권장 마이그레이션 단계
157
+
158
+ 1. `cms.posts.{create,update,delete}` 호출이 있으면 모두 제거하고 Studio로 이전.
159
+ 2. `/blog/[slug]` 라우트가 있으면 `getBySlug`로 단순화 + `generateMetadata`에 `toMetadata` 사용.
160
+ 3. `app/sitemap.ts`와 `/rss.xml`을 `toSitemapItems` / `toRssFeed`로 한 줄 변환.
161
+ 4. `next.config.ts`의 `images.remotePatterns`에 `REOPT_IMAGE_REMOTE_PATTERNS` 추가.
162
+ 5. cross-subdomain 세션 인식이 필요하면 `getSessionFromCookies`로 OAuth 흐름 제거.
163
+ 6. 약관 페이지가 있으면 `currentVersion.contentRich`를 opt-editor `StaticRenderer`로 렌더 (없으면 plain `content` fallback).
164
+
165
+ ### Removed (정리)
166
+
167
+ `webhook.post.published / post.updated / post.deleted` 이벤트 타입은 1.7 어떤
168
+ 버전에서도 production 백엔드 dispatcher가 없었기 때문에 1.8에서는 노출하지
169
+ 않는다. `record.* / entity.* / subscription.changed / customer.created` 6종은 그대로.
170
+
171
+ ---
172
+
173
+ ## 1.5.x → 1.6.0
174
+
175
+ `1.6.0` is mostly additive but introduces three behavior changes worth
176
+ reviewing. Each section includes a before/after snippet.
177
+
178
+ ---
179
+
180
+ ### 1. HTTP 400 / 403 / 404 / 409 now throw dedicated error classes
181
+
182
+ **Who is affected**: Code that branches on `err.code === "REQUEST_ERROR"` to
183
+ distinguish these four client errors.
184
+
185
+ Previously every 4xx (other than 401 / 422 / 429) surfaced as a generic
186
+ `ReoptSDKError` with `code: "REQUEST_ERROR"`. As of `1.6.0` the SDK throws
187
+ one of four new dedicated classes:
188
+
189
+ | Status | Class | Code |
190
+ | ------ | ----------------- | ------------- |
191
+ | 400 | `BadRequestError` | `BAD_REQUEST` |
192
+ | 403 | `ForbiddenError` | `FORBIDDEN` |
193
+ | 404 | `NotFoundError` | `NOT_FOUND` |
194
+ | 409 | `ConflictError` | `CONFLICT` |
195
+
196
+ All four extend `ReoptSDKError`, so `instanceof ReoptSDKError` and
197
+ `isReoptSDKError(err)` keep working without changes.
198
+
199
+ ```ts
200
+ // ❌ 1.5.x — no longer matches 400/403/404/409
201
+ if (isReoptSDKError(err) && err.code === "REQUEST_ERROR") { ... }
202
+
203
+ // ✅ 1.6.0 — handle each case explicitly
204
+ import {
205
+ BadRequestError, ForbiddenError, NotFoundError, ConflictError,
206
+ } from "@reopt-ai/brandapp-sdk";
207
+
208
+ if (err instanceof NotFoundError) { /* 404 */ }
209
+ else if (err instanceof ForbiddenError) { /* 403 */ }
210
+ else if (err instanceof ConflictError) { /* 409 */ }
211
+ else if (err instanceof BadRequestError){ /* 400 */ }
212
+ ```
213
+
214
+ Or, if you just want "anything 4xx from the SDK":
215
+
216
+ ```ts
217
+ if (isReoptSDKError(err) && err.status >= 400 && err.status < 500) { ... }
218
+ ```
219
+
220
+ ---
221
+
222
+ ### 2. Webhook handler now requires a valid timestamp by default
223
+
224
+ **Who is affected**: Anyone sending webhooks with no `timestamp` field, or
225
+ with a timestamp format the SDK can't parse (anything other than an ISO
226
+ string or a number of epoch milliseconds).
227
+
228
+ `createWebhookHandler()` now enforces a 5-minute replay window by default.
229
+ Payloads with a missing / malformed timestamp return **400**; payloads
230
+ outside the window return **410**.
231
+
232
+ ```ts
233
+ // Previous behavior: always pass (no replay protection)
234
+ // 1.6.0 default: require timestamp within ±5 minutes
235
+
236
+ // ✅ Keep the new default (recommended)
237
+ createWebhookHandler({ secret, handlers });
238
+
239
+ // ✅ Customize the window
240
+ createWebhookHandler({ secret, handlers, toleranceMs: 10 * 60_000 });
241
+
242
+ // ✅ Opt out entirely (not recommended for production)
243
+ createWebhookHandler({ secret, handlers, toleranceMs: 0 });
244
+ ```
245
+
246
+ The exported constant `DEFAULT_WEBHOOK_TOLERANCE_MS` is available if you
247
+ want to reference it in your own config.
248
+
249
+ ---
250
+
251
+ ### 3. SSE parser preserves whitespace in streaming data
252
+
253
+ **Who is affected**: Anyone consuming `sdk.ai.stream()` /
254
+ `sdk.ai.streamWithMetadata()` or the Vercel AI SDK provider — unlikely to
255
+ need code changes, but the output is _visibly_ different.
256
+
257
+ Previously every SSE `data:` value was trimmed of leading and trailing
258
+ whitespace, which dropped the leading space in deltas like `" world"` and
259
+ produced `"Helloworld"`. `1.6.0` follows the SSE spec: exactly one
260
+ optional space after the colon is consumed, everything else is preserved.
261
+
262
+ **Expect correctly-spaced output going forward.** If you were manually
263
+ adding spaces between chunks as a workaround, remove that logic.
264
+
265
+ ---
266
+
267
+ ### 4. Dev server: direct HTTP consumers may need shape updates
268
+
269
+ **Who is affected**: Only projects that use the in-memory dev server
270
+ (`@reopt-ai/brandapp-sdk/dev`) and call its routes directly with
271
+ `fetch()` — _not_ projects that go through the SDK, which is the
272
+ supported path. The SDK-mediated call paths are unchanged.
273
+
274
+ The dev server's AI routes previously returned shapes that did not match
275
+ the real production API. They now match, which means direct `fetch()`
276
+ consumers need updates:
277
+
278
+ ```ts
279
+ // ❌ 1.5.x
280
+ const res = await fetch(`${dev.url}/.../ai/chat/completions`, ...);
281
+ const { data } = await res.json();
282
+ data.content; // string
283
+
284
+ // ✅ 1.6.0 (matches CompletionResult)
285
+ data.message.content; // string
286
+ data.message.role; // "assistant"
287
+ data.id; // string
288
+ data.creditsRemaining; // number
289
+
290
+ // Credits: { total, used, remaining } → { balance, limit, percentage, status, resetAt }
291
+ // SSE: `data: {"type":"text-delta",...}` → `event: text-delta\ndata: <text>`
292
+ ```
293
+
294
+ Using `sdk.ai.*` against the dev server requires no changes.
295
+
296
+ The dev server also now **rejects requests targeting a different
297
+ `brandappId` than it was configured for** (404 with a structured error).
298
+ Create a separate dev server instance per `brandappId` if you need
299
+ multi-tenant tests.
300
+
301
+ ---
302
+
303
+ ## Minor / non-breaking additions
304
+
305
+ These are opt-in — no action required to stay on `1.5.x` behavior.
306
+
307
+ - `sdk.eav.*`, `sdk.ai.*`, etc. now accept a fourth `options` arg on the
308
+ low-level `BaseHttpClient.fetch()` for per-call timeout / abort.
309
+ - `createReoptAdapter()` and `createReoptOAuth()` now throw at construction
310
+ time if somehow invoked in a browser (safety check; server-only code
311
+ stays server-only).
312
+ - `InMemoryStore.toSnapshot()` returns a deep copy — mutating the snapshot
313
+ no longer affects the store.
314
+ - EAV `bulkCreate` / `bulkUpdate` / `bulkDelete` validate the 100-record
315
+ cap client-side before hitting the server.
@@ -0,0 +1,163 @@
1
+ # Testing Guide
2
+
3
+ BrandApp SDK의 테스트 유틸리티를 사용하면 격리된 환경에서 SDK 통합 테스트를 실행할 수 있습니다.
4
+
5
+ ## 설치
6
+
7
+ ```bash
8
+ npm install @reopt-ai/brandapp-sdk hono vitest
9
+ ```
10
+
11
+ ## `createTestSDK`
12
+
13
+ 테스트 스위트별 독립 서버 + SDK 인스턴스를 생성합니다.
14
+
15
+ ```typescript
16
+ import { describe, it, expect, beforeEach, afterAll } from "vitest";
17
+ import { createTestSDK } from "@reopt-ai/brandapp-sdk/testing";
18
+
19
+ const schema = {
20
+ entities: {
21
+ contacts: {
22
+ name: "contacts",
23
+ attributes: {
24
+ name: { label: "Name", dataType: "text", isRequired: true },
25
+ email: { label: "Email", dataType: "text", isUnique: true },
26
+ },
27
+ },
28
+ },
29
+ };
30
+
31
+ describe("contacts", () => {
32
+ const testCtx = await createTestSDK({ schema });
33
+
34
+ beforeEach(async () => {
35
+ // resetAll: 서버 데이터 초기화 + SDK 캐시 클리어
36
+ await testCtx.resetAll();
37
+ });
38
+
39
+ afterAll(async () => {
40
+ await testCtx.devServer.close();
41
+ });
42
+
43
+ it("creates a contact", async () => {
44
+ const entities = await testCtx.sdk.eav.entities.list();
45
+ const contacts = entities.find((e) => e.name === "contacts");
46
+
47
+ const record = await testCtx.sdk.eav.records.create(contacts.id, {
48
+ values: { name: "Alice", email: "alice@test.com" },
49
+ });
50
+
51
+ expect(record.values.name).toBe("Alice");
52
+ });
53
+ });
54
+ ```
55
+
56
+ ## `createTestServer`
57
+
58
+ SDK 없이 서버만 생성합니다. SDK 설정을 직접 제어할 때 사용합니다.
59
+
60
+ ```typescript
61
+ import { createTestServer } from "@reopt-ai/brandapp-sdk/testing";
62
+ import { createReoptSDK } from "@reopt-ai/brandapp-sdk";
63
+
64
+ const { devServer, sdkConfig } = await createTestServer({ schema });
65
+ const sdk = createReoptSDK({ ...sdkConfig, debug: true });
66
+
67
+ // ...tests...
68
+
69
+ await devServer.close();
70
+ ```
71
+
72
+ ## `createFixture`
73
+
74
+ 반복적인 테스트 데이터를 팩토리 패턴으로 생성합니다.
75
+
76
+ ```typescript
77
+ import { createFixture } from "@reopt-ai/brandapp-sdk/testing";
78
+
79
+ const fixture = createFixture({
80
+ contact: (overrides) => ({
81
+ values: {
82
+ name: "Default Name",
83
+ email: "default@test.com",
84
+ status: "active",
85
+ ...overrides,
86
+ },
87
+ }),
88
+ order: (overrides) => ({
89
+ values: {
90
+ product: "Widget",
91
+ amount: 100,
92
+ ...overrides,
93
+ },
94
+ }),
95
+ });
96
+
97
+ // 기본값 사용
98
+ const defaultContact = fixture.contact();
99
+
100
+ // 커스텀 값 오버라이드
101
+ const customContact = fixture.contact({
102
+ name: "Alice",
103
+ email: "alice@test.com",
104
+ });
105
+ ```
106
+
107
+ ## 시드 데이터
108
+
109
+ ```typescript
110
+ await testCtx.devServer.seed({
111
+ contacts: [
112
+ fixture.contact(),
113
+ fixture.contact({ name: "Alice" }),
114
+ fixture.contact({ name: "Bob", status: "inactive" }),
115
+ ],
116
+ });
117
+ ```
118
+
119
+ ## 초기 시드
120
+
121
+ `createTestSDK`에 초기 시드를 전달할 수 있습니다:
122
+
123
+ ```typescript
124
+ const testCtx = await createTestSDK({
125
+ schema,
126
+ seed: {
127
+ contacts: [{ values: { name: "Preset User", email: "preset@test.com" } }],
128
+ },
129
+ });
130
+ ```
131
+
132
+ ## 격리
133
+
134
+ 각 `createTestSDK`/`createTestServer` 호출은 독립된 포트에서 서버를 시작합니다. 병렬 테스트 실행 시에도 데이터 충돌이 없습니다.
135
+
136
+ ```typescript
137
+ const test1 = await createTestSDK({ schema });
138
+ const test2 = await createTestSDK({ schema });
139
+
140
+ // test1.url !== test2.url (서로 다른 포트)
141
+ // test1의 데이터 변경은 test2에 영향 없음
142
+ ```
143
+
144
+ ## 스냅샷/복원
145
+
146
+ 복잡한 테스트 시나리오에서 상태를 저장/복원합니다:
147
+
148
+ ```typescript
149
+ // 복잡한 상태 구축 후 저장
150
+ await testCtx.devServer.snapshot("/tmp/test-baseline.json");
151
+
152
+ // 테스트 실행 후 원래 상태로 복원
153
+ await testCtx.devServer.restore("/tmp/test-baseline.json");
154
+ ```
155
+
156
+ ## `resetAll` vs `devServer.reset`
157
+
158
+ | 메서드 | 서버 데이터 | SDK 캐시 |
159
+ | ------------------- | ----------- | --------------------------------- |
160
+ | `devServer.reset()` | 초기화 | 유지 (오래된 entity ID 참조 가능) |
161
+ | `resetAll()` | 초기화 | 클리어 (새 SDK 인스턴스 생성) |
162
+
163
+ **`beforeEach`에서는 항상 `resetAll()`을 사용하세요.** `devServer.reset()`은 entity를 재생성하므로 ID가 변경되지만, SDK의 내부 캐시가 이전 ID를 참조할 수 있습니다.
package/package.json ADDED
@@ -0,0 +1,173 @@
1
+ {
2
+ "name": "@reopt-ai/brandapp-sdk",
3
+ "version": "3.0.0",
4
+ "description": "Reopt Brandapp SDK — Better Auth adapter, OAuth login, and EAV client",
5
+ "author": "Reopt",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ },
16
+ "./ai": {
17
+ "types": "./dist/ai/index.d.ts",
18
+ "import": "./dist/ai/index.js"
19
+ },
20
+ "./ai-provider": {
21
+ "types": "./dist/ai-provider/index.d.ts",
22
+ "import": "./dist/ai-provider/index.js"
23
+ },
24
+ "./auth": {
25
+ "types": "./dist/auth/index.d.ts",
26
+ "import": "./dist/auth/index.js"
27
+ },
28
+ "./better-auth": {
29
+ "types": "./dist/better-auth/index.d.ts",
30
+ "import": "./dist/better-auth/index.js"
31
+ },
32
+ "./better-auth/client": {
33
+ "types": "./dist/better-auth/client.d.ts",
34
+ "import": "./dist/better-auth/client.js"
35
+ },
36
+ "./cms": {
37
+ "types": "./dist/cms/index.d.ts",
38
+ "import": "./dist/cms/index.js"
39
+ },
40
+ "./eav": {
41
+ "types": "./dist/eav/index.d.ts",
42
+ "import": "./dist/eav/index.js"
43
+ },
44
+ "./eav/schema": {
45
+ "types": "./dist/eav/schema.d.ts",
46
+ "import": "./dist/eav/schema.js"
47
+ },
48
+ "./eav/coerce": {
49
+ "types": "./dist/eav/coerce.d.ts",
50
+ "import": "./dist/eav/coerce.js"
51
+ },
52
+ "./eav/migrate": {
53
+ "types": "./dist/eav/migrate.d.ts",
54
+ "import": "./dist/eav/migrate.js"
55
+ },
56
+ "./feedback": {
57
+ "types": "./dist/feedback/index.d.ts",
58
+ "import": "./dist/feedback/index.js"
59
+ },
60
+ "./files": {
61
+ "types": "./dist/files/index.d.ts",
62
+ "import": "./dist/files/index.js"
63
+ },
64
+ "./plans": {
65
+ "types": "./dist/plans/index.d.ts",
66
+ "import": "./dist/plans/index.js"
67
+ },
68
+ "./push": {
69
+ "types": "./dist/push/index.d.ts",
70
+ "import": "./dist/push/index.js"
71
+ },
72
+ "./react/hooks": {
73
+ "types": "./dist/react/hooks.d.ts",
74
+ "import": "./dist/react/hooks.js"
75
+ },
76
+ "./terms": {
77
+ "types": "./dist/terms/index.d.ts",
78
+ "import": "./dist/terms/index.js"
79
+ },
80
+ "./webhooks": {
81
+ "types": "./dist/webhooks/index.d.ts",
82
+ "import": "./dist/webhooks/index.js"
83
+ },
84
+ "./dev": {
85
+ "types": "./dist/dev/index.d.ts",
86
+ "import": "./dist/dev/index.js"
87
+ },
88
+ "./testing": {
89
+ "types": "./dist/testing/index.d.ts",
90
+ "import": "./dist/testing/index.js"
91
+ }
92
+ },
93
+ "files": [
94
+ "dist",
95
+ "!dist/**/*.map",
96
+ "docs",
97
+ "LICENSE",
98
+ "README.md",
99
+ "CHANGELOG.md"
100
+ ],
101
+ "sideEffects": false,
102
+ "publishConfig": {
103
+ "access": "public",
104
+ "registry": "https://registry.npmjs.org"
105
+ },
106
+ "peerDependencies": {
107
+ "@ai-sdk/provider": ">=4.0.0",
108
+ "@reopt-ai/opt-editor": ">=1.0.0",
109
+ "@tanstack/react-query": ">=5.0.0",
110
+ "better-auth": "^1.6.0",
111
+ "hono": ">=4.0.0",
112
+ "react": ">=18.0.0"
113
+ },
114
+ "peerDependenciesMeta": {
115
+ "@ai-sdk/provider": {
116
+ "optional": true
117
+ },
118
+ "@reopt-ai/opt-editor": {
119
+ "optional": true
120
+ },
121
+ "better-auth": {
122
+ "optional": true
123
+ },
124
+ "hono": {
125
+ "optional": true
126
+ },
127
+ "@tanstack/react-query": {
128
+ "optional": true
129
+ },
130
+ "react": {
131
+ "optional": true
132
+ }
133
+ },
134
+ "devDependencies": {
135
+ "@ai-sdk/provider": "4.0.0",
136
+ "@reopt-ai/opt-editor": "1.1.2",
137
+ "@testing-library/react": "^16.3.2",
138
+ "better-auth": "^1.4.0",
139
+ "happy-dom": "^20.8.9",
140
+ "hono": "^4.7.0",
141
+ "tsup": "^8.0.0",
142
+ "typescript": "5.9.2",
143
+ "vitest": "^4.1.2",
144
+ "@reopt/typescript-config": "0.0.0"
145
+ },
146
+ "keywords": [
147
+ "reopt",
148
+ "brandapp",
149
+ "sdk",
150
+ "better-auth",
151
+ "auth",
152
+ "adapter",
153
+ "oauth",
154
+ "eav",
155
+ "typescript"
156
+ ],
157
+ "repository": {
158
+ "type": "git",
159
+ "url": "https://github.com/reopt-ai/reopt",
160
+ "directory": "packages/brandapp-sdk"
161
+ },
162
+ "engines": {
163
+ "node": ">=18"
164
+ },
165
+ "scripts": {
166
+ "build": "tsup",
167
+ "dev": "tsup --watch",
168
+ "type-check": "tsc --noEmit",
169
+ "test": "vitest run",
170
+ "test:critical": "vitest run __tests__/eav-client.test.ts __tests__/http-client.test.ts",
171
+ "clean": "rm -rf dist"
172
+ }
173
+ }