@reopt-ai/brandapp-sdk 3.3.0 → 3.5.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 +115 -0
  2. package/README.md +10 -1
  3. package/dist/abort--nOBFN4M.js +50 -0
  4. package/dist/ai/index.d.ts +2 -314
  5. package/dist/ai/index.js +3 -8
  6. package/dist/ai-provider/index.d.ts +79 -163
  7. package/dist/ai-provider/index.js +752 -685
  8. package/dist/auth/index.d.ts +27 -27
  9. package/dist/auth/index.js +41 -34
  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 -144
  14. package/dist/client-61ldOHMz.js +503 -0
  15. package/dist/client-7PCoxVhZ.js +28 -0
  16. package/dist/client-B7rZQ8Zi.d.ts +272 -0
  17. package/dist/client-BGGd_cpV.d.ts +103 -0
  18. package/dist/client-BoIuyx4S.js +273 -0
  19. package/dist/client-BruP5_nU.d.ts +147 -0
  20. package/dist/client-BxtZt405.js +305 -0
  21. package/dist/client-ByN3EQdk.js +83 -0
  22. package/dist/client-CAghoGD_.js +53 -0
  23. package/dist/client-C_pHsPlj.js +81 -0
  24. package/dist/client-D0eBxh8j.d.ts +284 -0
  25. package/dist/client-D6gs61w8.d.ts +53 -0
  26. package/dist/client-DDw5yz_h.d.ts +53 -0
  27. package/dist/client-Dxg8_DIH.d.ts +71 -0
  28. package/dist/client-aMR4CRB8.d.ts +211 -0
  29. package/dist/client-lk6wBu_0.d.ts +48 -0
  30. package/dist/client-wEVKLdly.js +55 -0
  31. package/dist/client-zF1RG2uA.js +86 -0
  32. package/dist/cms/index.d.ts +52 -108
  33. package/dist/cms/index.js +103 -86
  34. package/dist/config-CRytOPPl.d.ts +394 -0
  35. package/dist/config-aml9oQpX.js +487 -0
  36. package/dist/dev/index.d.ts +2 -528
  37. package/dist/dev/index.js +3047 -2967
  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 -126
  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-BjDFIyA6.d.ts → errors-CRCcErNC.d.ts} +55 -53
  48. package/dist/feedback/index.d.ts +2 -132
  49. package/dist/feedback/index.js +3 -6
  50. package/dist/files/index.d.ts +14 -14
  51. package/dist/files/index.js +41 -25
  52. package/dist/http-client-BZc2mngq.js +386 -0
  53. package/dist/index-1j_738qk.d.ts +470 -0
  54. package/dist/index-CeOLGdyL.d.ts +169 -0
  55. package/dist/index.d.ts +6 -230
  56. package/dist/index.js +119 -71
  57. package/dist/logout/index.d.ts +56 -53
  58. package/dist/logout/index.js +232 -289
  59. package/dist/plans/index.d.ts +2 -236
  60. package/dist/plans/index.js +3 -6
  61. package/dist/push/index.d.ts +2 -79
  62. package/dist/push/index.js +3 -6
  63. package/dist/query-xWqtfkvR.js +35 -0
  64. package/dist/react/hooks.d.ts +157 -100
  65. package/dist/react/hooks.js +862 -406
  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 -6
  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 -50
  76. package/dist/webhooks/index.js +150 -127
  77. package/docs/api-reference.md +121 -8
  78. package/docs/errors.md +19 -0
  79. package/docs/files.md +165 -7
  80. package/package.json +7 -6
  81. package/dist/chunk-2LSCQHAU.js +0 -21
  82. package/dist/chunk-4U4ZPPL4.js +0 -599
  83. package/dist/chunk-55KHY5GH.js +0 -96
  84. package/dist/chunk-C5VTRZWX.js +0 -458
  85. package/dist/chunk-F7BXBTZI.js +0 -54
  86. package/dist/chunk-FJUCWXX3.js +0 -350
  87. package/dist/chunk-H33OTQEN.js +0 -112
  88. package/dist/chunk-L4DHB36G.js +0 -75
  89. package/dist/chunk-OG7R3UAR.js +0 -105
  90. package/dist/chunk-PF24XU54.js +0 -32
  91. package/dist/chunk-QN3QD67K.js +0 -49
  92. package/dist/chunk-REIKXSMY.js +0 -7
  93. package/dist/chunk-UGBBXCZE.js +0 -157
  94. package/dist/chunk-UVT2E6KD.js +0 -81
  95. package/dist/chunk-YPLT3RFL.js +0 -63
  96. package/dist/chunk-YTKSAWV2.js +0 -463
  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
@@ -1,717 +1,784 @@
1
- import { createSSELineProcessor } from '../chunk-L4DHB36G.js';
2
- import { createManagedAbort } from '../chunk-F7BXBTZI.js';
3
- import { createAuthHeader } from '../chunk-2LSCQHAU.js';
4
- import { assertBrowserSafe, validateConfig, resolveBaseUrl, SDK_VERSION, mapHttpStatusToError } from '../chunk-C5VTRZWX.js';
5
- import { NoSuchModelError, APICallError } from '@ai-sdk/provider';
1
+ import { A as mapHttpStatusToError, i as resolveBaseUrl, n as SDK_VERSION, o as validateConfig, r as assertBrowserSafe } from "../config-aml9oQpX.js";
2
+ import { t as createManagedAbort } from "../abort--nOBFN4M.js";
3
+ import { t as createAuthHeader } from "../encoding-Bwfm3iaE.js";
4
+ import { t as createSSELineProcessor } from "../sse-parser-FMjxM7sY.js";
5
+ import { APICallError, NoSuchModelError } from "@ai-sdk/provider";
6
6
 
7
+ //#region src/ai-provider/provider-http.ts
8
+ /**
9
+ * Shared HTTP utilities for BrandApp AI provider models.
10
+ *
11
+ * Used by BrandappLanguageModel and BrandappImageModel to avoid duplication.
12
+ */
13
+ /** Per-request id for X-Request-Id / Idempotency-Key + error correlation. */
7
14
  function newRequestId(sdkVersion) {
8
- return globalThis.crypto?.randomUUID?.() ?? `sdk-${sdkVersion}-${Date.now()}`;
15
+ return globalThis.crypto?.randomUUID?.() ?? `sdk-${sdkVersion}-${Date.now()}`;
9
16
  }
17
+ /**
18
+ * Call-invariant base headers (auth + content-type + SDK version). Compute
19
+ * once per model and reuse via {@link mergeProviderHeaders} — these don't
20
+ * change between requests.
21
+ */
10
22
  function buildBaseProviderHeaders(config) {
11
- return {
12
- Authorization: config.authHeader,
13
- "Content-Type": "application/json",
14
- "X-SDK-Version": `brandapp-sdk/${config.sdkVersion}`
15
- };
23
+ return {
24
+ Authorization: config.authHeader,
25
+ "Content-Type": "application/json",
26
+ "X-SDK-Version": `brandapp-sdk/${config.sdkVersion}`
27
+ };
16
28
  }
29
+ /** Merge per-call headers onto a base, dropping `undefined` values. */
17
30
  function mergeProviderHeaders(base, extraHeaders) {
18
- if (!extraHeaders) return { ...base };
19
- const headers = { ...base };
20
- for (const [key, value] of Object.entries(extraHeaders)) {
21
- if (value !== void 0) {
22
- headers[key] = value;
23
- }
24
- }
25
- return headers;
31
+ if (!extraHeaders) return { ...base };
32
+ const headers = { ...base };
33
+ for (const [key, value] of Object.entries(extraHeaders)) if (value !== void 0) headers[key] = value;
34
+ return headers;
26
35
  }
