@dakota-xyz/ts-sdk 3.2.0 → 3.4.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.
- package/README.md +95 -4
- package/dist/governance/index.d.mts +315 -0
- package/dist/governance/index.d.ts +315 -0
- package/dist/governance/index.js +379 -0
- package/dist/governance/index.js.map +1 -0
- package/dist/governance/index.mjs +365 -0
- package/dist/governance/index.mjs.map +1 -0
- package/dist/index.d.mts +983 -105
- package/dist/index.d.ts +983 -105
- package/dist/index.js +872 -123
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +852 -122
- package/dist/index.mjs.map +1 -1
- package/dist/webhook/index.d.mts +3 -2
- package/dist/webhook/index.d.ts +3 -2
- package/dist/webhook/index.js +1 -0
- package/dist/webhook/index.js.map +1 -1
- package/dist/webhook/index.mjs +1 -0
- package/dist/webhook/index.mjs.map +1 -1
- package/package.json +15 -3
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/environment.ts","../src/client/errors.ts","../src/client/config.ts","../src/client/transport.ts","../src/client/pagination.ts","../src/client/resources/base.ts","../src/client/resources/customers.ts","../src/client/resources/recipients.ts","../src/client/resources/destinations.ts","../src/client/resources/accounts.ts","../src/client/resources/transactions.ts","../src/client/resources/wallets.ts","../src/client/resources/events.ts","../src/client/resources/applications.ts","../src/client/resources/policies.ts","../src/client/resources/signer-groups.ts","../src/client/resources/api-keys.ts","../src/client/resources/users.ts","../src/client/resources/webhooks.ts","../src/client/resources/info.ts","../src/client/resources/legal.ts","../src/client/resources/rd-marketing-fee.ts","../src/client/resources/sandbox.ts","../src/client/resources/self-serve.ts","../src/client/resources/fee-payout-destination.ts","../src/client/resources/payment-agents.ts","../src/client/resources/instructions.ts","../src/client/resources/mandates.ts","../src/client/resources/scheduled-payments.ts","../src/client/resources/insights.ts","../src/client/resources/agentic-policy.ts","../src/agentic/chat.ts","../src/agentic/wallets.ts","../src/client/client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AAA,GAAW,aAAa,QAAQ,CAAA;AACtC,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACvB,EAAA,MAAM,KAAK,QAAA,CAAS,MAAA;AAAA,IAClB,EAAE,GAAA,EAAK,SAAA,EAAW,WAAA,EAAa,KAAA,EAAM;AAAA,IACrC,MAAA,CAAO,IAAA,CAAK,eAAA,EAAiB,QAAQ;AAAA,GACvC;AACA,EAAA,IAAI,CAAC,EAAA,EAAI;AACP,IAAA,MAAM,IAAI,MAAM,+BAA+B,CAAA;AAAA,EACjD;AACF","file":"index.mjs","sourcesContent":["/**\n * Environment configuration for Dakota Platform API.\n */\nexport enum Environment {\n /** Sandbox environment for testing - no real money moves */\n Sandbox = 'sandbox',\n /** Production environment - real transactions with real money */\n Production = 'production',\n /** Development environment (internal use) */\n Development = 'development',\n /** Local environment (internal use) */\n Local = 'local',\n}\n\nconst ENVIRONMENT_URLS: Record<Environment, string> = {\n [Environment.Sandbox]: 'https://api.platform.sandbox.dakota.xyz',\n [Environment.Production]: 'https://api.platform.dakota.xyz',\n [Environment.Development]: 'https://api.platform.development.dakota.xyz',\n [Environment.Local]: 'http://localhost:6464',\n};\n\n/**\n * Get the base URL for a given environment.\n */\nexport function getEnvironmentURL(env: Environment): string {\n const url = ENVIRONMENT_URLS[env];\n if (!url) {\n throw new Error(`Unknown environment: ${env}`);\n }\n return url;\n}\n","/**\n * Error classes for Dakota SDK.\n */\n\n/** Status codes that are safe to retry */\nconst RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);\n\n/**\n * Represents a structured Dakota Platform API error response.\n */\nexport class APIError extends Error {\n /** HTTP status code */\n readonly statusCode: number;\n /** Machine-readable error code */\n readonly code: string;\n /** Additional error details */\n readonly details: Record<string, unknown> | null;\n /** Request ID for support tickets */\n readonly requestId: string | null;\n /** Raw response body */\n readonly rawBody: string | null;\n /** Whether this error is safe to retry */\n readonly retryable: boolean;\n /**\n * A plain-language rendition of the problem, written for the END CUSTOMER,\n * when one exists for this error.\n *\n * `message` names request fields and actions so a machine caller can\n * self-correct. This says the same thing without API vocabulary. Show it\n * when relaying an error into a human surface (chat, email, UI), and fall\n * back to `message` when it is null.\n */\n readonly userMessage: string | null;\n /**\n * A link the customer can follow to CLEAR this error, present only on\n * problems with a concrete self-service remedy.\n *\n * Today `terms-not-accepted` returns one, pointing at the hosted flow where\n * the outstanding agreement can be signed. It is token-gated and usable\n * as-is — send the customer to it rather than parsing one out of the\n * message.\n */\n readonly resolutionUrl: string | null;\n\n constructor(\n statusCode: number,\n code: string,\n message: string,\n options?: {\n details?: Record<string, unknown> | null;\n requestId?: string | null;\n rawBody?: string | null;\n userMessage?: string | null;\n resolutionUrl?: string | null;\n }\n ) {\n super(message);\n this.name = 'APIError';\n this.statusCode = statusCode;\n this.code = code;\n this.details = options?.details ?? null;\n this.requestId = options?.requestId ?? null;\n this.rawBody = options?.rawBody ?? null;\n this.retryable = RETRYABLE_STATUS_CODES.has(statusCode);\n this.userMessage = options?.userMessage ?? null;\n this.resolutionUrl = options?.resolutionUrl ?? null;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, APIError);\n }\n }\n\n /**\n * Create an APIError from an HTTP response.\n */\n static async fromResponse(response: Response): Promise<APIError> {\n const requestId = response.headers.get('x-request-id');\n let rawBody: string | null = null;\n let code = `http_${response.status}`;\n let message = response.statusText || 'Unknown error';\n let details: Record<string, unknown> | null = null;\n let userMessage: string | null = null;\n let resolutionUrl: string | null = null;\n\n try {\n rawBody = await response.text();\n const parsed = JSON.parse(rawBody);\n\n // Try ProblemDetails format (RFC 7807)\n if (parsed.type && typeof parsed.type === 'string') {\n // Extract code from type URI fragment (e.g., \"...#invalid-request\")\n const hashIndex = parsed.type.lastIndexOf('#');\n if (hashIndex !== -1) {\n code = parsed.type.substring(hashIndex + 1);\n }\n }\n\n // Use code if directly provided\n if (parsed.code) {\n code = parsed.code;\n }\n\n // Build message from title and detail\n if (parsed.title) {\n message = parsed.title;\n if (parsed.detail) {\n message = `${parsed.title}: ${parsed.detail}`;\n }\n } else if (parsed.message) {\n message = parsed.message;\n } else if (parsed.detail) {\n message = parsed.detail;\n }\n\n // Extract details\n if (parsed.details && typeof parsed.details === 'object') {\n details = parsed.details;\n }\n\n // RFC 9457 extensions. `message` stays the machine-facing rendition;\n // these two are what a human surface should show instead.\n if (typeof parsed.user_message === 'string') {\n userMessage = parsed.user_message;\n }\n if (typeof parsed.resolution_url === 'string') {\n resolutionUrl = parsed.resolution_url;\n }\n } catch {\n // Failed to parse JSON, use defaults\n }\n\n return new APIError(response.status, code, message, {\n details,\n requestId,\n rawBody,\n userMessage,\n resolutionUrl,\n });\n }\n\n override toString(): string {\n if (this.code) {\n return `APIError [${this.statusCode} ${this.code}]: ${this.message}`;\n }\n return `APIError [${this.statusCode}]: ${this.message}`;\n }\n}\n\n/**\n * Represents a transport-level error (network, timeout, etc.).\n */\nexport class TransportError extends Error {\n /** The underlying error that caused this transport error */\n readonly cause: Error | undefined;\n\n constructor(message: string, cause?: Error) {\n super(message);\n this.name = 'TransportError';\n this.cause = cause;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, TransportError);\n }\n }\n\n override toString(): string {\n if (this.cause) {\n return `TransportError: ${this.message} (caused by: ${this.cause.message})`;\n }\n return `TransportError: ${this.message}`;\n }\n}\n\n/**\n * Represents a configuration error.\n */\nexport class ConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigurationError';\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ConfigurationError);\n }\n }\n}\n","/**\n * Configuration types and validation for Dakota SDK.\n */\n\nimport { Environment, getEnvironmentURL } from './environment.js';\nimport { ConfigurationError } from './errors.js';\n\n/**\n * Authentication mode for API requests.\n */\nexport enum AuthMode {\n /** Automatically select the best auth method based on the endpoint */\n Auto = 'auto',\n /** Always use x-api-key header */\n APIKey = 'api_key',\n /** Always use X-Application-Token header */\n ApplicationToken = 'application_token',\n}\n\n/**\n * Retry policy configuration.\n */\nexport interface RetryPolicy {\n /** Maximum number of attempts including the initial request (default: 3) */\n maxAttempts: number;\n /** Initial backoff delay in milliseconds (default: 200) */\n initialBackoffMs: number;\n /** Maximum backoff delay in milliseconds (default: 2000) */\n maxBackoffMs: number;\n}\n\n/**\n * Logger interface for SDK logging.\n */\nexport interface Logger {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n}\n\n/**\n * Configuration options for DakotaClient.\n */\nexport interface DakotaClientConfig {\n /** API key for authentication (required unless applicationToken is provided) */\n apiKey?: string;\n /** Application token for authentication (alternative to apiKey) */\n applicationToken?: string;\n /** Target environment (default: Sandbox) */\n environment?: Environment;\n /** Override the base URL (takes precedence over environment) */\n baseURL?: string;\n /** Authentication mode (default: Auto) */\n authMode?: AuthMode;\n /**\n * Request timeout in milliseconds (default: 15000).\n *\n * Setting this explicitly applies it to EVERY request, including the\n * model-backed agentic endpoints that otherwise get a longer default\n * ({@link AGENTIC_MODEL_TIMEOUT_MS}) — so you keep full control, but a\n * global value tuned for fast reads will also cap agent turns. To keep\n * the long agentic default while tightening everything else, leave this\n * unset and pass `{ timeout }` per request instead.\n *\n * Note this is a per-ATTEMPT deadline: with the default retry policy a\n * timing-out request can be attempted up to `retryPolicy.maxAttempts`\n * times, so worst-case wall clock is roughly `timeout × maxAttempts`.\n */\n timeout?: number;\n /** Retry policy configuration */\n retryPolicy?: Partial<RetryPolicy>;\n /** Logger instance */\n logger?: Logger;\n /** Automatically generate idempotency keys for POST requests (default: true) */\n automaticIdempotency?: boolean;\n /** Custom idempotency key generator */\n idempotencyKeyGenerator?: () => string;\n /** Custom fetch implementation */\n fetch?: typeof fetch;\n}\n\n/**\n * Resolved configuration with all defaults applied.\n */\nexport interface ResolvedConfig {\n apiKey: string | null;\n applicationToken: string | null;\n baseURL: string;\n authMode: AuthMode;\n timeout: number;\n /**\n * Whether `timeout` came from the caller rather than the default.\n *\n * An explicit timeout is a deliberate choice and wins everywhere. An\n * inherited default does not, so endpoints that know they are slow (the\n * model-backed agentic ones) can raise it without overriding a value the\n * caller actually asked for.\n */\n timeoutWasExplicit: boolean;\n retryPolicy: RetryPolicy;\n logger: Logger;\n automaticIdempotency: boolean;\n idempotencyKeyGenerator: () => string;\n fetch: typeof fetch;\n}\n\n/**\n * Default per-request timeout (ms).\n *\n * Sized for ordinary CRUD reads and writes, which answer in well under a\n * second. It is deliberately NOT the deadline for the agentic endpoints\n * that call a model — see {@link AGENTIC_MODEL_TIMEOUT_MS}.\n */\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\n/**\n * Default per-request timeout (ms) for the agentic endpoints whose work is\n * a sequence of model calls: drafting proposals.\n *\n * A multi-payee drafting turn (\"pay these nine vendors every Friday\")\n * legitimately runs minutes — it reads payees, checks balances, drafts, and\n * revises, each a separate model round. Under the ordinary 15s deadline\n * those turns abort client-side while the server is still working, which\n * reads as flakiness rather than as a deadline: the simple turns finish in\n * time and the complex ones do not.\n *\n * Applies only when the caller did not set `timeout` on the client (an\n * explicit choice always wins) and can be overridden per request.\n */\nexport const AGENTIC_MODEL_TIMEOUT_MS = 180_000;\n\n/**\n * Default retry policy.\n */\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxAttempts: 3,\n initialBackoffMs: 200,\n maxBackoffMs: 2000,\n};\n\n/**\n * No-op logger that discards all messages.\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Console logger for development.\n */\nexport const consoleLogger: Logger = {\n debug: (msg, ...args) => console.debug(`[Dakota SDK] ${msg}`, ...args),\n info: (msg, ...args) => console.info(`[Dakota SDK] ${msg}`, ...args),\n warn: (msg, ...args) => console.warn(`[Dakota SDK] ${msg}`, ...args),\n error: (msg, ...args) => console.error(`[Dakota SDK] ${msg}`, ...args),\n};\n\n/**\n * Generate a UUID v4 for idempotency keys.\n */\nfunction generateUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Validate and resolve configuration with defaults.\n */\nexport function resolveConfig(config: DakotaClientConfig): ResolvedConfig {\n const authMode = config.authMode ?? AuthMode.Auto;\n\n // Validate authentication\n if (authMode === AuthMode.Auto) {\n if (!config.apiKey && !config.applicationToken) {\n throw new ConfigurationError('API key or application token is required');\n }\n } else if (authMode === AuthMode.APIKey) {\n if (!config.apiKey) {\n throw new ConfigurationError('API key is required when using AuthMode.APIKey');\n }\n } else if (authMode === AuthMode.ApplicationToken) {\n if (!config.applicationToken) {\n throw new ConfigurationError(\n 'Application token is required when using AuthMode.ApplicationToken'\n );\n }\n }\n\n // Resolve base URL\n let baseURL: string;\n if (config.baseURL) {\n baseURL = config.baseURL.replace(/\\/$/, ''); // Remove trailing slash\n // Validate URL\n try {\n new URL(baseURL);\n } catch {\n throw new ConfigurationError('Invalid base URL');\n }\n } else {\n const env = config.environment ?? Environment.Sandbox;\n baseURL = getEnvironmentURL(env);\n }\n\n // Validate timeout\n const timeoutWasExplicit = config.timeout !== undefined;\n const timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;\n if (timeout <= 0) {\n throw new ConfigurationError('Timeout must be greater than zero');\n }\n\n // Resolve retry policy\n const retryPolicy: RetryPolicy = {\n maxAttempts: config.retryPolicy?.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,\n initialBackoffMs: config.retryPolicy?.initialBackoffMs ?? DEFAULT_RETRY_POLICY.initialBackoffMs,\n maxBackoffMs: config.retryPolicy?.maxBackoffMs ?? DEFAULT_RETRY_POLICY.maxBackoffMs,\n };\n\n // Validate retry policy\n if (retryPolicy.maxAttempts <= 0) {\n throw new ConfigurationError('Retry max attempts must be greater than zero');\n }\n if (retryPolicy.initialBackoffMs <= 0) {\n throw new ConfigurationError('Retry initial backoff must be greater than zero');\n }\n if (retryPolicy.maxBackoffMs <= 0) {\n throw new ConfigurationError('Retry max backoff must be greater than zero');\n }\n if (retryPolicy.maxBackoffMs < retryPolicy.initialBackoffMs) {\n throw new ConfigurationError('Retry max backoff must be >= initial backoff');\n }\n\n return {\n apiKey: config.apiKey ?? null,\n applicationToken: config.applicationToken ?? null,\n baseURL,\n authMode,\n timeout,\n timeoutWasExplicit,\n retryPolicy,\n logger: config.logger ?? noopLogger,\n automaticIdempotency: config.automaticIdempotency ?? true,\n idempotencyKeyGenerator: config.idempotencyKeyGenerator ?? generateUUID,\n fetch: config.fetch ?? globalThis.fetch,\n };\n}\n","/**\n * HTTP transport layer with retry, authentication, and idempotency.\n */\n\nimport { ResolvedConfig, AuthMode } from './config.js';\nimport { APIError, TransportError } from './errors.js';\n\n/** Status codes that are safe to retry */\nconst RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);\n\n/** HTTP methods that are safe to retry without idempotency key */\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']);\n\n/**\n * HTTP methods that accept an idempotency key. Dakota's spec marks\n * `IdempotencyKeyHeader` as required on every mutating endpoint, so the\n * SDK must forward it for POST, PUT, PATCH, and DELETE. Earlier versions\n * only attached the header on POST and silently dropped it on PUT/PATCH.\n * DELETE is included because the platform's agentic detach endpoints\n * (e.g. DELETE /signer-groups/{id}/signers/{signer_id}) 400 without one.\n */\nconst IDEMPOTENT_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);\n\n/**\n * Request options for the transport layer.\n */\nexport interface TransportRequestOptions {\n method: string;\n path: string;\n body?: unknown;\n query?: Record<string, string | number | boolean | undefined>;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n signal?: AbortSignal;\n /**\n * Caller-supplied deadline (ms) for this one request. Beats everything —\n * it is the most specific statement of intent available.\n */\n timeout?: number;\n /**\n * The deadline (ms) this ENDPOINT wants when nobody has said otherwise —\n * how long its work actually takes. Used only when the caller passed no\n * per-request timeout AND set no explicit client-wide one, so it can\n * never override a deadline someone deliberately chose.\n */\n endpointTimeout?: number;\n /**\n * The operation's success response carries NO body — a bare 200, as\n * `POST /customers/{id}/applications/{id}/withdraw` answers. The transport\n * then resolves `undefined` without parsing, exactly as for a 204.\n *\n * Opt-in per operation on purpose. Every other call promises a document,\n * and for those an empty 2xx body is a fault (a proxy, a stalled upstream)\n * that must keep surfacing as an error and keep its retry: resolving\n * `undefined` there would move the failure to a TypeError far from the\n * call site.\n */\n noContent?: boolean;\n}\n\n/**\n * HTTP transport with retry, auth, and idempotency support.\n */\nexport class Transport {\n private readonly config: ResolvedConfig;\n\n constructor(config: ResolvedConfig) {\n this.config = config;\n }\n\n /**\n * Make an HTTP request with automatic retry and error handling.\n */\n async request<T>(options: TransportRequestOptions): Promise<T> {\n const { method, path, body, query, headers, idempotencyKey, signal, noContent } = options;\n\n // Build URL with query parameters\n const url = this.buildURL(path, query);\n\n // Build headers\n const requestHeaders = this.buildHeaders(method, path, headers, idempotencyKey);\n\n // Build request body\n const requestBody = body !== undefined ? JSON.stringify(body) : undefined;\n\n // Execute with retry\n return this.executeWithRetry<T>(\n url,\n {\n method,\n headers: requestHeaders,\n body: requestBody,\n signal,\n },\n this.resolveTimeout(options),\n noContent === true\n );\n }\n\n /**\n * Build the full URL with query parameters.\n */\n private buildURL(\n path: string,\n query?: Record<string, string | number | boolean | undefined>\n ): string {\n const url = new URL(path, this.config.baseURL);\n\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n return url.toString();\n }\n\n /**\n * Build request headers with authentication.\n */\n private buildHeaders(\n method: string,\n path: string,\n customHeaders?: Record<string, string>,\n idempotencyKey?: string\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': 'dakota-ts-sdk/1.0.0',\n ...customHeaders,\n };\n\n // Add authentication header\n this.addAuthHeader(headers, path);\n\n // Add idempotency key for mutating requests (POST, PUT, PATCH).\n if (IDEMPOTENT_METHODS.has(method)) {\n const key =\n idempotencyKey ??\n (this.config.automaticIdempotency ? this.config.idempotencyKeyGenerator() : undefined);\n if (key) {\n headers['x-idempotency-key'] = key;\n }\n }\n\n return headers;\n }\n\n /**\n * Add authentication header based on auth mode and path.\n */\n private addAuthHeader(headers: Record<string, string>, path: string): void {\n // Don't override existing auth headers\n if (headers['x-api-key'] || headers['x-application-token']) {\n return;\n }\n\n const { authMode, apiKey, applicationToken } = this.config;\n\n switch (authMode) {\n case AuthMode.APIKey:\n if (apiKey) {\n headers['x-api-key'] = apiKey;\n }\n break;\n\n case AuthMode.ApplicationToken:\n if (applicationToken) {\n headers['x-application-token'] = applicationToken;\n }\n break;\n\n case AuthMode.Auto:\n default:\n // For /applications routes, prefer application token\n if (path.startsWith('/applications') && applicationToken) {\n headers['x-application-token'] = applicationToken;\n } else if (apiKey) {\n headers['x-api-key'] = apiKey;\n } else if (applicationToken) {\n headers['x-application-token'] = applicationToken;\n }\n break;\n }\n }\n\n /**\n * Resolve the deadline for one request, most specific intent first:\n *\n * 1. the caller's per-request `timeout`\n * 2. an explicit client-wide `timeout`\n * 3. the endpoint's own default (slow endpoints raise their own)\n * 4. the client-wide default\n *\n * (2) sits above (3) on purpose: a caller who configured a timeout chose\n * it, and an endpoint must not quietly overrule that. (3) exists so the\n * far more common caller — the one who configured nothing — gets a\n * deadline that matches what the endpoint actually does.\n */\n private resolveTimeout(options: TransportRequestOptions): number {\n if (options.timeout !== undefined) {\n return options.timeout;\n }\n if (this.config.timeoutWasExplicit) {\n return this.config.timeout;\n }\n return options.endpointTimeout ?? this.config.timeout;\n }\n\n /**\n * Execute request with exponential backoff retry.\n *\n * `timeout` is per ATTEMPT, not per call: each attempt gets its own\n * deadline, so a request that keeps timing out can take up to\n * `timeout × maxAttempts` before it throws.\n */\n private async executeWithRetry<T>(\n url: string,\n init: RequestInit,\n timeout: number,\n noContent = false\n ): Promise<T> {\n const { maxAttempts, initialBackoffMs, maxBackoffMs } = this.config.retryPolicy;\n const method = init.method ?? 'GET';\n\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Declared outside the try so the catch can tell OUR deadline firing\n // apart from the caller aborting.\n let timedOut = false;\n try {\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeout);\n\n // Merge signals if provided\n const signal = init.signal\n ? this.mergeAbortSignals(init.signal, controller.signal)\n : controller.signal;\n\n this.logRequest(method, url, attempt);\n\n const response = await this.config.fetch(url, {\n ...init,\n signal,\n });\n\n clearTimeout(timeoutId);\n\n this.logResponse(method, url, response.status, attempt);\n\n // Check for successful response\n if (response.ok) {\n // Handle 204 No Content, and the operations that declare a bodiless\n // 200 (see `noContent`). Parsing an empty body as JSON throws, which\n // would reject a call whose side effect already happened.\n if (response.status === 204 || noContent) {\n return undefined as T;\n }\n return (await response.json()) as T;\n }\n\n // Convert to API error\n const apiError = await APIError.fromResponse(response);\n\n // Check if we should retry\n if (this.shouldRetry(response.status, method, init, attempt)) {\n lastError = apiError;\n const delay = this.calculateBackoff(attempt, response, initialBackoffMs, maxBackoffMs);\n this.config.logger.warn(\n `Request failed with ${response.status}, retrying in ${delay}ms (attempt ${attempt}/${maxAttempts})`\n );\n await this.sleep(delay);\n continue;\n }\n\n throw apiError;\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n // Handle abort/timeout. Only OUR deadline firing is a timeout — an\n // AbortError from the caller's own signal is a cancellation, and\n // reporting that as \"timed out\" sends people hunting a deadline\n // that never elapsed.\n if (error instanceof Error && error.name === 'AbortError' && timedOut) {\n lastError = new TransportError(\n `Request timed out after ${timeout}ms. ` +\n `This is the SDK's client-side deadline, not a server error — raise it with ` +\n `\\`new DakotaClient({ timeout })\\`, or per call with \\`{ timeout }\\` in the ` +\n `request options. Agent conversations are the usual cause: pass ` +\n `\\`{ timeout }\\` to \\`newAgentConversation\\`.`,\n error\n );\n } else if (error instanceof Error && error.name === 'AbortError') {\n // The caller cancelled. Retrying would re-issue a request they\n // explicitly called off, so this is terminal.\n throw new TransportError('Request aborted by caller', error);\n } else if (error instanceof Error) {\n lastError = new TransportError('Network error', error);\n } else {\n lastError = new TransportError('Unknown error');\n }\n\n // Retry on network errors for safe methods\n if (this.shouldRetryNetworkError(method, init, attempt)) {\n const delay = this.calculateBackoff(attempt, null, initialBackoffMs, maxBackoffMs);\n this.config.logger.warn(\n `Network error, retrying in ${delay}ms (attempt ${attempt}/${maxAttempts})`\n );\n await this.sleep(delay);\n continue;\n }\n\n throw lastError;\n }\n }\n\n // All retries exhausted\n throw lastError ?? new TransportError('Request failed after all retries');\n }\n\n /**\n * Determine if a request should be retried based on status code.\n */\n private shouldRetry(status: number, method: string, init: RequestInit, attempt: number): boolean {\n if (attempt >= this.config.retryPolicy.maxAttempts) {\n return false;\n }\n\n if (!RETRYABLE_STATUS_CODES.has(status)) {\n return false;\n }\n\n // Safe methods can always be retried\n if (SAFE_METHODS.has(method)) {\n return true;\n }\n\n // Mutating methods (POST/PUT/PATCH) can be retried if we have an\n // idempotency key. PUT/PATCH are already in SAFE_METHODS so they hit\n // the branch above; this catches POST.\n if (IDEMPOTENT_METHODS.has(method) && init.headers) {\n const headers = init.headers as Record<string, string>;\n return !!headers['x-idempotency-key'];\n }\n\n return false;\n }\n\n /**\n * Determine if a network error should be retried.\n */\n private shouldRetryNetworkError(method: string, init: RequestInit, attempt: number): boolean {\n if (attempt >= this.config.retryPolicy.maxAttempts) {\n return false;\n }\n\n // Safe methods can always be retried\n if (SAFE_METHODS.has(method)) {\n return true;\n }\n\n // Mutating methods (POST/PUT/PATCH) can be retried if we have an\n // idempotency key.\n if (IDEMPOTENT_METHODS.has(method) && init.headers) {\n const headers = init.headers as Record<string, string>;\n return !!headers['x-idempotency-key'];\n }\n\n return false;\n }\n\n /**\n * Calculate backoff delay with jitter.\n */\n private calculateBackoff(\n attempt: number,\n response: Response | null,\n initialBackoffMs: number,\n maxBackoffMs: number\n ): number {\n // Check for Retry-After header\n if (response) {\n const retryAfter = response.headers.get('retry-after');\n if (retryAfter) {\n const seconds = parseInt(retryAfter, 10);\n if (!isNaN(seconds)) {\n return seconds * 1000;\n }\n // Try parsing as HTTP date\n const date = Date.parse(retryAfter);\n if (!isNaN(date)) {\n return Math.max(0, date - Date.now());\n }\n }\n }\n\n // Exponential backoff with jitter (±20%)\n const exponentialDelay = initialBackoffMs * Math.pow(2, attempt - 1);\n const cappedDelay = Math.min(exponentialDelay, maxBackoffMs);\n const jitter = cappedDelay * 0.2 * (Math.random() * 2 - 1);\n return Math.round(cappedDelay + jitter);\n }\n\n /**\n * Merge multiple abort signals.\n */\n private mergeAbortSignals(signal1: AbortSignal, signal2: AbortSignal): AbortSignal {\n const controller = new AbortController();\n\n const abort = () => controller.abort();\n\n signal1.addEventListener('abort', abort);\n signal2.addEventListener('abort', abort);\n\n if (signal1.aborted || signal2.aborted) {\n controller.abort();\n }\n\n return controller.signal;\n }\n\n /**\n * Sleep for the specified duration.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n /**\n * Log outgoing request.\n */\n private logRequest(method: string, url: string, attempt: number): void {\n this.config.logger.debug(\n `Request: ${method} ${url}${attempt > 1 ? ` (attempt ${attempt})` : ''}`\n );\n }\n\n /**\n * Log response.\n */\n private logResponse(method: string, url: string, status: number, attempt: number): void {\n this.config.logger.debug(\n `Response: ${method} ${url} -> ${status}${attempt > 1 ? ` (attempt ${attempt})` : ''}`\n );\n }\n}\n","/**\n * Pagination utilities with async iterators.\n */\n\n/**\n * Pagination metadata from API responses.\n */\nexport interface PaginationMeta {\n total_count?: number;\n has_more_after?: boolean;\n has_more_before?: boolean;\n}\n\n/**\n * Paginated response structure.\n */\nexport interface PaginatedResponse<T> {\n data: T[];\n meta?: PaginationMeta;\n}\n\n/**\n * Parameters for paginated requests.\n */\nexport interface PaginationParams {\n starting_after?: string;\n ending_before?: string;\n limit?: number;\n}\n\n/**\n * Function to fetch a page of results.\n */\nexport type PageFetcher<T> = (cursor?: string) => Promise<PaginatedResponse<T>>;\n\n/**\n * Function to extract cursor from an item.\n */\nexport type CursorExtractor<T> = (item: T) => string;\n\n/**\n * Default cursor extractor that uses the 'id' field.\n */\nexport function defaultCursorExtractor<T extends { id?: string }>(item: T): string {\n if (!item.id) {\n throw new Error('Item does not have an id field for cursor extraction');\n }\n return item.id;\n}\n\n/**\n * Async iterator for paginated results.\n */\nexport class PaginatedIterator<T> implements AsyncIterable<T> {\n private readonly fetcher: PageFetcher<T>;\n private readonly cursorExtractor: CursorExtractor<T>;\n private cursor: string | undefined;\n private buffer: T[] = [];\n private hasMore = true;\n private started = false;\n\n constructor(fetcher: PageFetcher<T>, cursorExtractor?: CursorExtractor<T>) {\n this.fetcher = fetcher;\n this.cursorExtractor = cursorExtractor ?? (defaultCursorExtractor as CursorExtractor<T>);\n }\n\n /**\n * Implement async iterator protocol.\n */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next: async (): Promise<IteratorResult<T>> => {\n const item = await this.next();\n if (item === null) {\n return { done: true, value: undefined };\n }\n return { done: false, value: item };\n },\n };\n }\n\n /**\n * Get the next item, or null if no more items.\n */\n async next(): Promise<T | null> {\n // If buffer has items, return next one\n if (this.buffer.length > 0) {\n return this.buffer.shift()!;\n }\n\n // If no more pages, we're done\n if (!this.hasMore && this.started) {\n return null;\n }\n\n // Fetch next page\n await this.fetchNextPage();\n\n // Return first item from buffer, or null if empty\n if (this.buffer.length > 0) {\n return this.buffer.shift()!;\n }\n\n return null;\n }\n\n /**\n * Collect all items into an array.\n */\n async toArray(): Promise<T[]> {\n const items: T[] = [];\n for await (const item of this) {\n items.push(item);\n }\n return items;\n }\n\n /**\n * Get the first item, or null if none.\n */\n async first(): Promise<T | null> {\n return this.next();\n }\n\n /**\n * Fetch the next page of results.\n */\n private async fetchNextPage(): Promise<void> {\n this.started = true;\n\n const response = await this.fetcher(this.cursor);\n this.buffer = response.data ?? [];\n\n // Update cursor for next page\n if (this.buffer.length > 0) {\n const lastItem = this.buffer[this.buffer.length - 1];\n if (lastItem) {\n this.cursor = this.cursorExtractor(lastItem);\n }\n }\n\n // Check if there are more pages\n this.hasMore = response.meta?.has_more_after ?? false;\n }\n}\n\n/**\n * Create a paginated iterator.\n */\nexport function paginate<T>(\n fetcher: PageFetcher<T>,\n cursorExtractor?: CursorExtractor<T>\n): PaginatedIterator<T> {\n return new PaginatedIterator(fetcher, cursorExtractor);\n}\n","/**\n * Base resource class for API resources.\n */\n\nimport { Transport } from '../transport.js';\nimport { PaginatedIterator, paginate, PageFetcher, CursorExtractor } from '../pagination.js';\n\n/**\n * Base class for API resources.\n */\nexport abstract class BaseResource {\n protected readonly transport: Transport;\n\n constructor(transport: Transport) {\n this.transport = transport;\n }\n\n /**\n * Create a paginated iterator for a list endpoint.\n *\n * `inspectMeta` is called with each page's raw `meta` before the page is\n * yielded, for endpoints whose meta says something the caller must act on.\n * Throw from it to fail the page.\n */\n protected paginate<T>(\n path: string,\n params?: Record<string, unknown>,\n cursorExtractor?: CursorExtractor<T>,\n inspectMeta?: (meta: Record<string, unknown> | undefined) => void\n ): PaginatedIterator<T> {\n const fetcher: PageFetcher<T> = async (cursor?: string) => {\n const query: Record<string, string | number | boolean | undefined> = {};\n\n // Add pagination params\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n query[key] = value as string | number | boolean;\n }\n }\n }\n\n if (cursor) {\n query.starting_after = cursor;\n }\n\n const response = await this.transport.request<\n | {\n data: T[];\n meta?: { has_more_after?: boolean };\n }\n | T[]\n >({\n method: 'GET',\n path,\n query,\n });\n\n // Not every list endpoint returns the `{data, meta}` envelope: a few\n // answer with a BARE ARRAY (GET /mandates and\n // GET /wallets/{id}/signer-groups today). Reading `.data` off those\n // yields undefined, which the old code turned into an empty page —\n // so the iterator finished immediately and the caller saw zero\n // results with no error, for records that plainly exist. Treat an\n // array as one complete page: there is no cursor to follow, so\n // `meta` is absent and `has_more_after` correctly reads false.\n if (Array.isArray(response)) {\n inspectMeta?.(undefined);\n return { data: response, meta: undefined };\n }\n\n inspectMeta?.(response.meta as Record<string, unknown> | undefined);\n\n return {\n data: response.data ?? [],\n meta: response.meta,\n };\n };\n\n return paginate(fetcher, cursorExtractor);\n }\n}\n","/**\n * Customers resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n BulkImportSumsubTokensRequest,\n BulkImportSumsubTokensResponse,\n Customer,\n CustomerCapabilities,\n CustomerCreateRequest,\n CustomerCreateResponse,\n CustomerListParams,\n CustomerPage,\n CustomerReEngagementResponse,\n ImportPersonaTokensRequest,\n ImportPersonaTokensResponse,\n PersonaImportJob,\n PersonaImportJobListParams,\n PersonaImportJobParams,\n PersonaImportJobsPage,\n RequestOptions,\n SubClientSummary,\n UpdateCustomerSubClientRequest,\n WithdrawApplicationRequest,\n} from '../types.js';\n\n/**\n * Customers API resource.\n */\nexport class CustomersResource extends BaseResource {\n /**\n * Create a new customer.\n *\n * Creates a customer record and initiates KYB onboarding.\n * Returns a URL where the customer can complete verification.\n *\n * @param data - Customer creation data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Created customer with KYB onboarding URL\n *\n * @example\n * ```typescript\n * const customer = await client.customers.create({\n * name: 'Acme Corp',\n * customerType: 'business',\n * externalId: 'your-internal-id',\n * });\n *\n * // With custom idempotency key\n * const customer = await client.customers.create(\n * { name: 'Acme Corp', customerType: 'business' },\n * { idempotencyKey: 'create-acme-corp-001' }\n * );\n * console.log(customer.applicationUrl); // KYB onboarding URL\n *\n * // Designate as a sub-client at creation (ENG-2454).\n * // `is_sub_client` can only be set here — a regular customer cannot\n * // be promoted afterwards. Cannot be combined with `sub_client_id`.\n * const subClient = await client.customers.create({\n * name: 'Partner Corp',\n * customer_type: 'business',\n * is_sub_client: true,\n * });\n * ```\n */\n async create(\n data: CustomerCreateRequest,\n options?: RequestOptions\n ): Promise<CustomerCreateResponse> {\n return this.transport.request<CustomerCreateResponse>({\n method: 'POST',\n path: '/customers',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List all customers.\n *\n * Returns a paginated async iterator over customer records.\n *\n * @param params - Optional filter and pagination parameters\n * @returns Async iterator of customers\n *\n * @example\n * ```typescript\n * // Iterate through all customers\n * for await (const customer of client.customers.list()) {\n * console.log(customer.name);\n * }\n *\n * // With filters\n * const active = client.customers.list({ kyb_status: 'active' });\n *\n * // Several statuses at once — one comma-separated string, not an array\n * const needsAttention = client.customers.list({\n * status: 'info_requested,frozen',\n * });\n *\n * // Collect all to array\n * const all = await client.customers.list().toArray();\n * ```\n */\n list(params?: CustomerListParams): PaginatedIterator<Customer> {\n return this.paginate<Customer>('/customers', params);\n }\n\n /**\n * One page of customers, with the per-status counts.\n *\n * {@link list} iterates rows and drops the envelope, so `status_counts` —\n * the counts a dashboard's status header renders — is unreachable through\n * it. This returns the raw page instead: same filters, one request, no\n * iteration.\n *\n * The counts are computed under the same filters but IGNORING the `status`\n * selection, so every chip keeps its count while one of them is the active\n * filter.\n *\n * @param params - The same filters {@link list} accepts\n * @returns One page: rows, pagination meta, and `status_counts`\n *\n * @example\n * ```typescript\n * const page = await client.customers.listPage({ limit: 25 });\n * console.log(page.status_counts?.info_requested ?? 0);\n * for (const customer of page.data) {\n * console.log(customer.name, customer.status);\n * }\n * ```\n */\n async listPage(params?: CustomerListParams): Promise<CustomerPage> {\n const page = await this.transport.request<CustomerPage>({\n method: 'GET',\n path: '/customers',\n query: params as Record<string, string | number | boolean | undefined> | undefined,\n });\n return { ...page, data: page.data ?? [] };\n }\n\n /**\n * Get a customer by ID.\n *\n * @param customerId - Customer ID (KSUID)\n * @returns Customer record\n *\n * @example\n * ```typescript\n * const customer = await client.customers.get('cust_abc123');\n * console.log(customer.kybStatus);\n * ```\n */\n async get(customerId: string): Promise<Customer> {\n return this.transport.request<Customer>({\n method: 'GET',\n path: `/customers/${customerId}`,\n });\n }\n\n /**\n * Delete a customer record.\n *\n * Soft-deletes the customer. Blocked with a 409 if the customer still has\n * associated accounts, or is referenced as a sub-client by another customer.\n *\n * @param customerId - Customer ID (KSUID)\n *\n * @example\n * ```typescript\n * await client.customers.delete('cust_abc123');\n * ```\n */\n async delete(customerId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/customers/${customerId}`,\n });\n }\n\n /**\n * List a customer's capabilities and what is still needed to unlock each.\n *\n * Returns the customer's rails (e.g. `international_wire`) with a status and\n * the OUTSTANDING requirements — terms to accept, documents to upload — that\n * gate them. Partner-agnostic: requirements are keyed by an opaque terms id\n * or document type, never a provider or partner name.\n *\n * @param customerId - Customer ID (KSUID)\n * @returns The customer's capabilities and their outstanding requirements\n *\n * @example\n * ```typescript\n * const { capabilities } = await client.customers.getCapabilities(customerId);\n * for (const cap of capabilities) {\n * if (cap.status !== 'action_required') continue;\n * for (const req of cap.requirements) {\n * console.log(`${cap.capability}: ${req.title} → ${req.url}`);\n * }\n * }\n * ```\n */\n async getCapabilities(customerId: string): Promise<CustomerCapabilities> {\n return this.transport.request<CustomerCapabilities>({\n method: 'GET',\n path: `/customers/${customerId}/capabilities`,\n });\n }\n\n /**\n * Mint a fresh application link for re-engaging an APPROVED customer.\n *\n * Issues a new onboarding token for an existing approved customer's\n * application and returns the rebuilt `application_url` — use it when the\n * original token has expired and the customer needs to come back through\n * the hosted flow (e.g. to accept outstanding partner disclosures).\n *\n * @param customerId - Customer ID (KSUID)\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The rebuilt application URL\n *\n * @example\n * ```typescript\n * const { application_url } = await client.customers.reEngage(customerId);\n * ```\n */\n async reEngage(\n customerId: string,\n options?: RequestOptions\n ): Promise<CustomerReEngagementResponse> {\n return this.transport.request<CustomerReEngagementResponse>({\n method: 'POST',\n path: `/customers/${customerId}/re-engagement`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Withdraw a customer's onboarding application.\n *\n * Closes the application when the customer will not or cannot continue —\n * for example after a request for information they chose not to answer.\n *\n * Withdrawal is FINAL. The application and its entities are recorded as\n * withdrawn, the customer's `status` becomes `withdrawn`, and onboarding\n * that customer again requires a new application. An application that\n * already has a decision returns a 409.\n *\n * Emits `customer.application.withdrawn`.\n *\n * @param customerId - Customer ID (KSUID)\n * @param applicationId - The customer's onboarding application ID\n * @param data - Optional `reason`, recorded for audit and shown to reviewers\n * @param options - Request options (e.g., custom idempotency key)\n *\n * @example\n * ```typescript\n * await client.customers.withdrawApplication(customerId, applicationId, {\n * reason: 'Customer opted not to proceed',\n * });\n * ```\n */\n async withdrawApplication(\n customerId: string,\n applicationId: string,\n data: WithdrawApplicationRequest = {},\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'POST',\n path: `/customers/${customerId}/applications/${applicationId}/withdraw`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n // The platform answers a bare 200 with no body.\n noContent: true,\n });\n }\n\n /**\n * Update the sub-client association for a customer.\n *\n * Associates or disassociates a customer with a sub-client.\n * Set `sub_client_id` to associate, or set it to `null` to disassociate.\n *\n * @deprecated The sub-client association can only be set when a customer is\n * created (`is_sub_client` / `sub_client_id` on `create`) and can no longer\n * be changed afterwards — this endpoint now returns 400.\n *\n * @param customerId - Customer ID (KSUID)\n * @param data - Sub-client association data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Updated customer record\n *\n * @example\n * ```typescript\n * // Associate customer with a sub-client\n * const customer = await client.customers.updateSubClient('cust_abc123', {\n * sub_client_id: 'cust_sub456',\n * });\n *\n * // Disassociate customer from sub-client\n * const customer = await client.customers.updateSubClient('cust_abc123', {\n * sub_client_id: null,\n * });\n * ```\n */\n async updateSubClient(\n customerId: string,\n data: UpdateCustomerSubClientRequest,\n options?: RequestOptions\n ): Promise<Customer> {\n return this.transport.request<Customer>({\n method: 'PATCH',\n path: `/customers/${customerId}/sub-client`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a summary of all sub-clients and their associated customer counts.\n *\n * @returns Array of sub-client summaries\n *\n * @example\n * ```typescript\n * const summaries = await client.customers.getSubClientSummary();\n * for (const summary of summaries) {\n * console.log(`${summary.sub_client_name}: ${summary.customer_count} customers`);\n * }\n * ```\n */\n async getSubClientSummary(): Promise<SubClientSummary[]> {\n const response = await this.transport.request<{ data: SubClientSummary[] }>({\n method: 'GET',\n path: '/customers/sub-client-summary',\n });\n return response.data;\n }\n\n /**\n * Bulk-import customers from Sumsub share tokens.\n *\n * Exchanges one or more Sumsub share tokens for Dakota customers + applications.\n * The response surfaces per-token results — individual tokens can fail while\n * others succeed.\n *\n * @param data - Bulk-import request containing the share tokens to redeem\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Bulk-import summary with per-token results\n *\n * @example\n * ```typescript\n * const result = await client.customers.bulkImportFromSumsubTokens({\n * tokens: ['_act-sbx-jwt-...', '_act-sbx-jwt-...'],\n * });\n * console.log(`Imported ${result.succeeded}/${result.total}`);\n * for (const r of result.results ?? []) {\n * if (!r.success) console.error(r.name, r.error);\n * }\n * ```\n */\n async bulkImportFromSumsubTokens(\n data: BulkImportSumsubTokensRequest,\n options?: RequestOptions\n ): Promise<BulkImportSumsubTokensResponse> {\n return this.transport.request<BulkImportSumsubTokensResponse>({\n method: 'POST',\n path: '/customers/bulk-import-sumsub-tokens',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Import customers from Persona Connect share tokens (`cnst_...`).\n *\n * Unlike the Sumsub import, Persona redemption is asynchronous on Persona's\n * side, so this returns a JOB immediately (HTTP 202). Poll\n * `getPersonaImportJob` for per-token results. Up to 5,000 tokens per\n * request — split larger migrations into multiple batches.\n *\n * Tokens are validated and de-duplicated up front, and a skipped token\n * never blocks an accepted one. A `skipped` entry is about the token STRING\n * (malformed, duplicated in the batch, or already imported) — it is never a\n * compliance decision about a person or application.\n *\n * @param data - The share tokens to import\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The queued job, with any tokens that could not be enqueued\n *\n * @example\n * ```typescript\n * const job = await client.customers.importPersonaTokens({\n * tokens: ['cnst_ABC123def456', 'cnst_GHI789jkl012'],\n * });\n * console.log(`${job.accepted}/${job.total} queued as ${job.job_id}`);\n * ```\n */\n async importPersonaTokens(\n data: ImportPersonaTokensRequest,\n options?: RequestOptions\n ): Promise<ImportPersonaTokensResponse> {\n return this.transport.request<ImportPersonaTokensResponse>({\n method: 'POST',\n path: '/customers/import-persona-tokens',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List this client's Persona share-token import jobs, newest first.\n *\n * This endpoint pages on its own cursor (`starting_after` + `has_more`), not\n * the standard list envelope, so it returns a single page rather than an\n * async iterator.\n *\n * @param params - Optional `limit` and `starting_after` job-id cursor\n * @returns One page of job summaries plus a `has_more` flag\n *\n * @example\n * ```typescript\n * const { jobs, has_more } = await client.customers.listPersonaImportJobs({ limit: 20 });\n * ```\n */\n async listPersonaImportJobs(params?: PersonaImportJobListParams): Promise<PersonaImportJobsPage> {\n return this.transport.request<PersonaImportJobsPage>({\n method: 'GET',\n path: '/customers/persona-import-jobs',\n query: { ...params },\n });\n }\n\n /**\n * Get a Persona import job's status and its per-token results.\n *\n * Result rows page on a row-index cursor: pass the last row's `index` as\n * `results_after_index` while `has_more_results` is true.\n *\n * @param jobId - Import job ID (`pij_...`)\n * @param params - Optional `results_limit` (1-500) and `results_after_index`\n * @returns Job status, row counts, and one page of result rows\n *\n * @example\n * ```typescript\n * let after: number | undefined;\n * do {\n * const job = await client.customers.getPersonaImportJob(jobId, {\n * results_after_index: after,\n * });\n * for (const row of job.results ?? []) {\n * if (row.state === 'failed') console.error(row.token, row.error);\n * after = row.index;\n * }\n * if (!job.has_more_results) break;\n * } while (true);\n * ```\n */\n async getPersonaImportJob(\n jobId: string,\n params?: PersonaImportJobParams\n ): Promise<PersonaImportJob> {\n return this.transport.request<PersonaImportJob>({\n method: 'GET',\n path: `/customers/persona-import-jobs/${jobId}`,\n query: { ...params },\n });\n }\n}\n","/**\n * Recipients resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Recipient,\n RecipientRequest,\n RecipientUpdateRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Recipients API resource.\n */\nexport class RecipientsResource extends BaseResource {\n /**\n * Create a new recipient for a customer.\n *\n * Recipients represent entities that can receive payments.\n *\n * @param customerId - Customer ID\n * @param data - Recipient creation data\n * @returns Created recipient\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.create(customerId, {\n * name: 'Treasury Account',\n * });\n * ```\n */\n async create(\n customerId: string,\n data: RecipientRequest,\n options?: RequestOptions\n ): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'POST',\n path: `/customers/${customerId}/recipients`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List recipients for a customer.\n *\n * @param customerId - Customer ID\n * @param params - Pagination parameters\n * @returns Async iterator of recipients\n *\n * @example\n * ```typescript\n * for await (const recipient of client.recipients.list(customerId)) {\n * console.log(recipient.name);\n * }\n * ```\n */\n list(customerId: string, params?: ListParams): PaginatedIterator<Recipient> {\n return this.paginate<Recipient>(`/customers/${customerId}/recipients`, params);\n }\n\n /**\n * Get a recipient by ID.\n *\n * @param recipientId - Recipient ID\n * @returns Recipient record\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.get(recipientId);\n * ```\n */\n async get(recipientId: string): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'GET',\n path: `/recipients/${recipientId}`,\n });\n }\n\n /**\n * Update a recipient.\n *\n * @param recipientId - Recipient ID\n * @param data - Update data\n * @returns Updated recipient\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.update(recipientId, {\n * name: 'Updated Name',\n * });\n * ```\n */\n async update(\n recipientId: string,\n data: RecipientUpdateRequest,\n options?: RequestOptions\n ): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'PUT',\n path: `/recipients/${recipientId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a recipient.\n *\n * @param recipientId - Recipient ID\n *\n * @example\n * ```typescript\n * await client.recipients.delete(recipientId);\n * ```\n */\n async delete(recipientId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/recipients/${recipientId}`,\n });\n }\n}\n","/**\n * Destinations resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Destination,\n DestinationCreateResponse,\n DestinationListParams,\n DestinationRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Destinations API resource.\n */\nexport class DestinationsResource extends BaseResource {\n /**\n * Create a new destination for a recipient.\n *\n * Destinations can be bank accounts (fiat_us / fiat_iban) or crypto\n * wallets (crypto).\n *\n * The platform returns just `{ id }` here (per `IDResponse`), not the\n * full destination object. Call `destinations.list(recipientId)` if\n * you need the rest of the fields.\n *\n * @param recipientId - Recipient ID\n * @param data - Destination creation data\n * @returns `{ id }` of the newly-created destination\n *\n * @example\n * ```typescript\n * // Crypto destination (for on-ramp)\n * const cryptoDest = await client.destinations.create(recipientId, {\n * destination_type: 'crypto',\n * name: 'Treasury USDC',\n * crypto_address: '0x742d35Cc6634C0532925a3b844Bc9e7595f...',\n * network_id: 'ethereum-mainnet',\n * });\n * // → cryptoDest.id\n *\n * // Fiat US destination (for off-ramp)\n * const bankDest = await client.destinations.create(recipientId, {\n * destination_type: 'fiat_us',\n * name: 'Acme Chase Checking',\n * bank_name: 'JPMorgan Chase',\n * account_holder_name: 'Acme Corp',\n * account_number: '000123456789',\n * aba_routing_number: '021000021',\n * account_type: 'checking',\n * });\n * // → bankDest.id\n * ```\n */\n async create(\n recipientId: string,\n data: DestinationRequest,\n options?: RequestOptions\n ): Promise<DestinationCreateResponse> {\n return this.transport.request<DestinationCreateResponse>({\n method: 'POST',\n path: `/recipients/${recipientId}/destinations`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List destinations for a recipient.\n *\n * @param recipientId - Recipient ID\n * @param params - Pagination parameters\n * @returns Async iterator of destinations\n *\n * @example\n * ```typescript\n * for await (const dest of client.destinations.list(recipientId)) {\n * console.log(dest);\n * }\n * ```\n */\n list(recipientId: string, params?: DestinationListParams): PaginatedIterator<Destination> {\n return this.paginate<Destination>(\n `/recipients/${recipientId}/destinations`,\n params,\n (item) => item.destination_id\n );\n }\n\n /**\n * Delete a destination.\n *\n * @param recipientId - Recipient ID\n * @param destinationId - Destination ID\n *\n * @example\n * ```typescript\n * await client.destinations.delete(recipientId, destinationId);\n * ```\n */\n async delete(recipientId: string, destinationId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/recipients/${recipientId}/destinations/${destinationId}`,\n });\n }\n}\n","/**\n * Accounts resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Account,\n AccountCreateRequest,\n AccountUpdateRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/** Account list parameters */\nexport interface AccountListParams extends ListParams {\n /** Account type filter. Required by the API. */\n account_type: 'onramp' | 'offramp' | 'swap';\n customer_id?: string;\n source_network_id?: string;\n destination_network_id?: string;\n destination_asset?: string;\n crypto_destination_id?: string;\n fiat_destination_id?: string;\n}\n\n/**\n * Accounts API resource.\n */\nexport class AccountsResource extends BaseResource {\n /**\n * Create a new account.\n *\n * Accounts define the flow of funds:\n * - **onramp**: USD → crypto (customer sends USD, receives stablecoin)\n * - **offramp**: crypto → USD (customer sends stablecoin, receives USD)\n * - **swap**: crypto → crypto (stablecoin conversion)\n *\n * @param data - Account creation data\n * @returns Created account\n *\n * @example\n * ```typescript\n * // Create an off-ramp account (crypto → USD)\n * const offramp = await client.accounts.create({\n * account_type: 'offramp',\n * customer_id: customerId,\n * fiat_destination_id: bankDestinationId,\n * asset: 'USDC',\n * network_id: 'ethereum-mainnet',\n * rail: 'ach',\n * capabilities: ['ach'],\n * });\n * // Returns: { crypto_address: '0x...' } - customer sends USDC here\n *\n * // Create an on-ramp account (USD → crypto)\n * const onramp = await client.accounts.create({\n * account_type: 'onramp',\n * customer_id: customerId,\n * crypto_destination_id: cryptoDestinationId,\n * asset: 'USDC',\n * network_id: 'ethereum-mainnet',\n * rail: 'ach',\n * capabilities: ['ach'],\n * });\n * // Returns: { bank_account: { bank_name, aba_routing_number, account_number } } - customer sends USD here\n * ```\n *\n * @remarks\n * `max_transactions` caps how many transactions the account may ever\n * create — `1` makes it a one-off. Know what reaching the cap does before\n * you set one: further deposits are **refused, not returned**. The funds\n * still arrive and are then held pending manual intervention, with nothing\n * converted, nothing forwarded, and no transaction on the account for\n * them. Stop sending to the deposit details once the cap is reached.\n */\n async create(data: AccountCreateRequest, options?: RequestOptions): Promise<Account> {\n return this.transport.request<Account>({\n method: 'POST',\n path: '/accounts',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List accounts.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of accounts\n *\n * @example\n * ```typescript\n * // List all accounts\n * for await (const account of client.accounts.list()) {\n * console.log(account);\n * }\n *\n * // Filter by customer\n * const customerAccounts = client.accounts.list({ customer_id: customerId });\n * ```\n */\n list(params?: AccountListParams): PaginatedIterator<Account> {\n return this.paginate<Account>('/accounts', params);\n }\n\n /**\n * Get an account by ID.\n *\n * @param accountId - Account ID\n * @returns Account record\n *\n * @example\n * ```typescript\n * const account = await client.accounts.get(accountId);\n * ```\n */\n async get(accountId: string): Promise<Account> {\n return this.transport.request<Account>({\n method: 'GET',\n path: `/accounts/${accountId}`,\n });\n }\n\n /**\n * Update an account.\n *\n * @param accountId - Account ID\n * @param data - Update data\n * @returns Updated account\n *\n * Only the developer fee can be updated, and setting one kind replaces the\n * other. `developer_fee_fixed` is a decimal string in units of the asset\n * deposited (at most 2 decimals, greater than 0); it applies to future\n * deposits only.\n *\n * @example\n * ```typescript\n * const account = await client.accounts.update(accountId, {\n * account_type: 'onramp',\n * developer_fee_fixed: '10.00',\n * });\n * console.log(account.minimum_deposit); // '10.01'\n * ```\n */\n async update(\n accountId: string,\n data: AccountUpdateRequest,\n options?: RequestOptions\n ): Promise<Account> {\n return this.transport.request<Account>({\n method: 'PATCH',\n path: `/accounts/${accountId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete an account.\n *\n * @param accountId - Account ID\n *\n * @example\n * ```typescript\n * await client.accounts.delete(accountId);\n * ```\n */\n async delete(accountId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/accounts/${accountId}`,\n });\n }\n}\n","/**\n * Transactions resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport { APIError } from '../errors.js';\nimport type {\n OneOffTransaction,\n OneOffTransactionRequest,\n AutoTransaction,\n AutoTransactionListParams,\n TransactionListParams,\n TransactionResourceType,\n WalletTransaction,\n RequestOptions,\n} from '../types.js';\n\n/**\n * The row shape `GET /transactions` yields for a given set of filters.\n *\n * The family decides the shape, so the filters decide the element type: name\n * `wallet` or `auto_account` and you get that family's rows, anything else is\n * the `one_off` family this endpoint defaults to.\n */\nexport type TransactionRowFor<P extends TransactionListParams | undefined> = P extends {\n transaction_type: 'wallet';\n}\n ? WalletTransaction\n : P extends { transaction_type: 'auto_account' }\n ? AutoTransaction\n : OneOffTransaction;\n\n/**\n * Transactions API resource.\n */\nexport class TransactionsResource extends BaseResource {\n /**\n * Create a one-off transaction.\n *\n * One-off transactions allow single transfers without setting up accounts.\n *\n * @param data - Transaction creation data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Created transaction\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.create({\n * customer_id: customerId,\n * amount: '1000.00',\n * source_asset: 'USDC',\n * source_network_id: 'ethereum-mainnet',\n * destination_id: destinationId,\n * destination_asset: 'USD',\n * destination_payment_rail: 'ach',\n * payment_reference: 'Invoice #12345',\n * });\n *\n * // With custom idempotency key\n * const tx = await client.transactions.create(\n * { customer_id: customerId, amount: '1000.00', ... },\n * { idempotencyKey: 'invoice-12345-payment' }\n * );\n *\n * console.log(tx.crypto_address); // Send USDC here\n * console.log(tx.status); // Transaction status\n * ```\n */\n async create(\n data: OneOffTransactionRequest,\n options?: RequestOptions\n ): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'POST',\n path: '/transactions',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List transactions.\n *\n * `GET /transactions` serves three resource families from one path, and the\n * family decides the row shape — so the family you ask for decides what this\n * iterator yields:\n *\n * | `transaction_type` | Yields |\n * |--------------------|--------|\n * | omitted or `'one_off'` | {@link OneOffTransaction} |\n * | `'wallet'` | {@link WalletTransaction} |\n * | `'auto_account'` | {@link AutoTransaction} (requires `customer_id`) |\n *\n * **The family is always named on the wire.** Left to the server, it is\n * INFERRED from the other filters, and `customer_id` on its own infers\n * `auto_account` — so `list({ customer_id })` would return that customer's\n * auto-account transactions while this method's type promised one-off ones.\n * Those rows parse into `OneOffTransaction` with missing fields rather than\n * failing, so nothing surfaced the substitution. Omitting the family here\n * therefore sends `transaction_type=one_off` rather than leaving it open.\n *\n * The family the server reports back (`meta.transaction_type`) is checked\n * against the one requested, and a mismatch throws instead of yielding rows\n * of the wrong shape.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator over the requested family\n *\n * @example\n * ```typescript\n * // One-off transactions (the default family)\n * for await (const tx of client.transactions.list()) {\n * console.log(tx.id, tx.status);\n * }\n *\n * // This customer's ONE-OFF transactions\n * const completed = client.transactions.list({\n * customer_id: customerId,\n * status: 'completed',\n * });\n *\n * // This customer's AUTO-ACCOUNT transactions — a different family,\n * // and a different row shape\n * for await (const tx of client.transactions.list({\n * transaction_type: 'auto_account',\n * customer_id: customerId,\n * })) {\n * console.log(tx.id);\n * }\n *\n * // Wallet transactions\n * const sent = client.transactions.list({\n * transaction_type: 'wallet',\n * wallet_id: walletId,\n * direction: 'out',\n * });\n * ```\n */\n list<P extends TransactionListParams | undefined = undefined>(\n params?: P\n ): PaginatedIterator<TransactionRowFor<P>> {\n // Name the family rather than letting the server infer one. See the doc\n // comment: an inferred family is how `{ customer_id }` came back as\n // auto-account rows typed as one-off ones.\n const requested: TransactionResourceType = params?.transaction_type ?? 'one_off';\n\n return this.paginate<TransactionRowFor<P>>(\n '/transactions',\n { ...params, transaction_type: requested },\n undefined,\n (meta) => assertFamily(meta, requested)\n );\n }\n\n /**\n * Get a transaction by ID.\n *\n * @param transactionId - Transaction ID\n * @returns Transaction record\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.get(transactionId);\n * console.log(tx.status);\n * ```\n */\n async get(transactionId: string): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'GET',\n path: `/transactions/${transactionId}`,\n });\n }\n\n /**\n * Cancel a transaction.\n *\n * Only pending transactions can be cancelled.\n *\n * @param transactionId - Transaction ID\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Cancelled transaction\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.cancel(transactionId);\n * console.log(tx.status); // 'cancelled'\n * ```\n */\n async cancel(transactionId: string, options?: RequestOptions): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'POST',\n path: `/transactions/${transactionId}/cancellations`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n\n/**\n * Fail a page whose family is not the one asked for.\n *\n * A POSITIVE mismatch only. An absent `transaction_type` means the response\n * made no claim about its family — older servers and the bare-array list\n * shapes do not send one — and treating silence as a mismatch would turn a\n * backstop into a new way for a working call to fail.\n */\nfunction assertFamily(\n meta: Record<string, unknown> | undefined,\n requested: TransactionResourceType\n): void {\n const served = meta?.transaction_type;\n if (typeof served !== 'string' || served === requested) return;\n\n throw new APIError(\n 200,\n 'transaction_family_mismatch',\n `Asked for ${requested} transactions but the server listed ${served}. ` +\n 'The rows in this page are not the shape this iterator yields, so they ' +\n 'are not returned.',\n { details: { requested, served } }\n );\n}\n\n/**\n * Auto Transactions API resource.\n */\nexport class AutoTransactionsResource extends BaseResource {\n /**\n * List auto transactions.\n *\n * `statuses` and `types` take a comma-separated string, not an array, and\n * `start_date` / `end_date` are Unix epoch SECONDS rather than the ISO\n * strings the other list endpoints take.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of auto transactions\n *\n * @example\n * ```typescript\n * const recent = client.autoTransactions.list({\n * auto_account_id: accountId,\n * statuses: 'pending,processing',\n * start_date: Math.floor(Date.now() / 1000) - 86_400,\n * sort_dir: 'desc',\n * });\n * ```\n */\n list(params?: AutoTransactionListParams): PaginatedIterator<AutoTransaction> {\n return this.paginate<AutoTransaction>('/auto-transactions', params);\n }\n\n /**\n * Get an auto transaction by ID.\n *\n * @param transactionId - Auto transaction ID\n * @returns Auto transaction record\n */\n async get(transactionId: string): Promise<AutoTransaction> {\n return this.transport.request<AutoTransaction>({\n method: 'GET',\n path: `/auto-transactions/${transactionId}`,\n });\n }\n}\n","/**\n * Wallets resource.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n Wallet,\n WalletCreateRequest,\n WalletBalances,\n WalletTransactionRequest,\n WalletTransaction,\n AttachedPolicy,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Wallets API resource.\n */\nexport class WalletsResource extends BaseResource {\n /**\n * Create a new wallet.\n *\n * Creates a non-custodial multi-sig wallet for a customer.\n *\n * @param data - Wallet creation data\n * @returns Created wallet\n *\n * @example\n * ```typescript\n * const wallet = await client.wallets.create({\n * customer_id: customerId,\n * family: 'evm',\n * name: 'Treasury Wallet',\n * });\n * console.log(wallet.address);\n * ```\n */\n async create(data: WalletCreateRequest, options?: RequestOptions): Promise<Wallet> {\n return this.transport.request<Wallet>({\n method: 'POST',\n path: '/wallets',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a single wallet by ID.\n *\n * @param walletId - Wallet ID\n * @returns Wallet record (includes `customer_name` and `created_at`)\n *\n * @example\n * ```typescript\n * const wallet = await client.wallets.get(walletId);\n * console.log(wallet.address, wallet.customer_name);\n * ```\n */\n async get(walletId: string): Promise<Wallet> {\n return this.transport.request<Wallet>({\n method: 'GET',\n path: `/wallets/${walletId}`,\n });\n }\n\n /**\n * Get policies attached to a wallet.\n *\n * Returns slim references (id + name) for the policies currently attached to the wallet.\n *\n * @param walletId - Wallet ID\n * @returns Array of attached policies\n *\n * @example\n * ```typescript\n * const policies = await client.wallets.getPolicies(walletId);\n * for (const policy of policies) {\n * console.log(policy.id, policy.name);\n * }\n * ```\n */\n async getPolicies(walletId: string): Promise<AttachedPolicy[]> {\n return this.transport.request<AttachedPolicy[]>({\n method: 'GET',\n path: `/wallets/${walletId}/policies`,\n });\n }\n\n /**\n * Get wallet balances.\n *\n * Returns the platform's full `WalletBalances` response: the wallet id,\n * its on-chain address, every per-asset balance, and a pre-computed\n * `total_amount_usd` across all assets. The previous return shape\n * (`WalletBalance[]`) silently dropped `address` and `total_amount_usd`,\n * forcing callers to do a second `wallets.get()` and sum the balances\n * by hand. This is a small breaking change with a one-line migration\n * (`balances` → `balances.balances`); the prior shape had been broken\n * since 1.3.x anyway.\n *\n * @param walletId - Wallet ID\n * @returns `{ wallet_id, address, balances, total_amount_usd }`\n *\n * @example\n * ```typescript\n * const { address, total_amount_usd, balances } =\n * await client.wallets.getBalances(walletId);\n * console.log(`${address} → $${total_amount_usd}`);\n * for (const b of balances) {\n * console.log(b.asset.id, b.amount_usd);\n * }\n * ```\n */\n async getBalances(walletId: string): Promise<WalletBalances> {\n // /wallets/{id}/balances returns the WalletBalances object directly\n // ({ wallet_id, address, balances, total_amount_usd }), not the\n // paginated { data, meta } envelope. The 1.3.x impl read\n // response.data here and silently returned undefined; the 1.4.x /\n // 1.5.x impl returned just the balances array, dropping the wrapper\n // fields. Now we return what the platform actually sends.\n return this.transport.request<WalletBalances>({\n method: 'GET',\n path: `/wallets/${walletId}/balances`,\n });\n }\n\n /**\n * Send a transaction from a wallet.\n *\n * The platform expects an **endorsed request** envelope —\n * `{ signatures, intent }` — at this endpoint. Build the\n * `SendTransactionIntent`, canonicalize it per RFC 8785 (JCS), sign\n * with the wallet's signer-group ECDSA P-256 key, base64-encode the\n * DER signature, then post the envelope.\n *\n * @param walletId - Wallet ID\n * @param data - Endorsed wallet transaction request: `{ signatures, intent }`\n * @returns Created transaction\n *\n * @example\n * ```typescript\n * import canonicalize from 'canonicalize';\n * import { createSign, createPrivateKey, randomUUID } from 'node:crypto';\n *\n * const intent = {\n * wallet_id: walletId,\n * caip2: 'eip155:1', // 11155111 for sepolia\n * operation: {\n * kind: 'transfer',\n * from: wallet.address,\n * to: '0x...',\n * amount: '100.00',\n * asset_id: 'USDC',\n * },\n * idempotency_key: randomUUID(),\n * };\n * const canonical = canonicalize(intent)!;\n * const sig = createSign('SHA256').update(canonical).sign({\n * key: createPrivateKey({ key: privateKeyDer, format: 'der', type: 'pkcs8' }),\n * dsaEncoding: 'der',\n * });\n * const tx = await client.wallets.createTransaction(walletId, {\n * signatures: [sig.toString('base64')],\n * intent,\n * });\n * ```\n *\n * @see https://docs.dakota.xyz/documentation/signing-guide\n */\n async createTransaction(\n walletId: string,\n data: WalletTransactionRequest,\n options?: RequestOptions\n ): Promise<WalletTransaction> {\n return this.transport.request<WalletTransaction>({\n method: 'POST',\n path: `/wallets/${walletId}/transactions`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Events resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type { Event, EventListParams } from '../types.js';\n\n/**\n * Events API resource.\n */\nexport class EventsResource extends BaseResource {\n /**\n * List events.\n *\n * Events track all platform activity and can be used for audit trails.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of events\n *\n * @example\n * ```typescript\n * for await (const event of client.events.list()) {\n * console.log(event.type, event.data);\n * }\n *\n * // Filter by event type\n * const customerEvents = client.events.list({\n * event_type: 'customer.created',\n * });\n * ```\n */\n list(params?: EventListParams): PaginatedIterator<Event> {\n return this.paginate<Event>('/events', params);\n }\n}\n","/**\n * Applications resource (Onboarding/KYB).\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Application,\n ApplicationDocumentUploadRequest,\n ApplicationGetParams,\n ApplicationDocumentUploadUrlRequest,\n ApplicationSubmissionRequest,\n AssociatedIndividual,\n AssociatedIndividualRequest,\n AttestationSubmitRequest,\n BusinessApplicationCreateRequest,\n BusinessDetailsResponse,\n DocumentUploadResponse,\n DocumentUploadUrlResponse,\n EDDRequest,\n EDDWithApplicationID,\n IndividualDetailsResponse,\n IndividualDocumentUploadRequest,\n IndividualDocumentUploadUrlRequest,\n IndividualRequest,\n LegalAcceptanceContext,\n ListParams,\n RequestOptions,\n UploadedDocumentMetadata,\n} from '../types.js';\n\n/** Parameters for listing application documents */\nexport interface DocumentListParams extends ListParams {\n category?: 'business' | 'identity' | 'edd';\n document_type?: string;\n}\n\n/**\n * Applications API resource for KYB onboarding.\n */\nexport class ApplicationsResource extends BaseResource {\n /**\n * List applications.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of applications\n */\n list(params?: ListParams): PaginatedIterator<Application> {\n return this.paginate<Application>('/applications', params);\n }\n\n /**\n * Get an application by ID.\n *\n * `include` inlines extra sections — a comma-separated list of `entities`,\n * `validation`, `edd`, `attestations`, or `all`. Each adds weight, and\n * `'all'` carries the full KYB record including every associated\n * individual's date of birth, nationality and email, so ask for what the\n * page renders.\n *\n * To render an accept-agreements page, use {@link getLegalAcceptance}\n * instead: it returns exactly that page's inputs and none of the personal\n * data.\n *\n * @param applicationId - Application ID\n * @param params - Optional `{ include }`\n * @returns Application record\n *\n * @example\n * ```typescript\n * const app = await client.applications.get(applicationId, {\n * include: 'entities,validation',\n * });\n * ```\n */\n async get(applicationId: string, params?: ApplicationGetParams): Promise<Application> {\n return this.transport.request<Application>({\n method: 'GET',\n path: `/applications/${applicationId}`,\n query: { ...params },\n });\n }\n\n /**\n * Submit an application for review.\n *\n * @param applicationId - Application ID\n * @param data - Submission data\n * @returns Submitted application\n */\n async submit(\n applicationId: string,\n data?: ApplicationSubmissionRequest,\n options?: RequestOptions\n ): Promise<Application> {\n return this.transport.request<Application>({\n method: 'POST',\n path: `/applications/${applicationId}/submissions`,\n body: data ?? {},\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Business Details\n // ==========================================================================\n\n /**\n * Update business details for an application.\n *\n * Uses PUT (full replace) per the OpenAPI spec.\n *\n * @param applicationId - Application ID\n * @param data - Business details (full BusinessApplicationCreateRequest)\n * @returns Updated business details with application context\n */\n async updateBusinessDetails(\n applicationId: string,\n data: BusinessApplicationCreateRequest,\n options?: RequestOptions\n ): Promise<BusinessDetailsResponse> {\n return this.transport.request<BusinessDetailsResponse>({\n method: 'PUT',\n path: `/applications/${applicationId}/business-details`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Individual Details (non-business applications)\n // ==========================================================================\n\n /**\n * Update individual details for a non-business application.\n *\n * Uses PUT (full replace) per the OpenAPI spec. Only callable when the\n * application status is 'pending'.\n *\n * @param applicationId - Application ID\n * @param data - Individual details (full IndividualRequest)\n * @returns Updated individual details with application context\n */\n async updateIndividualDetails(\n applicationId: string,\n data: IndividualRequest,\n options?: RequestOptions\n ): Promise<IndividualDetailsResponse> {\n return this.transport.request<IndividualDetailsResponse>({\n method: 'PUT',\n path: `/applications/${applicationId}/individual-details`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Associated Individuals\n // ==========================================================================\n\n /**\n * Add an associated individual to an application.\n *\n * @param applicationId - Application ID\n * @param data - Individual data\n * @returns Created individual\n */\n async addIndividual(\n applicationId: string,\n data: AssociatedIndividualRequest,\n options?: RequestOptions\n ): Promise<AssociatedIndividual> {\n return this.transport.request<AssociatedIndividual>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Update an associated individual.\n *\n * Uses PUT (full replace) per the OpenAPI spec.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Full individual data (replaces existing)\n * @returns Updated individual\n */\n async updateIndividual(\n applicationId: string,\n individualId: string,\n data: AssociatedIndividualRequest,\n options?: RequestOptions\n ): Promise<AssociatedIndividual> {\n return this.transport.request<AssociatedIndividual>({\n method: 'PUT',\n path: `/applications/${applicationId}/associated-individuals/${individualId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete an associated individual.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n */\n async deleteIndividual(applicationId: string, individualId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/applications/${applicationId}/associated-individuals/${individualId}`,\n });\n }\n\n // ==========================================================================\n // Attestations\n // ==========================================================================\n\n /**\n * What this application still needs to accept, and who may accept it.\n *\n * Exactly what an accept-agreements page renders, and deliberately nothing\n * more. `get(applicationId)` would answer with the full KYB record — the\n * business entity, and every associated individual's date of birth,\n * nationality and email — none of which that page displays. The link that\n * reaches this endpoint is EMAILED and travels in a URL query string, so its\n * credential is scoped to this call and the attestation submission, and\n * cannot read the application.\n *\n * Authenticates with an Application Token (`X-Application-Token`), including\n * the narrow legal-acceptance token a terms refusal issues.\n *\n * The documents come back as identity only. Fetch the text to display with\n * `client.legal.get(key)`, then pass the `version` you displayed back as\n * `legal_document_version` on {@link submitAttestation}.\n *\n * @param applicationId - Application ID\n * @returns Outstanding agreements, prior acceptances, and permitted attestors\n *\n * @example\n * ```typescript\n * const ctx = await client.applications.getLegalAcceptance(applicationId);\n *\n * for (const doc of ctx.outstanding_documents) {\n * const text = await client.legal.get(doc.key, doc.version);\n * render(text.content);\n * }\n *\n * // A business may have several control persons; an individual application\n * // has exactly one permissible attestor, so there is nobody to pick.\n * const attestor =\n * ctx.application_type === 'individual' ? ctx.attestors[0] : await pick(ctx.attestors);\n * ```\n */\n async getLegalAcceptance(applicationId: string): Promise<LegalAcceptanceContext> {\n return this.transport.request<LegalAcceptanceContext>({\n method: 'GET',\n path: `/applications/${applicationId}/legal-acceptance`,\n });\n }\n\n /**\n * Submit an attestation for an application.\n *\n * Additionally supplying `disclosure_id` (a terms key the provider\n * declared, e.g. `partner_disclosures`) and `disclosure_version` records the\n * attestation as a PARTNER DISCLOSURE acknowledgment instead of a standard\n * onboarding one: acceptance is stamped `customer_online`, the\n * partner-onboarding substatus advances, and an already-approved\n * application is reprovisioned. The API stays partner-agnostic — callers\n * supply a terms key and version, never a partner name. Get the outstanding\n * ones from `customers.getCapabilities(customerId)`.\n *\n * @param applicationId - Application ID\n * @param data - Attestation data (type, timestamp, applicant_id), plus\n * `disclosure_id` + `disclosure_version` to accept a partner disclosure\n */\n async submitAttestation(\n applicationId: string,\n data: AttestationSubmitRequest,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'POST',\n path: `/applications/${applicationId}/attestations`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Enhanced Due Diligence (EDD)\n // ==========================================================================\n\n /**\n * Get the EDD record for an application.\n *\n * @param applicationId - Application ID\n * @returns EDD record with application context\n */\n async getEDD(applicationId: string): Promise<EDDWithApplicationID> {\n return this.transport.request<EDDWithApplicationID>({\n method: 'GET',\n path: `/applications/${applicationId}/edd`,\n });\n }\n\n /**\n * Create or update the EDD record for an application.\n *\n * This endpoint is idempotent (uses PUT).\n *\n * @param applicationId - Application ID\n * @param data - EDD data\n * @returns Updated EDD record with application context\n */\n async createOrUpdateEDD(\n applicationId: string,\n data: EDDRequest,\n options?: RequestOptions\n ): Promise<EDDWithApplicationID> {\n return this.transport.request<EDDWithApplicationID>({\n method: 'PUT',\n path: `/applications/${applicationId}/edd`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Application Documents\n // ==========================================================================\n\n /**\n * Upload an application document using base64-encoded content.\n *\n * For files larger than 20MB, use {@link getDocumentUploadUrl} and upload\n * directly to cloud storage, then call {@link verifyDocument}.\n *\n * @param applicationId - Application ID\n * @param data - Document data including base64 content\n * @returns Document upload response with document_id\n */\n async createDocument(\n applicationId: string,\n data: ApplicationDocumentUploadRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/documents`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List documents for an application.\n *\n * Supports filtering by category and document type.\n *\n * @param applicationId - Application ID\n * @param params - Pagination and filter parameters\n * @returns Paginated iterator of document metadata\n */\n listDocuments(\n applicationId: string,\n params?: DocumentListParams\n ): PaginatedIterator<UploadedDocumentMetadata> {\n return this.paginate<UploadedDocumentMetadata>(\n `/applications/${applicationId}/documents`,\n params\n );\n }\n\n /**\n * Download/get a document by ID.\n *\n * @param applicationId - Application ID\n * @param documentId - Document ID\n * @returns Document content (binary)\n */\n async getDocument(applicationId: string, documentId: string): Promise<unknown> {\n return this.transport.request<unknown>({\n method: 'GET',\n path: `/applications/${applicationId}/documents/${documentId}`,\n });\n }\n\n /**\n * Delete a document from a pending application.\n *\n * Only documents from applications in 'pending' status can be deleted.\n *\n * @param applicationId - Application ID\n * @param documentId - Document ID\n */\n async deleteDocument(applicationId: string, documentId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/applications/${applicationId}/documents/${documentId}`,\n });\n }\n\n /**\n * Verify a document uploaded via presigned URL.\n *\n * After uploading a file to the presigned URL from {@link getDocumentUploadUrl},\n * call this endpoint to register and verify the upload.\n *\n * @param applicationId - Application ID\n * @param documentId - The upload_id from the presigned URL response\n * @returns Document upload response with document_id\n */\n async verifyDocument(\n applicationId: string,\n documentId: string,\n _data?: Record<string, unknown>,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/documents/${documentId}/verifications`,\n body: _data ?? {},\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a presigned upload URL for an application document.\n *\n * Use this for files larger than 20MB. Upload the file directly to the\n * returned URL, then call {@link verifyDocument} to register it.\n *\n * @param applicationId - Application ID\n * @param data - Document metadata\n * @returns Upload URL and upload ID\n */\n async getDocumentUploadUrl(\n applicationId: string,\n data: ApplicationDocumentUploadUrlRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadUrlResponse> {\n return this.transport.request<DocumentUploadUrlResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/document-uploads`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Individual Documents\n // ==========================================================================\n\n /**\n * Upload a document for an associated individual using base64-encoded content.\n *\n * Supports identity documents (passport, driver's license, residence permit)\n * and EDD documents (bank statement, etc.). For files larger than 10MB, use\n * {@link getIndividualDocumentUploadUrl} instead.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Document data including base64 content\n * @returns Document upload response with document_id\n */\n async uploadIndividualDocument(\n applicationId: string,\n individualId: string,\n data: IndividualDocumentUploadRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals/${individualId}/documents`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a presigned upload URL for an individual document.\n *\n * Use this for files larger than 10MB. Upload the file directly to the\n * returned URL.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Document metadata\n * @returns Upload URL and upload ID\n */\n async getIndividualDocumentUploadUrl(\n applicationId: string,\n individualId: string,\n data: IndividualDocumentUploadUrlRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadUrlResponse> {\n return this.transport.request<DocumentUploadUrlResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals/${individualId}/document-uploads`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Policies resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Policy,\n PolicyCreateRequest,\n PolicyRule,\n PolicyRuleCreateRequest,\n AttachedWallet,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Policies API resource.\n */\nexport class PoliciesResource extends BaseResource {\n /**\n * Create a new policy.\n *\n * @param data - Policy creation data\n * @returns Created policy\n */\n async create(data: PolicyCreateRequest, options?: RequestOptions): Promise<Policy> {\n return this.transport.request<Policy>({\n method: 'POST',\n path: '/policies',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List policies.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of policies\n */\n list(params?: ListParams): PaginatedIterator<Policy> {\n return this.paginate<Policy>('/policies', params);\n }\n\n /**\n * Get a policy by ID.\n *\n * @param policyId - Policy ID\n * @returns Policy record\n */\n async get(policyId: string): Promise<Policy> {\n return this.transport.request<Policy>({\n method: 'GET',\n path: `/policies/${policyId}`,\n });\n }\n\n /**\n * Delete a policy.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DeletePolicyIntent`. The server rejects requests without a valid\n * endorsement body.\n *\n * @param policyId - Policy ID\n * @param options - Request options (must include `endorsement`)\n */\n async delete(policyId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Add a rule to a policy.\n *\n * @param policyId - Policy ID\n * @param data - Rule creation data\n * @returns Created rule\n */\n async addRule(\n policyId: string,\n data: PolicyRuleCreateRequest,\n options?: RequestOptions\n ): Promise<PolicyRule> {\n return this.transport.request<PolicyRule>({\n method: 'POST',\n path: `/policies/${policyId}/rules`,\n body: options?.endorsement ?? data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Update a policy rule.\n *\n * @param policyId - Policy ID\n * @param ruleId - Rule ID\n * @param data - Update data\n * @returns Updated rule\n */\n async updateRule(\n policyId: string,\n ruleId: string,\n data: Partial<PolicyRuleCreateRequest>,\n options?: RequestOptions\n ): Promise<PolicyRule> {\n return this.transport.request<PolicyRule>({\n method: 'PATCH',\n path: `/policies/${policyId}/rules/${ruleId}`,\n body: options?.endorsement ?? data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a policy rule.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `RemovePolicyRuleIntent`. The server rejects requests without a valid\n * endorsement body.\n *\n * @param policyId - Policy ID\n * @param ruleId - Rule ID\n * @param options - Request options (must include `endorsement`)\n */\n async deleteRule(policyId: string, ruleId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}/rules/${ruleId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get wallets attached to a policy.\n *\n * Returns slim references (id + name + family) for the wallets the policy is currently attached to.\n *\n * @param policyId - Policy ID\n * @returns Array of attached wallets\n */\n async getWallets(policyId: string): Promise<AttachedWallet[]> {\n return this.transport.request<AttachedWallet[]>({\n method: 'GET',\n path: `/policies/${policyId}/wallets`,\n });\n }\n\n /**\n * Attach a policy to a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `AttachPolicyToWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param policyId - Policy ID\n * @param walletId - Wallet ID\n * @param options - Request options (must include `endorsement`)\n */\n async attachToWallet(\n policyId: string,\n walletId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'PUT',\n path: `/policies/${policyId}/wallets/${walletId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Detach a policy from a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DetachPolicyFromWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param policyId - Policy ID\n * @param walletId - Wallet ID\n * @param options - Request options (must include `endorsement`)\n */\n async detachFromWallet(\n policyId: string,\n walletId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}/wallets/${walletId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Signer Groups resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n SignerGroup,\n SignerGroupCreateRequest,\n SignerGroupGetParams,\n SignerGroupSignerAddRequest,\n Signer,\n SignerCreateRequest,\n AttachedWallet,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Signer Groups API resource.\n */\nexport class SignerGroupsResource extends BaseResource {\n /**\n * Create a new signer group.\n *\n * @param data - Signer group creation data\n * @returns Created signer group\n */\n async create(data: SignerGroupCreateRequest, options?: RequestOptions): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'POST',\n path: '/signer-groups',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List signer groups.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of signer groups\n */\n list(params?: ListParams): PaginatedIterator<SignerGroup> {\n return this.paginate<SignerGroup>('/signer-groups', params);\n }\n\n /**\n * Get a signer group by ID.\n *\n * Pass `{ include_removed: true }` to also get a `removed_members` array of\n * signers that were removed from this group, each carrying its `removed_at`\n * timestamp. Defaults to active members only.\n *\n * @param signerGroupId - Signer group ID\n * @param params - Optional `{ include_removed }`\n * @returns Signer group record\n *\n * @example\n * ```typescript\n * const group = await client.signerGroups.get(groupId, { include_removed: true });\n * for (const s of group.removed_members ?? []) {\n * console.log(s.name, 'removed at', s.removed_at);\n * }\n * ```\n */\n async get(signerGroupId: string, params?: SignerGroupGetParams): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'GET',\n path: `/signer-groups/${signerGroupId}`,\n query: { ...params },\n });\n }\n\n /**\n * Add an existing signer's public key to a group.\n *\n * The endpoint takes `{ member_key }` — the base64 PKIX (SPKI) public\n * key of an existing signer resource — not a fresh signer definition.\n * Returns the updated group (with the new member included).\n *\n * @param signerGroupId - Signer group ID\n * @param data - `{ member_key }` (the signer's base64 PKIX public key)\n * @returns The updated signer group\n */\n async addSigner(\n signerGroupId: string,\n data: SignerGroupSignerAddRequest,\n options?: RequestOptions\n ): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'POST',\n path: `/signer-groups/${signerGroupId}/signers`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Remove a signer from a group.\n *\n * @param signerGroupId - Signer group ID\n * @param signerId - The signer's KSUID `signer_id` — NOT its public key.\n * (The standalone `client.signers.delete()` takes the public key instead.)\n * @param options - Optional request options (e.g. an explicit idempotency\n * key — the platform requires one on this DELETE)\n */\n async removeSigner(\n signerGroupId: string,\n signerId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/signer-groups/${signerGroupId}/signers/${signerId}`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get wallets attached to a signer group.\n *\n * Returns slim references (id + name + family) for the wallets the signer group is currently attached to.\n *\n * @param signerGroupId - Signer group ID\n * @returns Array of attached wallets\n */\n async getWallets(signerGroupId: string): Promise<AttachedWallet[]> {\n return this.transport.request<AttachedWallet[]>({\n method: 'GET',\n path: `/signer-groups/${signerGroupId}/wallets`,\n });\n }\n\n /**\n * Attach a signer group to a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `AttachGroupToWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param walletId - Wallet ID\n * @param signerGroupId - Signer group ID\n * @param options - Request options (must include `endorsement`)\n */\n async attachToWallet(\n walletId: string,\n signerGroupId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'PUT',\n path: `/wallets/${walletId}/signer-groups/${signerGroupId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Detach a signer group from a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DetachGroupFromWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param walletId - Wallet ID\n * @param signerGroupId - Signer group ID\n * @param options - Request options (must include `endorsement`)\n */\n async detachFromWallet(\n walletId: string,\n signerGroupId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/wallets/${walletId}/signer-groups/${signerGroupId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List signer groups attached to a wallet.\n *\n * @param walletId - Wallet ID\n * @param params - Pagination parameters\n * @returns Async iterator of signer groups\n */\n listForWallet(walletId: string, params?: ListParams): PaginatedIterator<SignerGroup> {\n return this.paginate<SignerGroup>(`/wallets/${walletId}/signer-groups`, params);\n }\n}\n\n/**\n * Signers API resource.\n */\nexport class SignersResource extends BaseResource {\n /**\n * Create a new signer.\n *\n * @param data - Signer creation data (name, public_key, key_type)\n * @param options - Request options\n * @returns Created signer\n */\n async create(data: SignerCreateRequest, options?: RequestOptions): Promise<Signer> {\n return this.transport.request<Signer>({\n method: 'POST',\n path: '/signers',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a signer by public key.\n *\n * Soft-deletes all signers with the given public key.\n *\n * @param publicKey - Signer public key\n */\n async delete(publicKey: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/signers/${publicKey}`,\n });\n }\n}\n","/**\n * API Keys resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n ApiKey,\n ApiKeyResponse,\n ApiKeyCreateRequest,\n CreateApiKeyForClientRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * API Keys API resource.\n */\nexport class ApiKeysResource extends BaseResource {\n /**\n * Create a new API key.\n *\n * @param data - API key creation data\n * @returns Created API key (includes secret, only shown once)\n */\n async create(data: ApiKeyCreateRequest, options?: RequestOptions): Promise<ApiKeyResponse> {\n return this.transport.request<ApiKeyResponse>({\n method: 'POST',\n path: '/api-keys',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List API keys.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of API keys\n */\n list(params?: ListParams): PaginatedIterator<ApiKey> {\n return this.paginate<ApiKey>('/api-keys', params);\n }\n\n /**\n * Delete an API key.\n *\n * @param apiKeyId - API key ID\n */\n async delete(apiKeyId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/api-keys/${apiKeyId}`,\n });\n }\n\n /**\n * Delete all API keys.\n *\n * Intended for incident response only.\n */\n async deleteAll(): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: '/api-keys',\n });\n }\n\n /**\n * Create an API key for a specific client (admin only).\n *\n * Requires admin access token.\n *\n * @param data - Request data containing `client_id`\n * @param options - Request options\n * @returns Created API key response (includes key, only shown once)\n */\n async createForClient(\n data: CreateApiKeyForClientRequest,\n options?: RequestOptions\n ): Promise<ApiKeyResponse> {\n return this.transport.request<ApiKeyResponse>({\n method: 'POST',\n path: '/api-keys/admin',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Users resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n User,\n UserCreateRequest,\n UserUpdateRequest,\n UserListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Users API resource.\n */\nexport class UsersResource extends BaseResource {\n /**\n * Create a new user.\n *\n * @param data - User creation data\n * @returns Created user\n */\n async create(data: UserCreateRequest, options?: RequestOptions): Promise<User> {\n return this.transport.request<User>({\n method: 'POST',\n path: '/users',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List users.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of users\n */\n list(params?: UserListParams): PaginatedIterator<User> {\n return this.paginate<User>('/users', params);\n }\n\n /**\n * Update a user.\n *\n * @param userId - User ID\n * @param data - Update data (first_name, last_name, role)\n */\n async update(userId: string, data: UserUpdateRequest, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'PATCH',\n path: `/users/${userId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a user.\n *\n * @param userId - User ID\n */\n async delete(userId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/users/${userId}`,\n });\n }\n}\n","/**\n * Webhooks resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n WebhookTarget,\n WebhookTargetCreateRequest,\n WebhookTargetUpdateRequest,\n WebhookEvent,\n WebhookReplayResponse,\n WebhookHistoryListParams,\n WebhookHistoryResponse,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Webhooks API resource.\n */\nexport class WebhooksResource extends BaseResource {\n /**\n * Create a new webhook target.\n *\n * @param data - Webhook target creation data\n * @returns Created webhook target\n */\n async createTarget(\n data: WebhookTargetCreateRequest,\n options?: RequestOptions\n ): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'POST',\n path: '/webhooks/targets',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List webhook targets.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of webhook targets\n */\n listTargets(params?: ListParams): PaginatedIterator<WebhookTarget> {\n return this.paginate<WebhookTarget>('/webhooks/targets', params);\n }\n\n /**\n * Get a webhook target by ID.\n *\n * @param targetId - Webhook target ID\n * @returns Webhook target record\n */\n async getTarget(targetId: string): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'GET',\n path: `/webhooks/targets/${targetId}`,\n });\n }\n\n /**\n * Update a webhook target.\n *\n * @param targetId - Webhook target ID\n * @param data - Update data\n * @returns Updated webhook target\n */\n async updateTarget(\n targetId: string,\n data: WebhookTargetUpdateRequest,\n options?: RequestOptions\n ): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'PATCH',\n path: `/webhooks/targets/${targetId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a webhook target.\n *\n * @param targetId - Webhook target ID\n */\n async deleteTarget(targetId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/webhooks/targets/${targetId}`,\n });\n }\n\n /**\n * List webhook delivery history.\n *\n * Note: This endpoint uses cursor-based pagination (`cursor`/`has_more`) instead\n * of the standard `starting_after`/`has_more_after` format. Because of this,\n * it returns the raw response rather than a `PaginatedIterator`. Use the `cursor`\n * field from the response to fetch subsequent pages.\n *\n * @param params - Webhook history query parameters\n * @returns Webhook history response with `data`, `has_more`, and `cursor`\n *\n * @example\n * ```typescript\n * let cursor: string | undefined;\n * do {\n * const page = await client.webhooks.listEvents({ limit: 50, cursor });\n * for (const event of page.data) {\n * console.log(event);\n * }\n * cursor = page.cursor ?? undefined;\n * } while (page.has_more);\n * ```\n */\n async listEvents(params?: WebhookHistoryListParams): Promise<WebhookHistoryResponse> {\n const query: Record<string, string | number | boolean | undefined> = {};\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n query[key] = value as string | number | boolean;\n }\n }\n }\n return this.transport.request<WebhookHistoryResponse>({\n method: 'GET',\n path: '/webhooks',\n query,\n });\n }\n\n /**\n * Get a webhook event by ID.\n *\n * @param eventId - Webhook event ID\n * @returns Webhook event record\n */\n async getEvent(eventId: string): Promise<WebhookEvent> {\n return this.transport.request<WebhookEvent>({\n method: 'GET',\n path: `/webhooks/${eventId}`,\n });\n }\n\n /**\n * Replay a webhook event.\n *\n * Re-queues the webhook for delivery to all configured targets.\n *\n * @param eventId - Webhook event ID\n * @param options - Request options\n * @returns Replay response with `webhook_id`, `status`, and `replayed_to_count`\n */\n async replayEvent(eventId: string, options?: RequestOptions): Promise<WebhookReplayResponse> {\n return this.transport.request<WebhookReplayResponse>({\n method: 'POST',\n path: `/webhooks/events/${eventId}/replay`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Info resource for platform capabilities.\n */\n\nimport { BaseResource } from './base.js';\nimport type { Country } from '../types.js';\n\n/**\n * Info API resource for platform capabilities.\n */\nexport class InfoResource extends BaseResource {\n /**\n * Get supported countries.\n *\n * @returns Array of supported countries\n *\n * @example\n * ```typescript\n * const countries = await client.info.getCountries();\n * ```\n */\n async getCountries(): Promise<Country[]> {\n // /capabilities/countries returns Country[] directly, not the\n // paginated { data, meta } envelope. Earlier versions read\n // response.data here and silently returned undefined.\n return this.transport.request<Country[]>({\n method: 'GET',\n path: '/capabilities/countries',\n });\n }\n\n /**\n * Get supported networks.\n *\n * @returns Array of supported networks\n *\n * @example\n * ```typescript\n * const networks = await client.info.getNetworks();\n * for (const network of networks) {\n * console.log(network.id, network.name);\n * }\n * ```\n */\n async getNetworks(): Promise<string[]> {\n // /capabilities/networks returns string[] (network IDs like\n // \"ethereum-mainnet\") directly, not the paginated { data, meta }\n // envelope. Earlier versions typed this as Network[] and read\n // response.data, which silently returned undefined.\n return this.transport.request<string[]>({\n method: 'GET',\n path: '/capabilities/networks',\n });\n }\n}\n","/**\n * Legal documents resource.\n */\n\nimport { BaseResource } from './base.js';\nimport type { LegalDocument } from '../types.js';\n\n/**\n * Legal Documents API resource.\n *\n * The published terms a customer accepts during onboarding. **Unauthenticated**\n * — integrators need these before a customer relationship exists, so the\n * endpoints carry no credential and are safe to call from a signup page.\n */\nexport class LegalResource extends BaseResource {\n /**\n * List the revision of every legal document currently in force.\n *\n * An INDEX, not a bundle: each entry names a document and its in-force\n * revision, without the text. Fetch {@link get} for the one document you\n * are about to display — inlining every document would put the whole corpus\n * on every call.\n *\n * Not safe to cache indefinitely: it names whichever revision is in force\n * NOW, and that changes when a new one is published. A specific\n * `(key, version)` from {@link get} is a different matter — revisions are\n * immutable, so that text can be cached for as long as you like.\n *\n * @returns The in-force revision of each document, without its text\n *\n * @example\n * ```typescript\n * for (const doc of await client.legal.list()) {\n * console.log(doc.key, doc.version, doc.title);\n * }\n * ```\n */\n async list(): Promise<LegalDocument[]> {\n const response = await this.transport.request<{ data: LegalDocument[] }>({\n method: 'GET',\n path: '/legal/documents',\n });\n return response.data ?? [];\n }\n\n /**\n * Get one legal document — the revision in force, or a specific one.\n *\n * Pass the `version` you displayed back as `legal_document_version` when\n * submitting an attestation, so the acceptance record names the exact text\n * the customer saw rather than whichever revision happened to be current\n * when the request arrived.\n *\n * @param documentKey - Document identifier, e.g. `'dakota_tos'`\n * @param version - A specific published revision. Omit for the one in force\n * @returns The requested revision, including its text\n *\n * @example\n * ```typescript\n * const tos = await client.legal.get('dakota_tos');\n * render(tos.content);\n *\n * await client.applications.submitAttestation(applicationId, {\n * attestation_type: 'terms_of_service',\n * legal_document_version: tos.version, // records what they actually saw\n * // ...\n * });\n * ```\n */\n async get(documentKey: string, version?: string): Promise<LegalDocument> {\n return this.transport.request<LegalDocument>({\n method: 'GET',\n path: `/legal/documents/${documentKey}`,\n query: version !== undefined ? { version } : undefined,\n });\n }\n}\n","/**\n * Reserve-management marketing-fee statements resource.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n RDMarketingFeeStatement,\n RDPayoutDestination,\n RDPayoutDestinationRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * RD Marketing Fee API resource.\n *\n * The reserve-management statements for the calling client. The client comes\n * from the session and is never named in a request, so there is no id to pass\n * and no other client's statements to address.\n *\n * A client who has never had a rate gets a **404** from the two statement\n * methods: holding a rate is what being in the programme means, and there is\n * no separate entitlement record to read. The payout-destination methods\n * answer differently — see each: there a 404 means \"nothing registered yet\"\n * and it is 403 that means \"not in the programme\".\n */\nexport class RDMarketingFeeResource extends BaseResource {\n /**\n * The months this client has a statement for, newest first.\n *\n * Runs from the start of their contract to the running month, and the\n * RUNNING month IS included. It cannot be priced yet — the bank's interest\n * posts in the month after it is earned — but the balance is real and\n * accruing, and a client checking mid-month has to be able to see it. Its\n * fee figures come back absent rather than zero.\n *\n * An EMPTY list means the contract is real but no month has started yet.\n * That is different from a 404, which means no contract at all.\n *\n * @returns Statement months as `YYYY-MM-DD` (first day of the month, UTC)\n *\n * @example\n * ```typescript\n * const months = await client.rdMarketingFee.listMonths();\n * if (months.length === 0) {\n * // Contract starts next month or later — \"starting soon\", not an error.\n * }\n * ```\n */\n async listMonths(): Promise<string[]> {\n const response = await this.transport.request<{ months?: string[] }>({\n method: 'GET',\n path: '/rd-marketing-fee/statements',\n });\n return response.months ?? [];\n }\n\n /**\n * One month's statement — one row per calendar day: the date, the RD\n * balance, and that day's fee.\n *\n * The rows are the STORED daily principals, read rather than recomputed, so\n * what the client reads and what Dakota priced cannot drift.\n *\n * Absent is not zero. A balance is absent when the day has not been derived\n * yet and `'0'` when the client genuinely held no RD; fees are absent for\n * every day of a month whose rate has not been derived. Neither unknown is\n * reported as a zero, so render an absent figure as unknown rather than\n * defaulting it.\n *\n * @param month - First day of the month, UTC, as `YYYY-MM-DD`\n * @returns The month's statement, one row per day\n *\n * @example\n * ```typescript\n * const statement = await client.rdMarketingFee.getStatement('2026-08-01');\n * for (const day of statement.daily) {\n * console.log(day.date, day.balance_minor ?? 'not yet derived');\n * }\n * ```\n */\n async getStatement(month: string): Promise<RDMarketingFeeStatement> {\n return this.transport.request<RDMarketingFeeStatement>({\n method: 'GET',\n path: `/rd-marketing-fee/statements/${month}`,\n });\n }\n\n /**\n * The wallet this client's RD marketing fee is sent to.\n *\n * A **404** here is the ordinary state for a client who has not registered\n * one yet — not an error. A **403** means the client is not in the\n * programme at all.\n *\n * @returns The registered destination: always on Base (`eip155:8453`)\n *\n * @example\n * ```typescript\n * try {\n * const dest = await client.rdMarketingFee.getPayoutDestination();\n * console.log(dest.address);\n * } catch (error) {\n * if (error instanceof APIError && error.statusCode === 404) {\n * // Nothing registered yet — prompt for one.\n * }\n * }\n * ```\n */\n async getPayoutDestination(): Promise<RDPayoutDestination> {\n return this.transport.request<RDPayoutDestination>({\n method: 'GET',\n path: '/rd-marketing-fee/payout-destination',\n });\n }\n\n /**\n * Register, or replace, the wallet the RD marketing fee is sent to.\n *\n * RD exists only on Base, so the chain is not a parameter — only an EVM\n * `address`. There is one destination per client, so this REPLACES any\n * existing one. Emits `rd_payout_destination.updated`.\n *\n * This is a SEPARATE registration from the developer-fee payout\n * destination (`client.feePayoutDestination`): the two programmes pay\n * different assets and are set independently.\n *\n * @param data - The EVM address on Base to pay the fee to\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The stored destination\n *\n * @example\n * ```typescript\n * const dest = await client.rdMarketingFee.setPayoutDestination({\n * address: '0x1234567890123456789012345678901234567890',\n * });\n * console.log(dest.chain); // 'eip155:8453'\n * ```\n */\n async setPayoutDestination(\n data: RDPayoutDestinationRequest,\n options?: RequestOptions\n ): Promise<RDPayoutDestination> {\n return this.transport.request<RDPayoutDestination>({\n method: 'PUT',\n path: '/rd-marketing-fee/payout-destination',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Sandbox resource for testing simulations.\n *\n * @remarks\n * These endpoints are only available in the Sandbox environment.\n * In sandbox, Dakota does NOT monitor testnet blockchains - you must\n * use these simulation endpoints to trigger payment events.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n SimulateInboundRequest,\n SimulationResponse,\n SimulateOnboardingRequest,\n SimulateOnboardingResponse,\n AdvanceSimulationRequest,\n AdvanceSimulationResult,\n SimulationInspection,\n SandboxScenario,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Sandbox API resource for testing simulations.\n *\n * These endpoints are only available in the Sandbox environment.\n *\n * @remarks\n * **Important:** In sandbox, Dakota does NOT monitor testnet blockchains.\n * You must use these simulation endpoints to trigger payment events.\n *\n * @example\n * ```typescript\n * // Simulate ACH deposit to on-ramp account\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_inbound',\n * account_id: 'acc_123',\n * amount: '1000.00',\n * currency: 'USD',\n * });\n *\n * // Simulate off-ramp ACH settlement\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_outbound_settled',\n * account_id: 'acc_456',\n * one_off_transaction_id: 'tx_456',\n * amount: '500.00',\n * currency: 'USD',\n * });\n * ```\n */\nexport class SandboxResource extends BaseResource {\n /**\n * Simulate an inbound payment event.\n *\n * Triggers a simulated payment event through the mock banking provider.\n * The required fields depend on the simulation `type`:\n *\n * | Type | Required Fields |\n * |------|-----------------|\n * | `ach_inbound`, `fedwire_inbound`, `swift_inbound`, `fednow_inbound` | `account_id` |\n * | `crypto_inbound` | `wallet_address` |\n * | `*_outbound_*`, `*_reversal` | `account_id` + `one_off_transaction_id` |\n *\n * `swift_inbound` and `fedwire_inbound` behave identically: the rail a\n * deposit books on is derived from the RECEIVING account, so pick the\n * account, not the type, to choose between a SWIFT and a Fedwire deposit.\n *\n * @param data - Simulation request data\n * @returns Simulation response with ID and state\n *\n * @example Simulate ACH deposit to on-ramp\n * ```typescript\n * const result = await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_inbound',\n * account_id: 'acc_123',\n * amount: '1000.00',\n * currency: 'USD',\n * });\n * ```\n *\n * @example Simulate off-ramp ACH settlement\n * ```typescript\n * // After creating a one-off transaction for off-ramp testing\n * const tx = await client.transactions.create({\n * customer_id: 'cust_123',\n * amount: '100.00',\n * source_asset: 'USDC',\n * source_network_id: 'ethereum-sepolia',\n * destination_id: 'dest_456',\n * destination_asset: 'USD',\n * destination_payment_rail: 'ach',\n * });\n *\n * // Simulate the ACH settlement. `account_id` is the offramp account that\n * // funded the transaction.\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_outbound_settled',\n * account_id: 'acc_456',\n * one_off_transaction_id: tx.id,\n * amount: '100.00',\n * currency: 'USD',\n * });\n * ```\n *\n * @example Simulate crypto deposit to wallet\n * ```typescript\n * const result = await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'crypto_inbound',\n * wallet_address: '0x165cd37b4c644c2921454429e7f9358d18a45e14',\n * amount: '500.00',\n * currency: 'USDC',\n * });\n * ```\n */\n async simulateInbound(\n data: SimulateInboundRequest,\n options?: RequestOptions\n ): Promise<SimulationResponse> {\n return this.transport.request<SimulationResponse>({\n method: 'POST',\n path: '/sandbox/simulate/inbound',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Simulate an onboarding state transition.\n *\n * Drives KYB, KYC, or applicant account status through a sandbox transition\n * without waiting for real compliance review.\n *\n * **Important:** Use `kyb_approve` to fully approve any customer type (individual or\n * business). This triggers the complete onboarding flow including endorsement and\n * recipient creation. The `kyc_*` types only update the individual applicant's KYC\n * application status without triggering the full onboarding flow.\n *\n * @param data - Simulation request data\n * @returns Simulation response with previous and new state\n *\n * @example Approve KYB and activate applicant\n * ```typescript\n * // Step 1: Approve the KYB application\n * await client.sandbox.simulateOnboarding({\n * type: 'kyb_approve',\n * applicant_id: customer.application_id,\n * simulation_id: `sim_kyb_${Date.now()}`,\n * });\n *\n * // Step 2: Activate the applicant (triggers provisioning)\n * await client.sandbox.simulateOnboarding({\n * type: 'applicant_activate',\n * applicant_id: customer.application_id,\n * simulation_id: `sim_activate_${Date.now()}`,\n * });\n * ```\n *\n * @example Reject a KYB application\n * ```typescript\n * await client.sandbox.simulateOnboarding({\n * type: 'kyb_reject',\n * applicant_id: applicationId,\n * simulation_id: `sim_${Date.now()}`,\n * reason_code: 'MISSING_DOCUMENTS',\n * });\n * ```\n */\n async simulateOnboarding(\n data: SimulateOnboardingRequest,\n options?: RequestOptions\n ): Promise<SimulateOnboardingResponse> {\n return this.transport.request<SimulateOnboardingResponse>({\n method: 'POST',\n path: '/sandbox/simulate/onboarding',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get detailed simulation status and callback history.\n *\n * Returns the current state and callback delivery history for a sandbox simulation.\n * Use this to debug async flows and see whether callbacks have been delivered.\n *\n * @param simulationId - Simulation ID returned from simulateInbound/simulateOnboarding\n * @returns Full simulation inspection including state and callbacks\n *\n * @example\n * ```typescript\n * const inspection = await client.sandbox.getSimulation('sim_123');\n * console.log('State:', inspection.state);\n * console.log('Callbacks:', inspection.callbacks);\n * ```\n */\n async getSimulation(simulationId: string): Promise<SimulationInspection> {\n return this.transport.request<SimulationInspection>({\n method: 'GET',\n path: `/sandbox/simulations/${simulationId}`,\n });\n }\n\n /**\n * Advance a stateful simulation to the next state.\n *\n * Some scenarios pause and wait for explicit advancement. Use this method\n * to continue a paused simulation with a specific action.\n *\n * @param simulationId - Simulation ID\n * @param data - Action to take (e.g., 'release', 'reject', 'confirm', 'expire')\n * @returns Updated simulation state\n *\n * @example\n * ```typescript\n * const result = await client.sandbox.advanceSimulation('sim_123', {\n * action: 'release',\n * });\n * console.log('New state:', result.new_state);\n * ```\n */\n async advanceSimulation(\n simulationId: string,\n data?: AdvanceSimulationRequest,\n options?: RequestOptions\n ): Promise<AdvanceSimulationResult> {\n return this.transport.request<AdvanceSimulationResult>({\n method: 'POST',\n path: `/sandbox/simulations/${simulationId}/advance`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List available sandbox scenarios.\n *\n * Returns all simulation scenarios supported by the platform.\n * Use these scenario names in the `scenario` field of simulateInbound.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of scenarios\n *\n * @example\n * ```typescript\n * const scenarios = await client.sandbox.listScenarios().toArray();\n * for (const scenario of scenarios) {\n * console.log(`${scenario.name}: ${scenario.description}`);\n * }\n * ```\n */\n listScenarios(params?: ListParams): PaginatedIterator<SandboxScenario> {\n return this.paginate<SandboxScenario>('/sandbox/scenarios', params);\n }\n}\n","/**\n * Self-Serve Credits resource for managing prepaid transfer credits.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n SelfServeCreditsPurchaseRequest,\n SelfServeCreditsPurchaseResponse,\n SelfServeCreditsBalanceResponse,\n SelfServeCreditsLedgerResponse,\n SelfServeCreditsLedgerParams,\n SelfServeCreditsPricingResponse,\n SelfServeCreditTiersResponse,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Self-Serve Credits API resource.\n *\n * Manage prepaid credits for self-serve transfer capacity.\n */\nexport class SelfServeResource extends BaseResource {\n /**\n * Purchase self-serve credits.\n *\n * Creates a Stripe checkout session for purchasing credits at the specified tier.\n *\n * @param data - Purchase request with the tier price\n * @param options - Optional request options (e.g., idempotency key)\n * @returns Response containing the Stripe checkout URL\n *\n * @example\n * ```typescript\n * const { checkout_url } = await client.selfServe.purchaseCredits({\n * tier_price_cents: 10000,\n * });\n * // Redirect user to checkout_url\n * ```\n */\n async purchaseCredits(\n data: SelfServeCreditsPurchaseRequest,\n options?: RequestOptions\n ): Promise<SelfServeCreditsPurchaseResponse> {\n return this.transport.request<SelfServeCreditsPurchaseResponse>({\n method: 'POST',\n path: '/self-serve/credits/purchase',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get current credits balance.\n *\n * @returns The current balance and transfer capacity in cents\n *\n * @example\n * ```typescript\n * const balance = await client.selfServe.getBalance();\n * console.log(`Balance: $${balance.balance_cents / 100}`);\n * console.log(`Transfer capacity: $${balance.transfer_capacity_cents / 100}`);\n * ```\n */\n async getBalance(): Promise<SelfServeCreditsBalanceResponse> {\n return this.transport.request<SelfServeCreditsBalanceResponse>({\n method: 'GET',\n path: '/self-serve/credits/balance',\n });\n }\n\n /**\n * List credits ledger entries.\n *\n * Returns a cursor-paginated list of ledger entries (purchases, deductions, refunds).\n *\n * @param params - Optional query parameters for filtering and pagination\n * @returns Ledger response with entries and has_more flag\n *\n * @example\n * ```typescript\n * // Get recent ledger entries\n * const ledger = await client.selfServe.listLedger();\n * for (const entry of ledger.entries) {\n * console.log(entry.entry_type, entry.amount_cents, entry.description);\n * }\n *\n * // Filter by type with pagination\n * const purchases = await client.selfServe.listLedger({\n * type: 'purchase',\n * limit: 50,\n * });\n *\n * // Paging: carry BOTH halves of the cursor. Entries written in one\n * // transaction share a created_at, so a page boundary inside such a\n * // group drops rows when only `cursor` is sent.\n * const last = purchases.entries[purchases.entries.length - 1];\n * const next = await client.selfServe.listLedger({\n * type: 'purchase',\n * limit: 50,\n * cursor: last.created_at,\n * cursor_id: last.id,\n * });\n * ```\n */\n async listLedger(params?: SelfServeCreditsLedgerParams): Promise<SelfServeCreditsLedgerResponse> {\n const query: Record<string, string | number | boolean | undefined> = {};\n if (params?.cursor !== undefined) query.cursor = params.cursor;\n // Ignored by the server without `cursor`, and the ordering it completes is\n // what stops a page boundary splitting one transaction's entries.\n if (params?.cursor_id !== undefined) query.cursor_id = params.cursor_id;\n if (params?.limit !== undefined) query.limit = params.limit;\n if (params?.type !== undefined) query.type = params.type;\n\n return this.transport.request<SelfServeCreditsLedgerResponse>({\n method: 'GET',\n path: '/self-serve/credits/ledger',\n query,\n });\n }\n\n /**\n * List available credit tiers.\n *\n * Returns all available pricing tiers for purchasing credits.\n *\n * @returns Response containing the list of available tiers\n *\n * @example\n * ```typescript\n * const { tiers } = await client.selfServe.listTiers();\n * for (const tier of tiers) {\n * console.log(`$${tier.price_cents / 100} → $${tier.transfer_capacity_cents / 100} capacity`);\n * }\n * ```\n */\n async listTiers(): Promise<SelfServeCreditTiersResponse> {\n return this.transport.request<SelfServeCreditTiersResponse>({\n method: 'GET',\n path: '/self-serve/credits/tiers',\n });\n }\n\n /**\n * Get the self-serve client's pricing config (fee schedule).\n *\n * Returns the caller's current `ClientPricingConfig` — transfer/ACH/wire/SEPA/SWIFT/KYC/KYB\n * fees plus the monthly minimum. Self-serve clients only.\n *\n * @returns The current pricing configuration\n *\n * @example\n * ```typescript\n * const pricing = await client.selfServe.getPricing();\n * console.log(`ACH fee: ${pricing.achFeeCents} cents`);\n * console.log(`Wire fee: ${pricing.wireFeeCents} cents`);\n * ```\n */\n async getPricing(): Promise<SelfServeCreditsPricingResponse> {\n return this.transport.request<SelfServeCreditsPricingResponse>({\n method: 'GET',\n path: '/self-serve/credits/pricing',\n });\n }\n}\n","/**\n * Fee Payout Destination resource.\n *\n * Where Dakota pays your accrued developer fees. Exactly ONE destination\n * exists per organization, and it is crypto-only — a USDC wallet on any\n * supported chain.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n FeePayoutDestination,\n PutFeePayoutDestinationRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Fee Payout Destination API resource.\n */\nexport class FeePayoutDestinationResource extends BaseResource {\n /**\n * Get the destination registered to receive your developer-fee payouts.\n *\n * @returns The registered destination\n *\n * @example\n * ```typescript\n * const dest = await client.feePayoutDestination.get();\n * console.log(dest.chain, dest.wallet_address);\n * ```\n */\n async get(): Promise<FeePayoutDestination> {\n return this.transport.request<FeePayoutDestination>({\n method: 'GET',\n path: '/fee-payout-destination',\n });\n }\n\n /**\n * Register or replace your fee payout destination.\n *\n * There is exactly one destination per organization, so this REPLACES any\n * existing one. Emits `fee_payout_destination.updated`.\n *\n * `chain` is a CAIP-2 chain id (e.g. `eip155:8453`) from the supported\n * networks list — see `client.info.getNetworks()`.\n *\n * @param data - The USDC wallet to pay fees to\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The stored destination\n *\n * @example\n * ```typescript\n * const dest = await client.feePayoutDestination.set({\n * usdc_wallet: {\n * chain: 'eip155:8453',\n * address: '0x1234567890123456789012345678901234567890',\n * },\n * });\n * ```\n */\n async set(\n data: PutFeePayoutDestinationRequest,\n options?: RequestOptions\n ): Promise<FeePayoutDestination> {\n return this.transport.request<FeePayoutDestination>({\n method: 'PUT',\n path: '/fee-payout-destination',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Remove the registered fee payout destination, if one exists.\n *\n * Emits `fee_payout_destination.deleted`.\n *\n * @example\n * ```typescript\n * await client.feePayoutDestination.delete();\n * ```\n */\n async delete(): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: '/fee-payout-destination',\n });\n }\n}\n","/**\n * Payment Agents resource (ALPHA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { AGENTIC_MODEL_TIMEOUT_MS } from '../config.js';\nimport type {\n PaymentAgent,\n PaymentAgentCreateRequest,\n AgenticProposalsProgress,\n AgenticProposalsResult,\n CreateProposalsRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Payment Agents API resource (ALPHA).\n */\nexport class PaymentAgentsResource extends BaseResource {\n /**\n * Create a hosted payment agent.\n *\n * @param data - Payment agent creation data (customer_id, name, hosted)\n * @returns The created payment agent (id, signer_id, signer_public_key, state)\n */\n async create(data: PaymentAgentCreateRequest, options?: RequestOptions): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'POST',\n path: '/payment-agents',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a hosted payment agent.\n *\n * Returns the agent together with the wallets it can currently spend\n * from. `wallet_ids` are DERIVED at query time from the agent signer's\n * live signer-group membership, so they reflect the agent's access\n * right now — not just at creation time.\n *\n * @param paymentAgentId - Payment agent ID\n */\n async get(paymentAgentId: string): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'GET',\n path: `/payment-agents/${paymentAgentId}`,\n });\n }\n\n /**\n * Revoke a hosted payment agent.\n *\n * The agent can no longer be used, and its signing key is destroyed\n * in the isolated signer service (best-effort — the revoked state is\n * authoritative). Idempotent.\n *\n * The response's `signer_group_cleanup` names the signer groups the\n * (now-revoked) agent's signer still belongs to. A revoked signer can't\n * sign, but its group membership lingers — remove it with\n * `client.signerGroups.removeSigner(signer_group_id, signer_id)` to\n * finish de-provisioning.\n *\n * @param paymentAgentId - Payment agent ID\n * @returns The revoked payment agent (state=revoked, signer_group_cleanup?)\n */\n async revoke(paymentAgentId: string, options?: RequestOptions): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'POST',\n path: `/payment-agents/${paymentAgentId}/revoke`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Draft payment proposals from a conversation.\n *\n * Pure cognition, no side effects: turn a customer's natural-language\n * request into reviewable proposals. Stateless — send the whole\n * conversation so far in `messages` on each call. Prefer\n * `AgentConversation` for multi-turn chat; use this directly only for\n * one-shot proposals.\n *\n * SLOW BY NATURE. A turn is a sequence of model calls — read the payees,\n * check balances, draft, revise — so a multi-payee request legitimately\n * runs minutes. It therefore defaults to {@link AGENTIC_MODEL_TIMEOUT_MS}\n * rather than the client's ordinary deadline. Pass `{ timeout }` to\n * change it for one call; an explicit client-wide `timeout` still wins.\n *\n * The result may carry `blockers` ALONGSIDE proposals — they are not\n * alternatives. Branch on `blocker.code`, not on `reply`, and ignore codes\n * you do not recognize.\n *\n * The vocabulary the agent drafts under is the one registered with\n * `client.agenticPolicy.set()`. It is not a property of this request —\n * a policy sent here is ignored, which is why the option to send one is\n * gone.\n *\n * @param paymentAgentId - Payment agent ID\n * @param data - Prompt and/or messages\n * @returns Proposals (at high confidence) and/or a conversational reply\n */\n async createProposals(\n paymentAgentId: string,\n data: CreateProposalsRequest,\n options?: RequestOptions\n ): Promise<AgenticProposalsResult> {\n return this.transport.request<AgenticProposalsResult>({\n method: 'POST',\n path: `/payment-agents/${paymentAgentId}/proposals`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n endpointTimeout: AGENTIC_MODEL_TIMEOUT_MS,\n });\n }\n\n /**\n * Live progress of an in-flight drafting turn.\n *\n * A multi-payee drafting turn legitimately runs minutes (several sequential\n * model calls). While a `createProposals` call is in flight, poll this every\n * few seconds to show the customer what the agent is doing right now.\n *\n * Advisory display only. `active: false` means no turn is currently\n * publishing progress for this agent — idle, just finished, or served by\n * another instance — so fall back to a generic spinner. Never gate any\n * behaviour on this endpoint.\n *\n * The snapshot is coarse and customer-safe: a phase enum, one human\n * sentence, and the model round. Tool counts only — never payee names,\n * amounts, or addresses.\n *\n * @param paymentAgentId - Payment agent ID\n * @returns The current progress snapshot\n *\n * @example\n * ```typescript\n * const pending = client.paymentAgents.createProposals(agentId, { prompt });\n * const poll = setInterval(async () => {\n * const p = await client.paymentAgents.getProposalsProgress(agentId);\n * if (p.active) console.log(p.detail);\n * }, 3000);\n * const result = await pending.finally(() => clearInterval(poll));\n * ```\n */\n async getProposalsProgress(paymentAgentId: string): Promise<AgenticProposalsProgress> {\n return this.transport.request<AgenticProposalsProgress>({\n method: 'GET',\n path: `/payment-agents/${paymentAgentId}/proposals/progress`,\n });\n }\n}\n","/**\n * Instructions resource (ALPHA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n AgenticInstruction,\n AgenticInstructionsResult,\n CreateInstructionsRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Instructions API resource (ALPHA).\n *\n * Each accepted proposal becomes one persisted instruction whose action\n * series is actuated deterministically.\n */\nexport class InstructionsResource extends BaseResource {\n /**\n * Accept proposals — actuate them into persisted instructions.\n *\n * One optional field shapes the actuation:\n *\n * - `developer_fee_defaults` declares your fee PER PAYOUT TYPE —\n * `swap` for a crypto payout, `offramp` for a bank payout — each as\n * a percentage (`developer_fee_bps`) or a flat amount per payment\n * (`developer_fee_fixed`, a decimal string in units of the asset\n * deposited, added on top of the amount), never both. They are\n * independent, so one conversation can charge a swap and stay silent\n * about a bank payout in the same turn. Omit a payout type (or set its\n * `developer_fee_bps` to zero) and it carries no fee: nothing is\n * charged, nothing is added to the amount, and the agent is told\n * nothing about a fee it could mention. Both are\n * DEFAULTS for the auto-accounts this request creates — an action-level\n * `developer_fee_bps` or `developer_fee_fixed` still wins outright.\n *\n * It replaces the deprecated `developer_fee` (`swap_bps` /\n * `offramp_bps`), which the platform still accepts. Send one or the\n * other: both is a 400.\n *\n * The vocabulary the actuation is judged against comes from the policy\n * registered with `client.agenticPolicy.set()` — the same one the drafting\n * turn used, which is the point of registering it rather than sending it.\n *\n * @param data - The payment agent id and the proposals to accept\n * @returns instruction_ids + the mandates the batch drafted (in full\n * wire shape; sign the §8 approval immediately)\n */\n async create(\n data: CreateInstructionsRequest,\n options?: RequestOptions\n ): Promise<AgenticInstructionsResult> {\n return this.transport.request<AgenticInstructionsResult>({\n method: 'POST',\n path: '/instructions',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get an accepted instruction — its action series and the per-action\n * downstream artifacts actuation produced.\n *\n * @param instructionId - Instruction ID\n */\n async get(instructionId: string): Promise<AgenticInstruction> {\n return this.transport.request<AgenticInstruction>({\n method: 'GET',\n path: `/instructions/${instructionId}`,\n });\n }\n}\n","/**\n * Mandates resource (ALPHA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n AmendMandateRequest,\n ApproveMandateRequest,\n CancelMandateRequest,\n CreateMandateRequest,\n Mandate,\n MandateBudget,\n MandateListParams,\n MandateResponse,\n MandateVersion,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Mandates API resource (ALPHA).\n */\nexport class MandatesResource extends BaseResource {\n /**\n * List mandates (newest first), with the EFFECTIVE status — a pending or\n * active mandate past its valid_until reads \"expired\". Filter with\n * customer_id / signer_id / status; omit them all for the full collection.\n *\n * @param params - Optional pagination + filter parameters\n * @returns Async iterator of mandates\n */\n list(params?: MandateListParams): PaginatedIterator<Mandate> {\n return this.paginate<Mandate>('/mandates', params);\n }\n\n /**\n * Get a mandate — the signer it binds, its rule exactly as the customer\n * approves it, validity, and status.\n *\n * @param mandateId - Mandate ID\n */\n async get(mandateId: string): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'GET',\n path: `/mandates/${mandateId}`,\n });\n }\n\n /**\n * Create a mandate directly.\n *\n * Drafts a PENDING mandate from a direct user interaction — no instruction\n * back-link. Exactly one binding form names the signer the mandate binds:\n * `payment_agent_id` (hosted convenience — binds that agent's signer and\n * anchors to the agent's customer), or `signer_id` together with\n * `customer_id` (any of the client's signers, BYO keys included). The rule\n * is the one the customer will approve (via `approve`, a recognized signer\n * other than the bound one, §8).\n *\n * @param data - One binding form + rule + optional validity window\n * @returns The drafted (pending) mandate\n */\n async create(data: CreateMandateRequest, options?: RequestOptions): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'POST',\n path: '/mandates',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Approve a mandate.\n *\n * A recognized signer OTHER than the bound one signs the mandate payload\n * (see `mandateSignPayload` + `MandateSigner`) to activate it; arms its\n * scheduled payments.\n *\n * @param mandateId - Mandate ID\n * @param data - Approver public key (base64 PKIX) + base64 ASN.1 signature\n */\n async approve(\n mandateId: string,\n data: ApproveMandateRequest,\n options?: RequestOptions\n ): Promise<MandateResponse> {\n return this.transport.request<MandateResponse>({\n method: 'POST',\n path: `/mandates/${mandateId}/approve`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Cancel a mandate.\n *\n * Revokes a pending or active mandate. The canceller must be a recognized\n * signer OTHER than the bound one, with a valid signature over the mandate\n * payload — the bound signer can never mutate its own mandate.\n *\n * @param mandateId - Mandate ID\n * @param data - Signer public key (base64 PKIX) + base64 ASN.1 signature\n */\n async cancel(\n mandateId: string,\n data: CancelMandateRequest,\n options?: RequestOptions\n ): Promise<MandateResponse> {\n return this.transport.request<MandateResponse>({\n method: 'POST',\n path: `/mandates/${mandateId}/cancel`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Amend a mandate — append a new signed version of its rule.\n *\n * Carries a changed rule into force with ONE signature and WITHOUT resetting\n * the spend already made in the current window: usage accrues to the\n * MANDATE, so an agent that has spent 9,000 of a 10,000 monthly limit and is\n * amended to 20,000 has 11,000 left, not 20,000.\n *\n * The `rule` is stored and verified VERBATIM — this endpoint does not\n * normalize it. It must already be canonical: `window` present and non-empty\n * (send `'NONE'` for a lifetime window), `targets` as recipient ids rather\n * than payee names, and `asset` uppercase. `target_type`, `window`, `asset`\n * and `network_id` must also match the current version exactly; only the\n * amount fields and `targets` may differ. Anything else is a 400 naming the\n * offending field.\n *\n * Build `signature` from `mandateAmendSignPayload(mandate, version, rule)` —\n * the amend payload commits to the version being created, so a signature for\n * v2 can never be replayed to append v3.\n *\n * @param mandateId - Mandate ID\n * @param data - Amending signer public key + signature + the complete NEW rule\n * @returns The mandate at its new current version\n *\n * @example\n * ```typescript\n * const mandate = await client.mandates.get(mandateId);\n * const nextVersion = (mandate.version ?? 1) + 1;\n * const rule = { ...mandate.rule, max_amount_in_window: '20000' };\n * const payload = mandateAmendSignPayload(mandate, nextVersion, rule);\n *\n * const amended = await client.mandates.amend(mandateId, {\n * signer_public_key: signer.publicKeyBase64(),\n * signature: await signer.sign(payload),\n * rule,\n * });\n * ```\n */\n async amend(\n mandateId: string,\n data: AmendMandateRequest,\n options?: RequestOptions\n ): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'POST',\n path: `/mandates/${mandateId}/amend`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List a mandate's versions, oldest first.\n *\n * The append-only history of every rule that was ever in force under this\n * mandate, and the §8 signer that put each one there. Versions are\n * immutable, so a rule listed here never changes — this is what makes an\n * executed payment's `mandate_version` audit stamp legible.\n *\n * @param mandateId - Mandate ID\n * @returns Every version, oldest first\n */\n async listVersions(mandateId: string): Promise<MandateVersion[]> {\n return this.transport.request<MandateVersion[]>({\n method: 'GET',\n path: `/mandates/${mandateId}/versions`,\n });\n }\n\n /**\n * Get a mandate's remaining budget right now.\n *\n * The mandate's `rule` gives the ceilings; this gives the CONSUMPTION — what\n * has already been spent, what is earmarked by scheduled payments that have\n * not fired yet, and therefore what is left. Read it before scheduling:\n * otherwise an over-budget payment is only discovered when the gate denies\n * it at its due date, days later, with the payee unpaid.\n *\n * Advisory — nothing here reserves budget, and the gate remains the\n * authority at fire time. Three things to honour when reading a line:\n *\n * - An ABSENT `remaining_amount` / `remaining_count` means \"not capped\",\n * never \"nothing left\" — EXCEPT on a `per_target` line with\n * `prior_scope: true`. That line's spend was booked under an earlier\n * version's target scope (before a `target_type` amendment) and no\n * current target claims it: the spend is real and still counts toward\n * the aggregate caps, but no payment can consume the bucket, so absent\n * remaining_* there means NO headroom. Never set on aggregate lines.\n * - A `remaining_amount` of `'?'` means the figure could not be summed and\n * MUST be treated as no headroom (the gate fails closed on the same data).\n *\n * @param mandateId - Mandate ID\n * @returns Per-target and aggregate budget lines, as of a stated instant\n *\n * @example\n * ```typescript\n * const budget = await client.mandates.getBudget(mandateId);\n * for (const line of [...budget.per_target, ...budget.aggregate]) {\n * const headroom = line.prior_scope\n * ? 'none (prior scope)'\n * : (line.remaining_amount ?? 'uncapped');\n * console.log(line.target ?? '(all payees)', line.bucket, headroom);\n * }\n * ```\n */\n async getBudget(mandateId: string): Promise<MandateBudget> {\n return this.transport.request<MandateBudget>({\n method: 'GET',\n path: `/mandates/${mandateId}/budget`,\n });\n }\n}\n","/**\n * Scheduled Payments resource (ALPHA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n CreateScheduledPaymentRequest,\n RequestOptions,\n ScheduledPayment,\n ScheduledPaymentListParams,\n} from '../types.js';\n\n/**\n * Scheduled Payments API resource (ALPHA).\n */\nexport class ScheduledPaymentsResource extends BaseResource {\n /**\n * List scheduled payments (oldest due first).\n *\n * Narrow the collection with the optional customer_id, signer_id,\n * wallet_id, mandate_id, and status filters; omit them all for the full\n * client collection.\n *\n * @param params - Optional pagination + filter parameters\n * @returns Async iterator of scheduled payments\n */\n list(params?: ScheduledPaymentListParams): PaginatedIterator<ScheduledPayment> {\n return this.paginate<ScheduledPayment>('/scheduled-payments', params);\n }\n\n /**\n * Schedule payments directly — bypass the proposal flow.\n *\n * Creates one or more scheduled payments for a signer under an existing\n * active mandate (coverage is matched at fire time, so no new signature\n * is needed here). The schedule is explicit `dates` OR `count` ×\n * `interval_seconds` from `start_at`.\n *\n * @param data - Signer + wallet + destination (or address+network_id) + schedule\n * @returns The rows that were created (one per date)\n */\n async create(\n data: CreateScheduledPaymentRequest,\n options?: RequestOptions\n ): Promise<ScheduledPayment[]> {\n return this.transport.request<ScheduledPayment[]>({\n method: 'POST',\n path: '/scheduled-payments',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Cancel one still-scheduled payment.\n *\n * Finalizes the row as cancelled. No signature is required — schedule rows\n * are bookkeeping, not authorization; the signed grant is the MANDATE,\n * which this does not touch.\n *\n * @param scheduledPaymentId - Scheduled payment ID\n */\n async cancel(scheduledPaymentId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'POST',\n path: `/scheduled-payments/${scheduledPaymentId}/cancel`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Insights resource (BETA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type { ClientInsightReport, ClientInsightsParams, InsightReport } from '../types.js';\n\n/**\n * Insights API resource (BETA).\n *\n * Read-only, advisory reporting over agentic activity — one customer's, or\n * the whole client's book. Nothing here moves money or changes state.\n */\nexport class InsightsResource extends BaseResource {\n /**\n * Get the customer's account insight report.\n *\n * A deterministic, read-only report: a snapshot of typed facts\n * (funding-wallet balances, upcoming totals, open payments, active\n * mandates), observations (`insights`), and advisory recommendations\n * (`suggestions`). Every item carries `evidence` — typed references to\n * the platform objects it was computed from. `kind` is an OPEN set;\n * ignore kinds you do not recognize.\n *\n * @param customerId - Customer ID\n * @returns The customer's insight report\n */\n async get(customerId: string): Promise<InsightReport> {\n return this.transport.request<InsightReport>({\n method: 'GET',\n path: `/customers/${customerId}/insights`,\n });\n }\n\n /**\n * Get the client-level portfolio insight report.\n *\n * The client-scope companion of {@link get}: one deterministic, read-only\n * report over ALL of the caller's customers' agentic activity. Items reuse\n * the customer report's shape, plus `customer_id` (omitted on\n * cross-customer aggregates) and `responsibility` (a grouping label for\n * filtering — not ownership). On top of the items the report carries\n * dashboard-shaped data: KPI `metrics` with previous-window values for\n * trend deltas, daily `series` for charts, and a per-customer roll-up in\n * `customers` sorted worst-first.\n *\n * Every filter is optional and only NARROWS the report; the response shape\n * never changes. The report scans at most 100 customers per request —\n * `snapshot.customers.scanned < total` says it was computed over a prefix\n * of the book, never silently.\n *\n * A 404 means agentic payments are not enabled for the key, or the\n * `customer_id` filter names an unknown customer.\n *\n * @param params - Optional filters and the report window\n * @returns The client's portfolio insight report\n *\n * @example\n * ```typescript\n * const report = await client.insights.getClientReport({\n * severity: 'critical,warn',\n * window_days: 30,\n * });\n * for (const row of report.customers) {\n * if (row.item_counts.critical > 0) console.log(row.customer_id, row.name);\n * }\n * ```\n */\n async getClientReport(params?: ClientInsightsParams): Promise<ClientInsightReport> {\n return this.transport.request<ClientInsightReport>({\n method: 'GET',\n path: '/insights',\n query: { ...params },\n });\n }\n}\n","/**\n * Agentic Client Policy resource (ALPHA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n AgenticClientPolicy,\n RegisteredAgenticClientPolicy,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Agentic Client Policy API resource (ALPHA).\n *\n * The policy is per CLIENT — it belongs to the client behind your API key,\n * never to a key, since API keys are N:1 to clients and a per-key policy\n * would fragment for anyone running one service key per deployment.\n *\n * There is no client id to pass. The route resolves the client from the API\n * key, so you cannot address another client's policy even to be refused.\n */\nexport class AgenticPolicyResource extends BaseResource {\n /**\n * Get the policy registered for the client behind your API key.\n *\n * A 404 here is the DEFAULT, not an error condition: with no registration\n * and no per-request policy the agent drafts on platform defaults, exactly\n * as it did before registration existed.\n *\n * @returns The normalized registered policy + its timestamps\n *\n * @example\n * ```typescript\n * try {\n * const { policy } = await client.agenticPolicy.get();\n * console.log(policy.labels);\n * } catch (e) {\n * if (e instanceof APIError && e.statusCode === 404) {\n * // No registration — platform defaults apply.\n * }\n * }\n * ```\n */\n async get(): Promise<RegisteredAgenticClientPolicy> {\n return this.transport.request<RegisteredAgenticClientPolicy>({\n method: 'GET',\n path: '/agentic-policy',\n });\n }\n\n /**\n * Register — or fully replace — this client's agentic policy.\n *\n * Registration is the ONLY way to set a policy. A policy is a property of\n * the CLIENT, not of a request: carried per request, a drafting turn and\n * the accept that followed it could be judged by different rules. The\n * platform accordingly stopped reading `client_policy` from request bodies,\n * and one sent there is now ignored — silently, since the agent simply\n * narrates in the platform's nouns again (\"destination\", \"mandate\") with no\n * error anywhere. Registering once removes that failure mode.\n *\n * FULL REPLACE, not a merge — the registration IS your declared vocabulary,\n * so an omitted field means you no longer want it, and an empty body (`{}`)\n * clears the registration back to platform defaults.\n *\n * Validated exactly like the per-request copy, so an unknown key, an\n * unsupported value, or a label for an unimplemented concept is a 400 HERE,\n * at registration — not a surprise on a customer's first conversation.\n *\n * The client comes from your API key; there is no id to pass.\n *\n * @param policy - The complete policy (`{}` clears it)\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The normalized stored policy + its timestamps\n *\n * @example\n * ```typescript\n * await client.agenticPolicy.set({\n * payee_model: 'flat',\n * payout_assets: ['USDC', 'USDT'],\n * labels: { limit: 'spending limit', payee: 'recipient', limit_unit: 'USD' },\n * payout_route: 'conversion_account_only',\n * mandate_strategy: 'external_only',\n * });\n * ```\n */\n async set(\n policy: AgenticClientPolicy,\n options?: RequestOptions\n ): Promise<RegisteredAgenticClientPolicy> {\n return this.transport.request<RegisteredAgenticClientPolicy>({\n method: 'PUT',\n path: '/agentic-policy',\n body: policy,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Multi-turn agent chat. The platform's proposals endpoint is STATELESS —\n * it holds no session and must be sent the whole transcript on every turn.\n * `AgentConversation` hides that bookkeeping so a caller just sends user\n * messages and reads the agent's clarifying questions / final proposals.\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport type { DakotaClient } from '../client/client.js';\nimport type {\n AgenticBlocker,\n AgenticProposal,\n AgenticProposalsResult,\n DeveloperFee,\n DeveloperFeeDefaults,\n} from '../client/types.js';\n\n/**\n * MIME types the platform accepts for a document attachment.\n */\nexport type AttachmentMediaType =\n | 'application/pdf'\n | 'image/png'\n | 'image/jpeg'\n | 'image/webp'\n | 'image/gif';\n\n/**\n * An input artifact on a user turn for the agent to read — today a document\n * (a PDF or image, e.g. an invoice to draft a payment from). `data` is the\n * RAW document bytes; the SDK base64-encodes them on the wire.\n */\nexport interface Attachment {\n mediaType: AttachmentMediaType;\n /** raw document bytes (not base64) */\n data: Uint8Array;\n /** optional, for display/audit */\n filename?: string;\n}\n\n/**\n * One turn of an agent conversation.\n */\nexport interface ChatMessage {\n role: 'user' | 'assistant';\n content: string;\n /**\n * Input artifacts attached to this turn for the agent to investigate.\n * Attachments ride only on the turn they are passed; they are NOT\n * persisted in the transcript.\n */\n attachments?: Attachment[];\n}\n\n/**\n * The agent's response to one user message.\n */\nexport interface ConversationTurn {\n /**\n * The agent's conversational text — a clarifying question or a\n * confirmation. May be empty when only proposals are returned.\n */\n reply: string;\n /**\n * The reviewable action series, present once the agent reaches high\n * confidence. Accept it via the instructions flow.\n */\n proposals: AgenticProposal[];\n /** Whether the agent drafted proposals this turn. */\n hasProposals: boolean;\n /**\n * Machine-actionable reasons the turn could not complete — for YOUR\n * application, not the customer. `reply` says the same thing in prose,\n * which software cannot branch on: \"extend the limit to cover Priya\",\n * \"I need her bank details\" and \"that rail is not supported\" all arrive\n * as some text.\n *\n * These ACCOMPANY proposals rather than replacing them, and routinely do.\n * The common case is a payee who does not exist yet: the turn proposes\n * creating them AND reports that the limit will not reach them, because\n * you have to do both, in that order — accept the proposal so the payee\n * has an id, then amend the limit to include it. Never treat proposals\n * and blockers as alternatives.\n *\n * Empty when nothing blocked the turn. Always switch on `code` and ignore\n * codes you do not know; new ones are added over time.\n */\n blockers: AgenticBlocker[];\n /** Whether the turn reported any blocker. */\n hasBlockers: boolean;\n /**\n * The boundary screen's verdict for this turn:\n *\n * - `\"ok\"` — normal payments turn.\n * - `\"warned\"` — off-topic; the customer was warned but may continue.\n * - `\"blocked\"` — the chat is terminated; stop serving it and offer a fresh\n * conversation.\n * - `\"rejected_input\"` — this message was refused WHOLESALE (e.g. more\n * payees than one conversation supports). `reply` explains what to\n * resend; the conversation continues unaffected, and the SDK has already\n * dropped the refused message from the transcript for you.\n *\n * Empty when the platform sent none. Treat it as an OPEN set — new values\n * may be added.\n */\n conversationStatus: string;\n}\n\n/**\n * The boundary screen's verdict for a message refused wholesale. Its contract\n * is that the message must NOT be added to the conversation history — see\n * {@link ConversationTurn.conversationStatus}.\n */\nconst REJECTED_INPUT = 'rejected_input';\n\n/** Options for an {@link AgentConversation}. */\nexport interface AgentConversationOptions {\n /**\n * The customer's IANA timezone (e.g. `'America/Los_Angeles'`).\n *\n * When set, the agent resolves every relative date (\"tomorrow\", \"Friday\")\n * and clock time (\"10 am\") in THIS zone: a date without a time is drafted\n * for 10:00 local, and a time without a date means its next local\n * occurrence. Left unset, times resolve as UTC and the agent says so when a\n * specific clock time matters.\n *\n * The conversation resends it on every turn, since the endpoint is\n * stateless. Note the zone's UTC offset is captured at drafting time, so a\n * DST transition before a far-future fire date shifts it by the DST delta.\n */\n timezone?: string;\n\n /**\n * Deadline (ms) for each turn of this conversation.\n *\n * Turns default to {@link AGENTIC_MODEL_TIMEOUT_MS}, which is sized for a\n * multi-payee drafting turn. Set this when your own turns are longer (a\n * very large payee list) or shorter (you would rather show the customer a\n * failure than keep them waiting).\n *\n * Required if the client was built with an explicit `timeout`: that\n * choice wins over the endpoint default, so a client configured with a\n * short global deadline will cut turns off unless you raise it here.\n */\n timeout?: number;\n\n /**\n * Your default developer fee, declared PER PAYOUT TYPE — `swap` for a\n * crypto payout, `offramp` for a bank one, each as `{ developer_fee_bps }`\n * or a flat `{ developer_fee_fixed: '10.00' }` per payment, never both.\n * The two are independent, so one conversation can charge a swap and stay\n * silent about a bank payout.\n *\n * Set it here as well as on `instructions.create()`, not instead of it.\n * The accept is what CHARGES the fee; declaring it on the drafting turn is\n * what lets the agent MENTION it — omit it and the agent is told nothing\n * about a fee it could name, so the customer approves a summary that never\n * disclosed one and then gets charged it.\n *\n * Resent on every turn, since the endpoint is stateless.\n */\n developerFeeDefaults?: DeveloperFeeDefaults;\n\n /**\n * @deprecated Use {@link developerFeeDefaults}: `swap_bps` is now\n * `swap.developer_fee_bps` and `offramp_bps` is now\n * `offramp.developer_fee_bps`. Still sent as `developer_fee` while the\n * platform accepts it. Set one or the other — the SDK forwards both if\n * both are set, and the platform rejects that with a 400.\n */\n developerFee?: DeveloperFee;\n}\n\n/**\n * A stateful, multi-turn proposals chat with one agent.\n *\n * Keeps the running transcript, appends each user message and the agent's\n * reply, and resends the whole transcript on every {@link send} — so\n * callers never deal with the stateless endpoint's \"send all history each\n * time\" contract.\n *\n * For a stateless backend (one HTTP request per chat message), persist\n * {@link messages} between requests and rebuild with\n * {@link DakotaClient.resumeAgentConversation}.\n */\nexport class AgentConversation {\n private readonly client: DakotaClient;\n private readonly paymentAgentId: string;\n private readonly timezone?: string;\n private readonly timeout?: number;\n private readonly developerFeeDefaults?: DeveloperFeeDefaults;\n private readonly developerFee?: DeveloperFee;\n private history: ChatMessage[] = [];\n\n constructor(\n client: DakotaClient,\n paymentAgentId: string,\n history?: ChatMessage[],\n options?: AgentConversationOptions\n ) {\n this.client = client;\n this.paymentAgentId = paymentAgentId;\n this.timezone = options?.timezone;\n this.timeout = options?.timeout;\n this.developerFeeDefaults = options?.developerFeeDefaults;\n this.developerFee = options?.developerFee;\n if (history && history.length > 0) {\n this.history = history.map(cloneMessage);\n }\n }\n\n /**\n * Adds the user's message to the transcript, asks the agent, records the\n * agent's reply, and returns the turn. When `hasProposals` is true the\n * agent has drafted a reviewable action series; otherwise `reply` holds\n * its next question.\n *\n * On error the optimistic user turn is rolled back, so the caller may\n * retry the same call without duplicating it.\n */\n async send(userMessage: string): Promise<ConversationTurn> {\n return this.sendWithAttachments(userMessage);\n }\n\n /**\n * {@link send} with documents (e.g. an invoice PDF) attached to the user\n * turn for the agent to read and draft payments from. Same turn semantics\n * and rollback-on-error behavior as `send`. Attachments ride only on the\n * turn they are passed; the stateless transcript keeps the agent's text\n * reply, so a follow-up turn relies on that summary rather than re-sending\n * the document.\n */\n async sendWithAttachments(\n userMessage: string,\n attachments?: Attachment[]\n ): Promise<ConversationTurn> {\n const hasAttachments = attachments !== undefined && attachments.length > 0;\n this.history.push({\n role: 'user',\n content: userMessage,\n ...(hasAttachments ? { attachments } : {}),\n });\n\n const messages = this.history.map(serializeMessage);\n\n // Attachments ride only on THIS request: they are serialized into\n // `messages` above, then dropped from the stored transcript so they are\n // neither persisted via messages() / resumeAgentConversation nor\n // re-sent on later turns.\n if (hasAttachments) {\n const last = this.history[this.history.length - 1];\n if (last) {\n delete last.attachments;\n }\n }\n\n let result: AgenticProposalsResult;\n try {\n result = await this.client.paymentAgents.createProposals(\n this.paymentAgentId,\n {\n messages,\n // Resent on EVERY turn — the endpoint is stateless, so a value\n // given once would be forgotten on the next one.\n ...(this.timezone ? { timezone: this.timezone } : {}),\n ...(this.developerFeeDefaults\n ? { developer_fee_defaults: this.developerFeeDefaults }\n : {}),\n ...(this.developerFee ? { developer_fee: this.developerFee } : {}),\n },\n this.timeout !== undefined ? { timeout: this.timeout } : undefined\n );\n } catch (err) {\n // Roll back the optimistic user turn so a retry does not duplicate it.\n this.history.pop();\n throw err;\n }\n\n const turn: ConversationTurn = {\n reply: result.reply ?? '',\n proposals: result.proposals ? [...result.proposals] : [],\n hasProposals: !!result.proposals && result.proposals.length > 0,\n blockers: result.blockers ? [...result.blockers] : [],\n hasBlockers: !!result.blockers && result.blockers.length > 0,\n conversationStatus: result.conversation_status ?? '',\n };\n\n // `rejected_input`: the server refused this message WHOLESALE and told us\n // not to keep it. Roll the optimistic user turn back and record no\n // assistant turn, so the transcript is identical to before this send. The\n // conversation itself continues unaffected — the caller still gets the\n // turn, whose `reply` explains what to resend.\n //\n // Without this the refused message stays in the transcript and is\n // re-transmitted on every later turn — the exact message the server asked\n // the client to drop — corrupting the conversation from here on. And\n // `messages()` returns a copy, so a caller could not repair it either.\n if (turn.conversationStatus === REJECTED_INPUT) {\n this.history.pop();\n return turn;\n }\n\n // Record an assistant turn so the transcript keeps alternating — the\n // platform (and the underlying model) reject two consecutive user\n // turns. Fall back to a placeholder when the agent returned only\n // proposals with no reply text.\n let assistant = turn.reply;\n if (!assistant) {\n assistant = turn.hasProposals ? '(drafted proposals for your review)' : '(no reply)';\n }\n this.history.push({ role: 'assistant', content: assistant });\n\n return turn;\n }\n\n /**\n * A copy of the full transcript so far. Persist this between requests in\n * a stateless backend and rebuild with\n * {@link DakotaClient.resumeAgentConversation}.\n */\n messages(): ChatMessage[] {\n return this.history.map(cloneMessage);\n }\n}\n\nfunction cloneMessage(m: ChatMessage): ChatMessage {\n const out: ChatMessage = { role: m.role, content: m.content };\n if (m.attachments && m.attachments.length > 0) {\n out.attachments = m.attachments.map((a) => ({ ...a }));\n }\n return out;\n}\n\nfunction serializeMessage(m: ChatMessage): {\n role: 'user' | 'assistant';\n content: string;\n attachments?: {\n type: 'document';\n document: {\n media_type: AttachmentMediaType;\n data: string;\n filename?: string;\n };\n }[];\n} {\n const out: ReturnType<typeof serializeMessage> = { role: m.role, content: m.content };\n if (m.attachments && m.attachments.length > 0) {\n out.attachments = m.attachments.map((a) => {\n const document: {\n media_type: AttachmentMediaType;\n data: string;\n filename?: string;\n } = {\n media_type: a.mediaType,\n data: Buffer.from(a.data).toString('base64'),\n };\n if (a.filename) {\n document.filename = a.filename;\n }\n return { type: 'document' as const, document };\n });\n }\n return out;\n}\n","/**\n * High-level agentic helpers: collapse the multi-step, crypto-heavy hosted-\n * agent flows into single calls with good defaults, so a partner integration\n * stays short. The raw operations remain reachable via the resource classes\n * on `DakotaClient`.\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { randomUUID } from 'node:crypto';\n\nimport type { DakotaClient } from '../client/client.js';\n\n/**\n * Grant a principal — a user OR an agent, both are just signers — permission\n * to spend from a wallet by adding its signer to an EXISTING signer group on\n * that wallet: the group whose attached policies should govern it.\n *\n * That membership change is the whole operation, and it is UNENDORSED: group\n * membership is a client-admin action, not a wallet endorsement, so it needs\n * NO signature — not from the wallet owner, not from the principal being\n * added. From then on the principal's transactions are subject to exactly\n * the policies bound to `spendingGroupId`, the same as any other member of\n * that group. The per-payment spend bound remains the agentic mandate gate,\n * not the policy.\n *\n * Deliberately reuses the wallet's pre-built policies and creates NO\n * per-signer policy. Two policy-engine realities make a per-signer policy\n * the wrong tool: a policy → wallet attach is endorsed by the policy's OWN\n * signer group (so only that group's key could attach it), and an\n * unconditional approval-threshold ALLOW policy inverts to a deny for any\n * transaction its group didn't sign, so a second signer's policy would veto\n * the first. Prepare the wallet's groups + policies in advance and point\n * each principal at the group whose constraints you want it to inherit.\n *\n * Idempotent: if the signer is already a member, returns\n * `alreadyMember: true` and makes no write. Rejects `spendingGroupId` if it\n * is not attached to `walletId`, so a wrong group fails loudly instead of\n * silently granting nothing.\n *\n * The key must already exist as a signer resource — the add endpoint takes\n * a `member_key` reference, it does not register keys. A hosted agent's key\n * is minted by `paymentAgents.create`; for a bare user key, register it\n * first (`POST /signers`) or the add fails with a signer-not-found error.\n *\n * @param client - Dakota client\n * @param walletId - The wallet the principal will spend from\n * @param signerPublicKey - The principal's registered signer public key\n * (base64 PKIX) — e.g. `signer_public_key` returned by\n * `paymentAgents.create` for a hosted agent\n * @param spendingGroupId - The signer group whose attached policies should\n * govern the principal; must already be attached to `walletId`\n * @param options - Optional. Supply `idempotencyKey` (a valid UUID — the\n * platform rejects other formats with 400) to make the WHOLE helper\n * safely retryable — a crashed or partitioned call replayed with the\n * same key dedupes the underlying write server-side. Defaults to a\n * fresh random UUID per call.\n * @returns `{ alreadyMember }` — true when the signer was already a member\n * (no write performed)\n */\nexport async function attachUserToWallet(\n client: DakotaClient,\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n): Promise<{ alreadyMember: boolean }> {\n if (!walletId || !signerPublicKey || !spendingGroupId) {\n throw new Error('walletId, signerPublicKey and spendingGroupId are all required');\n }\n\n await requireGroupOnWallet(client, walletId, spendingGroupId);\n\n // Idempotency: skip the add if the signer's key is already a member.\n const group = await client.signerGroups.get(spendingGroupId);\n for (const member of group.members ?? []) {\n if (member.public_key === signerPublicKey) {\n return { alreadyMember: true };\n }\n }\n\n // Add the signer to the group (unendorsed). Granting spend permission is\n // security-relevant, so set an explicit idempotency key rather than depend\n // on transport config (`automaticIdempotency: false` would otherwise send\n // this POST without the required header and 400).\n await client.signerGroups.addSigner(\n spendingGroupId,\n { member_key: signerPublicKey },\n { idempotencyKey: options?.idempotencyKey ?? randomUUID() }\n );\n return { alreadyMember: false };\n}\n\n/**\n * Revoke a principal's spend permission by removing its signer from\n * `spendingGroupId` — the inverse of {@link attachUserToWallet}, and\n * likewise UNENDORSED (no signature).\n *\n * Deliberately SCOPED to the one group you pass, NOT a sweep across every\n * group on the wallet, for two reasons:\n * - signer groups are NOT wallet-exclusive — the same group can govern\n * multiple wallets — so removing a signer from a group revokes it on\n * EVERY wallet that group governs; passing one explicit group keeps\n * that blast radius known instead of multiplying it across all of the\n * wallet's groups;\n * - a sweep cannot tell \"added for this agent\" from \"belongs here for\n * another reason\" (e.g. the human owner sitting in the admin group),\n * so it can lock out a legitimate member.\n *\n * Pass the same group you used to attach. Idempotent: if the signer isn't\n * a member, it is a no-op (`wasMember: false`). Rejects `spendingGroupId`\n * if it is not attached to `walletId`.\n *\n * NOTE: this does not guard against removing a group's LAST member —\n * emptying the group that governs a wallet can leave it with no authorized\n * signer. The caller must avoid stranding the wallet. For a hosted agent,\n * prefer `paymentAgents.revoke` (it destroys the agent's key, so the signer\n * can authorize nothing even while still listed) and use this for\n * membership hygiene.\n *\n * @param options - Optional. Supply `idempotencyKey` (a valid UUID) to\n * make the WHOLE helper safely retryable across crashes/partitions;\n * defaults to a fresh random UUID per call.\n */\nexport async function detachUserFromWallet(\n client: DakotaClient,\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n): Promise<{ wasMember: boolean }> {\n if (!walletId || !signerPublicKey || !spendingGroupId) {\n throw new Error('walletId, signerPublicKey and spendingGroupId are all required');\n }\n\n await requireGroupOnWallet(client, walletId, spendingGroupId);\n\n // Resolve the signer's public key → its resource id within the group: the\n // delete endpoint addresses members by id, not key. Absent ⇒ idempotent\n // no-op.\n const group = await client.signerGroups.get(spendingGroupId);\n let signerId = '';\n for (const member of group.members ?? []) {\n if (member.public_key === signerPublicKey) {\n signerId = member.id ?? '';\n break;\n }\n }\n if (!signerId) {\n return { wasMember: false };\n }\n\n // The platform requires an idempotency key on this DELETE. The transport\n // now injects one on DELETEs too, but revoking spend permission is\n // security-relevant, so we set one explicitly — this path must not depend\n // on transport configuration.\n await client.signerGroups.removeSigner(spendingGroupId, signerId, {\n idempotencyKey: options?.idempotencyKey ?? randomUUID(),\n });\n return { wasMember: true };\n}\n\n/**\n * Errors unless `spendingGroupId` is one of the signer groups attached to\n * `walletId` — so attach/detach can't silently operate on a group that has\n * nothing to do with the named wallet.\n *\n * Uses the symmetric group → wallets read (`GET /signer-groups/{id}/wallets`)\n * because it returns a bare array with a stable shape. Semantically\n * equivalent to `GET /wallets/{id}/signer-groups`; the check succeeds iff\n * the pair is attached.\n */\nasync function requireGroupOnWallet(\n client: DakotaClient,\n walletId: string,\n spendingGroupId: string\n): Promise<void> {\n const wallets = await client.signerGroups.getWallets(spendingGroupId);\n for (const w of wallets) {\n if (w.id === walletId) {\n return;\n }\n }\n throw new Error(`signer group ${spendingGroupId} is not attached to wallet ${walletId}`);\n}\n","/**\n * Dakota Platform API Client.\n */\n\nimport { DakotaClientConfig, ResolvedConfig, resolveConfig } from './config.js';\nimport { Transport } from './transport.js';\nimport {\n CustomersResource,\n RecipientsResource,\n DestinationsResource,\n AccountsResource,\n TransactionsResource,\n AutoTransactionsResource,\n WalletsResource,\n EventsResource,\n ApplicationsResource,\n PoliciesResource,\n SignerGroupsResource,\n SignersResource,\n ApiKeysResource,\n UsersResource,\n WebhooksResource,\n InfoResource,\n LegalResource,\n RDMarketingFeeResource,\n SandboxResource,\n SelfServeResource,\n FeePayoutDestinationResource,\n PaymentAgentsResource,\n InstructionsResource,\n MandatesResource,\n ScheduledPaymentsResource,\n InsightsResource,\n AgenticPolicyResource,\n} from './resources/index.js';\nimport {\n AgentConversation,\n type AgentConversationOptions,\n type ChatMessage,\n} from '../agentic/chat.js';\nimport {\n attachUserToWallet as attachUserToWalletHelper,\n detachUserFromWallet as detachUserFromWalletHelper,\n} from '../agentic/wallets.js';\n\n/**\n * Dakota Platform API Client.\n *\n * The main entry point for interacting with the Dakota Platform API.\n *\n * @example\n * ```typescript\n * import { DakotaClient, Environment } from 'dakota-ts-sdk';\n *\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * environment: Environment.Sandbox, // default\n * });\n *\n * // List customers\n * for await (const customer of client.customers.list()) {\n * console.log(customer.name);\n * }\n *\n * // Create a customer\n * const customer = await client.customers.create({\n * name: 'Acme Corp',\n * customer_type: 'business',\n * });\n * ```\n */\nexport class DakotaClient {\n private readonly config: ResolvedConfig;\n private readonly transport: Transport;\n\n // API Resources\n /** Customers API - manage customer records and KYB */\n readonly customers: CustomersResource;\n /** Recipients API - manage payment recipients */\n readonly recipients: RecipientsResource;\n /** Destinations API - manage bank accounts and crypto wallets */\n readonly destinations: DestinationsResource;\n /** Accounts API - manage on-ramp, off-ramp, and swap accounts */\n readonly accounts: AccountsResource;\n /** Transactions API - manage one-off transactions */\n readonly transactions: TransactionsResource;\n /** Auto Transactions API - manage automated transactions */\n readonly autoTransactions: AutoTransactionsResource;\n /** Wallets API - manage non-custodial wallets */\n readonly wallets: WalletsResource;\n /** Events API - query platform events */\n readonly events: EventsResource;\n /** Applications API - manage KYB applications */\n readonly applications: ApplicationsResource;\n /** Policies API - manage transaction policies */\n readonly policies: PoliciesResource;\n /** Signer Groups API - manage multi-sig signer groups */\n readonly signerGroups: SignerGroupsResource;\n /** Signers API - manage individual signers */\n readonly signers: SignersResource;\n /** API Keys API - manage API keys */\n readonly apiKeys: ApiKeysResource;\n /** Users API - manage platform users */\n readonly users: UsersResource;\n /** Webhooks API - manage webhook targets and events */\n readonly webhooks: WebhooksResource;\n /** Info API - query platform capabilities */\n readonly info: InfoResource;\n /** Legal API - the published terms customers accept (unauthenticated) */\n readonly legal: LegalResource;\n /** RD Marketing Fee API - this client's reserve-management statements */\n readonly rdMarketingFee: RDMarketingFeeResource;\n /** Sandbox API - testing simulations (sandbox only) */\n readonly sandbox: SandboxResource;\n /** Self-Serve Credits API - manage prepaid transfer credits */\n readonly selfServe: SelfServeResource;\n /** Fee Payout Destination API - where Dakota pays your accrued developer fees */\n readonly feePayoutDestination: FeePayoutDestinationResource;\n /** Payment Agents API (ALPHA) - hosted signing agents that draft payments */\n readonly paymentAgents: PaymentAgentsResource;\n /** Instructions API (ALPHA) - accept and inspect actuated proposals */\n readonly instructions: InstructionsResource;\n /** Mandates API (ALPHA) - the §8 authorizations that arm scheduled payments */\n readonly mandates: MandatesResource;\n /** Scheduled Payments API (ALPHA) - schedule rows created from instructions */\n readonly scheduledPayments: ScheduledPaymentsResource;\n /** Insights API (ALPHA) - read-only advisory reporting over agentic activity */\n readonly insights: InsightsResource;\n /** Agentic Policy API (ALPHA) - register the vocabulary the agent speaks for your product */\n readonly agenticPolicy: AgenticPolicyResource;\n\n /**\n * Create a new Dakota client.\n *\n * @param config - Client configuration\n * @throws ConfigurationError if configuration is invalid\n *\n * @example\n * ```typescript\n * // Basic usage (sandbox)\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * });\n *\n * // Production\n * const client = new DakotaClient({\n * apiKey: 'your_production_api_key',\n * environment: Environment.Production,\n * });\n *\n * // With custom configuration\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * timeout: 30000,\n * retryPolicy: {\n * maxAttempts: 5,\n * initialBackoffMs: 100,\n * maxBackoffMs: 5000,\n * },\n * logger: console,\n * });\n * ```\n */\n constructor(config: DakotaClientConfig) {\n this.config = resolveConfig(config);\n this.transport = new Transport(this.config);\n\n // Initialize resources\n this.customers = new CustomersResource(this.transport);\n this.recipients = new RecipientsResource(this.transport);\n this.destinations = new DestinationsResource(this.transport);\n this.accounts = new AccountsResource(this.transport);\n this.transactions = new TransactionsResource(this.transport);\n this.autoTransactions = new AutoTransactionsResource(this.transport);\n this.wallets = new WalletsResource(this.transport);\n this.events = new EventsResource(this.transport);\n this.applications = new ApplicationsResource(this.transport);\n this.policies = new PoliciesResource(this.transport);\n this.signerGroups = new SignerGroupsResource(this.transport);\n this.signers = new SignersResource(this.transport);\n this.apiKeys = new ApiKeysResource(this.transport);\n this.users = new UsersResource(this.transport);\n this.webhooks = new WebhooksResource(this.transport);\n this.info = new InfoResource(this.transport);\n this.legal = new LegalResource(this.transport);\n this.rdMarketingFee = new RDMarketingFeeResource(this.transport);\n this.sandbox = new SandboxResource(this.transport);\n this.selfServe = new SelfServeResource(this.transport);\n this.feePayoutDestination = new FeePayoutDestinationResource(this.transport);\n this.paymentAgents = new PaymentAgentsResource(this.transport);\n this.instructions = new InstructionsResource(this.transport);\n this.mandates = new MandatesResource(this.transport);\n this.scheduledPayments = new ScheduledPaymentsResource(this.transport);\n this.insights = new InsightsResource(this.transport);\n this.agenticPolicy = new AgenticPolicyResource(this.transport);\n }\n\n // ==========================================================================\n // Agentic Payments high-level helpers (ALPHA)\n //\n // Collapse the multi-step, crypto-heavy hosted-agent flows into single\n // calls with good defaults. The raw operations remain reachable via\n // `signerGroups.addSigner` / `signerGroups.removeSigner` and friends.\n // ==========================================================================\n\n /**\n * Start a fresh multi-turn conversation with a payment agent.\n *\n * Pass `{ timezone }` (an IANA zone) so the agent resolves \"tomorrow\" and\n * \"10 am\" in the customer's local time rather than UTC. The conversation\n * resends it on every turn.\n *\n * @see AgentConversation\n */\n newAgentConversation(\n paymentAgentId: string,\n options?: AgentConversationOptions\n ): AgentConversation {\n return new AgentConversation(this, paymentAgentId, undefined, options);\n }\n\n /**\n * Rebuild a conversation from a persisted transcript (oldest first) —\n * for backends that store the history between requests.\n *\n * A stateless backend must pass `{ timezone }` again here: the transcript\n * carries the messages, not the zone.\n */\n resumeAgentConversation(\n paymentAgentId: string,\n history: ChatMessage[],\n options?: AgentConversationOptions\n ): AgentConversation {\n return new AgentConversation(this, paymentAgentId, history, options);\n }\n\n /**\n * Grant a principal (user or agent — both are just signers) permission to\n * spend from a wallet by adding its signer to an EXISTING signer group on\n * that wallet. Idempotent; errors if the group isn't attached to the wallet.\n *\n * @see attachUserToWallet in `agentic/wallets.ts` for the full contract.\n */\n attachUserToWallet(\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n ): Promise<{ alreadyMember: boolean }> {\n return attachUserToWalletHelper(this, walletId, signerPublicKey, spendingGroupId, options);\n }\n\n /**\n * Revoke a principal's spend permission by removing its signer from the\n * given signer group — the inverse of {@link attachUserToWallet}.\n * Idempotent; errors if the group isn't attached to the wallet.\n *\n * @see detachUserFromWallet in `agentic/wallets.ts` for the full contract.\n */\n detachUserFromWallet(\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n ): Promise<{ wasMember: boolean }> {\n return detachUserFromWalletHelper(this, walletId, signerPublicKey, spendingGroupId, options);\n }\n\n /**\n * Get the resolved base URL.\n */\n get baseURL(): string {\n return this.config.baseURL;\n }\n}\n","/**\n * RFC 8785 (JCS) canonical JSON — the exact bytes the platform signs.\n *\n * A payload canonicalized here matches the platform's `enc.C14nJSON`\n * (json.Marshal + jsoncanonicalizer.Transform) byte-for-byte, so a\n * signature produced from the result verifies server-side.\n *\n * This implementation covers the value shapes the SDK ever puts into a\n * signed payload: nulls, booleans, finite integers/floats, strings,\n * arrays, and plain object maps. It intentionally does NOT handle\n * non-integer numbers with fractional parts differently from\n * JSON.stringify, because every mandate/endorsement payload the SDK\n * produces uses only integers, strings, arrays, and object maps — decimal\n * amounts are always sent as strings.\n */\n\n/**\n * RFC 8785 (JCS) canonicalize `value` and return its bytes as a UTF-8 string.\n *\n * @throws if `value` contains a non-finite number, a Symbol, a bigint, or a\n * circular reference — any of which cannot be encoded to canonical JSON.\n */\nexport function canonicalJSON(value: unknown): string {\n return canonicalize(value);\n}\n\nfunction canonicalize(value: unknown): string {\n if (value === null || value === undefined) {\n return 'null';\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new TypeError(`canonical JSON: non-finite number ${value}`);\n }\n // JSON.stringify already emits ES6 Number.prototype.toString() for\n // finite numbers, which is exactly what RFC 8785 § 3.2.2.3 mandates.\n return JSON.stringify(value);\n }\n if (typeof value === 'string') {\n // JSON.stringify handles JSON escape sequences per RFC 8259, matching\n // JCS's string-escape rules (§ 3.2.2.2).\n return JSON.stringify(value);\n }\n if (typeof value === 'bigint') {\n // BigInts have no unambiguous number representation for JSON;\n // fail loudly rather than produce bytes that won't verify.\n throw new TypeError('canonical JSON: bigint values are not supported');\n }\n if (Array.isArray(value)) {\n const parts = value.map((item) => canonicalize(item));\n return `[${parts.join(',')}]`;\n }\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // JCS sorts object member keys by their UTF-16 code-unit order,\n // which is exactly what a JavaScript `Array.prototype.sort()` on\n // strings produces (§ 3.2.3).\n const keys = Object.keys(obj).sort();\n const parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(obj[key])}`);\n return `{${parts.join(',')}}`;\n }\n throw new TypeError(`canonical JSON: unsupported value type ${typeof value}`);\n}\n","/**\n * §8 mandate signing. Approving (or cancelling) a mandate is not a bare API\n * call: it requires a cryptographic signature over the mandate's canonical\n * bytes, proving the action came from a holder of the registered key. This\n * file reproduces the platform's exact signed payload (RFC 8785 / JCS\n * canonical JSON) and a P-256 signing/verification path, so partners never\n * hand-roll JCS + ECDSA.\n *\n * The canonical bytes a signature covers — matched byte-for-byte with the\n * platform's MandatePayload — are JCS JSON of:\n *\n * {action, id, bound_signer, rule, valid_from, valid_until}\n *\n * signed as base64( ASN.1( ECDSA-P256( SHA-256(payload) ))), with the public\n * key as base64 PKIX (SPKI).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport {\n createPrivateKey,\n createPublicKey,\n createSign,\n createVerify,\n generateKeyPairSync,\n KeyObject,\n} from 'node:crypto';\n\nimport type { Mandate, MandateRule } from '../client/types.js';\nimport { canonicalJSON } from './canonicalize.js';\n\n/**\n * The §8 verb a signature authorizes. It is part of the signed payload so\n * an approval and a cancellation can never be each other's replay: a signed\n * cancel must not be byte-identical to a signed approve.\n */\nexport type MandateAction = 'approve' | 'cancel';\n\n/**\n * Produces the §8 signature the platform verifies for a mandate\n * approve/cancel. The caller holds the private key; the SDK never sees it.\n *\n * Implement this over your own key custody (HSM/KMS) for production. For\n * sandbox and tests, `P256MandateSigner` is a ready in-memory implementation.\n */\nexport interface MandateSigner {\n /**\n * The base64 PKIX (SPKI) P-256 public key — the exact form the platform\n * registered for this signer and verifies signatures against.\n */\n publicKeyBase64(): string;\n\n /**\n * Returns a base64 ASN.1 ECDSA signature over SHA-256(payload).\n */\n sign(payload: Uint8Array): Promise<string> | string;\n}\n\n/**\n * Reproduces, byte-for-byte, the canonical bytes the platform signs for one\n * §8 action on a mandate. Build it straight from the mandate as returned by\n * `mandates.get` / `mandates.list` — no server state is needed, and field\n * order is irrelevant (JCS sorts).\n *\n * `valid_from` / `valid_until` are always present in the signed payload\n * (even when zero); the wire omits a zero value, so a missing field\n * canonicalizes to 0 — matching the platform, which signs the int64\n * directly.\n */\nexport function mandateSignPayload(mandate: Mandate, action: MandateAction): Uint8Array {\n if (!mandate.id) {\n throw new Error('mandate has no id');\n }\n if (!mandate.bound_signer_id) {\n throw new Error('mandate has no bound_signer_id');\n }\n if (!mandate.rule) {\n throw new Error('mandate has no rule');\n }\n const encoded = canonicalJSON({\n action,\n id: mandate.id,\n bound_signer: mandate.bound_signer_id,\n rule: mandate.rule,\n valid_from: mandate.valid_from ?? 0,\n valid_until: mandate.valid_until ?? 0,\n });\n return new TextEncoder().encode(encoded);\n}\n\n/**\n * Reproduces, byte-for-byte, the canonical bytes the platform verifies for an\n * AMEND — appending version `version`, carrying `rule`, to `mandate`.\n *\n * The approve/cancel bytes are frozen, so amend gets its own payload rather\n * than an extra key on `mandateSignPayload`. It is the same JCS JSON plus one\n * key, `version`:\n *\n * {action: 'amend', id, bound_signer, rule, valid_from, valid_until, version}\n *\n * **`version` is what stops cross-version replay.** Without it, a signature\n * over `{amend, rule R}` would authorize \"make the current rule R\" forever: a\n * customer who signs v2 raising a limit to 20,000 and then v3 lowering it to\n * 5,000 could have the v2 signature replayed as a v4 — a rollback of their own\n * reduction, using their own signature. Binding the exact version number makes\n * each amend signature usable once, at one point in the mandate's history.\n *\n * `rule` is the NEW rule (what the signer is agreeing to), not the outgoing\n * one, and is taken verbatim — the amend endpoint never normalizes it, so the\n * bytes signed here are the bytes the server verifies. Pass the SAME rule\n * object to `mandates.amend`.\n *\n * @param mandate - The mandate as it is NOW (the amend is a compare-and-set on\n * its current version)\n * @param version - The version this amend creates — the mandate's current\n * `version` + 1\n * @param rule - The complete new rule, in canonical form\n */\nexport function mandateAmendSignPayload(\n mandate: Mandate,\n version: number,\n rule: MandateRule\n): Uint8Array {\n if (!mandate.id) {\n throw new Error('mandate has no id');\n }\n if (!mandate.bound_signer_id) {\n throw new Error('mandate has no bound_signer_id');\n }\n if (!Number.isInteger(version) || version < 2) {\n throw new Error('amend version must be an integer >= 2 (the version being created)');\n }\n const encoded = canonicalJSON({\n action: 'amend',\n id: mandate.id,\n bound_signer: mandate.bound_signer_id,\n rule,\n valid_from: mandate.valid_from ?? 0,\n valid_until: mandate.valid_until ?? 0,\n version,\n });\n return new TextEncoder().encode(encoded);\n}\n\n// ---------------------------------------------------------------------------\n// Endorsed-intent payload helpers.\n// ---------------------------------------------------------------------------\n//\n// Each reproduces, byte-for-byte, the canonical map the platform's policy\n// engine rebuilds to verify the endorsement (its intent reconstruction).\n// The idempotency_key is part of the signed bytes — reuse the SAME key on\n// the corresponding request.\n\n/**\n * Canonical bytes a recognized wallet signer endorses to attach a signer\n * group to a wallet.\n */\nexport function attachGroupPayload(\n walletId: string,\n groupId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'attach_group_to_wallet',\n wallet_id: walletId,\n group_id: groupId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to attach a policy to\n * a wallet.\n */\nexport function attachPolicyPayload(\n walletId: string,\n policyId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'attach_policy_to_wallet',\n wallet_id: walletId,\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to remove a signer\n * group from a wallet — the inverse of {@link attachGroupPayload}.\n */\nexport function detachGroupPayload(\n walletId: string,\n groupId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'detach_group_from_wallet',\n wallet_id: walletId,\n group_id: groupId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to remove a policy\n * from a wallet — the inverse of {@link attachPolicyPayload}.\n */\nexport function detachPolicyPayload(\n walletId: string,\n policyId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'detach_policy_from_wallet',\n wallet_id: walletId,\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to delete a policy.\n */\nexport function deletePolicyPayload(policyId: string, idempotencyKey: string): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'delete_policy',\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to remove a rule from a policy.\n */\nexport function removePolicyRulePayload(\n policyId: string,\n ruleId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'remove_policy_rule',\n policy_id: policyId,\n rule_id: ruleId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to update a rule's definition. `updatedDefinition` is the rule definition\n * as a JSON STRING; it is signed opaquely, exactly as sent on the update\n * request.\n */\nexport function updatePolicyRulePayload(\n policyId: string,\n ruleId: string,\n updatedDefinition: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'update_policy_rule',\n policy_id: policyId,\n rule_id: ruleId,\n updated_definition: updatedDefinition,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to add a rule to a policy. `action` (e.g. `\"allow\"`), `ruleType` (e.g.\n * `\"amount_threshold\"`), and `definition` (the rule-type-specific config,\n * in API format) must match the values sent on the add request, or the\n * endorsement won't verify against it.\n */\nexport function addPolicyRulePayload(\n policyId: string,\n action: string,\n ruleType: string,\n definition: Record<string, unknown>,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'add_policy_rule',\n action,\n rule_type: ruleType,\n policy_id: policyId,\n definition,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\nfunction textBytes(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\n// ---------------------------------------------------------------------------\n// P256MandateSigner — default in-memory signer (sandbox / tests)\n// ---------------------------------------------------------------------------\n\n/**\n * A {@link MandateSigner} holding a P-256 (ES256) private key in memory.\n *\n * Convenient for sandbox and tests; for production, implement\n * {@link MandateSigner} over your own key custody so the private key never\n * lives in the process.\n */\nexport class P256MandateSigner implements MandateSigner {\n private readonly privateKey: KeyObject;\n private readonly publicKey: KeyObject;\n\n private constructor(privateKey: KeyObject, publicKey: KeyObject) {\n this.privateKey = privateKey;\n this.publicKey = publicKey;\n }\n\n /**\n * Generate a fresh P-256 keypair.\n */\n static generate(): P256MandateSigner {\n const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });\n return new P256MandateSigner(privateKey, publicKey);\n }\n\n /**\n * Adopt an existing P-256 private key. Accepts a PKCS#8 PEM string, a\n * DER-encoded PKCS#8 buffer, or a Node {@link KeyObject}.\n */\n static fromPrivateKey(key: KeyObject | string | Uint8Array): P256MandateSigner {\n const privateKey =\n typeof key === 'string' || key instanceof Uint8Array\n ? createPrivateKey({\n key: key as string | Buffer,\n format: typeof key === 'string' ? 'pem' : 'der',\n type: 'pkcs8',\n })\n : key;\n if (privateKey.asymmetricKeyType !== 'ec') {\n throw new Error('a P-256 private key is required (ES256)');\n }\n const details = privateKey.asymmetricKeyDetails;\n if (details?.namedCurve !== 'prime256v1') {\n throw new Error('a P-256 private key is required (ES256)');\n }\n const publicKey = createPublicKey(privateKey);\n return new P256MandateSigner(privateKey, publicKey);\n }\n\n /**\n * base64 PKIX (SPKI) public key — pass this as the signer's registered\n * public key at agent creation / mandate approval.\n */\n publicKeyBase64(): string {\n const der = this.publicKey.export({ format: 'der', type: 'spki' });\n return Buffer.from(der).toString('base64');\n }\n\n /**\n * Returns base64( ASN.1 ECDSA signature over SHA-256(payload) ).\n */\n sign(payload: Uint8Array): string {\n const signer = createSign('SHA256');\n signer.update(payload);\n const sig = signer.sign({ key: this.privateKey, dsaEncoding: 'der' });\n return Buffer.from(sig).toString('base64');\n }\n}\n\n/**\n * Check a base64 ASN.1 signature over SHA-256 of the canonical payload\n * against a base64 PKIX P-256 public key — the platform's exact\n * verification. Exposed so callers (and tests) can self-check a signature\n * before submitting it.\n *\n * @throws if the public key or signature can't be parsed, or the signature\n * does not verify against the payload.\n */\nexport function verifyMandateSignature(\n publicKeyBase64: string,\n payload: Uint8Array,\n signatureBase64: string\n): void {\n let publicKey: KeyObject;\n try {\n publicKey = createPublicKey({\n key: Buffer.from(publicKeyBase64, 'base64'),\n format: 'der',\n type: 'spki',\n });\n } catch (err) {\n throw new Error(`parse public key: ${(err as Error).message}`);\n }\n if (publicKey.asymmetricKeyType !== 'ec') {\n throw new Error('not a P-256 public key (ES256 requires P-256)');\n }\n if (publicKey.asymmetricKeyDetails?.namedCurve !== 'prime256v1') {\n throw new Error('not a P-256 public key (ES256 requires P-256)');\n }\n const verifier = createVerify('SHA256');\n verifier.update(payload);\n const ok = verifier.verify(\n { key: publicKey, dsaEncoding: 'der' },\n Buffer.from(signatureBase64, 'base64')\n );\n if (!ok) {\n throw new Error('signature verification failed');\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/environment.ts","../src/client/errors.ts","../src/client/config.ts","../src/client/transport.ts","../src/client/pagination.ts","../src/client/resources/base.ts","../src/client/resources/customers.ts","../src/client/resources/recipients.ts","../src/agentic/canonicalize.ts","../src/governance/encoding.ts","../src/governance/intents.ts","../src/client/resources/destinations.ts","../src/client/resources/accounts.ts","../src/client/resources/transactions.ts","../src/client/resources/wallets.ts","../src/client/resources/events.ts","../src/client/resources/applications.ts","../src/client/resources/policies.ts","../src/governance/signer.ts","../src/client/resources/signer-groups.ts","../src/client/resources/api-keys.ts","../src/client/resources/users.ts","../src/client/resources/webhooks.ts","../src/client/resources/info.ts","../src/client/resources/legal.ts","../src/client/resources/rd-marketing-fee.ts","../src/client/resources/sandbox.ts","../src/client/resources/self-serve.ts","../src/client/resources/fee-payout-destination.ts","../src/client/resources/payment-agents.ts","../src/client/resources/instructions.ts","../src/client/resources/mandates.ts","../src/client/resources/scheduled-payments.ts","../src/client/resources/insights.ts","../src/client/resources/agentic-policy.ts","../src/agentic/chat.ts","../src/agentic/wallets.ts","../src/client/client.ts","../src/signing/es256.ts","../src/agentic/sign.ts","../src/governance/webauthn.ts"],"names":["Environment","AuthMode","RETRYABLE_STATUS_CODES","version","randomUUID"],"mappings":";;;AAGO,IAAK,WAAA,qBAAAA,YAAAA,KAAL;AAEL,EAAAA,aAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,aAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,aAAA,aAAA,CAAA,GAAc,aAAA;AAEd,EAAAA,aAAA,OAAA,CAAA,GAAQ,OAAA;AARE,EAAA,OAAAA,YAAAA;AAAA,CAAA,EAAA,WAAA,IAAA,EAAA;AAWZ,IAAM,gBAAA,GAAgD;AAAA,EACpD,CAAC,0BAAsB,yCAAA;AAAA,EACvB,CAAC,gCAAyB,iCAAA;AAAA,EAC1B,CAAC,kCAA0B,6CAAA;AAAA,EAC3B,CAAC,sBAAoB;AACvB,CAAA;AAKO,SAAS,kBAAkB,GAAA,EAA0B;AAC1D,EAAA,MAAM,GAAA,GAAM,iBAAiB,GAAG,CAAA;AAChC,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwB,GAAG,CAAA,CAAE,CAAA;AAAA,EAC/C;AACA,EAAA,OAAO,GAAA;AACT;;;ACzBA,IAAM,sBAAA,uBAA6B,GAAA,CAAI,CAAC,KAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAG,CAAC,CAAA;AAKzD,IAAM,QAAA,GAAN,MAAM,SAAA,SAAiB,KAAA,CAAM;AAAA;AAAA,EAEzB,UAAA;AAAA;AAAA,EAEA,IAAA;AAAA;AAAA,EAEA,OAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,OAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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W,IAAA,CAAK,MAAA,IAAU,GAAA,CAAI,KAAA,CAAM,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,KAAM,IAAA,CAAK,CAAC,CAAC,CAAA;AAAA,EACxE,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAiBO,SAAS,eACd,YAAA,EACkB;AAClB,EAAA,OAAO;AAAA,IACL,MAAM,KAAK,OAAA,EAAsC;AAC/C,MAAA,MAAM,UAAA,GAAa,MAAM,YAAA,CAAa,cAAA,CAAe,OAAO,CAAC,CAAA;AAC7D,MAAA,OAAO,cAAc,UAAU,CAAA;AAAA,IACjC;AAAA,GACF;AACF","file":"index.mjs","sourcesContent":["/**\n * Environment configuration for Dakota Platform API.\n */\nexport enum Environment {\n /** Sandbox environment for testing - no real money moves */\n Sandbox = 'sandbox',\n /** Production environment - real transactions with real money */\n Production = 'production',\n /** Development environment (internal use) */\n Development = 'development',\n /** Local environment (internal use) */\n Local = 'local',\n}\n\nconst ENVIRONMENT_URLS: Record<Environment, string> = {\n [Environment.Sandbox]: 'https://api.platform.sandbox.dakota.xyz',\n [Environment.Production]: 'https://api.platform.dakota.xyz',\n [Environment.Development]: 'https://api.platform.development.dakota.xyz',\n [Environment.Local]: 'http://localhost:6464',\n};\n\n/**\n * Get the base URL for a given environment.\n */\nexport function getEnvironmentURL(env: Environment): string {\n const url = ENVIRONMENT_URLS[env];\n if (!url) {\n throw new Error(`Unknown environment: ${env}`);\n }\n return url;\n}\n","/**\n * Error classes for Dakota SDK.\n */\n\n/** Status codes that are safe to retry */\nconst RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);\n\n/**\n * Represents a structured Dakota Platform API error response.\n */\nexport class APIError extends Error {\n /** HTTP status code */\n readonly statusCode: number;\n /** Machine-readable error code */\n readonly code: string;\n /** Additional error details */\n readonly details: Record<string, unknown> | null;\n /** Request ID for support tickets */\n readonly requestId: string | null;\n /** Raw response body */\n readonly rawBody: string | null;\n /** Whether this error is safe to retry */\n readonly retryable: boolean;\n /**\n * A plain-language rendition of the problem, written for the END CUSTOMER,\n * when one exists for this error.\n *\n * `message` names request fields and actions so a machine caller can\n * self-correct. This says the same thing without API vocabulary. Show it\n * when relaying an error into a human surface (chat, email, UI), and fall\n * back to `message` when it is null.\n */\n readonly userMessage: string | null;\n /**\n * A link the customer can follow to CLEAR this error, present only on\n * problems with a concrete self-service remedy.\n *\n * Today `terms-not-accepted` returns one, pointing at the hosted flow where\n * the outstanding agreement can be signed. It is token-gated and usable\n * as-is — send the customer to it rather than parsing one out of the\n * message.\n */\n readonly resolutionUrl: string | null;\n\n constructor(\n statusCode: number,\n code: string,\n message: string,\n options?: {\n details?: Record<string, unknown> | null;\n requestId?: string | null;\n rawBody?: string | null;\n userMessage?: string | null;\n resolutionUrl?: string | null;\n }\n ) {\n super(message);\n this.name = 'APIError';\n this.statusCode = statusCode;\n this.code = code;\n this.details = options?.details ?? null;\n this.requestId = options?.requestId ?? null;\n this.rawBody = options?.rawBody ?? null;\n this.retryable = RETRYABLE_STATUS_CODES.has(statusCode);\n this.userMessage = options?.userMessage ?? null;\n this.resolutionUrl = options?.resolutionUrl ?? null;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, APIError);\n }\n }\n\n /**\n * Create an APIError from an HTTP response.\n */\n static async fromResponse(response: Response): Promise<APIError> {\n const requestId = response.headers.get('x-request-id');\n let rawBody: string | null = null;\n let code = `http_${response.status}`;\n let message = response.statusText || 'Unknown error';\n let details: Record<string, unknown> | null = null;\n let userMessage: string | null = null;\n let resolutionUrl: string | null = null;\n\n try {\n rawBody = await response.text();\n const parsed = JSON.parse(rawBody);\n\n // Try ProblemDetails format (RFC 7807)\n if (parsed.type && typeof parsed.type === 'string') {\n // Extract code from type URI fragment (e.g., \"...#invalid-request\")\n const hashIndex = parsed.type.lastIndexOf('#');\n if (hashIndex !== -1) {\n code = parsed.type.substring(hashIndex + 1);\n }\n }\n\n // Use code if directly provided\n if (parsed.code) {\n code = parsed.code;\n }\n\n // Build message from title and detail\n if (parsed.title) {\n message = parsed.title;\n if (parsed.detail) {\n message = `${parsed.title}: ${parsed.detail}`;\n }\n } else if (parsed.message) {\n message = parsed.message;\n } else if (parsed.detail) {\n message = parsed.detail;\n }\n\n // Extract details\n if (parsed.details && typeof parsed.details === 'object') {\n details = parsed.details;\n }\n\n // RFC 9457 extensions. `message` stays the machine-facing rendition;\n // these two are what a human surface should show instead.\n if (typeof parsed.user_message === 'string') {\n userMessage = parsed.user_message;\n }\n if (typeof parsed.resolution_url === 'string') {\n resolutionUrl = parsed.resolution_url;\n }\n } catch {\n // Failed to parse JSON, use defaults\n }\n\n // A body not shaped like the platform's (numeric code, a code named like\n // an Object.prototype member) must still become a plain APIError.\n if (typeof code !== 'string') {\n code = `http_${response.status}`;\n }\n const governanceCode = code.replace(/-/g, '_');\n const Typed = GOVERNANCE_ERRORS.get(governanceCode);\n if (Typed) {\n code = governanceCode;\n }\n return new (Typed ?? APIError)(response.status, code, message, {\n details,\n requestId,\n rawBody,\n userMessage,\n resolutionUrl,\n });\n }\n\n override toString(): string {\n if (this.code) {\n return `APIError [${this.statusCode} ${this.code}]: ${this.message}`;\n }\n return `APIError [${this.statusCode}]: ${this.message}`;\n }\n}\n\n// ============================================================================\n// Signer-group governance refusals\n// ============================================================================\n//\n// Each is an APIError (so existing `instanceof APIError` handling still\n// catches it) with a class of its own, so a caller can react to the one\n// governance refusal it can act on without matching strings.\n\ntype APIErrorOptions = ConstructorParameters<typeof APIError>[3];\n\n/**\n * `endorsement_required` (400): the signer-group change needs signatures from\n * the group's governing members — the client has governance enforcement on,\n * or the group has governance settings. Send it signed: use\n * `signerGroups.addSignerSigned` / `removeSignersSigned` /\n * `updateGovernanceSigned`, or the `prepare*` + `submitSignedChange` pair.\n */\nexport class EndorsementRequiredError extends APIError {\n constructor(statusCode: number, code: string, message: string, options?: APIErrorOptions) {\n super(statusCode, code, message, options);\n this.name = 'EndorsementRequiredError';\n }\n}\n\n/**\n * `insufficient_endorsements` (403): the signatures do not meet the group's\n * governance quorum (`effective_governance_threshold` distinct governing\n * members). The refusal is final for that idempotency key: the platform\n * replays it, and a resend under the same key with more signatures is\n * refused as a different request. Prepare again (a new key and intent) and\n * collect every signature again.\n */\nexport class InsufficientEndorsementsError extends APIError {\n /** Signatures the platform counted, when it said so. */\n readonly have: number | null;\n /** Signatures the quorum needs, when it said so. */\n readonly need: number | null;\n\n constructor(statusCode: number, code: string, message: string, options?: APIErrorOptions) {\n super(statusCode, code, message, options);\n this.name = 'InsufficientEndorsementsError';\n const m = /have (\\d+), need (\\d+)/.exec(message);\n this.have = m ? Number(m[1]) : null;\n this.need = m ? Number(m[2]) : null;\n }\n}\n\n/**\n * `stale_signer_group_version` (409): the group changed after the signatures\n * were made, so they can never verify. Read the group's `version`, build a\n * new intent under a new idempotency key, and sign again (or pass\n * `staleRetries` to the one-call helpers to do that automatically).\n */\nexport class StaleSignerGroupVersionError extends APIError {\n constructor(statusCode: number, code: string, message: string, options?: APIErrorOptions) {\n super(statusCode, code, message, options);\n this.name = 'StaleSignerGroupVersionError';\n }\n}\n\n/**\n * `below_threshold` (422): the removal would leave the group below a\n * threshold it must keep (at least one member, its governance quorum, or a\n * governed group's threshold). Add members first or remove fewer.\n */\nexport class BelowThresholdError extends APIError {\n constructor(statusCode: number, code: string, message: string, options?: APIErrorOptions) {\n super(statusCode, code, message, options);\n this.name = 'BelowThresholdError';\n }\n}\n\n/**\n * `invalid_governing_group` (409): the group's governing signer group is\n * missing or no longer valid, so no signature can satisfy its governance.\n */\nexport class InvalidGoverningGroupError extends APIError {\n constructor(statusCode: number, code: string, message: string, options?: APIErrorOptions) {\n super(statusCode, code, message, options);\n this.name = 'InvalidGoverningGroupError';\n }\n}\n\nconst GOVERNANCE_ERRORS = new Map<string, typeof APIError>([\n ['endorsement_required', EndorsementRequiredError],\n ['insufficient_endorsements', InsufficientEndorsementsError],\n ['stale_signer_group_version', StaleSignerGroupVersionError],\n ['below_threshold', BelowThresholdError],\n ['invalid_governing_group', InvalidGoverningGroupError],\n]);\n\n/**\n * Represents a transport-level error (network, timeout, etc.).\n */\nexport class TransportError extends Error {\n /** The underlying error that caused this transport error */\n readonly cause: Error | undefined;\n\n constructor(message: string, cause?: Error) {\n super(message);\n this.name = 'TransportError';\n this.cause = cause;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, TransportError);\n }\n }\n\n override toString(): string {\n if (this.cause) {\n return `TransportError: ${this.message} (caused by: ${this.cause.message})`;\n }\n return `TransportError: ${this.message}`;\n }\n}\n\n/**\n * Represents a configuration error.\n */\nexport class ConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigurationError';\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ConfigurationError);\n }\n }\n}\n","/**\n * Configuration types and validation for Dakota SDK.\n */\n\nimport { Environment, getEnvironmentURL } from './environment.js';\nimport { ConfigurationError } from './errors.js';\n\n/**\n * Authentication mode for API requests.\n */\nexport enum AuthMode {\n /** Automatically select the best auth method based on the endpoint */\n Auto = 'auto',\n /** Always use x-api-key header */\n APIKey = 'api_key',\n /** Always use X-Application-Token header */\n ApplicationToken = 'application_token',\n}\n\n/**\n * Retry policy configuration.\n */\nexport interface RetryPolicy {\n /** Maximum number of attempts including the initial request (default: 3) */\n maxAttempts: number;\n /** Initial backoff delay in milliseconds (default: 200) */\n initialBackoffMs: number;\n /** Maximum backoff delay in milliseconds (default: 2000) */\n maxBackoffMs: number;\n}\n\n/**\n * Logger interface for SDK logging.\n */\nexport interface Logger {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n}\n\n/**\n * Configuration options for DakotaClient.\n */\nexport interface DakotaClientConfig {\n /** API key for authentication (required unless applicationToken is provided) */\n apiKey?: string;\n /** Application token for authentication (alternative to apiKey) */\n applicationToken?: string;\n /** Target environment (default: Sandbox) */\n environment?: Environment;\n /** Override the base URL (takes precedence over environment) */\n baseURL?: string;\n /** Authentication mode (default: Auto) */\n authMode?: AuthMode;\n /**\n * Request timeout in milliseconds (default: 15000).\n *\n * Setting this explicitly applies it to EVERY request, including the\n * model-backed agentic endpoints that otherwise get a longer default\n * ({@link AGENTIC_MODEL_TIMEOUT_MS}) — so you keep full control, but a\n * global value tuned for fast reads will also cap agent turns. To keep\n * the long agentic default while tightening everything else, leave this\n * unset and pass `{ timeout }` per request instead.\n *\n * Note this is a per-ATTEMPT deadline: with the default retry policy a\n * timing-out request can be attempted up to `retryPolicy.maxAttempts`\n * times, so worst-case wall clock is roughly `timeout × maxAttempts`.\n */\n timeout?: number;\n /** Retry policy configuration */\n retryPolicy?: Partial<RetryPolicy>;\n /** Logger instance */\n logger?: Logger;\n /** Automatically generate idempotency keys for POST requests (default: true) */\n automaticIdempotency?: boolean;\n /** Custom idempotency key generator */\n idempotencyKeyGenerator?: () => string;\n /** Custom fetch implementation */\n fetch?: typeof fetch;\n}\n\n/**\n * Resolved configuration with all defaults applied.\n */\nexport interface ResolvedConfig {\n apiKey: string | null;\n applicationToken: string | null;\n baseURL: string;\n authMode: AuthMode;\n timeout: number;\n /**\n * Whether `timeout` came from the caller rather than the default.\n *\n * An explicit timeout is a deliberate choice and wins everywhere. An\n * inherited default does not, so endpoints that know they are slow (the\n * model-backed agentic ones) can raise it without overriding a value the\n * caller actually asked for.\n */\n timeoutWasExplicit: boolean;\n retryPolicy: RetryPolicy;\n logger: Logger;\n automaticIdempotency: boolean;\n idempotencyKeyGenerator: () => string;\n fetch: typeof fetch;\n}\n\n/**\n * Default per-request timeout (ms).\n *\n * Sized for ordinary CRUD reads and writes, which answer in well under a\n * second. It is deliberately NOT the deadline for the agentic endpoints\n * that call a model — see {@link AGENTIC_MODEL_TIMEOUT_MS}.\n */\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\n/**\n * Default per-request timeout (ms) for the agentic endpoints whose work is\n * a sequence of model calls: drafting proposals.\n *\n * A multi-payee drafting turn (\"pay these nine vendors every Friday\")\n * legitimately runs minutes — it reads payees, checks balances, drafts, and\n * revises, each a separate model round. Under the ordinary 15s deadline\n * those turns abort client-side while the server is still working, which\n * reads as flakiness rather than as a deadline: the simple turns finish in\n * time and the complex ones do not.\n *\n * Applies only when the caller did not set `timeout` on the client (an\n * explicit choice always wins) and can be overridden per request.\n */\nexport const AGENTIC_MODEL_TIMEOUT_MS = 180_000;\n\n/**\n * Default retry policy.\n */\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxAttempts: 3,\n initialBackoffMs: 200,\n maxBackoffMs: 2000,\n};\n\n/**\n * No-op logger that discards all messages.\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Console logger for development.\n */\nexport const consoleLogger: Logger = {\n debug: (msg, ...args) => console.debug(`[Dakota SDK] ${msg}`, ...args),\n info: (msg, ...args) => console.info(`[Dakota SDK] ${msg}`, ...args),\n warn: (msg, ...args) => console.warn(`[Dakota SDK] ${msg}`, ...args),\n error: (msg, ...args) => console.error(`[Dakota SDK] ${msg}`, ...args),\n};\n\n/**\n * Generate a UUID v4 for idempotency keys.\n */\nfunction generateUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Validate and resolve configuration with defaults.\n */\nexport function resolveConfig(config: DakotaClientConfig): ResolvedConfig {\n const authMode = config.authMode ?? AuthMode.Auto;\n\n // Validate authentication\n if (authMode === AuthMode.Auto) {\n if (!config.apiKey && !config.applicationToken) {\n throw new ConfigurationError('API key or application token is required');\n }\n } else if (authMode === AuthMode.APIKey) {\n if (!config.apiKey) {\n throw new ConfigurationError('API key is required when using AuthMode.APIKey');\n }\n } else if (authMode === AuthMode.ApplicationToken) {\n if (!config.applicationToken) {\n throw new ConfigurationError(\n 'Application token is required when using AuthMode.ApplicationToken'\n );\n }\n }\n\n // Resolve base URL\n let baseURL: string;\n if (config.baseURL) {\n baseURL = config.baseURL.replace(/\\/$/, ''); // Remove trailing slash\n // Validate URL\n try {\n new URL(baseURL);\n } catch {\n throw new ConfigurationError('Invalid base URL');\n }\n } else {\n const env = config.environment ?? Environment.Sandbox;\n baseURL = getEnvironmentURL(env);\n }\n\n // Validate timeout\n const timeoutWasExplicit = config.timeout !== undefined;\n const timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;\n if (timeout <= 0) {\n throw new ConfigurationError('Timeout must be greater than zero');\n }\n\n // Resolve retry policy\n const retryPolicy: RetryPolicy = {\n maxAttempts: config.retryPolicy?.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,\n initialBackoffMs: config.retryPolicy?.initialBackoffMs ?? DEFAULT_RETRY_POLICY.initialBackoffMs,\n maxBackoffMs: config.retryPolicy?.maxBackoffMs ?? DEFAULT_RETRY_POLICY.maxBackoffMs,\n };\n\n // Validate retry policy\n if (retryPolicy.maxAttempts <= 0) {\n throw new ConfigurationError('Retry max attempts must be greater than zero');\n }\n if (retryPolicy.initialBackoffMs <= 0) {\n throw new ConfigurationError('Retry initial backoff must be greater than zero');\n }\n if (retryPolicy.maxBackoffMs <= 0) {\n throw new ConfigurationError('Retry max backoff must be greater than zero');\n }\n if (retryPolicy.maxBackoffMs < retryPolicy.initialBackoffMs) {\n throw new ConfigurationError('Retry max backoff must be >= initial backoff');\n }\n\n return {\n apiKey: config.apiKey ?? null,\n applicationToken: config.applicationToken ?? null,\n baseURL,\n authMode,\n timeout,\n timeoutWasExplicit,\n retryPolicy,\n logger: config.logger ?? noopLogger,\n automaticIdempotency: config.automaticIdempotency ?? true,\n idempotencyKeyGenerator: config.idempotencyKeyGenerator ?? generateUUID,\n fetch: config.fetch ?? globalThis.fetch,\n };\n}\n","/**\n * HTTP transport layer with retry, authentication, and idempotency.\n */\n\nimport { ResolvedConfig, AuthMode } from './config.js';\nimport { APIError, TransportError } from './errors.js';\n\n/** Status codes that are safe to retry */\nconst RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);\n\n/** HTTP methods that are safe to retry without idempotency key */\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']);\n\n/**\n * HTTP methods that accept an idempotency key. Dakota's spec marks\n * `IdempotencyKeyHeader` as required on every mutating endpoint, so the\n * SDK must forward it for POST, PUT, PATCH, and DELETE. Earlier versions\n * only attached the header on POST and silently dropped it on PUT/PATCH.\n * DELETE is included because the platform's agentic detach endpoints\n * (e.g. DELETE /signer-groups/{id}/signers/{signer_id}) 400 without one.\n */\nconst IDEMPOTENT_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);\n\n/**\n * Request options for the transport layer.\n */\nexport interface TransportRequestOptions {\n method: string;\n path: string;\n body?: unknown;\n query?: Record<string, string | number | boolean | undefined>;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n signal?: AbortSignal;\n /**\n * Caller-supplied deadline (ms) for this one request. Beats everything —\n * it is the most specific statement of intent available.\n */\n timeout?: number;\n /**\n * The deadline (ms) this ENDPOINT wants when nobody has said otherwise —\n * how long its work actually takes. Used only when the caller passed no\n * per-request timeout AND set no explicit client-wide one, so it can\n * never override a deadline someone deliberately chose.\n */\n endpointTimeout?: number;\n /**\n * The operation's success response carries NO body — a bare 200, as\n * `POST /customers/{id}/applications/{id}/withdraw` answers. The transport\n * then resolves `undefined` without parsing, exactly as for a 204.\n *\n * Opt-in per operation on purpose. Every other call promises a document,\n * and for those an empty 2xx body is a fault (a proxy, a stalled upstream)\n * that must keep surfacing as an error and keep its retry: resolving\n * `undefined` there would move the failure to a TypeError far from the\n * call site.\n */\n noContent?: boolean;\n}\n\n/**\n * HTTP transport with retry, auth, and idempotency support.\n */\nexport class Transport {\n private readonly config: ResolvedConfig;\n\n constructor(config: ResolvedConfig) {\n this.config = config;\n }\n\n /**\n * Make an HTTP request with automatic retry and error handling.\n */\n async request<T>(options: TransportRequestOptions): Promise<T> {\n const { method, path, body, query, headers, idempotencyKey, signal, noContent } = options;\n\n // Build URL with query parameters\n const url = this.buildURL(path, query);\n\n // Build headers\n const requestHeaders = this.buildHeaders(method, path, headers, idempotencyKey);\n\n // Build request body\n const requestBody = body !== undefined ? JSON.stringify(body) : undefined;\n\n // Execute with retry\n return this.executeWithRetry<T>(\n url,\n {\n method,\n headers: requestHeaders,\n body: requestBody,\n signal,\n },\n this.resolveTimeout(options),\n noContent === true\n );\n }\n\n /**\n * Build the full URL with query parameters.\n */\n private buildURL(\n path: string,\n query?: Record<string, string | number | boolean | undefined>\n ): string {\n const url = new URL(path, this.config.baseURL);\n\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n return url.toString();\n }\n\n /**\n * Build request headers with authentication.\n */\n private buildHeaders(\n method: string,\n path: string,\n customHeaders?: Record<string, string>,\n idempotencyKey?: string\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': 'dakota-ts-sdk/1.0.0',\n ...customHeaders,\n };\n\n // Add authentication header\n this.addAuthHeader(headers, path);\n\n // Add idempotency key for mutating requests (POST, PUT, PATCH).\n if (IDEMPOTENT_METHODS.has(method)) {\n const key =\n idempotencyKey ??\n (this.config.automaticIdempotency ? this.config.idempotencyKeyGenerator() : undefined);\n if (key) {\n headers['x-idempotency-key'] = key;\n }\n }\n\n return headers;\n }\n\n /**\n * Add authentication header based on auth mode and path.\n */\n private addAuthHeader(headers: Record<string, string>, path: string): void {\n // Don't override existing auth headers\n if (headers['x-api-key'] || headers['x-application-token']) {\n return;\n }\n\n const { authMode, apiKey, applicationToken } = this.config;\n\n switch (authMode) {\n case AuthMode.APIKey:\n if (apiKey) {\n headers['x-api-key'] = apiKey;\n }\n break;\n\n case AuthMode.ApplicationToken:\n if (applicationToken) {\n headers['x-application-token'] = applicationToken;\n }\n break;\n\n case AuthMode.Auto:\n default:\n // For /applications routes, prefer application token\n if (path.startsWith('/applications') && applicationToken) {\n headers['x-application-token'] = applicationToken;\n } else if (apiKey) {\n headers['x-api-key'] = apiKey;\n } else if (applicationToken) {\n headers['x-application-token'] = applicationToken;\n }\n break;\n }\n }\n\n /**\n * Resolve the deadline for one request, most specific intent first:\n *\n * 1. the caller's per-request `timeout`\n * 2. an explicit client-wide `timeout`\n * 3. the endpoint's own default (slow endpoints raise their own)\n * 4. the client-wide default\n *\n * (2) sits above (3) on purpose: a caller who configured a timeout chose\n * it, and an endpoint must not quietly overrule that. (3) exists so the\n * far more common caller — the one who configured nothing — gets a\n * deadline that matches what the endpoint actually does.\n */\n private resolveTimeout(options: TransportRequestOptions): number {\n if (options.timeout !== undefined) {\n return options.timeout;\n }\n if (this.config.timeoutWasExplicit) {\n return this.config.timeout;\n }\n return options.endpointTimeout ?? this.config.timeout;\n }\n\n /**\n * Execute request with exponential backoff retry.\n *\n * `timeout` is per ATTEMPT, not per call: each attempt gets its own\n * deadline, so a request that keeps timing out can take up to\n * `timeout × maxAttempts` before it throws.\n */\n private async executeWithRetry<T>(\n url: string,\n init: RequestInit,\n timeout: number,\n noContent = false\n ): Promise<T> {\n const { maxAttempts, initialBackoffMs, maxBackoffMs } = this.config.retryPolicy;\n const method = init.method ?? 'GET';\n\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Declared outside the try so the catch can tell OUR deadline firing\n // apart from the caller aborting.\n let timedOut = false;\n try {\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeout);\n\n // Merge signals if provided\n const signal = init.signal\n ? this.mergeAbortSignals(init.signal, controller.signal)\n : controller.signal;\n\n this.logRequest(method, url, attempt);\n\n const response = await this.config.fetch(url, {\n ...init,\n signal,\n });\n\n clearTimeout(timeoutId);\n\n this.logResponse(method, url, response.status, attempt);\n\n // Check for successful response\n if (response.ok) {\n // Handle 204 No Content, and the operations that declare a bodiless\n // 200 (see `noContent`). Parsing an empty body as JSON throws, which\n // would reject a call whose side effect already happened.\n if (response.status === 204 || noContent) {\n return undefined as T;\n }\n return (await response.json()) as T;\n }\n\n // Convert to API error\n const apiError = await APIError.fromResponse(response);\n\n // Check if we should retry\n if (this.shouldRetry(response.status, method, init, attempt)) {\n lastError = apiError;\n const delay = this.calculateBackoff(attempt, response, initialBackoffMs, maxBackoffMs);\n this.config.logger.warn(\n `Request failed with ${response.status}, retrying in ${delay}ms (attempt ${attempt}/${maxAttempts})`\n );\n await this.sleep(delay);\n continue;\n }\n\n throw apiError;\n } catch (error) {\n if (error instanceof APIError) {\n throw error;\n }\n\n // Handle abort/timeout. Only OUR deadline firing is a timeout — an\n // AbortError from the caller's own signal is a cancellation, and\n // reporting that as \"timed out\" sends people hunting a deadline\n // that never elapsed.\n if (error instanceof Error && error.name === 'AbortError' && timedOut) {\n lastError = new TransportError(\n `Request timed out after ${timeout}ms. ` +\n `This is the SDK's client-side deadline, not a server error — raise it with ` +\n `\\`new DakotaClient({ timeout })\\`, or per call with \\`{ timeout }\\` in the ` +\n `request options. Agent conversations are the usual cause: pass ` +\n `\\`{ timeout }\\` to \\`newAgentConversation\\`.`,\n error\n );\n } else if (error instanceof Error && error.name === 'AbortError') {\n // The caller cancelled. Retrying would re-issue a request they\n // explicitly called off, so this is terminal.\n throw new TransportError('Request aborted by caller', error);\n } else if (error instanceof Error) {\n lastError = new TransportError('Network error', error);\n } else {\n lastError = new TransportError('Unknown error');\n }\n\n // Retry on network errors for safe methods\n if (this.shouldRetryNetworkError(method, init, attempt)) {\n const delay = this.calculateBackoff(attempt, null, initialBackoffMs, maxBackoffMs);\n this.config.logger.warn(\n `Network error, retrying in ${delay}ms (attempt ${attempt}/${maxAttempts})`\n );\n await this.sleep(delay);\n continue;\n }\n\n throw lastError;\n }\n }\n\n // All retries exhausted\n throw lastError ?? new TransportError('Request failed after all retries');\n }\n\n /**\n * Determine if a request should be retried based on status code.\n */\n private shouldRetry(status: number, method: string, init: RequestInit, attempt: number): boolean {\n if (attempt >= this.config.retryPolicy.maxAttempts) {\n return false;\n }\n\n if (!RETRYABLE_STATUS_CODES.has(status)) {\n return false;\n }\n\n // Safe methods can always be retried\n if (SAFE_METHODS.has(method)) {\n return true;\n }\n\n // Mutating methods (POST/PUT/PATCH) can be retried if we have an\n // idempotency key. PUT/PATCH are already in SAFE_METHODS so they hit\n // the branch above; this catches POST.\n if (IDEMPOTENT_METHODS.has(method) && init.headers) {\n const headers = init.headers as Record<string, string>;\n return !!headers['x-idempotency-key'];\n }\n\n return false;\n }\n\n /**\n * Determine if a network error should be retried.\n */\n private shouldRetryNetworkError(method: string, init: RequestInit, attempt: number): boolean {\n if (attempt >= this.config.retryPolicy.maxAttempts) {\n return false;\n }\n\n // Safe methods can always be retried\n if (SAFE_METHODS.has(method)) {\n return true;\n }\n\n // Mutating methods (POST/PUT/PATCH) can be retried if we have an\n // idempotency key.\n if (IDEMPOTENT_METHODS.has(method) && init.headers) {\n const headers = init.headers as Record<string, string>;\n return !!headers['x-idempotency-key'];\n }\n\n return false;\n }\n\n /**\n * Calculate backoff delay with jitter.\n */\n private calculateBackoff(\n attempt: number,\n response: Response | null,\n initialBackoffMs: number,\n maxBackoffMs: number\n ): number {\n // Check for Retry-After header\n if (response) {\n const retryAfter = response.headers.get('retry-after');\n if (retryAfter) {\n const seconds = parseInt(retryAfter, 10);\n if (!isNaN(seconds)) {\n return seconds * 1000;\n }\n // Try parsing as HTTP date\n const date = Date.parse(retryAfter);\n if (!isNaN(date)) {\n return Math.max(0, date - Date.now());\n }\n }\n }\n\n // Exponential backoff with jitter (±20%)\n const exponentialDelay = initialBackoffMs * Math.pow(2, attempt - 1);\n const cappedDelay = Math.min(exponentialDelay, maxBackoffMs);\n const jitter = cappedDelay * 0.2 * (Math.random() * 2 - 1);\n return Math.round(cappedDelay + jitter);\n }\n\n /**\n * Merge multiple abort signals.\n */\n private mergeAbortSignals(signal1: AbortSignal, signal2: AbortSignal): AbortSignal {\n const controller = new AbortController();\n\n const abort = () => controller.abort();\n\n signal1.addEventListener('abort', abort);\n signal2.addEventListener('abort', abort);\n\n if (signal1.aborted || signal2.aborted) {\n controller.abort();\n }\n\n return controller.signal;\n }\n\n /**\n * Sleep for the specified duration.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n /**\n * Log outgoing request.\n */\n private logRequest(method: string, url: string, attempt: number): void {\n this.config.logger.debug(\n `Request: ${method} ${url}${attempt > 1 ? ` (attempt ${attempt})` : ''}`\n );\n }\n\n /**\n * Log response.\n */\n private logResponse(method: string, url: string, status: number, attempt: number): void {\n this.config.logger.debug(\n `Response: ${method} ${url} -> ${status}${attempt > 1 ? ` (attempt ${attempt})` : ''}`\n );\n }\n}\n","/**\n * Pagination utilities with async iterators.\n */\n\n/**\n * Pagination metadata from API responses.\n */\nexport interface PaginationMeta {\n total_count?: number;\n has_more_after?: boolean;\n has_more_before?: boolean;\n}\n\n/**\n * Paginated response structure.\n */\nexport interface PaginatedResponse<T> {\n data: T[];\n meta?: PaginationMeta;\n}\n\n/**\n * Parameters for paginated requests.\n */\nexport interface PaginationParams {\n starting_after?: string;\n ending_before?: string;\n limit?: number;\n}\n\n/**\n * Function to fetch a page of results.\n */\nexport type PageFetcher<T> = (cursor?: string) => Promise<PaginatedResponse<T>>;\n\n/**\n * Function to extract cursor from an item.\n */\nexport type CursorExtractor<T> = (item: T) => string;\n\n/**\n * Default cursor extractor that uses the 'id' field.\n */\nexport function defaultCursorExtractor<T extends { id?: string }>(item: T): string {\n if (!item.id) {\n throw new Error('Item does not have an id field for cursor extraction');\n }\n return item.id;\n}\n\n/**\n * Async iterator for paginated results.\n */\nexport class PaginatedIterator<T> implements AsyncIterable<T> {\n private readonly fetcher: PageFetcher<T>;\n private readonly cursorExtractor: CursorExtractor<T>;\n private cursor: string | undefined;\n private buffer: T[] = [];\n private hasMore = true;\n private started = false;\n\n constructor(fetcher: PageFetcher<T>, cursorExtractor?: CursorExtractor<T>) {\n this.fetcher = fetcher;\n this.cursorExtractor = cursorExtractor ?? (defaultCursorExtractor as CursorExtractor<T>);\n }\n\n /**\n * Implement async iterator protocol.\n */\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next: async (): Promise<IteratorResult<T>> => {\n const item = await this.next();\n if (item === null) {\n return { done: true, value: undefined };\n }\n return { done: false, value: item };\n },\n };\n }\n\n /**\n * Get the next item, or null if no more items.\n */\n async next(): Promise<T | null> {\n // If buffer has items, return next one\n if (this.buffer.length > 0) {\n return this.buffer.shift()!;\n }\n\n // If no more pages, we're done\n if (!this.hasMore && this.started) {\n return null;\n }\n\n // Fetch next page\n await this.fetchNextPage();\n\n // Return first item from buffer, or null if empty\n if (this.buffer.length > 0) {\n return this.buffer.shift()!;\n }\n\n return null;\n }\n\n /**\n * Collect all items into an array.\n */\n async toArray(): Promise<T[]> {\n const items: T[] = [];\n for await (const item of this) {\n items.push(item);\n }\n return items;\n }\n\n /**\n * Get the first item, or null if none.\n */\n async first(): Promise<T | null> {\n return this.next();\n }\n\n /**\n * Fetch the next page of results.\n */\n private async fetchNextPage(): Promise<void> {\n this.started = true;\n\n const response = await this.fetcher(this.cursor);\n this.buffer = response.data ?? [];\n\n // Update cursor for next page\n if (this.buffer.length > 0) {\n const lastItem = this.buffer[this.buffer.length - 1];\n if (lastItem) {\n this.cursor = this.cursorExtractor(lastItem);\n }\n }\n\n // Check if there are more pages\n this.hasMore = response.meta?.has_more_after ?? false;\n }\n}\n\n/**\n * Create a paginated iterator.\n */\nexport function paginate<T>(\n fetcher: PageFetcher<T>,\n cursorExtractor?: CursorExtractor<T>\n): PaginatedIterator<T> {\n return new PaginatedIterator(fetcher, cursorExtractor);\n}\n","/**\n * Base resource class for API resources.\n */\n\nimport { Transport } from '../transport.js';\nimport { PaginatedIterator, paginate, PageFetcher, CursorExtractor } from '../pagination.js';\n\n/**\n * Base class for API resources.\n */\nexport abstract class BaseResource {\n protected readonly transport: Transport;\n\n constructor(transport: Transport) {\n this.transport = transport;\n }\n\n /**\n * Create a paginated iterator for a list endpoint.\n *\n * `inspectMeta` is called with each page's raw `meta` before the page is\n * yielded, for endpoints whose meta says something the caller must act on.\n * Throw from it to fail the page.\n */\n protected paginate<T>(\n path: string,\n params?: Record<string, unknown>,\n cursorExtractor?: CursorExtractor<T>,\n inspectMeta?: (meta: Record<string, unknown> | undefined) => void\n ): PaginatedIterator<T> {\n const fetcher: PageFetcher<T> = async (cursor?: string) => {\n const query: Record<string, string | number | boolean | undefined> = {};\n\n // Add pagination params\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n query[key] = value as string | number | boolean;\n }\n }\n }\n\n if (cursor) {\n query.starting_after = cursor;\n }\n\n const response = await this.transport.request<\n | {\n data: T[];\n meta?: { has_more_after?: boolean };\n }\n | T[]\n >({\n method: 'GET',\n path,\n query,\n });\n\n // Not every list endpoint returns the `{data, meta}` envelope: a few\n // answer with a BARE ARRAY (GET /mandates and\n // GET /wallets/{id}/signer-groups today). Reading `.data` off those\n // yields undefined, which the old code turned into an empty page —\n // so the iterator finished immediately and the caller saw zero\n // results with no error, for records that plainly exist. Treat an\n // array as one complete page: there is no cursor to follow, so\n // `meta` is absent and `has_more_after` correctly reads false.\n if (Array.isArray(response)) {\n inspectMeta?.(undefined);\n return { data: response, meta: undefined };\n }\n\n inspectMeta?.(response.meta as Record<string, unknown> | undefined);\n\n return {\n data: response.data ?? [],\n meta: response.meta,\n };\n };\n\n return paginate(fetcher, cursorExtractor);\n }\n}\n","/**\n * Customers resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n BulkImportSumsubTokensRequest,\n BulkImportSumsubTokensResponse,\n Customer,\n CustomerCapabilities,\n CustomerCreateRequest,\n CustomerCreateResponse,\n CustomerListParams,\n CustomerPage,\n CustomerReEngagementResponse,\n ImportPersonaTokensRequest,\n ImportPersonaTokensResponse,\n PersonaImportJob,\n PersonaImportJobListParams,\n PersonaImportJobParams,\n PersonaImportJobsPage,\n RequestOptions,\n SubClientSummary,\n UpdateCustomerSubClientRequest,\n WithdrawApplicationRequest,\n} from '../types.js';\n\n/**\n * Customers API resource.\n */\nexport class CustomersResource extends BaseResource {\n /**\n * Create a new customer.\n *\n * Creates a customer record and initiates KYB onboarding.\n * Returns a URL where the customer can complete verification.\n *\n * @param data - Customer creation data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Created customer with KYB onboarding URL\n *\n * @example\n * ```typescript\n * const customer = await client.customers.create({\n * name: 'Acme Corp',\n * customerType: 'business',\n * externalId: 'your-internal-id',\n * });\n *\n * // With custom idempotency key\n * const customer = await client.customers.create(\n * { name: 'Acme Corp', customerType: 'business' },\n * { idempotencyKey: 'create-acme-corp-001' }\n * );\n * console.log(customer.applicationUrl); // KYB onboarding URL\n *\n * // Designate as a sub-client at creation (ENG-2454).\n * // `is_sub_client` can only be set here — a regular customer cannot\n * // be promoted afterwards. Cannot be combined with `sub_client_id`.\n * const subClient = await client.customers.create({\n * name: 'Partner Corp',\n * customer_type: 'business',\n * is_sub_client: true,\n * });\n * ```\n */\n async create(\n data: CustomerCreateRequest,\n options?: RequestOptions\n ): Promise<CustomerCreateResponse> {\n return this.transport.request<CustomerCreateResponse>({\n method: 'POST',\n path: '/customers',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List all customers.\n *\n * Returns a paginated async iterator over customer records.\n *\n * @param params - Optional filter and pagination parameters\n * @returns Async iterator of customers\n *\n * @example\n * ```typescript\n * // Iterate through all customers\n * for await (const customer of client.customers.list()) {\n * console.log(customer.name);\n * }\n *\n * // With filters\n * const active = client.customers.list({ kyb_status: 'active' });\n *\n * // Several statuses at once — one comma-separated string, not an array\n * const needsAttention = client.customers.list({\n * status: 'info_requested,frozen',\n * });\n *\n * // Collect all to array\n * const all = await client.customers.list().toArray();\n * ```\n */\n list(params?: CustomerListParams): PaginatedIterator<Customer> {\n return this.paginate<Customer>('/customers', params);\n }\n\n /**\n * One page of customers, with the per-status counts.\n *\n * {@link list} iterates rows and drops the envelope, so `status_counts` —\n * the counts a dashboard's status header renders — is unreachable through\n * it. This returns the raw page instead: same filters, one request, no\n * iteration.\n *\n * The counts are computed under the same filters but IGNORING the `status`\n * selection, so every chip keeps its count while one of them is the active\n * filter.\n *\n * @param params - The same filters {@link list} accepts\n * @returns One page: rows, pagination meta, and `status_counts`\n *\n * @example\n * ```typescript\n * const page = await client.customers.listPage({ limit: 25 });\n * console.log(page.status_counts?.info_requested ?? 0);\n * for (const customer of page.data) {\n * console.log(customer.name, customer.status);\n * }\n * ```\n */\n async listPage(params?: CustomerListParams): Promise<CustomerPage> {\n const page = await this.transport.request<CustomerPage>({\n method: 'GET',\n path: '/customers',\n query: params as Record<string, string | number | boolean | undefined> | undefined,\n });\n return { ...page, data: page.data ?? [] };\n }\n\n /**\n * Get a customer by ID.\n *\n * @param customerId - Customer ID (KSUID)\n * @returns Customer record\n *\n * @example\n * ```typescript\n * const customer = await client.customers.get('cust_abc123');\n * console.log(customer.kybStatus);\n * ```\n */\n async get(customerId: string): Promise<Customer> {\n return this.transport.request<Customer>({\n method: 'GET',\n path: `/customers/${customerId}`,\n });\n }\n\n /**\n * Delete a customer record.\n *\n * Soft-deletes the customer. Blocked with a 409 if the customer still has\n * associated accounts, or is referenced as a sub-client by another customer.\n *\n * @param customerId - Customer ID (KSUID)\n *\n * @example\n * ```typescript\n * await client.customers.delete('cust_abc123');\n * ```\n */\n async delete(customerId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/customers/${customerId}`,\n });\n }\n\n /**\n * List a customer's capabilities and what is still needed to unlock each.\n *\n * Returns the customer's rails (e.g. `international_wire`) with a status and\n * the OUTSTANDING requirements — terms to accept, documents to upload — that\n * gate them. Partner-agnostic: requirements are keyed by an opaque terms id\n * or document type, never a provider or partner name.\n *\n * @param customerId - Customer ID (KSUID)\n * @returns The customer's capabilities and their outstanding requirements\n *\n * @example\n * ```typescript\n * const { capabilities } = await client.customers.getCapabilities(customerId);\n * for (const cap of capabilities) {\n * if (cap.status !== 'action_required') continue;\n * for (const req of cap.requirements) {\n * console.log(`${cap.capability}: ${req.title} → ${req.url}`);\n * }\n * }\n * ```\n */\n async getCapabilities(customerId: string): Promise<CustomerCapabilities> {\n return this.transport.request<CustomerCapabilities>({\n method: 'GET',\n path: `/customers/${customerId}/capabilities`,\n });\n }\n\n /**\n * Mint a fresh application link for re-engaging an APPROVED customer.\n *\n * Issues a new onboarding token for an existing approved customer's\n * application and returns the rebuilt `application_url` — use it when the\n * original token has expired and the customer needs to come back through\n * the hosted flow (e.g. to accept outstanding partner disclosures).\n *\n * @param customerId - Customer ID (KSUID)\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The rebuilt application URL\n *\n * @example\n * ```typescript\n * const { application_url } = await client.customers.reEngage(customerId);\n * ```\n */\n async reEngage(\n customerId: string,\n options?: RequestOptions\n ): Promise<CustomerReEngagementResponse> {\n return this.transport.request<CustomerReEngagementResponse>({\n method: 'POST',\n path: `/customers/${customerId}/re-engagement`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Withdraw a customer's onboarding application.\n *\n * Closes the application when the customer will not or cannot continue —\n * for example after a request for information they chose not to answer.\n *\n * Withdrawal is FINAL. The application and its entities are recorded as\n * withdrawn, the customer's `status` becomes `withdrawn`, and onboarding\n * that customer again requires a new application. An application that\n * already has a decision returns a 409.\n *\n * Emits `customer.application.withdrawn`.\n *\n * @param customerId - Customer ID (KSUID)\n * @param applicationId - The customer's onboarding application ID\n * @param data - Optional `reason`, recorded for audit and shown to reviewers\n * @param options - Request options (e.g., custom idempotency key)\n *\n * @example\n * ```typescript\n * await client.customers.withdrawApplication(customerId, applicationId, {\n * reason: 'Customer opted not to proceed',\n * });\n * ```\n */\n async withdrawApplication(\n customerId: string,\n applicationId: string,\n data: WithdrawApplicationRequest = {},\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'POST',\n path: `/customers/${customerId}/applications/${applicationId}/withdraw`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n // The platform answers a bare 200 with no body.\n noContent: true,\n });\n }\n\n /**\n * Update the sub-client association for a customer.\n *\n * Associates or disassociates a customer with a sub-client.\n * Set `sub_client_id` to associate, or set it to `null` to disassociate.\n *\n * @deprecated The sub-client association can only be set when a customer is\n * created (`is_sub_client` / `sub_client_id` on `create`) and can no longer\n * be changed afterwards — this endpoint now returns 400.\n *\n * @param customerId - Customer ID (KSUID)\n * @param data - Sub-client association data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Updated customer record\n *\n * @example\n * ```typescript\n * // Associate customer with a sub-client\n * const customer = await client.customers.updateSubClient('cust_abc123', {\n * sub_client_id: 'cust_sub456',\n * });\n *\n * // Disassociate customer from sub-client\n * const customer = await client.customers.updateSubClient('cust_abc123', {\n * sub_client_id: null,\n * });\n * ```\n */\n async updateSubClient(\n customerId: string,\n data: UpdateCustomerSubClientRequest,\n options?: RequestOptions\n ): Promise<Customer> {\n return this.transport.request<Customer>({\n method: 'PATCH',\n path: `/customers/${customerId}/sub-client`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a summary of all sub-clients and their associated customer counts.\n *\n * @returns Array of sub-client summaries\n *\n * @example\n * ```typescript\n * const summaries = await client.customers.getSubClientSummary();\n * for (const summary of summaries) {\n * console.log(`${summary.sub_client_name}: ${summary.customer_count} customers`);\n * }\n * ```\n */\n async getSubClientSummary(): Promise<SubClientSummary[]> {\n const response = await this.transport.request<{ data: SubClientSummary[] }>({\n method: 'GET',\n path: '/customers/sub-client-summary',\n });\n return response.data;\n }\n\n /**\n * Bulk-import customers from Sumsub share tokens.\n *\n * Exchanges one or more Sumsub share tokens for Dakota customers + applications.\n * The response surfaces per-token results — individual tokens can fail while\n * others succeed.\n *\n * @param data - Bulk-import request containing the share tokens to redeem\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Bulk-import summary with per-token results\n *\n * @example\n * ```typescript\n * const result = await client.customers.bulkImportFromSumsubTokens({\n * tokens: ['_act-sbx-jwt-...', '_act-sbx-jwt-...'],\n * });\n * console.log(`Imported ${result.succeeded}/${result.total}`);\n * for (const r of result.results ?? []) {\n * if (!r.success) console.error(r.name, r.error);\n * }\n * ```\n */\n async bulkImportFromSumsubTokens(\n data: BulkImportSumsubTokensRequest,\n options?: RequestOptions\n ): Promise<BulkImportSumsubTokensResponse> {\n return this.transport.request<BulkImportSumsubTokensResponse>({\n method: 'POST',\n path: '/customers/bulk-import-sumsub-tokens',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Import customers from Persona Connect share tokens (`cnst_...`).\n *\n * Unlike the Sumsub import, Persona redemption is asynchronous on Persona's\n * side, so this returns a JOB immediately (HTTP 202). Poll\n * `getPersonaImportJob` for per-token results. Up to 5,000 tokens per\n * request — split larger migrations into multiple batches.\n *\n * Tokens are validated and de-duplicated up front, and a skipped token\n * never blocks an accepted one. A `skipped` entry is about the token STRING\n * (malformed, duplicated in the batch, or already imported) — it is never a\n * compliance decision about a person or application.\n *\n * @param data - The share tokens to import\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The queued job, with any tokens that could not be enqueued\n *\n * @example\n * ```typescript\n * const job = await client.customers.importPersonaTokens({\n * tokens: ['cnst_ABC123def456', 'cnst_GHI789jkl012'],\n * });\n * console.log(`${job.accepted}/${job.total} queued as ${job.job_id}`);\n * ```\n */\n async importPersonaTokens(\n data: ImportPersonaTokensRequest,\n options?: RequestOptions\n ): Promise<ImportPersonaTokensResponse> {\n return this.transport.request<ImportPersonaTokensResponse>({\n method: 'POST',\n path: '/customers/import-persona-tokens',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List this client's Persona share-token import jobs, newest first.\n *\n * This endpoint pages on its own cursor (`starting_after` + `has_more`), not\n * the standard list envelope, so it returns a single page rather than an\n * async iterator.\n *\n * @param params - Optional `limit` and `starting_after` job-id cursor\n * @returns One page of job summaries plus a `has_more` flag\n *\n * @example\n * ```typescript\n * const { jobs, has_more } = await client.customers.listPersonaImportJobs({ limit: 20 });\n * ```\n */\n async listPersonaImportJobs(params?: PersonaImportJobListParams): Promise<PersonaImportJobsPage> {\n return this.transport.request<PersonaImportJobsPage>({\n method: 'GET',\n path: '/customers/persona-import-jobs',\n query: { ...params },\n });\n }\n\n /**\n * Get a Persona import job's status and its per-token results.\n *\n * Result rows page on a row-index cursor: pass the last row's `index` as\n * `results_after_index` while `has_more_results` is true.\n *\n * @param jobId - Import job ID (`pij_...`)\n * @param params - Optional `results_limit` (1-500) and `results_after_index`\n * @returns Job status, row counts, and one page of result rows\n *\n * @example\n * ```typescript\n * let after: number | undefined;\n * do {\n * const job = await client.customers.getPersonaImportJob(jobId, {\n * results_after_index: after,\n * });\n * for (const row of job.results ?? []) {\n * if (row.state === 'failed') console.error(row.token, row.error);\n * after = row.index;\n * }\n * if (!job.has_more_results) break;\n * } while (true);\n * ```\n */\n async getPersonaImportJob(\n jobId: string,\n params?: PersonaImportJobParams\n ): Promise<PersonaImportJob> {\n return this.transport.request<PersonaImportJob>({\n method: 'GET',\n path: `/customers/persona-import-jobs/${jobId}`,\n query: { ...params },\n });\n }\n}\n","/**\n * Recipients resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Recipient,\n RecipientRequest,\n RecipientUpdateRequest,\n RecipientListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Recipients API resource.\n */\nexport class RecipientsResource extends BaseResource {\n /**\n * Create a new recipient for a customer.\n *\n * Recipients represent entities that can receive payments.\n *\n * @param customerId - Customer ID\n * @param data - Recipient creation data\n * @returns Created recipient\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.create(customerId, {\n * name: 'Treasury Account',\n * external_id: 'vendor-1177', // optional: your own label, not unique\n * });\n * ```\n */\n async create(\n customerId: string,\n data: RecipientRequest,\n options?: RequestOptions\n ): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'POST',\n path: `/customers/${customerId}/recipients`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List recipients for a customer.\n *\n * @param customerId - Customer ID\n * @param params - Pagination parameters and an optional `external_id` filter\n * @returns Async iterator of recipients\n *\n * @example\n * ```typescript\n * for await (const recipient of client.recipients.list(customerId)) {\n * console.log(recipient.name);\n * }\n *\n * // Look up recipients by your own label\n * const matches = await client.recipients\n * .list(customerId, { external_id: 'vendor-1177' })\n * .toArray();\n * ```\n */\n list(customerId: string, params?: RecipientListParams): PaginatedIterator<Recipient> {\n return this.paginate<Recipient>(`/customers/${customerId}/recipients`, params);\n }\n\n /**\n * Get a recipient by ID.\n *\n * @param recipientId - Recipient ID\n * @returns Recipient record\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.get(recipientId);\n * ```\n */\n async get(recipientId: string): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'GET',\n path: `/recipients/${recipientId}`,\n });\n }\n\n /**\n * Update a recipient.\n *\n * @param recipientId - Recipient ID\n * @param data - Update data\n * @returns Updated recipient\n *\n * @example\n * ```typescript\n * const recipient = await client.recipients.update(recipientId, {\n * name: 'Updated Name',\n * });\n * ```\n */\n async update(\n recipientId: string,\n data: RecipientUpdateRequest,\n options?: RequestOptions\n ): Promise<Recipient> {\n return this.transport.request<Recipient>({\n method: 'PUT',\n path: `/recipients/${recipientId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a recipient.\n *\n * @param recipientId - Recipient ID\n *\n * @example\n * ```typescript\n * await client.recipients.delete(recipientId);\n * ```\n */\n async delete(recipientId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/recipients/${recipientId}`,\n });\n }\n}\n","/**\n * RFC 8785 (JCS) canonical JSON — the exact bytes the platform signs.\n *\n * A payload canonicalized here matches the platform's `enc.C14nJSON`\n * (json.Marshal + jsoncanonicalizer.Transform) byte-for-byte, so a\n * signature produced from the result verifies server-side.\n *\n * This implementation covers the value shapes the SDK ever puts into a\n * signed payload: nulls, booleans, finite integers/floats, strings,\n * arrays, and plain object maps. It intentionally does NOT handle\n * non-integer numbers with fractional parts differently from\n * JSON.stringify, because every mandate/endorsement payload the SDK\n * produces uses only integers, strings, arrays, and object maps — decimal\n * amounts are always sent as strings.\n */\n\n/**\n * RFC 8785 (JCS) canonicalize `value` and return its bytes as a UTF-8 string.\n *\n * @throws if `value` contains a non-finite number, a Symbol, a bigint, or a\n * circular reference — any of which cannot be encoded to canonical JSON.\n */\nexport function canonicalJSON(value: unknown): string {\n return canonicalize(value);\n}\n\nfunction canonicalize(value: unknown): string {\n if (value === null || value === undefined) {\n return 'null';\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new TypeError(`canonical JSON: non-finite number ${value}`);\n }\n // JSON.stringify already emits ES6 Number.prototype.toString() for\n // finite numbers, which is exactly what RFC 8785 § 3.2.2.3 mandates.\n return JSON.stringify(value);\n }\n if (typeof value === 'string') {\n // JSON.stringify handles JSON escape sequences per RFC 8259, matching\n // JCS's string-escape rules (§ 3.2.2.2).\n return JSON.stringify(value);\n }\n if (typeof value === 'bigint') {\n // BigInts have no unambiguous number representation for JSON;\n // fail loudly rather than produce bytes that won't verify.\n throw new TypeError('canonical JSON: bigint values are not supported');\n }\n if (Array.isArray(value)) {\n const parts = value.map((item) => canonicalize(item));\n return `[${parts.join(',')}]`;\n }\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // JCS sorts object member keys by their UTF-16 code-unit order,\n // which is exactly what a JavaScript `Array.prototype.sort()` on\n // strings produces (§ 3.2.3).\n const keys = Object.keys(obj).sort();\n const parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(obj[key])}`);\n return `{${parts.join(',')}}`;\n }\n throw new TypeError(`canonical JSON: unsupported value type ${typeof value}`);\n}\n","/**\n * Byte helpers that work the same in browsers, React Native and Node, with\n * no `Buffer` and no `node:` import, so the governance entry point stays\n * bundle-safe.\n */\n\nconst B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/** Standard base64 (RFC 4648 §4), padded. */\nexport function bytesToBase64(bytes: Uint8Array): string {\n let out = '';\n let i = 0;\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!;\n out +=\n B64_ALPHABET[(n >> 18) & 63]! +\n B64_ALPHABET[(n >> 12) & 63]! +\n B64_ALPHABET[(n >> 6) & 63]! +\n B64_ALPHABET[n & 63]!;\n }\n const rest = bytes.length - i;\n if (rest === 1) {\n const n = bytes[i]! << 16;\n out += B64_ALPHABET[(n >> 18) & 63]! + B64_ALPHABET[(n >> 12) & 63]! + '==';\n } else if (rest === 2) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8);\n out +=\n B64_ALPHABET[(n >> 18) & 63]! +\n B64_ALPHABET[(n >> 12) & 63]! +\n B64_ALPHABET[(n >> 6) & 63]! +\n '=';\n }\n return out;\n}\n\n/** base64url (RFC 4648 §5), unpadded — the encoding WebAuthn uses. */\nexport function bytesToBase64url(bytes: Uint8Array): string {\n return stripPadding(bytesToBase64(bytes).replace(/\\+/g, '-').replace(/\\//g, '_'));\n}\n\n// Trailing '=' removal without a regex: an unanchored /=+$/ backtracks\n// quadratically on a long run of '=' that is not at the end.\nfunction stripPadding(s: string): string {\n let end = s.length;\n while (end > 0 && s.charCodeAt(end - 1) === 61 /* '=' */) end--;\n return s.slice(0, end);\n}\n\n/**\n * Decode base64 in either alphabet, padded or not.\n *\n * @throws on characters outside both alphabets or an impossible length.\n */\nexport function base64ToBytes(input: string): Uint8Array {\n const s = stripPadding(input.replace(/-/g, '+').replace(/_/g, '/'));\n if (!/^[A-Za-z0-9+/]*$/.test(s) || s.length % 4 === 1) {\n throw new TypeError('invalid base64 or base64url string');\n }\n const out = new Uint8Array(Math.floor((s.length * 3) / 4));\n let o = 0;\n for (let i = 0; i < s.length; i += 4) {\n const a = B64_ALPHABET.indexOf(s[i]!);\n const b = B64_ALPHABET.indexOf(s[i + 1]!);\n const c = i + 2 < s.length ? B64_ALPHABET.indexOf(s[i + 2]!) : 0;\n const d = i + 3 < s.length ? B64_ALPHABET.indexOf(s[i + 3]!) : 0;\n const n = (a << 18) | (b << 12) | (c << 6) | d;\n out[o++] = (n >> 16) & 255;\n if (i + 2 < s.length) out[o++] = (n >> 8) & 255;\n if (i + 3 < s.length) out[o++] = n & 255;\n }\n return out;\n}\n\n/** UTF-8 bytes of a string. */\nexport function utf8(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\n/** A copy of any BufferSource as a plain Uint8Array. */\nexport function toBytes(source: ArrayBuffer | ArrayBufferView): Uint8Array {\n // isView / toString instead of instanceof: buffers from another realm\n // (an iframe, jsdom, some React Native bridges) fail `instanceof`.\n if (ArrayBuffer.isView(source)) {\n return new Uint8Array(source.buffer, source.byteOffset, source.byteLength).slice();\n }\n if (Object.prototype.toString.call(source) === '[object ArrayBuffer]') {\n return new Uint8Array((source as ArrayBuffer).slice(0));\n }\n throw new TypeError('expected an ArrayBuffer or a typed array');\n}\n","/**\n * Canonical intents for signer-group governance changes.\n *\n * A change to a governed signer group (adding or removing members, changing\n * who governs it) needs signatures from the group's governing members. Each\n * signature covers the RFC 8785 (JCS) canonical JSON of an \"intent\" that the\n * policy engine rebuilds from the request and checks byte-for-byte. A wrong\n * key, a missing `signer_group_version`, or an idempotency key that differs\n * from the `X-Idempotency-Key` header gives a signature that never verifies,\n * so build the intent here rather than by hand.\n *\n * The builders are pure (no I/O, no `node:` import), so they run in a\n * browser or mobile app as well as on a server. The byte equality with the\n * policy engine is pinned by golden vectors in the test suite.\n */\n\nimport { canonicalJSON } from '../agentic/canonicalize.js';\nimport { utf8 } from './encoding.js';\n\n/** `add_signers_to_group`: endorses adding members to a signer group. */\nexport interface AddSignersToGroupIntent {\n readonly type: 'add_signers_to_group';\n readonly signer_group_id: string;\n readonly new_member_keys: readonly string[];\n readonly signer_group_version: number;\n readonly idempotency_key: string;\n}\n\n/**\n * `remove_signers_from_group`: endorses removing members. Note the group id\n * key is `group_id` here, not `signer_group_id`.\n */\nexport interface RemoveSignersFromGroupIntent {\n readonly type: 'remove_signers_from_group';\n readonly group_id: string;\n readonly members_to_remove: readonly string[];\n readonly signer_group_version: number;\n readonly idempotency_key: string;\n}\n\n/**\n * `update_signer_group_governance`: endorses replacing a group's governance\n * settings. An optional setting is ABSENT when not set (never null), and an\n * absent setting is cleared by the change.\n */\nexport interface UpdateSignerGroupGovernanceIntent {\n readonly type: 'update_signer_group_governance';\n readonly signer_group_id: string;\n readonly signer_group_version: number;\n readonly idempotency_key: string;\n readonly governance_threshold?: number;\n readonly governance_signer_group_id?: string;\n}\n\n/** `create_crypto_destination`: endorses creating a crypto destination. */\nexport interface CreateCryptoDestinationIntent {\n readonly type: 'create_crypto_destination';\n readonly recipient_id: string;\n readonly network_id: string;\n readonly address: string;\n readonly signer_group_id: string;\n readonly idempotency_key: string;\n}\n\n/** Any intent this module builds. */\nexport type GovernanceIntent =\n | AddSignersToGroupIntent\n | RemoveSignersFromGroupIntent\n | UpdateSignerGroupGovernanceIntent\n | CreateCryptoDestinationIntent;\n\n/**\n * An intent together with the exact bytes its signatures cover.\n *\n * - `canonical` is the canonical JSON as a string (handy to store or log).\n * - `bytes` is its UTF-8 encoding: what an ES256 signer signs, and what a\n * WebAuthn `navigator.credentials.get()` call takes as its `challenge`.\n */\nexport interface CanonicalIntent<T extends GovernanceIntent = GovernanceIntent> {\n readonly intent: T;\n readonly canonical: string;\n readonly bytes: Uint8Array;\n}\n\nconst LOWERCASE_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\n/**\n * Check that `key` is a lowercase UUID, the only idempotency key the platform\n * accepts on these endpoints. The same key goes into the intent and the\n * `X-Idempotency-Key` header, so an uppercase key would be refused even\n * though its signature is otherwise valid.\n *\n * @throws TypeError when it is not.\n */\nexport function assertIdempotencyKey(key: string): void {\n if (typeof key !== 'string' || !LOWERCASE_UUID.test(key)) {\n throw new TypeError(\n `idempotency key must be a lowercase UUID (got ${JSON.stringify(key)}); the platform refuses any other form`\n );\n }\n}\n\n/**\n * A fresh lowercase v4 UUID for a governance change, from the platform's\n * cryptographic random source (`crypto.randomUUID`, else\n * `crypto.getRandomValues`).\n */\nexport function newIdempotencyKey(): string {\n const c = (\n globalThis as {\n crypto?: { randomUUID?: () => string; getRandomValues?: (a: Uint8Array) => Uint8Array };\n }\n ).crypto;\n if (c && typeof c.randomUUID === 'function') {\n return c.randomUUID().toLowerCase();\n }\n if (!c || typeof c.getRandomValues !== 'function') {\n throw new Error('no cryptographic random source: pass an idempotency key explicitly');\n }\n const b = c.getRandomValues(new Uint8Array(16));\n b[6] = (b[6]! & 0x0f) | 0x40;\n b[8] = (b[8]! & 0x3f) | 0x80;\n const hex = Array.from(b, (x: number) => x.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction nonEmpty(name: string, value: string): string {\n if (typeof value !== 'string' || value === '') {\n throw new TypeError(`${name} is required`);\n }\n return value;\n}\n\nfunction keyList(name: string, keys: readonly string[]): string[] {\n if (!Array.isArray(keys) || keys.length === 0) {\n throw new TypeError(`${name} must list at least one public key`);\n }\n return keys.map((k, i) => {\n const key = nonEmpty(`${name}[${i}]`, k);\n // The platform trims an added member key before it rebuilds the intent it\n // verifies, so a key signed with surrounding whitespace can never verify.\n // Refuse it rather than guess which form the caller meant to sign.\n if (key.trim() !== key) {\n throw new TypeError(`${name}[${i}] has leading or trailing whitespace; trim it first`);\n }\n return key;\n });\n}\n\nfunction version(v: number): number {\n if (!Number.isSafeInteger(v) || v < 0) {\n throw new TypeError(\n `signer_group_version must be a non-negative integer (got ${String(v)}); read it from the group's \\`version\\``\n );\n }\n return v;\n}\n\nfunction finish<T extends GovernanceIntent>(intent: T): CanonicalIntent<T> {\n const canonical = canonicalJSON(intent);\n return { intent, canonical, bytes: utf8(canonical) };\n}\n\n/**\n * Intent for adding members to a signer group\n * (`POST /signer-groups/{id}/signers`). That endpoint adds one `member_key`\n * per request, so pass `[memberKey]`.\n *\n * @param params.signerGroupVersion - the group's current `version` (0 is valid\n * and is signed as 0)\n * @param params.idempotencyKey - a lowercase UUID; send the SAME value as the\n * request's `X-Idempotency-Key`\n */\nexport function addSignersToGroupIntent(params: {\n signerGroupId: string;\n newMemberKeys: readonly string[];\n signerGroupVersion: number;\n idempotencyKey: string;\n}): CanonicalIntent<AddSignersToGroupIntent> {\n assertIdempotencyKey(params.idempotencyKey);\n return finish({\n type: 'add_signers_to_group',\n signer_group_id: nonEmpty('signerGroupId', params.signerGroupId),\n new_member_keys: keyList('newMemberKeys', params.newMemberKeys),\n signer_group_version: version(params.signerGroupVersion),\n idempotency_key: params.idempotencyKey,\n });\n}\n\n/**\n * Intent for removing members from a signer group\n * (`POST /signer-groups/{id}/signer-removals`). `membersToRemove` is signed\n * in the order given, which must be the order sent.\n */\nexport function removeSignersFromGroupIntent(params: {\n signerGroupId: string;\n membersToRemove: readonly string[];\n signerGroupVersion: number;\n idempotencyKey: string;\n}): CanonicalIntent<RemoveSignersFromGroupIntent> {\n assertIdempotencyKey(params.idempotencyKey);\n return finish({\n type: 'remove_signers_from_group',\n group_id: nonEmpty('signerGroupId', params.signerGroupId),\n members_to_remove: keyList('membersToRemove', params.membersToRemove),\n signer_group_version: version(params.signerGroupVersion),\n idempotency_key: params.idempotencyKey,\n });\n}\n\n/**\n * Intent for replacing a signer group's governance settings\n * (`PATCH /signer-groups/{id}/governance`).\n *\n * The change replaces the WHOLE governance state: leave a setting out (or\n * pass null) to clear it, which the intent expresses by omitting the key.\n * No `governanceThreshold` means the default quorum; no\n * `governanceSignerGroupId` means the group governs itself.\n */\nexport function updateSignerGroupGovernanceIntent(params: {\n signerGroupId: string;\n signerGroupVersion: number;\n idempotencyKey: string;\n governanceThreshold?: number | null;\n governanceSignerGroupId?: string | null;\n}): CanonicalIntent<UpdateSignerGroupGovernanceIntent> {\n assertIdempotencyKey(params.idempotencyKey);\n const intent: {\n -readonly [K in keyof UpdateSignerGroupGovernanceIntent]: UpdateSignerGroupGovernanceIntent[K];\n } = {\n type: 'update_signer_group_governance',\n signer_group_id: nonEmpty('signerGroupId', params.signerGroupId),\n signer_group_version: version(params.signerGroupVersion),\n idempotency_key: params.idempotencyKey,\n };\n if (params.governanceThreshold !== undefined && params.governanceThreshold !== null) {\n // The platform stores it as an int32.\n const t = params.governanceThreshold;\n if (!Number.isSafeInteger(t) || t < 1 || t > 2147483647) {\n throw new TypeError(\n 'governanceThreshold must be an integer from 1 to 2^31-1, or null to clear it'\n );\n }\n intent.governance_threshold = params.governanceThreshold;\n }\n if (params.governanceSignerGroupId !== undefined && params.governanceSignerGroupId !== null) {\n intent.governance_signer_group_id = nonEmpty(\n 'governanceSignerGroupId',\n params.governanceSignerGroupId\n );\n }\n return finish(intent);\n}\n\n/**\n * Intent for creating a crypto destination endorsed by a signer group's\n * governance (`POST /recipients/{recipient_id}/destinations` with\n * `destination_type: 'crypto'`, `signatures` and `signer_group_id`). Send\n * `crypto_address` = `address` and the same `network_id`.\n */\nexport function createCryptoDestinationIntent(params: {\n recipientId: string;\n networkId: string;\n address: string;\n signerGroupId: string;\n idempotencyKey: string;\n}): CanonicalIntent<CreateCryptoDestinationIntent> {\n assertIdempotencyKey(params.idempotencyKey);\n return finish({\n type: 'create_crypto_destination',\n recipient_id: nonEmpty('recipientId', params.recipientId),\n network_id: nonEmpty('networkId', params.networkId),\n address: nonEmpty('address', params.address),\n signer_group_id: nonEmpty('signerGroupId', params.signerGroupId),\n idempotency_key: params.idempotencyKey,\n });\n}\n","/**\n * Destinations resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { assertIdempotencyKey } from '../../governance/intents.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Destination,\n DestinationCreateResponse,\n DestinationListParams,\n DestinationRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Destinations API resource.\n */\nexport class DestinationsResource extends BaseResource {\n /**\n * Create a new destination for a recipient.\n *\n * Destinations can be bank accounts (fiat_us / fiat_iban) or crypto\n * wallets (crypto).\n *\n * The platform returns just `{ id }` here (per `IDResponse`), not the\n * full destination object. Call `destinations.list(recipientId)` if\n * you need the rest of the fields.\n *\n * @param recipientId - Recipient ID\n * @param data - Destination creation data\n * @returns `{ id }` of the newly-created destination\n *\n * @example\n * ```typescript\n * // Crypto destination (for on-ramp)\n * const cryptoDest = await client.destinations.create(recipientId, {\n * destination_type: 'crypto',\n * name: 'Treasury USDC',\n * crypto_address: '0x742d35Cc6634C0532925a3b844Bc9e7595f...',\n * network_id: 'ethereum-mainnet',\n * });\n * // → cryptoDest.id\n *\n * // Fiat US destination (for off-ramp)\n * const bankDest = await client.destinations.create(recipientId, {\n * destination_type: 'fiat_us',\n * name: 'Acme Chase Checking',\n * bank_name: 'JPMorgan Chase',\n * account_holder_name: 'Acme Corp',\n * account_number: '000123456789',\n * aba_routing_number: '021000021',\n * account_type: 'checking',\n * });\n * // → bankDest.id\n * ```\n */\n async create(\n recipientId: string,\n data: DestinationRequest,\n options?: RequestOptions\n ): Promise<DestinationCreateResponse> {\n // A signed (governed) crypto destination carries its idempotency key\n // inside the signed intent, so a generated one could never match it.\n const signatures = (data as { signatures?: readonly unknown[] }).signatures;\n if (signatures !== undefined && signatures.length > 0) {\n if (!options?.idempotencyKey) {\n throw new TypeError(\n 'destinations.create with signatures needs options.idempotencyKey: the idempotency_key inside the signed intent (a generated one could never match)'\n );\n }\n assertIdempotencyKey(options.idempotencyKey);\n }\n return this.transport.request<DestinationCreateResponse>({\n method: 'POST',\n path: `/recipients/${recipientId}/destinations`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List destinations for a recipient.\n *\n * @param recipientId - Recipient ID\n * @param params - Pagination parameters\n * @returns Async iterator of destinations\n *\n * @example\n * ```typescript\n * for await (const dest of client.destinations.list(recipientId)) {\n * console.log(dest);\n * }\n * ```\n */\n list(recipientId: string, params?: DestinationListParams): PaginatedIterator<Destination> {\n return this.paginate<Destination>(\n `/recipients/${recipientId}/destinations`,\n params,\n (item) => item.destination_id\n );\n }\n\n /**\n * Delete a destination.\n *\n * @param recipientId - Recipient ID\n * @param destinationId - Destination ID\n *\n * @example\n * ```typescript\n * await client.destinations.delete(recipientId, destinationId);\n * ```\n */\n async delete(recipientId: string, destinationId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/recipients/${recipientId}/destinations/${destinationId}`,\n });\n }\n}\n","/**\n * Accounts resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Account,\n AccountCreateRequest,\n AccountUpdateRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/** Account list parameters */\nexport interface AccountListParams extends ListParams {\n /** Account type filter. Required by the API. */\n account_type: 'onramp' | 'offramp' | 'swap';\n customer_id?: string;\n source_network_id?: string;\n destination_network_id?: string;\n destination_asset?: string;\n crypto_destination_id?: string;\n fiat_destination_id?: string;\n}\n\n/**\n * Accounts API resource.\n */\nexport class AccountsResource extends BaseResource {\n /**\n * Create a new account.\n *\n * Accounts define the flow of funds:\n * - **onramp**: USD → crypto (customer sends USD, receives stablecoin)\n * - **offramp**: crypto → USD (customer sends stablecoin, receives USD)\n * - **swap**: crypto → crypto (stablecoin conversion)\n *\n * @param data - Account creation data\n * @returns Created account\n *\n * @example\n * ```typescript\n * // Create an off-ramp account (crypto → USD)\n * const offramp = await client.accounts.create({\n * account_type: 'offramp',\n * customer_id: customerId,\n * fiat_destination_id: bankDestinationId,\n * asset: 'USDC',\n * network_id: 'ethereum-mainnet',\n * rail: 'ach',\n * capabilities: ['ach'],\n * });\n * // Returns: { crypto_address: '0x...' } - customer sends USDC here\n *\n * // Create an on-ramp account (USD → crypto)\n * const onramp = await client.accounts.create({\n * account_type: 'onramp',\n * customer_id: customerId,\n * crypto_destination_id: cryptoDestinationId,\n * asset: 'USDC',\n * network_id: 'ethereum-mainnet',\n * rail: 'ach',\n * capabilities: ['ach'],\n * });\n * // Returns: { bank_account: { bank_name, aba_routing_number, account_number } } - customer sends USD here\n * ```\n *\n * @remarks\n * `max_transactions` caps how many transactions the account may ever\n * create — `1` makes it a one-off. Know what reaching the cap does before\n * you set one: further deposits are **refused, not returned**. The funds\n * still arrive and are then held pending manual intervention, with nothing\n * converted, nothing forwarded, and no transaction on the account for\n * them. Stop sending to the deposit details once the cap is reached.\n */\n async create(data: AccountCreateRequest, options?: RequestOptions): Promise<Account> {\n return this.transport.request<Account>({\n method: 'POST',\n path: '/accounts',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List accounts.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of accounts\n *\n * @example\n * ```typescript\n * // List all accounts\n * for await (const account of client.accounts.list()) {\n * console.log(account);\n * }\n *\n * // Filter by customer\n * const customerAccounts = client.accounts.list({ customer_id: customerId });\n * ```\n */\n list(params?: AccountListParams): PaginatedIterator<Account> {\n return this.paginate<Account>('/accounts', params);\n }\n\n /**\n * Get an account by ID.\n *\n * @param accountId - Account ID\n * @returns Account record\n *\n * @example\n * ```typescript\n * const account = await client.accounts.get(accountId);\n * ```\n */\n async get(accountId: string): Promise<Account> {\n return this.transport.request<Account>({\n method: 'GET',\n path: `/accounts/${accountId}`,\n });\n }\n\n /**\n * Update an account.\n *\n * @param accountId - Account ID\n * @param data - Update data\n * @returns Updated account\n *\n * Only the developer fee can be updated, and setting one kind replaces the\n * other. `developer_fee_fixed` is a decimal string in units of the asset\n * deposited (at most 2 decimals, greater than 0); it applies to future\n * deposits only.\n *\n * @example\n * ```typescript\n * const account = await client.accounts.update(accountId, {\n * account_type: 'onramp',\n * developer_fee_fixed: '10.00',\n * });\n * console.log(account.minimum_deposit); // '10.01'\n * ```\n */\n async update(\n accountId: string,\n data: AccountUpdateRequest,\n options?: RequestOptions\n ): Promise<Account> {\n return this.transport.request<Account>({\n method: 'PATCH',\n path: `/accounts/${accountId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete an account.\n *\n * @param accountId - Account ID\n *\n * @example\n * ```typescript\n * await client.accounts.delete(accountId);\n * ```\n */\n async delete(accountId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/accounts/${accountId}`,\n });\n }\n}\n","/**\n * Transactions resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport { APIError } from '../errors.js';\nimport type {\n OneOffTransaction,\n OneOffTransactionRequest,\n AutoTransaction,\n AutoTransactionListParams,\n TransactionListParams,\n TransactionResourceType,\n WalletTransaction,\n RequestOptions,\n} from '../types.js';\n\n/**\n * The row shape `GET /transactions` yields for a given set of filters.\n *\n * The family decides the shape, so the filters decide the element type: name\n * `wallet` or `auto_account` and you get that family's rows, anything else is\n * the `one_off` family this endpoint defaults to.\n */\nexport type TransactionRowFor<P extends TransactionListParams | undefined> = P extends {\n transaction_type: 'wallet';\n}\n ? WalletTransaction\n : P extends { transaction_type: 'auto_account' }\n ? AutoTransaction\n : OneOffTransaction;\n\n/**\n * Transactions API resource.\n */\nexport class TransactionsResource extends BaseResource {\n /**\n * Create a one-off transaction.\n *\n * One-off transactions allow single transfers without setting up accounts.\n *\n * @param data - Transaction creation data\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Created transaction\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.create({\n * customer_id: customerId,\n * amount: '1000.00',\n * source_asset: 'USDC',\n * source_network_id: 'ethereum-mainnet',\n * destination_id: destinationId,\n * destination_asset: 'USD',\n * destination_payment_rail: 'ach',\n * payment_reference: 'Invoice #12345',\n * });\n *\n * // With custom idempotency key\n * const tx = await client.transactions.create(\n * { customer_id: customerId, amount: '1000.00', ... },\n * { idempotencyKey: 'invoice-12345-payment' }\n * );\n *\n * console.log(tx.crypto_address); // Send USDC here\n * console.log(tx.status); // Transaction status\n * ```\n */\n async create(\n data: OneOffTransactionRequest,\n options?: RequestOptions\n ): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'POST',\n path: '/transactions',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List transactions.\n *\n * `GET /transactions` serves three resource families from one path, and the\n * family decides the row shape — so the family you ask for decides what this\n * iterator yields:\n *\n * | `transaction_type` | Yields |\n * |--------------------|--------|\n * | omitted or `'one_off'` | {@link OneOffTransaction} |\n * | `'wallet'` | {@link WalletTransaction} |\n * | `'auto_account'` | {@link AutoTransaction} (requires `customer_id`) |\n *\n * **The family is always named on the wire.** Left to the server, it is\n * INFERRED from the other filters, and `customer_id` on its own infers\n * `auto_account` — so `list({ customer_id })` would return that customer's\n * auto-account transactions while this method's type promised one-off ones.\n * Those rows parse into `OneOffTransaction` with missing fields rather than\n * failing, so nothing surfaced the substitution. Omitting the family here\n * therefore sends `transaction_type=one_off` rather than leaving it open.\n *\n * The family the server reports back (`meta.transaction_type`) is checked\n * against the one requested, and a mismatch throws instead of yielding rows\n * of the wrong shape.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator over the requested family\n *\n * @example\n * ```typescript\n * // One-off transactions (the default family)\n * for await (const tx of client.transactions.list()) {\n * console.log(tx.id, tx.status);\n * }\n *\n * // This customer's ONE-OFF transactions\n * const completed = client.transactions.list({\n * customer_id: customerId,\n * status: 'completed',\n * });\n *\n * // This customer's AUTO-ACCOUNT transactions — a different family,\n * // and a different row shape\n * for await (const tx of client.transactions.list({\n * transaction_type: 'auto_account',\n * customer_id: customerId,\n * })) {\n * console.log(tx.id);\n * }\n *\n * // Wallet transactions\n * const sent = client.transactions.list({\n * transaction_type: 'wallet',\n * wallet_id: walletId,\n * direction: 'out',\n * });\n * ```\n */\n list<P extends TransactionListParams | undefined = undefined>(\n params?: P\n ): PaginatedIterator<TransactionRowFor<P>> {\n // Name the family rather than letting the server infer one. See the doc\n // comment: an inferred family is how `{ customer_id }` came back as\n // auto-account rows typed as one-off ones.\n const requested: TransactionResourceType = params?.transaction_type ?? 'one_off';\n\n return this.paginate<TransactionRowFor<P>>(\n '/transactions',\n { ...params, transaction_type: requested },\n undefined,\n (meta) => assertFamily(meta, requested)\n );\n }\n\n /**\n * Get a transaction by ID.\n *\n * @param transactionId - Transaction ID\n * @returns Transaction record\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.get(transactionId);\n * console.log(tx.status);\n * ```\n */\n async get(transactionId: string): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'GET',\n path: `/transactions/${transactionId}`,\n });\n }\n\n /**\n * Cancel a transaction.\n *\n * Only pending transactions can be cancelled.\n *\n * @param transactionId - Transaction ID\n * @param options - Request options (e.g., custom idempotency key)\n * @returns Cancelled transaction\n *\n * @example\n * ```typescript\n * const tx = await client.transactions.cancel(transactionId);\n * console.log(tx.status); // 'cancelled'\n * ```\n */\n async cancel(transactionId: string, options?: RequestOptions): Promise<OneOffTransaction> {\n return this.transport.request<OneOffTransaction>({\n method: 'POST',\n path: `/transactions/${transactionId}/cancellations`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n\n/**\n * Fail a page whose family is not the one asked for.\n *\n * A POSITIVE mismatch only. An absent `transaction_type` means the response\n * made no claim about its family — older servers and the bare-array list\n * shapes do not send one — and treating silence as a mismatch would turn a\n * backstop into a new way for a working call to fail.\n */\nfunction assertFamily(\n meta: Record<string, unknown> | undefined,\n requested: TransactionResourceType\n): void {\n const served = meta?.transaction_type;\n if (typeof served !== 'string' || served === requested) return;\n\n throw new APIError(\n 200,\n 'transaction_family_mismatch',\n `Asked for ${requested} transactions but the server listed ${served}. ` +\n 'The rows in this page are not the shape this iterator yields, so they ' +\n 'are not returned.',\n { details: { requested, served } }\n );\n}\n\n/**\n * Auto Transactions API resource.\n */\nexport class AutoTransactionsResource extends BaseResource {\n /**\n * List auto transactions.\n *\n * `statuses` and `types` take a comma-separated string, not an array, and\n * `start_date` / `end_date` are Unix epoch SECONDS rather than the ISO\n * strings the other list endpoints take.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of auto transactions\n *\n * @example\n * ```typescript\n * const recent = client.autoTransactions.list({\n * auto_account_id: accountId,\n * statuses: 'pending,processing',\n * start_date: Math.floor(Date.now() / 1000) - 86_400,\n * sort_dir: 'desc',\n * });\n * ```\n */\n list(params?: AutoTransactionListParams): PaginatedIterator<AutoTransaction> {\n return this.paginate<AutoTransaction>('/auto-transactions', params);\n }\n\n /**\n * Get an auto transaction by ID.\n *\n * @param transactionId - Auto transaction ID\n * @returns Auto transaction record\n */\n async get(transactionId: string): Promise<AutoTransaction> {\n return this.transport.request<AutoTransaction>({\n method: 'GET',\n path: `/auto-transactions/${transactionId}`,\n });\n }\n}\n","/**\n * Wallets resource.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n Wallet,\n WalletCreateRequest,\n WalletBalances,\n WalletTransactionRequest,\n WalletTransaction,\n AttachedPolicy,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Wallets API resource.\n */\nexport class WalletsResource extends BaseResource {\n /**\n * Create a new wallet.\n *\n * Creates a non-custodial multi-sig wallet for a customer.\n *\n * @param data - Wallet creation data\n * @returns Created wallet\n *\n * @example\n * ```typescript\n * const wallet = await client.wallets.create({\n * customer_id: customerId,\n * family: 'evm',\n * name: 'Treasury Wallet',\n * });\n * console.log(wallet.address);\n * ```\n */\n async create(data: WalletCreateRequest, options?: RequestOptions): Promise<Wallet> {\n return this.transport.request<Wallet>({\n method: 'POST',\n path: '/wallets',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a single wallet by ID.\n *\n * @param walletId - Wallet ID\n * @returns Wallet record (includes `customer_name` and `created_at`)\n *\n * @example\n * ```typescript\n * const wallet = await client.wallets.get(walletId);\n * console.log(wallet.address, wallet.customer_name);\n * ```\n */\n async get(walletId: string): Promise<Wallet> {\n return this.transport.request<Wallet>({\n method: 'GET',\n path: `/wallets/${walletId}`,\n });\n }\n\n /**\n * Get policies attached to a wallet.\n *\n * Returns slim references (id + name) for the policies currently attached to the wallet.\n *\n * @param walletId - Wallet ID\n * @returns Array of attached policies\n *\n * @example\n * ```typescript\n * const policies = await client.wallets.getPolicies(walletId);\n * for (const policy of policies) {\n * console.log(policy.id, policy.name);\n * }\n * ```\n */\n async getPolicies(walletId: string): Promise<AttachedPolicy[]> {\n return this.transport.request<AttachedPolicy[]>({\n method: 'GET',\n path: `/wallets/${walletId}/policies`,\n });\n }\n\n /**\n * Get wallet balances.\n *\n * Returns the platform's full `WalletBalances` response: the wallet id,\n * its on-chain address, every per-asset balance, and a pre-computed\n * `total_amount_usd` across all assets. The previous return shape\n * (`WalletBalance[]`) silently dropped `address` and `total_amount_usd`,\n * forcing callers to do a second `wallets.get()` and sum the balances\n * by hand. This is a small breaking change with a one-line migration\n * (`balances` → `balances.balances`); the prior shape had been broken\n * since 1.3.x anyway.\n *\n * @param walletId - Wallet ID\n * @returns `{ wallet_id, address, balances, total_amount_usd }`\n *\n * @example\n * ```typescript\n * const { address, total_amount_usd, balances } =\n * await client.wallets.getBalances(walletId);\n * console.log(`${address} → $${total_amount_usd}`);\n * for (const b of balances) {\n * console.log(b.asset.id, b.amount_usd);\n * }\n * ```\n */\n async getBalances(walletId: string): Promise<WalletBalances> {\n // /wallets/{id}/balances returns the WalletBalances object directly\n // ({ wallet_id, address, balances, total_amount_usd }), not the\n // paginated { data, meta } envelope. The 1.3.x impl read\n // response.data here and silently returned undefined; the 1.4.x /\n // 1.5.x impl returned just the balances array, dropping the wrapper\n // fields. Now we return what the platform actually sends.\n return this.transport.request<WalletBalances>({\n method: 'GET',\n path: `/wallets/${walletId}/balances`,\n });\n }\n\n /**\n * Send a transaction from a wallet.\n *\n * The platform expects an **endorsed request** envelope —\n * `{ signatures, intent }` — at this endpoint. Build the\n * `SendTransactionIntent`, canonicalize it per RFC 8785 (JCS), sign\n * with the wallet's signer-group ECDSA P-256 key, base64-encode the\n * DER signature, then post the envelope.\n *\n * Use the SDK's `canonicalJSON`: it matches the platform's canonical form\n * byte for byte. Write `amount` in its shortest decimal form (`'100'`, not\n * `'100.00'`; `'0.5'`, not `'0.50'`). The platform parses the amount as a\n * decimal and re-serializes it before it checks the signature, so trailing\n * zeros change the signed bytes and the signature fails.\n *\n * @param walletId - Wallet ID\n * @param data - Endorsed wallet transaction request: `{ signatures, intent }`\n * @returns Created transaction\n *\n * @example\n * ```typescript\n * import { canonicalJSON } from '@dakota-xyz/ts-sdk';\n * import { createSign, createPrivateKey, randomUUID } from 'node:crypto';\n *\n * const intent = {\n * wallet_id: walletId,\n * caip2: 'eip155:1', // 11155111 for sepolia\n * operation: {\n * kind: 'transfer',\n * from: wallet.address,\n * to: '0x...',\n * amount: '100', // shortest decimal form, see below\n * asset_id: 'USDC',\n * },\n * idempotency_key: randomUUID(),\n * };\n * const canonical = canonicalJSON(intent);\n * const sig = createSign('SHA256').update(canonical).sign({\n * key: createPrivateKey({ key: privateKeyDer, format: 'der', type: 'pkcs8' }),\n * dsaEncoding: 'der',\n * });\n * const tx = await client.wallets.createTransaction(walletId, {\n * signatures: [sig.toString('base64')],\n * intent,\n * });\n * ```\n *\n * @see https://docs.dakota.xyz/documentation/signing-guide\n */\n async createTransaction(\n walletId: string,\n data: WalletTransactionRequest,\n options?: RequestOptions\n ): Promise<WalletTransaction> {\n return this.transport.request<WalletTransaction>({\n method: 'POST',\n path: `/wallets/${walletId}/transactions`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Events resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type { Event, EventListParams } from '../types.js';\n\n/**\n * Events API resource.\n */\nexport class EventsResource extends BaseResource {\n /**\n * List events.\n *\n * Events track all platform activity and can be used for audit trails.\n *\n * @param params - Filter and pagination parameters\n * @returns Async iterator of events\n *\n * @example\n * ```typescript\n * for await (const event of client.events.list()) {\n * console.log(event.type, event.data);\n * }\n *\n * // Filter by event type\n * const customerEvents = client.events.list({\n * event_type: 'customer.created',\n * });\n * ```\n */\n list(params?: EventListParams): PaginatedIterator<Event> {\n return this.paginate<Event>('/events', params);\n }\n}\n","/**\n * Applications resource (Onboarding/KYB).\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Application,\n ApplicationDocumentUploadRequest,\n ApplicationGetParams,\n ApplicationDocumentUploadUrlRequest,\n ApplicationSubmissionRequest,\n AssociatedIndividual,\n AssociatedIndividualRequest,\n AttestationSubmitRequest,\n BusinessApplicationCreateRequest,\n BusinessDetailsResponse,\n DocumentUploadResponse,\n DocumentUploadUrlResponse,\n EDDRequest,\n EDDWithApplicationID,\n IndividualDetailsResponse,\n IndividualDocumentUploadRequest,\n IndividualDocumentUploadUrlRequest,\n IndividualRequest,\n LegalAcceptanceContext,\n ListParams,\n RequestOptions,\n UploadedDocumentMetadata,\n} from '../types.js';\n\n/** Parameters for listing application documents */\nexport interface DocumentListParams extends ListParams {\n category?: 'business' | 'identity' | 'edd';\n document_type?: string;\n}\n\n/**\n * Applications API resource for KYB onboarding.\n */\nexport class ApplicationsResource extends BaseResource {\n /**\n * List applications.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of applications\n */\n list(params?: ListParams): PaginatedIterator<Application> {\n return this.paginate<Application>('/applications', params);\n }\n\n /**\n * Get an application by ID.\n *\n * `include` inlines extra sections — a comma-separated list of `entities`,\n * `validation`, `edd`, `attestations`, or `all`. Each adds weight, and\n * `'all'` carries the full KYB record including every associated\n * individual's date of birth, nationality and email, so ask for what the\n * page renders.\n *\n * To render an accept-agreements page, use {@link getLegalAcceptance}\n * instead: it returns exactly that page's inputs and none of the personal\n * data.\n *\n * @param applicationId - Application ID\n * @param params - Optional `{ include }`\n * @returns Application record\n *\n * @example\n * ```typescript\n * const app = await client.applications.get(applicationId, {\n * include: 'entities,validation',\n * });\n * ```\n */\n async get(applicationId: string, params?: ApplicationGetParams): Promise<Application> {\n return this.transport.request<Application>({\n method: 'GET',\n path: `/applications/${applicationId}`,\n query: { ...params },\n });\n }\n\n /**\n * Submit an application for review.\n *\n * @param applicationId - Application ID\n * @param data - Submission data\n * @returns Submitted application\n */\n async submit(\n applicationId: string,\n data?: ApplicationSubmissionRequest,\n options?: RequestOptions\n ): Promise<Application> {\n return this.transport.request<Application>({\n method: 'POST',\n path: `/applications/${applicationId}/submissions`,\n body: data ?? {},\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Business Details\n // ==========================================================================\n\n /**\n * Update business details for an application.\n *\n * Uses PUT (full replace) per the OpenAPI spec.\n *\n * @param applicationId - Application ID\n * @param data - Business details (full BusinessApplicationCreateRequest)\n * @returns Updated business details with application context\n */\n async updateBusinessDetails(\n applicationId: string,\n data: BusinessApplicationCreateRequest,\n options?: RequestOptions\n ): Promise<BusinessDetailsResponse> {\n return this.transport.request<BusinessDetailsResponse>({\n method: 'PUT',\n path: `/applications/${applicationId}/business-details`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Individual Details (non-business applications)\n // ==========================================================================\n\n /**\n * Update individual details for a non-business application.\n *\n * Uses PUT (full replace) per the OpenAPI spec. Only callable when the\n * application status is 'pending'.\n *\n * @param applicationId - Application ID\n * @param data - Individual details (full IndividualRequest)\n * @returns Updated individual details with application context\n */\n async updateIndividualDetails(\n applicationId: string,\n data: IndividualRequest,\n options?: RequestOptions\n ): Promise<IndividualDetailsResponse> {\n return this.transport.request<IndividualDetailsResponse>({\n method: 'PUT',\n path: `/applications/${applicationId}/individual-details`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Associated Individuals\n // ==========================================================================\n\n /**\n * Add an associated individual to an application.\n *\n * @param applicationId - Application ID\n * @param data - Individual data\n * @returns Created individual\n */\n async addIndividual(\n applicationId: string,\n data: AssociatedIndividualRequest,\n options?: RequestOptions\n ): Promise<AssociatedIndividual> {\n return this.transport.request<AssociatedIndividual>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Update an associated individual.\n *\n * Uses PUT (full replace) per the OpenAPI spec.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Full individual data (replaces existing)\n * @returns Updated individual\n */\n async updateIndividual(\n applicationId: string,\n individualId: string,\n data: AssociatedIndividualRequest,\n options?: RequestOptions\n ): Promise<AssociatedIndividual> {\n return this.transport.request<AssociatedIndividual>({\n method: 'PUT',\n path: `/applications/${applicationId}/associated-individuals/${individualId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete an associated individual.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n */\n async deleteIndividual(applicationId: string, individualId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/applications/${applicationId}/associated-individuals/${individualId}`,\n });\n }\n\n // ==========================================================================\n // Attestations\n // ==========================================================================\n\n /**\n * What this application still needs to accept, and who may accept it.\n *\n * Exactly what an accept-agreements page renders, and deliberately nothing\n * more. `get(applicationId)` would answer with the full KYB record — the\n * business entity, and every associated individual's date of birth,\n * nationality and email — none of which that page displays. The link that\n * reaches this endpoint is EMAILED and travels in a URL query string, so its\n * credential is scoped to this call and the attestation submission, and\n * cannot read the application.\n *\n * Authenticates with an Application Token (`X-Application-Token`), including\n * the narrow legal-acceptance token a terms refusal issues.\n *\n * The documents come back as identity only. Fetch the text to display with\n * `client.legal.get(key)`, then pass the `version` you displayed back as\n * `legal_document_version` on {@link submitAttestation}.\n *\n * @param applicationId - Application ID\n * @returns Outstanding agreements, prior acceptances, and permitted attestors\n *\n * @example\n * ```typescript\n * const ctx = await client.applications.getLegalAcceptance(applicationId);\n *\n * for (const doc of ctx.outstanding_documents) {\n * const text = await client.legal.get(doc.key, doc.version);\n * render(text.content);\n * }\n *\n * // A business may have several control persons; an individual application\n * // has exactly one permissible attestor, so there is nobody to pick.\n * const attestor =\n * ctx.application_type === 'individual' ? ctx.attestors[0] : await pick(ctx.attestors);\n * ```\n */\n async getLegalAcceptance(applicationId: string): Promise<LegalAcceptanceContext> {\n return this.transport.request<LegalAcceptanceContext>({\n method: 'GET',\n path: `/applications/${applicationId}/legal-acceptance`,\n });\n }\n\n /**\n * Submit an attestation for an application.\n *\n * Additionally supplying `disclosure_id` (a terms key the provider\n * declared, e.g. `partner_disclosures`) and `disclosure_version` records the\n * attestation as a PARTNER DISCLOSURE acknowledgment instead of a standard\n * onboarding one: acceptance is stamped `customer_online`, the\n * partner-onboarding substatus advances, and an already-approved\n * application is reprovisioned. The API stays partner-agnostic — callers\n * supply a terms key and version, never a partner name. Get the outstanding\n * ones from `customers.getCapabilities(customerId)`.\n *\n * @param applicationId - Application ID\n * @param data - Attestation data (type, timestamp, applicant_id), plus\n * `disclosure_id` + `disclosure_version` to accept a partner disclosure\n */\n async submitAttestation(\n applicationId: string,\n data: AttestationSubmitRequest,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'POST',\n path: `/applications/${applicationId}/attestations`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Enhanced Due Diligence (EDD)\n // ==========================================================================\n\n /**\n * Get the EDD record for an application.\n *\n * @param applicationId - Application ID\n * @returns EDD record with application context\n */\n async getEDD(applicationId: string): Promise<EDDWithApplicationID> {\n return this.transport.request<EDDWithApplicationID>({\n method: 'GET',\n path: `/applications/${applicationId}/edd`,\n });\n }\n\n /**\n * Create or update the EDD record for an application.\n *\n * This endpoint is idempotent (uses PUT).\n *\n * @param applicationId - Application ID\n * @param data - EDD data\n * @returns Updated EDD record with application context\n */\n async createOrUpdateEDD(\n applicationId: string,\n data: EDDRequest,\n options?: RequestOptions\n ): Promise<EDDWithApplicationID> {\n return this.transport.request<EDDWithApplicationID>({\n method: 'PUT',\n path: `/applications/${applicationId}/edd`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Application Documents\n // ==========================================================================\n\n /**\n * Upload an application document using base64-encoded content.\n *\n * For files larger than 20MB, use {@link getDocumentUploadUrl} and upload\n * directly to cloud storage, then call {@link verifyDocument}.\n *\n * @param applicationId - Application ID\n * @param data - Document data including base64 content\n * @returns Document upload response with document_id\n */\n async createDocument(\n applicationId: string,\n data: ApplicationDocumentUploadRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/documents`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List documents for an application.\n *\n * Supports filtering by category and document type.\n *\n * @param applicationId - Application ID\n * @param params - Pagination and filter parameters\n * @returns Paginated iterator of document metadata\n */\n listDocuments(\n applicationId: string,\n params?: DocumentListParams\n ): PaginatedIterator<UploadedDocumentMetadata> {\n return this.paginate<UploadedDocumentMetadata>(\n `/applications/${applicationId}/documents`,\n params\n );\n }\n\n /**\n * Download/get a document by ID.\n *\n * @param applicationId - Application ID\n * @param documentId - Document ID\n * @returns Document content (binary)\n */\n async getDocument(applicationId: string, documentId: string): Promise<unknown> {\n return this.transport.request<unknown>({\n method: 'GET',\n path: `/applications/${applicationId}/documents/${documentId}`,\n });\n }\n\n /**\n * Delete a document from a pending application.\n *\n * Only documents from applications in 'pending' status can be deleted.\n *\n * @param applicationId - Application ID\n * @param documentId - Document ID\n */\n async deleteDocument(applicationId: string, documentId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/applications/${applicationId}/documents/${documentId}`,\n });\n }\n\n /**\n * Verify a document uploaded via presigned URL.\n *\n * After uploading a file to the presigned URL from {@link getDocumentUploadUrl},\n * call this endpoint to register and verify the upload.\n *\n * @param applicationId - Application ID\n * @param documentId - The upload_id from the presigned URL response\n * @returns Document upload response with document_id\n */\n async verifyDocument(\n applicationId: string,\n documentId: string,\n _data?: Record<string, unknown>,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/documents/${documentId}/verifications`,\n body: _data ?? {},\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a presigned upload URL for an application document.\n *\n * Use this for files larger than 20MB. Upload the file directly to the\n * returned URL, then call {@link verifyDocument} to register it.\n *\n * @param applicationId - Application ID\n * @param data - Document metadata\n * @returns Upload URL and upload ID\n */\n async getDocumentUploadUrl(\n applicationId: string,\n data: ApplicationDocumentUploadUrlRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadUrlResponse> {\n return this.transport.request<DocumentUploadUrlResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/document-uploads`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // ==========================================================================\n // Individual Documents\n // ==========================================================================\n\n /**\n * Upload a document for an associated individual using base64-encoded content.\n *\n * Supports identity documents (passport, driver's license, residence permit)\n * and EDD documents (bank statement, etc.). For files larger than 10MB, use\n * {@link getIndividualDocumentUploadUrl} instead.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Document data including base64 content\n * @returns Document upload response with document_id\n */\n async uploadIndividualDocument(\n applicationId: string,\n individualId: string,\n data: IndividualDocumentUploadRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadResponse> {\n return this.transport.request<DocumentUploadResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals/${individualId}/documents`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a presigned upload URL for an individual document.\n *\n * Use this for files larger than 10MB. Upload the file directly to the\n * returned URL.\n *\n * @param applicationId - Application ID\n * @param individualId - Individual ID\n * @param data - Document metadata\n * @returns Upload URL and upload ID\n */\n async getIndividualDocumentUploadUrl(\n applicationId: string,\n individualId: string,\n data: IndividualDocumentUploadUrlRequest,\n options?: RequestOptions\n ): Promise<DocumentUploadUrlResponse> {\n return this.transport.request<DocumentUploadUrlResponse>({\n method: 'POST',\n path: `/applications/${applicationId}/associated-individuals/${individualId}/document-uploads`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Policies resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n Policy,\n PolicyCreateRequest,\n PolicyRule,\n PolicyRuleCreateRequest,\n AttachedWallet,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Policies API resource.\n */\nexport class PoliciesResource extends BaseResource {\n /**\n * Create a new policy.\n *\n * @param data - Policy creation data\n * @returns Created policy\n */\n async create(data: PolicyCreateRequest, options?: RequestOptions): Promise<Policy> {\n return this.transport.request<Policy>({\n method: 'POST',\n path: '/policies',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List policies.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of policies\n */\n list(params?: ListParams): PaginatedIterator<Policy> {\n return this.paginate<Policy>('/policies', params);\n }\n\n /**\n * Get a policy by ID.\n *\n * @param policyId - Policy ID\n * @returns Policy record\n */\n async get(policyId: string): Promise<Policy> {\n return this.transport.request<Policy>({\n method: 'GET',\n path: `/policies/${policyId}`,\n });\n }\n\n /**\n * Delete a policy.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DeletePolicyIntent`. The server rejects requests without a valid\n * endorsement body.\n *\n * @param policyId - Policy ID\n * @param options - Request options (must include `endorsement`)\n */\n async delete(policyId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Add a rule to a policy.\n *\n * @param policyId - Policy ID\n * @param data - Rule creation data\n * @returns Created rule\n */\n async addRule(\n policyId: string,\n data: PolicyRuleCreateRequest,\n options?: RequestOptions\n ): Promise<PolicyRule> {\n return this.transport.request<PolicyRule>({\n method: 'POST',\n path: `/policies/${policyId}/rules`,\n body: options?.endorsement ?? data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Update a policy rule.\n *\n * @param policyId - Policy ID\n * @param ruleId - Rule ID\n * @param data - Update data\n * @returns Updated rule\n */\n async updateRule(\n policyId: string,\n ruleId: string,\n data: Partial<PolicyRuleCreateRequest>,\n options?: RequestOptions\n ): Promise<PolicyRule> {\n return this.transport.request<PolicyRule>({\n method: 'PATCH',\n path: `/policies/${policyId}/rules/${ruleId}`,\n body: options?.endorsement ?? data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a policy rule.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `RemovePolicyRuleIntent`. The server rejects requests without a valid\n * endorsement body.\n *\n * @param policyId - Policy ID\n * @param ruleId - Rule ID\n * @param options - Request options (must include `endorsement`)\n */\n async deleteRule(policyId: string, ruleId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}/rules/${ruleId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get wallets attached to a policy.\n *\n * Returns slim references (id + name + family) for the wallets the policy is currently attached to.\n *\n * @param policyId - Policy ID\n * @returns Array of attached wallets\n */\n async getWallets(policyId: string): Promise<AttachedWallet[]> {\n return this.transport.request<AttachedWallet[]>({\n method: 'GET',\n path: `/policies/${policyId}/wallets`,\n });\n }\n\n /**\n * Attach a policy to a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `AttachPolicyToWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param policyId - Policy ID\n * @param walletId - Wallet ID\n * @param options - Request options (must include `endorsement`)\n */\n async attachToWallet(\n policyId: string,\n walletId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'PUT',\n path: `/policies/${policyId}/wallets/${walletId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Detach a policy from a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DetachPolicyFromWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param policyId - Policy ID\n * @param walletId - Wallet ID\n * @param options - Request options (must include `endorsement`)\n */\n async detachFromWallet(\n policyId: string,\n walletId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/policies/${policyId}/wallets/${walletId}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Pluggable signers for governance intents.\n *\n * A signer turns the intent's canonical bytes into one `signatures[]` entry.\n * The SDK ships three:\n * - ES256 on a server: `ES256Signer` (also exported as `P256MandateSigner`) in the\n * main entry, or your own HSM/KMS behind this interface.\n * - ES256 in a browser: {@link webCryptoES256Signer} over a WebCrypto key.\n * - Passkey: `webauthnSigner` from this entry point.\n */\n\nimport { bytesToBase64, toBytes } from './encoding.js';\nimport type { CanonicalIntent } from './intents.js';\n\n/**\n * Produces one `signatures[]` entry over a governance intent's canonical\n * bytes. For ES256 that is base64 of the ASN.1 DER ECDSA signature over\n * SHA-256(payload); for a passkey it is the packed assertion.\n */\nexport interface GovernanceSigner {\n sign(payload: Uint8Array): Promise<string> | string;\n}\n\n/** A {@link GovernanceSigner} or a bare signing function. */\nexport type GovernanceSignerLike =\n | GovernanceSigner\n | ((payload: Uint8Array) => Promise<string> | string);\n\n/**\n * Sign an intent with each signer, one after another (passkey prompts must\n * not overlap), and return the signatures in signer order.\n *\n * @throws when `signers` is empty or a signer returns an empty signature\n */\nexport async function signGovernanceIntent(\n intent: CanonicalIntent | Uint8Array,\n signers: readonly GovernanceSignerLike[]\n): Promise<string[]> {\n if (!Array.isArray(signers) || signers.length === 0) {\n throw new TypeError('a governance change needs at least one signer');\n }\n const bytes = ArrayBuffer.isView(intent) ? toBytes(intent) : intent.bytes;\n const out: string[] = [];\n for (const s of signers) {\n // Each signer gets its own copy, so one cannot alter what the next signs.\n const sig = typeof s === 'function' ? await s(bytes.slice()) : await s.sign(bytes.slice());\n if (typeof sig !== 'string' || sig === '') {\n throw new Error('a governance signer returned an empty signature');\n }\n out.push(sig);\n }\n return out;\n}\n\n/**\n * The part of WebCrypto's `SubtleCrypto` the ES256 signer uses. Declared\n * structurally so the SDK does not need the DOM type library; a real\n * `crypto.subtle` (browser, Deno, Node's `webcrypto.subtle`) satisfies it.\n */\nexport interface SubtleCryptoLike {\n sign(\n algorithm: { name: 'ECDSA'; hash: 'SHA-256' },\n key: never,\n data: ArrayBuffer\n ): Promise<ArrayBuffer>;\n}\n\n/**\n * An ES256 {@link GovernanceSigner} over a WebCrypto P-256 private key, for\n * browsers and other runtimes without `node:crypto`. The key can be\n * non-extractable. WebCrypto returns raw `r || s`; this converts it to the\n * ASN.1 DER form the platform verifies.\n *\n * @param privateKey - an ECDSA P-256 `CryptoKey` with the `sign` usage\n * (typed loosely so the SDK does not require the DOM type library)\n * @param subtle - the SubtleCrypto to use (defaults to `globalThis.crypto.subtle`)\n */\nexport function webCryptoES256Signer(\n privateKey: object,\n subtle?: SubtleCryptoLike\n): GovernanceSigner {\n return {\n async sign(payload: Uint8Array): Promise<string> {\n const s = subtle ?? (globalThis as { crypto?: { subtle?: SubtleCryptoLike } }).crypto?.subtle;\n if (!s) {\n throw new Error(\n 'WebCrypto is not available: pass a SubtleCrypto or use ES256Signer on Node'\n );\n }\n const raw = new Uint8Array(\n await s.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n privateKey as never,\n toArrayBuffer(payload)\n )\n );\n return bytesToBase64(p1363ToDer(raw));\n },\n };\n}\n\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n const out = new ArrayBuffer(bytes.length);\n new Uint8Array(out).set(bytes);\n return out;\n}\n\n/** IEEE P1363 `r || s` (64 bytes for P-256) to an ASN.1 DER ECDSA signature. */\nfunction p1363ToDer(sig: Uint8Array): Uint8Array {\n if (sig.length !== 64) {\n throw new Error(`expected a 64-byte P-256 signature, got ${sig.length} bytes`);\n }\n const int = (bytes: Uint8Array): Uint8Array => {\n let i = 0;\n while (i < bytes.length - 1 && bytes[i] === 0) i++;\n const trimmed = bytes.slice(i);\n // A leading 1 bit would make the INTEGER negative: prefix a zero byte.\n const body = trimmed[0]! & 0x80 ? Uint8Array.of(0, ...trimmed) : trimmed;\n return Uint8Array.of(0x02, body.length, ...body);\n };\n const r = int(sig.slice(0, 32));\n const s = int(sig.slice(32));\n return Uint8Array.of(0x30, r.length + s.length, ...r, ...s);\n}\n","/**\n * Signer Groups resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport { randomUUID } from 'node:crypto';\n\nimport { StaleSignerGroupVersionError } from '../errors.js';\nimport {\n addSignersToGroupIntent,\n assertIdempotencyKey,\n newIdempotencyKey,\n removeSignersFromGroupIntent,\n updateSignerGroupGovernanceIntent,\n type CanonicalIntent,\n} from '../../governance/intents.js';\nimport { signGovernanceIntent, type GovernanceSignerLike } from '../../governance/signer.js';\nimport { utf8 } from '../../governance/encoding.js';\nimport type {\n SignerGroup,\n SignerGroupCreateRequest,\n SignerGroupGetParams,\n SignerGroupGovernanceSettings,\n SignerGroupGovernanceUpdateRequest,\n SignerGroupSignerAddRequest,\n SignerGroupSignerRemovalRequest,\n Signer,\n SignerCreateRequest,\n AttachedWallet,\n ListParams,\n PreparedSignerGroupChange,\n PrepareSignerGroupChangeOptions,\n RequestOptions,\n SignedSignerGroupChangeOptions,\n} from '../types.js';\n\n/**\n * Signer Groups API resource.\n */\nexport class SignerGroupsResource extends BaseResource {\n /**\n * Create a new signer group.\n *\n * @param data - Signer group creation data\n * @returns Created signer group\n */\n async create(data: SignerGroupCreateRequest, options?: RequestOptions): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'POST',\n path: '/signer-groups',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List signer groups.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of signer groups\n */\n list(params?: ListParams): PaginatedIterator<SignerGroup> {\n return this.paginate<SignerGroup>('/signer-groups', params);\n }\n\n /**\n * Get a signer group by ID.\n *\n * Pass `{ include_removed: true }` to also get a `removed_members` array of\n * signers that were removed from this group, each carrying its `removed_at`\n * timestamp. Defaults to active members only.\n *\n * @param signerGroupId - Signer group ID\n * @param params - Optional `{ include_removed }`\n * @returns Signer group record\n *\n * @example\n * ```typescript\n * const group = await client.signerGroups.get(groupId, { include_removed: true });\n * for (const s of group.removed_members ?? []) {\n * console.log(s.name, 'removed at', s.removed_at);\n * }\n * ```\n */\n async get(signerGroupId: string, params?: SignerGroupGetParams): Promise<SignerGroup> {\n return this.transport.request<SignerGroup>({\n method: 'GET',\n path: `/signer-groups/${seg(signerGroupId)}`,\n query: { ...params },\n });\n }\n\n /**\n * Add an existing signer's public key to a group.\n *\n * The endpoint takes `{ member_key }` — the base64 PKIX (SPKI) public\n * key of an existing signer resource — not a fresh signer definition.\n * Returns the updated group (with the new member included).\n *\n * A governed group (governance settings, or a client with governance\n * enforcement on) refuses an unsigned add with\n * `EndorsementRequiredError`; use {@link addSignerSigned} instead, or pass\n * `signatures` + `signer_group_version` yourself with the SAME idempotency\n * key that is inside the signed intent.\n *\n * @param signerGroupId - Signer group ID\n * @param data - `{ member_key }` (the signer's base64 PKIX public key)\n * @returns The updated signer group\n */\n async addSigner(\n signerGroupId: string,\n data: SignerGroupSignerAddRequest,\n options?: RequestOptions\n ): Promise<SignerGroup> {\n if (data.signatures !== undefined) {\n requireSignedKey('addSigner', options);\n }\n return this.transport.request<SignerGroup>({\n method: 'POST',\n path: `/signer-groups/${seg(signerGroupId)}/signers`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Remove ONE signer from a group, unsigned, by its KSUID `signer_id`\n * (`DELETE /signer-groups/{id}/signers/{signer_id}`).\n *\n * A governed group refuses this with `EndorsementRequiredError`; use\n * {@link removeSignersSigned} instead. Not to be confused with\n * {@link removeSigners} (plural), the signed removal by PUBLIC KEY.\n *\n * @param signerGroupId - Signer group ID\n * @param signerId - The signer's KSUID `signer_id` — NOT its public key.\n * (The standalone `client.signers.delete()` takes the public key instead.)\n * @param options - Optional request options (e.g. an explicit idempotency\n * key — the platform requires one on this DELETE)\n */\n async removeSigner(\n signerGroupId: string,\n signerId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/signer-groups/${seg(signerGroupId)}/signers/${seg(signerId)}`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n // --------------------------------------------------------------------------\n // Signed (governed) membership and governance changes\n // --------------------------------------------------------------------------\n\n /**\n * Remove members by PUBLIC KEY, with signatures from the group's governance\n * (`POST /signer-groups/{id}/signer-removals`). Low level: you supply the\n * signed body, and `options.idempotencyKey` is required and MUST be the key\n * inside the signed intent. Prefer {@link removeSignersSigned}. (The\n * singular {@link removeSigner} is the unsigned removal by `signer_id`.)\n */\n async removeSigners(\n signerGroupId: string,\n data: SignerGroupSignerRemovalRequest,\n options?: RequestOptions\n ): Promise<SignerGroup> {\n requireSignedKey('removeSigners', options);\n return this.transport.request<SignerGroup>({\n method: 'POST',\n path: `/signer-groups/${seg(signerGroupId)}/signer-removals`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Replace a group's governance settings with signatures from its current\n * governance (`PATCH /signer-groups/{id}/governance`). The body is the\n * WHOLE state: a setting left out is cleared. Low level: you supply the\n * signed body, and `options.idempotencyKey` is required and MUST be the key\n * inside the signed intent. Prefer {@link updateGovernanceSigned}.\n */\n async updateGovernance(\n signerGroupId: string,\n data: SignerGroupGovernanceUpdateRequest,\n options?: RequestOptions\n ): Promise<SignerGroup> {\n requireSignedKey('updateGovernance', options);\n return this.transport.request<SignerGroup>({\n method: 'PATCH',\n path: `/signer-groups/${seg(signerGroupId)}/governance`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Build (but do not sign or send) the change that adds `memberKey` to the\n * group. Reads the group's current `version` unless\n * `options.signerGroupVersion` is given, and generates a lowercase UUID\n * idempotency key unless one is given.\n *\n * Use it when the signatures are collected elsewhere — for example a\n * passkey in the user's browser: send `change.canonical` there, pass it to\n * `buildChallenge`, then give the packed assertions to\n * {@link submitSignedChange}.\n */\n async prepareAddSigner(\n signerGroupId: string,\n memberKey: string,\n options?: PrepareSignerGroupChangeOptions\n ): Promise<PreparedSignerGroupChange> {\n return this.prepareChange(\n 'add_signers_to_group',\n signerGroupId,\n { memberKeys: [memberKey] },\n options\n );\n }\n\n /**\n * Build (but do not sign or send) the change that removes `memberKeys`\n * (public keys, as the group lists them; signed in this order).\n */\n async prepareRemoveSigners(\n signerGroupId: string,\n memberKeys: readonly string[],\n options?: PrepareSignerGroupChangeOptions\n ): Promise<PreparedSignerGroupChange> {\n return this.prepareChange(\n 'remove_signers_from_group',\n signerGroupId,\n { memberKeys: [...memberKeys] },\n options\n );\n }\n\n /**\n * Build (but do not sign or send) the change that sets the group's\n * governance to `settings`. It replaces the whole state: a setting left\n * out or null is cleared.\n */\n async prepareGovernanceUpdate(\n signerGroupId: string,\n settings: SignerGroupGovernanceSettings,\n options?: PrepareSignerGroupChangeOptions\n ): Promise<PreparedSignerGroupChange> {\n const governance: { governance_threshold?: number; governance_signer_group_id?: string } = {};\n if (settings.governance_threshold !== undefined && settings.governance_threshold !== null) {\n governance.governance_threshold = settings.governance_threshold;\n }\n if (\n settings.governance_signer_group_id !== undefined &&\n settings.governance_signer_group_id !== null\n ) {\n governance.governance_signer_group_id = settings.governance_signer_group_id;\n }\n return this.prepareChange(\n 'update_signer_group_governance',\n signerGroupId,\n { governance },\n options\n );\n }\n\n /**\n * Send a prepared change with its signatures (ES256 DER base64, or packed\n * passkey assertions), using the change's idempotency key as\n * `X-Idempotency-Key`. Re-checks that the change still matches the intent\n * that was signed and refuses it otherwise, without sending anything.\n *\n * @throws EndorsementRequiredError, InsufficientEndorsementsError,\n * StaleSignerGroupVersionError, BelowThresholdError (all APIError)\n */\n async submitSignedChange(\n change: PreparedSignerGroupChange,\n signatures: readonly string[],\n options?: Pick<RequestOptions, 'timeout'>\n ): Promise<SignerGroup> {\n if (\n !Array.isArray(signatures) ||\n signatures.length === 0 ||\n signatures.some((s) => typeof s !== 'string' || s === '')\n ) {\n throw new TypeError('a signed change needs at least one non-empty signature');\n }\n const built = buildChangeIntent(change);\n if (built.canonical !== change.canonical) {\n throw new Error(\n 'the prepared change does not match the intent that was signed (it was altered after it was prepared); prepare it again'\n );\n }\n // Every body field comes from the intent that was rebuilt and checked\n // above, never from the stored change, so nothing unsigned goes out.\n const i = built.intent;\n const requestOptions = { idempotencyKey: i.idempotency_key, timeout: options?.timeout };\n const sigs = [...signatures];\n switch (i.type) {\n case 'add_signers_to_group':\n return this.addSigner(\n i.signer_group_id,\n {\n member_key: i.new_member_keys[0]!,\n signer_group_version: i.signer_group_version,\n signatures: sigs,\n },\n requestOptions\n );\n case 'remove_signers_from_group':\n return this.removeSigners(\n i.group_id,\n {\n members_to_remove: [...i.members_to_remove],\n signer_group_version: i.signer_group_version,\n signatures: sigs,\n },\n requestOptions\n );\n case 'update_signer_group_governance': {\n const body: SignerGroupGovernanceUpdateRequest = {\n ...(i.governance_threshold !== undefined && {\n governance_threshold: i.governance_threshold,\n }),\n ...(i.governance_signer_group_id !== undefined && {\n governance_signer_group_id: i.governance_signer_group_id,\n }),\n signer_group_version: i.signer_group_version,\n signatures: sigs,\n };\n return this.updateGovernance(i.signer_group_id, body, requestOptions);\n }\n default:\n throw new TypeError(`cannot submit a ${i.type} change from signerGroups`);\n }\n }\n\n /**\n * Add `memberKey` to a governed group in one call: read the version, build\n * the `add_signers_to_group` intent, sign it with each signer (in order),\n * and send it with the same idempotency key in the intent and the header.\n *\n * @param signers - ES256 signers (`ES256Signer`, your KMS) or plain\n * `(bytes) => signature` functions; together they must meet the group's\n * `effective_governance_threshold`. For a passkey in the user's browser\n * or app, use {@link prepareAddSigner} + {@link submitSignedChange}\n * instead, so the API key stays on your server; `webauthnSigner` fits\n * here only when the passkey prompt runs in the same process as this\n * client. Each stale retry calls every signer again.\n * @example\n * ```typescript\n * const group = await client.signerGroups.addSignerSigned(groupId, newKey, [\n * ES256Signer.fromPrivateKey(adminKeyPem),\n * ]);\n * ```\n */\n async addSignerSigned(\n signerGroupId: string,\n memberKey: string,\n signers: readonly GovernanceSignerLike[],\n options?: SignedSignerGroupChangeOptions\n ): Promise<SignerGroup> {\n return this.signAndSubmit(\n () => this.prepareAddSigner(signerGroupId, memberKey, options),\n signers,\n options\n );\n }\n\n /** Remove `memberKeys` from a governed group in one call; see {@link addSignerSigned}. */\n async removeSignersSigned(\n signerGroupId: string,\n memberKeys: readonly string[],\n signers: readonly GovernanceSignerLike[],\n options?: SignedSignerGroupChangeOptions\n ): Promise<SignerGroup> {\n return this.signAndSubmit(\n () => this.prepareRemoveSigners(signerGroupId, memberKeys, options),\n signers,\n options\n );\n }\n\n /**\n * Replace a group's governance settings in one call; see\n * {@link addSignerSigned}. Signed by the group's CURRENT governance.\n *\n * `staleRetries` is refused here: the change replaces the WHOLE governance\n * state, so re-signing it after someone else changed the group would\n * silently undo their change. On `StaleSignerGroupVersionError`, re-read\n * the group, decide, and call again.\n */\n async updateGovernanceSigned(\n signerGroupId: string,\n settings: SignerGroupGovernanceSettings,\n signers: readonly GovernanceSignerLike[],\n options?: SignedSignerGroupChangeOptions\n ): Promise<SignerGroup> {\n if (options?.staleRetries) {\n throw new TypeError(\n 'staleRetries is not supported on updateGovernanceSigned: a re-sign after a concurrent change would undo it'\n );\n }\n return this.signAndSubmit(\n () => this.prepareGovernanceUpdate(signerGroupId, settings, options),\n signers,\n options\n );\n }\n\n private async prepareChange(\n kind: PreparedSignerGroupChange['kind'],\n signerGroupId: string,\n fields: Pick<PreparedSignerGroupChange, 'memberKeys' | 'governance'>,\n options?: PrepareSignerGroupChangeOptions\n ): Promise<PreparedSignerGroupChange> {\n if (options?.idempotencyKey !== undefined) {\n assertIdempotencyKey(options.idempotencyKey);\n }\n const signerGroupVersion =\n options?.signerGroupVersion ?? (await this.currentVersion(signerGroupId));\n const draft = {\n kind,\n signerGroupId,\n signerGroupVersion,\n idempotencyKey: options?.idempotencyKey ?? governanceIdempotencyKey(),\n ...fields,\n canonical: '',\n };\n return { ...draft, canonical: buildChangeIntent(draft).canonical };\n }\n\n private async currentVersion(signerGroupId: string): Promise<number> {\n const group = await this.get(signerGroupId);\n if (typeof group.version !== 'number') {\n throw new Error(\n `signer group ${signerGroupId} has no version in the response, so a signed change cannot be built; pass signerGroupVersion if you know it`\n );\n }\n return group.version;\n }\n\n private async signAndSubmit(\n prepare: () => Promise<PreparedSignerGroupChange>,\n signers: readonly GovernanceSignerLike[],\n options?: SignedSignerGroupChangeOptions\n ): Promise<SignerGroup> {\n if (!Array.isArray(signers) || signers.length === 0) {\n throw new TypeError('a governance change needs at least one signer');\n }\n let retries = staleRetryBudget(options);\n for (;;) {\n const change = await prepare();\n const signatures = await signGovernanceIntent(utf8(change.canonical), signers);\n try {\n return await this.submitSignedChange(change, signatures, { timeout: options?.timeout });\n } catch (err) {\n if (err instanceof StaleSignerGroupVersionError && retries > 0) {\n retries--;\n continue;\n }\n throw err;\n }\n }\n }\n\n /**\n * Get wallets attached to a signer group.\n *\n * Returns slim references (id + name + family) for the wallets the signer group is currently attached to.\n *\n * @param signerGroupId - Signer group ID\n * @returns Array of attached wallets\n */\n async getWallets(signerGroupId: string): Promise<AttachedWallet[]> {\n return this.transport.request<AttachedWallet[]>({\n method: 'GET',\n path: `/signer-groups/${seg(signerGroupId)}/wallets`,\n });\n }\n\n /**\n * Attach a signer group to a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `AttachGroupToWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param walletId - Wallet ID\n * @param signerGroupId - Signer group ID\n * @param options - Request options (must include `endorsement`)\n */\n async attachToWallet(\n walletId: string,\n signerGroupId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'PUT',\n path: `/wallets/${seg(walletId)}/signer-groups/${seg(signerGroupId)}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Detach a signer group from a wallet.\n *\n * Endorsed endpoint — `options.endorsement` must contain a signed\n * `DetachGroupFromWalletIntent`. The server rejects requests without a\n * valid endorsement body.\n *\n * @param walletId - Wallet ID\n * @param signerGroupId - Signer group ID\n * @param options - Request options (must include `endorsement`)\n */\n async detachFromWallet(\n walletId: string,\n signerGroupId: string,\n options?: RequestOptions\n ): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/wallets/${seg(walletId)}/signer-groups/${seg(signerGroupId)}`,\n body: options?.endorsement,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List signer groups attached to a wallet.\n *\n * @param walletId - Wallet ID\n * @param params - Pagination parameters\n * @returns Async iterator of signer groups\n */\n listForWallet(walletId: string, params?: ListParams): PaginatedIterator<SignerGroup> {\n return this.paginate<SignerGroup>(`/wallets/${walletId}/signer-groups`, params);\n }\n}\n\n/**\n * One id as a URL path segment. Ids are plain tokens today; encoding keeps a\n * value from elsewhere (a prepared change that went through a browser, say)\n * from reaching a different route with this client's API key.\n * `encodeURIComponent` leaves `.` and `..` alone, and URL parsing resolves\n * them as dot segments, so those (and an empty id) are refused outright.\n */\nfunction seg(id: string): string {\n if (typeof id !== 'string' || id === '' || id === '.' || id === '..') {\n throw new TypeError(`invalid id for a request path: ${JSON.stringify(id)}`);\n }\n return encodeURIComponent(id);\n}\n\n/** Most stale re-signs the one-call helpers will make (each may prompt a passkey). */\nconst MAX_STALE_RETRIES = 5;\n\nfunction staleRetryBudget(options?: SignedSignerGroupChangeOptions): number {\n const n = options?.staleRetries ?? 0;\n if (!Number.isInteger(n) || n < 0 || n > MAX_STALE_RETRIES) {\n throw new TypeError(`staleRetries must be an integer from 0 to ${MAX_STALE_RETRIES}`);\n }\n // A fixed version or key would sign the same stale intent again.\n if (\n n > 0 &&\n (options?.signerGroupVersion !== undefined || options?.idempotencyKey !== undefined)\n ) {\n throw new TypeError(\n 'staleRetries cannot be combined with a fixed signerGroupVersion or idempotencyKey: a retry needs a fresh read and a fresh key'\n );\n }\n return n;\n}\n\n/**\n * The idempotency key for a new signed change: a lowercase v4 UUID from the\n * runtime's WebCrypto, else from `node:crypto` (Node 18 has no global\n * `crypto` by default).\n */\nfunction governanceIdempotencyKey(): string {\n const c = (globalThis as { crypto?: { randomUUID?: unknown } }).crypto;\n return typeof c?.randomUUID === 'function' ? newIdempotencyKey() : randomUUID().toLowerCase();\n}\n\n/** A signed request carries the key inside its signed intent; it must not be generated here. */\nfunction requireSignedKey(method: string, options?: RequestOptions): void {\n if (!options?.idempotencyKey) {\n throw new TypeError(\n `${method} with signatures needs options.idempotencyKey: the idempotency_key inside the signed intent (a generated one could never match)`\n );\n }\n assertIdempotencyKey(options.idempotencyKey);\n}\n\n/**\n * Rebuild the canonical intent a prepared change stands for. Validates its\n * fields on the way (lowercase UUID key, non-negative version, keys).\n */\nfunction buildChangeIntent(change: PreparedSignerGroupChange): CanonicalIntent {\n const common = {\n signerGroupId: change.signerGroupId,\n signerGroupVersion: change.signerGroupVersion,\n idempotencyKey: change.idempotencyKey,\n };\n switch (change.kind) {\n case 'add_signers_to_group':\n if (!change.memberKeys || change.memberKeys.length !== 1) {\n throw new TypeError(\n 'an add change carries exactly one member key (the endpoint adds one per request)'\n );\n }\n return addSignersToGroupIntent({ ...common, newMemberKeys: change.memberKeys });\n case 'remove_signers_from_group':\n return removeSignersFromGroupIntent({ ...common, membersToRemove: change.memberKeys ?? [] });\n case 'update_signer_group_governance':\n return updateSignerGroupGovernanceIntent({\n ...common,\n governanceThreshold: change.governance?.governance_threshold,\n governanceSignerGroupId: change.governance?.governance_signer_group_id,\n });\n default:\n throw new TypeError(\n `unknown signer-group change kind ${JSON.stringify((change as { kind: unknown }).kind)}`\n );\n }\n}\n\n/**\n * Signers API resource.\n */\nexport class SignersResource extends BaseResource {\n /**\n * Create a new signer.\n *\n * @param data - Signer creation data (name, public_key, key_type)\n * @param options - Request options\n * @returns Created signer\n */\n async create(data: SignerCreateRequest, options?: RequestOptions): Promise<Signer> {\n return this.transport.request<Signer>({\n method: 'POST',\n path: '/signers',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a signer by public key.\n *\n * Soft-deletes all signers with the given public key.\n *\n * @param publicKey - Signer public key\n */\n async delete(publicKey: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/signers/${publicKey}`,\n });\n }\n}\n","/**\n * API Keys resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n ApiKey,\n ApiKeyResponse,\n ApiKeyCreateRequest,\n ApiKeyUpdateRequest,\n CreateApiKeyForClientRequest,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * API Keys API resource.\n */\nexport class ApiKeysResource extends BaseResource {\n /**\n * Create a new API key.\n *\n * @param data - API key creation data\n * @returns Created API key (includes secret, only shown once)\n */\n async create(data: ApiKeyCreateRequest, options?: RequestOptions): Promise<ApiKeyResponse> {\n return this.transport.request<ApiKeyResponse>({\n method: 'POST',\n path: '/api-keys',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List API keys.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of API keys\n */\n list(params?: ListParams): PaginatedIterator<ApiKey> {\n return this.paginate<ApiKey>('/api-keys', params);\n }\n\n /**\n * Change the name, the scope, or both, of an API key. A new scope applies\n * from the next request made with the key. The key value does not change.\n *\n * @param apiKeyId - API key ID\n * @param data - The new name, the new scope, or both\n * @returns The updated API key\n */\n async update(\n apiKeyId: string,\n data: ApiKeyUpdateRequest,\n options?: RequestOptions\n ): Promise<ApiKey> {\n return this.transport.request<ApiKey>({\n method: 'PATCH',\n path: `/api-keys/${apiKeyId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete an API key.\n *\n * @param apiKeyId - API key ID\n */\n async delete(apiKeyId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/api-keys/${apiKeyId}`,\n });\n }\n\n /**\n * Delete all API keys.\n *\n * Intended for incident response only.\n */\n async deleteAll(): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: '/api-keys',\n });\n }\n\n /**\n * Create an API key for a specific client (admin only).\n *\n * Requires admin access token.\n *\n * @param data - Request data containing `client_id`\n * @param options - Request options\n * @returns Created API key response (includes key, only shown once)\n */\n async createForClient(\n data: CreateApiKeyForClientRequest,\n options?: RequestOptions\n ): Promise<ApiKeyResponse> {\n return this.transport.request<ApiKeyResponse>({\n method: 'POST',\n path: '/api-keys/admin',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Users resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n User,\n UserCreateRequest,\n UserUpdateRequest,\n UserListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Users API resource.\n */\nexport class UsersResource extends BaseResource {\n /**\n * Create a new user.\n *\n * @param data - User creation data\n * @returns Created user\n */\n async create(data: UserCreateRequest, options?: RequestOptions): Promise<User> {\n return this.transport.request<User>({\n method: 'POST',\n path: '/users',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List users.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of users\n */\n list(params?: UserListParams): PaginatedIterator<User> {\n return this.paginate<User>('/users', params);\n }\n\n /**\n * Update a user.\n *\n * @param userId - User ID\n * @param data - Update data (first_name, last_name, role)\n */\n async update(userId: string, data: UserUpdateRequest, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'PATCH',\n path: `/users/${userId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a user.\n *\n * @param userId - User ID\n */\n async delete(userId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/users/${userId}`,\n });\n }\n}\n","/**\n * Webhooks resource.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n WebhookTarget,\n WebhookTargetCreateRequest,\n WebhookTargetUpdateRequest,\n WebhookEvent,\n WebhookReplayResponse,\n WebhookHistoryListParams,\n WebhookHistoryResponse,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Webhooks API resource.\n */\nexport class WebhooksResource extends BaseResource {\n /**\n * Create a new webhook target.\n *\n * @param data - Webhook target creation data\n * @returns Created webhook target\n */\n async createTarget(\n data: WebhookTargetCreateRequest,\n options?: RequestOptions\n ): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'POST',\n path: '/webhooks/targets',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List webhook targets.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of webhook targets\n */\n listTargets(params?: ListParams): PaginatedIterator<WebhookTarget> {\n return this.paginate<WebhookTarget>('/webhooks/targets', params);\n }\n\n /**\n * Get a webhook target by ID.\n *\n * @param targetId - Webhook target ID\n * @returns Webhook target record\n */\n async getTarget(targetId: string): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'GET',\n path: `/webhooks/targets/${targetId}`,\n });\n }\n\n /**\n * Update a webhook target.\n *\n * @param targetId - Webhook target ID\n * @param data - Update data\n * @returns Updated webhook target\n */\n async updateTarget(\n targetId: string,\n data: WebhookTargetUpdateRequest,\n options?: RequestOptions\n ): Promise<WebhookTarget> {\n return this.transport.request<WebhookTarget>({\n method: 'PATCH',\n path: `/webhooks/targets/${targetId}`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Delete a webhook target.\n *\n * @param targetId - Webhook target ID\n */\n async deleteTarget(targetId: string): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: `/webhooks/targets/${targetId}`,\n });\n }\n\n /**\n * List webhook delivery history.\n *\n * Note: This endpoint uses cursor-based pagination (`cursor`/`has_more`) instead\n * of the standard `starting_after`/`has_more_after` format. Because of this,\n * it returns the raw response rather than a `PaginatedIterator`. Use the `cursor`\n * field from the response to fetch subsequent pages.\n *\n * @param params - Webhook history query parameters\n * @returns Webhook history response with `data`, `has_more`, and `cursor`\n *\n * @example\n * ```typescript\n * let cursor: string | undefined;\n * do {\n * const page = await client.webhooks.listEvents({ limit: 50, cursor });\n * for (const event of page.data) {\n * console.log(event);\n * }\n * cursor = page.cursor ?? undefined;\n * } while (page.has_more);\n * ```\n */\n async listEvents(params?: WebhookHistoryListParams): Promise<WebhookHistoryResponse> {\n const query: Record<string, string | number | boolean | undefined> = {};\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n query[key] = value as string | number | boolean;\n }\n }\n }\n return this.transport.request<WebhookHistoryResponse>({\n method: 'GET',\n path: '/webhooks',\n query,\n });\n }\n\n /**\n * Get a webhook event by ID.\n *\n * @param eventId - Webhook event ID\n * @returns Webhook event record\n */\n async getEvent(eventId: string): Promise<WebhookEvent> {\n return this.transport.request<WebhookEvent>({\n method: 'GET',\n path: `/webhooks/${eventId}`,\n });\n }\n\n /**\n * Replay a webhook event.\n *\n * Re-queues the webhook for delivery to all configured targets.\n *\n * @param eventId - Webhook event ID\n * @param options - Request options\n * @returns Replay response with `webhook_id`, `status`, and `replayed_to_count`\n */\n async replayEvent(eventId: string, options?: RequestOptions): Promise<WebhookReplayResponse> {\n return this.transport.request<WebhookReplayResponse>({\n method: 'POST',\n path: `/webhooks/events/${eventId}/replay`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Info resource for platform capabilities.\n */\n\nimport { BaseResource } from './base.js';\nimport type { Country } from '../types.js';\n\n/**\n * Info API resource for platform capabilities.\n */\nexport class InfoResource extends BaseResource {\n /**\n * Get supported countries.\n *\n * @returns Array of supported countries\n *\n * @example\n * ```typescript\n * const countries = await client.info.getCountries();\n * ```\n */\n async getCountries(): Promise<Country[]> {\n // /capabilities/countries returns Country[] directly, not the\n // paginated { data, meta } envelope. Earlier versions read\n // response.data here and silently returned undefined.\n return this.transport.request<Country[]>({\n method: 'GET',\n path: '/capabilities/countries',\n });\n }\n\n /**\n * Get supported networks.\n *\n * @returns Array of supported networks\n *\n * @example\n * ```typescript\n * const networks = await client.info.getNetworks();\n * for (const network of networks) {\n * console.log(network.id, network.name);\n * }\n * ```\n */\n async getNetworks(): Promise<string[]> {\n // /capabilities/networks returns string[] (network IDs like\n // \"ethereum-mainnet\") directly, not the paginated { data, meta }\n // envelope. Earlier versions typed this as Network[] and read\n // response.data, which silently returned undefined.\n return this.transport.request<string[]>({\n method: 'GET',\n path: '/capabilities/networks',\n });\n }\n}\n","/**\n * Legal documents resource.\n */\n\nimport { BaseResource } from './base.js';\nimport type { LegalDocument } from '../types.js';\n\n/**\n * Legal Documents API resource.\n *\n * The published terms a customer accepts during onboarding. **Unauthenticated**\n * — integrators need these before a customer relationship exists, so the\n * endpoints carry no credential and are safe to call from a signup page.\n */\nexport class LegalResource extends BaseResource {\n /**\n * List the revision of every legal document currently in force.\n *\n * An INDEX, not a bundle: each entry names a document and its in-force\n * revision, without the text. Fetch {@link get} for the one document you\n * are about to display — inlining every document would put the whole corpus\n * on every call.\n *\n * Not safe to cache indefinitely: it names whichever revision is in force\n * NOW, and that changes when a new one is published. A specific\n * `(key, version)` from {@link get} is a different matter — revisions are\n * immutable, so that text can be cached for as long as you like.\n *\n * @returns The in-force revision of each document, without its text\n *\n * @example\n * ```typescript\n * for (const doc of await client.legal.list()) {\n * console.log(doc.key, doc.version, doc.title);\n * }\n * ```\n */\n async list(): Promise<LegalDocument[]> {\n const response = await this.transport.request<{ data: LegalDocument[] }>({\n method: 'GET',\n path: '/legal/documents',\n });\n return response.data ?? [];\n }\n\n /**\n * Get one legal document — the revision in force, or a specific one.\n *\n * Pass the `version` you displayed back as `legal_document_version` when\n * submitting an attestation, so the acceptance record names the exact text\n * the customer saw rather than whichever revision happened to be current\n * when the request arrived.\n *\n * @param documentKey - Document identifier, e.g. `'dakota_tos'`\n * @param version - A specific published revision. Omit for the one in force\n * @returns The requested revision, including its text\n *\n * @example\n * ```typescript\n * const tos = await client.legal.get('dakota_tos');\n * render(tos.content);\n *\n * await client.applications.submitAttestation(applicationId, {\n * attestation_type: 'terms_of_service',\n * legal_document_version: tos.version, // records what they actually saw\n * // ...\n * });\n * ```\n */\n async get(documentKey: string, version?: string): Promise<LegalDocument> {\n return this.transport.request<LegalDocument>({\n method: 'GET',\n path: `/legal/documents/${documentKey}`,\n query: version !== undefined ? { version } : undefined,\n });\n }\n}\n","/**\n * Reserve-management marketing-fee statements resource.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n RDMarketingFeeStatement,\n RDPayoutDestination,\n RDPayoutDestinationRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * RD Marketing Fee API resource.\n *\n * The reserve-management statements for the calling client. The client comes\n * from the session and is never named in a request, so there is no id to pass\n * and no other client's statements to address.\n *\n * A client who has never had a rate gets a **404** from the two statement\n * methods: holding a rate is what being in the programme means, and there is\n * no separate entitlement record to read. The payout-destination methods\n * answer differently — see each: there a 404 means \"nothing registered yet\"\n * and it is 403 that means \"not in the programme\".\n */\nexport class RDMarketingFeeResource extends BaseResource {\n /**\n * The months this client has a statement for, newest first.\n *\n * Runs from the start of their contract to the running month, and the\n * RUNNING month IS included. It cannot be priced yet — the bank's interest\n * posts in the month after it is earned — but the balance is real and\n * accruing, and a client checking mid-month has to be able to see it. Its\n * fee figures come back absent rather than zero.\n *\n * An EMPTY list means the contract is real but no month has started yet.\n * That is different from a 404, which means no contract at all.\n *\n * @returns Statement months as `YYYY-MM-DD` (first day of the month, UTC)\n *\n * @example\n * ```typescript\n * const months = await client.rdMarketingFee.listMonths();\n * if (months.length === 0) {\n * // Contract starts next month or later — \"starting soon\", not an error.\n * }\n * ```\n */\n async listMonths(): Promise<string[]> {\n const response = await this.transport.request<{ months?: string[] }>({\n method: 'GET',\n path: '/rd-marketing-fee/statements',\n });\n return response.months ?? [];\n }\n\n /**\n * One month's statement — one row per calendar day: the date, the RD\n * balance, and that day's fee.\n *\n * The rows are the STORED daily principals, read rather than recomputed, so\n * what the client reads and what Dakota priced cannot drift.\n *\n * Absent is not zero. A balance is absent when the day has not been derived\n * yet and `'0'` when the client genuinely held no RD; fees are absent for\n * every day of a month whose rate has not been derived. Neither unknown is\n * reported as a zero, so render an absent figure as unknown rather than\n * defaulting it.\n *\n * @param month - First day of the month, UTC, as `YYYY-MM-DD`\n * @returns The month's statement, one row per day\n *\n * @example\n * ```typescript\n * const statement = await client.rdMarketingFee.getStatement('2026-08-01');\n * for (const day of statement.daily) {\n * console.log(day.date, day.balance_minor ?? 'not yet derived');\n * }\n * ```\n */\n async getStatement(month: string): Promise<RDMarketingFeeStatement> {\n return this.transport.request<RDMarketingFeeStatement>({\n method: 'GET',\n path: `/rd-marketing-fee/statements/${month}`,\n });\n }\n\n /**\n * The wallet this client's RD marketing fee is sent to.\n *\n * A **404** here is the ordinary state for a client who has not registered\n * one yet — not an error. A **403** means the client is not in the\n * programme at all.\n *\n * @returns The registered destination: always on Base (`eip155:8453`)\n *\n * @example\n * ```typescript\n * try {\n * const dest = await client.rdMarketingFee.getPayoutDestination();\n * console.log(dest.address);\n * } catch (error) {\n * if (error instanceof APIError && error.statusCode === 404) {\n * // Nothing registered yet — prompt for one.\n * }\n * }\n * ```\n */\n async getPayoutDestination(): Promise<RDPayoutDestination> {\n return this.transport.request<RDPayoutDestination>({\n method: 'GET',\n path: '/rd-marketing-fee/payout-destination',\n });\n }\n\n /**\n * Register, or replace, the wallet the RD marketing fee is sent to.\n *\n * RD exists only on Base, so the chain is not a parameter — only an EVM\n * `address`. There is one destination per client, so this REPLACES any\n * existing one. Emits `rd_payout_destination.updated`.\n *\n * This is a SEPARATE registration from the developer-fee payout\n * destination (`client.feePayoutDestination`): the two programmes pay\n * different assets and are set independently.\n *\n * @param data - The EVM address on Base to pay the fee to\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The stored destination\n *\n * @example\n * ```typescript\n * const dest = await client.rdMarketingFee.setPayoutDestination({\n * address: '0x1234567890123456789012345678901234567890',\n * });\n * console.log(dest.chain); // 'eip155:8453'\n * ```\n */\n async setPayoutDestination(\n data: RDPayoutDestinationRequest,\n options?: RequestOptions\n ): Promise<RDPayoutDestination> {\n return this.transport.request<RDPayoutDestination>({\n method: 'PUT',\n path: '/rd-marketing-fee/payout-destination',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Sandbox resource for testing simulations.\n *\n * @remarks\n * These endpoints are only available in the Sandbox environment.\n * Sandbox custody is real on testnets: Dakota sees real testnet crypto\n * sent to a sandbox address. The banking layer is mocked, so use these\n * simulation endpoints to trigger fiat payment events.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n SimulateInboundRequest,\n SimulationResponse,\n SimulateOnboardingRequest,\n SimulateOnboardingResponse,\n AdvanceSimulationRequest,\n AdvanceSimulationResult,\n SimulationInspection,\n SandboxScenario,\n ListParams,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Sandbox API resource for testing simulations.\n *\n * These endpoints are only available in the Sandbox environment.\n *\n * @remarks\n * **Important:** Sandbox custody is real on testnets, so Dakota sees real\n * testnet crypto sent to a sandbox address. The banking layer is mocked:\n * use these simulation endpoints to trigger fiat payment events.\n *\n * @example\n * ```typescript\n * // Simulate ACH deposit to on-ramp account\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_inbound',\n * account_id: 'acc_123',\n * amount: '1000.00',\n * currency: 'USD',\n * });\n *\n * // Simulate off-ramp ACH settlement\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_outbound_settled',\n * account_id: 'acc_456',\n * one_off_transaction_id: 'tx_456',\n * amount: '500.00',\n * currency: 'USD',\n * });\n * ```\n */\nexport class SandboxResource extends BaseResource {\n /**\n * Simulate an inbound payment event.\n *\n * Triggers a simulated payment event through the mock banking provider.\n * The required fields depend on the simulation `type`:\n *\n * | Type | Required Fields |\n * |------|-----------------|\n * | `ach_inbound`, `fedwire_inbound`, `swift_inbound`, `fednow_inbound` | `account_id` |\n * | `crypto_inbound` | `wallet_address` |\n * | `*_outbound_*`, `*_reversal` | `account_id` + `one_off_transaction_id` |\n *\n * `swift_inbound` and `fedwire_inbound` behave identically: the rail a\n * deposit books on is derived from the RECEIVING account, so pick the\n * account, not the type, to choose between a SWIFT and a Fedwire deposit.\n *\n * @param data - Simulation request data\n * @returns Simulation response with ID and state\n *\n * @example Simulate ACH deposit to on-ramp\n * ```typescript\n * const result = await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_inbound',\n * account_id: 'acc_123',\n * amount: '1000.00',\n * currency: 'USD',\n * });\n * ```\n *\n * @example Simulate off-ramp ACH settlement\n * ```typescript\n * // After creating a one-off transaction for off-ramp testing\n * const tx = await client.transactions.create({\n * customer_id: 'cust_123',\n * amount: '100.00',\n * source_asset: 'USDC',\n * source_network_id: 'ethereum-sepolia',\n * destination_id: 'dest_456',\n * destination_asset: 'USD',\n * destination_payment_rail: 'ach',\n * });\n *\n * // Simulate the ACH settlement. `account_id` is the offramp account that\n * // funded the transaction.\n * await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'ach_outbound_settled',\n * account_id: 'acc_456',\n * one_off_transaction_id: tx.id,\n * amount: '100.00',\n * currency: 'USD',\n * });\n * ```\n *\n * @example Simulate crypto deposit to wallet\n * ```typescript\n * const result = await client.sandbox.simulateInbound({\n * simulation_id: `sim_${Date.now()}`,\n * type: 'crypto_inbound',\n * wallet_address: '0x165cd37b4c644c2921454429e7f9358d18a45e14',\n * amount: '500.00',\n * currency: 'USDC',\n * });\n * ```\n */\n async simulateInbound(\n data: SimulateInboundRequest,\n options?: RequestOptions\n ): Promise<SimulationResponse> {\n return this.transport.request<SimulationResponse>({\n method: 'POST',\n path: '/sandbox/simulate/inbound',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Simulate an onboarding state transition.\n *\n * Drives KYB, KYC, or applicant account status through a sandbox transition\n * without waiting for real compliance review.\n *\n * **Important:** Use `kyb_approve` to fully approve any customer type (individual or\n * business). This triggers the complete onboarding flow including endorsement and\n * recipient creation. The `kyc_*` types only update the individual applicant's KYC\n * application status without triggering the full onboarding flow.\n *\n * @param data - Simulation request data\n * @returns Simulation response with previous and new state\n *\n * `applicant_activate` runs the same code path as `kyb_approve`. One call\n * is enough: do not send `applicant_activate` after `kyb_approve`.\n *\n * @example Approve an application\n * ```typescript\n * await client.sandbox.simulateOnboarding({\n * type: 'kyb_approve',\n * applicant_id: customer.application_id,\n * simulation_id: `sim_kyb_${Date.now()}`,\n * });\n * ```\n *\n * @example Reject a KYB application\n * ```typescript\n * await client.sandbox.simulateOnboarding({\n * type: 'kyb_reject',\n * applicant_id: applicationId,\n * simulation_id: `sim_${Date.now()}`,\n * reason_code: 'MISSING_DOCUMENTS',\n * });\n * ```\n */\n async simulateOnboarding(\n data: SimulateOnboardingRequest,\n options?: RequestOptions\n ): Promise<SimulateOnboardingResponse> {\n return this.transport.request<SimulateOnboardingResponse>({\n method: 'POST',\n path: '/sandbox/simulate/onboarding',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get detailed simulation status and callback history.\n *\n * Returns the current state and callback delivery history for a sandbox simulation.\n * Use this to debug async flows and see whether callbacks have been delivered.\n *\n * @param simulationId - Simulation ID returned from simulateInbound/simulateOnboarding\n * @returns Full simulation inspection including state and callbacks\n *\n * @example\n * ```typescript\n * const inspection = await client.sandbox.getSimulation('sim_123');\n * console.log('State:', inspection.state);\n * console.log('Callbacks:', inspection.callbacks);\n * ```\n */\n async getSimulation(simulationId: string): Promise<SimulationInspection> {\n return this.transport.request<SimulationInspection>({\n method: 'GET',\n path: `/sandbox/simulations/${simulationId}`,\n });\n }\n\n /**\n * Advance a stateful simulation to the next state.\n *\n * Some scenarios pause and wait for explicit advancement. Use this method\n * to continue a paused simulation with a specific action.\n *\n * @param simulationId - Simulation ID\n * @param data - Action to take (e.g., 'release', 'reject', 'confirm', 'expire')\n * @returns Updated simulation state\n *\n * @example\n * ```typescript\n * const result = await client.sandbox.advanceSimulation('sim_123', {\n * action: 'release',\n * });\n * console.log('New state:', result.new_state);\n * ```\n */\n async advanceSimulation(\n simulationId: string,\n data?: AdvanceSimulationRequest,\n options?: RequestOptions\n ): Promise<AdvanceSimulationResult> {\n return this.transport.request<AdvanceSimulationResult>({\n method: 'POST',\n path: `/sandbox/simulations/${simulationId}/advance`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List available sandbox scenarios.\n *\n * Returns all simulation scenarios supported by the platform.\n * Use these scenario names in the `scenario` field of simulateInbound.\n *\n * @param params - Pagination parameters\n * @returns Async iterator of scenarios\n *\n * @example\n * ```typescript\n * const scenarios = await client.sandbox.listScenarios().toArray();\n * for (const scenario of scenarios) {\n * console.log(`${scenario.name}: ${scenario.description}`);\n * }\n * ```\n */\n listScenarios(params?: ListParams): PaginatedIterator<SandboxScenario> {\n return this.paginate<SandboxScenario>('/sandbox/scenarios', params);\n }\n}\n","/**\n * Self-Serve Credits resource for managing prepaid transfer credits.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n SelfServeCreditsPurchaseRequest,\n SelfServeCreditsPurchaseResponse,\n SelfServeCreditsBalanceResponse,\n SelfServeCreditsLedgerResponse,\n SelfServeCreditsLedgerParams,\n SelfServeCreditsPricingResponse,\n SelfServeCreditTiersResponse,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Self-Serve Credits API resource.\n *\n * Manage prepaid credits for self-serve transfer capacity.\n */\nexport class SelfServeResource extends BaseResource {\n /**\n * Purchase self-serve credits.\n *\n * Creates a Stripe checkout session for purchasing credits at the specified tier.\n *\n * @param data - Purchase request with the tier price\n * @param options - Optional request options (e.g., idempotency key)\n * @returns Response containing the Stripe checkout URL\n *\n * @example\n * ```typescript\n * const { checkout_url } = await client.selfServe.purchaseCredits({\n * tier_price_cents: 10000,\n * });\n * // Redirect user to checkout_url\n * ```\n */\n async purchaseCredits(\n data: SelfServeCreditsPurchaseRequest,\n options?: RequestOptions\n ): Promise<SelfServeCreditsPurchaseResponse> {\n return this.transport.request<SelfServeCreditsPurchaseResponse>({\n method: 'POST',\n path: '/self-serve/credits/purchase',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get current credits balance.\n *\n * @returns The current balance and transfer capacity in cents\n *\n * @example\n * ```typescript\n * const balance = await client.selfServe.getBalance();\n * console.log(`Balance: $${balance.balance_cents / 100}`);\n * console.log(`Transfer capacity: $${balance.transfer_capacity_cents / 100}`);\n * ```\n */\n async getBalance(): Promise<SelfServeCreditsBalanceResponse> {\n return this.transport.request<SelfServeCreditsBalanceResponse>({\n method: 'GET',\n path: '/self-serve/credits/balance',\n });\n }\n\n /**\n * List credits ledger entries.\n *\n * Returns a cursor-paginated list of ledger entries (purchases, deductions, refunds).\n *\n * @param params - Optional query parameters for filtering and pagination\n * @returns Ledger response with entries and has_more flag\n *\n * @example\n * ```typescript\n * // Get recent ledger entries\n * const ledger = await client.selfServe.listLedger();\n * for (const entry of ledger.entries) {\n * console.log(entry.entry_type, entry.amount_cents, entry.description);\n * }\n *\n * // Filter by type with pagination\n * const purchases = await client.selfServe.listLedger({\n * type: 'purchase',\n * limit: 50,\n * });\n *\n * // Paging: carry BOTH halves of the cursor. Entries written in one\n * // transaction share a created_at, so a page boundary inside such a\n * // group drops rows when only `cursor` is sent.\n * const last = purchases.entries[purchases.entries.length - 1];\n * const next = await client.selfServe.listLedger({\n * type: 'purchase',\n * limit: 50,\n * cursor: last.created_at,\n * cursor_id: last.id,\n * });\n * ```\n */\n async listLedger(params?: SelfServeCreditsLedgerParams): Promise<SelfServeCreditsLedgerResponse> {\n const query: Record<string, string | number | boolean | undefined> = {};\n if (params?.cursor !== undefined) query.cursor = params.cursor;\n // Ignored by the server without `cursor`, and the ordering it completes is\n // what stops a page boundary splitting one transaction's entries.\n if (params?.cursor_id !== undefined) query.cursor_id = params.cursor_id;\n if (params?.limit !== undefined) query.limit = params.limit;\n if (params?.type !== undefined) query.type = params.type;\n\n return this.transport.request<SelfServeCreditsLedgerResponse>({\n method: 'GET',\n path: '/self-serve/credits/ledger',\n query,\n });\n }\n\n /**\n * List available credit tiers.\n *\n * Returns all available pricing tiers for purchasing credits.\n *\n * @returns Response containing the list of available tiers\n *\n * @example\n * ```typescript\n * const { tiers } = await client.selfServe.listTiers();\n * for (const tier of tiers) {\n * console.log(`$${tier.price_cents / 100} → $${tier.transfer_capacity_cents / 100} capacity`);\n * }\n * ```\n */\n async listTiers(): Promise<SelfServeCreditTiersResponse> {\n return this.transport.request<SelfServeCreditTiersResponse>({\n method: 'GET',\n path: '/self-serve/credits/tiers',\n });\n }\n\n /**\n * Get the self-serve client's pricing config (fee schedule).\n *\n * Returns the caller's current `ClientPricingConfig` — transfer/ACH/wire/SEPA/SWIFT/KYC/KYB\n * fees plus the monthly minimum. Self-serve clients only.\n *\n * @returns The current pricing configuration\n *\n * @example\n * ```typescript\n * const pricing = await client.selfServe.getPricing();\n * console.log(`ACH fee: ${pricing.achFeeCents} cents`);\n * console.log(`Wire fee: ${pricing.wireFeeCents} cents`);\n * ```\n */\n async getPricing(): Promise<SelfServeCreditsPricingResponse> {\n return this.transport.request<SelfServeCreditsPricingResponse>({\n method: 'GET',\n path: '/self-serve/credits/pricing',\n });\n }\n}\n","/**\n * Fee Payout Destination resource.\n *\n * Where Dakota pays your accrued developer fees. Exactly ONE destination\n * exists per organization, and it is crypto-only — a USDC wallet on any\n * supported chain.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n FeePayoutDestination,\n PutFeePayoutDestinationRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Fee Payout Destination API resource.\n */\nexport class FeePayoutDestinationResource extends BaseResource {\n /**\n * Get the destination registered to receive your developer-fee payouts.\n *\n * @returns The registered destination\n *\n * @example\n * ```typescript\n * const dest = await client.feePayoutDestination.get();\n * console.log(dest.chain, dest.wallet_address);\n * ```\n */\n async get(): Promise<FeePayoutDestination> {\n return this.transport.request<FeePayoutDestination>({\n method: 'GET',\n path: '/fee-payout-destination',\n });\n }\n\n /**\n * Register or replace your fee payout destination.\n *\n * There is exactly one destination per organization, so this REPLACES any\n * existing one. Emits `fee_payout_destination.updated`.\n *\n * `chain` is a CAIP-2 chain id (e.g. `eip155:8453`) from the supported\n * networks list — see `client.info.getNetworks()`.\n *\n * @param data - The USDC wallet to pay fees to\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The stored destination\n *\n * @example\n * ```typescript\n * const dest = await client.feePayoutDestination.set({\n * usdc_wallet: {\n * chain: 'eip155:8453',\n * address: '0x1234567890123456789012345678901234567890',\n * },\n * });\n * ```\n */\n async set(\n data: PutFeePayoutDestinationRequest,\n options?: RequestOptions\n ): Promise<FeePayoutDestination> {\n return this.transport.request<FeePayoutDestination>({\n method: 'PUT',\n path: '/fee-payout-destination',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Remove the registered fee payout destination, if one exists.\n *\n * Emits `fee_payout_destination.deleted`.\n *\n * @example\n * ```typescript\n * await client.feePayoutDestination.delete();\n * ```\n */\n async delete(): Promise<void> {\n await this.transport.request<void>({\n method: 'DELETE',\n path: '/fee-payout-destination',\n });\n }\n}\n","/**\n * Payment Agents resource (ALPHA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { AGENTIC_MODEL_TIMEOUT_MS } from '../config.js';\nimport type {\n PaymentAgent,\n PaymentAgentCreateRequest,\n AgenticProposalsProgress,\n AgenticProposalsResult,\n CreateProposalsRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Payment Agents API resource (ALPHA).\n */\nexport class PaymentAgentsResource extends BaseResource {\n /**\n * Create a hosted payment agent.\n *\n * @param data - Payment agent creation data (customer_id, name, hosted)\n * @returns The created payment agent (id, signer_id, signer_public_key, state)\n */\n async create(data: PaymentAgentCreateRequest, options?: RequestOptions): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'POST',\n path: '/payment-agents',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get a hosted payment agent.\n *\n * Returns the agent together with the wallets it can currently spend\n * from. `wallet_ids` are DERIVED at query time from the agent signer's\n * live signer-group membership, so they reflect the agent's access\n * right now — not just at creation time.\n *\n * @param paymentAgentId - Payment agent ID\n */\n async get(paymentAgentId: string): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'GET',\n path: `/payment-agents/${paymentAgentId}`,\n });\n }\n\n /**\n * Revoke a hosted payment agent.\n *\n * The agent can no longer be used, and its signing key is destroyed\n * in the isolated signer service (best-effort — the revoked state is\n * authoritative). Idempotent.\n *\n * The response's `signer_group_cleanup` names the signer groups the\n * (now-revoked) agent's signer still belongs to. A revoked signer can't\n * sign, but its group membership lingers — remove it with\n * `client.signerGroups.removeSigner(signer_group_id, signer_id)` to\n * finish de-provisioning.\n *\n * @param paymentAgentId - Payment agent ID\n * @returns The revoked payment agent (state=revoked, signer_group_cleanup?)\n */\n async revoke(paymentAgentId: string, options?: RequestOptions): Promise<PaymentAgent> {\n return this.transport.request<PaymentAgent>({\n method: 'POST',\n path: `/payment-agents/${paymentAgentId}/revoke`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Draft payment proposals from a conversation.\n *\n * Pure cognition, no side effects: turn a customer's natural-language\n * request into reviewable proposals. Stateless — send the whole\n * conversation so far in `messages` on each call. Prefer\n * `AgentConversation` for multi-turn chat; use this directly only for\n * one-shot proposals.\n *\n * SLOW BY NATURE. A turn is a sequence of model calls — read the payees,\n * check balances, draft, revise — so a multi-payee request legitimately\n * runs minutes. It therefore defaults to {@link AGENTIC_MODEL_TIMEOUT_MS}\n * rather than the client's ordinary deadline. Pass `{ timeout }` to\n * change it for one call; an explicit client-wide `timeout` still wins.\n *\n * The result may carry `blockers` ALONGSIDE proposals — they are not\n * alternatives. Branch on `blocker.code`, not on `reply`, and ignore codes\n * you do not recognize.\n *\n * The vocabulary the agent drafts under is the one registered with\n * `client.agenticPolicy.set()`. It is not a property of this request —\n * a policy sent here is ignored, which is why the option to send one is\n * gone.\n *\n * @param paymentAgentId - Payment agent ID\n * @param data - Prompt and/or messages\n * @returns Proposals (at high confidence) and/or a conversational reply\n */\n async createProposals(\n paymentAgentId: string,\n data: CreateProposalsRequest,\n options?: RequestOptions\n ): Promise<AgenticProposalsResult> {\n return this.transport.request<AgenticProposalsResult>({\n method: 'POST',\n path: `/payment-agents/${paymentAgentId}/proposals`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n endpointTimeout: AGENTIC_MODEL_TIMEOUT_MS,\n });\n }\n\n /**\n * Live progress of an in-flight drafting turn.\n *\n * A multi-payee drafting turn legitimately runs minutes (several sequential\n * model calls). While a `createProposals` call is in flight, poll this every\n * few seconds to show the customer what the agent is doing right now.\n *\n * Advisory display only. `active: false` means no turn is currently\n * publishing progress for this agent — idle, just finished, or served by\n * another instance — so fall back to a generic spinner. Never gate any\n * behaviour on this endpoint.\n *\n * The snapshot is coarse and customer-safe: a phase enum, one human\n * sentence, and the model round. Tool counts only — never payee names,\n * amounts, or addresses.\n *\n * @param paymentAgentId - Payment agent ID\n * @returns The current progress snapshot\n *\n * @example\n * ```typescript\n * const pending = client.paymentAgents.createProposals(agentId, { prompt });\n * const poll = setInterval(async () => {\n * const p = await client.paymentAgents.getProposalsProgress(agentId);\n * if (p.active) console.log(p.detail);\n * }, 3000);\n * const result = await pending.finally(() => clearInterval(poll));\n * ```\n */\n async getProposalsProgress(paymentAgentId: string): Promise<AgenticProposalsProgress> {\n return this.transport.request<AgenticProposalsProgress>({\n method: 'GET',\n path: `/payment-agents/${paymentAgentId}/proposals/progress`,\n });\n }\n}\n","/**\n * Instructions resource (ALPHA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n AgenticInstruction,\n AgenticInstructionsResult,\n CreateInstructionsRequest,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Instructions API resource (ALPHA).\n *\n * Each accepted proposal becomes one persisted instruction whose action\n * series is actuated deterministically.\n */\nexport class InstructionsResource extends BaseResource {\n /**\n * Accept proposals — actuate them into persisted instructions.\n *\n * One optional field shapes the actuation:\n *\n * - `developer_fee_defaults` declares your fee PER PAYOUT TYPE —\n * `swap` for a crypto payout, `offramp` for a bank payout — each as\n * a percentage (`developer_fee_bps`) or a flat amount per payment\n * (`developer_fee_fixed`, a decimal string in units of the asset\n * deposited, added on top of the amount), never both. They are\n * independent, so one conversation can charge a swap and stay silent\n * about a bank payout in the same turn. Omit a payout type (or set its\n * `developer_fee_bps` to zero) and it carries no fee: nothing is\n * charged, nothing is added to the amount, and the agent is told\n * nothing about a fee it could mention. Both are\n * DEFAULTS for the auto-accounts this request creates — an action-level\n * `developer_fee_bps` or `developer_fee_fixed` still wins outright.\n *\n * It replaces the deprecated `developer_fee` (`swap_bps` /\n * `offramp_bps`), which the platform still accepts. Send one or the\n * other: both is a 400.\n *\n * The vocabulary the actuation is judged against comes from the policy\n * registered with `client.agenticPolicy.set()` — the same one the drafting\n * turn used, which is the point of registering it rather than sending it.\n *\n * @param data - The payment agent id and the proposals to accept\n * @returns instruction_ids + the mandates the batch drafted (in full\n * wire shape; sign the §8 approval immediately)\n */\n async create(\n data: CreateInstructionsRequest,\n options?: RequestOptions\n ): Promise<AgenticInstructionsResult> {\n return this.transport.request<AgenticInstructionsResult>({\n method: 'POST',\n path: '/instructions',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Get an accepted instruction — its action series and the per-action\n * downstream artifacts actuation produced.\n *\n * @param instructionId - Instruction ID\n */\n async get(instructionId: string): Promise<AgenticInstruction> {\n return this.transport.request<AgenticInstruction>({\n method: 'GET',\n path: `/instructions/${instructionId}`,\n });\n }\n}\n","/**\n * Mandates resource (ALPHA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n AmendMandateRequest,\n ApproveMandateRequest,\n CancelMandateRequest,\n CreateMandateRequest,\n Mandate,\n MandateBudget,\n MandateListParams,\n MandateResponse,\n MandateVersion,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Mandates API resource (ALPHA).\n */\nexport class MandatesResource extends BaseResource {\n /**\n * List mandates (newest first), with the EFFECTIVE status — a pending or\n * active mandate past its valid_until reads \"expired\". Filter with\n * customer_id / signer_id / status; omit them all for the full collection.\n *\n * @param params - Optional pagination + filter parameters\n * @returns Async iterator of mandates\n */\n list(params?: MandateListParams): PaginatedIterator<Mandate> {\n return this.paginate<Mandate>('/mandates', params);\n }\n\n /**\n * Get a mandate — the signer it binds, its rule exactly as the customer\n * approves it, validity, and status.\n *\n * @param mandateId - Mandate ID\n */\n async get(mandateId: string): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'GET',\n path: `/mandates/${mandateId}`,\n });\n }\n\n /**\n * Create a mandate directly.\n *\n * Drafts a PENDING mandate from a direct user interaction — no instruction\n * back-link. Exactly one binding form names the signer the mandate binds:\n * `payment_agent_id` (hosted convenience — binds that agent's signer and\n * anchors to the agent's customer), or `signer_id` together with\n * `customer_id` (any of the client's signers, BYO keys included). The rule\n * is the one the customer will approve (via `approve`, a recognized signer\n * other than the bound one, §8).\n *\n * @param data - One binding form + rule + optional validity window\n * @returns The drafted (pending) mandate\n */\n async create(data: CreateMandateRequest, options?: RequestOptions): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'POST',\n path: '/mandates',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Approve a mandate.\n *\n * A recognized signer OTHER than the bound one signs the mandate payload\n * (see `mandateSignPayload` + `MandateSigner`) to activate it; arms its\n * scheduled payments.\n *\n * @param mandateId - Mandate ID\n * @param data - Approver public key (base64 PKIX) + base64 ASN.1 signature\n */\n async approve(\n mandateId: string,\n data: ApproveMandateRequest,\n options?: RequestOptions\n ): Promise<MandateResponse> {\n return this.transport.request<MandateResponse>({\n method: 'POST',\n path: `/mandates/${mandateId}/approve`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Cancel a mandate.\n *\n * Revokes a pending or active mandate. The canceller must be a recognized\n * signer OTHER than the bound one, with a valid signature over the mandate\n * payload — the bound signer can never mutate its own mandate.\n *\n * @param mandateId - Mandate ID\n * @param data - Signer public key (base64 PKIX) + base64 ASN.1 signature\n */\n async cancel(\n mandateId: string,\n data: CancelMandateRequest,\n options?: RequestOptions\n ): Promise<MandateResponse> {\n return this.transport.request<MandateResponse>({\n method: 'POST',\n path: `/mandates/${mandateId}/cancel`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Amend a mandate — append a new signed version of its rule.\n *\n * Carries a changed rule into force with ONE signature and WITHOUT resetting\n * the spend already made in the current window: usage accrues to the\n * MANDATE, so an agent that has spent 9,000 of a 10,000 monthly limit and is\n * amended to 20,000 has 11,000 left, not 20,000.\n *\n * The `rule` is stored and verified VERBATIM — this endpoint does not\n * normalize it. It must already be canonical: `window` present and non-empty\n * (send `'NONE'` for a lifetime window), `targets` as recipient ids rather\n * than payee names, and `asset` uppercase. `target_type`, `window`, `asset`\n * and `network_id` must also match the current version exactly; only the\n * amount fields and `targets` may differ. Anything else is a 400 naming the\n * offending field.\n *\n * Build `signature` from `mandateAmendSignPayload(mandate, version, rule)` —\n * the amend payload commits to the version being created, so a signature for\n * v2 can never be replayed to append v3.\n *\n * @param mandateId - Mandate ID\n * @param data - Amending signer public key + signature + the complete NEW rule\n * @returns The mandate at its new current version\n *\n * @example\n * ```typescript\n * const mandate = await client.mandates.get(mandateId);\n * const nextVersion = (mandate.version ?? 1) + 1;\n * const rule = { ...mandate.rule, max_amount_in_window: '20000' };\n * const payload = mandateAmendSignPayload(mandate, nextVersion, rule);\n *\n * const amended = await client.mandates.amend(mandateId, {\n * signer_public_key: signer.publicKeyBase64(),\n * signature: await signer.sign(payload),\n * rule,\n * });\n * ```\n */\n async amend(\n mandateId: string,\n data: AmendMandateRequest,\n options?: RequestOptions\n ): Promise<Mandate> {\n return this.transport.request<Mandate>({\n method: 'POST',\n path: `/mandates/${mandateId}/amend`,\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * List a mandate's versions, oldest first.\n *\n * The append-only history of every rule that was ever in force under this\n * mandate, and the §8 signer that put each one there. Versions are\n * immutable, so a rule listed here never changes — this is what makes an\n * executed payment's `mandate_version` audit stamp legible.\n *\n * @param mandateId - Mandate ID\n * @returns Every version, oldest first\n */\n async listVersions(mandateId: string): Promise<MandateVersion[]> {\n return this.transport.request<MandateVersion[]>({\n method: 'GET',\n path: `/mandates/${mandateId}/versions`,\n });\n }\n\n /**\n * Get a mandate's remaining budget right now.\n *\n * The mandate's `rule` gives the ceilings; this gives the CONSUMPTION — what\n * has already been spent, what is earmarked by scheduled payments that have\n * not fired yet, and therefore what is left. Read it before scheduling:\n * otherwise an over-budget payment is only discovered when the gate denies\n * it at its due date, days later, with the payee unpaid.\n *\n * Advisory — nothing here reserves budget, and the gate remains the\n * authority at fire time. Three things to honour when reading a line:\n *\n * - An ABSENT `remaining_amount` / `remaining_count` means \"not capped\",\n * never \"nothing left\" — EXCEPT on a `per_target` line with\n * `prior_scope: true`. That line's spend was booked under an earlier\n * version's target scope (before a `target_type` amendment) and no\n * current target claims it: the spend is real and still counts toward\n * the aggregate caps, but no payment can consume the bucket, so absent\n * remaining_* there means NO headroom. Never set on aggregate lines.\n * - A `remaining_amount` of `'?'` means the figure could not be summed and\n * MUST be treated as no headroom (the gate fails closed on the same data).\n *\n * @param mandateId - Mandate ID\n * @returns Per-target and aggregate budget lines, as of a stated instant\n *\n * @example\n * ```typescript\n * const budget = await client.mandates.getBudget(mandateId);\n * for (const line of [...budget.per_target, ...budget.aggregate]) {\n * const headroom = line.prior_scope\n * ? 'none (prior scope)'\n * : (line.remaining_amount ?? 'uncapped');\n * console.log(line.target ?? '(all payees)', line.bucket, headroom);\n * }\n * ```\n */\n async getBudget(mandateId: string): Promise<MandateBudget> {\n return this.transport.request<MandateBudget>({\n method: 'GET',\n path: `/mandates/${mandateId}/budget`,\n });\n }\n}\n","/**\n * Scheduled Payments resource (ALPHA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport { PaginatedIterator } from '../pagination.js';\nimport type {\n CreateScheduledPaymentRequest,\n RequestOptions,\n ScheduledPayment,\n ScheduledPaymentListParams,\n} from '../types.js';\n\n/**\n * Scheduled Payments API resource (ALPHA).\n */\nexport class ScheduledPaymentsResource extends BaseResource {\n /**\n * List scheduled payments (oldest due first).\n *\n * Narrow the collection with the optional customer_id, signer_id,\n * wallet_id, mandate_id, and status filters; omit them all for the full\n * client collection.\n *\n * @param params - Optional pagination + filter parameters\n * @returns Async iterator of scheduled payments\n */\n list(params?: ScheduledPaymentListParams): PaginatedIterator<ScheduledPayment> {\n return this.paginate<ScheduledPayment>('/scheduled-payments', params);\n }\n\n /**\n * Schedule payments directly — bypass the proposal flow.\n *\n * Creates one or more scheduled payments for a signer under an existing\n * active mandate (coverage is matched at fire time, so no new signature\n * is needed here). The schedule is explicit `dates` OR `count` ×\n * `interval_seconds` from `start_at`.\n *\n * @param data - Signer + wallet + destination (or address+network_id) + schedule\n * @returns The rows that were created (one per date)\n */\n async create(\n data: CreateScheduledPaymentRequest,\n options?: RequestOptions\n ): Promise<ScheduledPayment[]> {\n return this.transport.request<ScheduledPayment[]>({\n method: 'POST',\n path: '/scheduled-payments',\n body: data,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n\n /**\n * Cancel one still-scheduled payment.\n *\n * Finalizes the row as cancelled. No signature is required — schedule rows\n * are bookkeeping, not authorization; the signed grant is the MANDATE,\n * which this does not touch.\n *\n * @param scheduledPaymentId - Scheduled payment ID\n */\n async cancel(scheduledPaymentId: string, options?: RequestOptions): Promise<void> {\n await this.transport.request<void>({\n method: 'POST',\n path: `/scheduled-payments/${scheduledPaymentId}/cancel`,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Insights resource (BETA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type { ClientInsightReport, ClientInsightsParams, InsightReport } from '../types.js';\n\n/**\n * Insights API resource (BETA).\n *\n * Read-only, advisory reporting over agentic activity — one customer's, or\n * the whole client's book. Nothing here moves money or changes state.\n */\nexport class InsightsResource extends BaseResource {\n /**\n * Get the customer's account insight report.\n *\n * A deterministic, read-only report: a snapshot of typed facts\n * (funding-wallet balances, upcoming totals, open payments, active\n * mandates), observations (`insights`), and advisory recommendations\n * (`suggestions`). Every item carries `evidence` — typed references to\n * the platform objects it was computed from. `kind` is an OPEN set;\n * ignore kinds you do not recognize.\n *\n * @param customerId - Customer ID\n * @returns The customer's insight report\n */\n async get(customerId: string): Promise<InsightReport> {\n return this.transport.request<InsightReport>({\n method: 'GET',\n path: `/customers/${customerId}/insights`,\n });\n }\n\n /**\n * Get the client-level portfolio insight report.\n *\n * The client-scope companion of {@link get}: one deterministic, read-only\n * report over ALL of the caller's customers' agentic activity. Items reuse\n * the customer report's shape, plus `customer_id` (omitted on\n * cross-customer aggregates) and `responsibility` (a grouping label for\n * filtering — not ownership). On top of the items the report carries\n * dashboard-shaped data: KPI `metrics` with previous-window values for\n * trend deltas, daily `series` for charts, and a per-customer roll-up in\n * `customers` sorted worst-first.\n *\n * Every filter is optional and only NARROWS the report; the response shape\n * never changes. The report scans at most 100 customers per request —\n * `snapshot.customers.scanned < total` says it was computed over a prefix\n * of the book, never silently.\n *\n * A 404 means agentic payments are not enabled for the key, or the\n * `customer_id` filter names an unknown customer.\n *\n * @param params - Optional filters and the report window\n * @returns The client's portfolio insight report\n *\n * @example\n * ```typescript\n * const report = await client.insights.getClientReport({\n * severity: 'critical,warn',\n * window_days: 30,\n * });\n * for (const row of report.customers) {\n * if (row.item_counts.critical > 0) console.log(row.customer_id, row.name);\n * }\n * ```\n */\n async getClientReport(params?: ClientInsightsParams): Promise<ClientInsightReport> {\n return this.transport.request<ClientInsightReport>({\n method: 'GET',\n path: '/insights',\n query: { ...params },\n });\n }\n}\n","/**\n * Agentic Client Policy resource (ALPHA).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { BaseResource } from './base.js';\nimport type {\n AgenticClientPolicy,\n RegisteredAgenticClientPolicy,\n RequestOptions,\n} from '../types.js';\n\n/**\n * Agentic Client Policy API resource (ALPHA).\n *\n * The policy is per CLIENT — it belongs to the client behind your API key,\n * never to a key, since API keys are N:1 to clients and a per-key policy\n * would fragment for anyone running one service key per deployment.\n *\n * There is no client id to pass. The route resolves the client from the API\n * key, so you cannot address another client's policy even to be refused.\n */\nexport class AgenticPolicyResource extends BaseResource {\n /**\n * Get the policy registered for the client behind your API key.\n *\n * A 404 here is the DEFAULT, not an error condition: with no registration\n * and no per-request policy the agent drafts on platform defaults, exactly\n * as it did before registration existed.\n *\n * @returns The normalized registered policy + its timestamps\n *\n * @example\n * ```typescript\n * try {\n * const { policy } = await client.agenticPolicy.get();\n * console.log(policy.labels);\n * } catch (e) {\n * if (e instanceof APIError && e.statusCode === 404) {\n * // No registration — platform defaults apply.\n * }\n * }\n * ```\n */\n async get(): Promise<RegisteredAgenticClientPolicy> {\n return this.transport.request<RegisteredAgenticClientPolicy>({\n method: 'GET',\n path: '/agentic-policy',\n });\n }\n\n /**\n * Register — or fully replace — this client's agentic policy.\n *\n * Registration is the ONLY way to set a policy. A policy is a property of\n * the CLIENT, not of a request: carried per request, a drafting turn and\n * the accept that followed it could be judged by different rules. The\n * platform accordingly stopped reading `client_policy` from request bodies,\n * and one sent there is now ignored — silently, since the agent simply\n * narrates in the platform's nouns again (\"destination\", \"mandate\") with no\n * error anywhere. Registering once removes that failure mode.\n *\n * FULL REPLACE, not a merge — the registration IS your declared vocabulary,\n * so an omitted field means you no longer want it, and an empty body (`{}`)\n * clears the registration back to platform defaults.\n *\n * Validated exactly like the per-request copy, so an unknown key, an\n * unsupported value, or a label for an unimplemented concept is a 400 HERE,\n * at registration — not a surprise on a customer's first conversation.\n *\n * The client comes from your API key; there is no id to pass.\n *\n * @param policy - The complete policy (`{}` clears it)\n * @param options - Request options (e.g., custom idempotency key)\n * @returns The normalized stored policy + its timestamps\n *\n * @example\n * ```typescript\n * await client.agenticPolicy.set({\n * payee_model: 'flat',\n * payout_assets: ['USDC', 'USDT'],\n * labels: { limit: 'spending limit', payee: 'recipient', limit_unit: 'USD' },\n * payout_route: 'conversion_account_only',\n * mandate_strategy: 'external_only',\n * });\n * ```\n */\n async set(\n policy: AgenticClientPolicy,\n options?: RequestOptions\n ): Promise<RegisteredAgenticClientPolicy> {\n return this.transport.request<RegisteredAgenticClientPolicy>({\n method: 'PUT',\n path: '/agentic-policy',\n body: policy,\n idempotencyKey: options?.idempotencyKey,\n timeout: options?.timeout,\n });\n }\n}\n","/**\n * Multi-turn agent chat. The platform's proposals endpoint is STATELESS —\n * it holds no session and must be sent the whole transcript on every turn.\n * `AgentConversation` hides that bookkeeping so a caller just sends user\n * messages and reads the agent's clarifying questions / final proposals.\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport type { DakotaClient } from '../client/client.js';\nimport type {\n AgenticBlocker,\n AgenticProposal,\n AgenticProposalsResult,\n DeveloperFee,\n DeveloperFeeDefaults,\n} from '../client/types.js';\n\n/**\n * MIME types the platform accepts for a document attachment.\n */\nexport type AttachmentMediaType =\n | 'application/pdf'\n | 'image/png'\n | 'image/jpeg'\n | 'image/webp'\n | 'image/gif';\n\n/**\n * An input artifact on a user turn for the agent to read — today a document\n * (a PDF or image, e.g. an invoice to draft a payment from). `data` is the\n * RAW document bytes; the SDK base64-encodes them on the wire.\n */\nexport interface Attachment {\n mediaType: AttachmentMediaType;\n /** raw document bytes (not base64) */\n data: Uint8Array;\n /** optional, for display/audit */\n filename?: string;\n}\n\n/**\n * One turn of an agent conversation.\n */\nexport interface ChatMessage {\n role: 'user' | 'assistant';\n content: string;\n /**\n * Input artifacts attached to this turn for the agent to investigate.\n * Attachments ride only on the turn they are passed; they are NOT\n * persisted in the transcript.\n */\n attachments?: Attachment[];\n}\n\n/**\n * The agent's response to one user message.\n */\nexport interface ConversationTurn {\n /**\n * The agent's conversational text — a clarifying question or a\n * confirmation. May be empty when only proposals are returned.\n */\n reply: string;\n /**\n * The reviewable action series, present once the agent reaches high\n * confidence. Accept it via the instructions flow.\n */\n proposals: AgenticProposal[];\n /** Whether the agent drafted proposals this turn. */\n hasProposals: boolean;\n /**\n * Machine-actionable reasons the turn could not complete — for YOUR\n * application, not the customer. `reply` says the same thing in prose,\n * which software cannot branch on: \"extend the limit to cover Priya\",\n * \"I need her bank details\" and \"that rail is not supported\" all arrive\n * as some text.\n *\n * These ACCOMPANY proposals rather than replacing them, and routinely do.\n * The common case is a payee who does not exist yet: the turn proposes\n * creating them AND reports that the limit will not reach them, because\n * you have to do both, in that order — accept the proposal so the payee\n * has an id, then amend the limit to include it. Never treat proposals\n * and blockers as alternatives.\n *\n * Empty when nothing blocked the turn. Always switch on `code` and ignore\n * codes you do not know; new ones are added over time.\n */\n blockers: AgenticBlocker[];\n /** Whether the turn reported any blocker. */\n hasBlockers: boolean;\n /**\n * The boundary screen's verdict for this turn:\n *\n * - `\"ok\"` — normal payments turn.\n * - `\"warned\"` — off-topic; the customer was warned but may continue.\n * - `\"blocked\"` — the chat is terminated; stop serving it and offer a fresh\n * conversation.\n * - `\"rejected_input\"` — this message was refused WHOLESALE (e.g. more\n * payees than one conversation supports). `reply` explains what to\n * resend; the conversation continues unaffected, and the SDK has already\n * dropped the refused message from the transcript for you.\n *\n * Empty when the platform sent none. Treat it as an OPEN set — new values\n * may be added.\n */\n conversationStatus: string;\n}\n\n/**\n * The boundary screen's verdict for a message refused wholesale. Its contract\n * is that the message must NOT be added to the conversation history — see\n * {@link ConversationTurn.conversationStatus}.\n */\nconst REJECTED_INPUT = 'rejected_input';\n\n/** Options for an {@link AgentConversation}. */\nexport interface AgentConversationOptions {\n /**\n * The customer's IANA timezone (e.g. `'America/Los_Angeles'`).\n *\n * When set, the agent resolves every relative date (\"tomorrow\", \"Friday\")\n * and clock time (\"10 am\") in THIS zone: a date without a time is drafted\n * for 10:00 local, and a time without a date means its next local\n * occurrence. Left unset, times resolve as UTC and the agent says so when a\n * specific clock time matters.\n *\n * The conversation resends it on every turn, since the endpoint is\n * stateless. Note the zone's UTC offset is captured at drafting time, so a\n * DST transition before a far-future fire date shifts it by the DST delta.\n */\n timezone?: string;\n\n /**\n * Deadline (ms) for each turn of this conversation.\n *\n * Turns default to {@link AGENTIC_MODEL_TIMEOUT_MS}, which is sized for a\n * multi-payee drafting turn. Set this when your own turns are longer (a\n * very large payee list) or shorter (you would rather show the customer a\n * failure than keep them waiting).\n *\n * Required if the client was built with an explicit `timeout`: that\n * choice wins over the endpoint default, so a client configured with a\n * short global deadline will cut turns off unless you raise it here.\n */\n timeout?: number;\n\n /**\n * Your default developer fee, declared PER PAYOUT TYPE — `swap` for a\n * crypto payout, `offramp` for a bank one, each as `{ developer_fee_bps }`\n * or a flat `{ developer_fee_fixed: '10.00' }` per payment, never both.\n * The two are independent, so one conversation can charge a swap and stay\n * silent about a bank payout.\n *\n * Set it here as well as on `instructions.create()`, not instead of it.\n * The accept is what CHARGES the fee; declaring it on the drafting turn is\n * what lets the agent MENTION it — omit it and the agent is told nothing\n * about a fee it could name, so the customer approves a summary that never\n * disclosed one and then gets charged it.\n *\n * Resent on every turn, since the endpoint is stateless.\n */\n developerFeeDefaults?: DeveloperFeeDefaults;\n\n /**\n * @deprecated Use {@link developerFeeDefaults}: `swap_bps` is now\n * `swap.developer_fee_bps` and `offramp_bps` is now\n * `offramp.developer_fee_bps`. Still sent as `developer_fee` while the\n * platform accepts it. Set one or the other — the SDK forwards both if\n * both are set, and the platform rejects that with a 400.\n */\n developerFee?: DeveloperFee;\n}\n\n/**\n * A stateful, multi-turn proposals chat with one agent.\n *\n * Keeps the running transcript, appends each user message and the agent's\n * reply, and resends the whole transcript on every {@link send} — so\n * callers never deal with the stateless endpoint's \"send all history each\n * time\" contract.\n *\n * For a stateless backend (one HTTP request per chat message), persist\n * {@link messages} between requests and rebuild with\n * {@link DakotaClient.resumeAgentConversation}.\n */\nexport class AgentConversation {\n private readonly client: DakotaClient;\n private readonly paymentAgentId: string;\n private readonly timezone?: string;\n private readonly timeout?: number;\n private readonly developerFeeDefaults?: DeveloperFeeDefaults;\n private readonly developerFee?: DeveloperFee;\n private history: ChatMessage[] = [];\n\n constructor(\n client: DakotaClient,\n paymentAgentId: string,\n history?: ChatMessage[],\n options?: AgentConversationOptions\n ) {\n this.client = client;\n this.paymentAgentId = paymentAgentId;\n this.timezone = options?.timezone;\n this.timeout = options?.timeout;\n this.developerFeeDefaults = options?.developerFeeDefaults;\n this.developerFee = options?.developerFee;\n if (history && history.length > 0) {\n this.history = history.map(cloneMessage);\n }\n }\n\n /**\n * Adds the user's message to the transcript, asks the agent, records the\n * agent's reply, and returns the turn. When `hasProposals` is true the\n * agent has drafted a reviewable action series; otherwise `reply` holds\n * its next question.\n *\n * On error the optimistic user turn is rolled back, so the caller may\n * retry the same call without duplicating it.\n */\n async send(userMessage: string): Promise<ConversationTurn> {\n return this.sendWithAttachments(userMessage);\n }\n\n /**\n * {@link send} with documents (e.g. an invoice PDF) attached to the user\n * turn for the agent to read and draft payments from. Same turn semantics\n * and rollback-on-error behavior as `send`. Attachments ride only on the\n * turn they are passed; the stateless transcript keeps the agent's text\n * reply, so a follow-up turn relies on that summary rather than re-sending\n * the document.\n */\n async sendWithAttachments(\n userMessage: string,\n attachments?: Attachment[]\n ): Promise<ConversationTurn> {\n const hasAttachments = attachments !== undefined && attachments.length > 0;\n this.history.push({\n role: 'user',\n content: userMessage,\n ...(hasAttachments ? { attachments } : {}),\n });\n\n const messages = this.history.map(serializeMessage);\n\n // Attachments ride only on THIS request: they are serialized into\n // `messages` above, then dropped from the stored transcript so they are\n // neither persisted via messages() / resumeAgentConversation nor\n // re-sent on later turns.\n if (hasAttachments) {\n const last = this.history[this.history.length - 1];\n if (last) {\n delete last.attachments;\n }\n }\n\n let result: AgenticProposalsResult;\n try {\n result = await this.client.paymentAgents.createProposals(\n this.paymentAgentId,\n {\n messages,\n // Resent on EVERY turn — the endpoint is stateless, so a value\n // given once would be forgotten on the next one.\n ...(this.timezone ? { timezone: this.timezone } : {}),\n ...(this.developerFeeDefaults\n ? { developer_fee_defaults: this.developerFeeDefaults }\n : {}),\n ...(this.developerFee ? { developer_fee: this.developerFee } : {}),\n },\n this.timeout !== undefined ? { timeout: this.timeout } : undefined\n );\n } catch (err) {\n // Roll back the optimistic user turn so a retry does not duplicate it.\n this.history.pop();\n throw err;\n }\n\n const turn: ConversationTurn = {\n reply: result.reply ?? '',\n proposals: result.proposals ? [...result.proposals] : [],\n hasProposals: !!result.proposals && result.proposals.length > 0,\n blockers: result.blockers ? [...result.blockers] : [],\n hasBlockers: !!result.blockers && result.blockers.length > 0,\n conversationStatus: result.conversation_status ?? '',\n };\n\n // `rejected_input`: the server refused this message WHOLESALE and told us\n // not to keep it. Roll the optimistic user turn back and record no\n // assistant turn, so the transcript is identical to before this send. The\n // conversation itself continues unaffected — the caller still gets the\n // turn, whose `reply` explains what to resend.\n //\n // Without this the refused message stays in the transcript and is\n // re-transmitted on every later turn — the exact message the server asked\n // the client to drop — corrupting the conversation from here on. And\n // `messages()` returns a copy, so a caller could not repair it either.\n if (turn.conversationStatus === REJECTED_INPUT) {\n this.history.pop();\n return turn;\n }\n\n // Record an assistant turn so the transcript keeps alternating — the\n // platform (and the underlying model) reject two consecutive user\n // turns. Fall back to a placeholder when the agent returned only\n // proposals with no reply text.\n let assistant = turn.reply;\n if (!assistant) {\n assistant = turn.hasProposals ? '(drafted proposals for your review)' : '(no reply)';\n }\n this.history.push({ role: 'assistant', content: assistant });\n\n return turn;\n }\n\n /**\n * A copy of the full transcript so far. Persist this between requests in\n * a stateless backend and rebuild with\n * {@link DakotaClient.resumeAgentConversation}.\n */\n messages(): ChatMessage[] {\n return this.history.map(cloneMessage);\n }\n}\n\nfunction cloneMessage(m: ChatMessage): ChatMessage {\n const out: ChatMessage = { role: m.role, content: m.content };\n if (m.attachments && m.attachments.length > 0) {\n out.attachments = m.attachments.map((a) => ({ ...a }));\n }\n return out;\n}\n\nfunction serializeMessage(m: ChatMessage): {\n role: 'user' | 'assistant';\n content: string;\n attachments?: {\n type: 'document';\n document: {\n media_type: AttachmentMediaType;\n data: string;\n filename?: string;\n };\n }[];\n} {\n const out: ReturnType<typeof serializeMessage> = { role: m.role, content: m.content };\n if (m.attachments && m.attachments.length > 0) {\n out.attachments = m.attachments.map((a) => {\n const document: {\n media_type: AttachmentMediaType;\n data: string;\n filename?: string;\n } = {\n media_type: a.mediaType,\n data: Buffer.from(a.data).toString('base64'),\n };\n if (a.filename) {\n document.filename = a.filename;\n }\n return { type: 'document' as const, document };\n });\n }\n return out;\n}\n","/**\n * High-level agentic helpers: collapse the multi-step, crypto-heavy hosted-\n * agent flows into single calls with good defaults, so a partner integration\n * stays short. The raw operations remain reachable via the resource classes\n * on `DakotaClient`.\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport { randomUUID } from 'node:crypto';\n\nimport type { DakotaClient } from '../client/client.js';\n\n/**\n * Grant a principal — a user OR an agent, both are just signers — permission\n * to spend from a wallet by adding its signer to an EXISTING signer group on\n * that wallet: the group whose attached policies should govern it.\n *\n * That membership change is the whole operation, and it is UNENDORSED: group\n * membership is a client-admin action, not a wallet endorsement, so it needs\n * NO signature — not from the wallet owner, not from the principal being\n * added. From then on the principal's transactions are subject to exactly\n * the policies bound to `spendingGroupId`, the same as any other member of\n * that group. The per-payment spend bound remains the agentic mandate gate,\n * not the policy.\n *\n * Deliberately reuses the wallet's pre-built policies and creates NO\n * per-signer policy. Two policy-engine realities make a per-signer policy\n * the wrong tool: a policy → wallet attach is endorsed by the policy's OWN\n * signer group (so only that group's key could attach it), and an\n * unconditional approval-threshold ALLOW policy inverts to a deny for any\n * transaction its group didn't sign, so a second signer's policy would veto\n * the first. Prepare the wallet's groups + policies in advance and point\n * each principal at the group whose constraints you want it to inherit.\n *\n * Idempotent: if the signer is already a member, returns\n * `alreadyMember: true` and makes no write. Rejects `spendingGroupId` if it\n * is not attached to `walletId`, so a wrong group fails loudly instead of\n * silently granting nothing.\n *\n * The key must already exist as a signer resource — the add endpoint takes\n * a `member_key` reference, it does not register keys. A hosted agent's key\n * is minted by `paymentAgents.create`; for a bare user key, register it\n * first (`POST /signers`) or the add fails with a signer-not-found error.\n *\n * @param client - Dakota client\n * @param walletId - The wallet the principal will spend from\n * @param signerPublicKey - The principal's registered signer public key\n * (base64 PKIX) — e.g. `signer_public_key` returned by\n * `paymentAgents.create` for a hosted agent\n * @param spendingGroupId - The signer group whose attached policies should\n * govern the principal; must already be attached to `walletId`\n * @param options - Optional. Supply `idempotencyKey` (a valid UUID — the\n * platform rejects other formats with 400) to make the WHOLE helper\n * safely retryable — a crashed or partitioned call replayed with the\n * same key dedupes the underlying write server-side. Defaults to a\n * fresh random UUID per call.\n * @returns `{ alreadyMember }` — true when the signer was already a member\n * (no write performed)\n */\nexport async function attachUserToWallet(\n client: DakotaClient,\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n): Promise<{ alreadyMember: boolean }> {\n if (!walletId || !signerPublicKey || !spendingGroupId) {\n throw new Error('walletId, signerPublicKey and spendingGroupId are all required');\n }\n\n await requireGroupOnWallet(client, walletId, spendingGroupId);\n\n // Idempotency: skip the add if the signer's key is already a member.\n const group = await client.signerGroups.get(spendingGroupId);\n for (const member of group.members ?? []) {\n if (member.public_key === signerPublicKey) {\n return { alreadyMember: true };\n }\n }\n\n // Add the signer to the group (unendorsed). Granting spend permission is\n // security-relevant, so set an explicit idempotency key rather than depend\n // on transport config (`automaticIdempotency: false` would otherwise send\n // this POST without the required header and 400).\n await client.signerGroups.addSigner(\n spendingGroupId,\n { member_key: signerPublicKey },\n { idempotencyKey: options?.idempotencyKey ?? randomUUID() }\n );\n return { alreadyMember: false };\n}\n\n/**\n * Revoke a principal's spend permission by removing its signer from\n * `spendingGroupId` — the inverse of {@link attachUserToWallet}, and\n * likewise UNENDORSED (no signature).\n *\n * Deliberately SCOPED to the one group you pass, NOT a sweep across every\n * group on the wallet, for two reasons:\n * - signer groups are NOT wallet-exclusive — the same group can govern\n * multiple wallets — so removing a signer from a group revokes it on\n * EVERY wallet that group governs; passing one explicit group keeps\n * that blast radius known instead of multiplying it across all of the\n * wallet's groups;\n * - a sweep cannot tell \"added for this agent\" from \"belongs here for\n * another reason\" (e.g. the human owner sitting in the admin group),\n * so it can lock out a legitimate member.\n *\n * Pass the same group you used to attach. Idempotent: if the signer isn't\n * a member, it is a no-op (`wasMember: false`). Rejects `spendingGroupId`\n * if it is not attached to `walletId`.\n *\n * NOTE: this does not guard against removing a group's LAST member —\n * emptying the group that governs a wallet can leave it with no authorized\n * signer. The caller must avoid stranding the wallet. For a hosted agent,\n * prefer `paymentAgents.revoke` (it destroys the agent's key, so the signer\n * can authorize nothing even while still listed) and use this for\n * membership hygiene.\n *\n * @param options - Optional. Supply `idempotencyKey` (a valid UUID) to\n * make the WHOLE helper safely retryable across crashes/partitions;\n * defaults to a fresh random UUID per call.\n */\nexport async function detachUserFromWallet(\n client: DakotaClient,\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n): Promise<{ wasMember: boolean }> {\n if (!walletId || !signerPublicKey || !spendingGroupId) {\n throw new Error('walletId, signerPublicKey and spendingGroupId are all required');\n }\n\n await requireGroupOnWallet(client, walletId, spendingGroupId);\n\n // Resolve the signer's public key → its resource id within the group: the\n // delete endpoint addresses members by id, not key. Absent ⇒ idempotent\n // no-op.\n const group = await client.signerGroups.get(spendingGroupId);\n let signerId = '';\n for (const member of group.members ?? []) {\n if (member.public_key === signerPublicKey) {\n signerId = member.id ?? '';\n break;\n }\n }\n if (!signerId) {\n return { wasMember: false };\n }\n\n // The platform requires an idempotency key on this DELETE. The transport\n // now injects one on DELETEs too, but revoking spend permission is\n // security-relevant, so we set one explicitly — this path must not depend\n // on transport configuration.\n await client.signerGroups.removeSigner(spendingGroupId, signerId, {\n idempotencyKey: options?.idempotencyKey ?? randomUUID(),\n });\n return { wasMember: true };\n}\n\n/**\n * Errors unless `spendingGroupId` is one of the signer groups attached to\n * `walletId` — so attach/detach can't silently operate on a group that has\n * nothing to do with the named wallet.\n *\n * Uses the symmetric group → wallets read (`GET /signer-groups/{id}/wallets`)\n * because it returns a bare array with a stable shape. Semantically\n * equivalent to `GET /wallets/{id}/signer-groups`; the check succeeds iff\n * the pair is attached.\n */\nasync function requireGroupOnWallet(\n client: DakotaClient,\n walletId: string,\n spendingGroupId: string\n): Promise<void> {\n const wallets = await client.signerGroups.getWallets(spendingGroupId);\n for (const w of wallets) {\n if (w.id === walletId) {\n return;\n }\n }\n throw new Error(`signer group ${spendingGroupId} is not attached to wallet ${walletId}`);\n}\n","/**\n * Dakota Platform API Client.\n */\n\nimport { DakotaClientConfig, ResolvedConfig, resolveConfig } from './config.js';\nimport { Transport } from './transport.js';\nimport {\n CustomersResource,\n RecipientsResource,\n DestinationsResource,\n AccountsResource,\n TransactionsResource,\n AutoTransactionsResource,\n WalletsResource,\n EventsResource,\n ApplicationsResource,\n PoliciesResource,\n SignerGroupsResource,\n SignersResource,\n ApiKeysResource,\n UsersResource,\n WebhooksResource,\n InfoResource,\n LegalResource,\n RDMarketingFeeResource,\n SandboxResource,\n SelfServeResource,\n FeePayoutDestinationResource,\n PaymentAgentsResource,\n InstructionsResource,\n MandatesResource,\n ScheduledPaymentsResource,\n InsightsResource,\n AgenticPolicyResource,\n} from './resources/index.js';\nimport {\n AgentConversation,\n type AgentConversationOptions,\n type ChatMessage,\n} from '../agentic/chat.js';\nimport {\n attachUserToWallet as attachUserToWalletHelper,\n detachUserFromWallet as detachUserFromWalletHelper,\n} from '../agentic/wallets.js';\n\n/**\n * Dakota Platform API Client.\n *\n * The main entry point for interacting with the Dakota Platform API.\n *\n * @example\n * ```typescript\n * import { DakotaClient, Environment } from 'dakota-ts-sdk';\n *\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * environment: Environment.Sandbox, // default\n * });\n *\n * // List customers\n * for await (const customer of client.customers.list()) {\n * console.log(customer.name);\n * }\n *\n * // Create a customer\n * const customer = await client.customers.create({\n * name: 'Acme Corp',\n * customer_type: 'business',\n * });\n * ```\n */\nexport class DakotaClient {\n private readonly config: ResolvedConfig;\n private readonly transport: Transport;\n\n // API Resources\n /** Customers API - manage customer records and KYB */\n readonly customers: CustomersResource;\n /** Recipients API - manage payment recipients */\n readonly recipients: RecipientsResource;\n /** Destinations API - manage bank accounts and crypto wallets */\n readonly destinations: DestinationsResource;\n /** Accounts API - manage on-ramp, off-ramp, and swap accounts */\n readonly accounts: AccountsResource;\n /** Transactions API - manage one-off transactions */\n readonly transactions: TransactionsResource;\n /** Auto Transactions API - manage automated transactions */\n readonly autoTransactions: AutoTransactionsResource;\n /** Wallets API - manage non-custodial wallets */\n readonly wallets: WalletsResource;\n /** Events API - query platform events */\n readonly events: EventsResource;\n /** Applications API - manage KYB applications */\n readonly applications: ApplicationsResource;\n /** Policies API - manage transaction policies */\n readonly policies: PoliciesResource;\n /** Signer Groups API - manage multi-sig signer groups */\n readonly signerGroups: SignerGroupsResource;\n /** Signers API - manage individual signers */\n readonly signers: SignersResource;\n /** API Keys API - manage API keys */\n readonly apiKeys: ApiKeysResource;\n /** Users API - manage platform users */\n readonly users: UsersResource;\n /** Webhooks API - manage webhook targets and events */\n readonly webhooks: WebhooksResource;\n /** Info API - query platform capabilities */\n readonly info: InfoResource;\n /** Legal API - the published terms customers accept (unauthenticated) */\n readonly legal: LegalResource;\n /** RD Marketing Fee API - this client's reserve-management statements */\n readonly rdMarketingFee: RDMarketingFeeResource;\n /** Sandbox API - testing simulations (sandbox only) */\n readonly sandbox: SandboxResource;\n /** Self-Serve Credits API - manage prepaid transfer credits */\n readonly selfServe: SelfServeResource;\n /** Fee Payout Destination API - where Dakota pays your accrued developer fees */\n readonly feePayoutDestination: FeePayoutDestinationResource;\n /** Payment Agents API (ALPHA) - hosted signing agents that draft payments */\n readonly paymentAgents: PaymentAgentsResource;\n /** Instructions API (ALPHA) - accept and inspect actuated proposals */\n readonly instructions: InstructionsResource;\n /** Mandates API (ALPHA) - the §8 authorizations that arm scheduled payments */\n readonly mandates: MandatesResource;\n /** Scheduled Payments API (ALPHA) - schedule rows created from instructions */\n readonly scheduledPayments: ScheduledPaymentsResource;\n /** Insights API (ALPHA) - read-only advisory reporting over agentic activity */\n readonly insights: InsightsResource;\n /** Agentic Policy API (ALPHA) - register the vocabulary the agent speaks for your product */\n readonly agenticPolicy: AgenticPolicyResource;\n\n /**\n * Create a new Dakota client.\n *\n * @param config - Client configuration\n * @throws ConfigurationError if configuration is invalid\n *\n * @example\n * ```typescript\n * // Basic usage (sandbox)\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * });\n *\n * // Production\n * const client = new DakotaClient({\n * apiKey: 'your_production_api_key',\n * environment: Environment.Production,\n * });\n *\n * // With custom configuration\n * const client = new DakotaClient({\n * apiKey: 'your_api_key',\n * timeout: 30000,\n * retryPolicy: {\n * maxAttempts: 5,\n * initialBackoffMs: 100,\n * maxBackoffMs: 5000,\n * },\n * logger: console,\n * });\n * ```\n */\n constructor(config: DakotaClientConfig) {\n this.config = resolveConfig(config);\n this.transport = new Transport(this.config);\n\n // Initialize resources\n this.customers = new CustomersResource(this.transport);\n this.recipients = new RecipientsResource(this.transport);\n this.destinations = new DestinationsResource(this.transport);\n this.accounts = new AccountsResource(this.transport);\n this.transactions = new TransactionsResource(this.transport);\n this.autoTransactions = new AutoTransactionsResource(this.transport);\n this.wallets = new WalletsResource(this.transport);\n this.events = new EventsResource(this.transport);\n this.applications = new ApplicationsResource(this.transport);\n this.policies = new PoliciesResource(this.transport);\n this.signerGroups = new SignerGroupsResource(this.transport);\n this.signers = new SignersResource(this.transport);\n this.apiKeys = new ApiKeysResource(this.transport);\n this.users = new UsersResource(this.transport);\n this.webhooks = new WebhooksResource(this.transport);\n this.info = new InfoResource(this.transport);\n this.legal = new LegalResource(this.transport);\n this.rdMarketingFee = new RDMarketingFeeResource(this.transport);\n this.sandbox = new SandboxResource(this.transport);\n this.selfServe = new SelfServeResource(this.transport);\n this.feePayoutDestination = new FeePayoutDestinationResource(this.transport);\n this.paymentAgents = new PaymentAgentsResource(this.transport);\n this.instructions = new InstructionsResource(this.transport);\n this.mandates = new MandatesResource(this.transport);\n this.scheduledPayments = new ScheduledPaymentsResource(this.transport);\n this.insights = new InsightsResource(this.transport);\n this.agenticPolicy = new AgenticPolicyResource(this.transport);\n }\n\n // ==========================================================================\n // Agentic Payments high-level helpers (ALPHA)\n //\n // Collapse the multi-step, crypto-heavy hosted-agent flows into single\n // calls with good defaults. The raw operations remain reachable via\n // `signerGroups.addSigner` / `signerGroups.removeSigner` and friends.\n // ==========================================================================\n\n /**\n * Start a fresh multi-turn conversation with a payment agent.\n *\n * Pass `{ timezone }` (an IANA zone) so the agent resolves \"tomorrow\" and\n * \"10 am\" in the customer's local time rather than UTC. The conversation\n * resends it on every turn.\n *\n * @see AgentConversation\n */\n newAgentConversation(\n paymentAgentId: string,\n options?: AgentConversationOptions\n ): AgentConversation {\n return new AgentConversation(this, paymentAgentId, undefined, options);\n }\n\n /**\n * Rebuild a conversation from a persisted transcript (oldest first) —\n * for backends that store the history between requests.\n *\n * A stateless backend must pass `{ timezone }` again here: the transcript\n * carries the messages, not the zone.\n */\n resumeAgentConversation(\n paymentAgentId: string,\n history: ChatMessage[],\n options?: AgentConversationOptions\n ): AgentConversation {\n return new AgentConversation(this, paymentAgentId, history, options);\n }\n\n /**\n * Grant a principal (user or agent — both are just signers) permission to\n * spend from a wallet by adding its signer to an EXISTING signer group on\n * that wallet. Idempotent; errors if the group isn't attached to the wallet.\n *\n * @see attachUserToWallet in `agentic/wallets.ts` for the full contract.\n */\n attachUserToWallet(\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n ): Promise<{ alreadyMember: boolean }> {\n return attachUserToWalletHelper(this, walletId, signerPublicKey, spendingGroupId, options);\n }\n\n /**\n * Revoke a principal's spend permission by removing its signer from the\n * given signer group — the inverse of {@link attachUserToWallet}.\n * Idempotent; errors if the group isn't attached to the wallet.\n *\n * @see detachUserFromWallet in `agentic/wallets.ts` for the full contract.\n */\n detachUserFromWallet(\n walletId: string,\n signerPublicKey: string,\n spendingGroupId: string,\n options?: { idempotencyKey?: string }\n ): Promise<{ wasMember: boolean }> {\n return detachUserFromWalletHelper(this, walletId, signerPublicKey, spendingGroupId, options);\n }\n\n /**\n * Get the resolved base URL.\n */\n get baseURL(): string {\n return this.config.baseURL;\n }\n}\n","/**\n * ES256 (ECDSA P-256 over SHA-256) key handling for the platform's signed\n * requests: signer-group governance intents and agentic mandates verify\n * exactly this form.\n */\n\nimport {\n createPrivateKey,\n createPublicKey,\n createSign,\n createVerify,\n generateKeyPairSync,\n KeyObject,\n} from 'node:crypto';\n\n/**\n * An ES256 signer holding a P-256 private key in memory: base64 ASN.1 DER\n * ECDSA over SHA-256 of the payload, with the public key as base64 PKIX\n * (SPKI). It satisfies both `GovernanceSigner` (signer-group governance) and\n * `MandateSigner` (agentic mandates, where it is also exported as\n * `P256MandateSigner`).\n *\n * Convenient for servers, sandbox and tests. For production keys, implement\n * the signer interface over your own key custody (HSM/KMS) so the private key\n * never lives in the process. Node only (uses `node:crypto`); in a browser use\n * `webCryptoES256Signer`.\n */\nexport class ES256Signer {\n private readonly privateKey: KeyObject;\n private readonly publicKey: KeyObject;\n\n private constructor(privateKey: KeyObject, publicKey: KeyObject) {\n this.privateKey = privateKey;\n this.publicKey = publicKey;\n }\n\n /**\n * Generate a fresh P-256 keypair.\n */\n static generate(): ES256Signer {\n const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });\n return new ES256Signer(privateKey, publicKey);\n }\n\n /**\n * Adopt an existing P-256 private key. Accepts a PKCS#8 PEM string, a\n * DER-encoded PKCS#8 buffer, or a Node {@link KeyObject}.\n */\n static fromPrivateKey(key: KeyObject | string | Uint8Array): ES256Signer {\n const privateKey =\n typeof key === 'string' || key instanceof Uint8Array\n ? createPrivateKey({\n key: key as string | Buffer,\n format: typeof key === 'string' ? 'pem' : 'der',\n type: 'pkcs8',\n })\n : key;\n if (privateKey.asymmetricKeyType !== 'ec') {\n throw new Error('a P-256 private key is required (ES256)');\n }\n const details = privateKey.asymmetricKeyDetails;\n if (details?.namedCurve !== 'prime256v1') {\n throw new Error('a P-256 private key is required (ES256)');\n }\n const publicKey = createPublicKey(privateKey);\n return new ES256Signer(privateKey, publicKey);\n }\n\n /**\n * base64 PKIX (SPKI) public key — pass this as the signer's registered\n * public key at agent creation / mandate approval.\n */\n publicKeyBase64(): string {\n const der = this.publicKey.export({ format: 'der', type: 'spki' });\n return Buffer.from(der).toString('base64');\n }\n\n /**\n * Returns base64( ASN.1 ECDSA signature over SHA-256(payload) ).\n */\n sign(payload: Uint8Array): string {\n const signer = createSign('SHA256');\n signer.update(payload);\n const sig = signer.sign({ key: this.privateKey, dsaEncoding: 'der' });\n return Buffer.from(sig).toString('base64');\n }\n}\n\n/**\n * Check a base64 ASN.1 signature over SHA-256 of the canonical payload\n * against a base64 PKIX P-256 public key — the platform's exact\n * verification. Exposed so callers (and tests) can self-check a signature\n * before submitting it.\n *\n * @throws if the public key or signature can't be parsed, or the signature\n * does not verify against the payload.\n */\nexport function verifyES256Signature(\n publicKeyBase64: string,\n payload: Uint8Array,\n signatureBase64: string\n): void {\n let publicKey: KeyObject;\n try {\n publicKey = createPublicKey({\n key: Buffer.from(publicKeyBase64, 'base64'),\n format: 'der',\n type: 'spki',\n });\n } catch (err) {\n throw new Error(`parse public key: ${(err as Error).message}`);\n }\n if (publicKey.asymmetricKeyType !== 'ec') {\n throw new Error('not a P-256 public key (ES256 requires P-256)');\n }\n if (publicKey.asymmetricKeyDetails?.namedCurve !== 'prime256v1') {\n throw new Error('not a P-256 public key (ES256 requires P-256)');\n }\n const verifier = createVerify('SHA256');\n verifier.update(payload);\n const ok = verifier.verify(\n { key: publicKey, dsaEncoding: 'der' },\n Buffer.from(signatureBase64, 'base64')\n );\n if (!ok) {\n throw new Error('signature verification failed');\n }\n}\n","/**\n * §8 mandate signing. Approving (or cancelling) a mandate is not a bare API\n * call: it requires a cryptographic signature over the mandate's canonical\n * bytes, proving the action came from a holder of the registered key. This\n * file reproduces the platform's exact signed payload (RFC 8785 / JCS\n * canonical JSON) and a P-256 signing/verification path, so partners never\n * hand-roll JCS + ECDSA.\n *\n * The canonical bytes a signature covers — matched byte-for-byte with the\n * platform's MandatePayload — are JCS JSON of:\n *\n * {action, id, bound_signer, rule, valid_from, valid_until}\n *\n * signed as base64( ASN.1( ECDSA-P256( SHA-256(payload) ))), with the public\n * key as base64 PKIX (SPKI).\n *\n * Agentic payments is a beta surface (x-beta, flag-gated on the platform)\n * and may change without a major-version bump.\n */\n\nimport type { Mandate, MandateRule } from '../client/types.js';\nimport { canonicalJSON } from './canonicalize.js';\n\n/**\n * The §8 verb a signature authorizes. It is part of the signed payload so\n * an approval and a cancellation can never be each other's replay: a signed\n * cancel must not be byte-identical to a signed approve.\n */\nexport type MandateAction = 'approve' | 'cancel';\n\n/**\n * Produces the §8 signature the platform verifies for a mandate\n * approve/cancel. The caller holds the private key; the SDK never sees it.\n *\n * Implement this over your own key custody (HSM/KMS) for production. For\n * sandbox and tests, `P256MandateSigner` is a ready in-memory implementation.\n */\nexport interface MandateSigner {\n /**\n * The base64 PKIX (SPKI) P-256 public key — the exact form the platform\n * registered for this signer and verifies signatures against.\n */\n publicKeyBase64(): string;\n\n /**\n * Returns a base64 ASN.1 ECDSA signature over SHA-256(payload).\n */\n sign(payload: Uint8Array): Promise<string> | string;\n}\n\n/**\n * Reproduces, byte-for-byte, the canonical bytes the platform signs for one\n * §8 action on a mandate. Build it straight from the mandate as returned by\n * `mandates.get` / `mandates.list` — no server state is needed, and field\n * order is irrelevant (JCS sorts).\n *\n * `valid_from` / `valid_until` are always present in the signed payload\n * (even when zero); the wire omits a zero value, so a missing field\n * canonicalizes to 0 — matching the platform, which signs the int64\n * directly.\n */\nexport function mandateSignPayload(mandate: Mandate, action: MandateAction): Uint8Array {\n if (!mandate.id) {\n throw new Error('mandate has no id');\n }\n if (!mandate.bound_signer_id) {\n throw new Error('mandate has no bound_signer_id');\n }\n if (!mandate.rule) {\n throw new Error('mandate has no rule');\n }\n const encoded = canonicalJSON({\n action,\n id: mandate.id,\n bound_signer: mandate.bound_signer_id,\n rule: mandate.rule,\n valid_from: mandate.valid_from ?? 0,\n valid_until: mandate.valid_until ?? 0,\n });\n return new TextEncoder().encode(encoded);\n}\n\n/**\n * Reproduces, byte-for-byte, the canonical bytes the platform verifies for an\n * AMEND — appending version `version`, carrying `rule`, to `mandate`.\n *\n * The approve/cancel bytes are frozen, so amend gets its own payload rather\n * than an extra key on `mandateSignPayload`. It is the same JCS JSON plus one\n * key, `version`:\n *\n * {action: 'amend', id, bound_signer, rule, valid_from, valid_until, version}\n *\n * **`version` is what stops cross-version replay.** Without it, a signature\n * over `{amend, rule R}` would authorize \"make the current rule R\" forever: a\n * customer who signs v2 raising a limit to 20,000 and then v3 lowering it to\n * 5,000 could have the v2 signature replayed as a v4 — a rollback of their own\n * reduction, using their own signature. Binding the exact version number makes\n * each amend signature usable once, at one point in the mandate's history.\n *\n * `rule` is the NEW rule (what the signer is agreeing to), not the outgoing\n * one, and is taken verbatim — the amend endpoint never normalizes it, so the\n * bytes signed here are the bytes the server verifies. Pass the SAME rule\n * object to `mandates.amend`.\n *\n * @param mandate - The mandate as it is NOW (the amend is a compare-and-set on\n * its current version)\n * @param version - The version this amend creates — the mandate's current\n * `version` + 1\n * @param rule - The complete new rule, in canonical form\n */\nexport function mandateAmendSignPayload(\n mandate: Mandate,\n version: number,\n rule: MandateRule\n): Uint8Array {\n if (!mandate.id) {\n throw new Error('mandate has no id');\n }\n if (!mandate.bound_signer_id) {\n throw new Error('mandate has no bound_signer_id');\n }\n if (!Number.isInteger(version) || version < 2) {\n throw new Error('amend version must be an integer >= 2 (the version being created)');\n }\n const encoded = canonicalJSON({\n action: 'amend',\n id: mandate.id,\n bound_signer: mandate.bound_signer_id,\n rule,\n valid_from: mandate.valid_from ?? 0,\n valid_until: mandate.valid_until ?? 0,\n version,\n });\n return new TextEncoder().encode(encoded);\n}\n\n// ---------------------------------------------------------------------------\n// Endorsed-intent payload helpers.\n// ---------------------------------------------------------------------------\n//\n// Each reproduces, byte-for-byte, the canonical map the platform's policy\n// engine rebuilds to verify the endorsement (its intent reconstruction).\n// The idempotency_key is part of the signed bytes — reuse the SAME key on\n// the corresponding request.\n\n/**\n * Canonical bytes a recognized wallet signer endorses to attach a signer\n * group to a wallet.\n */\nexport function attachGroupPayload(\n walletId: string,\n groupId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'attach_group_to_wallet',\n wallet_id: walletId,\n group_id: groupId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to attach a policy to\n * a wallet.\n */\nexport function attachPolicyPayload(\n walletId: string,\n policyId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'attach_policy_to_wallet',\n wallet_id: walletId,\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to remove a signer\n * group from a wallet — the inverse of {@link attachGroupPayload}.\n */\nexport function detachGroupPayload(\n walletId: string,\n groupId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'detach_group_from_wallet',\n wallet_id: walletId,\n group_id: groupId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a recognized wallet signer endorses to remove a policy\n * from a wallet — the inverse of {@link attachPolicyPayload}.\n */\nexport function detachPolicyPayload(\n walletId: string,\n policyId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'detach_policy_from_wallet',\n wallet_id: walletId,\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to delete a policy.\n */\nexport function deletePolicyPayload(policyId: string, idempotencyKey: string): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'delete_policy',\n policy_id: policyId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to remove a rule from a policy.\n */\nexport function removePolicyRulePayload(\n policyId: string,\n ruleId: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'remove_policy_rule',\n policy_id: policyId,\n rule_id: ruleId,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to update a rule's definition. `updatedDefinition` is the rule definition\n * as a JSON STRING; it is signed opaquely, exactly as sent on the update\n * request.\n */\nexport function updatePolicyRulePayload(\n policyId: string,\n ruleId: string,\n updatedDefinition: string,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'update_policy_rule',\n policy_id: policyId,\n rule_id: ruleId,\n updated_definition: updatedDefinition,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\n/**\n * Canonical bytes a member of the policy's governing signer group endorses\n * to add a rule to a policy. `action` (e.g. `\"allow\"`), `ruleType` (e.g.\n * `\"amount_threshold\"`), and `definition` (the rule-type-specific config,\n * in API format) must match the values sent on the add request, or the\n * endorsement won't verify against it.\n */\nexport function addPolicyRulePayload(\n policyId: string,\n action: string,\n ruleType: string,\n definition: Record<string, unknown>,\n idempotencyKey: string\n): Uint8Array {\n return textBytes(\n canonicalJSON({\n type: 'add_policy_rule',\n action,\n rule_type: ruleType,\n policy_id: policyId,\n definition,\n idempotency_key: idempotencyKey,\n })\n );\n}\n\nfunction textBytes(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\n// ---------------------------------------------------------------------------\n// ES256 key handling lives in ../signing/es256.ts (shared with signer-group\n// governance, which is not a beta surface). Re-exported here under the\n// names this module has always used.\n// ---------------------------------------------------------------------------\n\nexport {\n ES256Signer as P256MandateSigner,\n verifyES256Signature as verifyMandateSignature,\n} from '../signing/es256.js';\n","/**\n * Passkey (WebAuthn) signatures for governance intents.\n *\n * The platform verifies a passkey signature like this: the assertion's\n * `clientDataJSON.challenge` must decode to the intent's canonical JSON\n * itself (NOT a hash of it), and the authenticator's signature over\n * `authenticatorData || SHA-256(clientDataJSON)` must verify against the\n * signer's registered COSE key. The `signatures[]` entry is base64url of the\n * `CredentialAssertionResponse` JSON.\n *\n * So the SDK does two small things and never touches the credential:\n * - {@link buildChallenge} gives you the bytes to pass as\n * `navigator.credentials.get({ publicKey: { challenge } })`.\n * - {@link packAssertion} turns the returned credential into the\n * `signatures[]` entry.\n */\n\nimport { base64ToBytes, bytesToBase64url, toBytes, utf8 } from './encoding.js';\nimport type { CanonicalIntent } from './intents.js';\nimport type { GovernanceSigner } from './signer.js';\n\n/**\n * Binary data as WebAuthn APIs hand it out: an ArrayBuffer or typed array\n * (browsers), or a base64 / base64url string (most React Native passkey\n * libraries, and `PublicKeyCredential.toJSON()`).\n */\nexport type BinaryOrBase64 = ArrayBuffer | ArrayBufferView | string;\n\n/**\n * The parts of a `PublicKeyCredential` (with an `AuthenticatorAssertionResponse`)\n * that the platform reads. A browser's `navigator.credentials.get()` result\n * satisfies it as-is: the DOM types its `response` as the base\n * `AuthenticatorResponse`, so `authenticatorData` and `signature` are\n * optional here and checked at run time by {@link packAssertion}.\n */\nexport interface AssertionCredential {\n readonly id: string;\n readonly rawId: BinaryOrBase64;\n readonly type: string;\n readonly authenticatorAttachment?: string | null;\n readonly response: {\n readonly clientDataJSON: BinaryOrBase64;\n readonly authenticatorData?: BinaryOrBase64;\n readonly signature?: BinaryOrBase64;\n readonly userHandle?: BinaryOrBase64 | null;\n };\n}\n\n/**\n * What a challenge can be built from: a built intent, anything else that\n * carries the `canonical` string (such as a `PreparedSignerGroupChange`),\n * the `canonical` string itself (what a server would send to the browser),\n * or its bytes.\n */\nexport type ChallengeSource =\n | CanonicalIntent\n | { readonly canonical: string }\n | string\n | Uint8Array\n | ArrayBuffer;\n\n/**\n * The WebAuthn challenge for an intent: its raw canonical JSON bytes, as a\n * fresh `ArrayBuffer`. Pass it as `publicKey.challenge`; the browser\n * base64url-encodes it into `clientDataJSON`, which is exactly what the\n * platform expects. (An `ArrayBuffer` is a `BufferSource` under every\n * TypeScript version, unlike a `Uint8Array` on TypeScript 5.7+.)\n *\n * @throws TypeError when `intent` is none of the {@link ChallengeSource} forms\n */\nexport function buildChallenge(intent: ChallengeSource): ArrayBuffer {\n const bytes = challengeBytes(intent);\n const out = new ArrayBuffer(bytes.length);\n new Uint8Array(out).set(bytes);\n return out;\n}\n\nfunction challengeBytes(intent: ChallengeSource): Uint8Array {\n if (typeof intent === 'string') {\n return utf8(intent);\n }\n if (isBinary(intent)) {\n return toBytes(intent);\n }\n if (intent && typeof intent === 'object') {\n // `canonical` first: it is the one field every source carries, and a\n // built intent's `bytes` are its UTF-8 encoding anyway.\n const canonical = (intent as { canonical?: unknown }).canonical;\n if (typeof canonical === 'string') {\n return utf8(canonical);\n }\n }\n throw new TypeError(\n 'expected a built intent, a prepared change, its canonical string, or its bytes'\n );\n}\n\nfunction isBinary(v: unknown): v is ArrayBuffer | ArrayBufferView {\n return ArrayBuffer.isView(v) || Object.prototype.toString.call(v) === '[object ArrayBuffer]';\n}\n\nfunction b64urlField(name: string, value: BinaryOrBase64 | null | undefined): string {\n if (value === undefined || value === null || value === '') {\n throw new TypeError(`passkey assertion is missing ${name}`);\n }\n if (typeof value === 'string') {\n // Normalize either base64 alphabet to unpadded base64url.\n return bytesToBase64url(base64ToBytes(value));\n }\n return bytesToBase64url(toBytes(value));\n}\n\n/**\n * Package a passkey assertion as a `signatures[]` entry: base64url of the\n * `CredentialAssertionResponse` JSON\n * (`{id, rawId, type, authenticatorAttachment?, clientExtensionResults, response: {clientDataJSON, authenticatorData, signature, userHandle?}}`,\n * every binary field base64url).\n *\n * @param credential - what `navigator.credentials.get()` returned (or a\n * mobile passkey library's equivalent)\n * @throws TypeError when it is not a public-key assertion or a field is\n * missing\n */\nexport function packAssertion(credential: AssertionCredential): string {\n if (!credential || credential.type !== 'public-key') {\n throw new TypeError('expected a WebAuthn assertion with type \"public-key\"');\n }\n if (typeof credential.id !== 'string' || credential.id === '') {\n throw new TypeError('passkey assertion is missing id');\n }\n const r = credential.response;\n if (!r) {\n throw new TypeError('passkey assertion is missing response');\n }\n const response: Record<string, string> = {\n clientDataJSON: b64urlField('clientDataJSON', r.clientDataJSON),\n authenticatorData: b64urlField('authenticatorData', r.authenticatorData),\n signature: b64urlField('signature', r.signature),\n };\n if (r.userHandle !== undefined && r.userHandle !== null && r.userHandle !== '') {\n response.userHandle = b64urlField('userHandle', r.userHandle);\n }\n const envelope: Record<string, unknown> = {\n // The verifier requires `id` to be base64url; some mobile libraries hand\n // out standard base64, so normalize it like the binary fields.\n id: b64urlField('id', credential.id),\n rawId: b64urlField('rawId', credential.rawId),\n type: 'public-key',\n clientExtensionResults: {},\n response,\n };\n if (credential.authenticatorAttachment) {\n envelope.authenticatorAttachment = credential.authenticatorAttachment;\n }\n return bytesToBase64url(utf8(JSON.stringify(envelope)));\n}\n\n/** Longest packed assertion {@link assertionChallengeMatches} will decode. */\nconst MAX_PACKED_ASSERTION_LENGTH = 64 * 1024;\n\n/**\n * Whether a packed passkey signature was made over `intent` — its challenge\n * equals the intent's canonical bytes. A cheap server-side check of what a\n * browser sent back before you submit it. It does NOT verify the signature\n * itself; the platform does that. Returns false for anything that is not a\n * packed assertion, including one longer than 64 KiB.\n */\nexport function assertionChallengeMatches(packed: string, intent: ChallengeSource): boolean {\n // `packed` usually comes from a browser, so bound the work it can cause\n // before decoding it. A real assertion is a few kilobytes.\n if (typeof packed !== 'string' || packed.length > MAX_PACKED_ASSERTION_LENGTH) {\n return false;\n }\n try {\n const envelope = JSON.parse(new TextDecoder().decode(base64ToBytes(packed))) as {\n response?: { clientDataJSON?: string };\n };\n const clientDataB64 = envelope.response?.clientDataJSON;\n if (typeof clientDataB64 !== 'string') {\n return false;\n }\n const clientData = JSON.parse(new TextDecoder().decode(base64ToBytes(clientDataB64))) as {\n challenge?: string;\n };\n if (typeof clientData.challenge !== 'string') {\n return false;\n }\n const got = base64ToBytes(clientData.challenge);\n const want = new Uint8Array(buildChallenge(intent));\n return got.length === want.length && got.every((b, i) => b === want[i]);\n } catch {\n return false;\n }\n}\n\n/**\n * A {@link GovernanceSigner} backed by a passkey. `getAssertion` receives\n * the challenge and returns the credential; in a browser:\n *\n * ```typescript\n * const signer = webauthnSigner((challenge) =>\n * navigator.credentials.get({\n * publicKey: { challenge, rpId: 'app.example.com', userVerification: 'required' },\n * }) as Promise<PublicKeyCredential>\n * );\n * ```\n *\n * Every call prompts the user, so do not use it with automatic stale-version\n * retries unless a second prompt is acceptable.\n */\nexport function webauthnSigner(\n getAssertion: (challenge: ArrayBuffer) => Promise<AssertionCredential> | AssertionCredential\n): GovernanceSigner {\n return {\n async sign(payload: Uint8Array): Promise<string> {\n const credential = await getAssertion(buildChallenge(payload));\n return packAssertion(credential);\n },\n };\n}\n"]}
|