@reopt-ai/brandapp-sdk 3.1.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +39 -14
  3. package/dist/abort--nOBFN4M.js +50 -0
  4. package/dist/ai/index.d.ts +2 -314
  5. package/dist/ai/index.js +3 -7
  6. package/dist/ai-provider/index.d.ts +79 -163
  7. package/dist/ai-provider/index.js +752 -671
  8. package/dist/auth/index.d.ts +27 -27
  9. package/dist/auth/index.js +41 -33
  10. package/dist/better-auth/client.d.ts +6 -5
  11. package/dist/better-auth/client.js +28 -5
  12. package/dist/better-auth/index.d.ts +19 -17
  13. package/dist/better-auth/index.js +180 -133
  14. package/dist/client-B1q5P8rv.js +83 -0
  15. package/dist/client-B9QHVhdM.js +77 -0
  16. package/dist/client-BGGd_cpV.d.ts +103 -0
  17. package/dist/client-BJcy1V1a.js +140 -0
  18. package/dist/client-Beivhucf.js +55 -0
  19. package/dist/client-BruP5_nU.d.ts +147 -0
  20. package/dist/client-D-yNxNfk.js +28 -0
  21. package/dist/client-D0eBxh8j.d.ts +284 -0
  22. package/dist/client-D3RHHUUW.d.ts +207 -0
  23. package/dist/client-D6gs61w8.d.ts +53 -0
  24. package/dist/client-DBnK7ooQ.js +86 -0
  25. package/dist/client-DDw5yz_h.d.ts +53 -0
  26. package/dist/client-DPmoKuR9.js +305 -0
  27. package/dist/client-DsdakibF.js +503 -0
  28. package/dist/client-Dxg8_DIH.d.ts +71 -0
  29. package/dist/client-EbhUIhHq.js +53 -0
  30. package/dist/client-lk6wBu_0.d.ts +48 -0
  31. package/dist/client-p49ol9pg.d.ts +124 -0
  32. package/dist/cms/index.d.ts +52 -108
  33. package/dist/cms/index.js +105 -84
  34. package/dist/config-CRytOPPl.d.ts +394 -0
  35. package/dist/config-Cw0a3-C8.js +487 -0
  36. package/dist/dev/index.d.ts +2 -509
  37. package/dist/dev/index.js +2740 -2873
  38. package/dist/eav/coerce.d.ts +3 -1
  39. package/dist/eav/coerce.js +72 -46
  40. package/dist/eav/index.d.ts +72 -100
  41. package/dist/eav/index.js +158 -125
  42. package/dist/eav/migrate.d.ts +112 -109
  43. package/dist/eav/migrate.js +230 -196
  44. package/dist/eav/schema.d.ts +111 -150
  45. package/dist/eav/schema.js +624 -603
  46. package/dist/encoding-Bwfm3iaE.js +21 -0
  47. package/dist/{errors-DIAS8Rsl.d.ts → errors-CRCcErNC.d.ts} +55 -53
  48. package/dist/feedback/index.d.ts +2 -132
  49. package/dist/feedback/index.js +3 -5
  50. package/dist/files/index.d.ts +14 -14
  51. package/dist/files/index.js +41 -24
  52. package/dist/http-client-QKUvvirs.js +386 -0
  53. package/dist/index-DrVaKfhs.d.ts +456 -0
  54. package/dist/index-Z6OGcurJ.d.ts +169 -0
  55. package/dist/index.d.ts +6 -221
  56. package/dist/index.js +119 -70
  57. package/dist/logout/index.d.ts +109 -0
  58. package/dist/logout/index.js +264 -0
  59. package/dist/plans/index.d.ts +2 -236
  60. package/dist/plans/index.js +3 -5
  61. package/dist/push/index.d.ts +2 -79
  62. package/dist/push/index.js +3 -5
  63. package/dist/query-BvbCiGWb.js +35 -0
  64. package/dist/react/hooks.d.ts +97 -95
  65. package/dist/react/hooks.js +742 -356
  66. package/dist/sse-parser-FMjxM7sY.js +86 -0
  67. package/dist/terms/index.d.ts +3 -79
  68. package/dist/terms/index.js +3 -5
  69. package/dist/testing/index.d.ts +52 -104
  70. package/dist/testing/index.js +94 -72
  71. package/dist/types-B-SMkH6s.d.ts +26 -0
  72. package/dist/types-BXDcoJHG.d.ts +131 -0
  73. package/dist/types-BrghN2rJ.d.ts +105 -0
  74. package/dist/types-DjDRszNj.js +11 -0
  75. package/dist/webhooks/index.d.ts +77 -47
  76. package/dist/webhooks/index.js +150 -127
  77. package/docs/api-reference.md +179 -2
  78. package/docs/dev-server.md +19 -18
  79. package/docs/errors.md +72 -15
  80. package/docs/logout.md +166 -0
  81. package/package.json +10 -5
  82. package/dist/chunk-2Q654O63.js +0 -350
  83. package/dist/chunk-F7BXBTZI.js +0 -54
  84. package/dist/chunk-IJOXTBIE.js +0 -599
  85. package/dist/chunk-JWXUVQRC.js +0 -157
  86. package/dist/chunk-L4DHB36G.js +0 -75
  87. package/dist/chunk-MRQY45U5.js +0 -465
  88. package/dist/chunk-N5JVE4WX.js +0 -449
  89. package/dist/chunk-O3PUWIDJ.js +0 -105
  90. package/dist/chunk-POLKEOYH.js +0 -63
  91. package/dist/chunk-R5CCGDUH.js +0 -49
  92. package/dist/chunk-RBHP7IZF.js +0 -96
  93. package/dist/chunk-REIKXSMY.js +0 -7
  94. package/dist/chunk-T7YTITRJ.js +0 -112
  95. package/dist/chunk-V73GORO3.js +0 -81
  96. package/dist/chunk-VRNBYSWU.js +0 -32
  97. package/dist/client-BkcO-0C2.d.ts +0 -216
  98. package/dist/client-CN5_tNOC.d.ts +0 -147
  99. package/dist/client-DttyeM_h.d.ts +0 -102
  100. package/dist/config-CtxyJsDR.d.ts +0 -397
  101. package/dist/typed-client-BxOVIiMU.d.ts +0 -40
  102. package/dist/types-6E3ZLL9X.d.ts +0 -24
  103. package/dist/types-DskYLVb8.d.ts +0 -104
  104. package/dist/types-ckmDDW3N.d.ts +0 -129