36
+ /**
37
+ * Convenience: base + per-call merge in one call. Kept for the image model,
38
+ * which builds a fresh header set per request.
39
+ */
27
40
  function buildProviderHeaders(config, extraHeaders) {
28
- return mergeProviderHeaders(buildBaseProviderHeaders(config), extraHeaders);
41
+ return mergeProviderHeaders(buildBaseProviderHeaders(config), extraHeaders);
29
42
  }
43
+ /**
44
+ * fetch with a hard deadline that covers the **entire** transfer — headers AND
45
+ * body. A plain fetch + timeout that clears once headers arrive leaves the body
46
+ * read (`.json()`/`.arrayBuffer()`) unbounded, so a server that sends headers
47
+ * then stalls the body hangs forever. We buffer the body inside the timeout
48
+ * window (the abort signal aborts a stalled read) and hand back a `Response`
49
+ * over the buffered bytes, so callers keep calling `.json()`/`.arrayBuffer()`
50
+ * unchanged — now non-blocking. Non-streaming reads only (both AI-provider
51
+ * callers consume the full body).
52
+ */
30
53
  async function fetchWithTimeout(config, fetchFn, url, init) {
31
- const controller = new AbortController();
32
- const existingSignal = init.signal;
33
- const onAbort = () => controller.abort(existingSignal.reason);
34
- if (existingSignal) {
35
- existingSignal.addEventListener("abort", onAbort);
36
- }
37
- const timeoutId = setTimeout(
38
- () => controller.abort(new Error("Request timed out")),
39
- config.timeout
40
- );
41
- try {
42
- const response = await fetchFn(url, {
43
- ...init,
44
- signal: controller.signal
45
- });
46
- const hasBody = response.body !== null;
47
- const buffer = hasBody ? await response.arrayBuffer() : null;
48
- const headers = new Headers(response.headers);
49
- headers.delete("content-encoding");
50
- headers.delete("content-length");
51
- return new Response(buffer, {
52
- status: response.status,
53
- statusText: response.statusText,
54
- headers
55
- });
56
- } finally {
57
- clearTimeout(timeoutId);
58
- existingSignal?.removeEventListener("abort", onAbort);
59
- }
54
+ const controller = new AbortController();
55
+ const existingSignal = init.signal;
56
+ const onAbort = () => controller.abort(existingSignal.reason);
57
+ if (existingSignal) existingSignal.addEventListener("abort", onAbort);
58
+ const timeoutId = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Request timed out")), config.timeout);
59
+ try {
60
+ const response = await fetchFn(url, {
61
+ ...init,
62
+ signal: controller.signal
63
+ });
64
+ const buffer = response.body !== null ? await response.arrayBuffer() : null;
65
+ const headers = new Headers(response.headers);
66
+ headers.delete("content-encoding");
67
+ headers.delete("content-length");
68
+ return new Response(buffer, {
69
+ status: response.status,
70
+ statusText: response.statusText,
71
+ headers
72
+ });
73
+ } finally {
74
+ clearTimeout(timeoutId);
75
+ existingSignal?.removeEventListener("abort", onAbort);
76
+ }
60
77
  }
78
+ /**
79
+ * 비-OK 응답을 AI SDK의 `APICallError`로 throw한다.
80
+ *
81
+ * - `APICallError`라서 AI SDK의 내장 재시도(`isRetryable`)·에러 분류가 동작한다.
82
+ * - `cause`에 typed `ReoptSDKError`, `data`에 `{ code, diagnostic }`를 실어
83
+ * `sdk.ai.*` 경로와 **동일한 코드/진단**을 노출한다(공유 mapper 사용).
84
+ * 소비처: `err.data?.code`, `err.data?.diagnostic`, `err.cause`(ReoptSDKError).
85
+ */
61
86
  async function throwProviderApiError(response, url, requestBodyValues, requestId) {
62
- const body = await response.json().catch(() => ({}));
63
- const code = body.error?.code;
64
- const message = body.error?.message ?? `HTTP ${response.status}`;
65
- const reoptError = mapHttpStatusToError(response.status, code, message, {
66
- method: "POST",
67
- url,
68
- requestId
69
- });
70
- throw new APICallError({
71
- message: reoptError.message,
72
- url,
73
- requestBodyValues,
74
- statusCode: response.status,
75
- responseHeaders: extractResponseHeaders(response),
76
- responseBody: JSON.stringify(body),
77
- isRetryable: response.status === 429 || response.status >= 500,
78
- data: {
79
- code: reoptError.code,
80
- diagnostic: reoptError.diagnostic,
81
- reoptError
82
- },
83
- cause: reoptError
84
- });
87
+ const body = await response.json().catch(() => ({}));
88
+ const code = body.error?.code;
89
+ const message = body.error?.message ?? `HTTP ${response.status}`;
90
+ const reoptError = mapHttpStatusToError(response.status, code, message, {
91
+ method: "POST",
92
+ url,
93
+ requestId
94
+ });
95
+ throw new APICallError({
96
+ message: reoptError.message,
97
+ url,
98
+ requestBodyValues,
99
+ statusCode: response.status,
100
+ responseHeaders: extractResponseHeaders(response),
101
+ responseBody: JSON.stringify(body),
102
+ isRetryable: response.status === 429 || response.status >= 500,
103
+ data: {
104
+ code: reoptError.code,
105
+ diagnostic: reoptError.diagnostic,
106
+ reoptError
107
+ },
108
+ cause: reoptError
109
+ });
85
110
  }
86
111
  function extractResponseHeaders(response) {
87
- const headers = {};
88
- response.headers.forEach((value, key) => {
89
- headers[key] = value;
90
- });
91
- return headers;
112
+ const headers = {};
113
+ response.headers.forEach((value, key) => {
114
+ headers[key] = value;
115
+ });
116
+ return headers;
92
117
  }
93
118
 
