@01.software/sdk 0.2.9-dev.260306.2ae88fe → 0.2.9-dev.260309.c56872d
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.
- package/dist/{auth-7rMGkvN0.d.cts → auth-BieKA-OQ.d.ts} +13 -2
- package/dist/{auth-wTPFmG0W.d.ts → auth-CAV8xgZk.d.cts} +13 -2
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +2 -2
- package/dist/auth.d.ts +2 -2
- package/dist/auth.js.map +1 -1
- package/dist/components.d.cts +1 -1
- package/dist/components.d.ts +1 -1
- package/dist/flow.cjs +319 -61
- package/dist/flow.cjs.map +1 -1
- package/dist/flow.d.cts +88 -44
- package/dist/flow.d.ts +88 -44
- package/dist/flow.js +316 -57
- package/dist/flow.js.map +1 -1
- package/dist/index.cjs +208 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +227 -39
- package/dist/index.d.ts +227 -39
- package/dist/index.js +208 -22
- package/dist/index.js.map +1 -1
- package/dist/{payload-types-Dp1qa5_Z.d.cts → payload-types-2wbfaDxp.d.cts} +948 -130
- package/dist/{payload-types-Dp1qa5_Z.d.ts → payload-types-2wbfaDxp.d.ts} +948 -130
- package/dist/{webhook-BQQe_xSK.d.ts → webhook-Byzl1A0g.d.cts} +2 -2
- package/dist/{webhook-BPpNKVcz.d.cts → webhook-I6ZDGW1d.d.ts} +2 -2
- package/dist/webhook.cjs +1 -1
- package/dist/webhook.cjs.map +1 -1
- package/dist/webhook.d.cts +2 -2
- package/dist/webhook.d.ts +2 -2
- package/dist/webhook.js +1 -1
- package/dist/webhook.js.map +1 -1
- package/package.json +22 -21
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Sort, Where } from 'payload';
|
|
2
|
-
import './payload-types-
|
|
2
|
+
import './payload-types-2wbfaDxp.js';
|
|
3
3
|
|
|
4
4
|
declare class SDKError extends Error {
|
|
5
5
|
readonly code: string;
|
|
@@ -34,6 +34,13 @@ declare class ConfigError extends SDKError {
|
|
|
34
34
|
declare class TimeoutError extends SDKError {
|
|
35
35
|
constructor(message?: string, details?: unknown, userMessage?: string, suggestion?: string);
|
|
36
36
|
}
|
|
37
|
+
declare class GoneError extends SDKError {
|
|
38
|
+
constructor(message?: string, details?: unknown, userMessage?: string, suggestion?: string);
|
|
39
|
+
}
|
|
40
|
+
declare class ServiceUnavailableError extends SDKError {
|
|
41
|
+
readonly retryAfter?: number;
|
|
42
|
+
constructor(message?: string, retryAfter?: number, details?: unknown, userMessage?: string, suggestion?: string);
|
|
43
|
+
}
|
|
37
44
|
declare class UsageLimitError extends SDKError {
|
|
38
45
|
readonly usage: {
|
|
39
46
|
limit: number;
|
|
@@ -66,6 +73,8 @@ declare function isValidationError(error: unknown): error is ValidationError;
|
|
|
66
73
|
declare function isApiError(error: unknown): error is ApiError;
|
|
67
74
|
declare function isConfigError(error: unknown): error is ConfigError;
|
|
68
75
|
declare function isTimeoutError(error: unknown): error is TimeoutError;
|
|
76
|
+
declare function isGoneError(error: unknown): error is GoneError;
|
|
77
|
+
declare function isServiceUnavailableError(error: unknown): error is ServiceUnavailableError;
|
|
69
78
|
declare function isUsageLimitError(error: unknown): error is UsageLimitError;
|
|
70
79
|
|
|
71
80
|
type Environment = 'local' | 'development' | 'staging' | 'production';
|
|
@@ -200,6 +209,8 @@ interface FetchOptions extends RequestInit {
|
|
|
200
209
|
baseUrl?: string;
|
|
201
210
|
debug?: boolean | DebugConfig;
|
|
202
211
|
retry?: RetryConfig;
|
|
212
|
+
/** Called on 401 when customerToken is set. Return a new token to retry, or null to fail. */
|
|
213
|
+
onUnauthorized?: () => Promise<string | null>;
|
|
203
214
|
}
|
|
204
215
|
interface JwtPayload {
|
|
205
216
|
clientKey: string;
|
|
@@ -284,4 +295,4 @@ declare function parseApiKey(apiKey: string): {
|
|
|
284
295
|
secretKey: string;
|
|
285
296
|
};
|
|
286
297
|
|
|
287
|
-
export { type ApiQueryOptions as A, type ClientBrowserConfig as C, type DeepPartial as D, type ExtractArrayType as E, type FetchOptions as F, type JwtPayload as J, NetworkError as N, type PayloadFindResponse as P, type RetryConfig as R, SDKError as S, TimeoutError as T, UsageLimitError as U, ValidationError as V, type PayloadMutationResponse as a, type ClientState as b, type ClientServerConfig as c, type DebugConfig as d, type ErrorLogger as e, ApiError as f, ConfigError as g,
|
|
298
|
+
export { type ApiQueryOptions as A, type PaginationMeta as B, type ClientBrowserConfig as C, type DeepPartial as D, type ExtractArrayType as E, type FetchOptions as F, GoneError as G, type ApiQueryReactOptions as H, type JwtPayload as J, NetworkError as N, type PayloadFindResponse as P, type RetryConfig as R, SDKError as S, TimeoutError as T, UsageLimitError as U, ValidationError as V, type PayloadMutationResponse as a, type ClientState as b, type ClientServerConfig as c, type DebugConfig as d, type ErrorLogger as e, ApiError as f, ConfigError as g, ServiceUnavailableError as h, isSDKError as i, isNetworkError as j, isValidationError as k, isApiError as l, isConfigError as m, isTimeoutError as n, isGoneError as o, isServiceUnavailableError as p, isUsageLimitError as q, createServerToken as r, decodeServerToken as s, createApiKey as t, parseApiKey as u, verifyServerToken as v, type Environment as w, API_URLS as x, resolveApiUrl as y, type ClientMetadata as z };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Sort, Where } from 'payload';
|
|
2
|
-
import './payload-types-
|
|
2
|
+
import './payload-types-2wbfaDxp.cjs';
|
|
3
3
|
|
|
4
4
|
declare class SDKError extends Error {
|
|
5
5
|
readonly code: string;
|
|
@@ -34,6 +34,13 @@ declare class ConfigError extends SDKError {
|
|
|
34
34
|
declare class TimeoutError extends SDKError {
|
|
35
35
|
constructor(message?: string, details?: unknown, userMessage?: string, suggestion?: string);
|
|
36
36
|
}
|
|
37
|
+
declare class GoneError extends SDKError {
|
|
38
|
+
constructor(message?: string, details?: unknown, userMessage?: string, suggestion?: string);
|
|
39
|
+
}
|
|
40
|
+
declare class ServiceUnavailableError extends SDKError {
|
|
41
|
+
readonly retryAfter?: number;
|
|
42
|
+
constructor(message?: string, retryAfter?: number, details?: unknown, userMessage?: string, suggestion?: string);
|
|
43
|
+
}
|
|
37
44
|
declare class UsageLimitError extends SDKError {
|
|
38
45
|
readonly usage: {
|
|
39
46
|
limit: number;
|
|
@@ -66,6 +73,8 @@ declare function isValidationError(error: unknown): error is ValidationError;
|
|
|
66
73
|
declare function isApiError(error: unknown): error is ApiError;
|
|
67
74
|
declare function isConfigError(error: unknown): error is ConfigError;
|
|
68
75
|
declare function isTimeoutError(error: unknown): error is TimeoutError;
|
|
76
|
+
declare function isGoneError(error: unknown): error is GoneError;
|
|
77
|
+
declare function isServiceUnavailableError(error: unknown): error is ServiceUnavailableError;
|
|
69
78
|
declare function isUsageLimitError(error: unknown): error is UsageLimitError;
|
|
70
79
|
|
|
71
80
|
type Environment = 'local' | 'development' | 'staging' | 'production';
|
|
@@ -200,6 +209,8 @@ interface FetchOptions extends RequestInit {
|
|
|
200
209
|
baseUrl?: string;
|
|
201
210
|
debug?: boolean | DebugConfig;
|
|
202
211
|
retry?: RetryConfig;
|
|
212
|
+
/** Called on 401 when customerToken is set. Return a new token to retry, or null to fail. */
|
|
213
|
+
onUnauthorized?: () => Promise<string | null>;
|
|
203
214
|
}
|
|
204
215
|
interface JwtPayload {
|
|
205
216
|
clientKey: string;
|
|
@@ -284,4 +295,4 @@ declare function parseApiKey(apiKey: string): {
|
|
|
284
295
|
secretKey: string;
|
|
285
296
|
};
|
|
286
297
|
|
|
287
|
-
export { type ApiQueryOptions as A, type ClientBrowserConfig as C, type DeepPartial as D, type ExtractArrayType as E, type FetchOptions as F, type JwtPayload as J, NetworkError as N, type PayloadFindResponse as P, type RetryConfig as R, SDKError as S, TimeoutError as T, UsageLimitError as U, ValidationError as V, type PayloadMutationResponse as a, type ClientState as b, type ClientServerConfig as c, type DebugConfig as d, type ErrorLogger as e, ApiError as f, ConfigError as g,
|
|
298
|
+
export { type ApiQueryOptions as A, type PaginationMeta as B, type ClientBrowserConfig as C, type DeepPartial as D, type ExtractArrayType as E, type FetchOptions as F, GoneError as G, type ApiQueryReactOptions as H, type JwtPayload as J, NetworkError as N, type PayloadFindResponse as P, type RetryConfig as R, SDKError as S, TimeoutError as T, UsageLimitError as U, ValidationError as V, type PayloadMutationResponse as a, type ClientState as b, type ClientServerConfig as c, type DebugConfig as d, type ErrorLogger as e, ApiError as f, ConfigError as g, ServiceUnavailableError as h, isSDKError as i, isNetworkError as j, isValidationError as k, isApiError as l, isConfigError as m, isTimeoutError as n, isGoneError as o, isServiceUnavailableError as p, isUsageLimitError as q, createServerToken as r, decodeServerToken as s, createApiKey as t, parseApiKey as u, verifyServerToken as v, type Environment as w, API_URLS as x, resolveApiUrl as y, type ClientMetadata as z };
|
package/dist/auth.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth.ts","../src/core/internal/utils/index.ts"],"sourcesContent":["export type { JwtPayload } from './core/internal/utils'\nexport {\n createServerToken,\n verifyServerToken,\n decodeServerToken,\n createApiKey,\n parseApiKey,\n} from './core/internal/utils'\n","import { SignJWT, jwtVerify, decodeJwt } from 'jose'\nimport { createNetworkError, createUsageLimitError, createTimeoutError, TimeoutError, NetworkError } from '../errors'\nimport type { DebugConfig, RetryConfig } from '../../client/types'\nimport { API_URLS } from '../../client/types'\n\nconst DEFAULT_TIMEOUT = 30000\nconst DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504]\nconst NON_RETRYABLE_STATUSES = [401, 403, 404, 422]\nconst SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']\n\nexport interface FetchOptions extends RequestInit {\n clientKey?: string\n secretKey?: string\n customerToken?: string\n timeout?: number\n baseUrl?: string\n debug?: boolean | DebugConfig\n retry?: RetryConfig\n}\n\nexport interface JwtPayload {\n clientKey: string\n iat?: number\n exp?: number\n}\n\n/**\n * Creates a JWT token for server-side authentication.\n * The token is valid for 1 hour by default.\n *\n * @param clientKey - Client API key\n * @param secretKey - Secret key used for signing\n * @param expiresIn - Token expiration time (default: '1h')\n * @returns Promise<string> JWT token\n *\n * @example\n * ```typescript\n * const token = await createServerToken('client-key', 'secret-key')\n * // Use in Authorization header: `Bearer ${token}`\n * ```\n */\nexport async function createServerToken(\n clientKey: string,\n secretKey: string,\n expiresIn: string = '1h',\n): Promise<string> {\n if (!clientKey || !secretKey) {\n throw new Error('clientKey and secretKey are required.')\n }\n\n const secret = new TextEncoder().encode(secretKey)\n return new SignJWT({ clientKey })\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuedAt()\n .setExpirationTime(expiresIn)\n .sign(secret)\n}\n\n/**\n * Verifies a JWT token and returns the payload.\n *\n * @param token - JWT token to verify\n * @param secretKey - Secret key used for verification\n * @returns Promise<JwtPayload> Verified payload containing clientKey\n * @throws Error if token is invalid or expired\n *\n * @example\n * ```typescript\n * const payload = await verifyServerToken(token, 'secret-key')\n * console.log(payload.clientKey)\n * ```\n */\nexport async function verifyServerToken(\n token: string,\n secretKey: string,\n): Promise<JwtPayload> {\n if (!token || !secretKey) {\n throw new Error('token and secretKey are required.')\n }\n\n const secret = new TextEncoder().encode(secretKey)\n const { payload } = await jwtVerify(token, secret, {\n algorithms: ['HS256'],\n })\n\n if (!payload.clientKey || typeof payload.clientKey !== 'string') {\n throw new Error('Invalid token payload: clientKey is missing')\n }\n\n return {\n clientKey: payload.clientKey as string,\n iat: payload.iat,\n exp: payload.exp,\n }\n}\n\n/**\n * Decodes a JWT token without verification.\n * WARNING: Use this only when you need to inspect token contents.\n * Always use verifyServerToken for authentication.\n *\n * @param token - JWT token to decode\n * @returns JwtPayload Decoded payload (unverified)\n *\n * @example\n * ```typescript\n * const payload = decodeServerToken(token)\n * console.log(payload.clientKey) // Unverified!\n * ```\n */\nexport function decodeServerToken(token: string): JwtPayload {\n if (!token) {\n throw new Error('token is required.')\n }\n\n const payload = decodeJwt(token)\n\n if (!payload.clientKey || typeof payload.clientKey !== 'string') {\n throw new Error('Invalid token payload: clientKey is missing')\n }\n\n return {\n clientKey: payload.clientKey as string,\n iat: payload.iat,\n exp: payload.exp,\n }\n}\n\n// ============================================================================\n// API Key Utilities\n// ============================================================================\n\n/**\n * Creates a Base64-encoded API key from clientKey and secretKey.\n * Use this for MCP server authentication.\n *\n * @param clientKey - Client API key\n * @param secretKey - Secret key\n * @returns Base64-encoded API key\n *\n * @example\n * ```typescript\n * const apiKey = createApiKey('client-key', 'secret-key')\n * // Use in x-api-key header\n * ```\n */\nexport function createApiKey(clientKey: string, secretKey: string): string {\n if (!clientKey || !secretKey) {\n throw new Error('clientKey and secretKey are required.')\n }\n\n // Browser와 Node.js 모두 지원\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(`${clientKey}:${secretKey}`).toString('base64')\n }\n return btoa(`${clientKey}:${secretKey}`)\n}\n\n/**\n * Parses a Base64-encoded API key to extract clientKey and secretKey.\n *\n * @param apiKey - Base64-encoded API key\n * @returns Object containing clientKey and secretKey\n * @throws Error if API key is invalid\n *\n * @example\n * ```typescript\n * const { clientKey, secretKey } = parseApiKey(apiKey)\n * ```\n */\nexport function parseApiKey(apiKey: string): {\n clientKey: string\n secretKey: string\n} {\n if (!apiKey) {\n throw new Error('apiKey is required.')\n }\n\n try {\n let decoded: string\n if (typeof Buffer !== 'undefined') {\n decoded = Buffer.from(apiKey, 'base64').toString('utf-8')\n } else {\n decoded = atob(apiKey)\n }\n\n const colonIndex = decoded.indexOf(':')\n if (colonIndex === -1) {\n throw new Error('Invalid format: missing colon separator')\n }\n\n const clientKey = decoded.substring(0, colonIndex)\n const secretKey = decoded.substring(colonIndex + 1)\n\n if (!clientKey || !secretKey) {\n throw new Error('Invalid format: empty clientKey or secretKey')\n }\n\n return { clientKey, secretKey }\n } catch {\n throw new Error('Invalid API key. Expected Base64 encoded \"clientKey:secretKey\"')\n }\n}\n\nfunction debugLog(\n debug: boolean | DebugConfig | undefined,\n type: 'request' | 'response' | 'error',\n message: string,\n data?: unknown,\n) {\n if (!debug) return\n\n const shouldLog =\n debug === true ||\n (type === 'request' && (debug as DebugConfig).logRequests) ||\n (type === 'response' && (debug as DebugConfig).logResponses) ||\n (type === 'error' && (debug as DebugConfig).logErrors)\n\n if (shouldLog) {\n console.group(`[SDK ${type.toUpperCase()}] ${message}`)\n if (data) console.log(data)\n console.groupEnd()\n }\n}\n\nfunction getErrorSuggestion(status: number): string | undefined {\n if (status === 401) return 'Please check your authentication credentials.'\n if (status === 404) return 'The requested resource was not found.'\n if (status >= 500)\n return 'A server error occurred. Please try again later.'\n return undefined\n}\n\nasync function delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport async function _fetch(\n url: string,\n options?: FetchOptions,\n): Promise<Response> {\n const {\n clientKey,\n secretKey,\n customerToken,\n timeout = DEFAULT_TIMEOUT,\n baseUrl = API_URLS.production,\n debug,\n retry,\n ...requestInit\n } = options || {}\n\n const retryConfig = {\n maxRetries: retry?.maxRetries ?? 3,\n retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,\n retryDelay:\n retry?.retryDelay ??\n ((attempt: number) => Math.min(1000 * 2 ** attempt, 10000)),\n }\n\n // Generate JWT once before retry loop (token valid for 1h)\n let authToken: string | undefined\n if (secretKey && clientKey) {\n authToken = await createServerToken(clientKey, secretKey)\n } else if (customerToken) {\n authToken = customerToken\n }\n\n let lastError: Error | undefined\n\n for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {\n try {\n const headers = new Headers(requestInit.headers)\n\n if (clientKey) {\n headers.set('X-Client-Key', clientKey)\n }\n\n if (authToken) {\n headers.set('Authorization', `Bearer ${authToken}`)\n }\n\n if (!headers.has('Content-Type') && requestInit.body && !(requestInit.body instanceof FormData)) {\n headers.set('Content-Type', 'application/json')\n }\n\n // Redact sensitive headers for debug logging\n const redactedHeaders = Object.fromEntries(headers.entries())\n if (redactedHeaders['authorization']) {\n const token = redactedHeaders['authorization']\n // Show only \"Bearer eyJ...****\" to aid debugging without exposing the full token\n redactedHeaders['authorization'] = token.length > 15\n ? `${token.slice(0, 15)}...****`\n : '****'\n }\n\n debugLog(debug, 'request', url, {\n method: requestInit.method || 'GET',\n headers: redactedHeaders,\n attempt: attempt + 1,\n })\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n const response = await fetch(`${baseUrl}${url}`, {\n ...requestInit,\n headers,\n signal: controller.signal,\n })\n\n clearTimeout(timeoutId)\n\n debugLog(debug, 'response', url, {\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries()),\n })\n\n if (!response.ok) {\n // Usage limit 429 — never retry (distinguished by X-Usage-Limit header)\n if (\n response.status === 429 &&\n response.headers.get('X-Usage-Limit')\n ) {\n const limit = parseInt(response.headers.get('X-Usage-Limit') || '0', 10)\n const current = parseInt(response.headers.get('X-Usage-Current') || '0', 10)\n const remaining = parseInt(response.headers.get('X-Usage-Remaining') || '0', 10)\n\n throw createUsageLimitError(\n `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,\n { limit, current, remaining },\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n 'Monthly API call limit exceeded. Please upgrade your plan.',\n 'Upgrade your tenant plan to increase the monthly API call limit.',\n )\n }\n\n // Never retry non-retryable statuses regardless of user config\n if (NON_RETRYABLE_STATUSES.includes(response.status)) {\n throw createNetworkError(\n `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n `Request failed (status: ${response.status})`,\n getErrorSuggestion(response.status),\n )\n }\n\n const error = createNetworkError(\n `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n `Request failed (status: ${response.status})`,\n getErrorSuggestion(response.status),\n )\n\n const method = (requestInit.method || 'GET').toUpperCase()\n if (\n attempt < retryConfig.maxRetries &&\n SAFE_METHODS.includes(method) &&\n retryConfig.retryableStatuses.includes(response.status)\n ) {\n lastError = error\n const retryDelay = retryConfig.retryDelay(attempt)\n debugLog(debug, 'error', `Retrying in ${retryDelay}ms...`, error)\n await delay(retryDelay)\n continue\n }\n\n throw error\n }\n\n return response\n } catch (error) {\n debugLog(debug, 'error', url, error)\n\n const method = (requestInit.method || 'GET').toUpperCase()\n const isSafe = SAFE_METHODS.includes(method)\n\n if (error instanceof Error && error.name === 'AbortError') {\n const timeoutError = createTimeoutError(\n `Request timed out after ${timeout}ms.`,\n { url, timeout, attempt: attempt + 1 },\n 'The request timed out.',\n 'Please check your network connection or try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = timeoutError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw timeoutError\n }\n\n if (error instanceof TypeError) {\n const networkError = createNetworkError(\n 'Network connection failed.',\n undefined,\n { url, originalError: error.message, attempt: attempt + 1 },\n 'Network connection failed.',\n 'Please check your internet connection and try again.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = networkError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw networkError\n }\n\n if (error instanceof NetworkError || error instanceof TimeoutError) {\n if (\n isSafe &&\n attempt < retryConfig.maxRetries &&\n error.status &&\n !NON_RETRYABLE_STATUSES.includes(error.status) &&\n retryConfig.retryableStatuses.includes(error.status)\n ) {\n lastError = error\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw error\n }\n\n const unknownError = createNetworkError(\n error instanceof Error\n ? error.message\n : 'An unknown network error occurred.',\n undefined,\n { url, originalError: error, attempt: attempt + 1 },\n 'An unknown error occurred.',\n 'Please try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = unknownError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw unknownError\n }\n }\n\n throw lastError ?? new NetworkError('Request failed after retries')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAA8C;AAyC9C,SAAsB,kBACpB,WACA,WACA,YAAoB,MACH;AAAA;AACjB,QAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,YAAM,IAAI,MAAM,uCAAuC;AAAA,IACzD;AAEA,UAAM,SAAS,IAAI,YAAY,EAAE,OAAO,SAAS;AACjD,WAAO,IAAI,oBAAQ,EAAE,UAAU,CAAC,EAC7B,mBAAmB,EAAE,KAAK,QAAQ,CAAC,EACnC,YAAY,EACZ,kBAAkB,SAAS,EAC3B,KAAK,MAAM;AAAA,EAChB;AAAA;AAgBA,SAAsB,kBACpB,OACA,WACqB;AAAA;AACrB,QAAI,CAAC,SAAS,CAAC,WAAW;AACxB,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AAEA,UAAM,SAAS,IAAI,YAAY,EAAE,OAAO,SAAS;AACjD,UAAM,EAAE,QAAQ,IAAI,UAAM,uBAAU,OAAO,QAAQ;AAAA,MACjD,YAAY,CAAC,OAAO;AAAA,IACtB,CAAC;AAED,QAAI,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,UAAU;AAC/D,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AAEA,WAAO;AAAA,MACL,WAAW,QAAQ;AAAA,MACnB,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA;AAgBO,SAAS,kBAAkB,OAA2B;AAC3D,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,oBAAoB;AAAA,EACtC;AAEA,QAAM,cAAU,uBAAU,KAAK;AAE/B,MAAI,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,UAAU;AAC/D,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AAEA,SAAO;AAAA,IACL,WAAW,QAAQ;AAAA,IACnB,KAAK,QAAQ;AAAA,IACb,KAAK,QAAQ;AAAA,EACf;AACF;AAoBO,SAAS,aAAa,WAAmB,WAA2B;AACzE,MAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AAGA,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,OAAO,KAAK,GAAG,SAAS,IAAI,SAAS,EAAE,EAAE,SAAS,QAAQ;AAAA,EACnE;AACA,SAAO,KAAK,GAAG,SAAS,IAAI,SAAS,EAAE;AACzC;AAcO,SAAS,YAAY,QAG1B;AACA,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,qBAAqB;AAAA,EACvC;AAEA,MAAI;AACF,QAAI;AACJ,QAAI,OAAO,WAAW,aAAa;AACjC,gBAAU,OAAO,KAAK,QAAQ,QAAQ,EAAE,SAAS,OAAO;AAAA,IAC1D,OAAO;AACL,gBAAU,KAAK,MAAM;AAAA,IACvB;AAEA,UAAM,aAAa,QAAQ,QAAQ,GAAG;AACtC,QAAI,eAAe,IAAI;AACrB,YAAM,IAAI,MAAM,yCAAyC;AAAA,IAC3D;AAEA,UAAM,YAAY,QAAQ,UAAU,GAAG,UAAU;AACjD,UAAM,YAAY,QAAQ,UAAU,aAAa,CAAC;AAElD,QAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,YAAM,IAAI,MAAM,8CAA8C;AAAA,IAChE;AAEA,WAAO,EAAE,WAAW,UAAU;AAAA,EAChC,SAAQ;AACN,UAAM,IAAI,MAAM,gEAAgE;AAAA,EAClF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/auth.ts","../src/core/internal/utils/index.ts"],"sourcesContent":["export type { JwtPayload } from './core/internal/utils'\nexport {\n createServerToken,\n verifyServerToken,\n decodeServerToken,\n createApiKey,\n parseApiKey,\n} from './core/internal/utils'\n","import { SignJWT, jwtVerify, decodeJwt } from 'jose'\nimport { createNetworkError, createUsageLimitError, createTimeoutError, TimeoutError, NetworkError } from '../errors'\nimport type { DebugConfig, RetryConfig } from '../../client/types'\nimport { API_URLS } from '../../client/types'\n\nconst DEFAULT_TIMEOUT = 30000\nconst DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504]\nconst NON_RETRYABLE_STATUSES = [401, 403, 404, 422]\nconst SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']\n\nexport interface FetchOptions extends RequestInit {\n clientKey?: string\n secretKey?: string\n customerToken?: string\n timeout?: number\n baseUrl?: string\n debug?: boolean | DebugConfig\n retry?: RetryConfig\n /** Called on 401 when customerToken is set. Return a new token to retry, or null to fail. */\n onUnauthorized?: () => Promise<string | null>\n}\n\nexport interface JwtPayload {\n clientKey: string\n iat?: number\n exp?: number\n}\n\n/**\n * Creates a JWT token for server-side authentication.\n * The token is valid for 1 hour by default.\n *\n * @param clientKey - Client API key\n * @param secretKey - Secret key used for signing\n * @param expiresIn - Token expiration time (default: '1h')\n * @returns Promise<string> JWT token\n *\n * @example\n * ```typescript\n * const token = await createServerToken('client-key', 'secret-key')\n * // Use in Authorization header: `Bearer ${token}`\n * ```\n */\nexport async function createServerToken(\n clientKey: string,\n secretKey: string,\n expiresIn: string = '1h',\n): Promise<string> {\n if (!clientKey || !secretKey) {\n throw new Error('clientKey and secretKey are required.')\n }\n\n const secret = new TextEncoder().encode(secretKey)\n return new SignJWT({ clientKey })\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuedAt()\n .setExpirationTime(expiresIn)\n .sign(secret)\n}\n\n/**\n * Verifies a JWT token and returns the payload.\n *\n * @param token - JWT token to verify\n * @param secretKey - Secret key used for verification\n * @returns Promise<JwtPayload> Verified payload containing clientKey\n * @throws Error if token is invalid or expired\n *\n * @example\n * ```typescript\n * const payload = await verifyServerToken(token, 'secret-key')\n * console.log(payload.clientKey)\n * ```\n */\nexport async function verifyServerToken(\n token: string,\n secretKey: string,\n): Promise<JwtPayload> {\n if (!token || !secretKey) {\n throw new Error('token and secretKey are required.')\n }\n\n const secret = new TextEncoder().encode(secretKey)\n const { payload } = await jwtVerify(token, secret, {\n algorithms: ['HS256'],\n })\n\n if (!payload.clientKey || typeof payload.clientKey !== 'string') {\n throw new Error('Invalid token payload: clientKey is missing')\n }\n\n return {\n clientKey: payload.clientKey as string,\n iat: payload.iat,\n exp: payload.exp,\n }\n}\n\n/**\n * Decodes a JWT token without verification.\n * WARNING: Use this only when you need to inspect token contents.\n * Always use verifyServerToken for authentication.\n *\n * @param token - JWT token to decode\n * @returns JwtPayload Decoded payload (unverified)\n *\n * @example\n * ```typescript\n * const payload = decodeServerToken(token)\n * console.log(payload.clientKey) // Unverified!\n * ```\n */\nexport function decodeServerToken(token: string): JwtPayload {\n if (!token) {\n throw new Error('token is required.')\n }\n\n const payload = decodeJwt(token)\n\n if (!payload.clientKey || typeof payload.clientKey !== 'string') {\n throw new Error('Invalid token payload: clientKey is missing')\n }\n\n return {\n clientKey: payload.clientKey as string,\n iat: payload.iat,\n exp: payload.exp,\n }\n}\n\n// ============================================================================\n// API Key Utilities\n// ============================================================================\n\n/**\n * Creates a Base64-encoded API key from clientKey and secretKey.\n * Use this for MCP server authentication.\n *\n * @param clientKey - Client API key\n * @param secretKey - Secret key\n * @returns Base64-encoded API key\n *\n * @example\n * ```typescript\n * const apiKey = createApiKey('client-key', 'secret-key')\n * // Use in x-api-key header\n * ```\n */\nexport function createApiKey(clientKey: string, secretKey: string): string {\n if (!clientKey || !secretKey) {\n throw new Error('clientKey and secretKey are required.')\n }\n\n // Browser와 Node.js 모두 지원\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(`${clientKey}:${secretKey}`).toString('base64')\n }\n return btoa(`${clientKey}:${secretKey}`)\n}\n\n/**\n * Parses a Base64-encoded API key to extract clientKey and secretKey.\n *\n * @param apiKey - Base64-encoded API key\n * @returns Object containing clientKey and secretKey\n * @throws Error if API key is invalid\n *\n * @example\n * ```typescript\n * const { clientKey, secretKey } = parseApiKey(apiKey)\n * ```\n */\nexport function parseApiKey(apiKey: string): {\n clientKey: string\n secretKey: string\n} {\n if (!apiKey) {\n throw new Error('apiKey is required.')\n }\n\n try {\n let decoded: string\n if (typeof Buffer !== 'undefined') {\n decoded = Buffer.from(apiKey, 'base64').toString('utf-8')\n } else {\n decoded = atob(apiKey)\n }\n\n const colonIndex = decoded.indexOf(':')\n if (colonIndex === -1) {\n throw new Error('Invalid format: missing colon separator')\n }\n\n const clientKey = decoded.substring(0, colonIndex)\n const secretKey = decoded.substring(colonIndex + 1)\n\n if (!clientKey || !secretKey) {\n throw new Error('Invalid format: empty clientKey or secretKey')\n }\n\n return { clientKey, secretKey }\n } catch {\n throw new Error('Invalid API key. Expected Base64 encoded \"clientKey:secretKey\"')\n }\n}\n\nfunction debugLog(\n debug: boolean | DebugConfig | undefined,\n type: 'request' | 'response' | 'error',\n message: string,\n data?: unknown,\n) {\n if (!debug) return\n\n const shouldLog =\n debug === true ||\n (type === 'request' && (debug as DebugConfig).logRequests) ||\n (type === 'response' && (debug as DebugConfig).logResponses) ||\n (type === 'error' && (debug as DebugConfig).logErrors)\n\n if (shouldLog) {\n console.group(`[SDK ${type.toUpperCase()}] ${message}`)\n if (data) console.log(data)\n console.groupEnd()\n }\n}\n\nfunction getErrorSuggestion(status: number): string | undefined {\n if (status === 401) return 'Please check your authentication credentials.'\n if (status === 404) return 'The requested resource was not found.'\n if (status >= 500)\n return 'A server error occurred. Please try again later.'\n return undefined\n}\n\nasync function delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport async function _fetch(\n url: string,\n options?: FetchOptions,\n): Promise<Response> {\n const {\n clientKey,\n secretKey,\n customerToken,\n timeout = DEFAULT_TIMEOUT,\n baseUrl = API_URLS.production,\n debug,\n retry,\n onUnauthorized,\n ...requestInit\n } = options || {}\n\n const retryConfig = {\n maxRetries: retry?.maxRetries ?? 3,\n retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,\n retryDelay:\n retry?.retryDelay ??\n ((attempt: number) => Math.min(1000 * 2 ** attempt, 10000)),\n }\n\n // Generate JWT once before retry loop (token valid for 1h)\n let authToken: string | undefined\n if (secretKey && clientKey) {\n authToken = await createServerToken(clientKey, secretKey)\n } else if (customerToken) {\n authToken = customerToken\n }\n\n let lastError: Error | undefined\n let hasRetried401 = false\n\n for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {\n try {\n const headers = new Headers(requestInit.headers)\n\n if (clientKey) {\n headers.set('X-Client-Key', clientKey)\n }\n\n if (authToken) {\n headers.set('Authorization', `Bearer ${authToken}`)\n }\n\n if (!headers.has('Content-Type') && requestInit.body && !(requestInit.body instanceof FormData)) {\n headers.set('Content-Type', 'application/json')\n }\n\n // Redact sensitive headers for debug logging\n const redactedHeaders = Object.fromEntries(headers.entries())\n if (redactedHeaders['authorization']) {\n const token = redactedHeaders['authorization']\n // Show only \"Bearer eyJ...****\" to aid debugging without exposing the full token\n redactedHeaders['authorization'] = token.length > 15\n ? `${token.slice(0, 15)}...****`\n : '****'\n }\n\n debugLog(debug, 'request', url, {\n method: requestInit.method || 'GET',\n headers: redactedHeaders,\n attempt: attempt + 1,\n })\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n const response = await fetch(`${baseUrl}${url}`, {\n ...requestInit,\n headers,\n signal: controller.signal,\n })\n\n clearTimeout(timeoutId)\n\n debugLog(debug, 'response', url, {\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries()),\n })\n\n if (!response.ok) {\n // Usage limit 429 — never retry (distinguished by X-Usage-Limit header)\n if (\n response.status === 429 &&\n response.headers.get('X-Usage-Limit')\n ) {\n const limit = parseInt(response.headers.get('X-Usage-Limit') || '0', 10)\n const current = parseInt(response.headers.get('X-Usage-Current') || '0', 10)\n const remaining = parseInt(response.headers.get('X-Usage-Remaining') || '0', 10)\n\n throw createUsageLimitError(\n `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,\n { limit, current, remaining },\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n 'Monthly API call limit exceeded. Please upgrade your plan.',\n 'Upgrade your tenant plan to increase the monthly API call limit.',\n )\n }\n\n // Auto-refresh customer token on 401\n if (response.status === 401 && onUnauthorized && customerToken && !hasRetried401) {\n hasRetried401 = true\n try {\n const newToken = await onUnauthorized()\n if (newToken) {\n authToken = newToken\n continue\n }\n } catch {\n // Refresh failed, fall through to throw\n }\n }\n\n // Never retry non-retryable statuses regardless of user config\n if (NON_RETRYABLE_STATUSES.includes(response.status)) {\n throw createNetworkError(\n `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n `Request failed (status: ${response.status})`,\n getErrorSuggestion(response.status),\n )\n }\n\n const error = createNetworkError(\n `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n `Request failed (status: ${response.status})`,\n getErrorSuggestion(response.status),\n )\n\n const method = (requestInit.method || 'GET').toUpperCase()\n if (\n attempt < retryConfig.maxRetries &&\n SAFE_METHODS.includes(method) &&\n retryConfig.retryableStatuses.includes(response.status)\n ) {\n lastError = error\n const retryDelay = retryConfig.retryDelay(attempt)\n debugLog(debug, 'error', `Retrying in ${retryDelay}ms...`, error)\n await delay(retryDelay)\n continue\n }\n\n throw error\n }\n\n return response\n } catch (error) {\n debugLog(debug, 'error', url, error)\n\n const method = (requestInit.method || 'GET').toUpperCase()\n const isSafe = SAFE_METHODS.includes(method)\n\n if (error instanceof Error && error.name === 'AbortError') {\n const timeoutError = createTimeoutError(\n `Request timed out after ${timeout}ms.`,\n { url, timeout, attempt: attempt + 1 },\n 'The request timed out.',\n 'Please check your network connection or try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = timeoutError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw timeoutError\n }\n\n if (error instanceof TypeError) {\n const networkError = createNetworkError(\n 'Network connection failed.',\n undefined,\n { url, originalError: error.message, attempt: attempt + 1 },\n 'Network connection failed.',\n 'Please check your internet connection and try again.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = networkError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw networkError\n }\n\n if (error instanceof NetworkError || error instanceof TimeoutError) {\n if (\n isSafe &&\n attempt < retryConfig.maxRetries &&\n error.status &&\n !NON_RETRYABLE_STATUSES.includes(error.status) &&\n retryConfig.retryableStatuses.includes(error.status)\n ) {\n lastError = error\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw error\n }\n\n const unknownError = createNetworkError(\n error instanceof Error\n ? error.message\n : 'An unknown network error occurred.',\n undefined,\n { url, originalError: error, attempt: attempt + 1 },\n 'An unknown error occurred.',\n 'Please try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = unknownError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw unknownError\n }\n }\n\n throw lastError ?? new NetworkError('Request failed after retries')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAA8C;AA2C9C,SAAsB,kBACpB,WACA,WACA,YAAoB,MACH;AAAA;AACjB,QAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,YAAM,IAAI,MAAM,uCAAuC;AAAA,IACzD;AAEA,UAAM,SAAS,IAAI,YAAY,EAAE,OAAO,SAAS;AACjD,WAAO,IAAI,oBAAQ,EAAE,UAAU,CAAC,EAC7B,mBAAmB,EAAE,KAAK,QAAQ,CAAC,EACnC,YAAY,EACZ,kBAAkB,SAAS,EAC3B,KAAK,MAAM;AAAA,EAChB;AAAA;AAgBA,SAAsB,kBACpB,OACA,WACqB;AAAA;AACrB,QAAI,CAAC,SAAS,CAAC,WAAW;AACxB,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AAEA,UAAM,SAAS,IAAI,YAAY,EAAE,OAAO,SAAS;AACjD,UAAM,EAAE,QAAQ,IAAI,UAAM,uBAAU,OAAO,QAAQ;AAAA,MACjD,YAAY,CAAC,OAAO;AAAA,IACtB,CAAC;AAED,QAAI,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,UAAU;AAC/D,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AAEA,WAAO;AAAA,MACL,WAAW,QAAQ;AAAA,MACnB,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA;AAgBO,SAAS,kBAAkB,OAA2B;AAC3D,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,oBAAoB;AAAA,EACtC;AAEA,QAAM,cAAU,uBAAU,KAAK;AAE/B,MAAI,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,UAAU;AAC/D,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AAEA,SAAO;AAAA,IACL,WAAW,QAAQ;AAAA,IACnB,KAAK,QAAQ;AAAA,IACb,KAAK,QAAQ;AAAA,EACf;AACF;AAoBO,SAAS,aAAa,WAAmB,WAA2B;AACzE,MAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AAGA,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,OAAO,KAAK,GAAG,SAAS,IAAI,SAAS,EAAE,EAAE,SAAS,QAAQ;AAAA,EACnE;AACA,SAAO,KAAK,GAAG,SAAS,IAAI,SAAS,EAAE;AACzC;AAcO,SAAS,YAAY,QAG1B;AACA,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,qBAAqB;AAAA,EACvC;AAEA,MAAI;AACF,QAAI;AACJ,QAAI,OAAO,WAAW,aAAa;AACjC,gBAAU,OAAO,KAAK,QAAQ,QAAQ,EAAE,SAAS,OAAO;AAAA,IAC1D,OAAO;AACL,gBAAU,KAAK,MAAM;AAAA,IACvB;AAEA,UAAM,aAAa,QAAQ,QAAQ,GAAG;AACtC,QAAI,eAAe,IAAI;AACrB,YAAM,IAAI,MAAM,yCAAyC;AAAA,IAC3D;AAEA,UAAM,YAAY,QAAQ,UAAU,GAAG,UAAU;AACjD,UAAM,YAAY,QAAQ,UAAU,aAAa,CAAC;AAElD,QAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,YAAM,IAAI,MAAM,8CAA8C;AAAA,IAChE;AAEA,WAAO,EAAE,WAAW,UAAU;AAAA,EAChC,SAAQ;AACN,UAAM,IAAI,MAAM,gEAAgE;AAAA,EAClF;AACF;","names":[]}
|
package/dist/auth.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { J as JwtPayload,
|
|
1
|
+
export { J as JwtPayload, t as createApiKey, r as createServerToken, s as decodeServerToken, u as parseApiKey, v as verifyServerToken } from './auth-CAV8xgZk.cjs';
|
|
2
2
|
import 'payload';
|
|
3
|
-
import './payload-types-
|
|
3
|
+
import './payload-types-2wbfaDxp.cjs';
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { J as JwtPayload,
|
|
1
|
+
export { J as JwtPayload, t as createApiKey, r as createServerToken, s as decodeServerToken, u as parseApiKey, v as verifyServerToken } from './auth-BieKA-OQ.js';
|
|
2
2
|
import 'payload';
|
|
3
|
-
import './payload-types-
|
|
3
|
+
import './payload-types-2wbfaDxp.js';
|
package/dist/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/internal/utils/index.ts"],"sourcesContent":["import { SignJWT, jwtVerify, decodeJwt } from 'jose'\nimport { createNetworkError, createUsageLimitError, createTimeoutError, TimeoutError, NetworkError } from '../errors'\nimport type { DebugConfig, RetryConfig } from '../../client/types'\nimport { API_URLS } from '../../client/types'\n\nconst DEFAULT_TIMEOUT = 30000\nconst DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504]\nconst NON_RETRYABLE_STATUSES = [401, 403, 404, 422]\nconst SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']\n\nexport interface FetchOptions extends RequestInit {\n clientKey?: string\n secretKey?: string\n customerToken?: string\n timeout?: number\n baseUrl?: string\n debug?: boolean | DebugConfig\n retry?: RetryConfig\n}\n\nexport interface JwtPayload {\n clientKey: string\n iat?: number\n exp?: number\n}\n\n/**\n * Creates a JWT token for server-side authentication.\n * The token is valid for 1 hour by default.\n *\n * @param clientKey - Client API key\n * @param secretKey - Secret key used for signing\n * @param expiresIn - Token expiration time (default: '1h')\n * @returns Promise<string> JWT token\n *\n * @example\n * ```typescript\n * const token = await createServerToken('client-key', 'secret-key')\n * // Use in Authorization header: `Bearer ${token}`\n * ```\n */\nexport async function createServerToken(\n clientKey: string,\n secretKey: string,\n expiresIn: string = '1h',\n): Promise<string> {\n if (!clientKey || !secretKey) {\n throw new Error('clientKey and secretKey are required.')\n }\n\n const secret = new TextEncoder().encode(secretKey)\n return new SignJWT({ clientKey })\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuedAt()\n .setExpirationTime(expiresIn)\n .sign(secret)\n}\n\n/**\n * Verifies a JWT token and returns the payload.\n *\n * @param token - JWT token to verify\n * @param secretKey - Secret key used for verification\n * @returns Promise<JwtPayload> Verified payload containing clientKey\n * @throws Error if token is invalid or expired\n *\n * @example\n * ```typescript\n * const payload = await verifyServerToken(token, 'secret-key')\n * console.log(payload.clientKey)\n * ```\n */\nexport async function verifyServerToken(\n token: string,\n secretKey: string,\n): Promise<JwtPayload> {\n if (!token || !secretKey) {\n throw new Error('token and secretKey are required.')\n }\n\n const secret = new TextEncoder().encode(secretKey)\n const { payload } = await jwtVerify(token, secret, {\n algorithms: ['HS256'],\n })\n\n if (!payload.clientKey || typeof payload.clientKey !== 'string') {\n throw new Error('Invalid token payload: clientKey is missing')\n }\n\n return {\n clientKey: payload.clientKey as string,\n iat: payload.iat,\n exp: payload.exp,\n }\n}\n\n/**\n * Decodes a JWT token without verification.\n * WARNING: Use this only when you need to inspect token contents.\n * Always use verifyServerToken for authentication.\n *\n * @param token - JWT token to decode\n * @returns JwtPayload Decoded payload (unverified)\n *\n * @example\n * ```typescript\n * const payload = decodeServerToken(token)\n * console.log(payload.clientKey) // Unverified!\n * ```\n */\nexport function decodeServerToken(token: string): JwtPayload {\n if (!token) {\n throw new Error('token is required.')\n }\n\n const payload = decodeJwt(token)\n\n if (!payload.clientKey || typeof payload.clientKey !== 'string') {\n throw new Error('Invalid token payload: clientKey is missing')\n }\n\n return {\n clientKey: payload.clientKey as string,\n iat: payload.iat,\n exp: payload.exp,\n }\n}\n\n// ============================================================================\n// API Key Utilities\n// ============================================================================\n\n/**\n * Creates a Base64-encoded API key from clientKey and secretKey.\n * Use this for MCP server authentication.\n *\n * @param clientKey - Client API key\n * @param secretKey - Secret key\n * @returns Base64-encoded API key\n *\n * @example\n * ```typescript\n * const apiKey = createApiKey('client-key', 'secret-key')\n * // Use in x-api-key header\n * ```\n */\nexport function createApiKey(clientKey: string, secretKey: string): string {\n if (!clientKey || !secretKey) {\n throw new Error('clientKey and secretKey are required.')\n }\n\n // Browser와 Node.js 모두 지원\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(`${clientKey}:${secretKey}`).toString('base64')\n }\n return btoa(`${clientKey}:${secretKey}`)\n}\n\n/**\n * Parses a Base64-encoded API key to extract clientKey and secretKey.\n *\n * @param apiKey - Base64-encoded API key\n * @returns Object containing clientKey and secretKey\n * @throws Error if API key is invalid\n *\n * @example\n * ```typescript\n * const { clientKey, secretKey } = parseApiKey(apiKey)\n * ```\n */\nexport function parseApiKey(apiKey: string): {\n clientKey: string\n secretKey: string\n} {\n if (!apiKey) {\n throw new Error('apiKey is required.')\n }\n\n try {\n let decoded: string\n if (typeof Buffer !== 'undefined') {\n decoded = Buffer.from(apiKey, 'base64').toString('utf-8')\n } else {\n decoded = atob(apiKey)\n }\n\n const colonIndex = decoded.indexOf(':')\n if (colonIndex === -1) {\n throw new Error('Invalid format: missing colon separator')\n }\n\n const clientKey = decoded.substring(0, colonIndex)\n const secretKey = decoded.substring(colonIndex + 1)\n\n if (!clientKey || !secretKey) {\n throw new Error('Invalid format: empty clientKey or secretKey')\n }\n\n return { clientKey, secretKey }\n } catch {\n throw new Error('Invalid API key. Expected Base64 encoded \"clientKey:secretKey\"')\n }\n}\n\nfunction debugLog(\n debug: boolean | DebugConfig | undefined,\n type: 'request' | 'response' | 'error',\n message: string,\n data?: unknown,\n) {\n if (!debug) return\n\n const shouldLog =\n debug === true ||\n (type === 'request' && (debug as DebugConfig).logRequests) ||\n (type === 'response' && (debug as DebugConfig).logResponses) ||\n (type === 'error' && (debug as DebugConfig).logErrors)\n\n if (shouldLog) {\n console.group(`[SDK ${type.toUpperCase()}] ${message}`)\n if (data) console.log(data)\n console.groupEnd()\n }\n}\n\nfunction getErrorSuggestion(status: number): string | undefined {\n if (status === 401) return 'Please check your authentication credentials.'\n if (status === 404) return 'The requested resource was not found.'\n if (status >= 500)\n return 'A server error occurred. Please try again later.'\n return undefined\n}\n\nasync function delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport async function _fetch(\n url: string,\n options?: FetchOptions,\n): Promise<Response> {\n const {\n clientKey,\n secretKey,\n customerToken,\n timeout = DEFAULT_TIMEOUT,\n baseUrl = API_URLS.production,\n debug,\n retry,\n ...requestInit\n } = options || {}\n\n const retryConfig = {\n maxRetries: retry?.maxRetries ?? 3,\n retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,\n retryDelay:\n retry?.retryDelay ??\n ((attempt: number) => Math.min(1000 * 2 ** attempt, 10000)),\n }\n\n // Generate JWT once before retry loop (token valid for 1h)\n let authToken: string | undefined\n if (secretKey && clientKey) {\n authToken = await createServerToken(clientKey, secretKey)\n } else if (customerToken) {\n authToken = customerToken\n }\n\n let lastError: Error | undefined\n\n for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {\n try {\n const headers = new Headers(requestInit.headers)\n\n if (clientKey) {\n headers.set('X-Client-Key', clientKey)\n }\n\n if (authToken) {\n headers.set('Authorization', `Bearer ${authToken}`)\n }\n\n if (!headers.has('Content-Type') && requestInit.body && !(requestInit.body instanceof FormData)) {\n headers.set('Content-Type', 'application/json')\n }\n\n // Redact sensitive headers for debug logging\n const redactedHeaders = Object.fromEntries(headers.entries())\n if (redactedHeaders['authorization']) {\n const token = redactedHeaders['authorization']\n // Show only \"Bearer eyJ...****\" to aid debugging without exposing the full token\n redactedHeaders['authorization'] = token.length > 15\n ? `${token.slice(0, 15)}...****`\n : '****'\n }\n\n debugLog(debug, 'request', url, {\n method: requestInit.method || 'GET',\n headers: redactedHeaders,\n attempt: attempt + 1,\n })\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n const response = await fetch(`${baseUrl}${url}`, {\n ...requestInit,\n headers,\n signal: controller.signal,\n })\n\n clearTimeout(timeoutId)\n\n debugLog(debug, 'response', url, {\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries()),\n })\n\n if (!response.ok) {\n // Usage limit 429 — never retry (distinguished by X-Usage-Limit header)\n if (\n response.status === 429 &&\n response.headers.get('X-Usage-Limit')\n ) {\n const limit = parseInt(response.headers.get('X-Usage-Limit') || '0', 10)\n const current = parseInt(response.headers.get('X-Usage-Current') || '0', 10)\n const remaining = parseInt(response.headers.get('X-Usage-Remaining') || '0', 10)\n\n throw createUsageLimitError(\n `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,\n { limit, current, remaining },\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n 'Monthly API call limit exceeded. Please upgrade your plan.',\n 'Upgrade your tenant plan to increase the monthly API call limit.',\n )\n }\n\n // Never retry non-retryable statuses regardless of user config\n if (NON_RETRYABLE_STATUSES.includes(response.status)) {\n throw createNetworkError(\n `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n `Request failed (status: ${response.status})`,\n getErrorSuggestion(response.status),\n )\n }\n\n const error = createNetworkError(\n `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n `Request failed (status: ${response.status})`,\n getErrorSuggestion(response.status),\n )\n\n const method = (requestInit.method || 'GET').toUpperCase()\n if (\n attempt < retryConfig.maxRetries &&\n SAFE_METHODS.includes(method) &&\n retryConfig.retryableStatuses.includes(response.status)\n ) {\n lastError = error\n const retryDelay = retryConfig.retryDelay(attempt)\n debugLog(debug, 'error', `Retrying in ${retryDelay}ms...`, error)\n await delay(retryDelay)\n continue\n }\n\n throw error\n }\n\n return response\n } catch (error) {\n debugLog(debug, 'error', url, error)\n\n const method = (requestInit.method || 'GET').toUpperCase()\n const isSafe = SAFE_METHODS.includes(method)\n\n if (error instanceof Error && error.name === 'AbortError') {\n const timeoutError = createTimeoutError(\n `Request timed out after ${timeout}ms.`,\n { url, timeout, attempt: attempt + 1 },\n 'The request timed out.',\n 'Please check your network connection or try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = timeoutError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw timeoutError\n }\n\n if (error instanceof TypeError) {\n const networkError = createNetworkError(\n 'Network connection failed.',\n undefined,\n { url, originalError: error.message, attempt: attempt + 1 },\n 'Network connection failed.',\n 'Please check your internet connection and try again.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = networkError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw networkError\n }\n\n if (error instanceof NetworkError || error instanceof TimeoutError) {\n if (\n isSafe &&\n attempt < retryConfig.maxRetries &&\n error.status &&\n !NON_RETRYABLE_STATUSES.includes(error.status) &&\n retryConfig.retryableStatuses.includes(error.status)\n ) {\n lastError = error\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw error\n }\n\n const unknownError = createNetworkError(\n error instanceof Error\n ? error.message\n : 'An unknown network error occurred.',\n undefined,\n { url, originalError: error, attempt: attempt + 1 },\n 'An unknown error occurred.',\n 'Please try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = unknownError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw unknownError\n }\n }\n\n throw lastError ?? new NetworkError('Request failed after retries')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,WAAW,iBAAiB;AAyC9C,SAAsB,kBACpB,WACA,WACA,YAAoB,MACH;AAAA;AACjB,QAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,YAAM,IAAI,MAAM,uCAAuC;AAAA,IACzD;AAEA,UAAM,SAAS,IAAI,YAAY,EAAE,OAAO,SAAS;AACjD,WAAO,IAAI,QAAQ,EAAE,UAAU,CAAC,EAC7B,mBAAmB,EAAE,KAAK,QAAQ,CAAC,EACnC,YAAY,EACZ,kBAAkB,SAAS,EAC3B,KAAK,MAAM;AAAA,EAChB;AAAA;AAgBA,SAAsB,kBACpB,OACA,WACqB;AAAA;AACrB,QAAI,CAAC,SAAS,CAAC,WAAW;AACxB,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AAEA,UAAM,SAAS,IAAI,YAAY,EAAE,OAAO,SAAS;AACjD,UAAM,EAAE,QAAQ,IAAI,MAAM,UAAU,OAAO,QAAQ;AAAA,MACjD,YAAY,CAAC,OAAO;AAAA,IACtB,CAAC;AAED,QAAI,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,UAAU;AAC/D,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AAEA,WAAO;AAAA,MACL,WAAW,QAAQ;AAAA,MACnB,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA;AAgBO,SAAS,kBAAkB,OAA2B;AAC3D,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,oBAAoB;AAAA,EACtC;AAEA,QAAM,UAAU,UAAU,KAAK;AAE/B,MAAI,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,UAAU;AAC/D,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AAEA,SAAO;AAAA,IACL,WAAW,QAAQ;AAAA,IACnB,KAAK,QAAQ;AAAA,IACb,KAAK,QAAQ;AAAA,EACf;AACF;AAoBO,SAAS,aAAa,WAAmB,WAA2B;AACzE,MAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AAGA,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,OAAO,KAAK,GAAG,SAAS,IAAI,SAAS,EAAE,EAAE,SAAS,QAAQ;AAAA,EACnE;AACA,SAAO,KAAK,GAAG,SAAS,IAAI,SAAS,EAAE;AACzC;AAcO,SAAS,YAAY,QAG1B;AACA,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,qBAAqB;AAAA,EACvC;AAEA,MAAI;AACF,QAAI;AACJ,QAAI,OAAO,WAAW,aAAa;AACjC,gBAAU,OAAO,KAAK,QAAQ,QAAQ,EAAE,SAAS,OAAO;AAAA,IAC1D,OAAO;AACL,gBAAU,KAAK,MAAM;AAAA,IACvB;AAEA,UAAM,aAAa,QAAQ,QAAQ,GAAG;AACtC,QAAI,eAAe,IAAI;AACrB,YAAM,IAAI,MAAM,yCAAyC;AAAA,IAC3D;AAEA,UAAM,YAAY,QAAQ,UAAU,GAAG,UAAU;AACjD,UAAM,YAAY,QAAQ,UAAU,aAAa,CAAC;AAElD,QAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,YAAM,IAAI,MAAM,8CAA8C;AAAA,IAChE;AAEA,WAAO,EAAE,WAAW,UAAU;AAAA,EAChC,SAAQ;AACN,UAAM,IAAI,MAAM,gEAAgE;AAAA,EAClF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/core/internal/utils/index.ts"],"sourcesContent":["import { SignJWT, jwtVerify, decodeJwt } from 'jose'\nimport { createNetworkError, createUsageLimitError, createTimeoutError, TimeoutError, NetworkError } from '../errors'\nimport type { DebugConfig, RetryConfig } from '../../client/types'\nimport { API_URLS } from '../../client/types'\n\nconst DEFAULT_TIMEOUT = 30000\nconst DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504]\nconst NON_RETRYABLE_STATUSES = [401, 403, 404, 422]\nconst SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']\n\nexport interface FetchOptions extends RequestInit {\n clientKey?: string\n secretKey?: string\n customerToken?: string\n timeout?: number\n baseUrl?: string\n debug?: boolean | DebugConfig\n retry?: RetryConfig\n /** Called on 401 when customerToken is set. Return a new token to retry, or null to fail. */\n onUnauthorized?: () => Promise<string | null>\n}\n\nexport interface JwtPayload {\n clientKey: string\n iat?: number\n exp?: number\n}\n\n/**\n * Creates a JWT token for server-side authentication.\n * The token is valid for 1 hour by default.\n *\n * @param clientKey - Client API key\n * @param secretKey - Secret key used for signing\n * @param expiresIn - Token expiration time (default: '1h')\n * @returns Promise<string> JWT token\n *\n * @example\n * ```typescript\n * const token = await createServerToken('client-key', 'secret-key')\n * // Use in Authorization header: `Bearer ${token}`\n * ```\n */\nexport async function createServerToken(\n clientKey: string,\n secretKey: string,\n expiresIn: string = '1h',\n): Promise<string> {\n if (!clientKey || !secretKey) {\n throw new Error('clientKey and secretKey are required.')\n }\n\n const secret = new TextEncoder().encode(secretKey)\n return new SignJWT({ clientKey })\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuedAt()\n .setExpirationTime(expiresIn)\n .sign(secret)\n}\n\n/**\n * Verifies a JWT token and returns the payload.\n *\n * @param token - JWT token to verify\n * @param secretKey - Secret key used for verification\n * @returns Promise<JwtPayload> Verified payload containing clientKey\n * @throws Error if token is invalid or expired\n *\n * @example\n * ```typescript\n * const payload = await verifyServerToken(token, 'secret-key')\n * console.log(payload.clientKey)\n * ```\n */\nexport async function verifyServerToken(\n token: string,\n secretKey: string,\n): Promise<JwtPayload> {\n if (!token || !secretKey) {\n throw new Error('token and secretKey are required.')\n }\n\n const secret = new TextEncoder().encode(secretKey)\n const { payload } = await jwtVerify(token, secret, {\n algorithms: ['HS256'],\n })\n\n if (!payload.clientKey || typeof payload.clientKey !== 'string') {\n throw new Error('Invalid token payload: clientKey is missing')\n }\n\n return {\n clientKey: payload.clientKey as string,\n iat: payload.iat,\n exp: payload.exp,\n }\n}\n\n/**\n * Decodes a JWT token without verification.\n * WARNING: Use this only when you need to inspect token contents.\n * Always use verifyServerToken for authentication.\n *\n * @param token - JWT token to decode\n * @returns JwtPayload Decoded payload (unverified)\n *\n * @example\n * ```typescript\n * const payload = decodeServerToken(token)\n * console.log(payload.clientKey) // Unverified!\n * ```\n */\nexport function decodeServerToken(token: string): JwtPayload {\n if (!token) {\n throw new Error('token is required.')\n }\n\n const payload = decodeJwt(token)\n\n if (!payload.clientKey || typeof payload.clientKey !== 'string') {\n throw new Error('Invalid token payload: clientKey is missing')\n }\n\n return {\n clientKey: payload.clientKey as string,\n iat: payload.iat,\n exp: payload.exp,\n }\n}\n\n// ============================================================================\n// API Key Utilities\n// ============================================================================\n\n/**\n * Creates a Base64-encoded API key from clientKey and secretKey.\n * Use this for MCP server authentication.\n *\n * @param clientKey - Client API key\n * @param secretKey - Secret key\n * @returns Base64-encoded API key\n *\n * @example\n * ```typescript\n * const apiKey = createApiKey('client-key', 'secret-key')\n * // Use in x-api-key header\n * ```\n */\nexport function createApiKey(clientKey: string, secretKey: string): string {\n if (!clientKey || !secretKey) {\n throw new Error('clientKey and secretKey are required.')\n }\n\n // Browser와 Node.js 모두 지원\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(`${clientKey}:${secretKey}`).toString('base64')\n }\n return btoa(`${clientKey}:${secretKey}`)\n}\n\n/**\n * Parses a Base64-encoded API key to extract clientKey and secretKey.\n *\n * @param apiKey - Base64-encoded API key\n * @returns Object containing clientKey and secretKey\n * @throws Error if API key is invalid\n *\n * @example\n * ```typescript\n * const { clientKey, secretKey } = parseApiKey(apiKey)\n * ```\n */\nexport function parseApiKey(apiKey: string): {\n clientKey: string\n secretKey: string\n} {\n if (!apiKey) {\n throw new Error('apiKey is required.')\n }\n\n try {\n let decoded: string\n if (typeof Buffer !== 'undefined') {\n decoded = Buffer.from(apiKey, 'base64').toString('utf-8')\n } else {\n decoded = atob(apiKey)\n }\n\n const colonIndex = decoded.indexOf(':')\n if (colonIndex === -1) {\n throw new Error('Invalid format: missing colon separator')\n }\n\n const clientKey = decoded.substring(0, colonIndex)\n const secretKey = decoded.substring(colonIndex + 1)\n\n if (!clientKey || !secretKey) {\n throw new Error('Invalid format: empty clientKey or secretKey')\n }\n\n return { clientKey, secretKey }\n } catch {\n throw new Error('Invalid API key. Expected Base64 encoded \"clientKey:secretKey\"')\n }\n}\n\nfunction debugLog(\n debug: boolean | DebugConfig | undefined,\n type: 'request' | 'response' | 'error',\n message: string,\n data?: unknown,\n) {\n if (!debug) return\n\n const shouldLog =\n debug === true ||\n (type === 'request' && (debug as DebugConfig).logRequests) ||\n (type === 'response' && (debug as DebugConfig).logResponses) ||\n (type === 'error' && (debug as DebugConfig).logErrors)\n\n if (shouldLog) {\n console.group(`[SDK ${type.toUpperCase()}] ${message}`)\n if (data) console.log(data)\n console.groupEnd()\n }\n}\n\nfunction getErrorSuggestion(status: number): string | undefined {\n if (status === 401) return 'Please check your authentication credentials.'\n if (status === 404) return 'The requested resource was not found.'\n if (status >= 500)\n return 'A server error occurred. Please try again later.'\n return undefined\n}\n\nasync function delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport async function _fetch(\n url: string,\n options?: FetchOptions,\n): Promise<Response> {\n const {\n clientKey,\n secretKey,\n customerToken,\n timeout = DEFAULT_TIMEOUT,\n baseUrl = API_URLS.production,\n debug,\n retry,\n onUnauthorized,\n ...requestInit\n } = options || {}\n\n const retryConfig = {\n maxRetries: retry?.maxRetries ?? 3,\n retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,\n retryDelay:\n retry?.retryDelay ??\n ((attempt: number) => Math.min(1000 * 2 ** attempt, 10000)),\n }\n\n // Generate JWT once before retry loop (token valid for 1h)\n let authToken: string | undefined\n if (secretKey && clientKey) {\n authToken = await createServerToken(clientKey, secretKey)\n } else if (customerToken) {\n authToken = customerToken\n }\n\n let lastError: Error | undefined\n let hasRetried401 = false\n\n for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {\n try {\n const headers = new Headers(requestInit.headers)\n\n if (clientKey) {\n headers.set('X-Client-Key', clientKey)\n }\n\n if (authToken) {\n headers.set('Authorization', `Bearer ${authToken}`)\n }\n\n if (!headers.has('Content-Type') && requestInit.body && !(requestInit.body instanceof FormData)) {\n headers.set('Content-Type', 'application/json')\n }\n\n // Redact sensitive headers for debug logging\n const redactedHeaders = Object.fromEntries(headers.entries())\n if (redactedHeaders['authorization']) {\n const token = redactedHeaders['authorization']\n // Show only \"Bearer eyJ...****\" to aid debugging without exposing the full token\n redactedHeaders['authorization'] = token.length > 15\n ? `${token.slice(0, 15)}...****`\n : '****'\n }\n\n debugLog(debug, 'request', url, {\n method: requestInit.method || 'GET',\n headers: redactedHeaders,\n attempt: attempt + 1,\n })\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n const response = await fetch(`${baseUrl}${url}`, {\n ...requestInit,\n headers,\n signal: controller.signal,\n })\n\n clearTimeout(timeoutId)\n\n debugLog(debug, 'response', url, {\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries()),\n })\n\n if (!response.ok) {\n // Usage limit 429 — never retry (distinguished by X-Usage-Limit header)\n if (\n response.status === 429 &&\n response.headers.get('X-Usage-Limit')\n ) {\n const limit = parseInt(response.headers.get('X-Usage-Limit') || '0', 10)\n const current = parseInt(response.headers.get('X-Usage-Current') || '0', 10)\n const remaining = parseInt(response.headers.get('X-Usage-Remaining') || '0', 10)\n\n throw createUsageLimitError(\n `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,\n { limit, current, remaining },\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n 'Monthly API call limit exceeded. Please upgrade your plan.',\n 'Upgrade your tenant plan to increase the monthly API call limit.',\n )\n }\n\n // Auto-refresh customer token on 401\n if (response.status === 401 && onUnauthorized && customerToken && !hasRetried401) {\n hasRetried401 = true\n try {\n const newToken = await onUnauthorized()\n if (newToken) {\n authToken = newToken\n continue\n }\n } catch {\n // Refresh failed, fall through to throw\n }\n }\n\n // Never retry non-retryable statuses regardless of user config\n if (NON_RETRYABLE_STATUSES.includes(response.status)) {\n throw createNetworkError(\n `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n `Request failed (status: ${response.status})`,\n getErrorSuggestion(response.status),\n )\n }\n\n const error = createNetworkError(\n `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n { url, method: requestInit.method || 'GET', attempt: attempt + 1 },\n `Request failed (status: ${response.status})`,\n getErrorSuggestion(response.status),\n )\n\n const method = (requestInit.method || 'GET').toUpperCase()\n if (\n attempt < retryConfig.maxRetries &&\n SAFE_METHODS.includes(method) &&\n retryConfig.retryableStatuses.includes(response.status)\n ) {\n lastError = error\n const retryDelay = retryConfig.retryDelay(attempt)\n debugLog(debug, 'error', `Retrying in ${retryDelay}ms...`, error)\n await delay(retryDelay)\n continue\n }\n\n throw error\n }\n\n return response\n } catch (error) {\n debugLog(debug, 'error', url, error)\n\n const method = (requestInit.method || 'GET').toUpperCase()\n const isSafe = SAFE_METHODS.includes(method)\n\n if (error instanceof Error && error.name === 'AbortError') {\n const timeoutError = createTimeoutError(\n `Request timed out after ${timeout}ms.`,\n { url, timeout, attempt: attempt + 1 },\n 'The request timed out.',\n 'Please check your network connection or try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = timeoutError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw timeoutError\n }\n\n if (error instanceof TypeError) {\n const networkError = createNetworkError(\n 'Network connection failed.',\n undefined,\n { url, originalError: error.message, attempt: attempt + 1 },\n 'Network connection failed.',\n 'Please check your internet connection and try again.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = networkError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw networkError\n }\n\n if (error instanceof NetworkError || error instanceof TimeoutError) {\n if (\n isSafe &&\n attempt < retryConfig.maxRetries &&\n error.status &&\n !NON_RETRYABLE_STATUSES.includes(error.status) &&\n retryConfig.retryableStatuses.includes(error.status)\n ) {\n lastError = error\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw error\n }\n\n const unknownError = createNetworkError(\n error instanceof Error\n ? error.message\n : 'An unknown network error occurred.',\n undefined,\n { url, originalError: error, attempt: attempt + 1 },\n 'An unknown error occurred.',\n 'Please try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = unknownError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw unknownError\n }\n }\n\n throw lastError ?? new NetworkError('Request failed after retries')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,WAAW,iBAAiB;AA2C9C,SAAsB,kBACpB,WACA,WACA,YAAoB,MACH;AAAA;AACjB,QAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,YAAM,IAAI,MAAM,uCAAuC;AAAA,IACzD;AAEA,UAAM,SAAS,IAAI,YAAY,EAAE,OAAO,SAAS;AACjD,WAAO,IAAI,QAAQ,EAAE,UAAU,CAAC,EAC7B,mBAAmB,EAAE,KAAK,QAAQ,CAAC,EACnC,YAAY,EACZ,kBAAkB,SAAS,EAC3B,KAAK,MAAM;AAAA,EAChB;AAAA;AAgBA,SAAsB,kBACpB,OACA,WACqB;AAAA;AACrB,QAAI,CAAC,SAAS,CAAC,WAAW;AACxB,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AAEA,UAAM,SAAS,IAAI,YAAY,EAAE,OAAO,SAAS;AACjD,UAAM,EAAE,QAAQ,IAAI,MAAM,UAAU,OAAO,QAAQ;AAAA,MACjD,YAAY,CAAC,OAAO;AAAA,IACtB,CAAC;AAED,QAAI,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,UAAU;AAC/D,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AAEA,WAAO;AAAA,MACL,WAAW,QAAQ;AAAA,MACnB,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA;AAgBO,SAAS,kBAAkB,OAA2B;AAC3D,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,oBAAoB;AAAA,EACtC;AAEA,QAAM,UAAU,UAAU,KAAK;AAE/B,MAAI,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,UAAU;AAC/D,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AAEA,SAAO;AAAA,IACL,WAAW,QAAQ;AAAA,IACnB,KAAK,QAAQ;AAAA,IACb,KAAK,QAAQ;AAAA,EACf;AACF;AAoBO,SAAS,aAAa,WAAmB,WAA2B;AACzE,MAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AAGA,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,OAAO,KAAK,GAAG,SAAS,IAAI,SAAS,EAAE,EAAE,SAAS,QAAQ;AAAA,EACnE;AACA,SAAO,KAAK,GAAG,SAAS,IAAI,SAAS,EAAE;AACzC;AAcO,SAAS,YAAY,QAG1B;AACA,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,qBAAqB;AAAA,EACvC;AAEA,MAAI;AACF,QAAI;AACJ,QAAI,OAAO,WAAW,aAAa;AACjC,gBAAU,OAAO,KAAK,QAAQ,QAAQ,EAAE,SAAS,OAAO;AAAA,IAC1D,OAAO;AACL,gBAAU,KAAK,MAAM;AAAA,IACvB;AAEA,UAAM,aAAa,QAAQ,QAAQ,GAAG;AACtC,QAAI,eAAe,IAAI;AACrB,YAAM,IAAI,MAAM,yCAAyC;AAAA,IAC3D;AAEA,UAAM,YAAY,QAAQ,UAAU,GAAG,UAAU;AACjD,UAAM,YAAY,QAAQ,UAAU,aAAa,CAAC;AAElD,QAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,YAAM,IAAI,MAAM,8CAA8C;AAAA,IAChE;AAEA,WAAO,EAAE,WAAW,UAAU;AAAA,EAChC,SAAQ;AACN,UAAM,IAAI,MAAM,gEAAgE;AAAA,EAClF;AACF;","names":[]}
|
package/dist/components.d.cts
CHANGED
|
@@ -2,7 +2,7 @@ import React, { CSSProperties, JSX } from 'react';
|
|
|
2
2
|
import { SerializedLinkNode, SerializedBlockNode } from '@payloadcms/richtext-lexical';
|
|
3
3
|
import { SerializedEditorState, SerializedLexicalNode } from '@payloadcms/richtext-lexical/lexical';
|
|
4
4
|
import { JSXConverters, JSXConverter } from '@payloadcms/richtext-lexical/react';
|
|
5
|
-
import { F as Form } from './payload-types-
|
|
5
|
+
import { F as Form } from './payload-types-2wbfaDxp.cjs';
|
|
6
6
|
import { I as ImageData } from './image-TT8lTsk5.cjs';
|
|
7
7
|
import { BundledTheme } from 'shiki';
|
|
8
8
|
export { BundledTheme } from 'shiki';
|
package/dist/components.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import React, { CSSProperties, JSX } from 'react';
|
|
|
2
2
|
import { SerializedLinkNode, SerializedBlockNode } from '@payloadcms/richtext-lexical';
|
|
3
3
|
import { SerializedEditorState, SerializedLexicalNode } from '@payloadcms/richtext-lexical/lexical';
|
|
4
4
|
import { JSXConverters, JSXConverter } from '@payloadcms/richtext-lexical/react';
|
|
5
|
-
import { F as Form } from './payload-types-
|
|
5
|
+
import { F as Form } from './payload-types-2wbfaDxp.js';
|
|
6
6
|
import { I as ImageData } from './image-TT8lTsk5.js';
|
|
7
7
|
import { BundledTheme } from 'shiki';
|
|
8
8
|
export { BundledTheme } from 'shiki';
|