@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
package/docs/errors.md ADDED
@@ -0,0 +1,290 @@
1
+ # Error Code Reference
2
+
3
+ All SDK errors extend `ReoptSDKError` and include a `.diagnostic` property with structured debugging info.
4
+
5
+ ## Error Types
6
+
7
+ ### General
8
+
9
+ | Error Class | Status | Code | When |
10
+ | -------------------- | ------ | --------------------- | ---------------------------------------- |
11
+ | `AuthError` | 401 | `AUTH_ERROR` | Invalid clientId/clientSecret |
12
+ | `BadRequestError` | 400 | `BAD_REQUEST` | Malformed request (body / params) |
13
+ | `ForbiddenError` | 403 | `FORBIDDEN` | No permission for the resource |
14
+ | `NotFoundError` | 404 | `NOT_FOUND` | Resource does not exist (or was deleted) |
15
+ | `ConflictError` | 409 | `CONFLICT` | State conflict (duplicate key, race) |
16
+ | `ValidationError` | 422 | `VALIDATION_ERROR` | Field-level validation failure |
17
+ | `RateLimitError` | 429 | `RATE_LIMIT` | Too many requests |
18
+ | `CreditLimitError` | 402 | `CREDIT_LIMIT` | AI credit balance exhausted |
19
+ | `ModelAccessError` | 403 | `MODEL_ACCESS_DENIED` | Model not available for this plan tier |
20
+ | `ModelNotFoundError` | 404 | `MODEL_NOT_FOUND` | Unknown model id (typo / retired) |
21
+ | `ContentFilterError` | 422 | `CONTENT_FILTER` | Blocked by moderation policy |
22
+ | `ServerError` | 500 | `SERVER_ERROR` | Internal server error |
23
+ | `ReoptSDKError` | varies | varies | Base class (other / future API errors) |
24
+
25
+ > Every subclass sets `error.name` to its own class name (e.g. `"AuthError"`,
26
+ > `"RateLimitError"`, `"CreditLimitError"`) so log aggregation / Sentry grouping
27
+ > can distinguish them. `instanceof`, `.code`, and `.status` work as before.
28
+
29
+ ### EAV-specific (1.9+)
30
+
31
+ These extend the general classes above so existing `instanceof ConflictError` /
32
+ `instanceof BadRequestError` checks keep working — narrower classes just give
33
+ you a more direct branch when you care about the specific case.
34
+
35
+ | Error Class | Extends | Status | Code | When |
36
+ | --------------------------- | --------------- | ------- | ------------------------- | ----------------------------------------------------------- |
37
+ | `AuthUserRecordExistsError` | `ConflictError` | 409 | `AUTH_USER_RECORD_EXISTS` | 1:1 메타 entity에 같은 user의 record가 이미 있음 (→ upsert) |
38
+ | `DuplicateAuthUserError` | `ConflictError` | 409 | `DUPLICATE_AUTH_USER` | bulk create 입력에 같은 authUserId가 중복 |
39
+ | `AuthUserNotFoundError` | `ReoptSDKError` | 400/422 | `AUTH_USER_NOT_FOUND` | 참조한 authUserId가 이 brandapp에 없음 |
40
+ | `LimitExceededError` | `ReoptSDKError` | 422 | `LIMIT_EXCEEDED_*` | EAV 자원 한도 초과 (entity/attribute/record) |
41
+
42
+ 추가 EAV 코드 (전용 클래스 없이 일반 클래스 + `.code`로 분기):
43
+
44
+ | Code | Status | Class | Notes |
45
+ | ----------------------- | ------ | ----------------- | ---------------------------------------------------------- |
46
+ | `ENTITY_NOT_FOUND` | 404 | `NotFoundError` | URL의 entityId가 이 brandapp 소속이 아님 |
47
+ | `ATTRIBUTE_NOT_FOUND` | 404 | `NotFoundError` | URL의 attributeId가 entity 소속이 아님 |
48
+ | `RECORD_NOT_FOUND` | 404 | `NotFoundError` | URL의 recordId가 entity 소속이 아님 |
49
+ | `USER_NOT_FOUND` | 404 | `NotFoundError` | `/users/:authUserId/records` 경로의 user가 brandapp에 없음 |
50
+ | `RECORDS_NOT_FOUND` | 400 | `BadRequestError` | bulkUpdate에서 일부 record id가 entity에 없음 |
51
+ | `DUPLICATE_RECORD_ID` | 409 | `ConflictError` | bulkUpdate(brandappAuthUser) 입력에 같은 record id가 중복 |
52
+ | `AUTH_USER_ID_REQUIRED` | 400 | `BadRequestError` | `linkedTo='brandappAuthUser'` entity인데 authUserId 누락 |
53
+
54
+ All classes extend `ReoptSDKError`, so `instanceof ReoptSDKError` and
55
+ `isReoptSDKError(err)` match every SDK error.
56
+
57
+ ```ts
58
+ import {
59
+ isReoptSDKError,
60
+ NotFoundError,
61
+ ForbiddenError,
62
+ } from "@reopt-ai/brandapp-sdk";
63
+
64
+ try {
65
+ await sdk.eav.records.get(entityId, recordId);
66
+ } catch (err) {
67
+ if (err instanceof NotFoundError) {
68
+ // record deleted — refresh UI
69
+ } else if (err instanceof ForbiddenError) {
70
+ // re-check auth / workspace scope
71
+ } else if (isReoptSDKError(err)) {
72
+ console.error(`[${err.code}] ${err.message}`);
73
+ }
74
+ throw err;
75
+ }
76
+ ```
77
+
78
+ ### EAV-specific branches (1.9+)
79
+
80
+ The narrower EAV classes turn common race / limit cases into one-line branches
81
+ without losing the underlying `instanceof ConflictError` compatibility.
82
+
83
+ ```ts
84
+ import {
85
+ AuthUserRecordExistsError,
86
+ AuthUserNotFoundError,
87
+ LimitExceededError,
88
+ DuplicateAuthUserError,
89
+ } from "@reopt-ai/brandapp-sdk/eav";
90
+
91
+ try {
92
+ await sdk.eav.records.create(entityId, { authUserId, values });
93
+ } catch (err) {
94
+ // 1:1 메타 entity인데 이미 record가 있음 → upsert로 자동 전환
95
+ if (err instanceof AuthUserRecordExistsError) {
96
+ return sdk.eav.records.upsert(entityId, {
97
+ authUserId,
98
+ filters: [{ attributeId: keyAttrId, operator: "eq", value: keyValue }],
99
+ values,
100
+ });
101
+ }
102
+ // BrandappAuthUser가 아직 등록되지 않음 — 먼저 생성 후 재시도
103
+ if (err instanceof AuthUserNotFoundError) {
104
+ await provisionAuthUser(authUserId);
105
+ return sdk.eav.records.create(entityId, { authUserId, values });
106
+ }
107
+ // plan 한도 초과 — 사용자에게 정리/업그레이드 안내
108
+ if (err instanceof LimitExceededError) {
109
+ showUpgradePrompt(err.code); // LIMIT_EXCEEDED_RECORDS 등
110
+ throw err;
111
+ }
112
+ throw err;
113
+ }
114
+ ```
115
+
116
+ bulk create에서 같은 authUserId 중복은 dev-time bug에 가까움 (1:1 메타 위반):
117
+
118
+ ```ts
119
+ try {
120
+ await sdk.eav.records.bulkCreate(entityId, records);
121
+ } catch (err) {
122
+ if (err instanceof DuplicateAuthUserError) {
123
+ throw new Error("같은 user에 대해 두 번 record를 만들 수 없습니다.");
124
+ }
125
+ throw err;
126
+ }
127
+ ```
128
+
129
+ ## Error Diagnostic
130
+
131
+ Every error has an optional `.diagnostic` property:
132
+
133
+ ```typescript
134
+ type ErrorDiagnostic = {
135
+ cause: string; // Why the error happened
136
+ fix: string; // How to fix it (actionable)
137
+ envVar?: string; // Related environment variable
138
+ doc?: string; // Related documentation path
139
+ };
140
+ ```
141
+
142
+ ## Common Errors & Fixes
143
+
144
+ ### CONFIG_MISSING: `clientId is required`
145
+
146
+ - **Cause**: `BRANDAPP_CLIENT_ID` environment variable not set
147
+ - **Fix**: Add to `.env`: `BRANDAPP_CLIENT_ID=your-client-id`
148
+ - **Where to find**: Studio → BrandApp → Settings → OAuth Clients
149
+
150
+ ### CONFIG_INVALID: malformed config value
151
+
152
+ - **Cause**: A config value is present but malformed — a `brandappId`
153
+ containing URL-significant characters (whitespace, `/`, `?`, `#`), or a
154
+ `baseUrl` / `idBaseUrl` that is not a valid absolute URL.
155
+ - **Fix**: Copy the BrandApp ID exactly as shown in Studio (no surrounding
156
+ whitespace); use an absolute URL like `https://brandapp.reopt.ai` for host
157
+ overrides.
158
+ - **Note**: Credentials are trimmed and whitespace-only values are treated as
159
+ missing (`CONFIG_MISSING`).
160
+
161
+ ### AUTH_ERROR: `Authentication failed` (401)
162
+
163
+ - **Cause**: Invalid clientId or clientSecret
164
+ - **Fix**: Verify credentials in Studio → BrandApp → Settings → OAuth Clients
165
+ - **Check**: Ensure the OAuth client is not disabled
166
+
167
+ ### RATE_LIMIT: `Rate limit exceeded` (429)
168
+
169
+ - **Cause**: Too many requests per minute/hour
170
+ - **Fix**: Add delays between requests, or increase limits in BrandApp AI settings
171
+ - **Header**: Check `Retry-After` response header for wait time
172
+
173
+ ### CREDIT_LIMIT: `Insufficient AI credits` (402)
174
+
175
+ - **Cause**: BrandApp AI credit balance is zero
176
+ - **Fix**: Recharge credits in Studio → BrandApp → AI Credit page
177
+ - **Streaming**: 스트리밍 경로(`sdk.ai.stream*`)에서도 사전 402 / mid-stream
178
+ `error` 프레임(`status: 402`)이 `CreditLimitError`로 매핑된다(`.diagnostic` 포함).
179
+ - **Provider**: AI SDK provider는 `APICallError`를 던지며 `error.cause`가
180
+ `CreditLimitError`, `error.data.code === "CREDIT_LIMIT"`다.
181
+
182
+ ### MODEL_ACCESS_DENIED: `Model not available for this plan tier` (403)
183
+
184
+ - **Cause**: 요청한 모델의 tier가 구독 플랜 또는 BrandApp `allowedModels`/
185
+ `allowedImageModels` 정책에서 허용되지 않음.
186
+ - **Fix**: `sdk.ai.models()`로 사용 가능 모델을 조회하거나 플랜 업그레이드.
187
+ - **Class**: `ModelAccessError` — `isModelAccessError(e)`로 분기. 일반 권한 실패
188
+ (`ForbiddenError`)와 구분된다.
189
+
190
+ ### MODEL_NOT_FOUND: `Unknown model` (404)
191
+
192
+ - **Cause**: model id가 카탈로그에 없음(오타 또는 폐기된 모델).
193
+ - **Fix**: `sdk.ai.models()`의 `id`를 그대로 사용.
194
+
195
+ ### CONTENT_FILTER: `Content blocked by moderation policy` (422)
196
+
197
+ - **Cause**: 프롬프트/생성 결과가 콘텐츠 정책 위반.
198
+ - **Fix**: 프롬프트를 수정.
199
+
200
+ ### VALIDATION_ERROR: Field-level errors (422)
201
+
202
+ - **Cause**: One or more fields failed validation
203
+ - **Fix**: Check `error.fieldErrors` for per-field details
204
+ - **Example**: `error.toFieldMap()` returns `{ email: "Invalid email format" }`
205
+
206
+ ### FORBIDDEN: `Forbidden` / `Model tier not available` (403)
207
+
208
+ - **Cause**: No permission for the resource — e.g. the requested model
209
+ tier exceeds the subscription plan, the OAuth scope is missing, or the
210
+ record belongs to a different `authUserId`.
211
+ - **Fix**: Use a lower-tier model / upgrade BrandApp subscription, or
212
+ verify OAuth scopes and the `authUserId` filter on the call site.
213
+ - **Class**: `ForbiddenError extends ReoptSDKError`
214
+
215
+ ### NOT_FOUND: `Not found` (404)
216
+
217
+ - **Cause**: The resource does not exist (or was deleted by another
218
+ process)
219
+ - **Fix**: Verify the ID is current; refresh caches before retrying
220
+ - **Class**: `NotFoundError extends ReoptSDKError`
221
+
222
+ ### CONFLICT: `Conflict` (409)
223
+
224
+ - **Cause**: State conflict — e.g. a unique constraint violation, or a
225
+ concurrent modification
226
+ - **Fix**: Re-read the current resource state and retry
227
+ - **Class**: `ConflictError extends ReoptSDKError`
228
+
229
+ ### BAD_REQUEST: `Bad request` (400)
230
+
231
+ - **Cause**: The request body or query parameters are malformed
232
+ - **Fix**: Check the request payload against the API reference
233
+ - **Class**: `BadRequestError extends ReoptSDKError`
234
+
235
+ ### STREAM_ERROR: `No response body` (0)
236
+
237
+ - **Cause**: SSE streaming failed (network issue or timeout)
238
+ - **Fix**: Check network connectivity, increase timeout in SDK config
239
+
240
+ ### QUERY_TOO_LARGE: query string exceeds the URL limit (0)
241
+
242
+ - **Cause**: A GET request (EAV/CMS `list`/`count`) serialized too many or too
243
+ large `filters` into the query string, risking a server/proxy URL-length
244
+ rejection (~8 KB) that would surface as an opaque 414/400.
245
+ - **Fix**: Reduce the number of filters or the size of filter values; split a
246
+ large query into several smaller calls.
247
+
248
+ ### FILE_NOT_FOUND: `File not found` (404)
249
+
250
+ - **Cause**: The requested file ID does not exist or has been deleted
251
+ - **Fix**: Verify the file ID is correct; the file may have been deleted by another process
252
+
253
+ ### FILE_TOO_LARGE: `File size exceeds limit` (413)
254
+
255
+ - **Cause**: Uploaded file exceeds the maximum allowed size
256
+ - **Fix**: Reduce file size or compress before uploading; check BrandApp file size limits
257
+
258
+ ### UPLOAD_FAILED: `Upload failed` (varies)
259
+
260
+ - **Cause**: File upload failed (network error, invalid format, storage issue)
261
+ - **Fix**: Check file format and size; retry the upload; ensure network connectivity
262
+
263
+ ### TIMEOUT: `Request timed out` (408)
264
+
265
+ - **Cause**: Request exceeded the timeout limit. For **streaming** (`sdk.ai.stream`,
266
+ `streamWithMetadata`, the AI SDK provider) `timeout` is an _idle_ timeout —
267
+ the maximum gap between chunks — so a long but healthy generation is never
268
+ cut off; only a genuine stall aborts. For non-streaming requests it is a
269
+ wall-clock deadline.
270
+ - **Fix**: Increase `timeout` in SDK config (default: 15000ms, AI clients:
271
+ 30000ms, AI SDK provider: 60000ms, file upload: 30000ms).
272
+ - **Retries**: 5xx/network/timeout failures are retried only for idempotent
273
+ methods (GET/HEAD/PUT/DELETE) by default; POST/PATCH are not retried to avoid
274
+ duplicate side effects (opt in via `retryNonIdempotent`). 429 is always retried.
275
+
276
+ ## Debug Mode
277
+
278
+ Enable debug logging to see all requests:
279
+
280
+ ```bash
281
+ BRANDAPP_SDK_DEBUG=1 node app.js
282
+ # or
283
+ BRANDAPP_SDK_LOG_FORMAT=json node app.js # Structured JSON logs
284
+ ```
285
+
286
+ Or in code:
287
+
288
+ ```typescript
289
+ createReoptSDK({ ..., debug: true });
290
+ ```
package/docs/files.md ADDED
@@ -0,0 +1,272 @@
1
+ # File Management API
2
+
3
+ BrandApp SDK의 파일 관리 모듈로, 파일 목록 조회, 단건 조회, 업로드, 삭제를 지원합니다.
4
+
5
+ ## Entry Point
6
+
7
+ ```typescript
8
+ import { createReoptSDK } from "@reopt-ai/brandapp-sdk";
9
+ // or
10
+ import {
11
+ ReoptFileClient,
12
+ createReoptFileClient,
13
+ } from "@reopt-ai/brandapp-sdk/files";
14
+ ```
15
+
16
+ ## API Reference
17
+
18
+ ### `sdk.files.list(query?)`
19
+
20
+ 파일 목록을 조회합니다.
21
+
22
+ ```typescript
23
+ const { data: files, meta } = await sdk.files.list({
24
+ page: 1,
25
+ limit: 20,
26
+ contentType: "image/*", // MIME 타입 필터
27
+ sortBy: "createdAt", // "createdAt" | "name" | "size"
28
+ sortOrder: "desc", // "asc" | "desc"
29
+ });
30
+
31
+ console.log(`Total files: ${meta.total}`);
32
+ files.forEach((f) => console.log(f.name, f.url));
33
+ ```
34
+
35
+ ### `sdk.files.get(fileId)`
36
+
37
+ 단일 파일 정보를 조회합니다.
38
+
39
+ ```typescript
40
+ const file = await sdk.files.get("file-uuid");
41
+ console.log(file.name); // "banner.png"
42
+ console.log(file.url); // "https://...blob.vercel-storage.com/..."
43
+ console.log(file.size); // 12345
44
+ console.log(file.contentType); // "image/png"
45
+ ```
46
+
47
+ ### `sdk.files.upload(file, options?)`
48
+
49
+ 파일을 업로드합니다. 업로드된 파일은 Vercel Blob에 저장됩니다.
50
+
51
+ ```typescript
52
+ // Blob 업로드
53
+ const blob = new Blob(["hello world"], { type: "text/plain" });
54
+ const uploaded = await sdk.files.upload(blob, { name: "hello.txt" });
55
+ console.log(uploaded.url);
56
+
57
+ // File 업로드 (브라우저 <input type="file">)
58
+ const fileInput = document.querySelector("input[type=file]");
59
+ const uploaded = await sdk.files.upload(fileInput.files[0]);
60
+
61
+ // Buffer 업로드 (Node.js)
62
+ import fs from "fs";
63
+ const buf = fs.readFileSync("image.png");
64
+ const uploaded = await sdk.files.upload(buf, {
65
+ name: "image.png",
66
+ contentType: "image/png",
67
+ });
68
+ ```
69
+
70
+ #### Upload Options
71
+
72
+ | Option | Type | Description |
73
+ | ------------- | -------- | ----------------------------------- |
74
+ | `name` | `string` | 파일명 (미지정 시 원본 파일명 사용) |
75
+ | `contentType` | `string` | MIME 타입 (미지정 시 자동 감지) |
76
+
77
+ ### `sdk.files.delete(fileId)`
78
+
79
+ 파일을 삭제합니다.
80
+
81
+ ```typescript
82
+ await sdk.files.delete("file-uuid");
83
+ ```
84
+
85
+ ## Image Generation + File Management Workflow
86
+
87
+ AI 이미지 생성 결과를 파일로 관리하는 워크플로우:
88
+
89
+ ```typescript
90
+ const sdk = createReoptSDK({
91
+ clientId: process.env.BRANDAPP_CLIENT_ID!,
92
+ clientSecret: process.env.BRANDAPP_CLIENT_SECRET!,
93
+ brandappId: process.env.BRANDAPP_ID!,
94
+ });
95
+
96
+ // 1. AI로 이미지 생성 (자동 저장됨)
97
+ const image = await sdk.ai.generateImage({
98
+ prompt: "브랜드 배너 이미지",
99
+ style: "minimalist",
100
+ aspectRatio: "16:9",
101
+ });
102
+ console.log(`Generated: ${image.url} (${image.size} bytes)`);
103
+
104
+ // 2. 생성된 이미지를 파일 목록에서 조회
105
+ const file = await sdk.files.get(image.id);
106
+ console.log(`File name: ${file.name}`);
107
+
108
+ // 3. 이미지 파일 목록 조회
109
+ const { data: images } = await sdk.files.list({
110
+ contentType: "image/*",
111
+ sortBy: "createdAt",
112
+ sortOrder: "desc",
113
+ });
114
+
115
+ // 4. 불필요한 파일 삭제
116
+ await sdk.files.delete(image.id);
117
+ ```
118
+
119
+ ## React Hooks
120
+
121
+ ```typescript
122
+ import {
123
+ useFiles,
124
+ useFile,
125
+ useUploadFile,
126
+ useDeleteFile,
127
+ } from "@reopt-ai/brandapp-sdk/react/hooks";
128
+
129
+ // 파일 목록 조회
130
+ const { data } = useFiles(sdk, { contentType: "image/*" });
131
+
132
+ // 단일 파일 조회
133
+ const { data: file } = useFile(sdk, fileId);
134
+
135
+ // 파일 업로드
136
+ const upload = useUploadFile(sdk);
137
+ await upload.mutateAsync({ file: blob, options: { name: "banner.png" } });
138
+
139
+ // 파일 삭제
140
+ const deleteFile = useDeleteFile(sdk);
141
+ await deleteFile.mutateAsync("file-uuid");
142
+ ```
143
+
144
+ ## Error Handling
145
+
146
+ ```typescript
147
+ import { isReoptSDKError } from "@reopt-ai/brandapp-sdk";
148
+
149
+ try {
150
+ await sdk.files.upload(largeFile);
151
+ } catch (e) {
152
+ if (isReoptSDKError(e)) {
153
+ switch (e.code) {
154
+ case "FILE_NOT_FOUND":
155
+ console.log("파일을 찾을 수 없습니다");
156
+ break;
157
+ case "FILE_TOO_LARGE":
158
+ console.log("파일 크기 제한 초과");
159
+ break;
160
+ case "UPLOAD_FAILED":
161
+ console.log("업로드 실패:", e.message);
162
+ break;
163
+ case "TIMEOUT":
164
+ console.log("업로드 시간 초과 — timeout 설정 확인");
165
+ break;
166
+ }
167
+ }
168
+ }
169
+ ```
170
+
171
+ ## Types
172
+
173
+ ```typescript
174
+ type FileInfo = {
175
+ id: string;
176
+ name: string;
177
+ url: string | null;
178
+ size: number;
179
+ contentType: string | null;
180
+ pathname: string;
181
+ createdAt: string;
182
+ updatedAt: string;
183
+ };
184
+
185
+ type FileListQuery = {
186
+ page?: number;
187
+ limit?: number;
188
+ contentType?: string;
189
+ sortBy?: "createdAt" | "name" | "size";
190
+ sortOrder?: "asc" | "desc";
191
+ };
192
+
193
+ type FileListResponse = {
194
+ data: FileInfo[];
195
+ meta: { page: number; limit: number; total: number };
196
+ };
197
+
198
+ type UploadOptions = {
199
+ name?: string;
200
+ contentType?: string;
201
+ };
202
+ ```
203
+
204
+ ## Image URL Helpers (1.8+)
205
+
206
+ `@reopt-ai/brandapp-sdk/files`에서 노출하는 순수 함수 헬퍼. SDK는 vendor-specific
207
+ 변환을 강제하지 않고, Next.js `<Image>`와 결합하기 위한 thin layer만 제공한다.
208
+
209
+ ### `optimizeUrl(src, opts)`
210
+
211
+ `src`에 `width` / `quality` 쿼리를 추가한다. 기존 query는 보존되고 같은 키는
212
+ override된다. 잘못된 URL은 그대로 반환.
213
+
214
+ ```typescript
215
+ import { optimizeUrl } from "@reopt-ai/brandapp-sdk/files";
216
+
217
+ optimizeUrl("https://blob.example/x.png", { width: 800, quality: 80 });
218
+ // → "https://blob.example/x.png?w=800&q=80"
219
+
220
+ optimizeUrl("https://blob.example/x.png?v=1", { width: 600 });
221
+ // → "https://blob.example/x.png?v=1&w=600"
222
+
223
+ optimizeUrl("not-a-url", { width: 800 });
224
+ // → "not-a-url" (잘못된 URL은 변환 없이 그대로)
225
+ ```
226
+
227
+ 일반적으로 Next.js Image가 자체 optimization endpoint(`/_next/image`)를 사용하므로
228
+ 직접 호출은 정적 OG 이미지 등 외부 사용자가 URL을 직접 만들 때만 필요하다.
229
+
230
+ ### `createImageLoader(defaults?)`
231
+
232
+ Next.js `<Image loader={...}>` 호환 함수를 반환. 기본 quality를 한 번 정의해두면
233
+ 호출 시점에 width만 전달된다.
234
+
235
+ ```tsx
236
+ import Image from "next/image";
237
+ import { createImageLoader } from "@reopt-ai/brandapp-sdk/files";
238
+
239
+ const loader = createImageLoader({ quality: 80 });
240
+
241
+ export function Banner({ src }: { src: string }) {
242
+ return <Image loader={loader} src={src} width={1200} height={630} alt="" />;
243
+ }
244
+ ```
245
+
246
+ ### `REOPT_IMAGE_REMOTE_PATTERNS`
247
+
248
+ `next.config.ts`의 `images.remotePatterns`에 그대로 넣어 reopt가 호스팅하는
249
+ 이미지(Vercel Blob 등)를 Next.js Image optimization이 가져갈 수 있게 등록.
250
+
251
+ ```typescript
252
+ // next.config.ts
253
+ import type { NextConfig } from "next";
254
+ import { REOPT_IMAGE_REMOTE_PATTERNS } from "@reopt-ai/brandapp-sdk/files";
255
+
256
+ const config: NextConfig = {
257
+ images: {
258
+ remotePatterns: [
259
+ ...REOPT_IMAGE_REMOTE_PATTERNS,
260
+ // 그 외 자기 호스트 추가
261
+ ],
262
+ },
263
+ };
264
+
265
+ export default config;
266
+ ```
267
+
268
+ 현재 포함되는 호스트:
269
+
270
+ - `*.public.blob.vercel-storage.com` (Vercel Blob 기본 도메인)
271
+
272
+ 향후 reopt가 도입하는 이미지 호스트는 SDK 업그레이드만으로 자동 반영된다.