94
- // src/ai-provider/brandapp-image-model.ts
119
+ //#endregion
120
+ //#region src/ai-provider/brandapp-image-model.ts
95
121
  var BrandappImageModel = class {
96
- specificationVersion = "v3";
97
- provider = "brandapp";
98
- modelId;
99
- // BrandApp API emits exactly one image per request. AI SDK honors this by
100
- // calling `doGenerate({ n: 1 })` repeatedly when the caller asks for n>1.
101
- // The `Promise.all(n)` fan-out in `doGenerate` covers direct callers who
102
- // skip the AI SDK layer and pass `n>1` themselves.
103
- maxImagesPerCall = 1;
104
- config;
105
- constructor(modelId, config) {
106
- this.modelId = modelId;
107
- this.config = config;
108
- }
109
- // -----------------------------------------------------------------------
110
- // doGenerate — 이미지 생성
111
- // -----------------------------------------------------------------------
112
- async doGenerate(options) {
113
- const warnings = this.collectWarnings(options);
114
- const brandappOptions = options.providerOptions?.brandapp;
115
- const body = {
116
- prompt: options.prompt,
117
- model: this.modelId,
118
- // providerOptions.brandapp.aspectRatio → top-level aspectRatio → "1:1".
119
- aspectRatio: brandappOptions?.aspectRatio ?? options.aspectRatio ?? "1:1",
120
- customerId: brandappOptions?.customerId ?? this.config.customerId
121
- };
122
- if (brandappOptions?.negativePrompt) {
123
- body.negativePrompt = brandappOptions.negativePrompt;
124
- }
125
- if (brandappOptions?.style) {
126
- body.style = brandappOptions.style;
127
- }
128
- const fetchFn = this.config.fetch ?? globalThis.fetch;
129
- const count = Math.max(1, options.n);
130
- const url = `${this.config.baseUrl}/images/generate`;
131
- const generateOne = async () => {
132
- const requestId = newRequestId(this.config.sdkVersion);
133
- const response = await fetchWithTimeout(this.config, fetchFn, url, {
134
- method: "POST",
135
- headers: mergeProviderHeaders(
136
- buildProviderHeaders(this.config, options.headers),
137
- {
138
- "X-Request-Id": requestId,
139
- "Idempotency-Key": requestId
140
- }
141
- ),
142
- body: JSON.stringify(body),
143
- signal: options.abortSignal
144
- });
145
- if (!response.ok) {
146
- await throwProviderApiError(response, url, body, requestId);
147
- }
148
- const json = await response.json();
149
- const { data } = json;
150
- const imageResponse = await fetchWithTimeout(
151
- this.config,
152
- fetchFn,
153
- data.url,
154
- {
155
- method: "GET",
156
- signal: options.abortSignal
157
- }
158
- );
159
- if (!imageResponse.ok) {
160
- await throwProviderApiError(imageResponse, data.url, body, requestId);
161
- }
162
- const imageBuffer = await imageResponse.arrayBuffer();
163
- const base64 = arrayBufferToBase64(new Uint8Array(imageBuffer));
164
- return {
165
- base64,
166
- meta: {
167
- id: data.id,
168
- url: data.url,
169
- size: data.size,
170
- contentType: data.contentType,
171
- creditCost: data.usage.creditCost,
172
- creditsRemaining: data.creditsRemaining
173
- },
174
- responseHeaders: extractResponseHeaders(response)
175
- };
176
- };
177
- const results = await Promise.all(
178
- Array.from({ length: count }, () => generateOne())
179
- );
180
- const images = results.map((r) => r.base64);
181
- const perImageMetadata = results.map((r) => r.meta);
182
- const lastResponseHeaders = results[results.length - 1]?.responseHeaders;
183
- return {
184
- images,
185
- warnings,
186
- providerMetadata: {
187
- brandapp: {
188
- images: perImageMetadata
189
- }
190
- },
191
- response: {
192
- timestamp: /* @__PURE__ */ new Date(),
193
- modelId: this.modelId,
194
- headers: lastResponseHeaders
195
- }
196
- };
197
- }
198
- // -----------------------------------------------------------------------
199
- // 경고 수집 — 미지원 기능 보고
200
- // -----------------------------------------------------------------------
201
- collectWarnings(options) {
202
- const warnings = [];
203
- if (options.size != null) {
204
- warnings.push({
205
- type: "unsupported",
206
- feature: "size",
207
- details: "BrandApp AI API uses aspectRatio instead of size. Use aspectRatio parameter."
208
- });
209
- }
210
- if (options.seed != null) {
211
- warnings.push({
212
- type: "unsupported",
213
- feature: "seed",
214
- details: "BrandApp AI API does not support seed parameter"
215
- });
216
- }
217
- if (options.files?.length) {
218
- warnings.push({
219
- type: "unsupported",
220
- feature: "files",
221
- details: "BrandApp AI API does not support image editing or variation generation"
222
- });
223
- }
224
- if (options.mask != null) {
225
- warnings.push({
226
- type: "unsupported",
227
- feature: "mask",
228
- details: "BrandApp AI API does not support inpainting masks"
229
- });
230
- }
231
- return warnings;
232
- }
122
+ specificationVersion = "v3";
123
+ provider = "brandapp";
124
+ modelId;
125
+ maxImagesPerCall = 1;
126
+ config;
127
+ constructor(modelId, config) {
128
+ this.modelId = modelId;
129
+ this.config = config;
130
+ }
131
+ async doGenerate(options) {
132
+ const warnings = this.collectWarnings(options);
133
+ const brandappOptions = options.providerOptions?.brandapp;
134
+ const body = {
135
+ prompt: options.prompt,
136
+ model: this.modelId,
137
+ aspectRatio: brandappOptions?.aspectRatio ?? options.aspectRatio ?? "1:1",
138
+ customerId: brandappOptions?.customerId ?? this.config.customerId
139
+ };
140
+ if (brandappOptions?.negativePrompt) body.negativePrompt = brandappOptions.negativePrompt;
141
+ if (brandappOptions?.style) body.style = brandappOptions.style;
142
+ const fetchFn = this.config.fetch ?? globalThis.fetch;
143
+ const count = Math.max(1, options.n);
144
+ const url = `${this.config.baseUrl}/images/generate`;
145
+ const generateOne = async () => {
146
+ const requestId = newRequestId(this.config.sdkVersion);
147
+ const response = await fetchWithTimeout(this.config, fetchFn, url, {
148
+ method: "POST",
149
+ headers: mergeProviderHeaders(buildProviderHeaders(this.config, options.headers), {
150
+ "X-Request-Id": requestId,
151
+ "Idempotency-Key": requestId
152
+ }),
153
+ body: JSON.stringify(body),
154
+ signal: options.abortSignal
155
+ });
156
+ if (!response.ok) await throwProviderApiError(response, url, body, requestId);
157
+ const { data } = await response.json();
158
+ const imageResponse = await fetchWithTimeout(this.config, fetchFn, data.url, {
159
+ method: "GET",
160
+ signal: options.abortSignal
161
+ });
162
+ if (!imageResponse.ok) await throwProviderApiError(imageResponse, data.url, body, requestId);
163
+ const imageBuffer = await imageResponse.arrayBuffer();
164
+ return {
165
+ base64: arrayBufferToBase64(new Uint8Array(imageBuffer)),
166
+ meta: {
167
+ id: data.id,
168
+ url: data.url,
169
+ size: data.size,
170
+ contentType: data.contentType,
171
+ creditCost: data.usage.creditCost,
172
+ creditsRemaining: data.creditsRemaining
173
+ },
174
+ responseHeaders: extractResponseHeaders(response)
175
+ };
176
+ };
177
+ const results = await Promise.all(Array.from({ length: count }, () => generateOne()));
178
+ const images = results.map((r) => r.base64);
179
+ const perImageMetadata = results.map((r) => r.meta);
180
+ const lastResponseHeaders = results[results.length - 1]?.responseHeaders;
181
+ return {
182
+ images,
183
+ warnings,
184
+ providerMetadata: { brandapp: { images: perImageMetadata } },
185
+ response: {
186
+ timestamp: /* @__PURE__ */ new Date(),
187
+ modelId: this.modelId,
188
+ headers: lastResponseHeaders
189
+ }
190
+ };
191
+ }
192
+ collectWarnings(options) {
193
+ const warnings = [];
194
+ if (options.size != null) warnings.push({
195
+ type: "unsupported",
196
+ feature: "size",
197
+ details: "BrandApp AI API uses aspectRatio instead of size. Use aspectRatio parameter."
198
+ });
199
+ if (options.seed != null) warnings.push({
200
+ type: "unsupported",
201
+ feature: "seed",
202
+ details: "BrandApp AI API does not support seed parameter"
203
+ });
204
+ if (options.files?.length) warnings.push({
205
+ type: "unsupported",
206
+ feature: "files",
207
+ details: "BrandApp AI API does not support image editing or variation generation"
208
+ });
209
+ if (options.mask != null) warnings.push({
210
+ type: "unsupported",
211
+ feature: "mask",
212
+ details: "BrandApp AI API does not support inpainting masks"
213
+ });
214
+ return warnings;
215
+ }
233
216
  };
234
217
  function arrayBufferToBase64(bytes) {
235
- const binString = Array.from(bytes, (b) => String.fromCodePoint(b)).join("");
236
- return btoa(binString);
218
+ const binString = Array.from(bytes, (b) => String.fromCodePoint(b)).join("");
219
+ return btoa(binString);
237
220
  }