package/docs/errors.md CHANGED
@@ -6,21 +6,40 @@ All SDK errors extend `ReoptSDKError` and include a `.diagnostic` property with
6
6
 
7
7
  ### General
8
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) |
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
+ | `RequiredTermsError` | 422 | `REQUIRED_TERMS` | Plan checkout needs terms consent ([below](#required_terms)) |
23
+ | `ServerError` | 500 | `SERVER_ERROR` | Internal server error |
24
+ | `ReoptSDKError` | varies | varies | Base class (other / future API errors) |
25
+
26
+ `RequiredTermsError` (thrown by `sdk.plans.createCheckout`) carries
27
+ `missingTermsIds: string[]`; guard with `isRequiredTermsError(e)`.
28
+
29
+ ### Logout (OIDC Single Logout — `@reopt-ai/brandapp-sdk/logout`)
30
+
31
+ Raised by `verifyBackchannelLogoutToken` / `createBackchannelLogoutHandler`
32
+ (plain `ReoptSDKError` with a code — no dedicated subclass):
33
+
34
+ | Status | Code | When |
35
+ | ------ | --------------------------------- | --------------------------------------------------------------------- |
36
+ | 400 | `invalid_logout_token` | logout_token failed validation (bad signature / claims / structure) |
37
+ | 503 | `logout_verification_unavailable` | discovery/JWKS temporarily unreachable — **retryable**, not the token |
38
+
39
+ The handler maps `invalid_logout_token` → HTTP 400 and
40
+ `logout_verification_unavailable` → HTTP 503 (so the IdP retries instead of
41
+ treating a transient JWKS outage as a permanently bad token). See
42
+ [logout.md](./logout.md) for the full response contract.
24
43
 
25
44
  > Every subclass sets `error.name` to its own class name (e.g. `"AuthError"`,
26
45
  > `"RateLimitError"`, `"CreditLimitError"`) so log aggregation / Sentry grouping
@@ -203,6 +222,29 @@ type ErrorDiagnostic = {
203
222
  - **Fix**: Check `error.fieldErrors` for per-field details
204
223
  - **Example**: `error.toFieldMap()` returns `{ email: "Invalid email format" }`
205
224
 
225
+ <a id="required_terms"></a>
226
+
227
+ ### REQUIRED_TERMS: plan checkout needs terms consent (422)
228
+
229
+ - **Cause**: `sdk.plans.createCheckout` was called for a plan whose required
230
+ terms the customer has not yet consented to.
231
+ - **Fix**: read `error.missingTermsIds`, collect consent via `sdk.terms.list()`
232
+ \+ `sdk.terms.consent()`, then retry `createCheckout`.
233
+ - **Class**: `RequiredTermsError` — guard with `isRequiredTermsError(e)`; carries
234
+ `missingTermsIds: string[]`.
235
+
236
+ ```ts
237
+ import { isRequiredTermsError } from "@reopt-ai/brandapp-sdk";
238
+
239
+ try {
240
+ await sdk.plans.createCheckout({ planId, successUrl, cancelUrl }, token);
241
+ } catch (e) {
242
+ if (isRequiredTermsError(e)) {
243
+ // show consent UI for e.missingTermsIds, then retry
244
+ } else throw e;
245
+ }
246
+ ```
247
+
206
248
  ### FORBIDDEN: `Forbidden` / `Model tier not available` (403)
207
249
 
208
250
  - **Cause**: No permission for the resource — e.g. the requested model
@@ -272,6 +314,21 @@ type ErrorDiagnostic = {
272
314
  - **Retries**: 5xx/network/timeout failures are retried only for idempotent
273
315
  methods (GET/HEAD/PUT/DELETE) by default; POST/PATCH are not retried to avoid
274
316
  duplicate side effects (opt in via `retryNonIdempotent`). 429 is always retried.
317
+ A single read tunneled over POST can opt into retry per-call with the
318
+ `idempotent` fetch option (the Better Auth adapter uses this for
319
+ `findOne`/`findMany`/`count`).
320
+ - **Note**: `TIMEOUT` is reserved for the internal wall-clock/idle deadline. A
321
+ request you cancel via your own `AbortSignal` rejects with a distinct
322
+ `CANCELLED` error whose `name` is `"AbortError"` (the standard web
323
+ cancellation convention) and stops retrying immediately.
324
+
325
+ ### CANCELLED: caller aborted the request (0)
326
+
327
+ - **Cause**: The `AbortSignal` you passed as `FetchOptions.signal` was aborted
328
+ (e.g. React component unmount, request supersession).
329
+ - **Detect**: `err.name === "AbortError"` (or `err.code === "CANCELLED"`).
330
+ - **Note**: Distinct from `TIMEOUT` (408) — a caller cancel is not a server
331
+ timeout, and the retry loop breaks on it rather than burning retries.
275
332
 
276
333
  ## Debug Mode
277
334
 
package/docs/logout.md ADDED
@@ -0,0 +1,166 @@
1
+ # Logout — Single Logout across reopt and your app
2
+
3
+ `@reopt-ai/brandapp-sdk/logout` implements OIDC **Single Logout** so a session
4
+ can end in both directions between reopt (the Identity Provider) and your app
5
+ (a Relying Party):
6
+
7
+ - **Back-Channel Logout (receive)** — when a user logs out of reopt (or an admin
8
+ bans/deletes them, or another device is signed out), reopt notifies your app
9
+ server-to-server so you can end the matching session in your app.
10
+ - **RP-Initiated Logout (trigger)** — when a user logs out of **your** app, you
11
+ can optionally send them through reopt's `end_session_endpoint` to end their
12
+ reopt session too (and every session derived from it).
13
+
14
+ No external dependencies — signature verification uses Web Crypto (Ed25519).
15
+
16
+ > **Runtime**: Back-Channel Logout verification needs Ed25519 in Web Crypto —
17
+ > available on Node 20+, Deno, Cloudflare Workers, and modern browsers. Since the
18
+ > receiver runs server-side, any Node 20+ host (Firebase Functions, Vercel
19
+ > Functions, etc.) works.
20
+
21
+ ## 1. Receive Back-Channel Logout
22
+
23
+ Mount a handler at a stable URL and register that URL with reopt as your OAuth
24
+ client's `backchannel_logout_uri` (ask your reopt contact, or set it in Studio →
25
+ BrandApp → OAuth). reopt POSTs a signed `logout_token` there whenever the
26
+ originating reopt session is revoked.
27
+
28
+ ```ts
29
+ // Next.js App Router — app/api/auth/backchannel-logout/route.ts
30
+ import { createBackchannelLogoutHandler } from "@reopt-ai/brandapp-sdk/logout";
31
+
32
+ export const POST = createBackchannelLogoutHandler({
33
+ // Revoke every local session derived from this reopt session id.
34
+ onLogout: async ({ sid, sub }) => {
35
+ await db.sessions.deleteMany({ where: { reoptSid: sid } });
36
+ },
37
+ });
38
+ ```
39
+
40
+ The handler is a standard `(Request) => Promise<Response>`, so it also works with
41
+ Hono, plain Fetch servers, or any framework that speaks the Web `Request`/`Response`
42
+ API.
43
+
44
+ ### Wiring the `sid`
45
+
46
+ To end the right sessions, store the reopt **session id (`sid`)** when the user
47
+ logs in. It's the `sid` claim of the `id_token` you receive from the OAuth code
48
+ exchange. Persist it on your session row so `onLogout({ sid })` can find and
49
+ delete the matching sessions.
50
+
51
+ ```ts
52
+ // at login, after code exchange:
53
+ const { sid } = decodeIdToken(tokenResponse.id_token);
54
+ await db.sessions.create({ userId, reoptSid: sid, ... });
55
+ ```
56
+
57
+ ### Verify manually
58
+
59
+ If you need the claims without the HTTP wrapper (custom transport, testing):
60
+
61
+ ```ts
62
+ import { verifyBackchannelLogoutToken } from "@reopt-ai/brandapp-sdk/logout";
63
+
64
+ const { sid, sub } = await verifyBackchannelLogoutToken(logoutToken, {
65
+ clientId: process.env.BRANDAPP_CLIENT_ID,
66
+ });
67
+ ```
68
+
69
+ It throws `ReoptSDKError` (`code: "invalid_logout_token"`) on any failure:
70
+ bad signature, wrong issuer/audience, missing `backchannel-logout` event,
71
+ a forbidden `nonce`, a stale `iat`, or a non-`EdDSA` algorithm.
72
+
73
+ ### Response contract
74
+
75
+ | Situation | Status |
76
+ | ----------------------------------------------------------- | ------ |
77
+ | Valid token, `onLogout` succeeded | `200` |
78
+ | Missing/invalid `logout_token`, verification failed | `400` |
79
+ | Non-POST | `405` |
80
+ | `onLogout` threw (make it idempotent — reopt retries) | `501` |
81
+ | Verification infra (discovery/JWKS) temporarily unavailable | `503` |
82
+
83
+ All responses carry `Cache-Control: no-store` per the spec.
84
+
85
+ The `503` (code `logout_verification_unavailable`) is returned **instead of
86
+ `400`** when the reopt discovery/JWKS endpoint is briefly unreachable (e.g. a
87
+ deploy) — a transient infra failure is not a bad token, so the IdP is told the
88
+ request is retryable rather than permanently invalid.
89
+
90
+ Signatures are verified with Web Crypto **Ed25519** (zero external deps). The
91
+ JWKS is fetched from discovery and cached; on a signature miss it is force-
92
+ refetched once to survive key rotation, but that forced refetch is **throttled
93
+ per `jwks_uri`** and concurrent refetches are coalesced, so a flood of forged
94
+ tokens to this public endpoint cannot reflect load onto the shared JWKS
95
+ endpoint. Discovery/JWKS fetches carry a timeout and fail closed.
96
+
97
+ ## 2. Trigger RP-Initiated Logout
98
+
99
+ When the user logs out of your app, send them to reopt's `end_session_endpoint`
100
+ to also end the reopt session. Pass the `id_token` you got at login as the hint.
101
+
102
+ ```ts
103
+ import { buildEndSessionUrl } from "@reopt-ai/brandapp-sdk/logout";
104
+
105
+ const url = buildEndSessionUrl({
106
+ idToken: session.reoptIdToken, // id_token from login
107
+ postLogoutRedirectUri: "https://app.example.com/goodbye",
108
+ state: csrfToken, // optional, echoed back
109
+ });
110
+
111
+ // end your local session first, then:
112
+ redirect(url);
113
+ ```
114
+
115
+ For reopt to redirect back afterwards, `postLogoutRedirectUri` **must be
116
+ pre-registered** on your OAuth client's `post_logout_redirect_uris`. If it isn't
117
+ registered, reopt still ends the session but won't redirect.
118
+
119
+ ## How it fits together
120
+
121
+ ```
122
+ User logs out of reopt (or ban / delete / device sign-out)
123
+ │
124
+ ▼
125
+ reopt revokes the IdP session, then for each client with a
126
+ backchannel_logout_uri that holds tokens from that session:
127
+ │ POST logout_token (EdDSA JWT: aud, sid, events, …)
128
+ ▼
129
+ your handler → verify → onLogout({ sid }) → delete local sessions
130
+
131
+ User logs out of your app
132
+ │ redirect to buildEndSessionUrl({ idToken })
133
+ ▼
134
+ reopt end_session_endpoint → revokes that IdP session (cascades to all
135
+ derived sessions/tokens) → redirects to post_logout_redirect_uri
136
+ ```
137
+
138
+ ## Testing against the dev server
139
+
140
+ The in-memory dev server (`@reopt-ai/brandapp-sdk/dev`) is a faithful OIDC mock:
141
+ it signs real EdDSA tokens, serves its public key at `/api/auth/jwks`, and mounts
142
+ `/api/auth/oauth2/end-session`. Point your logout verifier at `dev.url` and mint a
143
+ `logout_token` to exercise your handler end-to-end — no reopt server required.
144
+
145
+ ```ts
146
+ import { createDevServer } from "@reopt-ai/brandapp-sdk/dev";
147
+
148
+ const dev = await createDevServer({ brandappId: "dev" });
149
+
150
+ const logoutToken = await dev.mintLogoutToken({
151
+ clientId: "my-brandapp",
152
+ sessionId: "idp-session-1",
153
+ userId: "user-1",
154
+ });
155
+
156
+ // Drive your handler with a form POST carrying logout_token=<token>, or verify
157
+ // directly — both fetch discovery + JWKS from the dev server:
158
+ const res = await POST(
159
+ new Request("http://localhost/api/auth/backchannel-logout", {
160
+ method: "POST",
161
+ headers: { "content-type": "application/x-www-form-urlencoded" },
162
+ body: new URLSearchParams({ logout_token: logoutToken }),
163
+ }),
164
+ );
165
+ // (configure the handler with idBaseUrl: dev.url, clientId: "my-brandapp")
166
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reopt-ai/brandapp-sdk",
3
- "version": "3.1.0",
3
+ "version": "3.4.0",
4
4
  "description": "Reopt Brandapp SDK — Better Auth adapter, OAuth login, and EAV client",
5
5
  "author": "Reopt",
6
6
  "license": "MIT",
@@ -57,6 +57,10 @@
57
57
  "types": "./dist/feedback/index.d.ts",
58
58
  "import": "./dist/feedback/index.js"
59
59
  },
60
+ "./logout": {
61
+ "types": "./dist/logout/index.d.ts",
62
+ "import": "./dist/logout/index.js"
63
+ },
60
64
  "./files": {
61
65
  "types": "./dist/files/index.d.ts",
62
66
  "import": "./dist/files/index.js"
@@ -135,11 +139,12 @@
135
139
  "@ai-sdk/provider": "4.0.0",
136
140
  "@reopt-ai/opt-editor": "1.1.2",
137
141
  "@testing-library/react": "^16.3.2",
142
+ "@types/node": "22.13.9",
138
143
  "better-auth": "^1.4.0",
139
144
  "happy-dom": "^20.8.9",
140
145
  "hono": "^4.7.0",
141
- "tsup": "^8.0.0",
142
- "typescript": "5.9.2",
146
+ "tsdown": "^0.22.14",
147
+ "typescript": "^7",
143
148
  "vitest": "^4.1.2",
144
149
  "@reopt/typescript-config": "0.0.0"
145
150
  },
@@ -163,8 +168,8 @@
163
168
  "node": ">=18"
164
169
  },
165
170
  "scripts": {
166
- "build": "tsup",
167
- "dev": "tsup --watch",
171
+ "build": "tsdown",
172
+ "dev": "tsdown --watch",
168
173
  "type-check": "tsc --noEmit",
169
174
  "test": "vitest run",
170
175
  "test:coverage": "vitest run --coverage",
@@ -1,350 +0,0 @@
1
- import { parseSSEStream } from './chunk-L4DHB36G.js';
2
- import { createManagedAbort } from './chunk-F7BXBTZI.js';
3
- import { BaseHttpClient } from './chunk-N5JVE4WX.js';
4
- import { validateConfig, ReoptSDKError, mapHttpStatusToError, SDK_VERSION } from './chunk-MRQY45U5.js';
5
-
6
- // src/ai/client.ts
7
- var ReoptAiClient = class {
8
- http;
9
- /**
10
- * Idle (inactivity) timeout for streaming, in ms — the maximum gap allowed
11
- * *between* SSE chunks, not a deadline on the whole generation. A long but
12
- * healthy generation keeps resetting this; only a genuine stall aborts.
13
- */
14
- streamIdleTimeout;
15
- constructor(config) {
16
- validateConfig(config);
17
- const pathPrefix = `/api/v1/brandapp/${config.brandappId}/ai`;
18
- this.http = new BaseHttpClient(config, pathPrefix);
19
- this.streamIdleTimeout = config.timeout ?? 6e4;
20
- }
21
- /**
22
- * AI 텍스트 생성 (non-streaming)
23
- *
24
- * @example
25
- * ```ts
26
- * const result = await sdk.ai.complete({
27
- * messages: [{ role: "user", content: "Hello" }],
28
- * model: "anthropic/claude-haiku-4.5",
29
- * maxTokens: 1024,
30
- * });
31
- * console.log(result.message.content);
32
- * ```
33
- */
34
- async complete(options) {
35
- const response = await this.http.fetch(
36
- "POST",
37
- "/chat/completions",
38
- {
39
- model: options.model,
40
- agentId: options.agentId,
41
- messages: options.messages,
42
- maxTokens: options.maxTokens,
43
- temperature: options.temperature,
44
- stream: false,
45
- customerId: options.customerId
46
- }
47
- );
48
- return response.data;
49
- }
50
- /**
51
- * AI 텍스트 생성 (SSE 스트리밍)
52
- *
53
- * async generator로 텍스트 청크를 반환합니다.
54
- * 사용량 메타데이터가 필요하면 `streamWithMetadata()`를 사용하세요.
55
- *
56
- * @example
57
- * ```ts
58
- * for await (const chunk of sdk.ai.stream({
59
- * messages: [{ role: "user", content: "Hello" }],
60
- * })) {
61
- * process.stdout.write(chunk);
62
- * }
63
- * ```
64
- */
65
- async *stream(options) {
66
- const { response, managed, requestId } = await this.fetchSSE(options);
67
- if (!response.body) {
68
- managed.cleanup();
69
- throw new ReoptSDKError("No response body", 0, "STREAM_ERROR");
70
- }
71
- try {
72
- for await (const { event, data } of parseSSEStream(response.body)) {
73
- managed.kick();
74
- if (event === "text-delta") {
75
- yield data;
76
- } else if (event === "error") {
77
- const ctx = { requestId };
78
- try {
79
- const err = JSON.parse(data);
80
- if (typeof err.status === "number") {
81
- throw mapHttpStatusToError(
82
- err.status,
83
- err.code,
84
- err.message,
85
- ctx
86
- );
87
- }
88
- throw new ReoptSDKError(
89
- err.message ?? "Stream error",
90
- 0,
91
- err.code ?? "STREAM_ERROR",
92
- ctx
93
- );
94
- } catch (e) {
95
- if (e instanceof ReoptSDKError) throw e;
96
- throw new ReoptSDKError(data, 0, "STREAM_ERROR", ctx);
97
- }
98
- }
99
- }
100
- } catch (e) {
101
- throw mapStreamError(e, managed);
102
- } finally {
103
- managed.cleanup();
104
- }
105
- }
106
- /**
107
- * AI 텍스트 생성 (SSE 스트리밍 + 메타데이터)
108
- *
109
- * 텍스트 청크와 함께 최종 사용량/크레딧 메타데이터를 반환합니다.
110
- *
111
- * @example
112
- * ```ts
113
- * const { textStream, metadata } = sdk.ai.streamWithMetadata({
114
- * messages: [{ role: "user", content: "Hello" }],
115
- * });
116
- *
117
- * let text = "";
118
- * for await (const chunk of textStream) {
119
- * text += chunk;
120
- * }
121
- *
122
- * const meta = await metadata;
123
- * console.log(`사용 크레딧: ${meta?.usage.creditCost}`);
124
- * ```
125
- */
126
- streamWithMetadata(options) {
127
- let resolveMeta;
128
- const metadata = new Promise((r) => {
129
- resolveMeta = r;
130
- });
131
- let settled = false;
132
- const settle = (v) => {
133
- if (settled) return;
134
- settled = true;
135
- resolveMeta(v);
136
- };
137
- const self = this;
138
- async function* gen() {
139
- const { response, managed, requestId } = await self.fetchSSE(options);
140
- if (!response.body) {
141
- managed.cleanup();
142
- settle(null);
143
- throw new ReoptSDKError("No response body", 0, "STREAM_ERROR");
144
- }
145
- try {
146
- for await (const { event, data } of parseSSEStream(response.body)) {
147
- managed.kick();
148
- if (event === "text-delta") {
149
- yield data;
150
- } else if (event === "done") {
151
- try {
152
- settle(JSON.parse(data));
153
- } catch {
154
- settle(null);
155
- }
156
- } else if (event === "error") {
157
- const ctx = { requestId };
158
- try {
159
- const err = JSON.parse(data);
160
- if (typeof err.status === "number") {
161
- throw mapHttpStatusToError(
162
- err.status,
163
- err.code,
164
- err.message,
165
- ctx
166
- );
167
- }
168
- throw new ReoptSDKError(
169
- err.message ?? "Stream error",
170
- 0,
171
- err.code ?? "STREAM_ERROR",
172
- ctx
173
- );
174
- } catch (e) {
175
- if (e instanceof ReoptSDKError) throw e;
176
- throw new ReoptSDKError(data, 0, "STREAM_ERROR", ctx);
177
- }
178
- }
179
- }
180
- } catch (e) {
181
- throw mapStreamError(e, managed);
182
- } finally {
183
- settle(null);
184
- managed.cleanup();
185
- }
186
- }
187
- return { textStream: gen(), metadata };
188
- }
189
- /**
190
- * 이미지 생성
191
- *
192
- * BrandApp의 AI 크레딧으로 이미지를 생성합니다.
193
- * 생성된 이미지는 자동으로 Vercel Blob에 저장되고 URL이 반환됩니다.
194
- *
195
- * @example
196
- * ```ts
197
- * const image = await sdk.ai.generateImage({
198
- * prompt: "브랜드 배너 이미지",
199
- * style: "minimalist",
200
- * aspectRatio: "16:9",
201
- * });
202
- * console.log(image.url); // https://...blob.vercel-storage.com/...
203
- * console.log(image.size); // 12345 (bytes)
204
- * ```
205
- */
206
- async generateImage(options) {
207
- const response = await this.http.fetch(
208
- "POST",
209
- "/images/generate",
210
- {
211
- prompt: options.prompt,
212
- negativePrompt: options.negativePrompt,
213
- style: options.style,
214
- aspectRatio: options.aspectRatio ?? "1:1",
215
- model: options.model,
216
- customerId: options.customerId
217
- }
218
- );
219
- return response.data;
220
- }
221
- /**
222
- * 크레딧 잔액 조회
223
- *
224
- * @example
225
- * ```ts
226
- * const credits = await sdk.ai.credits();
227
- * console.log(`${credits.balance} / ${credits.limit} (${credits.status})`);
228
- * ```
229
- */
230
- async credits() {
231
- const response = await this.http.fetch(
232
- "GET",
233
- "/credits"
234
- );
235
- return response.data;
236
- }
237
- /**
238
- * 사용 가능 모델 목록 조회
239
- *
240
- * @example
241
- * ```ts
242
- * const models = await sdk.ai.models();
243
- * models.forEach(m => console.log(`${m.id} (${m.tierLabel})`));
244
- * ```
245
- */
246
- async models() {
247
- const response = await this.http.fetch(
248
- "GET",
249
- "/models"
250
- );
251
- return response.data;
252
- }
253
- /**
254
- * 사용 가능한 커스텀 에이전트 목록 조회
255
- *
256
- * @example
257
- * ```ts
258
- * const agents = await sdk.ai.agents();
259
- * for (const agent of agents) {
260
- * console.log(`${agent.name}: ${agent.description}`);
261
- * }
262
- * ```
263
- */
264
- async agents() {
265
- const response = await this.http.fetch(
266
- "GET",
267
- "/agents"
268
- );
269
- return response.data;
270
- }
271
- // ---------------------------------------------------------------------------
272
- // Internal: SSE fetch (BaseHttpClient는 JSON 전용이므로 직접 fetch)
273
- // ---------------------------------------------------------------------------
274
- async fetchSSE(options) {
275
- const url = `${this.http.requestBaseUrl}/chat/completions`;
276
- const requestId = globalThis.crypto?.randomUUID?.() ?? `sdk-${SDK_VERSION}-${url.length}`;
277
- const ctx = { method: "POST", url, requestId };
278
- const maxConnectAttempts = 2;
279
- let lastConnectError;
280
- for (let attempt = 0; attempt < maxConnectAttempts; attempt++) {
281
- const managed = createManagedAbort({
282
- timeoutMs: this.streamIdleTimeout,
283
- external: options.signal,
284
- idle: true
285
- });
286
- try {
287
- const response = await globalThis.fetch(url, {
288
- method: "POST",
289
- headers: {
290
- Authorization: this.http.authorizationHeader,
291
- "Content-Type": "application/json",
292
- Accept: "text/event-stream",
293
- "X-SDK-Version": `brandapp-sdk/${SDK_VERSION}`,
294
- "X-Request-Id": requestId,
295
- "Idempotency-Key": requestId
296
- },
297
- body: JSON.stringify({
298
- model: options.model,
299
- agentId: options.agentId,
300
- messages: options.messages,
301
- maxTokens: options.maxTokens,
302
- temperature: options.temperature,
303
- stream: true,
304
- customerId: options.customerId
305
- }),
306
- signal: managed.signal
307
- });
308
- if (!response.ok) {
309
- const body = await response.json().catch(() => ({}));
310
- const err = body?.error ?? {};
311
- managed.cleanup();
312
- throw mapHttpStatusToError(
313
- response.status,
314
- err.code,
315
- err.message ?? `HTTP ${response.status}`,
316
- ctx
317
- );
318
- }
319
- return { response, managed, requestId };
320
- } catch (e) {
321
- managed.cleanup();
322
- if (e instanceof ReoptSDKError) throw e;
323
- if (managed.timedOut || options.signal?.aborted) {
324
- throw mapStreamError(e, managed);
325
- }
326
- lastConnectError = e;
327
- if (attempt < maxConnectAttempts - 1) continue;
328
- throw mapStreamError(e, managed);
329
- }
330
- }
331
- throw mapStreamError(lastConnectError, void 0);
332
- }
333
- };
334
- function mapStreamError(e, managed) {
335
- if (e instanceof ReoptSDKError) return e;
336
- if (e instanceof Error && e.name === "AbortError") {
337
- if (managed?.timedOut) {
338
- return new ReoptSDKError("Stream request timed out", 408, "TIMEOUT");
339
- }
340
- return new ReoptSDKError("Stream cancelled by caller", 0, "CANCELLED");
341
- }
342
- return e;
343
- }
344
- function createReoptAiClient(config) {
345
- return new ReoptAiClient(config);
346
- }
347
-
348
- export { ReoptAiClient, createReoptAiClient };
349
- //# sourceMappingURL=chunk-2Q654O63.js.map
350
- //# sourceMappingURL=chunk-2Q654O63.js.map