@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,557 @@
1
+ # API Reference
2
+
3
+ ## Entry Points
4
+
5
+ | Import Path | Purpose |
6
+ | ------------------------------------------- | ----------------------------------------------------------------------------------- |
7
+ | `@reopt-ai/brandapp-sdk` | Core SDK, errors, singleton |
8
+ | `@reopt-ai/brandapp-sdk/ai` | AI client (types, ReoptAiClient) |
9
+ | `@reopt-ai/brandapp-sdk/auth` | User-scoped auth + cross-subdomain session helpers |
10
+ | `@reopt-ai/brandapp-sdk/files` | File client + image URL helpers |
11
+ | `@reopt-ai/brandapp-sdk/ai-provider` | Vercel AI SDK LanguageModelV3 provider |
12
+ | `@reopt-ai/brandapp-sdk/eav` | EAV client, types, filter builder |
13
+ | `@reopt-ai/brandapp-sdk/eav/schema` | Schema definition, diff, sync, JSON Schema |
14
+ | `@reopt-ai/brandapp-sdk/eav/coerce` | Value coercion helpers |
15
+ | `@reopt-ai/brandapp-sdk/better-auth` | Better Auth adapter + OAuth (server) |
16
+ | `@reopt-ai/brandapp-sdk/better-auth/client` | OAuth client (browser) |
17
+ | `@reopt-ai/brandapp-sdk/react/hooks` | TanStack Query hooks |
18
+ | `@reopt-ai/brandapp-sdk/webhooks` | Webhook handler (HMAC verify, replay check) |
19
+ | `@reopt-ai/brandapp-sdk/dev` | In-memory dev server (offline development) |
20
+ | `@reopt-ai/brandapp-sdk/testing` | `createTestSDK` for Vitest fixtures |
21
+ | `@reopt-ai/brandapp-sdk/cms` | CMS posts/post-groups/tags (read-only) + SEO / Sitemap / RSS helpers + `EditorSpec` |
22
+ | `@reopt-ai/brandapp-sdk/terms` | Terms list (with `contentRich`), consent, withdraw |
23
+
24
+ ## Core SDK
25
+
26
+ ```typescript
27
+ import { createReoptSDK } from "@reopt-ai/brandapp-sdk";
28
+
29
+ const sdk = createReoptSDK({
30
+ clientId: string; // Required: OAuth Client ID
31
+ clientSecret: string; // Required: OAuth Client Secret
32
+ brandappId: string; // Required: BrandApp UUID
33
+ isProduction?: boolean; // Auto-detect from NODE_ENV
34
+ baseUrl?: string; // Override API URL
35
+ timeout?: number; // Request timeout (ms, default: 15000; AI/Files 30000).
36
+ // For streaming this is an *idle* timeout (max gap
37
+ // between chunks), not a cap on total time.
38
+ maxRetries?: number; // Max TOTAL attempts incl. the first (default: 3 →
39
+ // 1 call + 2 retries; 1 disables retries)
40
+ retryNonIdempotent?: boolean; // Retry POST/PATCH on 5xx/network too
41
+ // (default false; 429 is always retried)
42
+ schema?: SchemaDef; // EAV schema for type safety
43
+ debug?: boolean; // Enable debug logging
44
+ });
45
+
46
+ // Returns: { config, ai, auth, cms, eav, files }
47
+ ```
48
+
49
+ ### Errors
50
+
51
+ All SDK errors extend `ReoptSDKError`. See [`errors.md`](./errors.md) for
52
+ the full reference.
53
+
54
+ ```typescript
55
+ import {
56
+ ReoptSDKError,
57
+ AuthError, // 401
58
+ BadRequestError, // 400
59
+ ForbiddenError, // 403
60
+ NotFoundError, // 404
61
+ ConflictError, // 409
62
+ ValidationError, // 422 — .fieldErrors, .toFieldMap()
63
+ RateLimitError, // 429 (auto-retried)
64
+ ServerError, // 500 (auto-retried)
65
+ isReoptSDKError, // Bundle-safe type guard
66
+ isValidationError,
67
+ } from "@reopt-ai/brandapp-sdk";
68
+ ```
69
+
70
+ ### Per-call `FetchOptions`
71
+
72
+ `BaseHttpClient.fetch()` (used internally by every client) accepts an
73
+ optional fourth argument for per-call cancellation / timeout overrides:
74
+
75
+ ```typescript
76
+ import type { FetchOptions } from "@reopt-ai/brandapp-sdk";
77
+ // type FetchOptions = { signal?: AbortSignal; timeout?: number };
78
+ ```
79
+
80
+ ## AI Client (`sdk.ai`)
81
+
82
+ ```typescript
83
+ // Non-streaming completion
84
+ const result = await sdk.ai.complete({
85
+ messages: ChatMessage[]; // [{ role, content }]
86
+ model?: string; // Default: BrandApp config
87
+ maxTokens?: number;
88
+ temperature?: number;
89
+ customerId?: string; // Usage tracking
90
+ });
91
+ // Returns: { id, model, message, usage, creditsRemaining }
92
+
93
+ // Streaming (text only)
94
+ for await (const chunk of sdk.ai.stream({ messages })) {
95
+ process.stdout.write(chunk);
96
+ }
97
+
98
+ // Streaming (with metadata)
99
+ const { textStream, metadata } = sdk.ai.streamWithMetadata({ messages });
100
+ for await (const chunk of textStream) { ... }
101
+ const meta = await metadata; // { usage, creditsRemaining }
102
+
103
+ // Image generation (auto-saves to Vercel Blob)
104
+ const image = await sdk.ai.generateImage({
105
+ prompt: string; // Image description
106
+ negativePrompt?: string; // What to avoid
107
+ style?: string; // e.g. "watercolor", "photorealistic"
108
+ aspectRatio?: "1:1" | "16:9" | "9:16" | "4:3" | "3:4";
109
+ model?: string; // Default: google/gemini-2.5-flash-image
110
+ customerId?: string;
111
+ });
112
+ // Returns: { id, url, size, contentType, usage: { creditCost }, creditsRemaining }
113
+
114
+ // Credits
115
+ const credits = await sdk.ai.credits();
116
+ // Returns: { balance, limit, percentage, resetAt, status }
117
+
118
+ // Models
119
+ const models = await sdk.ai.models();
120
+ // Returns: [{ id, tier, tierLabel, inputRate, outputRate }]
121
+ ```
122
+
123
+ ## Auth Client (`sdk.auth`)
124
+
125
+ User-scoped endpoints that use the end user's OAuth access token (Bearer auth)
126
+ instead of the app's client credentials (Basic auth). Use these in server
127
+ handlers where you have the token from Better Auth (or your own OAuth flow).
128
+
129
+ ```typescript
130
+ // Link the signed-in user to a Brandapp Customer row (idempotent upsert).
131
+ // First call creates Customer/BrandCustomer/BrandappCustomer/CustomerExternalId;
132
+ // subsequent calls refresh `authorizedAt`.
133
+ const { customerId } = await sdk.auth.linkCurrentUser(accessToken);
134
+
135
+ // Soft-withdraw the current user: BrandappCustomer → churned, consents →
136
+ // withdrawn, Stripe subscription cancelled. Customer row is retained so
137
+ // re-linking later restores the same customerId.
138
+ await sdk.auth.withdrawCurrentUser(accessToken);
139
+
140
+ // Fetch the standard OIDC userinfo claims for the access token.
141
+ const claims = await sdk.auth.getUserInfo(accessToken);
142
+ // Returns: { sub, email?, email_verified?, name?, picture?, given_name?, family_name?, ... }
143
+ ```
144
+
145
+ These are the only SDK methods that accept an `accessToken` argument — every
146
+ other client (`eav`, `ai`, `files`, `cms`) authenticates with the app's
147
+ Basic Auth credentials and operates app-wide.
148
+
149
+ ### Session helpers (1.8+)
150
+
151
+ Cross-subdomain cookie를 받아 reopt id 서버의 Better Auth `/api/auth/get-session`
152
+ 에 위임 검증. 외부 마케팅 사이트(`www.example.com`)가 OAuth 흐름 없이
153
+ 사용자 세션을 인식할 때 사용.
154
+
155
+ ```typescript
156
+ import {
157
+ getSessionFromCookies,
158
+ verifySession,
159
+ type Session,
160
+ } from "@reopt-ai/brandapp-sdk/auth";
161
+
162
+ // Server component
163
+ import { cookies } from "next/headers";
164
+ const cookieHeader = (await cookies())
165
+ .getAll()
166
+ .map((c) => `${c.name}=${c.value}`)
167
+ .join("; ");
168
+ const session = await getSessionFromCookies(cookieHeader, {
169
+ idServerUrl: "https://id.reopt.ai", // Required
170
+ path?: string; // Default "/api/auth/get-session"
171
+ fetch?: typeof fetch; // Override (테스트/SSR proxy)
172
+ });
173
+ // Session | null
174
+
175
+ // Route handler — Request 객체에서 cookie 헤더 자동 추출
176
+ export async function GET(request: Request) {
177
+ const session = await verifySession(request, { idServerUrl: ID });
178
+ if (!session) return new Response("Unauthorized", { status: 401 });
179
+ return Response.json({ user: session.user });
180
+ }
181
+ ```
182
+
183
+ `Session.user = { id, email, name, image, emailVerified? }`,
184
+ `Session.session = { id, expiresAt, userId?, token?, ipAddress?, userAgent? }`.
185
+ 세션이 없거나 id 서버가 응답하지 않으면 `null`. Edge runtime / Node 양쪽 호환.
186
+
187
+ ## File Client (`sdk.files`)
188
+
189
+ ```typescript
190
+ // List files
191
+ const { data: files, meta } = await sdk.files.list({
192
+ page?: number; // Default: 1
193
+ limit?: number; // Default: 20
194
+ contentType?: string; // e.g. "image/*"
195
+ sortBy?: "createdAt" | "name" | "size";
196
+ sortOrder?: "asc" | "desc";
197
+ });
198
+ // Returns: { data: FileInfo[], meta: { page, limit, total } }
199
+
200
+ // Get single file
201
+ const file = await sdk.files.get(fileId);
202
+ // Returns: { id, name, url, size, contentType, pathname, createdAt, updatedAt }
203
+
204
+ // Upload file (multipart FormData)
205
+ const uploaded = await sdk.files.upload(file, {
206
+ name?: string; // Override filename
207
+ contentType?: string; // Override MIME type
208
+ });
209
+ // Accepts: Blob | Uint8Array | File
210
+ // Returns: FileInfo
211
+
212
+ // Delete file
213
+ await sdk.files.delete(fileId);
214
+ // Returns: void
215
+ ```
216
+
217
+ ### Image URL helpers (1.8+)
218
+
219
+ ```typescript
220
+ import {
221
+ optimizeUrl,
222
+ createImageLoader,
223
+ REOPT_IMAGE_REMOTE_PATTERNS,
224
+ type ImageRemotePattern,
225
+ } from "@reopt-ai/brandapp-sdk/files";
226
+
227
+ // width/quality query 추가 (잘못된 URL은 그대로 반환)
228
+ optimizeUrl("https://blob.example/x.png", { width: 800, quality: 80 });
229
+ // → "https://blob.example/x.png?w=800&q=80"
230
+
231
+ // Next.js <Image loader={...}> 호환
232
+ const loader = createImageLoader({ quality: 75 });
233
+ <Image loader={loader} src={url} width={1200} height={630} alt="" />;
234
+
235
+ // next.config.ts remotePatterns 등록
236
+ import type { NextConfig } from "next";
237
+ const config: NextConfig = {
238
+ images: { remotePatterns: REOPT_IMAGE_REMOTE_PATTERNS },
239
+ };
240
+ ```
241
+
242
+ 자세한 사용 패턴은 [`docs/files.md`](./files.md) 참고.
243
+
244
+ ## AI SDK Provider
245
+
246
+ ```typescript
247
+ import { createBrandappProvider } from "@reopt-ai/brandapp-sdk/ai-provider";
248
+ import { generateText, streamText } from "ai";
249
+
250
+ const brandapp = createBrandappProvider({
251
+ clientId, clientSecret, brandappId,
252
+ timeout?: number; // Default: 60000 (AI needs more time)
253
+ customerId?: string;
254
+ fetch?: typeof fetch; // Custom fetch for testing
255
+ });
256
+
257
+ // Use with any AI SDK function
258
+ const { text } = await generateText({ model: brandapp("model-id"), prompt: "..." });
259
+ const result = streamText({ model: brandapp("model-id"), prompt: "..." });
260
+
261
+ // Provider metadata includes BrandApp-specific data
262
+ const { providerMetadata } = await generateText({ ... });
263
+ providerMetadata?.brandapp?.creditCost;
264
+ providerMetadata?.brandapp?.creditsRemaining;
265
+
266
+ // Pass customerId via providerOptions
267
+ await generateText({
268
+ model: brandapp("model-id"),
269
+ providerOptions: { brandapp: { customerId: "..." } },
270
+ });
271
+
272
+ // Image generation via AI SDK
273
+ import { experimental_generateImage } from "ai";
274
+ const { image } = await experimental_generateImage({
275
+ model: brandapp.imageModel("google/gemini-2.5-flash-image"),
276
+ prompt: "A brand banner",
277
+ providerOptions: { brandapp: { style: "minimalist", aspectRatio: "16:9" } },
278
+ });
279
+ ```
280
+
281
+ ### 지원 범위 (정직한 계약)
282
+
283
+ BrandApp AI API는 멀티테넌트 안전을 위해 **텍스트·이미지 표면만** 노출한다.
284
+
285
+ **지원**
286
+
287
+ - `generateText()`, `streamText()` — 텍스트 생성
288
+ - `experimental_generateImage()` — 이미지 생성 (`brandapp.imageModel(...)`)
289
+ - `providerMetadata.brandapp` — `creditCost` / `creditsRemaining` / `responseId`
290
+ - `providerOptions.brandapp` — `customerId` / `style` / `negativePrompt` / `aspectRatio`
291
+ - `finishReason` — 서버가 보고하면 정확히 매핑(미보고 시 `stop`)
292
+
293
+ **미지원** (호출은 동작하되 `warnings`로 알리고 해당 부분은 무시/손실 변환됨)
294
+
295
+ - tool/function calling — `tools`는 경고 후 무시
296
+ - 구조화 출력 — `generateObject()` / `responseFormat: { type: "json" }`는 미지원
297
+ - 비전·파일 입력 — user 메시지의 image/file part는 드롭(경고)
298
+ - `topP` / `topK` / `frequencyPenalty` / `presencePenalty` / `stopSequences` / `seed`
299
+ - 임베딩·음성·전사 모델 — `brandapp.embeddingModel(...)` 등은 `NoSuchModelError`
300
+
301
+ **에러** — provider는 `APICallError`(AI SDK 표준)를 던진다. `error.isRetryable`로 재시도
302
+ 가능 여부(429/5xx)를, `error.data.code` / `error.data.diagnostic`로 `sdk.ai.*`와 **동일한**
303
+ 구조화 진단을, `error.cause`로 typed `ReoptSDKError`(예: `CreditLimitError`)를 얻는다.
304
+
305
+ ## EAV Client (`sdk.eav`)
306
+
307
+ ```typescript
308
+ // Entities
309
+ const entities = await sdk.eav.entities.list();
310
+ const entity = await sdk.eav.entities.get(entityId);
311
+
312
+ // Records
313
+ const { records, total } = await sdk.eav.records.list(entityId, {
314
+ page?: number;
315
+ limit?: number;
316
+ filters?: AttributeFilter[];
317
+ sortBy?: string;
318
+ sortOrder?: "asc" | "desc";
319
+ });
320
+ const record = await sdk.eav.records.get(entityId, recordId);
321
+ const created = await sdk.eav.records.create(entityId, { values: { ... } });
322
+ await sdk.eav.records.update(entityId, recordId, { values: { ... } });
323
+ await sdk.eav.records.delete(entityId, recordId);
324
+
325
+ // Bulk operations
326
+ await sdk.eav.records.bulkCreate(entityId, items);
327
+ await sdk.eav.records.bulkUpdate(entityId, items);
328
+ await sdk.eav.records.bulkDelete(entityId, ids);
329
+
330
+ // Pagination (async generator)
331
+ for await (const record of sdk.eav.records.listAll(entityId)) { ... }
332
+ ```
333
+
334
+ ## Filter Builder
335
+
336
+ ```typescript
337
+ import { where, createFilterBuilder } from "@reopt-ai/brandapp-sdk/eav";
338
+
339
+ // Name-based (simple)
340
+ where("status").eq("active");
341
+ where("age").gte(18);
342
+ where("deletedAt").isNull();
343
+
344
+ // ID-based (type-safe with generated constants)
345
+ const w = createFilterBuilder(ATTRIBUTE_IDS.contacts);
346
+ w("status").eq("active"); // TypeScript validates field names
347
+
348
+ // Operators: eq, neq, contains, gt, lt, gte, lte, isNull, isNotNull, after, before
349
+ ```
350
+
351
+ ## Schema & JSON Schema
352
+
353
+ ```typescript
354
+ import { defineEntity, defineSchema, schemaToJsonSchema } from "@reopt-ai/brandapp-sdk/eav/schema";
355
+
356
+ const contacts = defineEntity({ name: "contacts", attributes: { ... } });
357
+ const schema = defineSchema({ entities: { contacts } });
358
+
359
+ // Export as JSON Schema (for AI structured output, form builders)
360
+ const jsonSchema = schemaToJsonSchema(schema);
361
+ ```
362
+
363
+ ## CMS Client (`sdk.cms`) — read-only
364
+
365
+ 외부 사이트가 reopt 자체 컨텐츠(블로그 포스트·태그·그룹)를 읽는다.
366
+ Write(create/update/delete)는 1.8부터 SDK에서 제거됐고 Reopt Studio가 담당한다.
367
+
368
+ ```typescript
369
+ import type {
370
+ Post, PostDetail, PostGroup, Tag, EditorSpec,
371
+ ListPostsQuery, ListPostGroupsQuery, ListTagsQuery, CmsPaginatedResponse,
372
+ } from "@reopt-ai/brandapp-sdk/cms";
373
+
374
+ // 포스트 목록 — 필터/정렬/페이지네이션
375
+ const { records, page, limit, total, totalPages } = await sdk.cms.posts.list({
376
+ status?: "draft" | "scheduled" | "published" | "archived";
377
+ groupId?: string;
378
+ search?: string; // title/content 부분 검색 (대소문자 무관)
379
+ tags?: string[]; // OR — 태그 텍스트 중 하나라도 매칭
380
+ page?: number; // Default 1
381
+ limit?: number; // Default 20, max 100
382
+ sortBy?: "createdAt" | "updatedAt" | "title" | "publishedAt";
383
+ sortOrder?: "asc" | "desc";
384
+ });
385
+
386
+ // id 단건 — PostDetail (document.contentRich 포함)
387
+ const post = await sdk.cms.posts.get(postId);
388
+
389
+ // slug 단건 — `/blog/[slug]` 라우트에서 id 매핑 없이 사용. (1.8+)
390
+ const post = await sdk.cms.posts.getBySlug("hello-world", { groupId? });
391
+
392
+ // 그룹 목록/단건
393
+ const { records: groups } = await sdk.cms.postGroups.list({ ... });
394
+ const group = await sdk.cms.postGroups.get(groupId);
395
+
396
+ // 태그 목록 — brand 범위 내 사용된 태그 + 사용 건수 (1.8+)
397
+ const tags = await sdk.cms.tags.list({ groupId? });
398
+ // → [{ id, text, postCount }, ...]
399
+ ```
400
+
401
+ ### CMS helpers (1.8+) — SEO / Sitemap / RSS
402
+
403
+ 순수 함수. Next.js / React 의존 없음. cms 응답을 그대로 받아 표준 출력으로 변환.
404
+
405
+ ```typescript
406
+ import {
407
+ toMetadata,
408
+ toSitemapItems,
409
+ toRssFeed,
410
+ type SeoMetadata,
411
+ type SitemapItem,
412
+ } from "@reopt-ai/brandapp-sdk/cms";
413
+
414
+ // Next.js Metadata — title/description/openGraph(article)/twitter/canonical
415
+ import type { Metadata } from "next";
416
+ export async function generateMetadata({ params }): Promise<Metadata> {
417
+ const post = await sdk.cms.posts.getBySlug((await params).slug);
418
+ return toMetadata(post, { siteUrl: "https://www.example.com", basePath?: "/blog" });
419
+ }
420
+
421
+ // app/sitemap.ts — Next.js MetadataRoute.Sitemap
422
+ export default async function sitemap() {
423
+ const { records } = await sdk.cms.posts.list({ status: "published", limit: 200 });
424
+ return toSitemapItems(records, {
425
+ siteUrl: "https://www.example.com",
426
+ basePath?: "/blog", // Default "/blog"
427
+ changeFrequency?: "weekly", // Default "weekly"
428
+ priority?: 0.7, // Default 0.7
429
+ });
430
+ }
431
+
432
+ // /rss.xml — RSS 2.0 XML 문자열
433
+ export async function GET() {
434
+ const { records } = await sdk.cms.posts.list({ status: "published", limit: 50 });
435
+ const xml = toRssFeed(records, {
436
+ siteUrl: "https://www.example.com",
437
+ title: "Example Blog",
438
+ description: "Recent posts.",
439
+ basePath?: "/blog",
440
+ language?: "ko", // Default "ko"
441
+ });
442
+ return new Response(xml, { headers: { "Content-Type": "application/rss+xml" } });
443
+ }
444
+ ```
445
+
446
+ ### `EditorSpec` (1.8+)
447
+
448
+ `PostDetail.document.contentRich`의 타입. opt-editor의 `EditorSpec`과 구조적으로
449
+ 호환되며 SDK는 opt-editor에 의존하지 않는다.
450
+
451
+ ```tsx
452
+ "use client";
453
+ import {
454
+ StaticRenderer,
455
+ type EditorSpec as OptSpec,
456
+ } from "@reopt-ai/opt-editor";
457
+ import type { EditorSpec } from "@reopt-ai/brandapp-sdk/cms";
458
+
459
+ // boundary에서 cast 한 번 (둘 다 같은 shape)
460
+ export function PostBody({ contentRich }: { contentRich: EditorSpec }) {
461
+ return <StaticRenderer spec={contentRich as unknown as OptSpec} />;
462
+ }
463
+ ```
464
+
465
+ 자세한 데모는 [`docs/cms.md`](./cms.md) 또는 `apps/brandapp-playground/app/cms/posts/[slug]` 참고.
466
+
467
+ ## Terms Client (`sdk.terms`)
468
+
469
+ ```typescript
470
+ import type { TermsItem, TermsVersion, ConsentRecord } from "@reopt-ai/brandapp-sdk/terms";
471
+
472
+ // 활성 약관 + 현재 버전 (Basic Auth — 비로그인도 호출 가능)
473
+ const terms = await sdk.terms.list();
474
+ // terms[0].currentVersion: { id, version, content, contentRich, publishedAt, ... }
475
+ // contentRich (1.8+): EditorSpec | null — opt-editor StaticRenderer로 렌더 가능.
476
+ // 기존 plain content는 검색·법적 보존용으로 유지된다.
477
+
478
+ // Bearer 인증 — 사용자 동의 흐름
479
+ const mine = await sdk.terms.listMyConsents(accessToken);
480
+ const { count } = await sdk.terms.consent({ consents: [...] }, accessToken);
481
+ const { id } = await sdk.terms.withdraw(consentId, accessToken);
482
+ ```
483
+
484
+ ## Webhooks
485
+
486
+ ```typescript
487
+ import {
488
+ createWebhookHandler,
489
+ verifySignature,
490
+ DEFAULT_WEBHOOK_TOLERANCE_MS,
491
+ type WebhookPayload,
492
+ type WebhookEventType,
493
+ } from "@reopt-ai/brandapp-sdk/webhooks";
494
+
495
+ export const POST = createWebhookHandler({
496
+ secret: string; // Required: shared webhook secret
497
+ handlers: Partial<Record<WebhookEventType, (payload) => void | Promise<void>>>;
498
+ onError?: (error, payload) => void | Promise<void>;
499
+ toleranceMs?: number; // Default: DEFAULT_WEBHOOK_TOLERANCE_MS (5 min).
500
+ // Pass 0 to disable timestamp replay check.
501
+ });
502
+ // Returns: (req: Request) => Promise<Response>
503
+ // Responses: 200 (ok), 400 (bad json / bad timestamp), 401 (bad/missing signature
504
+ // or timestamp), 410 (timestamp outside tolerance), 500 (handler threw)
505
+
506
+ // Event types (match the platform sender):
507
+ // "contactCreated" | "contactUpdated" | "contactDeleted"
508
+ // | "workflowRunCompleted" | "workflowRunFailed"
509
+ // Payload: { id, type, entityType, entityId, createdAt, data }
510
+
511
+ // Manual signature verification — timestamp first; signs "{timestamp}.{body}",
512
+ // accepts the sha256=-prefixed header value the platform sends.
513
+ const timestamp = request.headers.get("x-reopt-timestamp")!;
514
+ const signature = request.headers.get("x-reopt-signature")!;
515
+ const ok = await verifySignature(timestamp, rawBody, signature, secret);
516
+ ```
517
+
518
+ ## React Hooks
519
+
520
+ ```typescript
521
+ import {
522
+ useAiCredits, useAiModels, useAiCompletion, useAiImageGenerate,
523
+ useEavRecords,
524
+ useFiles, useFile, useUploadFile, useDeleteFile,
525
+ } from "@reopt-ai/brandapp-sdk/react/hooks";
526
+
527
+ // Query hooks (auto-caching)
528
+ const { data: credits } = useAiCredits(sdk);
529
+ const { data: models } = useAiModels(sdk);
530
+ const { data } = useEavRecords(sdk, entityId, { filters: [...] });
531
+
532
+ // Mutation hooks
533
+ const { mutateAsync: complete } = useAiCompletion(sdk);
534
+ const result = await complete({ messages: [{ role: "user", content: "Hello" }] });
535
+
536
+ const { mutateAsync: generateImage } = useAiImageGenerate(sdk);
537
+ const image = await generateImage({ prompt: "A banner", aspectRatio: "16:9" });
538
+
539
+ // File hooks
540
+ const { data: fileList } = useFiles(sdk, { contentType: "image/*" });
541
+ const { data: file } = useFile(sdk, "file-uuid");
542
+
543
+ const { mutateAsync: upload } = useUploadFile(sdk);
544
+ const uploaded = await upload({ file: blob, options: { name: "banner.png" } });
545
+
546
+ const { mutateAsync: deleteFile } = useDeleteFile(sdk);
547
+ await deleteFile("file-uuid");
548
+
549
+ // CMS hooks (read-only) — usePostList / usePost / usePostGroupList /
550
+ // usePostGroup, plus 1.8+ usePostBySlug / useCmsTags
551
+ const { data } = usePostList(sdk, { status: "published" });
552
+ const { data: post } = usePostBySlug(sdk, slug, { groupId? });
553
+ const { data: tags } = useCmsTags(sdk, { groupId? });
554
+ ```
555
+
556
+ > **1.8 변경**: `useCreatePost` / `useUpdatePost` / `useDeletePost`는 cms write
557
+ > 표면 제거에 따라 함께 제거됐다. authoring은 Reopt Studio가 담당한다.