238
221
 
239
- // src/ai-provider/convert-prompt.ts
222
+ //#endregion
223
+ //#region src/ai-provider/convert-prompt.ts
224
+ /**
225
+ * AI SDK 프롬프트 → BrandApp API 메시지 배열 (+ 손실 변환 보고).
226
+ *
227
+ * BrandApp API는 텍스트 전용이라 비-text part는 손실된다. 무엇이 손실됐는지를
228
+ * `droppedParts`로 돌려줘 호출자(language model)가 `warnings`로 **소리내어** 알리게
229
+ * 한다(과거엔 file/image 입력이 조용히 사라졌다).
230
+ *
231
+ * - system: content 문자열 그대로
232
+ * - user: text part만 추출하여 결합 / file part는 드롭("file" 보고)
233
+ * - assistant: text + tool-call을 텍스트로 표현("tool-call" 보고)
234
+ * - tool: tool-result를 user 메시지 텍스트로 변환("tool-result" 보고)
235
+ */
240
236
  function convertPromptToBrandappMessages(prompt) {
241
- const messages = [];
242
- const dropped = /* @__PURE__ */ new Set();
243
- for (const message of prompt) {
244
- switch (message.role) {
245
- case "system": {
246
- messages.push({ role: "system", content: message.content });
247
- break;
248
- }
249
- case "user": {
250
- const textParts = [];
251
- for (const part of message.content) {
252
- if (part.type === "text") {
253
- textParts.push(part.text);
254
- } else {
255
- dropped.add("file");
256
- }
257
- }
258
- if (textParts.length > 0) {
259
- messages.push({ role: "user", content: textParts.join("\n") });
260
- }
261
- break;
262
- }
263
- case "assistant": {
264
- const textParts = message.content.filter(
265
- (part) => part.type === "text"
266
- ).map((part) => part.text);
267
- const toolCallParts = message.content.filter(
268
- (part) => part.type === "tool-call"
269
- ).map(
270
- (part) => `[Tool Call: ${part.toolName}(${typeof part.input === "string" ? part.input : JSON.stringify(part.input)})]`
271
- );
272
- if (toolCallParts.length > 0) dropped.add("tool-call");
273
- const allText = [...textParts, ...toolCallParts].join("\n");
274
- if (allText.length > 0) {
275
- messages.push({ role: "assistant", content: allText });
276
- }
277
- break;
278
- }
279
- case "tool": {
280
- const resultParts = message.content.filter(
281
- (part) => part.type === "tool-result"
282
- ).map((part) => {
283
- const output = typeof part.output === "string" ? part.output : JSON.stringify(part.output);
284
- return `[Tool Result: ${part.toolName}] ${output}`;
285
- });
286
- if (resultParts.length > 0) {
287
- dropped.add("tool-result");
288
- messages.push({ role: "user", content: resultParts.join("\n") });
289
- }
290
- break;
291
- }
292
- }
293
- }
294
- return { messages, droppedParts: [...dropped] };
237
+ const messages = [];
238
+ const dropped = /* @__PURE__ */ new Set();
239
+ for (const message of prompt) switch (message.role) {
240
+ case "system":
241
+ messages.push({
242
+ role: "system",
243
+ content: message.content
244
+ });
245
+ break;
246
+ case "user": {
247
+ const textParts = [];
248
+ for (const part of message.content) if (part.type === "text") textParts.push(part.text);
249
+ else dropped.add("file");
250
+ if (textParts.length > 0) messages.push({
251
+ role: "user",
252
+ content: textParts.join("\n")
253
+ });
254
+ break;
255
+ }
256
+ case "assistant": {
257
+ const textParts = message.content.filter((part) => part.type === "text").map((part) => part.text);
258
+ const toolCallParts = message.content.filter((part) => part.type === "tool-call").map((part) => `[Tool Call: ${part.toolName}(${typeof part.input === "string" ? part.input : JSON.stringify(part.input)})]`);
259
+ if (toolCallParts.length > 0) dropped.add("tool-call");
260
+ const allText = [...textParts, ...toolCallParts].join("\n");
261
+ if (allText.length > 0) messages.push({
262
+ role: "assistant",
263
+ content: allText
264
+ });
265
+ break;
266
+ }
267
+ case "tool": {
268
+ const resultParts = message.content.filter((part) => part.type === "tool-result").map((part) => {
269
+ const output = typeof part.output === "string" ? part.output : JSON.stringify(part.output);
270
+ return `[Tool Result: ${part.toolName}] ${output}`;
271
+ });
272
+ if (resultParts.length > 0) {
273
+ dropped.add("tool-result");
274
+ messages.push({
275
+ role: "user",
276
+ content: resultParts.join("\n")
277
+ });
278
+ }
279
+ break;
280
+ }
281
+ }
282
+ return {
283
+ messages,
284
+ droppedParts: [...dropped]
285
+ };
295
286
  }
296
287
 
