@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
@@ -0,0 +1,264 @@
1
+ import { a as resolveIdBaseUrl, x as ReoptSDKError } from "../config-Cw0a3-C8.js";
2
+
3
+ //#region src/logout/verify.ts
4
+ /**
5
+ * OIDC Back-Channel Logout 1.0 — logout_token 검증 (수신 측).
6
+ *
7
+ * reopt(IdP)가 IdP 세션 폐기 시 등록된 RP의 backchannel_logout_uri로 POST하는
8
+ * logout_token(EdDSA JWT)을 검증한다. 검증에 성공하면 `{ sid, sub }`를 반환하고,
9
+ * 실패하면 ReoptSDKError를 던진다.
10
+ *
11
+ * 서명 검증은 **Web Crypto(Ed25519)** 로 하며 외부 의존이 없다 — reopt jwks_uri의
12
+ * 공개키(OKP/Ed25519)를 fetch해 검증한다. reopt jwt 플러그인은 EdDSA로 서명하며
13
+ * (기본값, keyPairConfig 미지정), 프로덕션 `id.reopt.ai/api/auth/jwks`가 실제로
14
+ * `alg:EdDSA, kty:OKP, crv:Ed25519`를 노출함을 확인했다(2026-07-24). ⚠️ Ed25519
15
+ * Web Crypto는 Node 20+ · 최신 브라우저 · Deno · Cloudflare Workers에서 지원된다
16
+ * (back-channel 수신은 서버 사이드라 Node 20+ 환경이면 충분).
17
+ *
18
+ * 스펙 §2.6 검증 규칙 전부 적용: 서명·iss·aud·iat·events·(sid|sub)·nonce 금지.
19
+ */
20
+ const BACKCHANNEL_LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
21
+ /** JWKS 캐시 TTL — 키 로테이션과 조회 비용의 절충. 검증 실패 시 강제 refetch도 있음. */
22
+ const JWKS_CACHE_TTL_MS = 600 * 1e3;
23
+ /** logout_token iat 허용 나이 — 지연 전달·시계 편차를 감안. */
24
+ const DEFAULT_MAX_TOKEN_AGE_MS = 300 * 1e3;
25
+ /**
26
+ * discovery/JWKS fetch 타임아웃. back-channel 엔드포인트는 공개(무인증)라, 느린
27
+ * IdP로의 무한 fetch가 요청 핸들러를 붙잡지 못하게 상한을 둔다(fail-closed).
28
+ */
29
+ const VERIFICATION_FETCH_TIMEOUT_MS = 5 * 1e3;
30
+ /**
31
+ * jwks_uri별 *강제* refetch 최소 간격. 서명 불일치는 강제 refetch(키 로테이션 대응)를
32
+ * 부르는데, 이 스로틀이 위조 토큰 폭주가 공유 JWKS 엔드포인트로 부하를 반사시키는 것을
33
+ * 막는다. 초기 캐시 채우기 fetch(forceRefresh=false)는 이 창에 포함되지 않으므로, 실제
34
+ * 로테이션은 단일 검증 안에서 여전히 복구된다.
35
+ */
36
+ const JWKS_MIN_FORCED_REFETCH_INTERVAL_MS = 30 * 1e3;
37
+ const jwksCache = /* @__PURE__ */ new Map();
38
+ const jwksInflight = /* @__PURE__ */ new Map();
39
+ const jwksLastForcedRefetch = /* @__PURE__ */ new Map();
40
+ const discoveryCache = /* @__PURE__ */ new Map();
41
+ function base64UrlDecode(input) {
42
+ const base64 = (input + (input.length % 4 === 0 ? "" : "=".repeat(4 - input.length % 4))).replace(/-/g, "+").replace(/_/g, "/");
43
+ const binary = atob(base64);
44
+ const bytes = new Uint8Array(binary.length);
45
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
46
+ return bytes;
47
+ }
48
+ function decodeJson(segment) {
49
+ return JSON.parse(new TextDecoder().decode(base64UrlDecode(segment)));
50
+ }
51
+ function fail(message, cause) {
52
+ throw new ReoptSDKError(message, 400, "invalid_logout_token", void 0, {
53
+ cause,
54
+ fix: "reopt가 보낸 logout_token만 이 핸들러로 전달되는지, client_id·idBaseUrl 설정이 맞는지 확인하세요.",
55
+ doc: "logout.md"
56
+ });
57
+ }
58
+ /**
59
+ * 검증 *인프라*(discovery/JWKS)가 일시적으로 불가한 경우 — 토큰이 잘못된 게 아니다.
60
+ * 500대(retryable)로 던져, 핸들러가 IdP에 재시도 가능 응답(503)을 주게 한다. 이는
61
+ * 스펙 §2.8의 "처리 실패"에 해당하며, 정상 토큰을 400(영구 거부)으로 오분류하지 않는다.
62
+ */
63
+ function failUnavailable(message, cause) {
64
+ throw new ReoptSDKError(message, 503, "logout_verification_unavailable", void 0, {
65
+ cause,
66
+ fix: "reopt IdP의 discovery/JWKS 엔드포인트가 일시적으로 응답하지 않습니다. 잠시 후 재시도하세요.",
67
+ doc: "logout.md"
68
+ });
69
+ }
70
+ async function fetchDiscovery(idBaseUrl) {
71
+ const cached = discoveryCache.get(idBaseUrl);
72
+ if (cached && Date.now() - cached.fetchedAt < JWKS_CACHE_TTL_MS) return {
73
+ issuer: cached.issuer,
74
+ jwksUri: cached.jwksUri
75
+ };
76
+ const discoveryUrl = `${idBaseUrl}/api/auth/.well-known/openid-configuration`;
77
+ let res;
78
+ try {
79
+ res = await fetch(discoveryUrl, {
80
+ cache: "no-store",
81
+ signal: AbortSignal.timeout(VERIFICATION_FETCH_TIMEOUT_MS)
82
+ });
83
+ } catch (error) {
84
+ failUnavailable("OIDC discovery를 불러오지 못했습니다.", `discovery fetch 실패: ${String(error)}`);
85
+ }
86
+ if (!res.ok) failUnavailable("OIDC discovery 응답이 올바르지 않습니다.", `discovery HTTP ${res.status}`);
87
+ const doc = await res.json();
88
+ if (!doc.issuer || !doc.jwks_uri) failUnavailable("OIDC discovery에 issuer/jwks_uri가 없습니다.", "discovery 필드 누락");
89
+ discoveryCache.set(idBaseUrl, {
90
+ issuer: doc.issuer,
91
+ jwksUri: doc.jwks_uri,
92
+ fetchedAt: Date.now()
93
+ });
94
+ return {
95
+ issuer: doc.issuer,
96
+ jwksUri: doc.jwks_uri
97
+ };
98
+ }
99
+ async function fetchJwks(jwksUri, forceRefresh) {
100
+ const cached = jwksCache.get(jwksUri);
101
+ const now = Date.now();
102
+ if (!forceRefresh && cached && now - cached.fetchedAt < JWKS_CACHE_TTL_MS) return cached.keys;
103
+ const inflight = jwksInflight.get(jwksUri);
104
+ if (inflight) return inflight;
105
+ if (forceRefresh && cached) {
106
+ if (now - (jwksLastForcedRefetch.get(jwksUri) ?? 0) < JWKS_MIN_FORCED_REFETCH_INTERVAL_MS) return cached.keys;
107
+ }
108
+ if (forceRefresh) jwksLastForcedRefetch.set(jwksUri, now);
109
+ const promise = fetchJwksUncached(jwksUri).finally(() => {
110
+ jwksInflight.delete(jwksUri);
111
+ });
112
+ jwksInflight.set(jwksUri, promise);
113
+ return promise;
114
+ }
115
+ async function fetchJwksUncached(jwksUri) {
116
+ let res;
117
+ try {
118
+ res = await fetch(jwksUri, {
119
+ cache: "no-store",
120
+ signal: AbortSignal.timeout(VERIFICATION_FETCH_TIMEOUT_MS)
121
+ });
122
+ } catch (error) {
123
+ failUnavailable("JWKS를 불러오지 못했습니다.", `jwks fetch 실패: ${String(error)}`);
124
+ }
125
+ if (!res.ok) failUnavailable("JWKS 응답이 올바르지 않습니다.", `jwks HTTP ${res.status}`);
126
+ const keys = ((await res.json()).keys ?? []).filter((k) => k.kty === "OKP" && k.crv === "Ed25519" && typeof k.x === "string");
127
+ jwksCache.set(jwksUri, {
128
+ keys,
129
+ fetchedAt: Date.now(),
130
+ jwksUri
131
+ });
132
+ return keys;
133
+ }
134
+ async function verifyEd25519(jwk, signingInput, signature) {
135
+ try {
136
+ const key = await crypto.subtle.importKey("jwk", {
137
+ kty: jwk.kty,
138
+ crv: jwk.crv,
139
+ x: jwk.x
140
+ }, { name: "Ed25519" }, false, ["verify"]);
141
+ return await crypto.subtle.verify({ name: "Ed25519" }, key, signature, new TextEncoder().encode(signingInput));
142
+ } catch {
143
+ return false;
144
+ }
145
+ }
146
+ /**
147
+ * logout_token을 검증하고 폐기 대상 클레임(sid·sub)을 반환한다.
148
+ * 검증 실패는 ReoptSDKError(400, invalid_logout_token)로 던진다.
149
+ */
150
+ async function verifyBackchannelLogoutToken(logoutToken, options = {}) {
151
+ const config = options.config ?? {};
152
+ const clientId = options.clientId ?? config.clientId ?? (typeof process !== "undefined" ? process.env?.BRANDAPP_CLIENT_ID : void 0);
153
+ if (!clientId) fail("client_id가 필요합니다.", "clientId 미설정 — options.clientId 또는 BRANDAPP_CLIENT_ID env 필요");
154
+ const idBaseUrl = (options.idBaseUrl ?? resolveIdBaseUrl(config)).replace(/\/$/, "");
155
+ const parts = logoutToken.split(".");
156
+ if (parts.length !== 3) fail("logout_token 형식이 올바르지 않습니다.", "JWT 세그먼트 개수 오류");
157
+ const [headerB64, payloadB64, sigB64] = parts;
158
+ let header;
159
+ let payload;
160
+ try {
161
+ header = decodeJson(headerB64);
162
+ payload = decodeJson(payloadB64);
163
+ } catch {
164
+ fail("logout_token 디코드에 실패했습니다.", "base64url/JSON 파싱 오류");
165
+ }
166
+ if (header.alg !== "EdDSA") fail("지원하지 않는 서명 알고리즘입니다.", `alg=${header.alg ?? "none"} (EdDSA만 허용)`);
167
+ const { issuer, jwksUri } = await fetchDiscovery(idBaseUrl);
168
+ const signature = base64UrlDecode(sigB64);
169
+ const signingInput = `${headerB64}.${payloadB64}`;
170
+ const tryVerify = async (forceRefresh) => {
171
+ const keys = await fetchJwks(jwksUri, forceRefresh);
172
+ const candidates = header.kid ? keys.filter((k) => k.kid === header.kid) : keys;
173
+ const pool = candidates.length > 0 ? candidates : keys;
174
+ for (const jwk of pool) if (await verifyEd25519(jwk, signingInput, signature)) return true;
175
+ return false;
176
+ };
177
+ let verified = await tryVerify(false);
178
+ if (!verified) verified = await tryVerify(true);
179
+ if (!verified) fail("logout_token 서명 검증에 실패했습니다.", "서명 불일치 또는 키 없음");
180
+ if (payload.iss !== issuer) fail("issuer가 일치하지 않습니다.", `iss=${payload.iss} != ${issuer}`);
181
+ const aud = Array.isArray(payload.aud) ? payload.aud : payload.aud ? [payload.aud] : [];
182
+ if (!aud.includes(clientId)) fail("audience가 일치하지 않습니다.", "aud에 client_id 없음");
183
+ if (typeof payload.iat !== "number") fail("iat가 없습니다.", "iat 클레임 누락");
184
+ const maxAge = options.maxTokenAgeMs ?? DEFAULT_MAX_TOKEN_AGE_MS;
185
+ if (Date.now() - payload.iat * 1e3 > maxAge) fail("logout_token이 만료되었습니다.", "iat가 허용 나이를 초과");
186
+ if (payload.exp && Date.now() > payload.exp * 1e3) fail("logout_token이 만료되었습니다(exp).", "exp 경과");
187
+ if (payload.nonce !== void 0) fail("logout_token에 nonce가 있으면 안 됩니다.", "nonce 클레임 존재");
188
+ if (!(!!payload.events && Object.prototype.hasOwnProperty.call(payload.events, BACKCHANNEL_LOGOUT_EVENT))) fail("back-channel logout 이벤트가 없습니다.", "events에 backchannel-logout 멤버 없음");
189
+ if (!payload.sid && !payload.sub) fail("sid 또는 sub가 필요합니다.", "sid/sub 모두 없음");
190
+ if (!payload.sid) fail("sid가 없습니다.", "reopt logout_token은 sid 필수");
191
+ return {
192
+ sid: payload.sid,
193
+ sub: payload.sub,
194
+ iss: issuer,
195
+ aud
196
+ };
197
+ }
198
+ /** 테스트·장수명 프로세스용 — JWKS/discovery 캐시와 refetch 스로틀 상태를 비운다. */
199
+ function clearLogoutTokenCaches() {
200
+ jwksCache.clear();
201
+ jwksInflight.clear();
202
+ jwksLastForcedRefetch.clear();
203
+ discoveryCache.clear();
204
+ }
205
+
206
+ //#endregion
207
+ //#region src/logout/handler.ts
208
+ /** OIDC Back-Channel Logout 응답은 캐시 금지가 스펙 요구. */
209
+ function response(body, status) {
210
+ return new Response(JSON.stringify(body), {
211
+ status,
212
+ headers: {
213
+ "Content-Type": "application/json",
214
+ "Cache-Control": "no-store"
215
+ }
216
+ });
217
+ }
218
+ function createBackchannelLogoutHandler(config) {
219
+ return async (request) => {
220
+ if (request.method !== "POST") return response({ error: "Method not allowed" }, 405);
221
+ let logoutToken = null;
222
+ try {
223
+ const value = (await request.formData()).get("logout_token");
224
+ logoutToken = typeof value === "string" ? value : null;
225
+ } catch {
226
+ return response({ error: "invalid_request" }, 400);
227
+ }
228
+ if (!logoutToken) return response({ error: "invalid_request" }, 400);
229
+ let claims;
230
+ try {
231
+ claims = await verifyBackchannelLogoutToken(logoutToken, {
232
+ clientId: config.clientId,
233
+ idBaseUrl: config.idBaseUrl,
234
+ config: config.config,
235
+ maxTokenAgeMs: config.maxTokenAgeMs
236
+ });
237
+ } catch (error) {
238
+ if (error instanceof ReoptSDKError && error.status >= 500) return response({ error: error.code }, 503);
239
+ return response({ error: error instanceof ReoptSDKError ? error.code : "invalid_logout_token" }, 400);
240
+ }
241
+ try {
242
+ await config.onLogout(claims);
243
+ } catch {
244
+ return response({ error: "logout_processing_failed" }, 501);
245
+ }
246
+ return response({ ok: true }, 200);
247
+ };
248
+ }
249
+
250
+ //#endregion
251
+ //#region src/logout/end-session.ts
252
+ function buildEndSessionUrl(options) {
253
+ const idBaseUrl = (options.idBaseUrl ?? resolveIdBaseUrl(options.config ?? {})).replace(/\/$/, "");
254
+ const url = new URL(`${idBaseUrl}/api/auth/oauth2/end-session`);
255
+ url.searchParams.set("id_token_hint", options.idToken);
256
+ if (options.clientId) url.searchParams.set("client_id", options.clientId);
257
+ if (options.postLogoutRedirectUri) url.searchParams.set("post_logout_redirect_uri", options.postLogoutRedirectUri);
258
+ if (options.state) url.searchParams.set("state", options.state);
259
+ return url.toString();
260
+ }
261
+
262
+ //#endregion
263
+ export { buildEndSessionUrl, clearLogoutTokenCaches, createBackchannelLogoutHandler, verifyBackchannelLogoutToken };
264
+ //# sourceMappingURL=index.js.map
@@ -1,236 +1,2 @@
1
- import { q as ReoptSDKConfig } from '../config-CtxyJsDR.js';
2
-
3
- /**
4
- * Brandapp Plans types.
5
- *
6
- * Mirrors the response shape of `/api/v1/brandapp/{brandappId}/plans/*`.
7
- */
8
- /** Prisma `BillingModel` enum. */
9
- type PlanBillingModel = "recurring" | "usage";
10
- /** Prisma `PlanInterval` enum. */
11
- type PlanInterval = "monthly" | "yearly" | "once" | "lifetime";
12
- /** Prisma `MeterPricingMode` enum. */
13
- type MeterPricingMode = "flat" | "tiered";
14
- type PlanMeterTier = {
15
- /** 이 구간의 상한 수량. `null`이면 마지막(무제한) 구간. */
16
- upTo: number | null;
17
- /** 구간 단가 (통화 최소 단위 정수, 예: 원). */
18
- unitPrice: number;
19
- };
20
- /**
21
- * usage 과금 플랜의 사용량 미터.
22
- *
23
- * ⚠️ 현재 미터는 **read-only 메타데이터**다 — 사용량 집계·리포팅·청구 백엔드는
24
- * 아직 구현되지 않았다. 플랜 카탈로그에 "무엇을 얼마에 과금하는지" 표시하는
25
- * 용도로만 노출된다.
26
- */
27
- type PlanMeter = {
28
- id: string;
29
- name: string;
30
- /** API용 미터 키 (영문 소문자+숫자+언더스코어). */
31
- key: string;
32
- /** 단위 레이블 (예: "건", "GB"). */
33
- unitLabel: string;
34
- /** 포함 무료 수량. */
35
- includedQty: number;
36
- pricingMode: MeterPricingMode | string;
37
- /** flat 모드 단가 (통화 최소 단위 정수). */
38
- unitPrice: number;
39
- /** tiered 모드 구간. flat 모드이거나 미설정이면 `null`. */
40
- tiers: PlanMeterTier[] | null;
41
- sortOrder: number;
42
- };
43
- type PlanRequiredTerms = {
44
- id: string;
45
- title: string;
46
- /** Prisma `BrandappTermsType` (termsOfService/privacyPolicy/marketingConsent/custom). */
47
- type: string;
48
- };
49
- type Plan = {
50
- id: string;
51
- name: string;
52
- description: string | null;
53
- billingModel: PlanBillingModel | string;
54
- /** 정기 구독 가격 (통화 최소 단위 정수). usage 플랜은 보통 0. */
55
- priceAmount: number;
56
- /** ISO 4217 통화 코드 (예: "KRW", "USD"). */
57
- currency: string;
58
- interval: PlanInterval | string;
59
- /** usage 플랜의 기본 요금 (통화 최소 단위 정수). */
60
- baseFee: number;
61
- sortOrder: number;
62
- features: string[];
63
- /** usage 플랜의 사용량 미터 (read-only). */
64
- meters: PlanMeter[];
65
- /** 구독 전에 동의가 필요한 필수 약관. `sdk.terms`로 본문 조회·동의. */
66
- requiredTerms: PlanRequiredTerms[];
67
- };
68
- /** Prisma `BrandappCheckoutStatus`. */
69
- type CheckoutStatus = "pending" | "completed" | "canceled" | "expired" | "failed";
70
- /** `plans.createCheckout` 입력. */
71
- type CreateCheckoutInput = {
72
- /** 구독할 플랜 ID (`plans.list()`가 반환하는 `Plan.id`). */
73
- planId: string;
74
- /**
75
- * 결제 성공 후 고객을 돌려보낼 **절대** URL (내 앱의 복귀 페이지). 이 브랜드앱
76
- * OAuth 클라이언트에 등록된 redirect URI와 동일 origin이거나 reopt 호스트여야 한다.
77
- */
78
- successUrl: string;
79
- /** 결제 취소 시 돌려보낼 절대 URL (successUrl과 동일 검증). */
80
- cancelUrl: string;
81
- };
82
- /**
83
- * hosted-checkout 세션.
84
- *
85
- * `createCheckout`가 반환하면 `checkoutUrl`로 브라우저를 리다이렉트한다. 샌드박스
86
- * 모드에서 이 URL은 id.reopt.ai의 가상 결제 페이지이며, 결제를 승인하면 구독이
87
- * 활성화되고 `successUrl`(취소 시 `cancelUrl`)로 복귀한다. 복귀 후
88
- * `getCheckout(checkoutId)` 또는 `getMyPlan(token)`으로 결과를 확인한다.
89
- */
90
- type CheckoutSession = {
91
- checkoutId: string;
92
- /**
93
- * 브라우저를 리다이렉트할 결제 URL. `createCheckout` 응답에만 존재하고
94
- * `getCheckout` 응답에서는 `null`이다(capability token 재노출 방지).
95
- */
96
- checkoutUrl: string | null;
97
- /** 결제 제공자 — 현재 "sandbox"(가상 결제). */
98
- provider: string;
99
- status: CheckoutStatus | string;
100
- planId: string;
101
- planName: string;
102
- /** 결제 금액 (통화 최소 단위 정수). */
103
- amount: number;
104
- currency: string;
105
- interval: PlanInterval | string;
106
- /** ISO-8601 만료 시각 (pending 세션 TTL). */
107
- expiresAt: string;
108
- /** ISO-8601 완료 시각. 미완료면 `null`. */
109
- completedAt: string | null;
110
- };
111
- /** `plans.cancel` 결과. */
112
- type CancelSubscriptionResult = {
113
- status: "canceled";
114
- };
115
- /**
116
- * 현재 로그인 고객의 구독 플랜 + 엔타이틀먼트.
117
- *
118
- * 결제 상태는 이 고객 본인 소유(brandappCustomer) BillingState/PaymentProviderLink에서
119
- * 읽는다. 원시 결제 식별자(billingKey, 외부 subscription id)는 노출하지 않는다.
120
- */
121
- type CurrentPlan = {
122
- planId: string;
123
- planName: string;
124
- planDescription: string | null;
125
- priceAmount: number;
126
- currency: string;
127
- interval: PlanInterval | string;
128
- features: string[];
129
- /** BillingState.status (예: "active", "trialing", "canceled"). null이면 결제 상태 없음. */
130
- subscriptionStatus: string | null;
131
- /** ISO-8601 문자열. */
132
- planStartedAt: string | null;
133
- /** ISO-8601 문자열. `null`이면 무기한. */
134
- planExpiresAt: string | null;
135
- /** 활성 결제 제공자 — "paddle" | "toss" | null. */
136
- paymentProvider: string | null;
137
- };
138
-
139
- /**
140
- * Brandapp Plans client — read the plan catalog, the current customer's plan,
141
- * and drive a hosted checkout to subscribe & pay.
142
- *
143
- * - `list()` — Basic or Bearer. Active plans (catalog).
144
- * - `getMyPlan(accessToken)` — Bearer. The current customer's plan, or `null`.
145
- * - `createCheckout(input, accessToken)` — Bearer. Start a hosted checkout;
146
- * redirect the browser to the returned `checkoutUrl`.
147
- * - `getCheckout(checkoutId, accessToken)` — Bearer. Poll a checkout session.
148
- * - `cancel(accessToken)` — Bearer. Cancel the current sandbox subscription.
149
- *
150
- * ### Sandbox checkout (payment disabled)
151
- * When the Brandapp has real payment disabled (the default), `createCheckout`
152
- * returns a **sandbox** `checkoutUrl` — a virtual-payment page on id.reopt.ai
153
- * that activates the subscription without any real charge and redirects back to
154
- * your `successUrl`/`cancelUrl`. This is the built-in way to build and test the
155
- * full "list → subscribe → pay → entitlement" flow with no Toss/Paddle setup.
156
- *
157
- * ⚠️ Live Toss/Paddle checkout is **not** driven through the SDK yet (it needs
158
- * the provider browser SDK + host callbacks and stays in the first-party
159
- * brandfront flow) — `createCheckout` returns HTTP 409 `LIVE_MODE_UNSUPPORTED`
160
- * when the Brandapp is set to live payments. usage-model meters remain
161
- * read-only metadata (usage billing not implemented).
162
- *
163
- * @example
164
- * ```ts
165
- * const sdk = createReoptSDK({ clientId, clientSecret, brandappId });
166
- *
167
- * // Render the plan catalog (no user context required):
168
- * const plans = await sdk.plans.list();
169
- *
170
- * // After the customer signs in via OAuth, subscribe & pay:
171
- * try {
172
- * const checkout = await sdk.plans.createCheckout(
173
- * { planId: plans[0].id, successUrl, cancelUrl },
174
- * accessToken,
175
- * );
176
- * redirect(checkout.checkoutUrl!); // → sandbox payment page, then back to successUrl
177
- * } catch (e) {
178
- * if (isRequiredTermsError(e)) {
179
- * // collect consent for e.missingTermsIds via sdk.terms, then retry
180
- * }
181
- * }
182
- *
183
- * // On the return page, confirm the entitlement:
184
- * const current = await sdk.plans.getMyPlan(accessToken);
185
- * if (current?.subscriptionStatus === "active") {
186
- * // grant entitlement…
187
- * }
188
- * ```
189
- */
190
-
191
- declare class ReoptPlansClient {
192
- private readonly http;
193
- constructor(config: ReoptSDKConfig);
194
- /**
195
- * List active plans for this Brandapp (the customer-facing catalog). Works
196
- * with either Basic Auth (default) or Bearer Auth — pass `accessToken` when
197
- * calling from a handler that already has the customer's OAuth token to avoid
198
- * sending app credentials.
199
- */
200
- list(accessToken?: string): Promise<Plan[]>;
201
- /**
202
- * Fetch the current plan / entitlement for the OAuth customer represented by
203
- * `accessToken`. Returns `null` when the customer has no active plan.
204
- */
205
- getMyPlan(accessToken: string): Promise<CurrentPlan | null>;
206
- /**
207
- * Start a hosted checkout to subscribe the current customer (identified by
208
- * `accessToken`) to `input.planId`, then redirect the browser to the returned
209
- * `checkoutUrl`. In sandbox mode that URL is a virtual-payment page on
210
- * id.reopt.ai which activates the subscription and returns to your
211
- * `successUrl` / `cancelUrl`.
212
- *
213
- * @throws {RequiredTermsError} when the plan has required terms the customer
214
- * has not consented to. Read `missingTermsIds`, collect consent via
215
- * `sdk.terms`, then call again.
216
- * @throws {ReoptSDKError} `LIVE_MODE_UNSUPPORTED` (409) when the Brandapp is
217
- * configured for live Toss/Paddle payments (use the brandfront checkout).
218
- */
219
- createCheckout(input: CreateCheckoutInput, accessToken: string): Promise<CheckoutSession>;
220
- /**
221
- * Poll a checkout session by id (e.g. on your return page) to read its
222
- * `status` — `completed` means the subscription is active. `checkoutUrl` is
223
- * `null` here; use the URL from {@link createCheckout} to re-redirect.
224
- */
225
- getCheckout(checkoutId: string, accessToken: string): Promise<CheckoutSession>;
226
- /**
227
- * Cancel the current customer's active **sandbox** subscription. Access is
228
- * kept until the paid period ends (the billing state becomes `canceled`).
229
- * Real Toss/Paddle subscriptions are not affected — those use the provider
230
- * flow.
231
- */
232
- cancel(accessToken: string): Promise<CancelSubscriptionResult>;
233
- }
234
- declare function createReoptPlansClient(config: ReoptSDKConfig): ReoptPlansClient;
235
-
236
- export { type CancelSubscriptionResult, type CheckoutSession, type CheckoutStatus, type CreateCheckoutInput, type CurrentPlan, type MeterPricingMode, type Plan, type PlanBillingModel, type PlanInterval, type PlanMeter, type PlanMeterTier, type PlanRequiredTerms, ReoptPlansClient, createReoptPlansClient };
1
+ import { a as CheckoutStatus, c as MeterPricingMode, d as PlanInterval, f as PlanMeter, i as CheckoutSession, l as Plan, m as PlanRequiredTerms, n as createReoptPlansClient, o as CreateCheckoutInput, p as PlanMeterTier, r as CancelSubscriptionResult, s as CurrentPlan, t as ReoptPlansClient, u as PlanBillingModel } from "../client-D3RHHUUW.js";
2
+ export { type CancelSubscriptionResult, type CheckoutSession, type CheckoutStatus, type CreateCheckoutInput, type CurrentPlan, type MeterPricingMode, type Plan, type PlanBillingModel, type PlanInterval, type PlanMeter, type PlanMeterTier, type PlanRequiredTerms, ReoptPlansClient, createReoptPlansClient };
@@ -1,5 +1,3 @@
1
- export { ReoptPlansClient, createReoptPlansClient } from '../chunk-O3PUWIDJ.js';
2
- import '../chunk-N5JVE4WX.js';
3
- import '../chunk-MRQY45U5.js';
4
- //# sourceMappingURL=index.js.map
5
- //# sourceMappingURL=index.js.map
1
+ import { n as createReoptPlansClient, t as ReoptPlansClient } from "../client-B9QHVhdM.js";
2
+
3
+ export { ReoptPlansClient, createReoptPlansClient };
@@ -1,79 +1,2 @@
1
- import { q as ReoptSDKConfig } from '../config-CtxyJsDR.js';
2
-
3
- /** Push provider — native token kind. */
4
- type PushProvider = "fcm" | "apns";
5
- /** Device platform. */
6
- type PushPlatform = "ios" | "android" | "web";
7
- /** Input for registering a device push token. */
8
- type RegisterPushTokenInput = {
9
- /** Provider of the native token. */
10
- provider: PushProvider;
11
- /** Native device token (FCM registration token / APNs device token). */
12
- token: string;
13
- /** Device platform. */
14
- platform: PushPlatform;
15
- /** Optional device identifier (helps re-login/refresh upsert + unregister). */
16
- deviceId?: string;
17
- };
18
- type RegisterPushTokenResult = {
19
- registered: boolean;
20
- };
21
- /** Input for unregistering — one of token / deviceId is required. */
22
- type UnregisterPushTokenInput = {
23
- token?: string;
24
- deviceId?: string;
25
- };
26
- type UnregisterPushTokenResult = {
27
- unregistered: boolean;
28
- };
29
- /** A device currently registered for the signed-in customer. */
30
- type RegisteredPushDevice = {
31
- id: string;
32
- platform: PushPlatform;
33
- provider: PushProvider;
34
- deviceId: string | null;
35
- createdAt: string;
36
- lastSeenAt: string;
37
- };
38
-
39
- /**
40
- * Brandapp Push client.
41
- *
42
- * Lets a signed-in customer register/unregister their native device push token
43
- * (FCM/APNs) so the workspace can send them direct push notifications from the
44
- * reopt Studio send console. All methods require the end-user's OAuth access
45
- * token — the server resolves the token's linked customer and scopes the token
46
- * to them (unlinked users get 403 `LINK_REQUIRED`).
47
- *
48
- * The native token itself (FCM registration token / APNs device token) is
49
- * obtained by the host app (React Native / native shell) — this client only
50
- * registers/unregisters an already-obtained token.
51
- *
52
- * @example
53
- * ```ts
54
- * const sdk = createReoptSDK({ clientId, clientSecret, brandappId });
55
- *
56
- * // After obtaining a native token in the app:
57
- * await sdk.push.registerDeviceToken(
58
- * { provider: "fcm", token: fcmToken, platform: "android", deviceId },
59
- * accessToken,
60
- * );
61
- *
62
- * // On logout:
63
- * await sdk.push.unregisterDeviceToken({ deviceId }, accessToken);
64
- * ```
65
- */
66
-
67
- declare class ReoptPushClient {
68
- private readonly http;
69
- constructor(config: ReoptSDKConfig);
70
- /** Register (or refresh) the signed-in customer's device push token. */
71
- registerDeviceToken(input: RegisterPushTokenInput, accessToken: string): Promise<RegisterPushTokenResult>;
72
- /** Unregister a device token by `token` or `deviceId` (own tokens only). */
73
- unregisterDeviceToken(input: UnregisterPushTokenInput, accessToken: string): Promise<UnregisterPushTokenResult>;
74
- /** List the signed-in customer's registered devices (no raw tokens). */
75
- listDevices(accessToken: string): Promise<RegisteredPushDevice[]>;
76
- }
77
- declare function createReoptPushClient(config: ReoptSDKConfig): ReoptPushClient;
78
-
79
- export { type PushPlatform, type PushProvider, type RegisterPushTokenInput, type RegisterPushTokenResult, type RegisteredPushDevice, ReoptPushClient, type UnregisterPushTokenInput, type UnregisterPushTokenResult, createReoptPushClient };
1
+ import { a as RegisterPushTokenInput, c as UnregisterPushTokenInput, i as PushProvider, l as UnregisterPushTokenResult, n as createReoptPushClient, o as RegisterPushTokenResult, r as PushPlatform, s as RegisteredPushDevice, t as ReoptPushClient } from "../client-D6gs61w8.js";
2
+ export { type PushPlatform, type PushProvider, type RegisterPushTokenInput, type RegisterPushTokenResult, type RegisteredPushDevice, ReoptPushClient, type UnregisterPushTokenInput, type UnregisterPushTokenResult, createReoptPushClient };
@@ -1,5 +1,3 @@
1
- export { ReoptPushClient, createReoptPushClient } from '../chunk-R5CCGDUH.js';
2
- import '../chunk-N5JVE4WX.js';
3
- import '../chunk-MRQY45U5.js';
4
- //# sourceMappingURL=index.js.map
5
- //# sourceMappingURL=index.js.map
1
+ import { n as createReoptPushClient, t as ReoptPushClient } from "../client-D-yNxNfk.js";
2
+
3
+ export { ReoptPushClient, createReoptPushClient };
@@ -0,0 +1,35 @@
1
+ import { x as ReoptSDKError } from "./config-Cw0a3-C8.js";
2
+
3
+ //#region src/core/query.ts
4
+ /**
5
+ * Shared query-string builder for GET endpoints.
6
+ *
7
+ * Object/array values are JSON-serialized (e.g. EAV `filters`), everything
8
+ * else is stringified, then `encodeURIComponent`-escaped. Used by the EAV and
9
+ * CMS clients so the serialization rules stay in one place.
10
+ */
11
+ /**
12
+ * Maximum serialized query-string length (bytes, pre-`?`). Servers and proxies
13
+ * commonly reject URLs over ~8 KB with an opaque 414/400; we fail earlier with
14
+ * an actionable diagnostic so a caller passing too many/too-large filters
15
+ * learns the real cause instead of debugging a server-side rejection.
16
+ */
17
+ const MAX_QUERY_STRING_LENGTH = 7500;
18
+ function buildQuery(params) {
19
+ const entries = Object.entries(params).filter(([, v]) => v !== void 0 && v !== null);
20
+ if (entries.length === 0) return "";
21
+ const qs = "?" + entries.map(([k, v]) => {
22
+ const value = typeof v === "object" ? JSON.stringify(v) : String(v);
23
+ return `${k}=${encodeURIComponent(value)}`;
24
+ }).join("&");
25
+ if (qs.length > 7500) throw new ReoptSDKError(`Query string is too large (${qs.length} chars, limit ${MAX_QUERY_STRING_LENGTH}). Reduce the number of filters or the size of filter values.`, 0, "QUERY_TOO_LARGE", void 0, {
26
+ cause: "GET 요청의 쿼리스트링이 서버/프록시의 URL 길이 한도(통상 8KB)를 초과할 위험이 있음",
27
+ fix: "filters 개수를 줄이거나, 큰 value(예: 긴 contains 문자열)를 분리/축소. 대량 조건은 여러 번 나눠 조회",
28
+ doc: "docs/errors.md#query_too_large"
29
+ });
30
+ return qs;
31
+ }
32
+
33
+ //#endregion
34
+ export { buildQuery as t };
35
+ //# sourceMappingURL=query-BvbCiGWb.js.map