@ledewire/browser 0.2.1 → 0.3.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 (36) hide show
  1. package/README.md +12 -0
  2. package/dist/index.d.ts +1457 -33
  3. package/dist/index.js +53 -28
  4. package/dist/index.js.map +1 -1
  5. package/dist/ledewire.min.js +1 -1
  6. package/dist/ledewire.min.js.map +1 -1
  7. package/package.json +2 -2
  8. package/dist/client.d.ts +0 -89
  9. package/dist/client.d.ts.map +0 -1
  10. package/dist/client.test.d.ts +0 -2
  11. package/dist/client.test.d.ts.map +0 -1
  12. package/dist/index.d.ts.map +0 -1
  13. package/dist/local-storage-adapter.d.ts +0 -27
  14. package/dist/local-storage-adapter.d.ts.map +0 -1
  15. package/dist/local-storage-adapter.test.d.ts +0 -2
  16. package/dist/local-storage-adapter.test.d.ts.map +0 -1
  17. package/dist/resources/auth.d.ts +0 -45
  18. package/dist/resources/auth.d.ts.map +0 -1
  19. package/dist/resources/auth.test.d.ts +0 -2
  20. package/dist/resources/auth.test.d.ts.map +0 -1
  21. package/dist/resources/checkout.d.ts +0 -31
  22. package/dist/resources/checkout.d.ts.map +0 -1
  23. package/dist/resources/checkout.test.d.ts +0 -2
  24. package/dist/resources/checkout.test.d.ts.map +0 -1
  25. package/dist/resources/content.d.ts +0 -27
  26. package/dist/resources/content.d.ts.map +0 -1
  27. package/dist/resources/content.test.d.ts +0 -2
  28. package/dist/resources/content.test.d.ts.map +0 -1
  29. package/dist/resources/purchases.d.ts +0 -38
  30. package/dist/resources/purchases.d.ts.map +0 -1
  31. package/dist/resources/purchases.test.d.ts +0 -2
  32. package/dist/resources/purchases.test.d.ts.map +0 -1
  33. package/dist/resources/wallet.d.ts +0 -44
  34. package/dist/resources/wallet.d.ts.map +0 -1
  35. package/dist/resources/wallet.test.d.ts +0 -2
  36. package/dist/resources/wallet.test.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ledewire.min.js","sources":["../../core/src/errors.ts","../../core/src/http-client.ts","../../core/src/token-manager.ts","../src/resources/auth.ts","../src/resources/content.ts","../src/resources/purchases.ts","../src/resources/wallet.ts","../src/resources/checkout.ts","../src/client.ts","../src/local-storage-adapter.ts"],"sourcesContent":["/**\n * Base error class for all LedeWire SDK errors.\n * All errors thrown by the SDK are instances of this class,\n * making it safe to use `err instanceof LedewireError` as a type guard.\n *\n * @example\n * ```ts\n * try {\n * await client.purchases.create({ contentId: '...' })\n * } catch (err) {\n * if (err instanceof LedewireError) {\n * console.error(err.statusCode, err.message)\n * }\n * }\n * ```\n */\nexport class LedewireError extends Error {\n /** HTTP status code returned by the API (e.g. 400, 401, 404, 422). */\n public readonly statusCode: number\n\n /** Machine-readable error code from the API error body, if present. */\n public readonly code: number | undefined\n\n constructor(message: string, statusCode: number, code?: number) {\n super(message)\n this.name = 'LedewireError'\n this.statusCode = statusCode\n this.code = code\n // Restore prototype chain (required for extending built-in Error in TS)\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n\n/**\n * Thrown when the request lacks valid authentication credentials,\n * or when a token refresh fails and re-authentication is required.\n */\nexport class AuthError extends LedewireError {\n constructor(message: string, code?: number) {\n super(message, 401, code)\n this.name = 'AuthError'\n }\n}\n\n/**\n * Thrown when the authenticated user does not have permission\n * to perform the requested operation.\n */\nexport class ForbiddenError extends LedewireError {\n constructor(message: string, code?: number) {\n super(message, 403, code)\n this.name = 'ForbiddenError'\n }\n}\n\n/**\n * Thrown when the requested resource does not exist.\n */\nexport class NotFoundError extends LedewireError {\n constructor(message: string, code?: number) {\n super(message, 404, code)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when the purchase cannot be completed due to a validation\n * failure, such as a price mismatch or a duplicate purchase.\n */\nexport class PurchaseError extends LedewireError {\n constructor(message: string, statusCode: number, code?: number) {\n super(message, statusCode, code)\n this.name = 'PurchaseError'\n }\n}\n","import type { components } from './api.gen.js'\nimport { AuthError, ForbiddenError, LedewireError, NotFoundError } from './errors.js'\n\n/** @internal */\ntype ApiErrorBody = components['schemas']['ErrorResponse']\n\n/**\n * Configuration options for `HttpClient`.\n */\nexport interface HttpClientConfig {\n /** API base URL. Defaults to the production API. */\n baseUrl?: string\n /**\n * Returns the current access token (or null) before each request.\n * If null, requests are sent without an Authorization header.\n */\n getAccessToken?: () => string | null | Promise<string | null>\n /**\n * Called when a 401 is received on the first attempt.\n * Should refresh and return the new access token, or null to propagate\n * an `AuthError` to the caller.\n */\n onUnauthorized?: () => string | null | Promise<string | null>\n}\n\nconst DEFAULT_BASE_URL = 'https://api.ledewire.com'\n\n/**\n * Core HTTP client used by all SDK packages.\n *\n * Features:\n * - Injects `Authorization: Bearer <token>` headers automatically\n * - Maps HTTP error responses to typed `LedewireError` subclasses\n * - On receiving a 401, calls `onUnauthorized` once and retries the request\n *\n * This is an internal class - consumers should use the\n * package-level client factories (`init` / `createClient`) instead.\n */\nexport class HttpClient {\n private readonly baseUrl: string\n private readonly getAccessToken: NonNullable<HttpClientConfig['getAccessToken']>\n private readonly onUnauthorized: NonNullable<HttpClientConfig['onUnauthorized']>\n\n constructor(config: HttpClientConfig = {}) {\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n this.getAccessToken = config.getAccessToken ?? (() => null)\n this.onUnauthorized = config.onUnauthorized ?? (() => null)\n }\n\n /**\n * GET request with optional query parameters.\n * @param path - API path (e.g. `/v1/wallet/balance`)\n * @param params - Query string parameters\n */\n async get<T>(path: string, params?: Record<string, string>): Promise<T> {\n return this.request<T>('GET', this.buildUrl(path, params))\n }\n\n /**\n * POST request.\n * @param path - API path\n * @param body - Request body (JSON-serialized)\n */\n async post<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('POST', this.buildUrl(path), body)\n }\n\n /**\n * PUT request.\n * @param path - API path\n * @param body - Request body (JSON-serialized)\n */\n async put<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('PUT', this.buildUrl(path), body)\n }\n\n /**\n * PATCH request.\n * @param path - API path\n * @param body - Partial update body (JSON-serialized)\n */\n async patch<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('PATCH', this.buildUrl(path), body)\n }\n\n /**\n * DELETE request.\n * @param path - API path\n */\n async delete<T = void>(path: string): Promise<T> {\n return this.request<T>('DELETE', this.buildUrl(path))\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private buildUrl(path: string, params?: Record<string, string>): string {\n const url = `${this.baseUrl}${path}`\n if (!params || Object.keys(params).length === 0) return url\n return `${url}?${new URLSearchParams(params).toString()}`\n }\n\n private async request<T>(\n method: string,\n url: string,\n body?: unknown,\n isRetry = false,\n ): Promise<T> {\n const token = await this.getAccessToken()\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (token) headers['Authorization'] = `Bearer ${token}`\n\n const response = await fetch(url, {\n method,\n headers,\n ...(body !== undefined && { body: JSON.stringify(body) }),\n })\n\n if (response.status === 401 && !isRetry) {\n const newToken = await this.onUnauthorized()\n if (newToken) {\n return this.request<T>(method, url, body, true)\n }\n throw new AuthError('Session expired. Please re-authenticate.')\n }\n\n if (!response.ok) {\n await this.throwApiError(response)\n }\n\n if (response.status === 204) {\n return undefined as T\n }\n\n return response.json() as Promise<T>\n }\n\n private async throwApiError(response: Response): Promise<never> {\n let body: ApiErrorBody | undefined\n try {\n body = (await response.json()) as ApiErrorBody\n } catch {\n // Non-JSON body - fall through to use statusText\n }\n\n const message = body?.error.message ?? response.statusText\n const code = body?.error.code\n\n switch (response.status) {\n case 401:\n throw new AuthError(message, code)\n case 403:\n throw new ForbiddenError(message, code)\n case 404:\n throw new NotFoundError(message, code)\n default:\n throw new LedewireError(message, response.status, code)\n }\n }\n}\n","import type { StoredTokens, TokenStorage } from './types.js'\nimport { AuthError } from './errors.js'\n\n/** How many milliseconds before expiry to proactively refresh the token. */\nconst REFRESH_THRESHOLD_MS = 60_000 // 60 seconds\n\n/**\n * Options for constructing a `TokenManager`.\n */\nexport interface TokenManagerOptions {\n storage: TokenStorage\n /**\n * Exchanges a refresh token for a new token pair.\n * Implemented by each package's client factory using the\n * `/v1/auth/token/refresh` endpoint.\n */\n refreshFn: (refreshToken: string) => Promise<StoredTokens>\n /**\n * Called after a successful token refresh.\n * Use in server environments to persist the new tokens to a database or cache.\n *\n * @example\n * ```ts\n * onTokenRefreshed: async (tokens) => {\n * await redis.set('session:tokens', JSON.stringify(tokens))\n * }\n * ```\n */\n onTokenRefreshed?: (tokens: StoredTokens) => void | Promise<void>\n /**\n * Called when a refresh attempt fails and the user must re-authenticate.\n * Typically used to redirect to login or emit a UI event.\n *\n * @example\n * ```ts\n * onAuthExpired: () => { window.location.href = '/login' }\n * ```\n */\n onAuthExpired?: () => void | Promise<void>\n}\n\n/**\n * Manages the JWT token lifecycle transparently.\n *\n * - Proactively refreshes the access token when it expires within 60 seconds\n * - Handles reactive refresh on 401 responses from the HTTP client\n * - Deduplicates concurrent refresh calls (only one in-flight refresh at a time)\n * - Fires `onAuthExpired` when refresh fails so the UI can prompt re-login\n *\n * This is an internal class - use the package-level client factories instead.\n */\nexport class TokenManager {\n private readonly storage: TokenStorage\n private readonly refreshFn: TokenManagerOptions['refreshFn']\n private readonly onTokenRefreshed: TokenManagerOptions['onTokenRefreshed']\n private readonly onAuthExpired: TokenManagerOptions['onAuthExpired']\n private refreshPromise: Promise<StoredTokens | null> | null = null\n\n constructor(options: TokenManagerOptions) {\n this.storage = options.storage\n this.refreshFn = options.refreshFn\n this.onTokenRefreshed = options.onTokenRefreshed\n this.onAuthExpired = options.onAuthExpired\n }\n\n /**\n * Returns a valid access token, refreshing proactively if needed.\n * Returns `null` if no tokens are stored (user not authenticated).\n */\n async getAccessToken(): Promise<string | null> {\n const stored = await this.storage.getTokens()\n if (!stored) return null\n\n const expiresInMs = stored.expiresAt - Date.now()\n if (expiresInMs < REFRESH_THRESHOLD_MS) {\n const refreshed = await this.performRefresh(stored.refreshToken)\n return refreshed?.accessToken ?? null\n }\n\n return stored.accessToken\n }\n\n /**\n * Called by `HttpClient` when a 401 is received.\n * Attempts one refresh; returns the new access token or null.\n */\n async handleUnauthorized(): Promise<string | null> {\n const stored = await this.storage.getTokens()\n if (!stored) {\n await this.onAuthExpired?.()\n return null\n }\n const refreshed = await this.performRefresh(stored.refreshToken)\n if (!refreshed) await this.onAuthExpired?.()\n return refreshed?.accessToken ?? null\n }\n\n /** Store new tokens after a successful login or signup. */\n async setTokens(tokens: StoredTokens): Promise<void> {\n await this.storage.setTokens(tokens)\n }\n\n /** Clear all stored tokens (call on logout). */\n async clearTokens(): Promise<void> {\n await this.storage.clearTokens()\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private performRefresh(refreshToken: string): Promise<StoredTokens | null> {\n if (this.refreshPromise) return this.refreshPromise\n\n this.refreshPromise = this.refreshFn(refreshToken)\n .then(async (tokens) => {\n await this.storage.setTokens(tokens)\n await this.onTokenRefreshed?.(tokens)\n return tokens\n })\n .catch((_err: unknown) => {\n void this.storage.clearTokens()\n throw new AuthError('Token refresh failed. Please re-authenticate.')\n })\n .finally(() => {\n this.refreshPromise = null\n })\n\n return this.refreshPromise\n }\n}\n\n// ---------------------------------------------------------------------------\n// Built-in storage adapters\n// ---------------------------------------------------------------------------\n\n/**\n * In-memory token storage (default for both packages).\n * Tokens are cleared when the page unloads or the process exits.\n * This is the most secure default for browser environments.\n */\nexport class MemoryTokenStorage implements TokenStorage {\n private tokens: StoredTokens | null = null\n\n getTokens(): StoredTokens | null {\n return this.tokens\n }\n\n setTokens(tokens: StoredTokens): void {\n this.tokens = tokens\n }\n\n clearTokens(): void {\n this.tokens = null\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts an `expires_at` ISO 8601 string from an API auth response\n * into a Unix timestamp (milliseconds) for use in `StoredTokens.expiresAt`.\n *\n * @param expiresAt - ISO 8601 datetime string, e.g. `\"2026-01-01T12:00:00Z\"`\n * @returns Unix timestamp in milliseconds\n */\nexport function parseExpiresAt(expiresAt: string): number {\n return new Date(expiresAt).getTime()\n}\n","/**\n * Buyer authentication namespace for browser environments.\n *\n * Tokens are stored automatically in the `TokenManager` after every\n * successful call — callers never need to manage tokens directly.\n *\n * @module\n */\nimport { parseExpiresAt } from '@ledewire/core'\nimport type { HttpClient, TokenManager } from '@ledewire/core'\nimport type {\n AuthLoginEmailRequest,\n AuthLoginOAuthRequest,\n AuthSignupRequest,\n AuthenticationResponse,\n} from '@ledewire/core'\n\n/**\n * Buyer authentication: signup, email/password login, Google OAuth.\n *\n * Obtain via `lw.auth` — do not construct directly.\n *\n * @example\n * ```ts\n * const lw = Ledewire.init({ apiKey: 'your_api_key' })\n * await lw.auth.loginWithEmail({ email: 'u@example.com', password: 'pw' })\n * ```\n */\nexport class BrowserAuthNamespace {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly tokenManager: TokenManager,\n ) {}\n\n /**\n * Register a new buyer account with email and password.\n * Tokens are stored automatically after successful signup.\n *\n * @param body - Signup credentials and display name.\n * @returns The authentication token response.\n */\n async signup(body: AuthSignupRequest): Promise<AuthenticationResponse> {\n const res = await this.http.post<AuthenticationResponse>('/v1/auth/signup', body)\n await this.storeTokens(res)\n return res\n }\n\n /**\n * Log in with email and password.\n * Tokens are stored automatically after successful login.\n *\n * @param body - Email and password credentials.\n * @returns The authentication token response.\n */\n async loginWithEmail(body: AuthLoginEmailRequest): Promise<AuthenticationResponse> {\n const res = await this.http.post<AuthenticationResponse>('/v1/auth/login/email', body)\n await this.storeTokens(res)\n return res\n }\n\n /**\n * Log in with a Google ID token obtained from the Google OAuth flow.\n * Tokens are stored automatically after successful login.\n *\n * @param body - The Google ID token.\n * @returns The authentication token response.\n */\n async loginWithGoogle(body: AuthLoginOAuthRequest): Promise<AuthenticationResponse> {\n const res = await this.http.post<AuthenticationResponse>('/v1/auth/login/google', body)\n await this.storeTokens(res)\n return res\n }\n\n private async storeTokens(res: AuthenticationResponse): Promise<void> {\n await this.tokenManager.setTokens({\n accessToken: res.access_token,\n refreshToken: res.refresh_token,\n expiresAt: parseExpiresAt(res.expires_at),\n })\n }\n}\n","import type { HttpClient } from '@ledewire/core'\nimport type { ContentWithAccessResponse } from '@ledewire/core'\n\n/**\n * Buyer content namespace — fetch content with real-time access information.\n *\n * Obtain via `lw.content` — do not construct directly.\n *\n * @example\n * ```ts\n * const { content, access } = await lw.content.getWithAccess('content-id')\n * if (access.has_access) showFullContent(content)\n * ```\n */\nexport class BrowserContentNamespace {\n constructor(protected readonly http: HttpClient) {}\n\n /**\n * Returns a content item together with access information for the\n * authenticated buyer (or a generic access response when unauthenticated).\n *\n * @param id - The content ID.\n * @param userId - Optional user ID to check a specific user's access status.\n * @returns The content item with access information.\n */\n async getWithAccess(id: string, userId?: string): Promise<ContentWithAccessResponse> {\n const params: Record<string, string> = {}\n if (userId !== undefined) {\n params['user_id'] = userId\n }\n return this.http.get<ContentWithAccessResponse>(\n `/v1/content/${id}/with-access`,\n Object.keys(params).length > 0 ? params : undefined,\n )\n }\n}\n","import type { HttpClient } from '@ledewire/core'\nimport type { PurchaseCreateRequest, PurchaseResponse } from '@ledewire/core'\n\n/**\n * Buyer purchases namespace — create and retrieve content purchases.\n *\n * Obtain via `lw.purchases` — do not construct directly.\n *\n * @example\n * ```ts\n * await lw.purchases.create({ content_id: 'content-id' })\n * const all = await lw.purchases.list()\n * ```\n */\nexport class BrowserPurchasesNamespace {\n constructor(protected readonly http: HttpClient) {}\n\n /**\n * Completes a content purchase using the buyer's wallet balance.\n *\n * @param body - The content ID and expected price in cents.\n * @returns The completed purchase record.\n */\n async create(body: PurchaseCreateRequest): Promise<PurchaseResponse> {\n return this.http.post<PurchaseResponse>('/v1/purchases', body)\n }\n\n /**\n * Returns all purchases made by the authenticated buyer.\n *\n * @returns A list of purchase records, newest first.\n */\n async list(): Promise<PurchaseResponse[]> {\n return this.http.get<PurchaseResponse[]>('/v1/purchases')\n }\n\n /**\n * Returns a single purchase by ID.\n *\n * @param id - The purchase ID.\n * @returns The purchase record.\n */\n async get(id: string): Promise<PurchaseResponse> {\n return this.http.get<PurchaseResponse>(`/v1/purchases/${id}`)\n }\n}\n","import type { HttpClient } from '@ledewire/core'\nimport type {\n WalletBalanceResponse,\n WalletPaymentSessionRequest,\n WalletPaymentSessionResponse,\n WalletPaymentStatusResponse,\n WalletTransactionItem,\n} from '@ledewire/core'\n\n/**\n * Buyer wallet namespace — balance, transactions, and payment session management.\n *\n * Obtain via `lw.wallet` — do not construct directly.\n *\n * @example\n * ```ts\n * const { balance_cents } = await lw.wallet.balance()\n * const session = await lw.wallet.createPaymentSession({ amount_cents: 500 })\n * ```\n */\nexport class BrowserWalletNamespace {\n constructor(protected readonly http: HttpClient) {}\n\n /**\n * Returns the authenticated buyer's current wallet balance.\n *\n * @returns The current wallet balance in cents.\n */\n async balance(): Promise<WalletBalanceResponse> {\n return this.http.get<WalletBalanceResponse>('/v1/wallet/balance')\n }\n\n /**\n * Returns the authenticated buyer's wallet transaction history, newest first.\n *\n * @returns A list of completed wallet transaction entries.\n */\n async transactions(): Promise<WalletTransactionItem[]> {\n return this.http.get<WalletTransactionItem[]>('/v1/wallet/transactions')\n }\n\n /**\n * Creates a payment session for funding the buyer's wallet.\n *\n * @param body - The amount and currency to fund.\n * @returns Payment session details for use with the payment provider widget.\n */\n async createPaymentSession(\n body: WalletPaymentSessionRequest,\n ): Promise<WalletPaymentSessionResponse> {\n return this.http.post<WalletPaymentSessionResponse>('/v1/wallet/payment-session', body)\n }\n\n /**\n * Polls the status of a wallet funding payment session.\n *\n * @param sessionId - The session ID returned by `createPaymentSession`.\n * @returns The current payment status.\n */\n async getPaymentStatus(sessionId: string): Promise<WalletPaymentStatusResponse> {\n return this.http.get<WalletPaymentStatusResponse>(`/v1/wallet/payment-status/${sessionId}`)\n }\n}\n","import type { HttpClient } from '@ledewire/core'\nimport type { CheckoutStateResponse } from '@ledewire/core'\n\n/**\n * Checkout namespace — buyer checkout state for a specific content item.\n *\n * Obtain via `lw.checkout` — do not construct directly.\n *\n * @example\n * ```ts\n * const state = await lw.checkout.state('content-id')\n * // state.checkout_state.next_required_action:\n * // 'authenticate' | 'fund_wallet' | 'purchase' | 'view_content'\n * ```\n */\nexport class CheckoutNamespace {\n constructor(protected readonly http: HttpClient) {}\n\n /**\n * Returns the authenticated buyer's checkout readiness for a given piece of\n * content. Indicates whether the buyer needs to authenticate, fund their\n * wallet, or purchase before accessing the content.\n *\n * Works without authentication — returns anonymous checkout state when the\n * buyer is not logged in.\n *\n * @param contentId - The content item ID.\n * @returns The checkout state, including what action is required next.\n */\n async state(contentId: string): Promise<CheckoutStateResponse> {\n return this.http.get<CheckoutStateResponse>(`/v1/checkout/state/${contentId}`)\n }\n}\n","import { HttpClient, MemoryTokenStorage, TokenManager, parseExpiresAt } from '@ledewire/core'\nimport type { TokenStorage } from '@ledewire/core'\nimport { BrowserAuthNamespace } from './resources/auth.js'\nimport { BrowserContentNamespace } from './resources/content.js'\nimport { BrowserPurchasesNamespace } from './resources/purchases.js'\nimport { BrowserWalletNamespace } from './resources/wallet.js'\nimport { CheckoutNamespace } from './resources/checkout.js'\n\n/**\n * Configuration options for the LedeWire browser client.\n */\nexport interface BrowserClientConfig {\n /**\n * LedeWire API key that identifies the store.\n * Obtained from the LedeWire merchant dashboard.\n */\n apiKey: string\n /**\n * Override the API base URL.\n * Defaults to `https://api.ledewire.com`.\n */\n baseUrl?: string\n /**\n * Token storage adapter.\n * Defaults to {@link MemoryTokenStorage} (in-memory, most secure).\n *\n * To persist sessions across page reloads, use the built-in\n * `localStorageAdapter`:\n * ```ts\n * import { init, localStorageAdapter } from '@ledewire/browser'\n * const lw = init({ apiKey: '...', storage: localStorageAdapter() })\n * ```\n */\n storage?: TokenStorage\n /**\n * Called when the user's session expires and cannot be refreshed.\n * Use this to show a re-authentication prompt.\n *\n * @example\n * ```ts\n * onAuthExpired: () => showLoginModal()\n * ```\n */\n onAuthExpired?: () => void\n}\n\n/**\n * Initialises a LedeWire browser client.\n * This is the primary entry point for the browser SDK.\n *\n * @example CDN usage:\n * ```html\n * <script src=\"https://cdn.jsdelivr.net/npm/@ledewire/browser@1/dist/ledewire.min.js\"></script>\n * <script>\n * const lw = Ledewire.init({ apiKey: 'your_api_key' })\n * const state = await lw.checkout.state('content-id')\n * </script>\n * ```\n *\n * @example npm usage:\n * ```ts\n * import { init } from '@ledewire/browser'\n * const lw = init({ apiKey: 'your_api_key' })\n * ```\n */\nexport function init(config: BrowserClientConfig): BrowserClient {\n const baseUrl = config.baseUrl ?? 'https://api.ledewire.com'\n const storage = config.storage ?? new MemoryTokenStorage()\n\n const tokenManager = new TokenManager({\n storage,\n refreshFn: async (refreshToken) => {\n const res = await fetch(`${baseUrl}/v1/auth/token/refresh`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ refresh_token: refreshToken }),\n })\n if (!res.ok) throw new Error('Token refresh failed')\n const data = (await res.json()) as {\n access_token: string\n refresh_token: string\n expires_at: string\n }\n return {\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresAt: parseExpiresAt(data.expires_at),\n }\n },\n ...(config.onAuthExpired !== undefined && { onAuthExpired: config.onAuthExpired }),\n })\n\n const http = new HttpClient({\n baseUrl,\n getAccessToken: () => tokenManager.getAccessToken(),\n onUnauthorized: () => tokenManager.handleUnauthorized(),\n })\n\n return new BrowserClient(http, tokenManager, config)\n}\n\n/**\n * The LedeWire browser client.\n * Access buyer flows through the namespaced properties.\n *\n * @remarks\n * Instantiate with {@link init} rather than constructing directly.\n */\nexport class BrowserClient {\n /** Buyer authentication: email/password signup/login, Google, password reset */\n readonly auth: BrowserAuthNamespace\n\n /** Checkout state machine: determines next action for a piece of content */\n readonly checkout: CheckoutNamespace\n\n /** Wallet: balance, fund via payment session, transaction history */\n readonly wallet: BrowserWalletNamespace\n\n /** Content purchases for the authenticated buyer */\n readonly purchases: BrowserPurchasesNamespace\n\n /** Public content with per-user access information */\n readonly content: BrowserContentNamespace\n\n /** @internal */\n constructor(\n public readonly _http: HttpClient,\n public readonly _tokenManager: TokenManager,\n public readonly _config: BrowserClientConfig,\n ) {\n this.auth = new BrowserAuthNamespace(_http, _tokenManager)\n this.checkout = new CheckoutNamespace(_http)\n this.wallet = new BrowserWalletNamespace(_http)\n this.purchases = new BrowserPurchasesNamespace(_http)\n this.content = new BrowserContentNamespace(_http)\n }\n}\n","import type { TokenStorage, StoredTokens } from '@ledewire/core'\n\nconst DEFAULT_STORAGE_KEY = 'lw:tokens'\n\n/**\n * A {@link TokenStorage} adapter that persists tokens in `localStorage`.\n *\n * Tokens survive page reloads and browser restarts, which is convenient\n * for sites where users expect persistent sessions.\n *\n * **Security note:** `localStorage` is accessible to any JavaScript on the\n * same origin. Only use this adapter on sites you fully control and trust.\n * The default in-memory storage is safer for high-security use cases.\n *\n * @param key - The `localStorage` key used to store tokens.\n * Defaults to `'lw:tokens'`. Override this if you have multiple\n * LedeWire integrations on the same origin.\n *\n * @example\n * ```ts\n * import { init, localStorageAdapter } from '@ledewire/browser'\n *\n * const lw = init({\n * apiKey: 'your_api_key',\n * storage: localStorageAdapter(),\n * })\n * ```\n */\nexport function localStorageAdapter(key = DEFAULT_STORAGE_KEY): TokenStorage {\n return {\n getTokens(): StoredTokens | null {\n const raw = localStorage.getItem(key)\n if (!raw) return null\n try {\n return JSON.parse(raw) as StoredTokens\n } catch {\n // Corrupted value - treat as empty\n return null\n }\n },\n setTokens(tokens: StoredTokens): void {\n localStorage.setItem(key, JSON.stringify(tokens))\n },\n clearTokens(): void {\n localStorage.removeItem(key)\n },\n }\n}\n"],"names":["LedewireError","message","statusCode","code","__publicField","AuthError","ForbiddenError","NotFoundError","PurchaseError","DEFAULT_BASE_URL","HttpClient","config","path","params","body","url","method","isRetry","token","headers","response","REFRESH_THRESHOLD_MS","TokenManager","options","stored","refreshed","tokens","refreshToken","_err","MemoryTokenStorage","parseExpiresAt","expiresAt","BrowserAuthNamespace","http","tokenManager","res","BrowserContentNamespace","id","userId","BrowserPurchasesNamespace","BrowserWalletNamespace","sessionId","CheckoutNamespace","contentId","init","baseUrl","storage","data","BrowserClient","_http","_tokenManager","_config","DEFAULT_STORAGE_KEY","localStorageAdapter","key","raw"],"mappings":"2MAgBO,MAAMA,UAAsB,KAAM,CAOvC,YAAYC,EAAiBC,EAAoBC,EAAe,CAC9D,MAAMF,CAAO,EANCG,EAAA,mBAGAA,EAAA,aAId,KAAK,KAAO,gBACZ,KAAK,WAAaF,EAClB,KAAK,KAAOC,EAEZ,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,CAMO,MAAME,UAAkBL,CAAc,CAC3C,YAAYC,EAAiBE,EAAe,CAC1C,MAAMF,EAAS,IAAKE,CAAI,EACxB,KAAK,KAAO,WACd,CACF,CAMO,MAAMG,UAAuBN,CAAc,CAChD,YAAYC,EAAiBE,EAAe,CAC1C,MAAMF,EAAS,IAAKE,CAAI,EACxB,KAAK,KAAO,gBACd,CACF,CAKO,MAAMI,UAAsBP,CAAc,CAC/C,YAAYC,EAAiBE,EAAe,CAC1C,MAAMF,EAAS,IAAKE,CAAI,EACxB,KAAK,KAAO,eACd,CACF,CAMO,MAAMK,UAAsBR,CAAc,CAC/C,YAAYC,EAAiBC,EAAoBC,EAAe,CAC9D,MAAMF,EAASC,EAAYC,CAAI,EAC/B,KAAK,KAAO,eACd,CACF,CCjDA,MAAMM,EAAmB,2BAalB,MAAMC,CAAW,CAKtB,YAAYC,EAA2B,GAAI,CAJ1BP,EAAA,gBACAA,EAAA,uBACAA,EAAA,uBAGf,KAAK,SAAWO,EAAO,SAAWF,GAAkB,QAAQ,MAAO,EAAE,EACrE,KAAK,eAAiBE,EAAO,iBAAmB,IAAM,MACtD,KAAK,eAAiBA,EAAO,iBAAmB,IAAM,KACxD,CAOA,MAAM,IAAOC,EAAcC,EAA6C,CACtE,OAAO,KAAK,QAAW,MAAO,KAAK,SAASD,EAAMC,CAAM,CAAC,CAC3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ACF,OAAO,KAAK,MAAMA,CAAG,CACvB,MAAQ,CAEN,OAAO,IACT,CACF,EACA,UAAU7B,EAA4B,CACpC,aAAa,QAAQ4B,EAAK,KAAK,UAAU5B,CAAM,CAAC,CAClD,EACA,aAAoB,CAClB,aAAa,WAAW4B,CAAG,CAC7B,CAAA,CAEJ"}
1
+ {"version":3,"file":"ledewire.min.js","sources":["../../core/src/errors.ts","../../core/src/http-client.ts","../../core/src/token-manager.ts","../src/resources/auth.ts","../src/resources/config.ts","../src/resources/content.ts","../src/resources/purchases.ts","../src/resources/wallet.ts","../src/resources/checkout.ts","../src/client.ts","../src/local-storage-adapter.ts"],"sourcesContent":["/**\n * Base error class for all LedeWire SDK errors.\n * All errors thrown by the SDK are instances of this class,\n * making it safe to use `err instanceof LedewireError` as a type guard.\n *\n * @example\n * ```ts\n * try {\n * await client.purchases.create({ contentId: '...' })\n * } catch (err) {\n * if (err instanceof LedewireError) {\n * console.error(err.statusCode, err.message)\n * }\n * }\n * ```\n */\nexport class LedewireError extends Error {\n /** HTTP status code returned by the API (e.g. 400, 401, 404, 422). */\n public readonly statusCode: number\n\n /** Machine-readable error code from the API error body, if present. */\n public readonly code: number | undefined\n\n constructor(message: string, statusCode: number, code?: number) {\n super(message)\n this.name = 'LedewireError'\n this.statusCode = statusCode\n this.code = code\n // Restore prototype chain (required for extending built-in Error in TS)\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n\n/**\n * Thrown when the request lacks valid authentication credentials,\n * or when a token refresh fails and re-authentication is required.\n */\nexport class AuthError extends LedewireError {\n constructor(message: string, code?: number) {\n super(message, 401, code)\n this.name = 'AuthError'\n }\n}\n\n/**\n * Thrown when the authenticated user does not have permission\n * to perform the requested operation.\n */\nexport class ForbiddenError extends LedewireError {\n constructor(message: string, code?: number) {\n super(message, 403, code)\n this.name = 'ForbiddenError'\n }\n}\n\n/**\n * Thrown when the requested resource does not exist.\n */\nexport class NotFoundError extends LedewireError {\n constructor(message: string, code?: number) {\n super(message, 404, code)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when the purchase cannot be completed due to a validation\n * failure, such as a price mismatch or a duplicate purchase.\n */\nexport class PurchaseError extends LedewireError {\n constructor(message: string, statusCode: number, code?: number) {\n super(message, statusCode, code)\n this.name = 'PurchaseError'\n }\n}\n","import type { components } from './api.gen.js'\nimport { AuthError, ForbiddenError, LedewireError, NotFoundError } from './errors.js'\n\n/** @internal */\ntype ApiErrorBody = components['schemas']['ErrorResponse']\n\n/**\n * Configuration options for `HttpClient`.\n */\nexport interface HttpClientConfig {\n /** API base URL. Defaults to the production API. */\n baseUrl?: string\n /**\n * Returns the current access token (or null) before each request.\n * If null, requests are sent without an Authorization header.\n */\n getAccessToken?: () => string | null | Promise<string | null>\n /**\n * Called when a 401 is received on the first attempt.\n * Should refresh and return the new access token, or null to propagate\n * an `AuthError` to the caller.\n */\n onUnauthorized?: () => string | null | Promise<string | null>\n}\n\nconst DEFAULT_BASE_URL = 'https://api.ledewire.com'\n\n/**\n * Core HTTP client used by all SDK packages.\n *\n * Features:\n * - Injects `Authorization: Bearer <token>` headers automatically\n * - Maps HTTP error responses to typed `LedewireError` subclasses\n * - On receiving a 401, calls `onUnauthorized` once and retries the request\n *\n * This is an internal class - consumers should use the\n * package-level client factories (`init` / `createClient`) instead.\n */\nexport class HttpClient {\n private readonly baseUrl: string\n private readonly getAccessToken: NonNullable<HttpClientConfig['getAccessToken']>\n private readonly onUnauthorized: NonNullable<HttpClientConfig['onUnauthorized']>\n\n constructor(config: HttpClientConfig = {}) {\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n this.getAccessToken = config.getAccessToken ?? (() => null)\n this.onUnauthorized = config.onUnauthorized ?? (() => null)\n }\n\n /**\n * GET request with optional query parameters.\n * @param path - API path (e.g. `/v1/wallet/balance`)\n * @param params - Query string parameters\n */\n async get<T>(path: string, params?: Record<string, string>): Promise<T> {\n return this.request<T>('GET', this.buildUrl(path, params))\n }\n\n /**\n * POST request.\n * @param path - API path\n * @param body - Request body (JSON-serialized)\n */\n async post<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('POST', this.buildUrl(path), body)\n }\n\n /**\n * PUT request.\n * @param path - API path\n * @param body - Request body (JSON-serialized)\n */\n async put<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('PUT', this.buildUrl(path), body)\n }\n\n /**\n * PATCH request.\n * @param path - API path\n * @param body - Partial update body (JSON-serialized)\n */\n async patch<T>(path: string, body?: unknown): Promise<T> {\n return this.request<T>('PATCH', this.buildUrl(path), body)\n }\n\n /**\n * DELETE request.\n * @param path - API path\n */\n async delete<T = void>(path: string): Promise<T> {\n return this.request<T>('DELETE', this.buildUrl(path))\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private buildUrl(path: string, params?: Record<string, string>): string {\n const url = `${this.baseUrl}${path}`\n if (!params || Object.keys(params).length === 0) return url\n return `${url}?${new URLSearchParams(params).toString()}`\n }\n\n private async request<T>(\n method: string,\n url: string,\n body?: unknown,\n isRetry = false,\n ): Promise<T> {\n const token = await this.getAccessToken()\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (token) headers['Authorization'] = `Bearer ${token}`\n\n const response = await fetch(url, {\n method,\n headers,\n ...(body !== undefined && { body: JSON.stringify(body) }),\n })\n\n if (response.status === 401 && !isRetry) {\n const newToken = await this.onUnauthorized()\n if (newToken) {\n return this.request<T>(method, url, body, true)\n }\n throw new AuthError('Session expired. Please re-authenticate.')\n }\n\n if (!response.ok) {\n await this.throwApiError(response)\n }\n\n if (response.status === 204) {\n return undefined as T\n }\n\n return response.json() as Promise<T>\n }\n\n private async throwApiError(response: Response): Promise<never> {\n let body: ApiErrorBody | undefined\n try {\n body = (await response.json()) as ApiErrorBody\n } catch {\n // Non-JSON body - fall through to use statusText\n }\n\n const message = body?.error.message ?? response.statusText\n const code = body?.error.code\n\n switch (response.status) {\n case 401:\n throw new AuthError(message, code)\n case 403:\n throw new ForbiddenError(message, code)\n case 404:\n throw new NotFoundError(message, code)\n default:\n throw new LedewireError(message, response.status, code)\n }\n }\n}\n","import type { StoredTokens, TokenStorage } from './types.js'\nimport { AuthError } from './errors.js'\n\n/** How many milliseconds before expiry to proactively refresh the token. */\nconst REFRESH_THRESHOLD_MS = 60_000 // 60 seconds\n\n/**\n * Options for constructing a `TokenManager`.\n */\nexport interface TokenManagerOptions {\n storage: TokenStorage\n /**\n * Exchanges a refresh token for a new token pair.\n * Implemented by each package's client factory using the\n * `/v1/auth/token/refresh` endpoint.\n */\n refreshFn: (refreshToken: string) => Promise<StoredTokens>\n /**\n * Called after a successful token refresh.\n * Use in server environments to persist the new tokens to a database or cache.\n *\n * @example\n * ```ts\n * onTokenRefreshed: async (tokens) => {\n * await redis.set('session:tokens', JSON.stringify(tokens))\n * }\n * ```\n */\n onTokenRefreshed?: (tokens: StoredTokens) => void | Promise<void>\n /**\n * Called when a refresh attempt fails and the user must re-authenticate.\n * Typically used to redirect to login or emit a UI event.\n *\n * @example\n * ```ts\n * onAuthExpired: () => { window.location.href = '/login' }\n * ```\n */\n onAuthExpired?: () => void | Promise<void>\n}\n\n/**\n * Manages the JWT token lifecycle transparently.\n *\n * - Proactively refreshes the access token when it expires within 60 seconds\n * - Handles reactive refresh on 401 responses from the HTTP client\n * - Deduplicates concurrent refresh calls (only one in-flight refresh at a time)\n * - Fires `onAuthExpired` when refresh fails so the UI can prompt re-login\n *\n * This is an internal class - use the package-level client factories instead.\n */\nexport class TokenManager {\n private readonly storage: TokenStorage\n private readonly refreshFn: TokenManagerOptions['refreshFn']\n private readonly onTokenRefreshed: TokenManagerOptions['onTokenRefreshed']\n private readonly onAuthExpired: TokenManagerOptions['onAuthExpired']\n private refreshPromise: Promise<StoredTokens | null> | null = null\n\n constructor(options: TokenManagerOptions) {\n this.storage = options.storage\n this.refreshFn = options.refreshFn\n this.onTokenRefreshed = options.onTokenRefreshed\n this.onAuthExpired = options.onAuthExpired\n }\n\n /**\n * Returns a valid access token, refreshing proactively if needed.\n * Returns `null` if no tokens are stored (user not authenticated).\n */\n async getAccessToken(): Promise<string | null> {\n const stored = await this.storage.getTokens()\n if (!stored) return null\n\n const expiresInMs = stored.expiresAt - Date.now()\n if (expiresInMs < REFRESH_THRESHOLD_MS) {\n const refreshed = await this.performRefresh(stored.refreshToken)\n return refreshed?.accessToken ?? null\n }\n\n return stored.accessToken\n }\n\n /**\n * Called by `HttpClient` when a 401 is received.\n * Attempts one refresh; returns the new access token or null.\n */\n async handleUnauthorized(): Promise<string | null> {\n const stored = await this.storage.getTokens()\n if (!stored) {\n await this.onAuthExpired?.()\n return null\n }\n const refreshed = await this.performRefresh(stored.refreshToken)\n if (!refreshed) await this.onAuthExpired?.()\n return refreshed?.accessToken ?? null\n }\n\n /** Store new tokens after a successful login or signup. */\n async setTokens(tokens: StoredTokens): Promise<void> {\n await this.storage.setTokens(tokens)\n }\n\n /** Clear all stored tokens (call on logout). */\n async clearTokens(): Promise<void> {\n await this.storage.clearTokens()\n }\n\n // ---------------------------------------------------------------------------\n // Private\n // ---------------------------------------------------------------------------\n\n private performRefresh(refreshToken: string): Promise<StoredTokens | null> {\n if (this.refreshPromise) return this.refreshPromise\n\n this.refreshPromise = this.refreshFn(refreshToken)\n .then(async (tokens) => {\n await this.storage.setTokens(tokens)\n await this.onTokenRefreshed?.(tokens)\n return tokens\n })\n .catch((_err: unknown) => {\n void this.storage.clearTokens()\n throw new AuthError('Token refresh failed. Please re-authenticate.')\n })\n .finally(() => {\n this.refreshPromise = null\n })\n\n return this.refreshPromise\n }\n}\n\n// ---------------------------------------------------------------------------\n// Built-in storage adapters\n// ---------------------------------------------------------------------------\n\n/**\n * In-memory token storage (default for both packages).\n * Tokens are cleared when the page unloads or the process exits.\n * This is the most secure default for browser environments.\n */\nexport class MemoryTokenStorage implements TokenStorage {\n private tokens: StoredTokens | null = null\n\n getTokens(): StoredTokens | null {\n return this.tokens\n }\n\n setTokens(tokens: StoredTokens): void {\n this.tokens = tokens\n }\n\n clearTokens(): void {\n this.tokens = null\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts an `expires_at` ISO 8601 string from an API auth response\n * into a Unix timestamp (milliseconds) for use in `StoredTokens.expiresAt`.\n *\n * @param expiresAt - ISO 8601 datetime string, e.g. `\"2026-01-01T12:00:00Z\"`\n * @returns Unix timestamp in milliseconds\n */\nexport function parseExpiresAt(expiresAt: string): number {\n return new Date(expiresAt).getTime()\n}\n","/**\n * Buyer authentication namespace for browser environments.\n *\n * Tokens are stored automatically in the `TokenManager` after every\n * successful call — callers never need to manage tokens directly.\n *\n * @module\n */\nimport { parseExpiresAt } from '@ledewire/core'\nimport type { HttpClient, TokenManager } from '@ledewire/core'\nimport type {\n AuthLoginEmailRequest,\n AuthLoginOAuthRequest,\n AuthSignupRequest,\n AuthenticationResponse,\n} from '@ledewire/core'\n\n/**\n * Buyer authentication: signup, email/password login, Google OAuth.\n *\n * Obtain via `lw.auth` — do not construct directly.\n *\n * @example\n * ```ts\n * const lw = Ledewire.init({ apiKey: 'your_api_key' })\n * await lw.auth.loginWithEmail({ email: 'u@example.com', password: 'pw' })\n * ```\n */\nexport class BrowserAuthNamespace {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly tokenManager: TokenManager,\n ) {}\n\n /**\n * Register a new buyer account with email and password.\n * Tokens are stored automatically after successful signup.\n *\n * @param body - Signup credentials and display name.\n * @returns The authentication token response.\n */\n async signup(body: AuthSignupRequest): Promise<AuthenticationResponse> {\n const res = await this.http.post<AuthenticationResponse>('/v1/auth/signup', body)\n await this.storeTokens(res)\n return res\n }\n\n /**\n * Log in with email and password.\n * Tokens are stored automatically after successful login.\n *\n * @param body - Email and password credentials.\n * @returns The authentication token response.\n */\n async loginWithEmail(body: AuthLoginEmailRequest): Promise<AuthenticationResponse> {\n const res = await this.http.post<AuthenticationResponse>('/v1/auth/login/email', body)\n await this.storeTokens(res)\n return res\n }\n\n /**\n * Log in with a Google ID token obtained from the Google OAuth flow.\n * Tokens are stored automatically after successful login.\n *\n * @param body - The Google ID token.\n * @returns The authentication token response.\n */\n async loginWithGoogle(body: AuthLoginOAuthRequest): Promise<AuthenticationResponse> {\n const res = await this.http.post<AuthenticationResponse>('/v1/auth/login/google', body)\n await this.storeTokens(res)\n return res\n }\n\n private async storeTokens(res: AuthenticationResponse): Promise<void> {\n await this.tokenManager.setTokens({\n accessToken: res.access_token,\n refreshToken: res.refresh_token,\n expiresAt: parseExpiresAt(res.expires_at),\n })\n }\n}\n","/**\n * Platform configuration namespace (browser).\n *\n * Provides access to public (unauthenticated) platform-level configuration.\n *\n * @module\n */\nimport type { HttpClient } from '@ledewire/core'\nimport type { PublicConfigResponse } from '@ledewire/core'\n\n/**\n * Platform-level configuration for browser clients.\n *\n * Obtain via `client.config` — do not construct directly.\n */\nexport class BrowserConfigNamespace {\n /** @internal */\n constructor(protected readonly http: HttpClient) {}\n\n /**\n * Returns platform-level public configuration.\n * No authentication required — safe to call before the user has signed in.\n *\n * Use `google_client_id` to initialise the Google Identity Services library\n * on the storefront login page without requiring a prior authenticated call.\n *\n * @example\n * ```ts\n * const lw = init({ apiKey: 'your_api_key' })\n * const { google_client_id } = await lw.config.getPublic()\n * google.accounts.id.initialize({ client_id: google_client_id, callback })\n * ```\n */\n async getPublic(): Promise<PublicConfigResponse> {\n return this.http.get<PublicConfigResponse>('/v1/config/public')\n }\n}\n","import type { HttpClient } from '@ledewire/core'\nimport type { ContentWithAccessResponse } from '@ledewire/core'\n\n/**\n * Buyer content namespace — fetch content with real-time access information.\n *\n * Obtain via `lw.content` — do not construct directly.\n *\n * @example\n * ```ts\n * const { content, access } = await lw.content.getWithAccess('content-id')\n * if (access.has_access) showFullContent(content)\n * ```\n */\nexport class BrowserContentNamespace {\n constructor(protected readonly http: HttpClient) {}\n\n /**\n * Returns a content item together with access information for the\n * authenticated buyer (or a generic access response when unauthenticated).\n *\n * @param id - The content ID.\n * @param userId - Optional user ID to check a specific user's access status.\n * @returns The content item with access information.\n */\n async getWithAccess(id: string, userId?: string): Promise<ContentWithAccessResponse> {\n const params: Record<string, string> = {}\n if (userId !== undefined) {\n params['user_id'] = userId\n }\n return this.http.get<ContentWithAccessResponse>(\n `/v1/content/${id}/with-access`,\n Object.keys(params).length > 0 ? params : undefined,\n )\n }\n}\n","import type { HttpClient } from '@ledewire/core'\nimport type { PurchaseCreateRequest, PurchaseResponse } from '@ledewire/core'\n\n/**\n * Buyer purchases namespace — create and retrieve content purchases.\n *\n * Obtain via `lw.purchases` — do not construct directly.\n *\n * @example\n * ```ts\n * await lw.purchases.create({ content_id: 'content-id' })\n * const all = await lw.purchases.list()\n * ```\n */\nexport class BrowserPurchasesNamespace {\n constructor(protected readonly http: HttpClient) {}\n\n /**\n * Completes a content purchase using the buyer's wallet balance.\n *\n * @param body - The content ID and expected price in cents.\n * @returns The completed purchase record.\n */\n async create(body: PurchaseCreateRequest): Promise<PurchaseResponse> {\n return this.http.post<PurchaseResponse>('/v1/purchases', body)\n }\n\n /**\n * Returns all purchases made by the authenticated buyer.\n *\n * @returns A list of purchase records, newest first.\n */\n async list(): Promise<PurchaseResponse[]> {\n return this.http.get<PurchaseResponse[]>('/v1/purchases')\n }\n\n /**\n * Returns a single purchase by ID.\n *\n * @param id - The purchase ID.\n * @returns The purchase record.\n */\n async get(id: string): Promise<PurchaseResponse> {\n return this.http.get<PurchaseResponse>(`/v1/purchases/${id}`)\n }\n}\n","import type { HttpClient } from '@ledewire/core'\nimport type {\n WalletBalanceResponse,\n WalletPaymentSessionRequest,\n WalletPaymentSessionResponse,\n WalletPaymentStatusResponse,\n WalletTransactionItem,\n} from '@ledewire/core'\n\n/**\n * Buyer wallet namespace — balance, transactions, and payment session management.\n *\n * Obtain via `lw.wallet` — do not construct directly.\n *\n * @example\n * ```ts\n * const { balance_cents } = await lw.wallet.balance()\n * const session = await lw.wallet.createPaymentSession({ amount_cents: 500 })\n * ```\n */\nexport class BrowserWalletNamespace {\n constructor(protected readonly http: HttpClient) {}\n\n /**\n * Returns the authenticated buyer's current wallet balance.\n *\n * @returns The current wallet balance in cents.\n */\n async balance(): Promise<WalletBalanceResponse> {\n return this.http.get<WalletBalanceResponse>('/v1/wallet/balance')\n }\n\n /**\n * Returns the authenticated buyer's wallet transaction history, newest first.\n *\n * @returns A list of completed wallet transaction entries.\n */\n async transactions(): Promise<WalletTransactionItem[]> {\n return this.http.get<WalletTransactionItem[]>('/v1/wallet/transactions')\n }\n\n /**\n * Creates a payment session for funding the buyer's wallet.\n *\n * @param body - The amount and currency to fund.\n * @returns Payment session details for use with the payment provider widget.\n */\n async createPaymentSession(\n body: WalletPaymentSessionRequest,\n ): Promise<WalletPaymentSessionResponse> {\n return this.http.post<WalletPaymentSessionResponse>('/v1/wallet/payment-session', body)\n }\n\n /**\n * Polls the status of a wallet funding payment session.\n *\n * @param sessionId - The session ID returned by `createPaymentSession`.\n * @returns The current payment status.\n */\n async getPaymentStatus(sessionId: string): Promise<WalletPaymentStatusResponse> {\n return this.http.get<WalletPaymentStatusResponse>(`/v1/wallet/payment-status/${sessionId}`)\n }\n}\n","import type { HttpClient } from '@ledewire/core'\nimport type { CheckoutStateResponse } from '@ledewire/core'\n\n/**\n * Checkout namespace — buyer checkout state for a specific content item.\n *\n * Obtain via `lw.checkout` — do not construct directly.\n *\n * @example\n * ```ts\n * const state = await lw.checkout.state('content-id')\n * // state.checkout_state.next_required_action:\n * // 'authenticate' | 'fund_wallet' | 'purchase' | 'view_content'\n * ```\n */\nexport class CheckoutNamespace {\n constructor(protected readonly http: HttpClient) {}\n\n /**\n * Returns the authenticated buyer's checkout readiness for a given piece of\n * content. Indicates whether the buyer needs to authenticate, fund their\n * wallet, or purchase before accessing the content.\n *\n * Works without authentication — returns anonymous checkout state when the\n * buyer is not logged in.\n *\n * @param contentId - The content item ID.\n * @returns The checkout state, including what action is required next.\n */\n async state(contentId: string): Promise<CheckoutStateResponse> {\n return this.http.get<CheckoutStateResponse>(`/v1/checkout/state/${contentId}`)\n }\n}\n","import { HttpClient, MemoryTokenStorage, TokenManager, parseExpiresAt } from '@ledewire/core'\nimport type { TokenStorage } from '@ledewire/core'\nimport { BrowserAuthNamespace } from './resources/auth.js'\nimport { BrowserConfigNamespace } from './resources/config.js'\nimport { BrowserContentNamespace } from './resources/content.js'\nimport { BrowserPurchasesNamespace } from './resources/purchases.js'\nimport { BrowserWalletNamespace } from './resources/wallet.js'\nimport { CheckoutNamespace } from './resources/checkout.js'\n\n/**\n * Configuration options for the LedeWire browser client.\n */\nexport interface BrowserClientConfig {\n /**\n * LedeWire API key that identifies the store.\n * Obtained from the LedeWire merchant dashboard.\n */\n apiKey: string\n /**\n * Override the API base URL.\n * Defaults to `https://api.ledewire.com`.\n */\n baseUrl?: string\n /**\n * Token storage adapter.\n * Defaults to {@link MemoryTokenStorage} (in-memory, most secure).\n *\n * To persist sessions across page reloads, use the built-in\n * `localStorageAdapter`:\n * ```ts\n * import { init, localStorageAdapter } from '@ledewire/browser'\n * const lw = init({ apiKey: '...', storage: localStorageAdapter() })\n * ```\n */\n storage?: TokenStorage\n /**\n * Called when the user's session expires and cannot be refreshed.\n * Use this to show a re-authentication prompt.\n *\n * @example\n * ```ts\n * onAuthExpired: () => showLoginModal()\n * ```\n */\n onAuthExpired?: () => void\n}\n\n/**\n * Initialises a LedeWire browser client.\n * This is the primary entry point for the browser SDK.\n *\n * @example CDN usage:\n * ```html\n * <script src=\"https://cdn.jsdelivr.net/npm/@ledewire/browser@1/dist/ledewire.min.js\"></script>\n * <script>\n * const lw = Ledewire.init({ apiKey: 'your_api_key' })\n * const state = await lw.checkout.state('content-id')\n * </script>\n * ```\n *\n * @example npm usage:\n * ```ts\n * import { init } from '@ledewire/browser'\n * const lw = init({ apiKey: 'your_api_key' })\n * ```\n */\nexport function init(config: BrowserClientConfig): BrowserClient {\n const baseUrl = config.baseUrl ?? 'https://api.ledewire.com'\n const storage = config.storage ?? new MemoryTokenStorage()\n\n const tokenManager = new TokenManager({\n storage,\n refreshFn: async (refreshToken) => {\n const res = await fetch(`${baseUrl}/v1/auth/token/refresh`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ refresh_token: refreshToken }),\n })\n if (!res.ok) throw new Error('Token refresh failed')\n const data = (await res.json()) as {\n access_token: string\n refresh_token: string\n expires_at: string\n }\n return {\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresAt: parseExpiresAt(data.expires_at),\n }\n },\n ...(config.onAuthExpired !== undefined && { onAuthExpired: config.onAuthExpired }),\n })\n\n const http = new HttpClient({\n baseUrl,\n getAccessToken: () => tokenManager.getAccessToken(),\n onUnauthorized: () => tokenManager.handleUnauthorized(),\n })\n\n return new BrowserClient(http, tokenManager, config)\n}\n\n/**\n * The LedeWire browser client.\n * Access buyer flows through the namespaced properties.\n *\n * @remarks\n * Instantiate with {@link init} rather than constructing directly.\n */\nexport class BrowserClient {\n /** Platform-level public configuration (no auth required) */\n readonly config: BrowserConfigNamespace\n\n /** Buyer authentication: email/password signup/login, Google, password reset */\n readonly auth: BrowserAuthNamespace\n\n /** Checkout state machine: determines next action for a piece of content */\n readonly checkout: CheckoutNamespace\n\n /** Wallet: balance, fund via payment session, transaction history */\n readonly wallet: BrowserWalletNamespace\n\n /** Content purchases for the authenticated buyer */\n readonly purchases: BrowserPurchasesNamespace\n\n /** Public content with per-user access information */\n readonly content: BrowserContentNamespace\n\n /** @internal */\n constructor(\n public readonly _http: HttpClient,\n public readonly _tokenManager: TokenManager,\n public readonly _config: BrowserClientConfig,\n ) {\n this.config = new BrowserConfigNamespace(_http)\n this.auth = new BrowserAuthNamespace(_http, _tokenManager)\n this.checkout = new CheckoutNamespace(_http)\n this.wallet = new BrowserWalletNamespace(_http)\n this.purchases = new BrowserPurchasesNamespace(_http)\n this.content = new BrowserContentNamespace(_http)\n }\n}\n","import type { TokenStorage, StoredTokens } from '@ledewire/core'\n\nconst DEFAULT_STORAGE_KEY = 'lw:tokens'\n\n/**\n * A {@link TokenStorage} adapter that persists tokens in `localStorage`.\n *\n * Tokens survive page reloads and browser restarts, which is convenient\n * for sites where users expect persistent sessions.\n *\n * **Security note:** `localStorage` is accessible to any JavaScript on the\n * same origin. Only use this adapter on sites you fully control and trust.\n * The default in-memory storage is safer for high-security use cases.\n *\n * @param key - The `localStorage` key used to store tokens.\n * Defaults to `'lw:tokens'`. Override this if you have multiple\n * LedeWire integrations on the same origin.\n *\n * @example\n * ```ts\n * import { init, localStorageAdapter } from '@ledewire/browser'\n *\n * const lw = init({\n * apiKey: 'your_api_key',\n * storage: localStorageAdapter(),\n * })\n * ```\n */\nexport function localStorageAdapter(key = DEFAULT_STORAGE_KEY): TokenStorage {\n return {\n getTokens(): StoredTokens | null {\n const raw = localStorage.getItem(key)\n if (!raw) return null\n try {\n return JSON.parse(raw) as StoredTokens\n } catch {\n // Corrupted value - treat as empty\n return null\n }\n },\n setTokens(tokens: StoredTokens): void {\n localStorage.setItem(key, JSON.stringify(tokens))\n },\n clearTokens(): void {\n localStorage.removeItem(key)\n },\n }\n}\n"],"names":["LedewireError","message","statusCode","code","__publicField","AuthError","ForbiddenError","NotFoundError","PurchaseError","DEFAULT_BASE_URL","HttpClient","config","path","params","body","url","method","isRetry","token","headers","response","REFRESH_THRESHOLD_MS","TokenManager","options","stored","refreshed","tokens","refreshToken","_err","MemoryTokenStorage","parseExpiresAt","expiresAt","BrowserAuthNamespace","http","tokenManager","res","BrowserConfigNamespace","BrowserContentNamespace","id","userId","BrowserPurchasesNamespace","BrowserWalletNamespace","sessionId","CheckoutNamespace","contentId","init","baseUrl","storage","data","BrowserClient","_http","_tokenManager","_config","DEFAULT_STORAGE_KEY","localStorageAdapter","key","raw"],"mappings":"2MAgBO,MAAMA,UAAsB,KAAM,CAOvC,YAAYC,EAAiBC,EAAoBC,EAAe,CAC9D,MAAMF,CAAO,EANCG,EAAA,mBAGAA,EAAA,aAId,KAAK,KAAO,gBACZ,KAAK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K,UAAU7B,CAAM,CAAC,CAClD,EACA,aAAoB,CAClB,aAAa,WAAW6B,CAAG,CAC7B,CAAA,CAEJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ledewire/browser",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "LedeWire SDK for browsers — embed a paywall with a single script tag",
5
5
  "type": "module",
6
6
  "exports": {
@@ -39,7 +39,7 @@
39
39
  "access": "public"
40
40
  },
41
41
  "scripts": {
42
- "build": "vite build && tsc --emitDeclarationOnly",
42
+ "build": "vite build",
43
43
  "dev": "vite build --watch",
44
44
  "typecheck": "tsc --noEmit",
45
45
  "lint": "eslint src",
package/dist/client.d.ts DELETED
@@ -1,89 +0,0 @@
1
- import { HttpClient, TokenManager } from '@ledewire/core';
2
- import type { TokenStorage } from '@ledewire/core';
3
- import { BrowserAuthNamespace } from './resources/auth.js';
4
- import { BrowserContentNamespace } from './resources/content.js';
5
- import { BrowserPurchasesNamespace } from './resources/purchases.js';
6
- import { BrowserWalletNamespace } from './resources/wallet.js';
7
- import { CheckoutNamespace } from './resources/checkout.js';
8
- /**
9
- * Configuration options for the LedeWire browser client.
10
- */
11
- export interface BrowserClientConfig {
12
- /**
13
- * LedeWire API key that identifies the store.
14
- * Obtained from the LedeWire merchant dashboard.
15
- */
16
- apiKey: string;
17
- /**
18
- * Override the API base URL.
19
- * Defaults to `https://api.ledewire.com`.
20
- */
21
- baseUrl?: string;
22
- /**
23
- * Token storage adapter.
24
- * Defaults to {@link MemoryTokenStorage} (in-memory, most secure).
25
- *
26
- * To persist sessions across page reloads, use the built-in
27
- * `localStorageAdapter`:
28
- * ```ts
29
- * import { init, localStorageAdapter } from '@ledewire/browser'
30
- * const lw = init({ apiKey: '...', storage: localStorageAdapter() })
31
- * ```
32
- */
33
- storage?: TokenStorage;
34
- /**
35
- * Called when the user's session expires and cannot be refreshed.
36
- * Use this to show a re-authentication prompt.
37
- *
38
- * @example
39
- * ```ts
40
- * onAuthExpired: () => showLoginModal()
41
- * ```
42
- */
43
- onAuthExpired?: () => void;
44
- }
45
- /**
46
- * Initialises a LedeWire browser client.
47
- * This is the primary entry point for the browser SDK.
48
- *
49
- * @example CDN usage:
50
- * ```html
51
- * <script src="https://cdn.jsdelivr.net/npm/@ledewire/browser@1/dist/ledewire.min.js"></script>
52
- * <script>
53
- * const lw = Ledewire.init({ apiKey: 'your_api_key' })
54
- * const state = await lw.checkout.state('content-id')
55
- * </script>
56
- * ```
57
- *
58
- * @example npm usage:
59
- * ```ts
60
- * import { init } from '@ledewire/browser'
61
- * const lw = init({ apiKey: 'your_api_key' })
62
- * ```
63
- */
64
- export declare function init(config: BrowserClientConfig): BrowserClient;
65
- /**
66
- * The LedeWire browser client.
67
- * Access buyer flows through the namespaced properties.
68
- *
69
- * @remarks
70
- * Instantiate with {@link init} rather than constructing directly.
71
- */
72
- export declare class BrowserClient {
73
- readonly _http: HttpClient;
74
- readonly _tokenManager: TokenManager;
75
- readonly _config: BrowserClientConfig;
76
- /** Buyer authentication: email/password signup/login, Google, password reset */
77
- readonly auth: BrowserAuthNamespace;
78
- /** Checkout state machine: determines next action for a piece of content */
79
- readonly checkout: CheckoutNamespace;
80
- /** Wallet: balance, fund via payment session, transaction history */
81
- readonly wallet: BrowserWalletNamespace;
82
- /** Content purchases for the authenticated buyer */
83
- readonly purchases: BrowserPurchasesNamespace;
84
- /** Public content with per-user access information */
85
- readonly content: BrowserContentNamespace;
86
- /** @internal */
87
- constructor(_http: HttpClient, _tokenManager: TokenManager, _config: BrowserClientConfig);
88
- }
89
- //# sourceMappingURL=client.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAsB,YAAY,EAAkB,MAAM,gBAAgB,CAAA;AAC7F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAClD,OAAO,EAAE,oBAA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oot":"","sources":["../src/client.test.ts"],"names":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,YAAY,EACV,sBAAsB,EACtB,kBAAkB,EAClB,aAAa,EACb,qBAAqB,EACrB,iBAAiB,EACjB,yBAAyB,EACzB,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,EAChB,YAAY,EACZ,YAAY,EACZ,qBAAqB,EACrB,2BAA2B,EAC3B,4BAA4B,EAC5B,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,gBAAgB,CAAA;AACvB,OAAO,EACL,SAAS,EACT,cAAc,EACd,aAAa,EACb,kBAAkB,EAClB,aAAa,EACb,aAAa,EACb,cAAc,GACf,MAAM,gBAAgB,CAAA;AAGvB,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,YAAY,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAA"}
@@ -1,27 +0,0 @@
1
- import type { TokenStorage } from '@ledewire/core';
2
- /**
3
- * A {@link TokenStorage} adapter that persists tokens in `localStorage`.
4
- *
5
- * Tokens survive page reloads and browser restarts, which is convenient
6
- * for sites where users expect persistent sessions.
7
- *
8
- * **Security note:** `localStorage` is accessible to any JavaScript on the
9
- * same origin. Only use this adapter on sites you fully control and trust.
10
- * The default in-memory storage is safer for high-security use cases.
11
- *
12
- * @param key - The `localStorage` key used to store tokens.
13
- * Defaults to `'lw:tokens'`. Override this if you have multiple
14
- * LedeWire integrations on the same origin.
15
- *
16
- * @example
17
- * ```ts
18
- * import { init, localStorageAdapter } from '@ledewire/browser'
19
- *
20
- * const lw = init({
21
- * apiKey: 'your_api_key',
22
- * storage: localStorageAdapter(),
23
- * })
24
- * ```
25
- */
26
- export declare function localStorageAdapter(key?: string): TokenStorage;
27
- //# sourceMappingURL=local-storage-adapter.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"local-storage-adapter.d.ts","sourceRoot":"","sources":["../src/local-storage-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAgB,MAAM,gBAAgB,CAAA;AAIhE;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,SAAsB,GAAG,YAAY,CAmB3E"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=local-storage-adapter.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"local-storage-adapter.test.d.ts","sourceRoot":"","sources":["../src/local-storage-adapter.test.ts"],"names":[],"mappings":""}
@@ -1,45 +0,0 @@
1
- import type { HttpClient, TokenManager } from '@ledewire/core';
2
- import type { AuthLoginEmailRequest, AuthLoginOAuthRequest, AuthSignupRequest, AuthenticationResponse } from '@ledewire/core';
3
- /**
4
- * Buyer authentication: signup, email/password login, Google OAuth.
5
- *
6
- * Obtain via `lw.auth` — do not construct directly.
7
- *
8
- * @example
9
- * ```ts
10
- * const lw = Ledewire.init({ apiKey: 'your_api_key' })
11
- * await lw.auth.loginWithEmail({ email: 'u@example.com', password: 'pw' })
12
- * ```
13
- */
14
- export declare class BrowserAuthNamespace {
15
- private readonly http;
16
- private readonly tokenManager;
17
- /** @internal */
18
- constructor(http: HttpClient, tokenManager: TokenManager);
19
- /**
20
- * Register a new buyer account with email and password.
21
- * Tokens are stored automatically after successful signup.
22
- *
23
- * @param body - Signup credentials and display name.
24
- * @returns The authentication token response.
25
- */
26
- signup(body: AuthSignupRequest): Promise<AuthenticationResponse>;
27
- /**
28
- * Log in with email and password.
29
- * Tokens are stored automatically after successful login.
30
- *
31
- * @param body - Email and password credentials.
32
- * @returns The authentication token response.
33
- */
34
- loginWithEmail(body: AuthLoginEmailRequest): Promise<AuthenticationResponse>;
35
- /**
36
- * Log in with a Google ID token obtained from the Google OAuth flow.
37
- * Tokens are stored automatically after successful login.
38
- *
39
- * @param body - The Google ID token.
40
- * @returns The authentication token response.
41
- */
42
- loginWithGoogle(body: AuthLoginOAuthRequest): Promise<AuthenticationResponse>;
43
- private storeTokens;
44
- }
45
- //# sourceMappingURL=auth.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/resources/auth.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC9D,OAAO,KAAK,EACV,qBAAqB,EACrB,qBAAqB,EACrB,iBAAiB,EACjB,sBAAsB,EACvB,MAAM,gBAAgB,CAAA;AAEvB;;;;;;;;;;GAUG;AACH,qBAAa,oBAAoB;IAG7B,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,YAAY;IAH/B,gBAAgB;gBAEG,IAAI,EAAE,UAAU,EAChB,YAAY,EAAE,YAAY;IAG7C;;;;;;OAMG;IACG,MAAM,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAMtE;;;;;;OAMG;IACG,cAAc,CAAC,IAAI,EAAE,qBAAqB,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAMlF;;;;;;OAMG;IACG,eAAe,CAAC,IAAI,EAAE,qBAAqB,GAAG,OAAO,CAAC,sBAAsB,CAAC;YAMrE,WAAW;CAO1B"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=auth.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth.test.d.ts","sourceRoot":"","sources":["../../src/resources/auth.test.ts"],"names":[],"mappings":""}
@@ -1,31 +0,0 @@
1
- import type { HttpClient } from '@ledewire/core';
2
- import type { CheckoutStateResponse } from '@ledewire/core';
3
- /**
4
- * Checkout namespace — buyer checkout state for a specific content item.
5
- *
6
- * Obtain via `lw.checkout` — do not construct directly.
7
- *
8
- * @example
9
- * ```ts
10
- * const state = await lw.checkout.state('content-id')
11
- * // state.checkout_state.next_required_action:
12
- * // 'authenticate' | 'fund_wallet' | 'purchase' | 'view_content'
13
- * ```
14
- */
15
- export declare class CheckoutNamespace {
16
- protected readonly http: HttpClient;
17
- constructor(http: HttpClient);
18
- /**
19
- * Returns the authenticated buyer's checkout readiness for a given piece of
20
- * content. Indicates whether the buyer needs to authenticate, fund their
21
- * wallet, or purchase before accessing the content.
22
- *
23
- * Works without authentication — returns anonymous checkout state when the
24
- * buyer is not logged in.
25
- *
26
- * @param contentId - The content item ID.
27
- * @returns The checkout state, including what action is required next.
28
- */
29
- state(contentId: string): Promise<CheckoutStateResponse>;
30
- }
31
- //# sourceMappingURL=checkout.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"checkout.d.ts","sourceRoot":"","sources":["../../src/resources/checkout.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAChD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAA;AAE3D;;;;;;;;;;;GAWG;AACH,qBAAa,iBAAiB;IAChB,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU;gBAAhB,IAAI,EAAE,UAAU;IAE/C;;;;;;;;;;OAUG;IACG,KAAK,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,CAAC;CAG/D"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=checkout.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"checkout.test.d.ts","sourceRoot":"","sources":["../../src/resources/checkout.test.ts"],"names":[],"mappings":""}
@@ -1,27 +0,0 @@
1
- import type { HttpClient } from '@ledewire/core';
2
- import type { ContentWithAccessResponse } from '@ledewire/core';
3
- /**
4
- * Buyer content namespace — fetch content with real-time access information.
5
- *
6
- * Obtain via `lw.content` — do not construct directly.
7
- *
8
- * @example
9
- * ```ts
10
- * const { content, access } = await lw.content.getWithAccess('content-id')
11
- * if (access.has_access) showFullContent(content)
12
- * ```
13
- */
14
- export declare class BrowserContentNamespace {
15
- protected readonly http: HttpClient;
16
- constructor(http: HttpClient);
17
- /**
18
- * Returns a content item together with access information for the
19
- * authenticated buyer (or a generic access response when unauthenticated).
20
- *
21
- * @param id - The content ID.
22
- * @param userId - Optional user ID to check a specific user's access status.
23
- * @returns The content item with access information.
24
- */
25
- getWithAccess(id: string, userId?: string): Promise<ContentWithAccessResponse>;
26
- }
27
- //# sourceMappingURL=content.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"content.d.ts","sourceRoot":"","sources":["../../src/resources/content.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAChD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAA;AAE/D;;;;;;;;;;GAUG;AACH,qBAAa,uBAAuB;IACtB,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU;gBAAhB,IAAI,EAAE,UAAU;IAE/C;;;;;;;OAOG;IACG,aAAa,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,yBAAyB,CAAC;CAUrF"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=content.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"content.test.d.ts","sourceRoot":"","sources":["../../src/resources/content.test.ts"],"names":[],"mappings":""}
@@ -1,38 +0,0 @@
1
- import type { HttpClient } from '@ledewire/core';
2
- import type { PurchaseCreateRequest, PurchaseResponse } from '@ledewire/core';
3
- /**
4
- * Buyer purchases namespace — create and retrieve content purchases.
5
- *
6
- * Obtain via `lw.purchases` — do not construct directly.
7
- *
8
- * @example
9
- * ```ts
10
- * await lw.purchases.create({ content_id: 'content-id' })
11
- * const all = await lw.purchases.list()
12
- * ```
13
- */
14
- export declare class BrowserPurchasesNamespace {
15
- protected readonly http: HttpClient;
16
- constructor(http: HttpClient);
17
- /**
18
- * Completes a content purchase using the buyer's wallet balance.
19
- *
20
- * @param body - The content ID and expected price in cents.
21
- * @returns The completed purchase record.
22
- */
23
- create(body: PurchaseCreateRequest): Promise<PurchaseResponse>;
24
- /**
25
- * Returns all purchases made by the authenticated buyer.
26
- *
27
- * @returns A list of purchase records, newest first.
28
- */
29
- list(): Promise<PurchaseResponse[]>;
30
- /**
31
- * Returns a single purchase by ID.
32
- *
33
- * @param id - The purchase ID.
34
- * @returns The purchase record.
35
- */
36
- get(id: string): Promise<PurchaseResponse>;
37
- }
38
- //# sourceMappingURL=purchases.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"purchases.d.ts","sourceRoot":"","sources":["../../src/resources/purchases.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAChD,OAAO,KAAK,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAA;AAE7E;;;;;;;;;;GAUG;AACH,qBAAa,yBAAyB;IACxB,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU;gBAAhB,IAAI,EAAE,UAAU;IAE/C;;;;;OAKG;IACG,MAAM,CAAC,IAAI,EAAE,qBAAqB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAIpE;;;;OAIG;IACG,IAAI,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAIzC;;;;;OAKG;IACG,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;CAGjD"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=purchases.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"purchases.test.d.ts","sourceRoot":"","sources":["../../src/resources/purchases.test.ts"],"names":[],"mappings":""}
@@ -1,44 +0,0 @@
1
- import type { HttpClient } from '@ledewire/core';
2
- import type { WalletBalanceResponse, WalletPaymentSessionRequest, WalletPaymentSessionResponse, WalletPaymentStatusResponse, WalletTransactionItem } from '@ledewire/core';
3
- /**
4
- * Buyer wallet namespace — balance, transactions, and payment session management.
5
- *
6
- * Obtain via `lw.wallet` — do not construct directly.
7
- *
8
- * @example
9
- * ```ts
10
- * const { balance_cents } = await lw.wallet.balance()
11
- * const session = await lw.wallet.createPaymentSession({ amount_cents: 500 })
12
- * ```
13
- */
14
- export declare class BrowserWalletNamespace {
15
- protected readonly http: HttpClient;
16
- constructor(http: HttpClient);
17
- /**
18
- * Returns the authenticated buyer's current wallet balance.
19
- *
20
- * @returns The current wallet balance in cents.
21
- */
22
- balance(): Promise<WalletBalanceResponse>;
23
- /**
24
- * Returns the authenticated buyer's wallet transaction history, newest first.
25
- *
26
- * @returns A list of completed wallet transaction entries.
27
- */
28
- transactions(): Promise<WalletTransactionItem[]>;
29
- /**
30
- * Creates a payment session for funding the buyer's wallet.
31
- *
32
- * @param body - The amount and currency to fund.
33
- * @returns Payment session details for use with the payment provider widget.
34
- */
35
- createPaymentSession(body: WalletPaymentSessionRequest): Promise<WalletPaymentSessionResponse>;
36
- /**
37
- * Polls the status of a wallet funding payment session.
38
- *
39
- * @param sessionId - The session ID returned by `createPaymentSession`.
40
- * @returns The current payment status.
41
- */
42
- getPaymentStatus(sessionId: string): Promise<WalletPaymentStatusResponse>;
43
- }
44
- //# sourceMappingURL=wallet.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet.d.ts","sourceRoot":"","sources":["../../src/resources/wallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAChD,OAAO,KAAK,EACV,qBAAqB,EACrB,2BAA2B,EAC3B,4BAA4B,EAC5B,2BAA2B,EAC3B,qBAAqB,EACtB,MAAM,gBAAgB,CAAA;AAEvB;;;;;;;;;;GAUG;AACH,qBAAa,sBAAsB;IACrB,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU;gBAAhB,IAAI,EAAE,UAAU;IAE/C;;;;OAIG;IACG,OAAO,IAAI,OAAO,CAAC,qBAAqB,CAAC;IAI/C;;;;OAIG;IACG,YAAY,IAAI,OAAO,CAAC,qBAAqB,EAAE,CAAC;IAItD;;;;;OAKG;IACG,oBAAoB,CACxB,IAAI,EAAE,2BAA2B,GAChC,OAAO,CAAC,4BAA4B,CAAC;IAIxC;;;;;OAKG;IACG,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,2BAA2B,CAAC;CAGhF"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=wallet.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet.test.d.ts","sourceRoot":"","sources":["../../src/resources/wallet.test.ts"],"names":[],"mappings":""}