297
- // src/ai-provider/brandapp-language-model.ts
288
+ //#endregion
289
+ //#region src/ai-provider/brandapp-language-model.ts
298
290
  var BrandappLanguageModel = class {
299
- specificationVersion = "v3";
300
- provider = "brandapp";
301
- modelId;
302
- supportedUrls = {};
303
- config;
304
- /** Call-invariant headers, frozen once per model instead of per request. */
305
- baseHeaders;
306
- constructor(modelId, config) {
307
- this.modelId = modelId;
308
- this.config = config;
309
- this.baseHeaders = buildBaseProviderHeaders(config);
310
- }
311
- // -----------------------------------------------------------------------
312
- // doGenerate — Non-streaming
313
- // -----------------------------------------------------------------------
314
- async doGenerate(options) {
315
- const { messages, droppedParts } = convertPromptToBrandappMessages(
316
- options.prompt
317
- );
318
- const warnings = this.collectWarnings(options, droppedParts);
319
- const body = this.buildRequestBody(options, false, messages);
320
- const fetchFn = this.config.fetch ?? globalThis.fetch;
321
- const url = `${this.config.baseUrl}/chat/completions`;
322
- const requestId = newRequestId(this.config.sdkVersion);
323
- const response = await fetchWithTimeout(this.config, fetchFn, url, {
324
- method: "POST",
325
- headers: mergeProviderHeaders(this.baseHeaders, {
326
- ...options.headers,
327
- "X-Request-Id": requestId,
328
- "Idempotency-Key": requestId
329
- }),
330
- body: JSON.stringify(body),
331
- signal: options.abortSignal
332
- });
333
- if (!response.ok) {
334
- await throwProviderApiError(response, url, body, requestId);
335
- }
336
- const json = await response.json();
337
- const { data } = json;
338
- const responseHeaders = extractResponseHeaders(response);
339
- return {
340
- content: [{ type: "text", text: data.message.content }],
341
- // 서버가 finishReason을 보고하면 그대로, 미보고 시 정상 종료(stop)로 폴백.
342
- // raw 키는 LanguageModelV3FinishReason에서 필수 — 명시 제공.
343
- finishReason: data.finishReason ? { unified: data.finishReason.unified, raw: data.finishReason.raw } : { unified: "stop", raw: "stop" },
344
- usage: {
345
- inputTokens: {
346
- total: data.usage.promptTokens,
347
- noCache: void 0,
348
- cacheRead: void 0,
349
- cacheWrite: void 0
350
- },
351
- outputTokens: {
352
- total: data.usage.completionTokens,
353
- text: void 0,
354
- reasoning: void 0
355
- }
356
- },
357
- providerMetadata: {
358
- brandapp: {
359
- creditCost: data.usage.creditCost,
360
- creditsRemaining: data.creditsRemaining,
361
- responseId: data.id
362
- }
363
- },
364
- request: { body },
365
- response: {
366
- headers: responseHeaders,
367
- body: json,
368
- modelId: data.model
369
- },
370
- warnings
371
- };
372
- }
373
- // -----------------------------------------------------------------------
374
- // doStream — SSE Streaming
375
- // -----------------------------------------------------------------------
376
- async doStream(options) {
377
- const { messages, droppedParts } = convertPromptToBrandappMessages(
378
- options.prompt
379
- );
380
- const warnings = this.collectWarnings(options, droppedParts);
381
- const body = this.buildRequestBody(options, true, messages);
382
- const fetchFn = this.config.fetch ?? globalThis.fetch;
383
- const url = `${this.config.baseUrl}/chat/completions`;
384
- const requestId = newRequestId(this.config.sdkVersion);
385
- const managed = createManagedAbort({
386
- timeoutMs: this.config.timeout,
387
- external: options.abortSignal,
388
- idle: true
389
- });
390
- let response;
391
- try {
392
- response = await fetchFn(url, {
393
- method: "POST",
394
- headers: mergeProviderHeaders(this.baseHeaders, {
395
- ...options.headers,
396
- Accept: "text/event-stream",
397
- "X-Request-Id": requestId,
398
- "Idempotency-Key": requestId
399
- }),
400
- body: JSON.stringify(body),
401
- signal: managed.signal
402
- });
403
- } catch (e) {
404
- managed.cleanup();
405
- throw e;
406
- }
407
- if (!response.ok) {
408
- managed.cleanup();
409
- await throwProviderApiError(response, url, body, requestId);
410
- }
411
- const responseHeaders = extractResponseHeaders(response);
412
- if (!response.body) {
413
- managed.cleanup();
414
- throw new Error(
415
- "BrandApp AI API returned no response body for streaming"
416
- );
417
- }
418
- const stream = this.createStreamPartTransform(
419
- response.body,
420
- warnings,
421
- managed,
422
- options.includeRawChunks
423
- );
424
- return {
425
- stream,
426
- request: { body },
427
- response: { headers: responseHeaders }
428
- };
429
- }
430
- // -----------------------------------------------------------------------
431
- // 요청 빌드
432
- // -----------------------------------------------------------------------
433
- buildRequestBody(options, stream, messages) {
434
- const brandappOptions = options.providerOptions?.brandapp;
435
- return {
436
- model: this.modelId,
437
- messages,
438
- maxTokens: options.maxOutputTokens,
439
- temperature: options.temperature,
440
- stream,
441
- customerId: brandappOptions?.customerId ?? this.config.customerId
442
- };
443
- }
444
- // -----------------------------------------------------------------------
445
- // 경고 수집 — 미지원 기능 보고
446
- // -----------------------------------------------------------------------
447
- collectWarnings(options, droppedParts = []) {
448
- const warnings = [];
449
- for (const part of droppedParts) {
450
- warnings.push({
451
- type: "unsupported",
452
- feature: part === "file" ? "image/file input" : part,
453
- details: part === "file" ? "BrandApp AI API\uB294 \uD14D\uC2A4\uD2B8 \uC804\uC6A9\uC785\uB2C8\uB2E4 \u2014 \uC774\uBBF8\uC9C0/\uD30C\uC77C \uC785\uB825\uC740 \uBB34\uC2DC\uB429\uB2C8\uB2E4." : `BrandApp AI API does not support ${part} parts natively; converted to text (lossy).`
454
- });
455
- }
456
- if (options.topP != null) {
457
- warnings.push({
458
- type: "unsupported",
459
- feature: "topP",
460
- details: "BrandApp AI API does not support topP parameter"
461
- });
462
- }
463
- if (options.topK != null) {
464
- warnings.push({
465
- type: "unsupported",
466
- feature: "topK",
467
- details: "BrandApp AI API does not support topK parameter"
468
- });
469
- }
470
- if (options.frequencyPenalty != null) {
471
- warnings.push({
472
- type: "unsupported",
473
- feature: "frequencyPenalty",
474
- details: "BrandApp AI API does not support frequencyPenalty parameter"
475
- });
476
- }
477
- if (options.presencePenalty != null) {
478
- warnings.push({
479
- type: "unsupported",
480
- feature: "presencePenalty",
481
- details: "BrandApp AI API does not support presencePenalty parameter"
482
- });
483
- }
484
- if (options.stopSequences?.length) {
485
- warnings.push({
486
- type: "unsupported",
487
- feature: "stopSequences",
488
- details: "BrandApp AI API does not support stopSequences parameter"
489
- });
490
- }
491
- if (options.responseFormat?.type === "json") {
492
- warnings.push({
493
- type: "unsupported",
494
- feature: "responseFormat",
495
- details: "BrandApp AI API does not support JSON response format directly. Use prompt engineering instead."
496
- });
497
- }
498
- if (options.tools?.length) {
499
- warnings.push({
500
- type: "unsupported",
501
- feature: "tools",
502
- details: "BrandApp AI API does not support tool calling. Tools will be ignored."
503
- });
504
- }
505
- if (options.seed != null) {
506
- warnings.push({
507
- type: "unsupported",
508
- feature: "seed",
509
- details: "BrandApp AI API does not support seed parameter"
510
- });
511
- }
512
- return warnings;
513
- }
514
- // -----------------------------------------------------------------------
515
- // SSE 스트림 파싱 → ReadableStream<LanguageModelV3StreamPart>
516
- // -----------------------------------------------------------------------
517
- createStreamPartTransform(body, warnings, managed, includeRawChunks) {
518
- const decoder = new TextDecoder();
519
- const modelId = this.modelId;
520
- let emittedStreamStart = false;
521
- let emittedTextStart = false;
522
- let emittedTextEnd = false;
523
- let emittedFinish = false;
524
- const textId = "text-0";
525
- function processSSEEvent({ event, data }, controller) {
526
- if (includeRawChunks) {
527
- controller.enqueue({ type: "raw", rawValue: { event, data } });
528
- }
529
- switch (event) {
530
- case "text-delta": {
531
- if (!emittedTextStart) {
532
- controller.enqueue({ type: "text-start", id: textId });
533
- emittedTextStart = true;
534
- }
535
- controller.enqueue({ type: "text-delta", id: textId, delta: data });
536
- break;
537
- }
538
- case "done": {
539
- if (emittedTextStart && !emittedTextEnd) {
540
- controller.enqueue({ type: "text-end", id: textId });
541
- emittedTextEnd = true;
542
- }
543
- try {
544
- const meta = JSON.parse(data);
545
- controller.enqueue({
546
- type: "finish",
547
- usage: {
548
- inputTokens: {
549
- total: meta.usage.promptTokens,
550
- noCache: void 0,
551
- cacheRead: void 0,
552
- cacheWrite: void 0
553
- },
554
- outputTokens: {
555
- total: meta.usage.completionTokens,
556
- text: void 0,
557
- reasoning: void 0
558
- }
559
- },
560
- finishReason: meta.finishReason ? {
561
- unified: meta.finishReason.unified,
562
- raw: meta.finishReason.raw
563
- } : { unified: "stop", raw: "stop" },
564
- providerMetadata: {
565
- brandapp: {
566
- creditCost: meta.usage.creditCost,
567
- creditsRemaining: meta.creditsRemaining
568
- }
569
- }
570
- });
571
- } catch {
572
- controller.enqueue({
573
- type: "finish",
574
- usage: {
575
- inputTokens: {
576
- total: void 0,
577
- noCache: void 0,
578
- cacheRead: void 0,
579
- cacheWrite: void 0
580
- },
581
- outputTokens: {
582
- total: void 0,
583
- text: void 0,
584
- reasoning: void 0
585
- }
586
- },
587
- finishReason: { unified: "stop", raw: "stop" }
588
- });
589
- }
590
- emittedFinish = true;
591
- break;
592
- }
593
- case "error": {
594
- try {
595
- const err = JSON.parse(data);
596
- const mapped = typeof err.status === "number" ? mapHttpStatusToError(err.status, err.code, err.message) : new Error(err.message ?? "Stream error");
597
- controller.enqueue({ type: "error", error: mapped });
598
- } catch {
599
- controller.enqueue({ type: "error", error: new Error(data) });
600
- }
601
- break;
602
- }
603
- }
604
- }
605
- let processor;
606
- return body.pipeThrough(
607
- new TransformStream({
608
- transform(chunk, controller) {
609
- managed.kick();
610
- if (!emittedStreamStart) {
611
- controller.enqueue({ type: "stream-start", warnings });
612
- controller.enqueue({
613
- type: "response-metadata",
614
- timestamp: /* @__PURE__ */ new Date(),
615
- modelId
616
- });
617
- emittedStreamStart = true;
618
- }
619
- if (!processor) {
620
- processor = createSSELineProcessor((sseEvent) => {
621
- processSSEEvent(sseEvent, controller);
622
- });
623
- }
624
- processor.feed(decoder.decode(chunk, { stream: true }));
625
- },
626
- flush(controller) {
627
- managed.cleanup();
628
- if (!emittedStreamStart) {
629
- controller.enqueue({ type: "stream-start", warnings });
630
- }
631
- if (emittedTextStart && !emittedTextEnd) {
632
- controller.enqueue({ type: "text-end", id: textId });
633
- }
634
- if (!emittedFinish) {
635
- controller.enqueue({
636
- type: "finish",
637
- usage: {
638
- inputTokens: {
639
- total: void 0,
640
- noCache: void 0,
641
- cacheRead: void 0,
642
- cacheWrite: void 0
643
- },
644
- outputTokens: {
645
- total: void 0,
646
- text: void 0,
647
- reasoning: void 0
648
- }
649
- },
650
- finishReason: { unified: "error", raw: "incomplete_stream" }
651
- });
652
- }
653
- }
654
- })
655
- );
656
- }
291
+ specificationVersion = "v3";
292
+ provider = "brandapp";
293
+ modelId;
294
+ supportedUrls = {};
295
+ config;
296
+ /** Call-invariant headers, frozen once per model instead of per request. */
297
+ baseHeaders;
298
+ constructor(modelId, config) {
299
+ this.modelId = modelId;
300
+ this.config = config;
301
+ this.baseHeaders = buildBaseProviderHeaders(config);
302
+ }
303
+ async doGenerate(options) {
304
+ const { messages, droppedParts } = convertPromptToBrandappMessages(options.prompt);
305
+ const warnings = this.collectWarnings(options, droppedParts);
306
+ const body = this.buildRequestBody(options, false, messages);
307
+ const fetchFn = this.config.fetch ?? globalThis.fetch;
308
+ const url = `${this.config.baseUrl}/chat/completions`;
309
+ const requestId = newRequestId(this.config.sdkVersion);
310
+ const response = await fetchWithTimeout(this.config, fetchFn, url, {
311
+ method: "POST",
312
+ headers: mergeProviderHeaders(this.baseHeaders, {
313
+ ...options.headers,
314
+ "X-Request-Id": requestId,
315
+ "Idempotency-Key": requestId
316
+ }),
317
+ body: JSON.stringify(body),
318
+ signal: options.abortSignal
319
+ });
320
+ if (!response.ok) await throwProviderApiError(response, url, body, requestId);
321
+ const json = await response.json();
322
+ const { data } = json;
323
+ const responseHeaders = extractResponseHeaders(response);
324
+ return {
325
+ content: [{
326
+ type: "text",
327
+ text: data.message.content
328
+ }],
329
+ finishReason: data.finishReason ? {
330
+ unified: data.finishReason.unified,
331
+ raw: data.finishReason.raw
332
+ } : {
333
+ unified: "stop",
334
+ raw: "stop"
335
+ },
336
+ usage: {
337
+ inputTokens: {
338
+ total: data.usage.promptTokens,
339
+ noCache: void 0,
340
+ cacheRead: void 0,
341
+ cacheWrite: void 0
342
+ },
343
+ outputTokens: {
344
+ total: data.usage.completionTokens,
345
+ text: void 0,
346
+ reasoning: void 0
347
+ }
348
+ },
349
+ providerMetadata: { brandapp: {
350
+ creditCost: data.usage.creditCost,
351
+ creditsRemaining: data.creditsRemaining,
352
+ responseId: data.id
353
+ } },
354
+ request: { body },
355
+ response: {
356
+ headers: responseHeaders,
357
+ body: json,
358
+ modelId: data.model
359
+ },
360
+ warnings
361
+ };
362
+ }
363
+ async doStream(options) {
364
+ const { messages, droppedParts } = convertPromptToBrandappMessages(options.prompt);
365
+ const warnings = this.collectWarnings(options, droppedParts);
366
+ const body = this.buildRequestBody(options, true, messages);
367
+ const fetchFn = this.config.fetch ?? globalThis.fetch;
368
+ const url = `${this.config.baseUrl}/chat/completions`;
369
+ const requestId = newRequestId(this.config.sdkVersion);
370
+ const managed = createManagedAbort({
371
+ timeoutMs: this.config.timeout,
372
+ external: options.abortSignal,
373
+ idle: true
374
+ });
375
+ let response;
376
+ try {
377
+ response = await fetchFn(url, {
378
+ method: "POST",
379
+ headers: mergeProviderHeaders(this.baseHeaders, {
380
+ ...options.headers,
381
+ Accept: "text/event-stream",
382
+ "X-Request-Id": requestId,
383
+ "Idempotency-Key": requestId
384
+ }),
385
+ body: JSON.stringify(body),
386
+ signal: managed.signal
387
+ });
388
+ } catch (e) {
389
+ managed.cleanup();
390
+ throw e;
391
+ }
392
+ if (!response.ok) {
393
+ managed.cleanup();
394
+ await throwProviderApiError(response, url, body, requestId);
395
+ }
396
+ const responseHeaders = extractResponseHeaders(response);
397
+ if (!response.body) {
398
+ managed.cleanup();
399
+ throw new Error("BrandApp AI API returned no response body for streaming");
400
+ }
401
+ return {
402
+ stream: this.createStreamPartTransform(response.body, warnings, managed, options.includeRawChunks),
403
+ request: { body },
404
+ response: { headers: responseHeaders }
405
+ };
406
+ }
407
+ buildRequestBody(options, stream, messages) {
408
+ const brandappOptions = options.providerOptions?.brandapp;
409
+ return {
410
+ model: this.modelId,
411
+ messages,
412
+ maxTokens: options.maxOutputTokens,
413
+ temperature: options.temperature,
414
+ stream,
415
+ customerId: brandappOptions?.customerId ?? this.config.customerId
416
+ };
417
+ }
418
+ collectWarnings(options, droppedParts = []) {
419
+ const warnings = [];
420
+ for (const part of droppedParts) warnings.push({
421
+ type: "unsupported",
422
+ feature: part === "file" ? "image/file input" : part,
423
+ details: part === "file" ? "BrandApp AI API는 텍스트 전용입니다 — 이미지/파일 입력은 무시됩니다." : `BrandApp AI API does not support ${part} parts natively; converted to text (lossy).`
424
+ });
425
+ if (options.topP != null) warnings.push({
426
+ type: "unsupported",
427
+ feature: "topP",
428
+ details: "BrandApp AI API does not support topP parameter"
429
+ });
430
+ if (options.topK != null) warnings.push({
431
+ type: "unsupported",
432
+ feature: "topK",
433
+ details: "BrandApp AI API does not support topK parameter"
434
+ });
435
+ if (options.frequencyPenalty != null) warnings.push({
436
+ type: "unsupported",
437
+ feature: "frequencyPenalty",
438
+ details: "BrandApp AI API does not support frequencyPenalty parameter"
439
+ });
440
+ if (options.presencePenalty != null) warnings.push({
441
+ type: "unsupported",
442
+ feature: "presencePenalty",
443
+ details: "BrandApp AI API does not support presencePenalty parameter"
444
+ });
445
+ if (options.stopSequences?.length) warnings.push({
446
+ type: "unsupported",
447
+ feature: "stopSequences",
448
+ details: "BrandApp AI API does not support stopSequences parameter"
449
+ });
450
+ if (options.responseFormat?.type === "json") warnings.push({
451
+ type: "unsupported",
452
+ feature: "responseFormat",
453
+ details: "BrandApp AI API does not support JSON response format directly. Use prompt engineering instead."
454
+ });
455
+ if (options.tools?.length) warnings.push({
456
+ type: "unsupported",
457
+ feature: "tools",
458
+ details: "BrandApp AI API does not support tool calling. Tools will be ignored."
459
+ });
460
+ if (options.seed != null) warnings.push({
461
+ type: "unsupported",
462
+ feature: "seed",
463
+ details: "BrandApp AI API does not support seed parameter"
464
+ });
465
+ return warnings;
466
+ }
467
+ createStreamPartTransform(body, warnings, managed, includeRawChunks) {
468
+ const decoder = new TextDecoder();
469
+ const modelId = this.modelId;
470
+ let emittedStreamStart = false;
471
+ let emittedTextStart = false;
472
+ let emittedTextEnd = false;
473
+ let emittedFinish = false;
474
+ const textId = "text-0";
475
+ function processSSEEvent({ event, data }, controller) {
476
+ if (includeRawChunks) controller.enqueue({
477
+ type: "raw",
478
+ rawValue: {
479
+ event,
480
+ data
481
+ }
482
+ });
483
+ switch (event) {
484
+ case "text-delta":
485
+ if (!emittedTextStart) {
486
+ controller.enqueue({
487
+ type: "text-start",
488
+ id: textId
489
+ });
490
+ emittedTextStart = true;
491
+ }
492
+ controller.enqueue({
493
+ type: "text-delta",
494
+ id: textId,
495
+ delta: data
496
+ });
497
+ break;
498
+ case "done":
499
+ if (emittedTextStart && !emittedTextEnd) {
500
+ controller.enqueue({
501
+ type: "text-end",
502
+ id: textId
503
+ });
504
+ emittedTextEnd = true;
505
+ }
506
+ try {
507
+ const meta = JSON.parse(data);
508
+ controller.enqueue({
509
+ type: "finish",
510
+ usage: {
511
+ inputTokens: {
512
+ total: meta.usage.promptTokens,
513
+ noCache: void 0,
514
+ cacheRead: void 0,
515
+ cacheWrite: void 0
516
+ },
517
+ outputTokens: {
518
+ total: meta.usage.completionTokens,
519
+ text: void 0,
520
+ reasoning: void 0
521
+ }
522
+ },
523
+ finishReason: meta.finishReason ? {
524
+ unified: meta.finishReason.unified,
525
+ raw: meta.finishReason.raw
526
+ } : {
527
+ unified: "stop",
528
+ raw: "stop"
529
+ },
530
+ providerMetadata: { brandapp: {
531
+ creditCost: meta.usage.creditCost,
532
+ creditsRemaining: meta.creditsRemaining
533
+ } }
534
+ });
535
+ } catch {
536
+ controller.enqueue({
537
+ type: "finish",
538
+ usage: {
539
+ inputTokens: {
540
+ total: void 0,
541
+ noCache: void 0,
542
+ cacheRead: void 0,
543
+ cacheWrite: void 0
544
+ },
545
+ outputTokens: {
546
+ total: void 0,
547
+ text: void 0,
548
+ reasoning: void 0
549
+ }
550
+ },
551
+ finishReason: {
552
+ unified: "stop",
553
+ raw: "stop"
554
+ }
555
+ });
556
+ }
557
+ emittedFinish = true;
558
+ break;
559
+ case "error":
560
+ try {
561
+ const err = JSON.parse(data);
562
+ const mapped = typeof err.status === "number" ? mapHttpStatusToError(err.status, err.code, err.message) : new Error(err.message ?? "Stream error");
563
+ controller.enqueue({
564
+ type: "error",
565
+ error: mapped
566
+ });
567
+ } catch {
568
+ controller.enqueue({
569
+ type: "error",
570
+ error: new Error(data)
571
+ });
572
+ }
573
+ break;
574
+ }
575
+ }
576
+ let processor;
577
+ return body.pipeThrough(new TransformStream({
578
+ transform(chunk, controller) {
579
+ managed.kick();
580
+ if (!emittedStreamStart) {
581
+ controller.enqueue({
582
+ type: "stream-start",
583
+ warnings
584
+ });
585
+ controller.enqueue({
586
+ type: "response-metadata",
587
+ timestamp: /* @__PURE__ */ new Date(),
588
+ modelId
589
+ });
590
+ emittedStreamStart = true;
591
+ }
592
+ if (!processor) processor = createSSELineProcessor((sseEvent) => {
593
+ processSSEEvent(sseEvent, controller);
594
+ });
595
+ processor.feed(decoder.decode(chunk, { stream: true }));
596
+ },
597
+ flush(controller) {
598
+ managed.cleanup();
599
+ if (!emittedStreamStart) controller.enqueue({
600
+ type: "stream-start",
601
+ warnings
602
+ });
603
+ if (emittedTextStart && !emittedTextEnd) controller.enqueue({
604
+ type: "text-end",
605
+ id: textId
606
+ });
607
+ if (!emittedFinish) controller.enqueue({
608
+ type: "finish",
609
+ usage: {
610
+ inputTokens: {
611
+ total: void 0,
612
+ noCache: void 0,
613
+ cacheRead: void 0,
614
+ cacheWrite: void 0
615
+ },
616
+ outputTokens: {
617
+ total: void 0,
618
+ text: void 0,
619
+ reasoning: void 0
620
+ }
621
+ },
622
+ finishReason: {
623
+ unified: "error",
624
+ raw: "incomplete_stream"
625
+ }
626
+ });
627
+ }
628
+ }));
629
+ }
657
630
  };
