import { R as Row, T as Transport, Q as QueryResult, a as TransactionOptions } from './types-YTdPe6Qz.js'; /** * RpcPromise - A promise wrapper that supports capnweb magic map and pipelining * * This class enables: * - Magic map support for N+1 query elimination * - Promise pipelining for batched operations * - Lazy execution (queries don't execute until awaited or .map()'d) * * @example Magic Map * ```typescript * const usersWithOrders = await db.query('SELECT * FROM users') * .map(users => Promise.all( * users.map(u => db.query('SELECT * FROM orders WHERE user_id = $1', [u.id])) * )) * ``` * * @example Promise Pipelining * ```typescript * const user = db.query('SELECT * FROM users WHERE id = $1', [id]) * const posts = user.map(u => db.query('SELECT * FROM posts WHERE author = $1', [u.id])) * const comments = posts.map(p => db.query('SELECT * FROM comments WHERE post_id = ANY($1)', [p.map(x => x.id)])) * const result = await comments // Single round trip! * ``` */ /** * Execution context for RPC pipelining * Accumulates queries that can be batched together */ interface RpcExecutionContext { /** Add a query to the batch */ addQuery(sql: string, params?: unknown[]): number; /** Execute all batched queries */ executeBatch(): Promise; /** Get a pending result by query ID */ getResult(queryId: number): Promise; /** Check if the context is currently collecting queries */ isCollecting(): boolean; /** Start collecting queries for batching */ startCollecting(): void; /** Stop collecting and execute batch */ stopCollecting(): Promise; } /** * Result from a batched query */ interface BatchResult { queryId: number; rows: T[]; fields: Array<{ name: string; dataTypeID: number; }>; rowCount: number; durationMs: number; } /** * Map function signature for RpcPromise */ type MapFn = (value: T) => U | Promise; /** * RpcPromise implementation * Wraps a query operation with magic map and pipelining support */ declare class RpcPromise implements PromiseLike { private executor; private cachedResult; private executed; private executing; private context; constructor(executor: () => Promise, context?: RpcExecutionContext | null); /** * Map over the result with magic map support * * The map function receives the resolved value and can return: * - A plain value * - A Promise * - Another RpcPromise (for pipelining) * * When the callback returns RpcPromises, they are batched together * with the original query for efficient execution. * * @example * ```typescript * const usersWithPosts = db.query('SELECT * FROM users') * .map(users => Promise.all( * users.map(u => db.query('SELECT * FROM posts WHERE user_id = $1', [u.id])) * )) * ``` */ map(fn: MapFn): RpcPromise; /** * FlatMap for when the map function returns an RpcPromise */ flatMap(fn: (value: T) => RpcPromise): RpcPromise; /** * Execute the query and return the result */ execute(): Promise; /** * Reset the execution state to allow re-execution */ reset(): void; /** * Check if the promise has been executed */ isExecuted(): boolean; /** * PromiseLike implementation - makes this thenable */ then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null): Promise; /** * Catch handler */ catch(onrejected?: ((reason: unknown) => TResult | PromiseLike) | null): Promise; /** * Finally handler */ finally(onfinally?: (() => void) | null): Promise; } /** * Create an RpcPromise from a query function */ declare function createRpcPromise(executor: () => Promise, context?: RpcExecutionContext | null): RpcPromise; /** * Query result type for typed queries */ interface RpcQueryResult { rows: T[]; fields: Array<{ name: string; dataTypeID: number; }>; rowCount: number; durationMs: number; } /** * Create an RpcPromise that extracts rows from a query result */ declare function createRowsPromise(executor: () => Promise>, context?: RpcExecutionContext | null): RpcPromise; /** * Batch multiple RpcPromises for efficient execution * * This collects all queries from the provided promises and executes * them in a single batch, then distributes the results. * * @example * ```typescript * const [users, orders, products] = await batchExecute([ * db.query('SELECT * FROM users'), * db.query('SELECT * FROM orders'), * db.query('SELECT * FROM products'), * ]) * ``` */ declare function batchExecute[]>(promises: T): Promise<{ [K in keyof T]: T[K] extends RpcPromise ? U : never; }>; /** * Create a magic map wrapper that batches nested queries * * This enables the N+1 query elimination pattern: * ```typescript * const usersWithOrders = await magicMap( * db.query('SELECT * FROM users'), * users => users.map(u => db.query('SELECT * FROM orders WHERE user_id = $1', [u.id])) * ) * ``` */ declare function magicMap(source: RpcPromise, mapFn: (items: T[]) => RpcPromise[]): Promise; /** * RPC Transport for postgres.do * * Connects to PostgresDO via capnweb RPC for: * - Direct Worker-to-DO communication without HTTP overhead * - Promise pipelining for efficient batched operations * - Magic map support for N+1 query elimination * * @see packages/postgres/src/worker/rpc.ts for the server-side RPC API * @see packages/postgres/src/worker/proxy.ts for the proxy session pool */ /** * RPC Transport configuration */ interface RpcTransportConfig { /** WebSocket URL for the capnweb RPC endpoint */ url: string; /** API key for authentication */ apiKey?: string | undefined; /** Custom WebSocket implementation */ WebSocket?: typeof WebSocket | undefined; /** Connection timeout in milliseconds */ connectTimeout?: number | undefined; /** Request timeout in milliseconds */ requestTimeout?: number | undefined; /** Enable automatic batching */ autoBatch?: boolean | undefined; /** Batch delay in milliseconds (how long to wait for more queries) */ batchDelayMs?: number | undefined; } /** * RPC Transport implementation * * Provides capnweb-style RPC communication with PostgresDO: * - Automatic query batching for N+1 elimination * - Promise pipelining support * - WebSocket-based persistent connection */ declare class RpcTransport implements Transport, RpcExecutionContext { private readonly config; private readonly WebSocketImpl; private ws; private connected; private authenticated; private connecting; private requestId; private pendingRequests; private pendingBatch; private collecting; constructor(config: RpcTransportConfig); /** * Add a query to the current batch */ addQuery(sql: string, params?: unknown[]): number; /** * Execute all batched queries */ executeBatch(): Promise; /** * Get a pending result by query ID */ getResult(_queryId: number): Promise; /** * Check if the context is currently collecting queries */ isCollecting(): boolean; /** * Start collecting queries for batching */ startCollecting(): void; /** * Stop collecting and execute batch */ stopCollecting(): Promise; /** * Flush the pending batch immediately */ private flushBatch; /** * Execute a SQL query with RpcPromise support */ queryRpc(sql: string, params?: unknown[]): RpcPromise; /** * Execute a SQL query and return full result */ query(sql: string, params?: unknown[]): Promise>; /** * Execute a batch of queries */ batch(queries: Array<{ sql: string; params?: unknown[]; }>): Promise>>; /** * Execute a batch of queries within a transaction */ batchTransaction(queries: Array<{ sql: string; params?: unknown[]; }>, options?: TransactionOptions): Promise>>; /** * Execute multiple queries in a transaction (Transport interface) */ transaction(queries: Array<{ sql: string; params?: unknown[]; }>, options?: TransactionOptions): Promise; /** * Close the WebSocket connection */ close(): Promise; /** * Check if transport is connected */ isConnected(): boolean; /** * Ensure the WebSocket is connected and authenticated */ private ensureConnected; /** * Establish WebSocket connection */ private connect; /** * Authenticate with the API key */ private authenticate; /** * Send a request and wait for response */ private sendRequest; /** * Handle incoming WebSocket message */ private handleMessage; /** * Reject all pending requests */ private rejectAllPending; /** * Get next request ID */ private nextRequestId; /** * Serialize transaction options */ private serializeTransactionOptions; } /** * Create an RPC transport instance */ declare function createRpcTransport(config: RpcTransportConfig): RpcTransport; export { type BatchResult as B, type MapFn as M, RpcTransport as R, type RpcTransportConfig as a, RpcPromise as b, createRpcTransport as c, createRpcPromise as d, createRowsPromise as e, batchExecute as f, type RpcExecutionContext as g, type RpcQueryResult as h, magicMap as m };