import { Plugin, PluginContext } from "@cashu/coco-core/plugin"; import { JWTAuthProvider, NPCClient, PaymentRequiredError } from "npubcash-sdk"; import { Logger } from "@cashu/coco-core"; import * as npubcash_types0 from "npubcash-types"; //#region src/sync/sinceStore.d.ts /** * Interface for persisting the last processed timestamp. * * Implementations should store the timestamp durably to allow * resuming sync operations after restarts. */ interface SinceStore { /** * Retrieves the last processed timestamp. * @returns The timestamp in milliseconds, or 0 if never set */ get(): Promise; /** * Stores the last processed timestamp. * @param since - The timestamp in milliseconds */ set(since: number): Promise; } /** * In-memory implementation of SinceStore. * * Note: State is lost on restart. Use a database-backed * implementation for production use cases that require durability. * * @example * ```typescript * const store = new MemorySinceStore(0); * await store.set(Date.now()); * const since = await store.get(); // Returns the stored timestamp * ``` */ declare class MemorySinceStore implements SinceStore { private since; /** * Creates a new MemorySinceStore. * @param initialSince - Initial timestamp value (default: 0) */ constructor(initialSince?: number); get(): Promise; set(since: number): Promise; } /** * LocalStorage-based implementation of SinceStore. * * Persists the timestamp to browser localStorage, allowing state * to survive page refreshes and browser restarts. * * Note: Only works in browser environments where localStorage is available. * Will throw an error if localStorage is not accessible. * * @example * ```typescript * const store = new LocalStorageSinceStore("my-app-npc-since"); * await store.set(Date.now()); * const since = await store.get(); // Returns the stored timestamp * ``` */ declare class LocalStorageSinceStore implements SinceStore { private readonly key; private readonly fallbackValue; /** * Creates a new LocalStorageSinceStore. * @param key - The localStorage key to use for storing the timestamp * @param fallbackValue - Value to return if no timestamp is stored (default: 0) * @throws {Error} If localStorage is not available */ constructor(key: string, fallbackValue?: number); get(): Promise; set(since: number): Promise; /** * Removes the stored timestamp from localStorage. */ clear(): Promise; } //#endregion //#region src/types.d.ts /** * Quote data returned from NPubCash API */ interface NPCQuote { quoteId: string; mintUrl: string; amount: number; expiresAt: number; paidAt: number; request?: string; /** Additional properties from the API */ [key: string]: unknown; } /** * Transformed quote ready for the mint operation service */ interface MintQuote { quoteId: string; mintUrl: string; amount: number; expiry: number; paidAt: number; unit: string; state: string; quote: string; request: string; [key: string]: unknown; } /** * Signer type for JWT authentication. * This is intentionally typed as `unknown` to allow compatibility * with various signing implementations from npubcash-sdk. */ type Signer = ConstructorParameters[1]; type SetUsernameResult = { success: true; } | { success: false; pr: Omit; }; /** * Options used to add one NPubCash account runtime. */ interface AddNPCAccountOptions { id: string; signer: Signer; baseUrl?: string; sinceStore?: SinceStore; syncIntervalMs?: number; useWebsocket?: boolean; autoStart?: boolean; } /** * Persisted metadata for a host-owned NPC account. * * Signer material is intentionally not included. */ interface NPCAccountRecord { id: string; baseUrl: string; syncIntervalMs?: number; useWebsocket?: boolean; autoStart: boolean; createdAt: number; updatedAt: number; } /** * Optional host-provided metadata store for account registrations. */ interface NPCAccountStore { list(): Promise; upsert(record: NPCAccountRecord): Promise; remove(accountId: string): Promise; } /** * Creates a per-account SinceStore when one is not supplied explicitly. */ type NPCSinceStoreFactory = (accountId: string, baseUrl: string) => SinceStore | Promise; /** * Configuration options for NPCPlugin. */ interface NPCPluginOptions { /** * Default NPC server URL for accounts that do not provide one. */ defaultBaseUrl?: string; /** * Optional host-owned store for account metadata. */ accountStore?: NPCAccountStore; /** * Optional factory for creating account-scoped SinceStore instances. */ sinceStoreFactory?: NPCSinceStoreFactory; /** * Default interval in milliseconds between sync operations. * If not provided, interval-based syncing is disabled by default. */ syncIntervalMs?: number; /** * Enable WebSocket subscriptions by default for account runtimes. * @default false */ useWebsocket?: boolean; /** * Logger instance for debugging and error reporting. */ logger?: Logger; } /** * Account runtime status information. */ interface NPCAccountStatus { id: string; isReady: boolean; isRunning: boolean; isSyncing: boolean; isWebSocketConnected: boolean; isShutdown: boolean; } /** * Account summary returned by the root extension API. */ interface NPCAccountSummary extends NPCAccountStatus { baseUrl: string; autoStart: boolean; syncIntervalMs?: number; useWebsocket: boolean; } /** * Plugin status information. */ interface NPCPluginStatus { isInitialized: boolean; isReady: boolean; accountCount: number; runningAccountIds: string[]; syncingAccountIds: string[]; websocketConnectedAccountIds: string[]; } /** * Extended logger interface that supports structured logging */ interface StructuredLogger extends Logger { child?(bindings: Record): StructuredLogger; } /** * Creates a child logger if the logger supports it, otherwise returns the original */ declare function createChildLogger(logger: StructuredLogger | undefined, bindings: Record): StructuredLogger | undefined; /** * Formats a log message with optional context data */ declare function formatLogMessage(message: string, data?: Record): string; /** * Default values for quote transformation */ declare const QUOTE_DEFAULTS: { readonly UNIT: "sat"; readonly STATE_PAID: "PAID"; }; /** * Validates that a quote has required fields */ declare function isValidQuote(quote: unknown): quote is NPCQuote; /** * Validates that a string is a valid URL */ declare function isValidUrl(url: string): boolean; //#endregion //#region src/accounts/NPCAccountRuntime.d.ts declare const npcRequiredServices: readonly ["mintOperationService", "mintService", "quotes", "paymentRequestService", "eventBus"]; type NPCPluginContext = PluginContext; type SyncTrigger = "manual" | "websocket" | "interval"; interface NPCAccountRuntimeOptions { id: string; baseUrl: string; signer: Signer; sinceStore: SinceStore; syncIntervalMs?: number; useWebsocket: boolean; autoStart: boolean; logger?: StructuredLogger; client?: NPCClient; } /** * Owns the authenticated NPC client and sync lifecycle for one account. */ declare class NPCAccountRuntime { readonly id: string; readonly baseUrl: string; readonly signer: Signer; readonly sinceStore: SinceStore; readonly syncIntervalMs?: number; readonly useWebsocket: boolean; readonly autoStart: boolean; readonly client: NPCClient; private readonly logger?; private isStarted; private isRunning; private hasPendingUpdate; private runPromise?; private unsubscribe?; private intervalTimer?; private isReady; private isWebSocketConnected; private wsReconnectAttempts; private wsReconnectTimer?; private ctx?; private isShuttingDown; private areSubscriptionsPaused; private readyWaiters; constructor(options: NPCAccountRuntimeOptions); attachContext(ctx: NPCPluginContext): void; markReady(): void; getStatus(): NPCAccountStatus; getSummary(): NPCAccountSummary; start(): void; stop(): Promise; shutdown(): Promise; sync(trigger?: SyncTrigger): Promise; pauseSubscriptions(): void; resumeSubscriptions(): void; private teardown; private waitUntilReady; private resolveReadyWaiters; private disposeWebSocketSubscription; private connectWebSocket; private scheduleWebSocketReconnect; private armIntervalTimer; private requestSync; private startRunner; private syncPaidQuotesOnce; private prepareExistingMintOperation; } //#endregion //#region src/PluginApi.d.ts /** * Root NPC extension API registered on the host manager. */ declare class NPCPluginApi { private readonly plugin; constructor(plugin: NPCPlugin); addAccount(options: AddNPCAccountOptions): Promise; removeAccount(accountId: string): Promise; getAccount(accountId: string): NPCAccountApi | undefined; listAccounts(): NPCAccountSummary[]; getStatus(): NPCPluginStatus; syncAll(): Promise; shutdownAccount(accountId: string): Promise; } /** * Account-scoped NPC API. */ declare class NPCAccountApi { readonly id: string; private readonly getPrService; private readonly runtime; constructor(getPrService: () => NPCPluginContext["services"]["paymentRequestService"], runtime: NPCAccountRuntime); /** * Fetches NPC server metadata and account information. */ getInfo(): Promise; /** * Sets the account username, handling payment-required flows when requested. */ setUsername(username: string, attemptPayment?: boolean): Promise; /** * Retrieves raw NPC quotes created since a Unix timestamp. */ getQuotesSince(sinceUnix: number): Promise; /** * Triggers this account's quote sync cycle. */ sync(): Promise; start(): void; stop(): Promise; getStatus(): NPCAccountStatus; } //#endregion //#region src/plugins/NPCPlugin.d.ts type RequiredServices = typeof npcRequiredServices; /** * NPubCash plugin for @cashu/coco-core. * * The plugin owns host-level registration while account runtimes own NPC * clients, signers, timers, websocket subscriptions, and quote sync state. */ declare class NPCPlugin implements Plugin { readonly name = "npc"; readonly required: readonly ["mintOperationService", "mintService", "quotes", "paymentRequestService", "eventBus"]; private readonly defaultBaseUrl?; private readonly accountStore?; private readonly sinceStoreFactory?; private readonly syncIntervalMs?; private readonly useWebsocket; private readonly logger?; private readonly accounts; private ctx?; private isReady; private isShuttingDown; private rootApi?; private lifecycleUnsubscribers; constructor(options?: NPCPluginOptions); getStatus(): NPCPluginStatus; onInit(ctx: NPCPluginContext): () => Promise; onReady(): void; addAccount(options: AddNPCAccountOptions): Promise; removeAccount(accountId: string): Promise; getAccount(accountId: string): NPCAccountApi | undefined; listAccounts(): NPCAccountSummary[]; syncAll(): Promise; shutdownAccount(accountId: string): Promise; shutdown(): Promise; private normalizeAccountConfig; private matchesConfig; private resolveSinceStore; private subscribeToLifecycleEvents; private unsubscribeFromLifecycleEvents; private pauseSubscriptions; private resumeSubscriptions; private getPaymentRequestService; private createAccountRecord; } //#endregion //#region src/index.d.ts declare module "@cashu/coco-core/plugin" { interface PluginExtensions { npc: NPCPluginApi; } } //#endregion export { AddNPCAccountOptions, LocalStorageSinceStore, MemorySinceStore, MintQuote, NPCAccountApi, NPCAccountRecord, type NPCAccountStatus, NPCAccountStore, type NPCAccountSummary, NPCPlugin, NPCPluginApi, type NPCPluginOptions, type NPCPluginStatus, NPCQuote, NPCSinceStoreFactory, QUOTE_DEFAULTS, SetUsernameResult, Signer, SinceStore, StructuredLogger, createChildLogger, formatLogMessage, isValidQuote, isValidUrl };