import { S as SubscriptionTier, T as TierConfig, c as PortableReservation } from './types-DgQtamEe.js'; export { A as AIProviderType, B as BuiltinTier, g as CreditCheckResult, a as CreditOperationType, C as CreditSource, J as JournalReferenceType, M as MonthlyResetResult, f as PortableJournalEntry, P as PortableTransaction, d as PortableUsageLog, b as PortableUserCredits, R as ReservationStatus, h as ResourceType, g as SDKCreditCheckResult, e as SubscriptionExpiryResult, i as TransactionType, U as UsageHistoryEntry, j as UsageHistoryResponse, b as UserCredits, W as WithCreditsOptions, k as calculateAvailableCredits, t as toDate, l as toPortableTimestamp } from './types-DgQtamEe.js'; export { CreditError, CreditErrorCode, CreditErrorCodeType, commitReservationWithJournal, createInsufficientCreditsError, createInvalidOperationTypeError, createReservationAlreadyProcessedError, createReservationExpiredError, createReservationNotFoundError, createUserNotFoundError, isCreditError, isInsufficientCreditsError, releaseReservationWithJournal, reserveCreditsForOperation } from './core/index.js'; export { D as DeferredExecutor, c as createDeferredExecutor, g as genericDeferred, n as noopDeferred, s as synchronousDeferred } from './deferred-C7rrRfkm.js'; import { z } from 'zod'; export { C as CreateJournalEntryInput, a as CreateReservationInput, b as CreateTransactionInput, c as CreateUsageLogInput, d as CreditBalanceUpdate, e as CreditRepositoryFactory, I as ICreditRepository, J as JournalEntryQuery, T as TierUpdateInput, U as UsageLogQuery, t as toClientUserCredits } from './types-fW2JNmmr.js'; export { InMemoryCreditRepository, createInMemoryCreditRepository, generateId, getNextMonthlyReset } from './repository/index.js'; export { C as CreditsAuthProviderFactory, a as CreditsUser, I as ICreditsAuthProvider } from './types-OZU3I5OM.js'; export { ApiKeyCreditsProvider, createApiKeyProvider, verifyAdminApiKey, verifyBearerToken } from './auth/index.js'; export { CreditsService, LowBalanceNotificationCallback, SubscriptionExpiredNotificationCallback, createCreditsService } from './service/index.js'; export { ActionResult, CreditActionHandler, CreditsAdapter, CreditsAdapterConfig, createGenericAdapter } from './adapters/index.js'; export { AdminCreditsClient, AdminCreditsClientConfig, ApiResponse, AuthenticationError, AuthorizationError, CreditsClient, CreditsClientConfig, CreditsConfig, CreditsSDKError, ListUsersOptions, ListUsersResponse, NetworkError, PaginationOptions, ReservationResult, SDKErrorCode, SDKErrorCodeType, InsufficientCreditsError as SDKInsufficientCreditsError, ReservationExpiredError as SDKReservationExpiredError, ReservationNotFoundError as SDKReservationNotFoundError, UsageHistoryEntry as SDKUsageHistoryEntry, UsageHistoryResponse as SDKUsageHistoryResponse, ServerError, ValidationError, parseApiError } from './sdk/index.js'; /** * Schema for credit system configuration */ declare const creditSystemConfigSchema: z.ZodObject<{ /** * Operation costs in credits * Keys are operation type names (any non-empty string) * Values are positive numbers representing credit cost */ operationCosts: z.ZodRecord; /** * Display labels for operation types (English canonical labels). * Falls back to auto-generating from snake_case keys if not provided. */ operationLabels: z.ZodDefault>>; /** * Tier configurations */ tierConfigs: z.ZodRecord; isFree: z.ZodOptional; unlimited: z.ZodOptional; isDefault: z.ZodOptional; }, "strip", z.ZodTypeAny, { tier: string; monthlyCredits: number; priceUsd: number; features: string[]; unlimited?: boolean | undefined; isFree?: boolean | undefined; isDefault?: boolean | undefined; }, { tier: string; monthlyCredits: number; priceUsd: number; features: string[]; unlimited?: boolean | undefined; isFree?: boolean | undefined; isDefault?: boolean | undefined; }>>; /** * Reservation expiry time in milliseconds */ reservationExpiryMs: z.ZodDefault; /** * Default credits for new users (free tier) */ defaultFreeCredits: z.ZodDefault; /** * Grace period in days after subscription expires before downgrade */ subscriptionGracePeriodDays: z.ZodDefault; /** * Low balance notification threshold */ lowBalanceThreshold: z.ZodDefault; /** * Cooldown in hours between low balance notifications */ lowBalanceNotificationCooldownHours: z.ZodDefault; /** * Feature flags for optional features */ features: z.ZodDefault; notifications: z.ZodDefault; subscriptionExpiry: z.ZodDefault; usageHistory: z.ZodDefault; }, "strip", z.ZodTypeAny, { journalEntries: boolean; notifications: boolean; subscriptionExpiry: boolean; usageHistory: boolean; }, { journalEntries?: boolean | undefined; notifications?: boolean | undefined; subscriptionExpiry?: boolean | undefined; usageHistory?: boolean | undefined; }>>; }, "strip", z.ZodTypeAny, { operationCosts: Record; operationLabels: Record; tierConfigs: Record; features: { journalEntries: boolean; notifications: boolean; subscriptionExpiry: boolean; usageHistory: boolean; }; reservationExpiryMs: number; defaultFreeCredits: number; subscriptionGracePeriodDays: number; lowBalanceThreshold: number; lowBalanceNotificationCooldownHours: number; }, { operationCosts: Record; tierConfigs: Record; operationLabels?: Record | undefined; features?: { journalEntries?: boolean | undefined; notifications?: boolean | undefined; subscriptionExpiry?: boolean | undefined; usageHistory?: boolean | undefined; } | undefined; reservationExpiryMs?: number | undefined; defaultFreeCredits?: number | undefined; subscriptionGracePeriodDays?: number | undefined; lowBalanceThreshold?: number | undefined; lowBalanceNotificationCooldownHours?: number | undefined; }>; /** * Credit system configuration type */ type CreditSystemConfig = z.infer; /** * Load configuration from environment variables * Can be extended to load from other sources (file, remote config, etc.) * * Operation costs are loaded from CREDITS_OPERATION_COSTS as JSON: * CREDITS_OPERATION_COSTS={"story_generation":5,"image_generation":10} */ declare function loadConfigFromEnv(): Partial; /** * Initialize configuration * Merges default config with environment overrides */ declare function initializeConfig(overrides?: Partial): CreditSystemConfig; /** * Get the current configuration. * If an external provider is registered, delegates to it. * Otherwise falls back to the local currentConfig. */ declare function getConfig(): CreditSystemConfig; /** * Get all valid operation types from configuration * Returns the keys of the operationCosts object */ declare function getValidOperationTypes(): string[]; /** * Check if an operation type is valid (configured in the system) * @param type - The operation type to check * @returns true if the operation type is configured */ declare function isValidOperationType(type: string): boolean; /** * Get operation cost from configuration * @throws Error if the operation type is not configured */ declare function getConfigOperationCost(operationType: string): number; /** * Get all valid tier ids from configuration * Returns the keys of the tierConfigs object */ declare function getValidTiers(): string[]; /** * Check if a tier id is valid (configured in the system) */ declare function isValidTier(tier: string): boolean; /** * Check if a tier is the free/default tier. * Falls back to priceUsd === 0 when the isFree flag is not set. */ declare function isFreeTier(tier: SubscriptionTier): boolean; /** * Check if a tier is unlimited. * Falls back to monthlyCredits === 0 when the unlimited flag is not set. */ declare function isUnlimitedTier(tier: SubscriptionTier): boolean; /** * Get the tier assigned to brand-new users. * Prefers the tier flagged isDefault, then the first isFree tier, then "free". */ declare function getDefaultTier(): SubscriptionTier; /** * Magic balance assigned to unlimited tiers on upgrade. * Kept at 999999 for back-compat with stored/displayed balances. */ declare const UNLIMITED_BALANCE_SENTINEL = 999999; /** * Get the magic balance assigned to unlimited tiers on upgrade. */ declare function getUnlimitedSentinelBalance(): number; /** * Get tier configuration from configuration. * Falls back to the default tier (with a warning) if the tier is unknown. */ declare function getConfigTierConfig(tier: SubscriptionTier): TierConfig; /** * Get monthly limit for a tier from configuration * Returns Infinity for unlimited tier */ declare function getConfigMonthlyLimit(tier: SubscriptionTier): number; /** * Runtime zod validator for tier ids. Validates against the LIVE config keys * at parse time, so apps that add tiers via config get correct validation. */ declare const tierSchema: z.ZodType; /** * Parse/validate a tier id against the live config keys. * @throws ZodError if the tier is not configured */ declare function parseTier(value: unknown): SubscriptionTier; /** * Check if a feature is enabled */ declare function isFeatureEnabled(feature: keyof CreditSystemConfig["features"]): boolean; /** * Get the display label for an operation type. * Falls back to converting snake_case to Title Case if no label is configured. */ declare function getOperationLabel(operationType: string): string; /** * Get all operation labels as a record. * For any operation in operationCosts that lacks a label, generates one from the key. */ declare function getOperationLabels(): Record; /** * Reset configuration to defaults (for testing) */ declare function resetConfig(): void; /** Interface for external config providers (e.g. Firestore-backed) */ interface ICreditConfigProvider { getConfig(): CreditSystemConfig; } /** Register an external config provider. Called once at app startup. */ declare function registerConfigProvider(provider: ICreditConfigProvider): void; /** Get the registered provider, or null if none registered. */ declare function getConfigProvider(): ICreditConfigProvider | null; /** Clear registered provider (for testing). */ declare function clearConfigProvider(): void; /** * Get operation costs as a record * Returns all configured operation costs from the current config */ declare function getOperationCosts(): Record; /** * Get the credit cost for an operation type * Uses the configuration system for dynamic costs * * @param type - Operation type (must be configured in the system) * @returns Credit cost for the operation * @throws Error if the operation type is not configured */ declare function getOperationCost(type: string): number; /** * Get tier configuration * Uses the configuration system for dynamic configs * * @param tier - Subscription tier * @returns Tier configuration */ declare function getTierConfig(tier: SubscriptionTier): TierConfig; /** * Get monthly credit limit for a tier * Returns Infinity for unlimited tier * Uses the configuration system for dynamic limits * * @param tier - Subscription tier * @returns Monthly credit limit */ declare function getMonthlyLimit(tier: SubscriptionTier): number; /** * Get default free credits from configuration */ declare function getDefaultFreeCredits(): number; /** * Get reservation expiry time from configuration */ declare function getReservationExpiryMs(): number; /** * Information about an operation's cost and display label */ interface OperationCostInfo { key: string; cost: number; label: string; } /** * Get all operation costs with their display labels. * Returns a record keyed by operation type with cost + label. */ declare function getOperationCostsWithLabels(): Record; /** * Notification event types */ type CreditNotificationEvent = { type: "low_balance"; userId: string; balance: number; threshold: number; } | { type: "balance_depleted"; userId: string; } | { type: "subscription_expiring"; userId: string; expiresAt: Date; daysRemaining: number; } | { type: "subscription_expired"; userId: string; wasDowngraded: boolean; }; /** * Notification handler interface * Implementations can send emails, push notifications, etc. */ interface ICreditNotificationHandler { /** * Handle a notification event * @param event - The notification event */ handleNotification(event: CreditNotificationEvent): Promise; } /** * Register a notification handler */ declare function registerNotificationHandler(handler: ICreditNotificationHandler): void; /** * Clear all notification handlers (for testing) */ declare function clearNotificationHandlers(): void; /** * Clear cooldown state (for testing) */ declare function clearCooldownState(): void; /** * Check and trigger low balance notification if needed * Call this after commit operations * * @param userId - User ID * @param newBalance - Balance after the operation * @param threshold - Custom threshold (defaults to 10) */ declare function checkAndNotifyLowBalance(userId: string, newBalance: number, threshold?: number): Promise; /** * Trigger subscription expiring notification * * @param userId - User ID * @param expiresAt - When subscription expires * @param daysRemaining - Days until expiry */ declare function notifySubscriptionExpiring(userId: string, expiresAt: Date, daysRemaining: number): Promise; /** * Trigger subscription expired notification * * @param userId - User ID * @param wasDowngraded - Whether the user was downgraded to free tier */ declare function notifySubscriptionExpired(userId: string, wasDowngraded: boolean): Promise; /** * Console notification handler for development/testing * Logs notifications to console */ declare class ConsoleNotificationHandler implements ICreditNotificationHandler { handleNotification(event: CreditNotificationEvent): Promise; } /** * Credit error utilities * * Provides functions to parse and identify credit-related errors * for consistent error handling across the application. */ /** * Parsed information from a credit error message */ interface CreditErrorInfo { /** Credits currently available */ available: number; /** Credits required for the operation */ required: number; /** Difference between required and available */ shortfall: number; /** Original error message */ rawMessage: string; } /** * Parse a credit error message to extract available/required credits * * @param error - Error message string * @returns Parsed credit info or null if not a valid credit error format * * @example * ```ts * const error = "Insufficient credits. Available: 3, Required: 10"; * const info = parseCreditError(error); * // { available: 3, required: 10, shortfall: 7, rawMessage: "..." } * ``` */ declare function parseCreditError(error: string): CreditErrorInfo | null; /** * Check if an error message is a credit-related error * * @param error - Error message string * @returns true if the error is credit-related * * @example * ```ts * if (isCreditError(error)) { * showCreditErrorDialog(parseCreditError(error)); * } * ``` */ declare function isCreditErrorMessage(error: string): boolean; /** * Credit utility functions * * Common helper functions for credit calculations */ /** * Calculate total available credits from balance and bonus credits * * @param credits - Object containing balance and bonusCredits properties * @returns Total credits (balance + bonusCredits) * * @example * ```ts * const total = getTotalCredits({ balance: 100, bonusCredits: 50 }); * // Returns 150 * ``` */ declare function getTotalCredits(credits: { balance: number; bonusCredits: number; }): number; /** * Generate a unique request ID * * Format: req_{timestamp}_{randomPart} * Example: req_1706234567890_a1b2c3d4e5f6 * * @returns URL-safe request ID string */ declare function generateRequestId(): string; /** * Check if the input data indicates preview mode * * Preview mode skips actual credit deduction - used for dry runs * and UI previews where the user wants to see results without committing. * * @param data - The input data to check * @returns true if data has preview: true */ declare function isPreviewMode(data: unknown): boolean; /** * Create a dummy reservation for preview mode * * Used when `isPreviewMode(data)` returns true to provide * a valid reservation object without actual credit operations. * * @param userId - The user ID * @param operationType - The operation type * @returns A dummy PortableReservation with id "preview-mode" */ declare function createDummyReservation(userId: string, operationType: string): PortableReservation; export { ConsoleNotificationHandler, type CreditErrorInfo, type CreditNotificationEvent, PortableReservation as CreditReservation, type CreditSystemConfig, type ICreditConfigProvider, type ICreditNotificationHandler, type OperationCostInfo, PortableReservation, SubscriptionTier as SDKSubscriptionTier, SubscriptionTier, TierConfig, UNLIMITED_BALANCE_SENTINEL, checkAndNotifyLowBalance, clearConfigProvider, clearCooldownState, clearNotificationHandlers, createDummyReservation, generateRequestId, getConfig, getConfigMonthlyLimit, getConfigOperationCost, getConfigProvider, getConfigTierConfig, getDefaultFreeCredits, getDefaultTier, getMonthlyLimit, getOperationCost, getOperationCosts, getOperationCostsWithLabels, getOperationLabel, getOperationLabels, getReservationExpiryMs, getTierConfig, getTotalCredits, getUnlimitedSentinelBalance, getValidOperationTypes, getValidTiers, initializeConfig, isCreditErrorMessage, isFeatureEnabled, isFreeTier, isPreviewMode, isUnlimitedTier, isValidOperationType, isValidTier, loadConfigFromEnv, notifySubscriptionExpired, notifySubscriptionExpiring, parseCreditError, parseTier, registerConfigProvider, registerNotificationHandler, resetConfig, tierSchema };