658
631
 
659
- // src/ai-provider/index.ts
632
+ //#endregion
633
+ //#region src/ai-provider/index.ts
634
+ /**
635
+ * BrandApp AI SDK Provider
636
+ *
637
+ * Vercel AI SDK와 호환되는 커스텀 프로바이더를 생성합니다.
638
+ *
639
+ * **지원**: `generateText()`, `streamText()` (텍스트 생성), `generateImage()`
640
+ * (이미지 생성), `providerMetadata.brandapp`(크레딧/사용량), `providerOptions.brandapp`.
641
+ *
642
+ * **미지원** (호출 시 `warnings`로 알리고 해당 부분은 무시됨): tool/function calling,
643
+ * 구조화 출력(`generateObject`/`responseFormat: json`), 비전·파일 입력, `topP`/`topK`/
644
+ * `frequencyPenalty`/`presencePenalty`/`stopSequences`/`seed`. BrandApp AI API는 멀티
645
+ * 테넌트 안전을 위해 텍스트·이미지 표면만 노출한다. 임베딩/음성/전사 모델은 없다
646
+ * (`NoSuchModelError`).
647
+ *
648
+ * @example
649
+ * ```ts
650
+ * import { createBrandappProvider } from "@reopt-ai/brandapp-sdk/ai-provider";
651
+ * import { generateText, streamText } from "ai";
652
+ *
653
+ * const brandapp = createBrandappProvider({
654
+ * clientId: process.env.BRANDAPP_CLIENT_ID!,
655
+ * clientSecret: process.env.BRANDAPP_CLIENT_SECRET!,
656
+ * brandappId: process.env.BRANDAPP_ID!,
657
+ * });
658
+ *
659
+ * // Non-streaming
660
+ * const { text } = await generateText({
661
+ * model: brandapp("anthropic/claude-haiku-4.5"),
662
+ * prompt: "안녕하세요",
663
+ * });
664
+ *
665
+ * // Streaming
666
+ * const result = streamText({
667
+ * model: brandapp("zai/glm-4.7-flash"),
668
+ * prompt: "Hello, world!",
669
+ * });
670
+ *
671
+ * for await (const chunk of result.textStream) {
672
+ * process.stdout.write(chunk);
673
+ * }
674
+ *
675
+ * // BrandApp 전용 메타데이터 접근
676
+ * const { text, providerMetadata } = await generateText({
677
+ * model: brandapp("anthropic/claude-haiku-4.5"),
678
+ * prompt: "Hello",
679
+ * });
680
+ * console.log(providerMetadata?.brandapp?.creditCost);
681
+ * console.log(providerMetadata?.brandapp?.creditsRemaining);
682
+ *
683
+ * // customerId를 providerOptions로 전달
684
+ * const { text } = await generateText({
685
+ * model: brandapp("anthropic/claude-haiku-4.5"),
686
+ * prompt: "Hello",
687
+ * providerOptions: {
688
+ * brandapp: { customerId: "customer-uuid" },
689
+ * },
690
+ * });
691
+ *
692
+ * // Image generation
693
+ * const { images } = await generateImage({
694
+ * model: brandapp.imageModel("google/gemini-2.5-flash-image"),
695
+ * prompt: "A cat sitting on a windowsill",
696
+ * });
697
+ * ```
698
+ */
699
+ /**
700
+ * BrandApp AI SDK 프로바이더를 생성합니다.
701
+ *
702
+ * 반환된 함수는 모델 ID를 받아 LanguageModelV3 인스턴스를 반환합니다.
703
+ * AI SDK의 generateText(), streamText() 등에서 model 파라미터로 사용합니다.
704
+ *
705
+ * @example
706
+ * ```ts
707
+ * const brandapp = createBrandappProvider({ clientId, clientSecret, brandappId });
708
+ *
709
+ * // 함수 호출로 모델 인스턴스 생성
710
+ * const model = brandapp("anthropic/claude-haiku-4.5");
711
+ *
712
+ * // AI SDK 함수에 전달
713
+ * const { text } = await generateText({ model, prompt: "Hello" });
714
+ * ```
715
+ */
660
716
  function createBrandappProvider(config) {
661
- assertBrowserSafe(config);
662
- const sdkConfig = {
663
- clientId: config.clientId,
664
- clientSecret: config.clientSecret,
665
- brandappId: config.brandappId,
666
- token: config.token,
667
- isProduction: config.isProduction,
668
- baseUrl: config.baseUrl
669
- };
670
- validateConfig(sdkConfig);
671
- const baseUrl = resolveBaseUrl(sdkConfig) + `/api/v1/brandapp/${config.brandappId}/ai`;
672
- const modelConfig = {
673
- baseUrl,
674
- authHeader: createAuthHeader(sdkConfig),
675
- timeout: config.timeout ?? 6e4,
676
- sdkVersion: SDK_VERSION,
677
- customerId: config.customerId,
678
- fetch: config.fetch
679
- };
680
- const languageModelCache = /* @__PURE__ */ new Map();
681
- const imageModelCache = /* @__PURE__ */ new Map();
682
- function provider(modelId) {
683
- let model = languageModelCache.get(modelId);
684
- if (!model) {
685
- model = new BrandappLanguageModel(modelId, modelConfig);
686
- languageModelCache.set(modelId, model);
687
- }
688
- return model;
689
- }
690
- provider.specificationVersion = "v3";
691
- provider.languageModel = provider;
692
- provider.imageModel = (modelId) => {
693
- let model = imageModelCache.get(modelId);
694
- if (!model) {
695
- model = new BrandappImageModel(modelId, modelConfig);
696
- imageModelCache.set(modelId, model);
697
- }
698
- return model;
699
- };
700
- provider.embeddingModel = (modelId) => {
701
- throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
702
- };
703
- provider.textEmbeddingModel = (modelId) => {
704
- throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
705
- };
706
- provider.transcriptionModel = (modelId) => {
707
- throw new NoSuchModelError({ modelId, modelType: "transcriptionModel" });
708
- };
709
- provider.speechModel = (modelId) => {
710
- throw new NoSuchModelError({ modelId, modelType: "speechModel" });
711
- };
712
- return provider;
717
+ assertBrowserSafe(config);
718
+ const sdkConfig = {
719
+ clientId: config.clientId,
720
+ clientSecret: config.clientSecret,
721
+ brandappId: config.brandappId,
722
+ token: config.token,
723
+ isProduction: config.isProduction,
724
+ baseUrl: config.baseUrl
725
+ };
726
+ validateConfig(sdkConfig);
727
+ const modelConfig = {
728
+ baseUrl: resolveBaseUrl(sdkConfig) + `/api/v1/brandapp/${config.brandappId}/ai`,
729
+ authHeader: createAuthHeader(sdkConfig),
730
+ timeout: config.timeout ?? 6e4,
731
+ sdkVersion: SDK_VERSION,
732
+ customerId: config.customerId,
733
+ fetch: config.fetch
734
+ };
735
+ const languageModelCache = /* @__PURE__ */ new Map();
736
+ const imageModelCache = /* @__PURE__ */ new Map();
737
+ function provider(modelId) {
738
+ let model = languageModelCache.get(modelId);
739
+ if (!model) {
740
+ model = new BrandappLanguageModel(modelId, modelConfig);
741
+ languageModelCache.set(modelId, model);
742
+ }
743
+ return model;
744
+ }
745
+ provider.specificationVersion = "v3";
746
+ provider.languageModel = provider;
747
+ provider.imageModel = (modelId) => {
748
+ let model = imageModelCache.get(modelId);
749
+ if (!model) {
750
+ model = new BrandappImageModel(modelId, modelConfig);
751
+ imageModelCache.set(modelId, model);
752
+ }
753
+ return model;
754
+ };
755
+ provider.embeddingModel = (modelId) => {
756
+ throw new NoSuchModelError({
757
+ modelId,
758
+ modelType: "embeddingModel"
759
+ });
760
+ };
761
+ provider.textEmbeddingModel = (modelId) => {
762
+ throw new NoSuchModelError({
763
+ modelId,
764
+ modelType: "embeddingModel"
765
+ });
766
+ };
767
+ provider.transcriptionModel = (modelId) => {
768
+ throw new NoSuchModelError({
769
+ modelId,
770
+ modelType: "transcriptionModel"
771
+ });
772
+ };
773
+ provider.speechModel = (modelId) => {
774
+ throw new NoSuchModelError({
775
+ modelId,
776
+ modelType: "speechModel"
777
+ });
778
+ };
779
+ return provider;
713
780
  }
714
781
 
782
+ //#endregion
715
783
  export { BrandappImageModel, BrandappLanguageModel, createBrandappProvider };
716
- //# sourceMappingURL=index.js.map
717
784
  //# sourceMappingURL=index.js.map