@isroilov_an/paylov 0.0.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-DOu4B-bL.js","names":["delay","ENDPOINTS","ENDPOINTS","ENDPOINTS","ENDPOINTS","ENDPOINTS","ENDPOINTS","ENDPOINTS","ENDPOINTS","ENDPOINTS"],"sources":["../src/core/errors.ts","../src/core/numbers.ts","../src/core/money.ts","../src/core/time.ts","../src/core/decoding.ts","../src/core/errorDetails.ts","../src/core/envelope.ts","../src/core/lifecycle.ts","../src/core/http.ts","../src/core/auth.ts","../src/core/config.ts","../src/core/params.ts","../src/core/call.ts","../src/shared/otpSms.ts","../src/cards/decoders.ts","../src/cards/resource.ts","../src/shared/receiptItems.ts","../src/shared/transactions.ts","../src/fiscalization/decoders.ts","../src/fiscalization/resource.ts","../src/gateway/decoders.ts","../src/gateway/resource.ts","../src/holds/decoders.ts","../src/holds/resource.ts","../src/payments/decoders.ts","../src/payments/resource.ts","../src/splits/decoders.ts","../src/splits/resource.ts","../src/subMerchants/decoders.ts","../src/subMerchants/resource.ts","../src/transactions/decoders.ts","../src/transactions/resource.ts","../src/shared/checkoutAmount.ts","../src/onboarding/decoders.ts","../src/onboarding/client.ts"],"sourcesContent":["/**\n * The only error classes this SDK throws, one per origin. Errors carry allowlisted metadata only:\n * never a request body, query value, header, gateway message, gateway `data` or raw cause,\n * because those hold passwords, card data and caller identifiers.\n */\n\nimport type { PaylovErrorCode, PaylovKnownErrorCode } from './errorCodes.js';\nimport type { ResponseContext } from './types.js';\n\n/** Where a failure came from. */\nexport type PaylovErrorKind = 'input' | 'closed' | 'api' | 'protocol' | 'connection';\n\n/**\n * Rejected locally, before any I/O:\n * - `sdk_invalid_input`: a method parameter broke a rule.\n * - `sdk_invalid_amount`: an amount is not a valid integer amount for that call.\n * - `sdk_config_error`: constructor configuration broke a rule.\n */\nexport type PaylovInputErrorCode = 'sdk_invalid_input' | 'sdk_invalid_amount' | 'sdk_config_error';\n\n/** The rule a rejected input broke. */\nexport type PaylovInputRule = 'required' | 'type' | 'format' | 'range' | 'exclusive';\n\n/**\n * - `sdk_malformed_response`: a 2xx body did not match the endpoint's documented shape.\n * - `sdk_unexpected_status`: a non-2xx without a usable error body, for example a proxy page or\n * a bare 401/403.\n */\nexport type PaylovProtocolErrorCode = 'sdk_malformed_response' | 'sdk_unexpected_status';\n\n/** `sdk_aborted`: the caller's `signal` fired; `isSent` tells whether a request had left. */\nexport type PaylovConnectionErrorCode = 'sdk_timeout' | 'sdk_network_error' | 'sdk_aborted';\n\n/** The metadata `toJSON()` returns; safe to log. Details an error lacks are `undefined`. */\nexport interface PaylovErrorDiagnostic {\n readonly name: string;\n readonly kind: PaylovErrorKind;\n readonly code: PaylovErrorCode;\n readonly message: string;\n readonly httpStatus?: number;\n readonly endpoint?: string;\n readonly field?: string | undefined;\n readonly rule?: PaylovInputRule | undefined;\n readonly fields?: readonly string[] | undefined;\n readonly retryAfterSeconds?: number | undefined;\n readonly path?: string | undefined;\n readonly timeoutMs?: number | undefined;\n readonly isSent?: boolean;\n}\n\ntype DiagnosticDetails = Omit<PaylovErrorDiagnostic, 'name' | 'kind' | 'code' | 'message'>;\n\n/** The shared base of the five error classes; consumers use the {@link PaylovError} union. */\nabstract class PaylovBaseError extends Error {\n abstract override readonly name: string;\n abstract readonly kind: PaylovErrorKind;\n abstract readonly code: string;\n\n constructor(message: string) {\n super(message);\n Error.captureStackTrace(this, new.target);\n }\n\n /**\n * Returns SDK diagnostic metadata only.\n *\n * @example\n * logger.error('paylov call failed', error.toJSON());\n */\n toJSON(): PaylovErrorDiagnostic {\n return {\n name: this.name,\n kind: this.kind,\n code: this.code,\n message: this.message,\n ...this.diagnosticDetails(),\n };\n }\n\n protected abstract diagnosticDetails(): DiagnosticDetails;\n}\n\ninterface PaylovInputErrorInit {\n readonly code: PaylovInputErrorCode;\n readonly message: string;\n readonly field: string | undefined;\n readonly rule: PaylovInputRule;\n}\n\n/**\n * The SDK rejected a call locally, before any I/O: a parameter, an amount or the configuration\n * broke a rule. This is an integration bug, never a gateway answer. Messages name the field,\n * never its value.\n *\n * @example\n * catch (error) {\n * if (error instanceof PaylovInputError) logger.error('invalid paylov call', error.toJSON());\n * throw error;\n * }\n */\nexport class PaylovInputError extends PaylovBaseError {\n override readonly name = 'PaylovInputError' as const;\n readonly kind = 'input' as const;\n readonly code: PaylovInputErrorCode;\n /**\n * SDK parameter path such as `items[0].priceTiyin`; `undefined` when the params or\n * configuration object itself, or a choice between its top-level keys, broke the rule.\n */\n readonly field: string | undefined;\n readonly rule: PaylovInputRule;\n\n constructor(init: PaylovInputErrorInit) {\n super(init.message);\n this.code = init.code;\n this.field = init.field;\n this.rule = init.rule;\n }\n\n protected diagnosticDetails(): DiagnosticDetails {\n return { field: this.field, rule: this.rule };\n }\n}\n\n/**\n * The client was closed with `close()`. Nothing was sent, or the gateway rejected the request\n * before running it; a new client, on this process or another, can make the call.\n *\n * @example\n * catch (error) {\n * if (error instanceof PaylovClientClosedError) return serviceUnavailable();\n * throw error;\n * }\n */\nexport class PaylovClientClosedError extends PaylovBaseError {\n override readonly name = 'PaylovClientClosedError' as const;\n readonly kind = 'closed' as const;\n readonly code = 'sdk_client_closed' as const;\n\n constructor() {\n super('PaylovClient is closed; create a new client');\n }\n\n protected diagnosticDetails(): DiagnosticDetails {\n return {};\n }\n}\n\ninterface PaylovApiErrorInit {\n readonly code: PaylovErrorCode;\n readonly httpStatus: number;\n readonly endpoint: string;\n readonly fields?: readonly string[] | undefined;\n readonly retryAfterSeconds?: number | undefined;\n}\n\n/**\n * The gateway answered with an error code. Unknown codes keep this class; narrow with\n * {@link isPaylovApiError}.\n *\n * @example\n * catch (error) {\n * if (isPaylovApiError(error, 'rate_limit_exceeded')) await wait(error.retryAfterSeconds ?? 60);\n * else throw error;\n * }\n */\nexport class PaylovApiError extends PaylovBaseError {\n override readonly name = 'PaylovApiError' as const;\n readonly kind = 'api' as const;\n readonly code: PaylovErrorCode;\n readonly httpStatus: number;\n /** Static endpoint identity, e.g. `\"POST /merchant/receipts/pay/\"`. */\n readonly endpoint: string;\n /**\n * Wire field paths such as `items.0.title`, for `validation_error`, `field_not_valid` and\n * `field_required` only. Names, never messages or values; not translated to SDK names.\n */\n readonly fields: readonly string[] | undefined;\n /**\n * Seconds until a retry can succeed, from 1 to 3600: for `rate_limit_exceeded`, from the\n * `Retry-After` header (nothing retries a 429); for `card_is_blocked`,\n * the rest of the card's block after repeated wrong one-time codes.\n */\n readonly retryAfterSeconds: number | undefined;\n\n constructor(init: PaylovApiErrorInit) {\n super(`Paylov returned ${init.code} (HTTP ${init.httpStatus}) for ${init.endpoint}`);\n this.code = init.code;\n this.httpStatus = init.httpStatus;\n this.endpoint = init.endpoint;\n this.fields = init.fields;\n this.retryAfterSeconds = init.retryAfterSeconds;\n }\n\n protected diagnosticDetails(): DiagnosticDetails {\n return {\n httpStatus: this.httpStatus,\n endpoint: this.endpoint,\n fields: this.fields,\n retryAfterSeconds: this.retryAfterSeconds,\n };\n }\n}\n\ninterface PaylovProtocolErrorInit {\n readonly code: PaylovProtocolErrorCode;\n readonly httpStatus: number;\n readonly endpoint: string;\n readonly path?: string | undefined;\n}\n\n/**\n * The response did not match the endpoint's declared contract. After a POST the operation may\n * have executed: reconcile through the method's documented status read.\n *\n * @example\n * catch (error) {\n * if (error instanceof PaylovProtocolError) metrics.increment('paylov.protocol', error.toJSON());\n * throw error;\n * }\n */\nexport class PaylovProtocolError extends PaylovBaseError {\n override readonly name = 'PaylovProtocolError' as const;\n readonly kind = 'protocol' as const;\n readonly code: PaylovProtocolErrorCode;\n readonly httpStatus: number;\n readonly endpoint: string;\n /** The decoded location that failed, e.g. `result.card.status`; never its value. */\n readonly path: string | undefined;\n\n constructor(init: PaylovProtocolErrorInit) {\n super(\n init.code === 'sdk_malformed_response'\n ? `Paylov response for ${init.endpoint} has an unexpected shape` +\n (init.path !== undefined ? ` at \"${init.path}\"` : '')\n : `Paylov returned HTTP ${init.httpStatus} for ${init.endpoint} without a usable error body`,\n );\n this.code = init.code;\n this.httpStatus = init.httpStatus;\n this.endpoint = init.endpoint;\n this.path = init.path;\n }\n\n protected diagnosticDetails(): DiagnosticDetails {\n return { httpStatus: this.httpStatus, endpoint: this.endpoint, path: this.path };\n }\n}\n\ninterface PaylovConnectionErrorInit {\n readonly code: PaylovConnectionErrorCode;\n readonly endpoint: string;\n readonly isSent: boolean;\n readonly timeoutMs?: number | undefined;\n}\n\nconst CONNECTION_MESSAGES: Readonly<Record<PaylovConnectionErrorCode, string>> = {\n sdk_timeout: 'Paylov request timed out',\n sdk_network_error: 'Paylov request failed before the response was fully received',\n sdk_aborted: 'Paylov request was aborted by the caller',\n};\n\n/**\n * No usable response: DNS, TCP or TLS failure, a reset, the SDK timeout, or the caller's abort.\n * The underlying error is discarded: an injected transport can embed URLs, headers, bodies and\n * credentials anywhere in it. Once `isSent`, the operation of a POST may have executed.\n *\n * @example\n * catch (error) {\n * if (error instanceof PaylovConnectionError && error.code === 'sdk_timeout') {\n * metrics.increment('paylov.timeout', { endpoint: error.endpoint });\n * }\n * throw error;\n * }\n */\nexport class PaylovConnectionError extends PaylovBaseError {\n override readonly name = 'PaylovConnectionError' as const;\n readonly kind = 'connection' as const;\n readonly code: PaylovConnectionErrorCode;\n readonly endpoint: string;\n /**\n * Whether an attempt of the call reached the transport. `false` only for an `sdk_aborted` that\n * fired before anything was sent, so nothing can have executed.\n */\n readonly isSent: boolean;\n /** For `sdk_timeout` only: the per-attempt deadline that expired. */\n readonly timeoutMs: number | undefined;\n\n constructor(init: PaylovConnectionErrorInit) {\n const message = init.isSent\n ? CONNECTION_MESSAGES[init.code]\n : `${CONNECTION_MESSAGES[init.code]} before it was sent`;\n super(init.timeoutMs !== undefined ? `${message} after ${init.timeoutMs} ms` : message);\n this.code = init.code;\n this.endpoint = init.endpoint;\n this.isSent = init.isSent;\n this.timeoutMs = init.timeoutMs;\n }\n\n protected diagnosticDetails(): DiagnosticDetails {\n return { endpoint: this.endpoint, isSent: this.isSent, timeoutMs: this.timeoutMs };\n }\n}\n\n/**\n * Anything this SDK throws. Narrow with {@link isPaylovError}, check\n * {@link isPaylovOutcomeUnknown} (a gateway 5xx counts too), then switch on `kind` and `code`.\n *\n * @example\n * catch (error) {\n * if (!isPaylovError(error)) throw error;\n * if (isPaylovOutcomeUnknown(error)) return reconcileLater();\n * switch (error.kind) {\n * case 'closed':\n * return serviceUnavailable();\n * case 'api':\n * if (error.code === 'insufficient_funds') return declined();\n * break;\n * }\n * throw error;\n * }\n */\nexport type PaylovError =\n | PaylovInputError\n | PaylovClientClosedError\n | PaylovApiError\n | PaylovProtocolError\n | PaylovConnectionError;\n\n/** `sdk_invalid_input` for a method parameter. */\nexport function invalidInput(\n message: string,\n field: string,\n rule: PaylovInputRule,\n): PaylovInputError {\n return new PaylovInputError({ code: 'sdk_invalid_input', message, field, rule });\n}\n\n/** `sdk_invalid_amount` for an amount parameter. */\nexport function invalidAmount(\n message: string,\n field: string,\n rule: PaylovInputRule,\n): PaylovInputError {\n return new PaylovInputError({ code: 'sdk_invalid_amount', message, field, rule });\n}\n\n/** `sdk_config_error` for constructor configuration. */\nexport function configError(\n message: string,\n field: string,\n rule: PaylovInputRule,\n): PaylovInputError {\n return new PaylovInputError({ code: 'sdk_config_error', message, field, rule });\n}\n\nexport function clientClosedError(): PaylovClientClosedError {\n return new PaylovClientClosedError();\n}\n\n/** `sdk_malformed_response` for a 2xx body that does not match its documented shape. */\nexport function malformedResponse(context: ResponseContext, path?: string): PaylovProtocolError {\n return new PaylovProtocolError({ code: 'sdk_malformed_response', ...context, path });\n}\n\n/** `sdk_unexpected_status` for a non-2xx without a usable error body. */\nexport function unexpectedStatus(context: ResponseContext): PaylovProtocolError {\n return new PaylovProtocolError({ code: 'sdk_unexpected_status', ...context });\n}\n\n/** `sdk_aborted` for the caller's abort; `isSent` once an attempt of the call reached fetch. */\nexport function abortedError(endpoint: string, isSent: boolean): PaylovConnectionError {\n return new PaylovConnectionError({ code: 'sdk_aborted', endpoint, isSent });\n}\n\n/**\n * True for anything this SDK throws; narrows to the {@link PaylovError} union.\n *\n * @example\n * catch (error) {\n * if (!isPaylovError(error)) throw error;\n * metrics.increment('paylov.failure', { kind: error.kind, code: error.code });\n * }\n */\nexport function isPaylovError(error: unknown): error is PaylovError {\n return error instanceof PaylovBaseError;\n}\n\n/**\n * True when the operation may have executed although the call failed: a protocol error, a\n * connection error once a request was sent, or a gateway error with HTTP status 500 or above.\n * Reconcile such a call through the method's documented status read before repeating it. False\n * for input and closed-client errors, for an abort before anything was sent, for other gateway\n * errors, and for anything the SDK did not throw.\n *\n * @example\n * catch (error) {\n * if (isPaylovOutcomeUnknown(error)) return queueReconciliation(transactionId);\n * throw error;\n * }\n */\nexport function isPaylovOutcomeUnknown(error: unknown): boolean {\n if (!isPaylovError(error)) return false;\n if (error.kind === 'api') return error.httpStatus >= 500;\n if (error.kind === 'connection') return error.isSent;\n return error.kind === 'protocol';\n}\n\n/**\n * True for a gateway error code; with codes, only for one of those codes.\n *\n * @example\n * catch (error) {\n * if (isPaylovApiError(error, 'transaction_already_payed')) return markPaid(transactionId);\n * throw error;\n * }\n */\nexport function isPaylovApiError(error: unknown): error is PaylovApiError;\nexport function isPaylovApiError<C extends PaylovKnownErrorCode>(\n error: unknown,\n ...codes: [C, ...C[]]\n): error is PaylovApiError & { readonly code: C };\nexport function isPaylovApiError(error: unknown, ...codes: readonly string[]): boolean {\n return error instanceof PaylovApiError && (codes.length === 0 || codes.includes(error.code));\n}\n","/** Number guards shared by money, time and decoding. */\n\n/** A count, an id, a timestamp in seconds, or an amount in a minor unit. */\nexport function isNonNegativeSafeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n","/** Integer-tiyin money guards and converters (1 SUM = 100 tiyin). No float touches an amount. */\n\nimport { invalidAmount } from './errors.js';\nimport { isNonNegativeSafeInteger } from './numbers.js';\n\nconst DECIMAL_SUM = /^(\\d+)(?:\\.(\\d{1,2}))?$/;\n\n/** Every public amount and every wire minor-unit amount is a non-negative safe integer. */\nconst isTiyin: (value: unknown) => value is number = isNonNegativeSafeInteger;\n\n/**\n * Validates a caller amount. `label` prefixes the message (a method context); messages never\n * quote a rejected value.\n */\nexport function readTiyin(value: unknown, field: string, label: string = field): number {\n if (value === undefined) throw invalidAmount(`${label} is required`, field, 'required');\n if (!isTiyin(value)) {\n throw invalidAmount(`${label} must be a non-negative safe integer`, field, 'type');\n }\n return value;\n}\n\n/** A wire SUM amount as tiyin, or `undefined` when it is not a non-negative safe whole SUM. */\nexport function wireSumToTiyin(sum: unknown): number | undefined {\n if (!isNonNegativeSafeInteger(sum)) return undefined;\n const amountTiyin = sum * 100;\n return Number.isSafeInteger(amountTiyin) ? amountTiyin : undefined;\n}\n\n/** A tiyin amount as wire whole SUM, or `undefined` when it is not a whole SUM amount. */\nexport function tiyinToWireSum(amountTiyin: number): number | undefined {\n return isTiyin(amountTiyin) && amountTiyin % 100 === 0 ? amountTiyin / 100 : undefined;\n}\n\n/**\n * Converts SUM to tiyin exactly: a whole-SUM safe integer, or a decimal string with at most two\n * fraction digits. Pass a string for fractional SUM; a fractional number is rejected.\n *\n * @throws {@link PaylovInputError} `sdk_invalid_amount` for a negative, fractional or unsafe\n * number, a malformed string, or a result too large to express in tiyin.\n *\n * @example\n * sumToTiyin(1000); // 100000\n * sumToTiyin('12.5'); // 1250\n * sumToTiyin(10.5); // throws PaylovInputError sdk_invalid_amount\n */\nexport function sumToTiyin(sum: number | string): number {\n if (typeof sum === 'number') {\n const amountTiyin = wireSumToTiyin(sum);\n if (amountTiyin === undefined) {\n throw invalidAmount('sum must be a non-negative whole SUM safe integer', 'sum', 'type');\n }\n return amountTiyin;\n }\n const match = typeof sum === 'string' ? DECIMAL_SUM.exec(sum) : null;\n if (match === null) {\n throw invalidAmount(\n 'sum must be a decimal string with at most 2 fraction digits',\n 'sum',\n 'format',\n );\n }\n const [, whole = '', fraction = ''] = match;\n const amountTiyin = Number(whole) * 100 + Number(fraction.padEnd(2, '0'));\n if (!Number.isSafeInteger(amountTiyin)) {\n throw invalidAmount('sum is too large to express in tiyin', 'sum', 'range');\n }\n return amountTiyin;\n}\n\n/**\n * Formats a tiyin amount for display: ASCII-space thousands, `.` decimals, always two decimals.\n * Locale-independent, so output is identical on every Node ICU build. Never send it on the wire.\n *\n * @throws {@link PaylovInputError} `sdk_invalid_amount` when `amountTiyin` is not a non-negative\n * safe integer, so validate computed values such as balance deltas before display.\n *\n * @example\n * formatSum(2_500_000); // '25 000.00'\n * formatSum(5); // '0.05'\n */\nexport function formatSum(amountTiyin: number): string {\n readTiyin(amountTiyin, 'amountTiyin');\n // String slicing, not division: no float ever touches the amount.\n const digits = String(amountTiyin).padStart(3, '0');\n const whole = digits.slice(0, -2).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ' ');\n return `${whole}.${digits.slice(-2)}`;\n}\n","/**\n * Strict wire timestamp parsers. Each returns `undefined` for a malformed string or an impossible\n * calendar date. Tashkent is a fixed +05:00 offset without DST, so no time-zone database is\n * consulted.\n */\n\nimport { isNonNegativeSafeInteger } from './numbers.js';\n\nconst LOCAL_DATE_TIME = /^(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})$/;\nconst ISO_DATE_TIME =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:Z|([+-])(\\d{2}):(\\d{2}))$/;\n\n/** Tashkent's fixed offset east of UTC. */\nexport const TASHKENT_OFFSET_MINUTES = 300;\nconst MINUTE_MS = 60_000;\n\ntype WallClock = readonly [\n year: number,\n month: number,\n day: number,\n hour: number,\n minute: number,\n second: number,\n];\n\n/** Capture groups 1–6 as wall-clock components. */\nfunction wallClockOf(match: RegExpExecArray): WallClock {\n const at = (group: number): number => Number(match[group]);\n return [at(1), at(2), at(3), at(4), at(5), at(6)];\n}\n\n/**\n * Epoch milliseconds of wall-clock components read as UTC, or `undefined` when they do not\n * round-trip (Feb 30, hour 24, ...). `setUTCFullYear` keeps years below 100 literal.\n */\nfunction wallClockMs(parts: WallClock): number | undefined {\n const [year, month, day, hour, minute, second] = parts;\n const date = new Date(0);\n date.setUTCFullYear(year, month - 1, day);\n date.setUTCHours(hour, minute, second, 0);\n const actual = [\n date.getUTCFullYear(),\n date.getUTCMonth() + 1,\n date.getUTCDate(),\n date.getUTCHours(),\n date.getUTCMinutes(),\n date.getUTCSeconds(),\n ];\n return actual.every((value, index) => value === parts[index]) ? date.getTime() : undefined;\n}\n\n/** A four-digit year plus an offset of under a day always lies inside the `Date` range. */\nfunction parseLocal(value: string, offsetMinutes: number): Date | undefined {\n const match = LOCAL_DATE_TIME.exec(value);\n const ms = match === null ? undefined : wallClockMs(wallClockOf(match));\n return ms === undefined ? undefined : new Date(ms - offsetMinutes * MINUTE_MS);\n}\n\n/** `YYYY-MM-DD HH:mm:ss` in Tashkent time. */\nexport function parseTashkentDateTime(value: string): Date | undefined {\n return parseLocal(value, TASHKENT_OFFSET_MINUTES);\n}\n\n/** `YYYY-MM-DD HH:mm:ss` in UTC. */\nexport function parseUtcDateTime(value: string): Date | undefined {\n return parseLocal(value, 0);\n}\n\n/** Minutes east of UTC for groups 8–10 of an ISO match; `Z` leaves them unset. */\nfunction isoOffsetMinutes(match: RegExpExecArray): number | undefined {\n if (match[8] === undefined) return 0;\n const hours = Number(match[9]);\n const minutes = Number(match[10]);\n if (hours > 23 || minutes > 59) return undefined;\n return (match[8] === '-' ? -1 : 1) * (hours * 60 + minutes);\n}\n\n/** ISO 8601 with `Z` or `±HH:MM`; fractions beyond milliseconds are truncated. */\nexport function parseIsoDateTime(value: string): Date | undefined {\n const match = ISO_DATE_TIME.exec(value);\n if (match === null) return undefined;\n const ms = wallClockMs(wallClockOf(match));\n const offset = isoOffsetMinutes(match);\n if (ms === undefined || offset === undefined) return undefined;\n const fractionMs = Number((match[7] ?? '').padEnd(3, '0').slice(0, 3));\n return new Date(ms + fractionMs - offset * MINUTE_MS);\n}\n\n/** Non-negative safe-integer unix seconds inside the `Date` range. */\nexport function fromUnixSeconds(value: number): Date | undefined {\n if (!isNonNegativeSafeInteger(value)) return undefined;\n const date = new Date(value * 1000);\n return Number.isFinite(date.getTime()) ? date : undefined;\n}\n","/**\n * Response decoding primitives. A decoder takes the value and the path reported on failure, and\n * throws {@link DecodeFailure}, which only {@link decodePayload} turns into a public error.\n * Rejected values never enter errors: only the path does.\n */\n\nimport { malformedResponse } from './errors.js';\nimport { wireSumToTiyin } from './money.js';\nimport { isNonNegativeSafeInteger } from './numbers.js';\nimport {\n fromUnixSeconds,\n parseIsoDateTime,\n parseTashkentDateTime,\n parseUtcDateTime,\n} from './time.js';\nimport type { HttpResponse, PaylovJsonObject, PaylovJsonValue } from './types.js';\n\nexport type Decoder<T> = (value: unknown, path: string) => T;\n\n/** A decoded value broke its decoder at `path`. Internal: never surfaced as it is. */\nexport class DecodeFailure extends Error {\n readonly path: string;\n\n constructor(path: string) {\n super(`undecodable value at \"${path}\"`);\n this.path = path;\n }\n}\n\n/**\n * Decodes a response payload from `root` (`result` or `body`); a failure becomes\n * `sdk_malformed_response` at its path, with the response's endpoint and status.\n */\nexport function decodePayload<T>(response: HttpResponse, root: string, decode: Decoder<T>): T {\n try {\n return decode(response.payload, root);\n } catch (error) {\n if (error instanceof DecodeFailure) throw malformedResponse(response.context, error.path);\n throw error;\n }\n}\n\n/** Decodes one field of a record, reporting failures at `<path>.<key>`. */\nexport type FieldReader = <T>(key: string, decode: Decoder<T>) => T;\n\n/** A canonical UUID in either case. */\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Deeper JSON is rejected instead of copied: recursion this deep would overflow the stack. */\nconst MAX_JSON_DEPTH = 64;\n\n/** 4 to 6 leading digits, a `*` mask, the last 4 (docs 6+4, DEV 4+4). */\nconst MASKED_PAN = /^\\d{4,6}\\*+\\d{4}$/;\n\n/** A non-array object. */\nexport function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isUuid(value: unknown): value is string {\n return typeof value === 'string' && UUID.test(value);\n}\n\n/**\n * Copies a parsed JSON tree into typed JSON values; `undefined` when it holds anything else or\n * nests deeper than 64 levels.\n */\nexport function toJsonValue(value: unknown, depth = 0): PaylovJsonValue | undefined {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (depth >= MAX_JSON_DEPTH) return undefined;\n if (Array.isArray(value)) {\n const items: PaylovJsonValue[] = [];\n for (const item of value) {\n const json = toJsonValue(item, depth + 1);\n if (json === undefined) return undefined;\n items.push(json);\n }\n return items;\n }\n return isRecord(value) ? toJsonObject(value, depth) : undefined;\n}\n\nexport function toJsonObject(\n value: Readonly<Record<string, unknown>>,\n depth = 0,\n): PaylovJsonObject | undefined {\n const entries: [string, PaylovJsonValue][] = [];\n for (const [key, child] of Object.entries(value)) {\n const json = toJsonValue(child, depth + 1);\n if (json === undefined) return undefined;\n entries.push([key, json]);\n }\n return Object.fromEntries(entries);\n}\n\nexport function asRecord(value: unknown, path: string): Readonly<Record<string, unknown>> {\n if (!isRecord(value)) throw new DecodeFailure(path);\n return value;\n}\n\nexport function readFields(value: unknown, path: string): FieldReader {\n const record = asRecord(value, path);\n return (key, decode) => decode(record[key], `${path}.${key}`);\n}\n\n/** Decodes the single field `key` of a record. */\nexport function fieldOf<T>(key: string, decode: Decoder<T>): Decoder<T> {\n return (value, path) => readFields(value, path)(key, decode);\n}\n\nexport function asString(value: unknown, path: string): string {\n if (typeof value !== 'string') throw new DecodeFailure(path);\n return value;\n}\n\nexport function asNonEmptyString(value: unknown, path: string): string {\n const text = asString(value, path);\n if (text === '') throw new DecodeFailure(path);\n return text;\n}\n\nexport function asUuid(value: unknown, path: string): string {\n if (!isUuid(value)) throw new DecodeFailure(path);\n return value;\n}\n\nexport function asBoolean(value: unknown, path: string): boolean {\n if (typeof value !== 'boolean') throw new DecodeFailure(path);\n return value;\n}\n\n/** A count, an id or a lifetime in seconds. */\nexport function asNonNegativeInteger(value: unknown, path: string): number {\n if (!isNonNegativeSafeInteger(value)) throw new DecodeFailure(path);\n return value;\n}\n\n/** A wire amount already in tiyin. */\nexport const asTiyin: Decoder<number> = asNonNegativeInteger;\n\n/** A wire amount in whole SUM, as tiyin. */\nexport function asTiyinFromSum(value: unknown, path: string): number {\n const amountTiyin = wireSumToTiyin(value);\n if (amountTiyin === undefined) throw new DecodeFailure(path);\n return amountTiyin;\n}\n\n/** Anything else may be a full PAN, so it is rejected without being retained. */\nexport function asMaskedPan(value: unknown, path: string): string {\n const pan = asString(value, path);\n if (!MASKED_PAN.test(pan)) throw new DecodeFailure(path);\n return pan;\n}\n\n/** One of a closed set of wire values. Response unions stay open: use this for wire literals. */\nexport function asLiteral<const T extends string | number>(...values: readonly T[]): Decoder<T> {\n return (value, path) => {\n const match = values.find((candidate) => candidate === value);\n if (match === undefined) throw new DecodeFailure(path);\n return match;\n };\n}\n\nexport function asJsonObject(value: unknown, path: string): PaylovJsonObject {\n const json = toJsonObject(asRecord(value, path));\n if (json === undefined) throw new DecodeFailure(path);\n return json;\n}\n\n/** A documented `T | null` field; an absent key is malformed. */\nexport function nullable<T>(decode: Decoder<T>): Decoder<T | null> {\n return (value, path) => (value === null ? null : decode(value, path));\n}\n\n/** A field the gateway may omit or null; both read as `null`. */\nexport function nullish<T>(decode: Decoder<T>): Decoder<T | null> {\n return (value, path) => (value === null || value === undefined ? null : decode(value, path));\n}\n\n/** Decodes each item, reporting failures at `<path>[<index>]`. */\nexport function arrayOf<T>(decodeItem: Decoder<T>): Decoder<readonly T[]> {\n return (value, path) => {\n if (!Array.isArray(value)) throw new DecodeFailure(path);\n return value.map((item: unknown, index) => decodeItem(item, `${path}[${index}]`));\n };\n}\n\nfunction dateDecoder(parse: (value: string) => Date | undefined): Decoder<Date> {\n return (value, path) => {\n const date = parse(asString(value, path));\n if (date === undefined) throw new DecodeFailure(path);\n return date;\n };\n}\n\n/** `YYYY-MM-DD HH:mm:ss` in Tashkent time (fixed +05:00). */\nexport const asTashkentDateTime: Decoder<Date> = dateDecoder(parseTashkentDateTime);\n/** `YYYY-MM-DD HH:mm:ss` in UTC. */\nexport const asUtcDateTime: Decoder<Date> = dateDecoder(parseUtcDateTime);\n/** ISO 8601 with an explicit offset. */\nexport const asIsoDateTime: Decoder<Date> = dateDecoder(parseIsoDateTime);\n\n/** Non-negative integer Unix seconds, as a JSON number. */\nexport const asUnixDateTime: Decoder<Date> = (value, path) => {\n const date = typeof value === 'number' ? fromUnixSeconds(value) : undefined;\n if (date === undefined) throw new DecodeFailure(path);\n return date;\n};\n","/**\n * Closed decoders for the few facts a gateway `error` carries beyond its code. `message` is never\n * read: Paylov documents it as display text not to be parsed. Everything in `data` but field names\n * and the card-block delay is discarded: upstream integrations (Didox, WLCM) embed third-party\n * text and values there.\n */\n\nimport { isRecord } from './decoding.js';\n\ninterface ErrorDetails {\n readonly fields: readonly string[] | undefined;\n readonly retryAfterSeconds: number | undefined;\n}\n\nconst MAX_FIELDS = 32;\nconst FIELD_SEGMENT = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;\nconst INDEX_SEGMENT = /^\\d{1,9}$/;\nconst RETRY_AFTER_HEADER = /^\\d{1,4}$/;\nconst MAX_RETRY_AFTER_SECONDS = 3600;\n\n/** A numeric key is an array index only below a named key; top level it is a JSON offset. */\nfunction isFieldSegment(key: string, depth: number): boolean {\n return FIELD_SEGMENT.test(key) || (depth > 0 && INDEX_SEGMENT.test(key));\n}\n\n/** Flattens the key paths of a validation `data` map, keeping names only. */\nfunction collectFieldPaths(value: unknown, prefix: readonly string[], paths: string[]): void {\n if (paths.length >= MAX_FIELDS) return;\n if (isRecord(value)) {\n for (const [key, child] of Object.entries(value)) {\n if (isFieldSegment(key, prefix.length)) collectFieldPaths(child, [...prefix, key], paths);\n }\n return;\n }\n if (Array.isArray(value) && value.some(isRecord)) {\n value.forEach((child, index) => {\n if (isRecord(child)) collectFieldPaths(child, [...prefix, String(index)], paths);\n });\n return;\n }\n if (prefix.length > 0 && paths.length < MAX_FIELDS) paths.push(prefix.join('.'));\n}\n\nfunction isFieldPath(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.split('.').every((segment, depth) => isFieldSegment(segment, depth))\n );\n}\n\n/**\n * `validation_error` maps field names to messages; `field_not_valid` and `field_required` name one\n * field as `data.field`. Live, `field_not_valid` also sends the bare name and `field_required`\n * sends no `data` at all.\n */\nfunction decodeFields(code: string, data: unknown): readonly string[] {\n switch (code) {\n case 'validation_error': {\n const paths: string[] = [];\n collectFieldPaths(data, [], paths);\n return paths;\n }\n case 'field_not_valid':\n case 'field_required': {\n const field = isRecord(data) ? data['field'] : data;\n return isFieldPath(field) ? [field] : [];\n }\n default:\n return [];\n }\n}\n\nfunction asRetryDelay(seconds: unknown): number | undefined {\n const isDelay =\n typeof seconds === 'number' &&\n Number.isInteger(seconds) &&\n seconds >= 1 &&\n seconds <= MAX_RETRY_AFTER_SECONDS;\n return isDelay ? seconds : undefined;\n}\n\n/** Only the delta-seconds form of `Retry-After`; an HTTP-date reports no delay. */\nfunction decodeRateLimitDelay(retryAfter: string | null): number | undefined {\n const header = retryAfter?.trim();\n return header !== undefined && RETRY_AFTER_HEADER.test(header)\n ? asRetryDelay(Number(header))\n : undefined;\n}\n\n/** A blocked card reports the rest of its block as `data.sec_to_retry`. */\nfunction decodeCardBlockDelay(data: unknown): number | undefined {\n return asRetryDelay(isRecord(data) ? data['sec_to_retry'] : undefined);\n}\n\nfunction decodeRetryAfter(\n code: string,\n data: unknown,\n retryAfter: string | null,\n): number | undefined {\n if (code === 'rate_limit_exceeded') return decodeRateLimitDelay(retryAfter);\n if (code === 'card_is_blocked') return decodeCardBlockDelay(data);\n return undefined;\n}\n\n/**\n * The public details of one enveloped gateway error; absent facts are `undefined`. `retryAfter`\n * is the response's `Retry-After` header, the only header read.\n */\nexport function decodeErrorDetails(\n code: string,\n error: Readonly<Record<string, unknown>>,\n retryAfter: string | null,\n): ErrorDetails {\n const fields = decodeFields(code, error['data']);\n const retryAfterSeconds = decodeRetryAfter(code, error['data'], retryAfter);\n return { fields: fields.length > 0 ? fields : undefined, retryAfterSeconds };\n}\n","/**\n * The only interpreter of raw Paylov response bodies. Every observed REST failure, the token,\n * revoke and onboarding endpoints included, is `{result: null, error: {code, message, data?}}`.\n * Success depends on the shape the endpoint declares; the SDK never guesses it.\n */\n\nimport { decodeErrorDetails } from './errorDetails.js';\nimport {\n malformedResponse,\n PaylovApiError,\n unexpectedStatus,\n type PaylovProtocolError,\n} from './errors.js';\nimport { isRecord } from './decoding.js';\nimport type { ResponseContext, ResponseShape } from './types.js';\n\nconst WIRE_ERROR_CODE = /^[a-z][a-z0-9_]{0,127}$/;\n\n/** Error codes are identifiers, never arbitrary response text. */\nexport function isWireErrorCode(value: unknown): value is string {\n return typeof value === 'string' && WIRE_ERROR_CODE.test(value);\n}\n\nfunction isSuccessStatus(httpStatus: number): boolean {\n return httpStatus >= 200 && httpStatus < 300;\n}\n\n/** The validated `error.code` a body carries, for logger events and the 401 replay rule. */\nexport function envelopeErrorCode(body: unknown): string | undefined {\n const error = isRecord(body) ? body['error'] : undefined;\n const code = isRecord(error) ? error['code'] : undefined;\n return isWireErrorCode(code) ? code : undefined;\n}\n\n/** A body that is neither a declared success nor a decodable error. */\nfunction unusableBody(context: ResponseContext): PaylovProtocolError {\n return isSuccessStatus(context.httpStatus)\n ? malformedResponse(context)\n : unexpectedStatus(context);\n}\n\nfunction apiError(\n code: string,\n error: Readonly<Record<string, unknown>>,\n context: ResponseContext,\n retryAfter: string | null,\n): PaylovApiError {\n return new PaylovApiError({\n code,\n ...context,\n ...decodeErrorDetails(code, error, retryAfter),\n });\n}\n\nfunction unwrapResult(body: Readonly<Record<string, unknown>>, context: ResponseContext): unknown {\n const result = body['result'];\n // `result` may be a primitive such as `true`; only null or absent is malformed.\n if (result === null || result === undefined) throw malformedResponse(context, 'result');\n return result;\n}\n\nfunction successPayload(body: unknown, context: ResponseContext, shape: ResponseShape): unknown {\n if (shape === 'array') {\n if (!Array.isArray(body)) throw malformedResponse(context);\n return body;\n }\n if (!isRecord(body)) throw malformedResponse(context);\n if (shape === 'flat') return body;\n return unwrapResult(body, context);\n}\n\n/**\n * Returns the success payload as `unknown` for the owning decoder, or throws: `PaylovApiError`\n * for a decodable `error`, `PaylovProtocolError` for anything else. `retryAfter` is the\n * response's `Retry-After` header.\n */\nexport function normalizeResponse(\n body: unknown,\n context: ResponseContext,\n shape: ResponseShape,\n retryAfter: string | null,\n): unknown {\n // Branch on `error` being non-null, never on key presence or on the status alone: 404 carries\n // `card_not_found`, and some successes omit `error`.\n const error = isRecord(body) ? body['error'] : undefined;\n if (error !== null && error !== undefined) {\n const code = isRecord(error) ? error['code'] : undefined;\n if (!isRecord(error) || !isWireErrorCode(code)) throw unusableBody(context);\n throw apiError(code, error, context, retryAfter);\n }\n if (!isSuccessStatus(context.httpStatus)) throw unexpectedStatus(context);\n return successPayload(body, context, shape);\n}\n","/** Client open/closed state and caller cancellation, shared by the transport and token manager. */\n\nimport { clientClosedError } from './errors.js';\n\n/**\n * The open/closed state one `PaylovClient` shares across its transports and token manager.\n * Closing never aborts a request already sent; it refuses every later send.\n */\nexport class ClientLifecycle {\n #closed = false;\n\n get closed(): boolean {\n return this.#closed;\n }\n\n close(): void {\n this.#closed = true;\n }\n\n assertOpen(): void {\n if (this.#closed) throw clientClosedError();\n }\n}\n\n/** Rejects a wait once its signal fires; never surfaced, so it carries nothing. */\nclass AbortedWait extends Error {}\n\n/**\n * Settles with `promise`, or rejects once `signal` aborts, whichever comes first. Raced against\n * fetch and the body read, so the deadline holds even for a fetch that ignores its signal.\n */\nexport function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const onAbort = (): void => {\n reject(new AbortedWait());\n };\n if (signal.aborted) onAbort();\n signal.addEventListener('abort', onAbort, { once: true });\n void promise.then(resolve, reject).finally(() => {\n signal.removeEventListener('abort', onAbort);\n });\n });\n}\n\n/**\n * Waits for `promise` unless the caller's `signal` aborts first, then rejects with `aborted()`.\n * Only the wait is abandoned: a shared operation behind `promise` (a token grant) keeps running\n * for its other waiters.\n */\nexport async function untilAborted<T>(\n promise: Promise<T>,\n signal: AbortSignal | undefined,\n aborted: () => Error,\n): Promise<T> {\n if (signal === undefined) return promise;\n try {\n return await raceAbort(promise, signal);\n } catch (error) {\n if (signal.aborted) throw aborted();\n throw error;\n }\n}\n","/** Transport: URL construction, deadlines, abort, metadata logging, GET-only retries, 401 replay. */\n\nimport { setTimeout as delay } from 'node:timers/promises';\n\nimport { envelopeErrorCode, normalizeResponse } from './envelope.js';\nimport {\n abortedError,\n clientClosedError,\n invalidInput,\n PaylovConnectionError,\n type PaylovClientClosedError,\n} from './errors.js';\nimport { raceAbort, untilAborted, type ClientLifecycle } from './lifecycle.js';\nimport type {\n AuthorizationContext,\n AuthProvider,\n Endpoint,\n FetchLike,\n HttpClient,\n HttpResponse,\n PaylovHttpMethod,\n PaylovLogger,\n PaylovTransportConfig,\n RequestOptions,\n ResponseShape,\n} from './types.js';\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_RETRIES = 2;\nconst BASE_DELAY_MS = 200;\n/**\n * Transient gateway failures. 429 is excluded: the token endpoint asks for tens of seconds\n * (`retryAfterSeconds`), which a sub-second backoff would only spend against the same window.\n */\nconst RETRYABLE_STATUSES: ReadonlySet<number> = new Set([500, 502, 503, 504]);\nconst RATE_LIMITED = 429;\n\n/** Whether a GET that received `httpStatus` is retried. */\nexport function isRetryableStatus(httpStatus: number): boolean {\n return RETRYABLE_STATUSES.has(httpStatus);\n}\n\nexport interface HttpClientConfig extends PaylovTransportConfig {\n /** A bare origin, already validated by the surface's configuration. */\n readonly origin: string;\n /** Supplies Bearer headers and enables the single 401 replay. */\n readonly auth?: AuthProvider;\n readonly lifecycle?: ClientLifecycle;\n /** Test seams for deterministic backoff and jitter; not in any public configuration. */\n readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n readonly random?: () => number;\n}\n\nfunction noop(): void {\n // Swallows a rejection nobody awaits.\n}\n\n/** A logger, sync or async, must never delay or fail a request. */\nfunction callHookSafely(run: () => void | Promise<void>): void {\n void Promise.try(run).catch(noop);\n}\n\n/** Opens one logged attempt; the returned function closes it. */\nfunction logAttempt(\n logger: PaylovLogger | undefined,\n method: PaylovHttpMethod,\n endpoint: string,\n attempt: number,\n): (httpStatus: number, errorCode: string | undefined) => void {\n const event = { method, endpoint, attempt };\n if (logger?.onRequest !== undefined) callHookSafely(() => logger.onRequest?.(event));\n const startedAt = Date.now();\n return (httpStatus, errorCode) => {\n if (logger?.onResponse === undefined) return;\n const response = {\n ...event,\n httpStatus,\n durationMs: Date.now() - startedAt,\n ...(errorCode !== undefined ? { errorCode } : {}),\n };\n callHookSafely(() => logger.onResponse?.(response));\n };\n}\n\n/** The static identity logs and errors carry, e.g. `\"GET /merchant/userCard/getCard/{cardId}/\"`. */\nexport function endpointName(endpoint: Pick<Endpoint, 'method' | 'route'>): string {\n return `${endpoint.method} ${endpoint.route}`;\n}\n\n/** Rejects a lone surrogate before `encodeURIComponent` throws an unwrapped native error. */\nfunction encodeComponent(value: string, field: string): string {\n if (!value.isWellFormed()) {\n throw invalidInput(`${field} must contain well-formed Unicode`, field, 'format');\n }\n return encodeURIComponent(value);\n}\n\n/** Keeps an identifier inside one path segment; URL parsers normalize even encoded dot segments. */\nfunction encodePathSegment(value: string, field: string): string {\n if (value === '.' || value === '..') {\n throw invalidInput(`${field} must not be a dot path segment`, field, 'format');\n }\n return encodeComponent(value, field);\n}\n\n/** The route with each `{name}` filled; failures name the placeholder, the SDK parameter. */\nfunction fillRoute(route: string, values: Readonly<Record<string, string>> = {}): string {\n let path = route;\n for (const [name, value] of Object.entries(values)) {\n const segment = encodePathSegment(value, name);\n path = path.replace(`{${name}}`, () => segment);\n }\n return path;\n}\n\nfunction buildUrl(origin: string, route: string, options: RequestOptions): string {\n const path = fillRoute(route, options.path);\n const pairs = Object.entries(options.query ?? {}).flatMap(([key, value]) =>\n value === undefined\n ? []\n : [`${encodeURIComponent(key)}=${encodeComponent(String(value), key)}`],\n );\n return pairs.length > 0 ? `${origin}${path}?${pairs.join('&')}` : `${origin}${path}`;\n}\n\nfunction requestHeaders(\n custom: Readonly<Record<string, string>> = {},\n hasBody: boolean,\n): Record<string, string> {\n return {\n accept: 'application/json',\n ...custom,\n ...(hasBody ? { 'content-type': 'application/json' } : {}),\n };\n}\n\n/** Unparseable bodies become `undefined`; the normalizer classifies them by status. */\nasync function readJson(response: Response): Promise<unknown> {\n const raw = await response.text();\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return undefined;\n }\n}\n\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return delay(ms, undefined, signal === undefined ? {} : { signal });\n}\n\nfunction failureCode(\n callerSignal: AbortSignal | undefined,\n timeout: AbortSignal,\n): PaylovConnectionError['code'] {\n if (callerSignal?.aborted === true) return 'sdk_aborted';\n return timeout.aborted ? 'sdk_timeout' : 'sdk_network_error';\n}\n\ninterface Failed {\n readonly kind: 'failed';\n readonly failure: PaylovConnectionError;\n}\n\ninterface Received {\n readonly kind: 'received';\n readonly response: Response;\n readonly body: unknown;\n}\n\n/** A received exchange with the envelope code it logged and the credentials it carried. */\ninterface ReceivedAttempt extends Received {\n readonly errorCode: string | undefined;\n readonly authorization: AuthorizationContext | undefined;\n}\n\ntype Exchange = Received | Failed;\ntype Attempt = ReceivedAttempt | Failed;\n\n/** Whether a GET may retry: a connection failure other than an abort, or a transient status. */\nfunction isTransientFailure(outcome: Attempt): boolean {\n return outcome.kind === 'failed'\n ? outcome.failure.code !== 'sdk_aborted'\n : isRetryableStatus(outcome.response.status);\n}\n\n/**\n * Only the gateway's own authentication rejection is replayed. Bearer authentication is expected\n * to reject before any handler runs (an inference: every captured 401 answered a GET), so the\n * rejected request should not have executed. A bare 401 (a proxy) proves nothing about the token.\n * The token transport has no AuthProvider.\n */\nfunction isTokenRejection(\n outcome: Attempt,\n): outcome is ReceivedAttempt & { readonly authorization: AuthorizationContext } {\n return (\n outcome.kind === 'received' &&\n outcome.response.status === 401 &&\n outcome.errorCode === 'permission_denied' &&\n outcome.authorization !== undefined\n );\n}\n\n/** Everything about a request that stays the same across its attempts. */\ninterface PreparedRequest {\n readonly method: PaylovHttpMethod;\n /** The static identity, from {@link endpointName}. */\n readonly endpoint: string;\n readonly shape: ResponseShape;\n readonly url: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly body: string | undefined;\n readonly signal: AbortSignal | undefined;\n}\n\nfunction prepareRequest(\n origin: string,\n endpoint: Endpoint,\n options: RequestOptions,\n): PreparedRequest {\n const body = options.body === undefined ? undefined : JSON.stringify(options.body);\n return {\n method: endpoint.method,\n endpoint: endpointName(endpoint),\n shape: endpoint.shape,\n url: buildUrl(origin, endpoint.route, options),\n headers: requestHeaders(options.headers, body !== undefined),\n body,\n signal: options.signal,\n };\n}\n\n/** Rechecked after the synchronous request hook, which may close the client or abort. */\nfunction refusalAfterHook(\n lifecycle: ClientLifecycle | undefined,\n signal: AbortSignal | undefined,\n aborted: () => PaylovConnectionError,\n): PaylovClientClosedError | PaylovConnectionError | undefined {\n if (lifecycle?.closed === true) return clientClosedError();\n return signal?.aborted === true ? aborted() : undefined;\n}\n\nexport function createHttpClient(config: HttpClientConfig): HttpClient {\n const fetchImpl: FetchLike = config.fetch ?? ((input, init) => globalThis.fetch(input, init));\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const { auth, lifecycle, logger, origin } = config;\n const sleep = config.sleep ?? defaultSleep;\n const random = config.random ?? Math.random;\n\n /** Exponential backoff for the 1-based retry number, with jitter in `[0.5, 1]`. */\n function backoffMs(retryNumber: number): number {\n const step = BASE_DELAY_MS * 2 ** (retryNumber - 1);\n return step * (0.5 + random() * 0.5);\n }\n\n /**\n * One fetch and its body read under one deadline, so a gateway that sends headers and then\n * stalls cannot hang the call. Every failure becomes a connection error without a cause.\n */\n async function exchange(\n url: string,\n init: RequestInit,\n endpoint: string,\n callerSignal: AbortSignal | undefined,\n ): Promise<Exchange> {\n const timeout = AbortSignal.timeout(timeoutMs);\n const signal = callerSignal === undefined ? timeout : AbortSignal.any([timeout, callerSignal]);\n const failed = (): Failed => {\n const code = failureCode(callerSignal, timeout);\n const failure = new PaylovConnectionError({\n code,\n endpoint,\n isSent: true,\n timeoutMs: code === 'sdk_timeout' ? timeoutMs : undefined,\n });\n return { kind: 'failed', failure };\n };\n\n let response: Response;\n try {\n response = await raceAbort(fetchImpl(url, { ...init, signal }), signal);\n } catch {\n return failed();\n }\n // Redirects are disabled; a 3xx is final and its body is never read.\n if (response.status >= 300 && response.status < 400) {\n void response.body?.cancel().catch(noop);\n return { kind: 'received', response, body: undefined };\n }\n try {\n return { kind: 'received', response, body: await raceAbort(readJson(response), signal) };\n } catch {\n // Unless the caller aborted, a 429 stays a bodiless 429: never retried, and the token\n // manager still cools down.\n const keepsRateLimit = response.status === RATE_LIMITED && callerSignal?.aborted !== true;\n return keepsRateLimit ? { kind: 'received', response, body: undefined } : failed();\n }\n }\n\n /**\n * One authorized, logged attempt. Refusals before the fetch throw; fetch failures return.\n * `isSent` tells whether an earlier attempt of the call reached fetch.\n */\n async function sendAttempt(\n prepared: PreparedRequest,\n attempt: number,\n isSent: boolean,\n ): Promise<Attempt> {\n const { method, endpoint, signal } = prepared;\n const aborted = (): PaylovConnectionError => abortedError(endpoint, isSent);\n if (signal?.aborted === true) throw aborted();\n const authorization =\n auth === undefined ? undefined : await untilAborted(auth.authorize(), signal, aborted);\n lifecycle?.assertOpen();\n\n const closeAttempt = logAttempt(logger, method, endpoint, attempt);\n const refusal = refusalAfterHook(lifecycle, signal, aborted);\n if (refusal !== undefined) {\n closeAttempt(0, refusal.code);\n throw refusal;\n }\n\n const headers =\n authorization === undefined\n ? prepared.headers\n : { ...prepared.headers, authorization: authorization.header };\n const init: RequestInit = {\n method,\n redirect: 'manual',\n headers,\n ...(prepared.body !== undefined ? { body: prepared.body } : {}),\n };\n const outcome = await exchange(prepared.url, init, endpoint, signal);\n if (outcome.kind === 'failed') {\n closeAttempt(0, outcome.failure.code);\n return outcome;\n }\n const errorCode = envelopeErrorCode(outcome.body);\n closeAttempt(outcome.response.status, errorCode);\n return { ...outcome, errorCode, authorization };\n }\n\n async function request(endpoint: Endpoint, options: RequestOptions = {}): Promise<HttpResponse> {\n const prepared = prepareRequest(origin, endpoint, options);\n const { signal } = prepared;\n const abortedAfterSend = (): PaylovConnectionError => abortedError(prepared.endpoint, true);\n // Failure retries are GET-only: Paylov documents no idempotency, not even for DELETE.\n const retryable = endpoint.method === 'GET';\n let retriesUsed = 0;\n let replayed = false;\n let isSent = false;\n\n for (let attempt = 1; ; attempt += 1) {\n const outcome = await sendAttempt(prepared, attempt, isSent);\n isSent = true;\n if (!replayed && isTokenRejection(outcome)) {\n replayed = true;\n auth?.invalidate(outcome.authorization.generation);\n continue;\n }\n if (retryable && retriesUsed < MAX_RETRIES && isTransientFailure(outcome)) {\n retriesUsed += 1;\n await untilAborted(sleep(backoffMs(retriesUsed), signal), signal, abortedAfterSend);\n continue;\n }\n if (outcome.kind === 'failed') throw outcome.failure;\n\n const { response } = outcome;\n const context = { endpoint: prepared.endpoint, httpStatus: response.status };\n const retryAfter = response.headers.get('retry-after');\n const payload = normalizeResponse(outcome.body, context, prepared.shape, retryAfter);\n return { payload, context };\n }\n }\n\n return { request };\n}\n","/**\n * OAuth2 token management and revocation. Every `oauth2` snake_case wire name stays here and in\n * `fake.ts`.\n */\n\nimport {\n asNonEmptyString,\n asNonNegativeInteger,\n DecodeFailure,\n decodePayload,\n readFields,\n type Decoder,\n} from './decoding.js';\nimport { abortedError, isPaylovApiError, PaylovApiError, PaylovProtocolError } from './errors.js';\nimport { endpointName } from './http.js';\nimport { untilAborted, type ClientLifecycle } from './lifecycle.js';\nimport type { AuthorizationContext, AuthProvider, HttpClient, HttpResponse } from './types.js';\n\nexport const ENDPOINTS = {\n token: { method: 'POST', route: '/merchant/oauth2/token/', shape: 'flat' },\n revoke: { method: 'POST', route: '/merchant/oauth2/revoke/', shape: 'flat' },\n} as const;\nconst REVOKE_ENDPOINT = endpointName(ENDPOINTS.revoke);\nconst REFRESH_MARGIN_MS = 60_000;\n/** Used when a token-endpoint 429 carries no usable `Retry-After` delay. */\nconst DEFAULT_COOL_DOWN_SECONDS = 60;\n\ninterface TokenManagerConfig {\n /** A transport with neither an `AuthProvider` nor the lifecycle: revoke must run after close. */\n readonly http: HttpClient;\n readonly lifecycle: ClientLifecycle;\n readonly consumerKey: string;\n readonly consumerSecret: string;\n readonly username: string;\n readonly password: string;\n /** Test seam for deterministic expiry and cool-down; not in the public client config. */\n readonly now?: () => number;\n}\n\ninterface TokenSet {\n readonly accessToken: string;\n readonly refreshToken: string;\n /** Epoch milliseconds. */\n readonly accessExpiresAt: number;\n readonly refreshExpiresAt: number;\n}\n\nfunction ignore(): void {\n // A failed revocation or an abandoned wait still leaves the client closed.\n}\n\n/** Never surfaced: `close()` swallows it. */\nfunction abandonedClose(): Error {\n return abortedError(REVOKE_ENDPOINT, false);\n}\n\nfunction basicAuthHeader(consumerKey: string, consumerSecret: string): string {\n return `Basic ${Buffer.from(`${consumerKey}:${consumerSecret}`, 'utf8').toString('base64')}`;\n}\n\n/**\n * A lifetime in seconds as the epoch-ms deadline from `issuedAt`. No upper cap: 3600 / 2592000\n * are today's values, and a guessed cap would fail every login if Paylov changed them. Only a\n * zero or unsafe deadline is rejected.\n */\nfunction deadlineFrom(issuedAt: number): Decoder<number> {\n return (value, path) => {\n const lifetime = asNonNegativeInteger(value, path);\n const ms = issuedAt + lifetime * 1000;\n if (lifetime === 0 || !Number.isSafeInteger(ms)) throw new DecodeFailure(path);\n return ms;\n };\n}\n\n/** Failures name the field, never its value: the same body holds the tokens. */\nfunction decodeTokenSet(issuedAt: number): Decoder<TokenSet> {\n const asDeadline = deadlineFrom(issuedAt);\n return (value, path) => {\n const field = readFields(value, path);\n field('token_type', asNonEmptyString);\n return {\n accessToken: field('access_token', asNonEmptyString),\n refreshToken: field('refresh_token', asNonEmptyString),\n accessExpiresAt: field('expires_in', asDeadline),\n refreshExpiresAt: field('refresh_expires_in', asDeadline),\n };\n };\n}\n\n/**\n * Lazy, process-local, single-flight credential manager. It refreshes 60 s before expiry and\n * adopts each new pair at once, because a refresh rotates the refresh token.\n *\n * - A refresh rejected with `invalid_grant` falls back to one password grant. Nothing else does:\n * `invalid_client`, a 429 or a connection failure would fail the password grant too, and\n * failed password attempts lock the merchant account.\n * - An enveloped `invalid_grant` on the password grant is latched: every later `authorize()`\n * rethrows it without I/O. A bare 401/403 (a proxy) is not a credential verdict and does not.\n * - A token-endpoint HTTP 429 starts a cool-down, decoded envelope or not; until it ends\n * `authorize()` rethrows it without I/O.\n */\nexport class TokenManager implements AuthProvider {\n readonly #config: TokenManagerConfig;\n readonly #lifecycle: ClientLifecycle;\n readonly #now: () => number;\n\n #tokens: TokenSet | undefined;\n #generation = 0;\n #grant: Promise<AuthorizationContext> | undefined;\n #rejectedPassword: PaylovApiError | undefined;\n #coolDown:\n | { readonly until: number; readonly error: PaylovApiError | PaylovProtocolError }\n | undefined;\n #closing: Promise<void> | undefined;\n\n constructor(config: TokenManagerConfig) {\n this.#config = config;\n this.#lifecycle = config.lifecycle;\n this.#now = config.now ?? Date.now;\n }\n\n /** Callers race the shared grant against their own signal; this never takes one. */\n async authorize(): Promise<AuthorizationContext> {\n this.#lifecycle.assertOpen();\n if (this.#rejectedPassword !== undefined) throw this.#rejectedPassword;\n const coolDown = this.#coolDown;\n if (coolDown !== undefined && this.#now() < coolDown.until) throw coolDown.error;\n const tokens = this.#tokens;\n if (tokens !== undefined && this.#now() < tokens.accessExpiresAt - REFRESH_MARGIN_MS) {\n return this.#context(tokens);\n }\n return await this.#sharedGrant();\n }\n\n /** Expires only the access token of that generation, keeping the cheaper refresh grant. */\n invalidate(generation: number): void {\n const tokens = this.#tokens;\n if (tokens !== undefined && generation === this.#generation) {\n this.#tokens = { ...tokens, accessExpiresAt: 0 };\n }\n }\n\n /**\n * Closes the lifecycle, waits for an in-flight grant to settle, then revokes the newest access\n * token held. Concurrent calls share one revocation; the signal abandons only this wait. Never\n * rejects: the revoke attempt's logger events report a failed revocation.\n */\n async close(signal?: AbortSignal): Promise<void> {\n this.#closing ??= this.#closeAndRevoke();\n await untilAborted(this.#closing, signal, abandonedClose).catch(ignore);\n }\n\n #sharedGrant(): Promise<AuthorizationContext> {\n if (this.#grant !== undefined) return this.#grant;\n // Registered before the grant starts: its request hook may call close(), which must await it.\n const grant = Promise.withResolvers<AuthorizationContext>();\n this.#grant = grant.promise;\n // Cleared before waiters resume, on failure too, so one failed grant poisons no later caller.\n void this.#refreshOrLogin()\n .finally(() => {\n this.#grant = undefined;\n })\n .then(grant.resolve, grant.reject);\n return grant.promise;\n }\n\n async #refreshOrLogin(): Promise<AuthorizationContext> {\n const tokens = this.#tokens;\n if (tokens !== undefined && this.#now() < tokens.refreshExpiresAt) {\n try {\n return await this.#requestTokens({\n grant_type: 'refresh_token',\n refresh_token: tokens.refreshToken,\n });\n } catch (error) {\n if (!isPaylovApiError(error, 'invalid_grant')) throw error;\n this.#tokens = undefined;\n }\n }\n this.#lifecycle.assertOpen();\n try {\n return await this.#requestTokens({\n grant_type: 'password',\n username: this.#config.username,\n password: this.#config.password,\n });\n } catch (error) {\n if (isPaylovApiError(error, 'invalid_grant')) {\n this.#rejectedPassword = error;\n this.#tokens = undefined;\n }\n throw error;\n }\n }\n\n async #requestTokens(body: Readonly<Record<string, string>>): Promise<AuthorizationContext> {\n const { http, consumerKey, consumerSecret } = this.#config;\n let response: HttpResponse;\n try {\n response = await http.request(ENDPOINTS.token, {\n headers: { authorization: basicAuthHeader(consumerKey, consumerSecret) },\n body,\n });\n } catch (error) {\n const isRateLimited =\n (error instanceof PaylovApiError || error instanceof PaylovProtocolError) &&\n error.httpStatus === 429;\n if (isRateLimited) this.#startCoolDown(error);\n throw error;\n }\n const tokens = decodePayload(response, 'body', decodeTokenSet(this.#now()));\n // Held even after a close, so the revocation targets the newest token; never handed out.\n this.#tokens = tokens;\n this.#generation += 1;\n this.#lifecycle.assertOpen();\n return this.#context(tokens);\n }\n\n #startCoolDown(error: PaylovApiError | PaylovProtocolError): void {\n const retryAfterSeconds = error instanceof PaylovApiError ? error.retryAfterSeconds : undefined;\n const seconds = retryAfterSeconds ?? DEFAULT_COOL_DOWN_SECONDS;\n this.#coolDown = { until: this.#now() + seconds * 1000, error };\n }\n\n async #closeAndRevoke(): Promise<void> {\n this.#lifecycle.close();\n await this.#grant?.catch(() => undefined);\n const accessToken = this.#tokens?.accessToken;\n this.#tokens = undefined;\n if (accessToken === undefined) return;\n // Revoke is sent without `Authorization`, the only form that succeeded on every DEV day. A\n // failed revocation leaves the token valid until it expires, and the caller nothing to do;\n // its answer is not read.\n await this.#config.http\n .request(ENDPOINTS.revoke, { body: { token: accessToken } })\n .catch(ignore);\n }\n\n #context(tokens: TokenSet): AuthorizationContext {\n return { header: `Bearer ${tokens.accessToken}`, generation: this.#generation };\n }\n}\n","/** Constructor configuration shared by the network surfaces: origin, timeout, fetch, logger. */\n\nimport { configError } from './errors.js';\nimport { isRecord } from './decoding.js';\nimport type { HttpClientConfig } from './http.js';\nimport type { Params } from './params.js';\nimport type { FetchLike, PaylovLogger, PaylovTransportConfig } from './types.js';\n\n/** Node timers support at most a signed 32-bit millisecond delay. */\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\nfunction isFetchLike(value: unknown): value is FetchLike {\n return typeof value === 'function';\n}\n\n/** The caller's own logger object is kept, so class-based hooks keep their receiver. */\nfunction assertLogger(value: unknown): asserts value is PaylovLogger {\n if (!isRecord(value)) throw configError('logger must be an object', 'logger', 'type');\n for (const name of ['onRequest', 'onResponse']) {\n const hook = value[name];\n if (hook !== undefined && typeof hook !== 'function') {\n throw configError(`logger.${name} must be a function`, `logger.${name}`, 'type');\n }\n }\n}\n\n/** `timeoutMs`, `fetch` and `logger` from a configuration; only the options given. */\nfunction readTransportConfig(config: Params): PaylovTransportConfig {\n const timeoutMs = config.optionalInteger('timeoutMs', { min: 1, max: MAX_TIMEOUT_MS });\n const fetch = config.raw('fetch');\n if (fetch !== undefined && !isFetchLike(fetch)) {\n throw configError('fetch must be a function', 'fetch', 'type');\n }\n const logger = config.raw('logger');\n if (logger !== undefined) assertLogger(logger);\n return {\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n ...(fetch !== undefined ? { fetch } : {}),\n ...(logger !== undefined ? { logger } : {}),\n };\n}\n\n/**\n * A bare `https` origin. Every path starts with `/merchant/`, so a `.../merchant` base would\n * request `/merchant/merchant/...`; every call carries credentials, so cleartext is refused.\n * Credentials, a query or a fragment are checked on the text as given, before normalization.\n */\nfunction readHttpsOrigin(config: Params, key: string): string {\n const text = config.string(key).trim();\n const url = URL.parse(text);\n if (url === null || (url.protocol !== 'https:' && url.protocol !== 'http:')) {\n throw configError(`${key} must be an absolute https URL`, key, 'format');\n }\n if (url.protocol !== 'https:') throw configError(`${key} must use https`, key, 'format');\n if (url.username !== '' || url.password !== '' || /[?#]/.test(text)) {\n throw configError(`${key} must not include credentials, a query or a fragment`, key, 'format');\n }\n if (url.pathname !== '/') {\n throw configError(\n `${key} must be an origin without a path, e.g. https://dev.gw.paylov.uz`,\n key,\n 'format',\n );\n }\n return url.origin;\n}\n\n/** The transport of a network surface: its `baseUrl` origin and its transport options. */\nexport function readSurfaceTransport(config: Params): HttpClientConfig {\n return { origin: readHttpsOrigin(config, 'baseUrl'), ...readTransportConfig(config) };\n}\n","/**\n * Caller-input parsing. Malformed values become SDK input errors before any I/O; messages name\n * the method and field, never the value, because values carry credentials, card data and\n * personal data. Exceptions thrown by caller getters or proxies propagate unchanged.\n */\n\nimport { invalidAmount, invalidInput, PaylovInputError, type PaylovInputRule } from './errors.js';\nimport { isRecord, toJsonObject } from './decoding.js';\nimport { readTiyin, tiyinToWireSum } from './money.js';\nimport type { PaylovJsonObject } from './types.js';\n\n/** `unknown` when `L` lists every member of `T`, else `never`. */\ntype ListsEvery<T, L extends readonly T[]> = [Exclude<T, L[number]>] extends [never]\n ? unknown\n : never;\n\n/**\n * A closed set for `literal()` that lists every member of the public union `T`, so the two cannot\n * drift: a missing or foreign member fails to compile.\n *\n * @example\n * const DECISIONS = everyLiteral<WebhookDecisionWord>()(['accept', 'maintenance']);\n */\nexport function everyLiteral<T extends string | number>(): <const L extends readonly T[]>(\n values: L & ListsEvery<T, L>,\n) => L {\n return (values) => values;\n}\n\ninterface IntegerRange {\n readonly min: number;\n readonly max: number;\n}\n\n/** One method's parameters. Every getter validates the value and returns it. */\nexport interface Params {\n /** A non-blank string. */\n string(key: string): string;\n optionalString(key: string): string | undefined;\n integer(key: string): number;\n optionalInteger(key: string, range?: IntegerRange): number | undefined;\n optionalBoolean(key: string): boolean | undefined;\n literal<const T extends string | number>(key: string, values: readonly T[]): T;\n optionalLiteral<const T extends string | number>(\n key: string,\n values: readonly T[],\n ): T | undefined;\n /** An absolute `http(s)` URL. */\n url(key: string): string;\n optionalUrl(key: string): string | undefined;\n /** A JSON snapshot of that field only. */\n json(key: string): PaylovJsonObject;\n optionalJson(key: string): PaylovJsonObject | undefined;\n /** A record of strings whose every key and value matches `pattern`. */\n stringRecord(key: string, pattern: RegExp): Readonly<Record<string, string>>;\n array<T>(key: string, item: (params: Params, index: number) => T): readonly T[];\n optionalArray<T>(\n key: string,\n item: (params: Params, index: number) => T,\n ): readonly T[] | undefined;\n object<T>(key: string, read: (params: Params) => T): T;\n optionalObject<T>(key: string, read: (params: Params) => T): T | undefined;\n /** Exactly one of `keys` is present (not `undefined`); returns it. */\n exclusive<const K extends string>(keys: readonly K[]): K;\n /** A tiyin amount; failures are `sdk_invalid_amount`. */\n tiyin(key: string): number;\n optionalTiyin(key: string): number | undefined;\n /** A tiyin amount for an endpoint that takes whole SUM; returns the SUM to send. */\n tiyinAsWholeSum(key: string): number;\n /** The value as given, for rules that live with the caller (functions). */\n raw(key: string): unknown;\n}\n\ntype ParamsErrorCode = 'sdk_invalid_input' | 'sdk_config_error';\n\nclass ParamsReader implements Params {\n readonly #record: Readonly<Record<string, unknown>>;\n readonly #context: string;\n readonly #code: ParamsErrorCode;\n /** The field path of this object, e.g. `items[0]`; empty at the top level. */\n readonly #path: string;\n\n constructor(\n record: Readonly<Record<string, unknown>>,\n context: string,\n code: ParamsErrorCode,\n path: string,\n ) {\n this.#record = record;\n this.#context = context;\n this.#code = code;\n this.#path = path;\n }\n\n string(key: string): string {\n return this.#checkString(key, this.#required(key));\n }\n\n optionalString(key: string): string | undefined {\n const value = this.#read(key);\n return value === undefined ? undefined : this.#checkString(key, value);\n }\n\n integer(key: string): number {\n return this.#checkInteger(key, this.#required(key));\n }\n\n optionalInteger(key: string, range?: IntegerRange): number | undefined {\n const value = this.#read(key);\n return value === undefined ? undefined : this.#checkInteger(key, value, range);\n }\n\n optionalBoolean(key: string): boolean | undefined {\n const value = this.#read(key);\n return value === undefined ? undefined : this.#checkBoolean(key, value);\n }\n\n literal<const T extends string | number>(key: string, values: readonly T[]): T {\n return this.#checkLiteral(key, this.#required(key), values);\n }\n\n optionalLiteral<const T extends string | number>(\n key: string,\n values: readonly T[],\n ): T | undefined {\n const value = this.#read(key);\n return value === undefined ? undefined : this.#checkLiteral(key, value, values);\n }\n\n url(key: string): string {\n return this.#checkUrl(key, this.#required(key));\n }\n\n optionalUrl(key: string): string | undefined {\n const value = this.#read(key);\n return value === undefined ? undefined : this.#checkUrl(key, value);\n }\n\n json(key: string): PaylovJsonObject {\n return this.#checkJson(key, this.#required(key));\n }\n\n optionalJson(key: string): PaylovJsonObject | undefined {\n const value = this.#read(key);\n return value === undefined ? undefined : this.#checkJson(key, value);\n }\n\n stringRecord(key: string, pattern: RegExp): Readonly<Record<string, string>> {\n const value = this.#required(key);\n if (!isRecord(value)) throw this.#error(key, 'type', 'must be an object');\n const checked: [string, string][] = [];\n for (const [name, entry] of Object.entries(value)) {\n if (typeof entry !== 'string') throw this.#error(key, 'type', 'values must be strings');\n if (!(pattern.test(name) && pattern.test(entry))) {\n throw this.#error(key, 'format', 'has a key or value that is not allowed');\n }\n checked.push([name, entry]);\n }\n return Object.fromEntries(checked);\n }\n\n array<T>(key: string, item: (params: Params, index: number) => T): readonly T[] {\n return this.#checkArray(key, this.#required(key), item);\n }\n\n optionalArray<T>(\n key: string,\n item: (params: Params, index: number) => T,\n ): readonly T[] | undefined {\n const value = this.#read(key);\n return value === undefined ? undefined : this.#checkArray(key, value, item);\n }\n\n object<T>(key: string, read: (params: Params) => T): T {\n return read(this.#child(key, this.#required(key)));\n }\n\n optionalObject<T>(key: string, read: (params: Params) => T): T | undefined {\n const value = this.#read(key);\n return value === undefined ? undefined : read(this.#child(key, value));\n }\n\n exclusive<const K extends string>(keys: readonly K[]): K {\n const present = keys.filter((key) => this.#read(key) !== undefined);\n const [only] = present;\n if (only === undefined || present.length > 1) {\n const scope = this.#path === '' ? this.#context : `${this.#context}: ${this.#path}`;\n throw new PaylovInputError({\n code: this.#code,\n message: `${scope} requires exactly one of ${keys.join(', ')}`,\n field: this.#path === '' ? undefined : this.#path,\n rule: 'exclusive',\n });\n }\n return only;\n }\n\n tiyin(key: string): number {\n const field = this.#field(key);\n return readTiyin(this.#read(key), field, `${this.#context}: ${field}`);\n }\n\n optionalTiyin(key: string): number | undefined {\n return this.#read(key) === undefined ? undefined : this.tiyin(key);\n }\n\n tiyinAsWholeSum(key: string): number {\n const sum = tiyinToWireSum(this.tiyin(key));\n if (sum === undefined) {\n const field = this.#field(key);\n throw invalidAmount(\n `${this.#context}: ${field} must be a whole number of SUM (a multiple of 100)`,\n field,\n 'format',\n );\n }\n return sum;\n }\n\n raw(key: string): unknown {\n return this.#read(key);\n }\n\n #field(key: string): string {\n return this.#path === '' ? key : `${this.#path}.${key}`;\n }\n\n #error(key: string, rule: PaylovInputRule, text: string): PaylovInputError {\n const field = this.#field(key);\n return new PaylovInputError({\n code: this.#code,\n message: `${this.#context}: ${field} ${text}`,\n field,\n rule,\n });\n }\n\n /** Own properties only: an inherited value is not a parameter the caller passed. */\n #read(key: string): unknown {\n return Object.hasOwn(this.#record, key) ? this.#record[key] : undefined;\n }\n\n #required(key: string): unknown {\n const value = this.#read(key);\n if (value === undefined) throw this.#error(key, 'required', 'is required');\n return value;\n }\n\n #checkString(key: string, value: unknown): string {\n if (typeof value !== 'string') throw this.#error(key, 'type', 'must be a string');\n if (value.trim() === '') throw this.#error(key, 'required', 'must not be blank');\n return value;\n }\n\n #checkInteger(key: string, value: unknown, range?: IntegerRange): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value)) {\n throw this.#error(key, 'type', 'must be a safe integer');\n }\n if (range !== undefined && (value < range.min || value > range.max)) {\n throw this.#error(key, 'range', `must be between ${range.min} and ${range.max}`);\n }\n return value;\n }\n\n #checkBoolean(key: string, value: unknown): boolean {\n if (typeof value !== 'boolean') throw this.#error(key, 'type', 'must be a boolean');\n return value;\n }\n\n #checkLiteral<const T extends string | number>(\n key: string,\n value: unknown,\n values: readonly T[],\n ): T {\n const match = values.find((candidate) => candidate === value);\n if (match === undefined) {\n throw this.#error(key, 'format', `must be one of ${values.map(String).join(', ')}`);\n }\n return match;\n }\n\n #checkUrl(key: string, value: unknown): string {\n const text = this.#checkString(key, value);\n const protocol = URL.parse(text)?.protocol;\n if (protocol !== 'http:' && protocol !== 'https:') {\n throw this.#error(key, 'format', 'must be an absolute http(s) URL');\n }\n return text;\n }\n\n /** Serializer exceptions are discarded: a cycle or a BigInt says nothing the caller needs. */\n #checkJson(key: string, value: unknown): PaylovJsonObject {\n if (!isRecord(value)) throw this.#error(key, 'type', 'must be a JSON object');\n let snapshot: unknown;\n try {\n snapshot = JSON.parse(JSON.stringify(value));\n } catch {\n throw this.#error(key, 'type', 'must be JSON-serializable');\n }\n const json = isRecord(snapshot) ? toJsonObject(snapshot) : undefined;\n if (json === undefined) throw this.#error(key, 'type', 'must be a JSON object');\n return json;\n }\n\n #checkArray<T>(\n key: string,\n value: unknown,\n item: (params: Params, index: number) => T,\n ): readonly T[] {\n if (!Array.isArray(value)) throw this.#error(key, 'type', 'must be an array');\n const items: readonly unknown[] = value;\n // `Array.from` visits holes, so a sparse entry fails the object check like `undefined`.\n return Array.from(items, (element, index) =>\n item(this.#child(`${key}[${index}]`, element), index),\n );\n }\n\n #child(key: string, value: unknown): Params {\n if (!isRecord(value)) throw this.#error(key, 'type', 'must be an object');\n return new ParamsReader(value, this.#context, this.#code, this.#field(key));\n }\n}\n\nfunction readObject(value: unknown, context: string, code: ParamsErrorCode): Params {\n if (!isRecord(value)) {\n const message = `${context} expects an object`;\n throw new PaylovInputError({ code, message, field: undefined, rule: 'type' });\n }\n return new ParamsReader(value, context, code, '');\n}\n\n/** Method parameters; failures are `sdk_invalid_input` (`sdk_invalid_amount` for amounts). */\nexport function readParams(value: unknown, method: string): Params {\n return readObject(value, method, 'sdk_invalid_input');\n}\n\n/** Constructor configuration; failures are `sdk_config_error`. */\nexport function readConfig(value: unknown, surface: string): Params {\n return readObject(value, surface, 'sdk_config_error');\n}\n\n/** The `signal` of a method's `PaylovCallOptions`; anything but an `AbortSignal` is rejected. */\nexport function readCallSignal(options: unknown, method: string): AbortSignal | undefined {\n if (options === undefined) return undefined;\n const signal = readParams(options, `${method} options`).raw('signal');\n if (signal === undefined || signal instanceof AbortSignal) return signal;\n throw invalidInput(`${method} options: signal must be an AbortSignal`, 'signal', 'type');\n}\n","/**\n * The plumbing every endpoint method shares: read the call's input, send to a declared endpoint,\n * decode, and map the endpoint's miss code to a value.\n */\n\nimport { decodePayload, type Decoder } from './decoding.js';\nimport type { PaylovKnownErrorCode } from './errorCodes.js';\nimport { isPaylovApiError } from './errors.js';\nimport { readCallSignal, readParams, type Params } from './params.js';\nimport type { Endpoint, HttpClient, RequestOptions } from './types.js';\n\ninterface CallInput {\n readonly input: Params;\n readonly signal: AbortSignal | undefined;\n}\n\n/**\n * A method's parameters and the signal of its call options, both validated before any I/O.\n *\n * @example\n * const method = 'holds.release';\n * const { input, signal } = readCall(params, options, method);\n */\nexport function readCall(params: unknown, options: unknown, method: string): CallInput {\n return { input: readParams(params, method), signal: readCallSignal(options, method) };\n}\n\n/** The `{name}` placeholders of a path template. */\ntype PathParams<T extends string> = T extends `${string}{${infer Name}}${infer Rest}`\n ? Name | PathParams<Rest>\n : never;\n\n/**\n * The identifier values a route template needs; a static route takes none. Name each\n * placeholder after the SDK parameter: encoding failures name it.\n */\ntype PathValues<Route extends string> = [PathParams<Route>] extends [never]\n ? { readonly path?: undefined }\n : { readonly path: Readonly<Record<PathParams<Route>, string>> };\n\n/** What one call adds to its endpoint: values only, never the route, method or shape. */\nexport type EndpointRequest<E extends Endpoint> = Pick<\n RequestOptions,\n 'query' | 'body' | 'signal'\n> &\n PathValues<E['route']>;\n\n/**\n * Sends one request to `endpoint` and decodes its payload. Logs and errors carry the route\n * template, never the identifiers. Decode failures are reported under `result` for the enveloped\n * shapes and under `body` for the others.\n *\n * @example\n * return send(http, ENDPOINTS.get, { path: { cardId }, signal }, decodeFetchedCard);\n */\nexport async function send<E extends Endpoint, T>(\n http: HttpClient,\n endpoint: E,\n request: EndpointRequest<E>,\n decode: Decoder<T>,\n): Promise<T> {\n const response = await http.request(endpoint, request);\n return decodePayload(response, endpoint.shape === 'envelope' ? 'result' : 'body', decode);\n}\n\n/**\n * Resolves to `fallback` when `call` rejects with the endpoint's `miss` code; every other\n * failure, a decode failure included, propagates.\n *\n * @example\n * return orOnMiss(send(http, ENDPOINTS.get, { query, signal }, decodeHold), ENDPOINTS.get, null);\n */\nexport async function orOnMiss<T, F>(\n call: Promise<T>,\n endpoint: { readonly miss: PaylovKnownErrorCode },\n fallback: F,\n): Promise<T | F> {\n try {\n return await call;\n } catch (error) {\n if (isPaylovApiError(error, endpoint.miss)) return fallback;\n throw error;\n }\n}\n","// The optional `sms` object of PAN binding and payment without registration. Paylov lists the\n// field without a description [OPEN Q29], so the SDK checks only types and forwards it unchanged.\n\nimport type { Params } from '../core/params.js';\n\n/**\n * Optional OTP SMS settings, forwarded to Paylov unchanged. Paylov does not document what they\n * change; its test environment behaved the same with and without them.\n */\nexport interface OtpSmsSettings {\n readonly hash?: string;\n /** An integer; Paylov answers `validation_error` otherwise. */\n readonly templateId?: number;\n}\n\n/** The wire form; undefined keys are left out of the JSON body. */\ninterface WireOtpSms {\n readonly hash: string | undefined;\n readonly templateId: number | undefined;\n}\n\n/** Reads `sms`; use with `params.optionalObject`. */\nexport function readOtpSms(sms: Params): WireOtpSms {\n return { hash: sms.optionalString('hash'), templateId: sms.optionalInteger('templateId') };\n}\n","import {\n arrayOf,\n asBoolean,\n asIsoDateTime,\n asMaskedPan,\n asString,\n asTiyin,\n type Decoder,\n fieldOf,\n nullable,\n nullish,\n readFields,\n} from '../core/decoding.js';\nimport type { Card, CardBindLinkCreated, CardBindSession, PanBindingStarted } from './types.js';\n\ntype CardState = Pick<Card, 'isActive' | 'processingStatus' | 'isSmsEnabled'>;\n\nconst decodeFlatStatus: Decoder<CardState> = (value, path) => {\n const status = readFields(value, path);\n return {\n isActive: status('is_active', asBoolean),\n processingStatus: status('status_message', asString),\n isSmsEnabled: status('sms_info', asBoolean),\n };\n};\n\n/**\n * Each endpoint has exactly one status layout and never falls back to the other, so a layout\n * change surfaces as `sdk_malformed_response`. An error inside the confirm status is an inactive\n * status: `is_active: false` with the reason in `status_message`.\n */\nfunction cardDecoder(decodeStatus: Decoder<CardState>): Decoder<Card> {\n return (value, path) => {\n const card = readFields(value, path);\n const cardName = card('cardName', nullable(asString));\n return {\n cardId: card('cardId', asString),\n userId: card('userId', asString),\n holderName: card('owner', asString),\n cardName: cardName === '' ? null : cardName,\n maskedCardNumber: card('number', asMaskedPan),\n balanceTiyin: card('balance', asTiyin),\n bankId: card('bankId', asString),\n bankName: card('bankName', nullish(asString)),\n vendor: card('vendor', asString),\n processing: card('processing', asString),\n ...card('status', decodeStatus),\n };\n };\n}\n\n/** Confirm and the bind session carry a flat `status`. */\nconst decodeFlatCard: Decoder<Card> = cardDecoder(decodeFlatStatus);\n/** `getCard` and `getAllUserCards` nest it as `status.result`. */\nconst decodeNestedCard: Decoder<Card> = cardDecoder(fieldOf('result', decodeFlatStatus));\n\nexport const decodeConfirmedCard: Decoder<Card> = fieldOf('card', decodeFlatCard);\nexport const decodeFetchedCard: Decoder<Card> = fieldOf('card', decodeNestedCard);\nexport const decodeCardList: Decoder<readonly Card[]> = fieldOf('cards', arrayOf(decodeNestedCard));\n\nexport const decodePanBindingStarted: Decoder<PanBindingStarted> = (value, path) => {\n const result = readFields(value, path);\n return {\n cardId: result('cid', asString),\n // The OTP is already sent, so no mask format may fail the call.\n otpSentPhone: result('otpSentPhone', asString),\n };\n};\n\nexport const decodeBindLinkCreated: Decoder<CardBindLinkCreated> = (value, path) => {\n const result = readFields(value, path);\n return {\n token: result('token', asString),\n // The host differs between DEV and the docs: passed through unchanged.\n bindUrl: result('bindUrl', asString),\n expiresAt: result('expiresAt', asIsoDateTime),\n };\n};\n\n/** Only a `confirmed` session has a card; any other state's `card` is not read. */\nexport const decodeBindSession: Decoder<CardBindSession> = (value, path) => {\n const result = readFields(value, path);\n const status = result('state', asString);\n if (status !== 'confirmed') return { isBound: false, status, card: null };\n return { isBound: true, status, card: result('card', decodeFlatCard) };\n};\n\n/** `{match: boolean}`, the documented answer of the phone check. */\nexport const decodeMatch: Decoder<boolean> = fieldOf('match', asBoolean);\n\n/** Delete answers `result: true`; the envelope alone signals its success. */\nexport const decodeDeleted: Decoder<void> = () => undefined;\n","import { readCall, send } from '../core/call.js';\nimport type { HttpClient, PaylovCallOptions } from '../core/types.js';\nimport { readOtpSms } from '../shared/otpSms.js';\nimport {\n decodeBindLinkCreated,\n decodeBindSession,\n decodeCardList,\n decodeConfirmedCard,\n decodeFetchedCard,\n decodeMatch,\n decodePanBindingStarted,\n decodeDeleted,\n} from './decoders.js';\nimport type {\n Card,\n CardBindLinkCreated,\n CardBindSession,\n CheckCardPhoneParams,\n ConfirmPanBindingParams,\n CreateBindLinkParams,\n DeleteCardParams,\n GetBindSessionParams,\n GetCardParams,\n ListCardsParams,\n PanBindingStarted,\n StartPanBindingParams,\n} from './types.js';\n\nexport const ENDPOINTS = {\n createBindLink: {\n method: 'POST',\n route: '/merchant/userCard/createBindLink/',\n shape: 'envelope',\n },\n getBindSession: {\n method: 'GET',\n route: '/merchant/userCard/bindSession/{token}/status/',\n shape: 'envelope',\n },\n startPanBinding: {\n method: 'POST',\n route: '/merchant/userCard/createUserCard/',\n shape: 'envelope',\n },\n confirmPanBinding: {\n method: 'POST',\n route: '/merchant/userCard/confirmUserCardCreate/',\n shape: 'envelope',\n },\n get: { method: 'GET', route: '/merchant/userCard/getCard/{cardId}/', shape: 'envelope' },\n list: {\n method: 'GET',\n route: '/merchant/userCard/getAllUserCards/',\n shape: 'envelope',\n },\n delete: {\n method: 'DELETE',\n route: '/merchant/userCard/deleteUserCard/',\n shape: 'envelope',\n },\n checkPhone: {\n method: 'POST',\n route: '/merchant/userCard/checkPhoneMatch/',\n shape: 'envelope',\n },\n} as const;\n\n/** The `paylov.cards` namespace. Nothing here moves money. */\nexport interface CardsResource {\n /**\n * Starts a Card Bind session, the preferred way to bind a card: the cardholder enters the card\n * and the SMS code on a Paylov page, so the card number never reaches your servers. Open\n * `bindUrl` in a webview; the result arrives through the `card.bind` webhook or\n * {@link CardsResource.getBindSession}. A link binds one card and expires after about 20\n * minutes. Each call creates a new link.\n *\n * @throws {@link PaylovApiError} `permission_denied` when Card Bind is not enabled for the\n * merchant.\n *\n * @example\n * const link = await paylov.cards.createBindLink({\n * userId: 'user-42',\n * returnUrl: 'https://app.example/wallet/cards',\n * });\n * await bindSessions.save({ userId: 'user-42', token: link.token, expiresAt: link.expiresAt });\n * openWebView(link.bindUrl);\n */\n createBindLink(\n params: CreateBindLinkParams,\n options?: PaylovCallOptions,\n ): Promise<CardBindLinkCreated>;\n\n /**\n * Reads a Card Bind session, to recover a bind whose webhook never arrived (Paylov does not\n * retry it). `isBound` is `true` exactly when the card is attached; `card` is the card as it was\n * bound and stays even after the card is deleted, so read {@link CardsResource.get} for its\n * current state. The token stays out of logger events.\n *\n * @throws {@link PaylovApiError} `link_expired` (expired or unknown token; a link that bound a\n * card also answers it once expired, so check `cards.list` before offering a new link),\n * `link_already_used` (a card was already bound with this link: never offer a new one).\n *\n * @example\n * const session = await paylov.cards.getBindSession({ token: storedBindToken });\n * if (session.isBound) await userCards.saveOnce(storedBindToken, session.card.cardId);\n */\n getBindSession(\n params: GetBindSessionParams,\n options?: PaylovCallOptions,\n ): Promise<CardBindSession>;\n\n /**\n * PCI scope: takes a full card number server-side; the SDK keeps it out of logger events and\n * errors. Prefer {@link CardsResource.createBindLink}, which keeps it off your servers.\n *\n * Registers a card for a user and makes its processing center (Uzcard or Humo) send an OTP to\n * the phone linked to the card; pass the returned `cardId` and the code to\n * {@link CardsResource.confirmPanBinding}. Without SMS notifications on the card no OTP\n * arrives. While the last OTP is still valid, starting again for the same user and card fails\n * with `otp_code_already_sent`; after it expires, a new start sends a new OTP for the same\n * `cardId`.\n *\n * Recovery: when the outcome is unknown, start again; an unconfirmed card is never charged.\n *\n * @throws {@link PaylovApiError} `card_not_found` (unknown or unsupported card number),\n * `card_not_match` (wrong expiry), `phone_not_match`, `card_exists` (already bound to this\n * user), `otp_code_already_sent`, `card_not_active`, `sms_not_active`, `card_has_no_phone`.\n *\n * @example\n * const started = await paylov.cards.startPanBinding({\n * userId: 'user-42',\n * cardNumber: panFromSecureInput,\n * cardExpiry: expiryFromSecureInput, // YYMM\n * });\n * showOtpPrompt(`Uzcard/Humo sent a code to ${started.otpSentPhone}`);\n */\n startPanBinding(\n params: StartPanBindingParams,\n options?: PaylovCallOptions,\n ): Promise<PanBindingStarted>;\n\n /**\n * Confirms a card from {@link CardsResource.startPanBinding} with the cardholder's OTP and\n * returns the bound card, which can still read `isActive: false` with the reason in\n * `processingStatus`: check it before charging. A wrong code, a PINFL mismatch or invalid input\n * leaves the OTP usable, so the cardholder can retry. On Paylov's test environment an OTP lasts\n * about 90 seconds, and the fourth wrong OTP blocks the card for about five minutes, for\n * bindings and payments alike: `card_is_blocked`, with the rest of the block in\n * `retryAfterSeconds`. Stop prompting before that.\n *\n * Recovery: when the outcome is unknown (`isPaylovOutcomeUnknown`), read\n * `cards.get({ cardId })`. A repeated confirm answering `card_is_already_activated` means the\n * card is already confirmed.\n *\n * @throws {@link PaylovApiError} `invalid_otp`, `otp_expired`, `card_is_blocked`, `try_new_otp`,\n * `too_many_attempts`, `pinfl_not_match`, `card_is_already_activated`, `card_not_found`.\n *\n * @example\n * const card = await paylov.cards.confirmPanBinding({\n * cardId: started.cardId,\n * otp: otpFromCardholder,\n * });\n * await userCards.save('user-42', card.cardId);\n */\n confirmPanBinding(params: ConfirmPanBindingParams, options?: PaylovCallOptions): Promise<Card>;\n\n /**\n * Reads one card with its balance and status refreshed from the processing center.\n *\n * @throws {@link PaylovApiError} `card_not_found` (unknown or deleted),\n * `card_not_found_in_processing_center`, `card_is_blocked`,\n * `card_is_blocked_in_processing_center`, `balance_refresh_error`.\n *\n * @example\n * const card = await paylov.cards.get({ cardId: savedCardId });\n * if (!card.isActive) askForAnotherCard(card.processingStatus);\n */\n get(params: GetCardParams, options?: PaylovCallOptions): Promise<Card>;\n\n /**\n * Lists a merchant user's bound cards; an unknown user has none. One malformed card fails the\n * whole call.\n *\n * @example\n * const cards = await paylov.cards.list({ userId: 'user-42' });\n * const usable = cards.filter((card) => card.isActive);\n */\n list(params: ListCardsParams, options?: PaylovCallOptions): Promise<readonly Card[]>;\n\n /**\n * Unbinds a card. A repeated delete answers `card_not_found`, which means the card is already\n * gone. `cards.list` and `cards.get` can still return it for a short time.\n *\n * @throws {@link PaylovApiError} `card_not_found`.\n *\n * @example\n * await paylov.cards.delete({ cardId: savedCardId });\n */\n delete(params: DeleteCardParams, options?: PaylovCallOptions): Promise<void>;\n\n /**\n * Answers whether a phone number is the one linked to a card, as Paylov's `match` reports it.\n *\n * @throws {@link PaylovApiError} `card_not_found`, `permission_denied` (the check is not enabled\n * for the merchant), `phone_not_match`: Paylov documents a mismatch as `false`, yet the\n * development gateway answers this code for every phone, the card's own included, so it does not\n * prove a mismatch.\n *\n * @example\n * const linked = await paylov.cards.checkPhone({ cardId: savedCardId, phoneNumber: verifiedPhone });\n * if (!linked) flagForReview(savedCardId);\n */\n checkPhone(params: CheckCardPhoneParams, options?: PaylovCallOptions): Promise<boolean>;\n}\n\nexport function createCardsResource(http: HttpClient): CardsResource {\n return {\n async createBindLink(params, options) {\n const method = 'cards.createBindLink';\n const { input, signal } = readCall(params, options, method);\n const body = { userId: input.string('userId'), returnUrl: input.optionalUrl('returnUrl') };\n return send(http, ENDPOINTS.createBindLink, { body, signal }, decodeBindLinkCreated);\n },\n\n async getBindSession(params, options) {\n const method = 'cards.getBindSession';\n const { input, signal } = readCall(params, options, method);\n const path = { token: input.string('token') };\n return send(http, ENDPOINTS.getBindSession, { path, signal }, decodeBindSession);\n },\n\n async startPanBinding(params, options) {\n const method = 'cards.startPanBinding';\n const { input, signal } = readCall(params, options, method);\n const body = {\n userId: input.string('userId'),\n cardNumber: input.string('cardNumber'),\n expireDate: input.string('cardExpiry'),\n phoneNumber: input.optionalString('phoneNumber'),\n sms: input.optionalObject('sms', readOtpSms),\n };\n return send(http, ENDPOINTS.startPanBinding, { body, signal }, decodePanBindingStarted);\n },\n\n async confirmPanBinding(params, options) {\n const method = 'cards.confirmPanBinding';\n const { input, signal } = readCall(params, options, method);\n const body = {\n cardId: input.string('cardId'),\n otp: input.string('otp'),\n cardName: input.optionalString('cardName'),\n pinfl: input.optionalString('pinfl'),\n };\n return send(http, ENDPOINTS.confirmPanBinding, { body, signal }, decodeConfirmedCard);\n },\n\n async get(params, options) {\n const method = 'cards.get';\n const { input, signal } = readCall(params, options, method);\n const path = { cardId: input.string('cardId') };\n return send(http, ENDPOINTS.get, { path, signal }, decodeFetchedCard);\n },\n\n async list(params, options) {\n const method = 'cards.list';\n const { input, signal } = readCall(params, options, method);\n const query = { userId: input.string('userId') };\n return send(http, ENDPOINTS.list, { query, signal }, decodeCardList);\n },\n\n async delete(params, options) {\n const method = 'cards.delete';\n const { input, signal } = readCall(params, options, method);\n const query = { userCardId: input.string('cardId') };\n return send(http, ENDPOINTS.delete, { query, signal }, decodeDeleted);\n },\n\n async checkPhone(params, options) {\n const method = 'cards.checkPhone';\n const { input, signal } = readCall(params, options, method);\n // The docs name the field `phone`; the gateway requires `phoneNumber`.\n const body = {\n cardId: input.string('cardId'),\n phoneNumber: input.string('phoneNumber'),\n };\n return send(http, ENDPOINTS.checkPhone, { body, signal }, decodeMatch);\n },\n };\n}\n","/**\n * Fiscal receipt items, shared by fiscalization and splits. Prices and discounts are tiyin both\n * here and on the wire.\n */\n\nimport type { Params } from '../core/params.js';\n\n/** Fields every receipt item carries besides its `tin` or `pinfl`. */\nexport interface FiscalReceiptItemBase {\n /** Item name as it appears on the fiscal receipt. */\n readonly title: string;\n /**\n * Integer tiyin, the price of one unit before discount. The SDK assumes a line totals\n * `(priceTiyin - discountTiyin) * count`; Paylov documents no formula.\n */\n readonly priceTiyin: number;\n /** Integer tiyin off each unit; Paylov allows at most `priceTiyin`. */\n readonly discountTiyin?: number;\n /** Integer quantity; Paylov answers `validation_error` below 1. */\n readonly count: number;\n /** IKPU classifier code of the item. */\n readonly code: string;\n /** Integer VAT percentage. */\n readonly vatPercent: number;\n /** Package-type code. */\n readonly packageCode: string;\n}\n\n/** One receipt line, carrying exactly one of `tin` or `pinfl`. */\nexport type FiscalReceiptItem =\n | (FiscalReceiptItemBase & {\n /** Taxpayer id (INN) of the commitent; Paylov documents 9 digits. */\n readonly tin: string;\n // `?: undefined`, not `?: never`, so items built by spread still type-check under\n // `exactOptionalPropertyTypes`.\n readonly pinfl?: undefined;\n })\n | (FiscalReceiptItemBase & {\n /**\n * Personal identification number; Paylov documents 14 digits. Personal data; never logged or\n * quoted.\n */\n readonly pinfl: string;\n readonly tin?: undefined;\n });\n\n/** The wire form of one item; an undefined `discount` is left out of the JSON body. */\nexport interface WireReceiptItem {\n readonly title: string;\n readonly price: number;\n readonly discount: number | undefined;\n readonly count: number;\n readonly code: string;\n readonly vat_percent: number;\n readonly package_code: string;\n readonly tin?: string;\n readonly pinfl?: string;\n}\n\n/** Reads one item; use with `params.array` or `params.optionalArray`. */\nexport function readReceiptItem(item: Params): WireReceiptItem {\n const base = {\n title: item.string('title'),\n price: item.tiyin('priceTiyin'),\n discount: item.optionalTiyin('discountTiyin'),\n count: item.integer('count'),\n code: item.string('code'),\n vat_percent: item.integer('vatPercent'),\n package_code: item.string('packageCode'),\n };\n return item.exclusive(['tin', 'pinfl']) === 'tin'\n ? { ...base, tin: item.string('tin') }\n : { ...base, pinfl: item.string('pinfl') };\n}\n","/** Transaction shapes shared by the features that create, look up or read transactions. */\n\nimport { asString, fieldOf, type Decoder } from '../core/decoding.js';\nimport type { Params } from '../core/params.js';\n\n/** The gateway transaction an operation created or acted on. */\nexport interface TransactionReference {\n /** Gateway transaction id. */\n readonly transactionId: string;\n}\n\n/**\n * Decodes a status string, replacing each wire spelling in `statusByWire` with the SDK's word.\n * Other values pass through unchanged.\n */\nexport function statusDecoder(statusByWire: ReadonlyMap<string, string>): Decoder<string> {\n return (value, path) => {\n const status = asString(value, path);\n return statusByWire.get(status) ?? status;\n };\n}\n\n/** Decodes `{ transactionId }`. */\nexport const decodeTransactionReference: Decoder<TransactionReference> = (value, path) => ({\n transactionId: fieldOf('transactionId', asString)(value, path),\n});\n\n/**\n * Exactly one of the gateway `transactionId` or the merchant's own `externalId`.\n *\n * @example\n * const byId: TransactionLookup = { transactionId };\n * const byOrder: TransactionLookup = { externalId: `order-${order.id}` };\n */\nexport type TransactionLookup =\n // `?: undefined`, not `?: never`, so lookups built by spread still type-check under\n // `exactOptionalPropertyTypes`.\n | { readonly transactionId: string; readonly externalId?: undefined }\n | { readonly externalId: string; readonly transactionId?: undefined };\n\n/**\n * Reads a {@link TransactionLookup}: a `transactionId` or an `externalId`. The result carries\n * only the key given, ready to send.\n */\nexport function readTransactionLookup(input: Params): TransactionLookup {\n return input.exclusive(['transactionId', 'externalId']) === 'transactionId'\n ? { transactionId: input.string('transactionId') }\n : { externalId: input.string('externalId') };\n}\n","import {\n arrayOf,\n asBoolean,\n asNonNegativeInteger,\n asString,\n fieldOf,\n DecodeFailure,\n readFields,\n type Decoder,\n} from '../core/decoding.js';\nimport type {\n ActivityTypeCheck,\n FiscalReceipt,\n FiscalReceiptRegistered,\n FiscalReceiptRefunded,\n} from './types.js';\n\nconst decodeOfdReceipt: Decoder<FiscalReceiptRegistered> = (value, path) => {\n const field = readFields(value, path);\n return {\n receiptId: field('receiptId', asNonNegativeInteger),\n receiptUrl: field('receiptUrl', asString),\n terminalId: field('terminalId', asString),\n fiscalSign: field('fiscalSign', asString),\n };\n};\n\nexport const decodeFiscalReceiptRegistered: Decoder<FiscalReceiptRegistered> = fieldOf(\n 'ofd',\n decodeOfdReceipt,\n);\n\n/**\n * A known transaction without a receipt answers `success: false` with `receiptUrl` and\n * `isRefund` null and the other receipt keys absent (W c274); an unknown id is an API error.\n */\nexport const decodeReceiptLookup: Decoder<FiscalReceipt | null> = (value, path) => {\n const field = readFields(value, path);\n if (!field('success', asBoolean)) return null;\n return {\n ...decodeOfdReceipt(value, path),\n isRefund: field('isRefund', asBoolean),\n };\n};\n\nexport const decodeReceiptRefunded: Decoder<FiscalReceiptRefunded> = (value, path) => {\n const field = readFields(value, path);\n return {\n refund: field('ofd', fieldOf('refund', decodeOfdReceipt)),\n sale: field('sale', decodeOfdReceipt),\n };\n};\n\n/** `result.error` sits beside `success` and is ignored; only `success: true` is a success. */\nexport const decodeAttachConfirmation: Decoder<void> = (value, path) => {\n if (!fieldOf('success', asBoolean)(value, path)) {\n throw new DecodeFailure(`${path}.success`);\n }\n};\n\ninterface ActivityTypeDetails {\n /** The high-income answer; `undefined` when `success` is the whole answer. */\n readonly status: boolean | undefined;\n readonly activityNames: readonly string[];\n}\n\n/**\n * `data` is `null` (self-employed), the number 200 (a negative entrepreneur check, discarded) or\n * the high-income object, whose `status` is the answer while `success` only says the check ran.\n */\nconst decodeActivityTypeDetails: Decoder<ActivityTypeDetails> = (value, path) => {\n if (value === null || value === undefined || typeof value === 'number') {\n return { status: undefined, activityNames: [] };\n }\n const field = readFields(value, path);\n return {\n status: field('status', asBoolean),\n activityNames: field('activityNames', arrayOf(asString)),\n };\n};\n\n/** The upstream `reason` is free text from the tax service and is never read. */\nexport const decodeActivityTypeCheck: Decoder<ActivityTypeCheck> = (value, path) => {\n const field = readFields(value, path);\n const success = field('success', asBoolean);\n const { status = true, activityNames } = field('data', decodeActivityTypeDetails);\n return { isConfirmed: success && status, activityNames };\n};\n","import { orOnMiss, readCall, send } from '../core/call.js';\nimport { everyLiteral } from '../core/params.js';\nimport type { HttpClient, PaylovCallOptions } from '../core/types.js';\nimport { readReceiptItem } from '../shared/receiptItems.js';\nimport { readTransactionLookup } from '../shared/transactions.js';\nimport {\n decodeActivityTypeCheck,\n decodeAttachConfirmation,\n decodeReceiptLookup,\n decodeReceiptRefunded,\n decodeFiscalReceiptRegistered,\n} from './decoders.js';\nimport type {\n ActivityTypeCheck,\n AttachFiscalReceiptParams,\n CheckActivityTypeParams,\n FiscalActivityType,\n FiscalReceipt,\n FiscalReceiptRegistered,\n FiscalReceiptRefunded,\n GetFiscalReceiptParams,\n RefundFiscalReceiptParams,\n RegisterFiscalReceiptParams,\n} from './types.js';\n\nexport const ENDPOINTS = {\n registerReceipt: {\n method: 'POST',\n route: '/merchant/fiscalization/register/',\n shape: 'envelope',\n },\n getReceipt: {\n method: 'GET',\n route: '/merchant/fiscalization/status/',\n shape: 'envelope',\n // Paylov answers it only for an unknown `externalId`; an unknown `transactionId` is\n // `transaction_not_found`.\n miss: 'ofd_check_not_found',\n },\n attachReceipt: {\n method: 'POST',\n route: '/merchant/fiscalization/set-receipt/',\n shape: 'envelope',\n },\n refundReceipt: { method: 'POST', route: '/merchant/fiscalization/refund/', shape: 'envelope' },\n checkActivityType: {\n method: 'POST',\n route: '/merchant/fiscalization/activity-types/',\n shape: 'envelope',\n },\n} as const;\n\nexport const ACTIVITY_TYPES: readonly FiscalActivityType[] = everyLiteral<FiscalActivityType>()([\n 'individual_entrepreneur',\n 'self_employed',\n 'high_income',\n]);\n\nexport const WIRE_ACTIVITY_TYPES: Readonly<Record<FiscalActivityType, number>> = {\n individual_entrepreneur: 1,\n self_employed: 2,\n high_income: 3,\n};\n\n/**\n * The `paylov.fiscalization` namespace: OFD fiscal receipts and tax-service activity checks.\n * Every method except `getReceipt` needs fiscalization enabled for the merchant; otherwise it\n * fails with `permission_denied`.\n */\nexport interface FiscalizationResource {\n /**\n * Has Paylov register a fiscal receipt with the OFD: for a paid card payment by\n * `transactionId`, or for a cash sale by `externalId` and `phoneNumber`. Moves no money. Item\n * prices are integer tiyin; the lines, each `(priceTiyin - discountTiyin) * count`, must total\n * the transaction amount.\n *\n * Recovery: when `isPaylovOutcomeUnknown(error)`, read `getReceipt` before registering again;\n * `null` means nothing is registered yet. `ofd_check_already_generated` on a repeated call\n * means a receipt exists.\n *\n * @throws {@link PaylovApiError} `ofd_check_already_generated`,\n * `receipt_not_available_for_operation` (not paid), `invalid_amount` (item total),\n * `ofd_commitent_or_subcommission_not_active` (an item's TIN or PINFL has no active OFD\n * contract), `ofd_error`, `fiscal_receipt_not_generated`, `permission_denied`.\n *\n * @example\n * const receipt = await paylov.fiscalization.registerReceipt({\n * transactionId,\n * items: [\n * {\n * title: 'Consultation',\n * priceTiyin: 25_000_000,\n * count: 1,\n * code: ikpuCode,\n * vatPercent: 12,\n * packageCode,\n * tin: commitentTin,\n * },\n * ],\n * });\n * await receipts.save(transactionId, receipt.receiptId, receipt.receiptUrl);\n */\n registerReceipt(\n params: RegisterFiscalReceiptParams,\n options?: PaylovCallOptions,\n ): Promise<FiscalReceiptRegistered>;\n\n /**\n * Reads the receipt of a card payment by `transactionId`, or of a cash sale by the `externalId`\n * it was registered with. Resolves `null` when no receipt is found for the transaction or the\n * `externalId`; the OFD may register one later, so `null` is an observation, not proof. Moves\n * no money and works without fiscalization enabled.\n *\n * @throws {@link PaylovApiError} `transaction_not_found` for an unknown `transactionId`.\n *\n * @example\n * const receipt = await paylov.fiscalization.getReceipt({ transactionId, isRefund: false });\n * if (receipt !== null) await receipts.save(transactionId, receipt.receiptId, receipt.receiptUrl);\n */\n getReceipt(\n params: GetFiscalReceiptParams,\n options?: PaylovCallOptions,\n ): Promise<FiscalReceipt | null>;\n\n /**\n * Attaches a receipt you fiscalized yourself to a paid Paylov transaction; nothing is sent to\n * the OFD. Moves no money. Needs fiscalization in client-side mode, otherwise\n * `permission_denied`.\n *\n * Recovery: when `isPaylovOutcomeUnknown(error)`, read `getReceipt` before attaching again;\n * `ofd_check_already_generated` on a repeated call means a receipt is attached.\n *\n * @throws {@link PaylovApiError} `ofd_check_already_generated`, `field_not_valid` (`fields`\n * names the wire field `transactionId`, `dateTime` for `issuedAtRaw`, or `qrCodeUrl` for\n * `receiptUrl`), `external_id_already_exists`,\n * `transaction_not_found`, `receipt_not_available_for_operation`,\n * `ofd_too_many_requests_for_this_receipt`, `permission_denied`.\n *\n * @example\n * await paylov.fiscalization.attachReceipt({\n * transactionId,\n * terminalId: ofdReceipt.terminalId,\n * issuedAtRaw: '20260915143025',\n * fiscalSign: ofdReceipt.fiscalSign,\n * receiptUrl: ofdReceipt.receiptUrl,\n * receiptId: ofdReceipt.receiptId,\n * });\n */\n attachReceipt(params: AttachFiscalReceiptParams, options?: PaylovCallOptions): Promise<void>;\n\n /**\n * Registers an OFD refund receipt that reverses a sale receipt. Moves no money: refund a card\n * payment with `payments.refund`, which Paylov documents also cancels its fiscalization. For a\n * card payment, call this only when `getReceipt({ transactionId, isRefund: true })` shows no\n * refund receipt after `payments.refund`.\n *\n * Recovery: store each `receiptId` with its `transactionId` or `externalId`; when\n * `isPaylovOutcomeUnknown(error)`, read `getReceipt({ ..., isRefund: true })` before refunding\n * again.\n *\n * @throws {@link PaylovApiError} `ofd_check_not_found`, `ofd_error`, `permission_denied`.\n *\n * @example\n * const { refund } = await paylov.fiscalization.refundReceipt({ receiptId: sale.receiptId });\n * await receipts.saveRefund(sale.externalId, refund.receiptId, refund.receiptUrl);\n */\n refundReceipt(\n params: RefundFiscalReceiptParams,\n options?: PaylovCallOptions,\n ): Promise<FiscalReceiptRefunded>;\n\n /**\n * Asks the tax service whether a person has an activity type, before fiscalizing on their\n * behalf. Moves no money. A negative answer may arrive as `PaylovApiError`\n * `gateway_not_working` instead of `isConfirmed: false`; treat that as unconfirmed.\n *\n * @throws {@link PaylovApiError} `gateway_not_working`, `permission_denied`.\n *\n * @example\n * const check = await paylov.fiscalization.checkActivityType({\n * pinfl: sellerPinfl,\n * activityType: 'self_employed',\n * });\n * if (!check.isConfirmed) await sellers.flagForReview(sellerId);\n */\n checkActivityType(\n params: CheckActivityTypeParams,\n options?: PaylovCallOptions,\n ): Promise<ActivityTypeCheck>;\n}\n\nexport function createFiscalizationResource(http: HttpClient): FiscalizationResource {\n return {\n async registerReceipt(params, options) {\n const method = 'fiscalization.registerReceipt';\n const { input, signal } = readCall(params, options, method);\n const lookup = readTransactionLookup(input);\n const sale =\n lookup.transactionId === undefined\n ? { ...lookup, phoneNumber: input.string('phoneNumber') }\n : lookup;\n const body = { ...sale, items: input.array('items', readReceiptItem) };\n return send(http, ENDPOINTS.registerReceipt, { body, signal }, decodeFiscalReceiptRegistered);\n },\n\n async getReceipt(params, options) {\n const method = 'fiscalization.getReceipt';\n const { input, signal } = readCall(params, options, method);\n const query = {\n ...readTransactionLookup(input),\n refunded: input.optionalBoolean('isRefund'),\n };\n const receipt = send(http, ENDPOINTS.getReceipt, { query, signal }, decodeReceiptLookup);\n return orOnMiss(receipt, ENDPOINTS.getReceipt, null);\n },\n\n async attachReceipt(params, options) {\n const method = 'fiscalization.attachReceipt';\n const { input, signal } = readCall(params, options, method);\n const body = {\n transactionId: input.string('transactionId'),\n externalId: input.optionalString('externalId'),\n terminalId: input.string('terminalId'),\n dateTime: input.string('issuedAtRaw'),\n fiscalSign: input.string('fiscalSign'),\n qrCodeUrl: input.string('receiptUrl'),\n receiptId: input.integer('receiptId'),\n };\n return send(http, ENDPOINTS.attachReceipt, { body, signal }, decodeAttachConfirmation);\n },\n\n async refundReceipt(params, options) {\n const method = 'fiscalization.refundReceipt';\n const { input, signal } = readCall(params, options, method);\n const body = { receiptId: input.integer('receiptId') };\n return send(http, ENDPOINTS.refundReceipt, { body, signal }, decodeReceiptRefunded);\n },\n\n async checkActivityType(params, options) {\n const method = 'fiscalization.checkActivityType';\n const { input, signal } = readCall(params, options, method);\n const body = {\n pinfl: input.string('pinfl'),\n activityType: WIRE_ACTIVITY_TYPES[input.literal('activityType', ACTIVITY_TYPES)],\n };\n return send(http, ENDPOINTS.checkActivityType, { body, signal }, decodeActivityTypeCheck);\n },\n };\n}\n","import {\n arrayOf,\n asLiteral,\n asNonNegativeInteger,\n asString,\n fieldOf,\n nullable,\n readFields,\n type Decoder,\n} from '../core/decoding.js';\nimport type { Bank } from './types.js';\n\nexport const decodeStatus: Decoder<void> = (value, path) => {\n fieldOf('status', asLiteral('ok'))(value, path);\n};\n\nconst decodeBank: Decoder<Bank> = (value, path) => {\n const field = readFields(value, path);\n return {\n bankId: String(field('id', asNonNegativeInteger)),\n name: field('name', asString),\n officialName: field('official_name', nullable(asString)),\n };\n};\n\nexport const decodeBanks: Decoder<readonly Bank[]> = arrayOf(decodeBank);\n","import { send } from '../core/call.js';\nimport { readCallSignal } from '../core/params.js';\nimport type { HttpClient, PaylovCallOptions } from '../core/types.js';\nimport { decodeBanks, decodeStatus } from './decoders.js';\nimport type { Bank } from './types.js';\n\nexport const ENDPOINTS = {\n getStatus: { method: 'GET', route: '/merchant/status/', shape: 'flat' },\n listBanks: { method: 'GET', route: '/merchant/bankList/', shape: 'array' },\n} as const;\n\n/** The `paylov.gateway` namespace. */\nexport interface GatewayResource {\n /**\n * Checks that the gateway answers (`GET /merchant/status/`). It sends no token and Paylov\n * validates none, so it proves neither the credentials nor the account: use it as a liveness\n * probe only. Resolves for `{\"status\":\"ok\"}`; any other answer throws.\n *\n * @throws {@link PaylovConnectionError} when the gateway is unreachable or times out.\n * @throws {@link PaylovProtocolError} `sdk_malformed_response` for any other success body.\n *\n * @example\n * try {\n * await paylov.gateway.getStatus({ signal: AbortSignal.timeout(5_000) });\n * return { paylov: 'up' };\n * } catch {\n * return { paylov: 'down' };\n * }\n */\n getStatus(options?: PaylovCallOptions): Promise<void>;\n\n /**\n * Lists the banks Paylov knows (`GET /merchant/bankList/`). Each `bankId` is a string that\n * matches a card's `bankId`.\n *\n * @throws {@link PaylovApiError} `invalid_grant` when the credentials are rejected.\n *\n * @example\n * const banks = await paylov.gateway.listBanks();\n * const bankNames = new Map(banks.map((bank) => [bank.bankId, bank.officialName ?? bank.name]));\n */\n listBanks(options?: PaylovCallOptions): Promise<readonly Bank[]>;\n}\n\n/** `anonymousHttp` sends no `Authorization`: `status/` needs none and must not trigger a login. */\nexport function createGatewayResource(\n http: HttpClient,\n anonymousHttp: HttpClient,\n): GatewayResource {\n return {\n async getStatus(options) {\n const signal = readCallSignal(options, 'gateway.getStatus');\n return send(anonymousHttp, ENDPOINTS.getStatus, { signal }, decodeStatus);\n },\n\n async listBanks(options) {\n const signal = readCallSignal(options, 'gateway.listBanks');\n return send(http, ENDPOINTS.listBanks, { signal }, decodeBanks);\n },\n };\n}\n","import {\n asString,\n asTiyinFromSum,\n asUtcDateTime,\n nullable,\n readFields,\n type Decoder,\n} from '../core/decoding.js';\nimport { decodeTransactionReference, statusDecoder } from '../shared/transactions.js';\nimport type { Hold, HoldCaptured, HoldStatus } from './types.js';\n\n/** The SDK's word for each wire status it renames. */\nexport const HOLD_STATUS_BY_WIRE: ReadonlyMap<string, HoldStatus> = new Map([\n ['hold', 'held'],\n ['paid', 'captured'],\n ['cancelled', 'released'],\n]);\n\nconst decodeHoldStatus = statusDecoder(HOLD_STATUS_BY_WIRE);\n\n/** `hold/charge/` result; `payedAt` is UTC. */\nexport const decodeHoldCaptured: Decoder<HoldCaptured> = (value, path) => {\n const field = readFields(value, path);\n return {\n ...decodeTransactionReference(value, path),\n cardId: field('cardId', asString),\n capturedAt: field('payedAt', asUtcDateTime),\n };\n};\n\n/** `hold/status/` result; `amount` is whole SUM, `payedAt` and `cancelTime` are UTC. */\nexport const decodeHold: Decoder<Hold> = (value, path) => {\n const field = readFields(value, path);\n return {\n transactionId: field('transactionId', asString),\n status: field('status', decodeHoldStatus),\n amountTiyin: field('amount', asTiyinFromSum),\n capturedAt: field('payedAt', nullable(asUtcDateTime)),\n releasedAt: field('cancelTime', nullable(asUtcDateTime)),\n serviceId: field('serviceId', asString),\n };\n};\n","import { orOnMiss, readCall, send } from '../core/call.js';\nimport type { HttpClient, PaylovCallOptions } from '../core/types.js';\nimport {\n decodeTransactionReference,\n readTransactionLookup,\n type TransactionReference,\n} from '../shared/transactions.js';\nimport { decodeHold, decodeHoldCaptured } from './decoders.js';\nimport type {\n CaptureHoldParams,\n CreateHoldParams,\n GetHoldParams,\n Hold,\n HoldCaptured,\n ReleaseHoldParams,\n} from './types.js';\n\nexport const ENDPOINTS = {\n create: { method: 'POST', route: '/merchant/payment/hold/create/', shape: 'envelope' },\n capture: { method: 'POST', route: '/merchant/payment/hold/charge/', shape: 'envelope' },\n release: { method: 'POST', route: '/merchant/payment/hold/dismiss/', shape: 'envelope' },\n get: {\n method: 'GET',\n route: '/merchant/payment/hold/status/',\n shape: 'envelope',\n miss: 'transaction_not_found',\n },\n} as const;\n\n/**\n * The `paylov.holds` namespace: reserve funds on a bound card with `create`, then either\n * `capture` them once or `release` them before the hold runs out. Paylov sends no hold webhook,\n * so reconcile open holds by polling `get`.\n */\nexport interface HoldsResource {\n /**\n * Reserves `amountTiyin` on a bound card for `durationMinutes`. Money is reserved, not\n * captured.\n *\n * Recovery: when `isPaylovOutcomeUnknown(error)`, the hold may exist. Read\n * `holds.get({ externalId })`; a hold found is the result. `null` is not proof that the\n * create did not run: read again after a delay, then call `create` again with the same\n * `externalId`. A repeat answers `external_id_already_exists` when the hold exists.\n *\n * @throws {@link PaylovApiError} `insufficient_funds` or another card decline,\n * `external_id_already_exists`, `card_not_found` (unknown or deleted card), `service_not_found`.\n *\n * @example\n * const hold = await paylov.holds.create({\n * userId: booking.customerId,\n * cardId: booking.cardId,\n * amountTiyin: 150_000, // 1 500.00 SUM\n * durationMinutes: 24 * 60,\n * externalId: `booking-${booking.id}`,\n * });\n * await bookings.saveHold(booking.id, hold.transactionId);\n */\n create(params: CreateHoldParams, options?: PaylovCallOptions): Promise<TransactionReference>;\n\n /**\n * Captures a hold: **this moves money.** Capture is single-use. An amount below the held\n * amount is a partial capture and ends the hold: the remainder can be neither captured nor\n * released afterwards. Paylov does not document what happens to it; the SDK assumes Paylov and\n * the card's bank return it to the cardholder. After the hold's duration runs out, capture fails\n * with `hold_time_expired`, and Paylov's test environment then reported the hold `released`.\n *\n * Recovery: when `isPaylovOutcomeUnknown(error)`, read `holds.get({ transactionId })` before\n * anything else: `captured` means the capture happened and `amountTiyin` is the captured amount.\n * Never capture again blindly; a repeat answers `transaction_not_available_for_payment` once\n * the hold is captured or released.\n *\n * @throws {@link PaylovApiError} `invalid_amount` (more than the held amount),\n * `transaction_not_available_for_payment` (already captured, released, or not a hold),\n * `hold_time_expired`, `transaction_not_found`.\n *\n * @example\n * const captured = await paylov.holds.capture({\n * transactionId: booking.holdTransactionId,\n * amountTiyin: 150_000,\n * });\n * await bookings.markPaid(booking.id, captured.capturedAt);\n */\n capture(params: CaptureHoldParams, options?: PaylovCallOptions): Promise<HoldCaptured>;\n\n /**\n * Releases an uncaptured hold in full; moves no money. It cannot undo a capture: after one,\n * only `payments.refund` remains, and Paylov's test environment refuses it for a captured hold\n * with `processing_error`. Release every hold you will not capture, also after its duration runs\n * out. Release is the only documented way to free a hold, so the SDK reads `hold_not_found`\n * then as nothing left to release.\n *\n * Recovery: when `isPaylovOutcomeUnknown(error)`, read `holds.get({ transactionId })`: status\n * `released` means the release took effect.\n *\n * @throws {@link PaylovApiError} `hold_not_found` (already released, captured, or expired).\n *\n * @example\n * await paylov.holds.release({ transactionId: booking.holdTransactionId });\n */\n release(params: ReleaseHoldParams, options?: PaylovCallOptions): Promise<TransactionReference>;\n\n /**\n * Looks a hold up by exactly one of `transactionId` or `externalId`; `null` when the gateway\n * knows no such hold (`transaction_not_found`). A miss right after an ambiguous `create` is not\n * proof: read again after a delay. An expired hold can still read `held`: track its deadline\n * (creation time plus `durationMinutes`) yourself.\n *\n * @example\n * const hold = await paylov.holds.get({ externalId: `booking-${booking.id}` });\n * if (hold === null) await retryCreateLater(booking.id);\n * else if (hold.status === 'captured') await bookings.markPaid(booking.id, hold.capturedAt);\n */\n get(params: GetHoldParams, options?: PaylovCallOptions): Promise<Hold | null>;\n}\n\nexport function createHoldsResource(http: HttpClient): HoldsResource {\n return {\n async create(params, options) {\n const method = 'holds.create';\n const { input, signal } = readCall(params, options, method);\n const body = {\n userId: input.string('userId'),\n cardId: input.string('cardId'),\n amount: input.tiyinAsWholeSum('amountTiyin'),\n time: input.integer('durationMinutes'),\n externalId: input.string('externalId'),\n account: input.optionalJson('account'),\n serviceId: input.optionalString('serviceId'),\n };\n return send(http, ENDPOINTS.create, { body, signal }, decodeTransactionReference);\n },\n\n async capture(params, options) {\n const method = 'holds.capture';\n const { input, signal } = readCall(params, options, method);\n const body = {\n transactionId: input.string('transactionId'),\n amount: input.tiyinAsWholeSum('amountTiyin'),\n };\n return send(http, ENDPOINTS.capture, { body, signal }, decodeHoldCaptured);\n },\n\n async release(params, options) {\n const method = 'holds.release';\n const { input, signal } = readCall(params, options, method);\n const body = { transactionId: input.string('transactionId') };\n return send(http, ENDPOINTS.release, { body, signal }, decodeTransactionReference);\n },\n\n async get(params, options) {\n const method = 'holds.get';\n const { input, signal } = readCall(params, options, method);\n // Which key wins when both are sent is unobserved, so the SDK never sends both.\n const query = readTransactionLookup(input);\n const hold = send(http, ENDPOINTS.get, { query, signal }, decodeHold);\n return orOnMiss(hold, ENDPOINTS.get, null);\n },\n };\n}\n","import { asString, asTashkentDateTime, readFields, type Decoder } from '../core/decoding.js';\nimport { decodeTransactionReference } from '../shared/transactions.js';\nimport type { PanPaymentStarted, PaymentRefunded } from './types.js';\n\n/** `payment/cancel/` result. */\nexport const decodePaymentRefunded: Decoder<PaymentRefunded> = (value, path) => {\n const field = readFields(value, path);\n return {\n ...decodeTransactionReference(value, path),\n refundedAt: field('cancelTime', asTashkentDateTime),\n };\n};\n\n/** `paymentWithoutRegistration/` result; the echoed `extId` and the `code` are withheld. */\nexport const decodePanPaymentStarted: Decoder<PanPaymentStarted> = (value, path) => {\n const field = readFields(value, path);\n return {\n ...decodeTransactionReference(value, path),\n otpSentPhone: field('otpSentPhone', asString),\n };\n};\n","import { readCall, send } from '../core/call.js';\nimport type { HttpClient, PaylovCallOptions } from '../core/types.js';\nimport { readOtpSms } from '../shared/otpSms.js';\nimport { decodeTransactionReference, type TransactionReference } from '../shared/transactions.js';\nimport { decodePanPaymentStarted, decodePaymentRefunded } from './decoders.js';\nimport type {\n ConfirmPanPaymentParams,\n CreatePaymentParams,\n PanPaymentStarted,\n PaymentRefunded,\n PayPaymentParams,\n RefundPaymentParams,\n StartPanPaymentParams,\n} from './types.js';\n\nexport const ENDPOINTS = {\n create: { method: 'POST', route: '/merchant/receipts/create/', shape: 'envelope' },\n pay: { method: 'POST', route: '/merchant/receipts/pay/', shape: 'envelope' },\n refund: { method: 'POST', route: '/merchant/payment/cancel/', shape: 'envelope' },\n startPanPayment: {\n method: 'POST',\n route: '/merchant/paymentWithoutRegistration/',\n shape: 'envelope',\n },\n confirmPanPayment: { method: 'POST', route: '/merchant/confirmPayment/', shape: 'envelope' },\n} as const;\n\n/** The `paylov.payments` namespace. */\nexport interface PaymentsResource {\n /**\n * Creates an unpaid payment transaction for a saved card. **No money moves**; charge it with\n * {@link PaymentsResource.pay}.\n *\n * Each call creates a new transaction, and an unpaid one is never charged, so after any\n * failure just call again.\n *\n * @throws {@link PaylovApiError} `field_not_valid` (an amount outside the gateway's range),\n * `validation_error`.\n *\n * @example\n * const { transactionId } = await paylov.payments.create({\n * amountTiyin: 2_500_000, // 25 000.00 SUM\n * account: { order_id: 'A-1024' },\n * userId: 'user-42',\n * });\n */\n create(params: CreatePaymentParams, options?: PaylovCallOptions): Promise<TransactionReference>;\n\n /**\n * Charges a saved card for a transaction from {@link PaymentsResource.create}, for the amount\n * fixed there. **Moves money**; no OTP is involved. A declined charge leaves the transaction\n * either `failed`, with the code in `declineCode`, which can never be paid again, or still\n * `created`, which another card can pay.\n *\n * Recovery: after a decline or when `isPaylovOutcomeUnknown(error)`, read\n * `paylov.transactions.get` before acting again; never repeat `pay` blindly. A repeated `pay`\n * of a paid transaction fails with `transaction_already_payed`, of a `failed` one with\n * `transaction_not_available_for_payment`. Paylov does not document whether a pay can still land\n * while the status reads `created`; the SDK assumes a status that stays `created` across\n * repeated reads means the pay did not take effect: pay again with the same `transactionId`,\n * never a new transaction.\n *\n * @throws {@link PaylovApiError} `transaction_already_payed`,\n * `transaction_not_available_for_payment` (refunded, failed or not payable),\n * `card_is_not_for_this_check` (the card belongs to another user), `card_not_found`, and\n * declines such as `insufficient_funds` and `processing_error`.\n *\n * @example\n * await paylov.payments.pay({ transactionId, cardId, userId: 'user-42' });\n */\n pay(params: PayPaymentParams, options?: PaylovCallOptions): Promise<TransactionReference>;\n\n /**\n * Refunds a paid transaction **in full**; there is no partial refund. **Moves money back** to\n * the card and also cancels the payment's fiscal (OFD) receipt. Release an uncaptured hold with\n * `holds.release` instead.\n *\n * Paylov may refuse an API refund for some payment kinds: checkout and PAN payments, and on\n * Paylov's test environment captured holds. Then refund from the Paylov business panel or\n * through Paylov support, and confirm with `paylov.transactions.get`.\n *\n * Recovery: when `isPaylovOutcomeUnknown(error)`, read `paylov.transactions.get`: a refunded\n * transaction reads status `refunded` with `cancelledAt`. A repeated refund fails with\n * `transaction_not_available_for_cancel`.\n *\n * @throws {@link PaylovApiError} `transaction_not_available_for_cancel` (already refunded, never\n * paid, or a checkout or PAN payment), `processing_error` (a captured hold on Paylov's test\n * environment), `transaction_not_found`, `permission_denied`.\n *\n * @example\n * const { refundedAt } = await paylov.payments.refund({ transactionId });\n */\n refund(params: RefundPaymentParams, options?: PaylovCallOptions): Promise<PaymentRefunded>;\n\n /**\n * PCI scope: takes a full card number server-side; the SDK keeps it and the expiry out of\n * logger events and errors.\n *\n * Starts a one-off payment by card number, without binding the card. **No money moves yet**:\n * the card's processing center (Uzcard or Humo, not Paylov) sends an OTP by SMS to the phone\n * linked to the card. Finish with {@link PaymentsResource.confirmPanPayment}. A card without\n * SMS notifications never receives the OTP.\n *\n * Recovery: each call creates a new transaction and an unconfirmed one is never charged, so\n * after any failure start again.\n *\n * @throws {@link PaylovApiError} `card_not_found` (wrong number or expiry), `invalid_amount`.\n *\n * @example\n * const started = await paylov.payments.startPanPayment({\n * cardNumber: cardNumberFromSecureInput,\n * cardExpiry: cardExpiryFromSecureInput, // YYMM\n * amountTiyin: 120_000, // 1 200.00 SUM\n * account: { order_id: 'A-1025' },\n * });\n * showOtpPrompt(`Uzcard/Humo sent a code to ${started.otpSentPhone}`);\n */\n startPanPayment(\n params: StartPanPaymentParams,\n options?: PaylovCallOptions,\n ): Promise<PanPaymentStarted>;\n\n /**\n * Confirms a payment from {@link PaymentsResource.startPanPayment} with the cardholder's OTP.\n * **Moves money.** A wrong OTP fails with `invalid_otp` and can be retried with the right one.\n * On Paylov's test environment an OTP lasts about 90 seconds, and the fourth wrong OTP blocks\n * the card for about five minutes, for payments and bindings alike: `card_is_blocked`, with the\n * rest of the block in `retryAfterSeconds`. Stop prompting before that.\n *\n * Recovery: when `isPaylovOutcomeUnknown(error)`, read `paylov.transactions.get` before acting\n * again. A repeated confirm of a paid transaction fails with `otp_expired`, the same code as a\n * really expired OTP, so only the read tells them apart.\n *\n * @throws {@link PaylovApiError} `invalid_otp`, `otp_expired`, `card_is_blocked`,\n * `transaction_not_found`, and declines such as `insufficient_funds`.\n *\n * @example\n * await paylov.payments.confirmPanPayment({\n * transactionId: started.transactionId,\n * otp: otpFromUser,\n * });\n */\n confirmPanPayment(\n params: ConfirmPanPaymentParams,\n options?: PaylovCallOptions,\n ): Promise<TransactionReference>;\n}\n\nexport function createPaymentsResource(http: HttpClient): PaymentsResource {\n return {\n async create(params, options) {\n const method = 'payments.create';\n const { input, signal } = readCall(params, options, method);\n const body = {\n amount: input.tiyinAsWholeSum('amountTiyin'),\n // The gateway requires the key.\n account: input.optionalJson('account') ?? {},\n userId: input.optionalString('userId'),\n };\n return send(http, ENDPOINTS.create, { body, signal }, decodeTransactionReference);\n },\n\n async pay(params, options) {\n const method = 'payments.pay';\n const { input, signal } = readCall(params, options, method);\n const body = {\n transactionId: input.string('transactionId'),\n cardId: input.string('cardId'),\n userId: input.string('userId'),\n };\n return send(http, ENDPOINTS.pay, { body, signal }, decodeTransactionReference);\n },\n\n async refund(params, options) {\n const method = 'payments.refund';\n const { input, signal } = readCall(params, options, method);\n const body = { transactionId: input.string('transactionId') };\n return send(http, ENDPOINTS.refund, { body, signal }, decodePaymentRefunded);\n },\n\n async startPanPayment(params, options) {\n const method = 'payments.startPanPayment';\n const { input, signal } = readCall(params, options, method);\n // `extId` is never sent: the gateway echoes it but does not store it, so it cannot be\n // looked up afterwards.\n const body = {\n cardNumber: input.string('cardNumber'),\n expireDate: input.string('cardExpiry'),\n amount: input.tiyinAsWholeSum('amountTiyin'),\n // The gateway requires the key.\n account: input.optionalJson('account') ?? {},\n sms: input.optionalObject('sms', readOtpSms),\n };\n return send(http, ENDPOINTS.startPanPayment, { body, signal }, decodePanPaymentStarted);\n },\n\n async confirmPanPayment(params, options) {\n const method = 'payments.confirmPanPayment';\n const { input, signal } = readCall(params, options, method);\n const body = {\n transactionId: input.string('transactionId'),\n otp: input.string('otp'),\n sms: input.optionalObject('sms', readOtpSms),\n };\n return send(http, ENDPOINTS.confirmPanPayment, { body, signal }, decodeTransactionReference);\n },\n };\n}\n","import { arrayOf, asString, asTiyin, readFields, type Decoder } from '../core/decoding.js';\nimport type { SplitShare } from './types.js';\n\n/** One `splitPayment/status/` entry; `amount` is tiyin. */\nconst decodeSplitShare: Decoder<SplitShare> = (value, path) => {\n const field = readFields(value, path);\n return {\n recipientId: field('recipientId', asString),\n amountTiyin: field('amount', asTiyin),\n status: field('status', asString),\n createdAtRaw: field('createdAt', asString),\n };\n};\n\n/** `splitPayment/status/` result: one entry per recipient. */\nexport const decodeSplitShares: Decoder<readonly SplitShare[]> = arrayOf(decodeSplitShare);\n","import { readCall, send } from '../core/call.js';\nimport type { Params } from '../core/params.js';\nimport type { HttpClient, PaylovCallOptions } from '../core/types.js';\nimport { readReceiptItem, type WireReceiptItem } from '../shared/receiptItems.js';\nimport { decodeTransactionReference, type TransactionReference } from '../shared/transactions.js';\nimport { decodeSplitShares } from './decoders.js';\nimport type { CreateSplitParams, GetSplitParams, SplitShare } from './types.js';\n\nexport const ENDPOINTS = {\n create: { method: 'POST', route: '/merchant/splitPayment/', shape: 'envelope' },\n get: { method: 'GET', route: '/merchant/splitPayment/status/', shape: 'envelope' },\n} as const;\n\n/**\n * The `paylov.splits` namespace: divides a paid transaction among recipients. Both methods need\n * split payments enabled for the merchant; otherwise they fail with `permission_denied`.\n */\nexport interface SplitsResource {\n /**\n * Splits a paid transaction: each recipient receives a sub-transaction with its amount. Moves\n * money to the recipients. Amounts are integer tiyin and must add up to the transaction amount.\n * A recipient's `items` start OFD fiscalization of its share in the background.\n *\n * Recovery: when `isPaylovOutcomeUnknown(error)`, read `splits.get` before splitting again;\n * `split_already_done` on a repeated call means the split exists.\n *\n * @throws {@link PaylovApiError} `split_already_done`, `transaction_not_found`,\n * `invalid_amount` (amounts do not add up), `recipient_not_found`,\n * `ofd_commitent_or_subcommission_not_active`, `permission_denied`.\n *\n * @example\n * await paylov.splits.create({\n * transactionId,\n * recipients: [\n * { recipientId: platformRecipientId, amountTiyin: 150_000 },\n * { recipientId: sellerRecipientId, amountTiyin: 850_000 },\n * ],\n * });\n */\n create(params: CreateSplitParams, options?: PaylovCallOptions): Promise<TransactionReference>;\n\n /**\n * Reads every recipient's share of a split transaction. Moves no money.\n *\n * Unlike `holds.get`, a miss throws instead of returning `null`: Paylov documents\n * `split_not_found` for a transaction without a split, but that code has not been observed.\n *\n * @throws {@link PaylovApiError} `split_not_found`, `transaction_not_found`,\n * `permission_denied`.\n *\n * @example\n * const shares = await paylov.splits.get({ transactionId });\n * const unpaid = shares.filter((share) => share.status !== 'paid');\n */\n get(params: GetSplitParams, options?: PaylovCallOptions): Promise<readonly SplitShare[]>;\n}\n\ninterface WireSplitRecipient {\n readonly recipientId: string;\n /** Tiyin. */\n readonly amount: number;\n readonly items: readonly WireReceiptItem[] | undefined;\n}\n\nfunction readRecipient(recipient: Params): WireSplitRecipient {\n return {\n recipientId: recipient.string('recipientId'),\n amount: recipient.tiyin('amountTiyin'),\n items: recipient.optionalArray('items', readReceiptItem),\n };\n}\n\nexport function createSplitsResource(http: HttpClient): SplitsResource {\n return {\n async create(params, options) {\n const method = 'splits.create';\n const { input, signal } = readCall(params, options, method);\n const body = {\n transactionId: input.string('transactionId'),\n recipients: input.array('recipients', readRecipient),\n // When a resend is needed is undocumented ([OPEN Q59]); the flag is forwarded as given.\n resendOFD: input.optionalBoolean('resendOfd'),\n };\n return send(http, ENDPOINTS.create, { body, signal }, decodeTransactionReference);\n },\n\n async get(params, options) {\n const method = 'splits.get';\n const { input, signal } = readCall(params, options, method);\n const query = { transactionId: input.string('transactionId') };\n return send(http, ENDPOINTS.get, { query, signal }, decodeSplitShares);\n },\n };\n}\n","import { asString, readFields, type Decoder } from '../core/decoding.js';\nimport type { SubMerchantCreated } from './types.js';\n\n/** `subMerchant/merchant-create/` result. */\nexport const decodeSubMerchantCreated: Decoder<SubMerchantCreated> = (value, path) => {\n const field = readFields(value, path);\n return { subMerchantId: field('id', asString), name: field('name', asString) };\n};\n","import { readCall, send } from '../core/call.js';\nimport type { Params } from '../core/params.js';\nimport type { HttpClient, PaylovCallOptions } from '../core/types.js';\nimport { decodeSubMerchantCreated } from './decoders.js';\nimport type { CreateSubMerchantParams, SubMerchantCreated } from './types.js';\n\nexport const ENDPOINTS = {\n create: { method: 'POST', route: '/merchant/subMerchant/merchant-create/', shape: 'envelope' },\n} as const;\n\n/**\n * The `paylov.subMerchants` namespace. Needs sub-merchant creation enabled for the merchant;\n * otherwise `permission_denied`.\n */\nexport interface SubMerchantsResource {\n /**\n * Creates a child merchant under yours; Paylov staff activate it later. Moves no money. Tax ids,\n * director and bank details never reach logger events or errors.\n *\n * Recovery: no lookup exists. When `isPaylovOutcomeUnknown(error)`, repeat the call with the\n * same data; `sub_merchant_already_created` then means it exists.\n *\n * @throws {@link PaylovApiError} `sub_merchant_already_created` (the `name`, `tin`, `pinfl` or\n * `externalId` is taken among your sub-merchants), `validation_error` (`fields` names wire\n * fields such as `organization.oked` or `non_field_errors`), `rate_limit_exceeded` (more than\n * 100 calls per minute), `permission_denied`.\n *\n * @example\n * const { subMerchantId } = await paylov.subMerchants.create({\n * name: shop.displayName,\n * tin: shop.tin,\n * externalId: shop.id,\n * ofdVatPercent: 12,\n * });\n * await shops.linkPaylov(shop.id, subMerchantId);\n */\n create(params: CreateSubMerchantParams, options?: PaylovCallOptions): Promise<SubMerchantCreated>;\n}\n\ninterface WireOrganization {\n readonly name: string;\n readonly director_pinfl: string;\n readonly account_number: string;\n readonly oked: string;\n readonly legal_name: string | undefined;\n readonly director_fio: string | undefined;\n readonly director_passport: string | undefined;\n readonly director_passport_valid_to: string | undefined;\n readonly director_birth_date: string | undefined;\n readonly director_nationality: string | undefined;\n readonly dr_nationality_for_uzcard: string | undefined;\n readonly dr_nationality_for_humo: string | undefined;\n readonly mfo: string | undefined;\n}\n\nfunction readOrganization(organization: Params): WireOrganization {\n return {\n name: organization.string('name'),\n director_pinfl: organization.string('directorPinfl'),\n account_number: organization.string('accountNumber'),\n oked: organization.string('oked'),\n legal_name: organization.optionalString('legalName'),\n director_fio: organization.optionalString('directorFullName'),\n director_passport: organization.optionalString('directorPassport'),\n director_passport_valid_to: organization.optionalString('directorPassportValidTo'),\n director_birth_date: organization.optionalString('directorBirthDate'),\n director_nationality: organization.optionalString('directorNationality'),\n dr_nationality_for_uzcard: organization.optionalString('directorNationalityUzcard'),\n dr_nationality_for_humo: organization.optionalString('directorNationalityHumo'),\n mfo: organization.optionalString('mfo'),\n };\n}\n\nexport function createSubMerchantsResource(http: HttpClient): SubMerchantsResource {\n return {\n async create(params, options) {\n const method = 'subMerchants.create';\n const { input, signal } = readCall(params, options, method);\n const organization = input.optionalObject('organization', readOrganization);\n const pinfl = input.optionalString('pinfl');\n const needsTin = organization !== undefined || pinfl === undefined;\n const body = {\n name: input.string('name'),\n tin: needsTin ? input.string('tin') : input.optionalString('tin'),\n pinfl,\n external_id: input.optionalString('externalId'),\n create_new_organization: organization === undefined ? undefined : true,\n organization,\n self_employee_service: input.optionalBoolean('isSelfEmployed'),\n ofd_vat_percent: input.optionalInteger('ofdVatPercent'),\n SPIC: input.optionalString('spic'),\n spic_package_code: input.optionalString('spicPackageCode'),\n };\n return send(http, ENDPOINTS.create, { body, signal }, decodeSubMerchantCreated);\n },\n };\n}\n","import {\n arrayOf,\n asBoolean,\n asMaskedPan,\n asNonNegativeInteger,\n asString,\n asTashkentDateTime,\n asTiyin,\n fieldOf,\n DecodeFailure,\n nullable,\n readFields,\n type Decoder,\n} from '../core/decoding.js';\nimport { statusDecoder } from '../shared/transactions.js';\nimport type {\n FiscalReceiptSummary,\n Transaction,\n TransactionPage,\n TransactionStatus,\n} from './types.js';\n\n/**\n * The SDK's word for each wire status it renames. The fake encodes a word as its first wire\n * spelling here.\n */\nexport const TRANSACTION_STATUS_BY_WIRE: ReadonlyMap<string, TransactionStatus> = new Map([\n ['waiting', 'held'],\n ['payed', 'paid'],\n ['cancel', 'refunded'],\n // `cancel` marked a refunded sale and `refunded` an expired hold Paylov released, against the\n // vendor's \"Refunded\"; which marks what in general is unsettled, so both read `refunded`\n // [OPEN Q86].\n ['refunded', 'refunded'],\n]);\n\nconst decodeTransactionStatus = statusDecoder(TRANSACTION_STATUS_BY_WIRE);\n\nconst decodeFiscalReceiptSummary: Decoder<FiscalReceiptSummary> = (value, path) => {\n const receipt = readFields(value, path);\n return {\n receiptId: receipt('receipt_id', asNonNegativeInteger),\n receiptUrl: receipt('qr_code_url', asString),\n // The zone is undocumented, so the text stays raw.\n issuedAtRaw: receipt('date_time', asString),\n isRefund: receipt('is_refund', asBoolean),\n };\n};\n\n/**\n * Withholds `owner` (cardholder name), the float SUM `amount`, the label `transaction_type` and\n * `account`, which reads `{}` whatever was sent [OPEN Q87].\n */\nconst decodeTransaction: Decoder<Transaction> = (value, path) => {\n const transaction = readFields(value, path);\n return {\n transactionId: transaction('id', asString),\n externalId: transaction('external_id', nullable(asString)),\n userId: transaction('userId', nullable(asString)),\n cardId: transaction('card_id', nullable(asString)),\n maskedCardNumber: transaction('cardNumber', nullable(asMaskedPan)),\n amountTiyin: transaction('amount_in_tiyin', asTiyin),\n status: transaction('status', decodeTransactionStatus),\n declineCode: transaction('error_message', nullable(asString)),\n paidOrCreatedAt: transaction('date', asTashkentDateTime),\n cancelledAt: transaction('cancel_time', nullable(asTashkentDateTime)),\n isHold: transaction('is_hold', asBoolean),\n isSplit: transaction('is_split', asBoolean),\n isA2c: transaction('is_a2c', asBoolean),\n // `null`, not `false`, on every payment outside checkout.\n isCheckout: transaction('via_link', nullable(asBoolean)) === true,\n fiscalReceipts: transaction('ofd', arrayOf(decodeFiscalReceiptSummary)),\n };\n};\n\nexport const decodeTransactionPage: Decoder<TransactionPage> = (value, path) => {\n const page = readFields(value, path);\n return {\n total: page('totalTransaction', asNonNegativeInteger),\n transactions: page('transactions', arrayOf(decodeTransaction)),\n };\n};\n\nconst decodeRows = fieldOf('transactions', arrayOf(decodeTransaction));\n\n/**\n * The `getTransactions?id=` result: no row is a miss. Without a usable `id` the endpoint lists\n * paid transactions instead, so any other row, or more than one, is malformed.\n */\nexport function decodeRequestedTransaction(transactionId: string): Decoder<Transaction | null> {\n return (value, path) => {\n const rows = decodeRows(value, path);\n const [row] = rows;\n if (row === undefined) return null;\n if (rows.length > 1 || row.transactionId.toLowerCase() !== transactionId.toLowerCase()) {\n throw new DecodeFailure(`${path}.transactions`);\n }\n return row;\n };\n}\n\n/** `getTransactions/rrn/{id}/` result. */\nexport const decodeRrn: Decoder<string> = fieldOf('rrn', asString);\n","import { readCall, send } from '../core/call.js';\nimport type { HttpClient, PaylovCallOptions } from '../core/types.js';\nimport { decodeRequestedTransaction, decodeRrn, decodeTransactionPage } from './decoders.js';\nimport type {\n GetRrnParams,\n GetTransactionParams,\n ListTransactionsParams,\n Transaction,\n TransactionPage,\n} from './types.js';\n\nexport const ENDPOINTS = {\n getTransactions: { method: 'GET', route: '/merchant/getTransactions/', shape: 'envelope' },\n getRrn: {\n method: 'GET',\n route: '/merchant/getTransactions/rrn/{transactionId}/',\n shape: 'envelope',\n },\n} as const;\n\n/** The `paylov.transactions` namespace. */\nexport interface TransactionsResource {\n /**\n * Reads one transaction in any status: a receipt, PAN, hold or checkout payment. This is the\n * read to reconcile with after an ambiguous failure of a money-moving call.\n *\n * Resolves to `null` when the gateway knows no such transaction. A miss right after a failed\n * call is an observation, not proof that nothing was created: read again after a delay.\n *\n * @example\n * const transaction = await paylov.transactions.get({ transactionId });\n * if (transaction === null) {\n * // unknown to the gateway (so far)\n * } else if (transaction.status === 'paid') {\n * await orders.markPaid(orderId, transaction.paidOrCreatedAt);\n * } else if (transaction.status === 'failed') {\n * await orders.markDeclined(orderId, transaction.declineCode);\n * }\n */\n get(params: GetTransactionParams, options?: PaylovCallOptions): Promise<Transaction | null>;\n\n /**\n * Lists the merchant's **paid** transactions, newest payment first, one page at a time.\n *\n * Created, held, failed and refunded transactions are not listed, so a refunded\n * payment drops out: this is a settled-sales feed, not an audit log, and never a way to\n * reconcile. The list is merchant-wide (no user filter). Paylov does not document the page size\n * (20 on its test environment): page until `transactions` is empty or the rows seen reach\n * `total`.\n *\n * @throws {@link PaylovApiError} `field_not_valid` (a date the gateway rejects).\n *\n * @example\n * const seen: Transaction[] = [];\n * for (let page = 1; ; page += 1) {\n * const result = await paylov.transactions.list({\n * fromDate: '2026-11-01',\n * toDate: '2026-11-30',\n * page,\n * });\n * seen.push(...result.transactions);\n * if (result.transactions.length === 0 || seen.length >= result.total) break;\n * }\n */\n list(params?: ListTransactionsParams, options?: PaylovCallOptions): Promise<TransactionPage>;\n\n /**\n * Reads the card network's retrieval reference number (RRN) of a paid transaction, for\n * disputes and bank-side lookups. Known to work for `payments.pay` payments, also after a\n * refund. PAN payments have none (`transaction_not_available_for_payment`); whether captured\n * holds and checkout payments have one is undocumented.\n *\n * @throws {@link PaylovApiError} `transaction_not_found`, `receipt_not_available_for_operation`\n * (not paid), `transaction_not_available_for_payment` (a payment type without an RRN).\n *\n * @example\n * const rrn = await paylov.transactions.getRrn({ transactionId });\n */\n getRrn(params: GetRrnParams, options?: PaylovCallOptions): Promise<string>;\n}\n\nexport function createTransactionsResource(http: HttpClient): TransactionsResource {\n return {\n async get(params, options) {\n const method = 'transactions.get';\n const { input, signal } = readCall(params, options, method);\n const transactionId = input.string('transactionId');\n return send(\n http,\n ENDPOINTS.getTransactions,\n { query: { id: transactionId }, signal },\n decodeRequestedTransaction(transactionId),\n );\n },\n\n async list(params, options) {\n const method = 'transactions.list';\n const { input, signal } = readCall(params ?? {}, options, method);\n const query = {\n beginDate: input.optionalString('fromDate'),\n endDate: input.optionalString('toDate'),\n page: input.optionalInteger('page'),\n };\n return send(http, ENDPOINTS.getTransactions, { query, signal }, decodeTransactionPage);\n },\n\n async getRrn(params, options) {\n const method = 'transactions.getRrn';\n const { input, signal } = readCall(params, options, method);\n const transactionId = input.string('transactionId');\n return send(http, ENDPOINTS.getRrn, { path: { transactionId }, signal }, decodeRrn);\n },\n };\n}\n","/**\n * A checkout amount in the minor unit of its currency, shared by the checkout link and the\n * check/perform callbacks. The wire carries one integer plus a numeric currency code.\n */\n\nimport { isNonNegativeSafeInteger } from '../core/numbers.js';\nimport { everyLiteral, type Params } from '../core/params.js';\n\n/** Numeric currency codes the checkout accepts: 860 UZS, 840 USD. */\nexport type CheckoutCurrency = 860 | 840;\n\n/** The `CheckoutCurrency` values, for runtime checks. */\nexport const CHECKOUT_CURRENCIES: readonly CheckoutCurrency[] = everyLiteral<CheckoutCurrency>()([\n 860, 840,\n]);\n\n/**\n * An amount in the minor unit of its currency: tiyin for 860 (UZS), cents for 840 (USD).\n *\n * @example\n * const amount: CheckoutAmount = { currency: 860, amountTiyin: 50_000 }; // 500.00 SUM\n */\nexport type CheckoutAmount =\n | { readonly currency: 860; readonly amountTiyin: number }\n | { readonly currency: 840; readonly amountCents: number };\n\n/** Reads a checkout amount object under `key`; failures are `sdk_invalid_amount`. */\nexport function readCheckoutAmount(params: Params, key: string): CheckoutAmount {\n return params.object(key, (amount) =>\n amount.literal('currency', CHECKOUT_CURRENCIES) === 860\n ? { currency: 860, amountTiyin: amount.tiyin('amountTiyin') }\n : { currency: 840, amountCents: amount.tiyin('amountCents') },\n );\n}\n\n/** The integer the wire carries for the amount. */\nexport function minorUnitsOf(amount: CheckoutAmount): number {\n return amount.currency === 860 ? amount.amountTiyin : amount.amountCents;\n}\n\n/** Decodes a wire minor-unit amount and currency code, or `undefined` when either is invalid. */\nexport function decodeCheckoutAmount(\n minorUnits: unknown,\n currency: unknown,\n): CheckoutAmount | undefined {\n if (!isNonNegativeSafeInteger(minorUnits)) return undefined;\n if (currency === 860) return { currency, amountTiyin: minorUnits };\n if (currency === 840) return { currency, amountCents: minorUnits };\n return undefined;\n}\n","import { asLiteral, asString, fieldOf, readFields, type Decoder } from '../core/decoding.js';\nimport type { OnboardingCompleted } from './types.js';\n\n/** `{\"status\":\"ok\"}` means the token is usable. */\nexport const decodeTokenUsable: Decoder<true> = (value, path) => {\n fieldOf('status', asLiteral('ok'))(value, path);\n return true;\n};\n\n/** Failures name the field, never its value: the same body holds the consumer secret. */\nexport const decodeOnboardingCompleted: Decoder<OnboardingCompleted> = (value, path) => {\n const field = readFields(value, path);\n return {\n consumerKey: field('consumer_key', asString),\n consumerSecret: field('consumer_secret', asString),\n username: field('username', asString),\n };\n};\n","/** The operator onboarding step that issues merchant API credentials. */\n\nimport { orOnMiss, readCall, send } from '../core/call.js';\nimport { readSurfaceTransport } from '../core/config.js';\nimport { createHttpClient } from '../core/http.js';\nimport { readConfig } from '../core/params.js';\nimport type { HttpClient, PaylovCallOptions } from '../core/types.js';\nimport { decodeOnboardingCompleted, decodeTokenUsable } from './decoders.js';\nimport type {\n CheckOnboardingTokenParams,\n CompleteOnboardingParams,\n OnboardingCompleted,\n PaylovOnboardingConfig,\n} from './types.js';\n\nexport const ENDPOINTS = {\n checkToken: {\n method: 'GET',\n route: '/merchant/onboarding/',\n shape: 'flat',\n miss: 'invalid_or_expired',\n },\n complete: { method: 'POST', route: '/merchant/onboarding/', shape: 'flat' },\n} as const;\n\n/**\n * Completes Paylov merchant onboarding with the single-use token Paylov issues. It needs no\n * merchant credentials and is an operator step, run once, not part of a running integration.\n * The token travels in the query string and is never logged; the password and the issued\n * consumer secret never reach logger events or errors.\n *\n * @example\n * const onboarding = new PaylovOnboarding({ baseUrl: 'https://dev.gw.paylov.uz' });\n * if (!(await onboarding.checkToken({ token: onboardingToken }))) {\n * throw new Error('onboarding token is consumed or expired; ask Paylov for a new one');\n * }\n *\n * @throws {@link PaylovInputError} `sdk_config_error` for malformed configuration.\n */\nexport class PaylovOnboarding {\n readonly #http: HttpClient;\n\n constructor(config: PaylovOnboardingConfig) {\n this.#http = createHttpClient(\n readSurfaceTransport(readConfig(config, 'PaylovOnboarding config')),\n );\n }\n\n /**\n * Checks whether an onboarding token can still be used (`GET /merchant/onboarding/?token=`).\n * Resolves `false` when Paylov reports the token unknown, consumed or expired\n * (`invalid_or_expired`).\n *\n * @throws {@link PaylovApiError} any other gateway error, e.g. `validation_error`.\n *\n * @example\n * const usable = await onboarding.checkToken({ token: onboardingToken });\n * if (!usable) throw new Error('ask Paylov for a new onboarding token');\n */\n async checkToken(\n params: CheckOnboardingTokenParams,\n options?: PaylovCallOptions,\n ): Promise<boolean> {\n const method = 'onboarding.checkToken';\n const { input, signal } = readCall(params, options, method);\n const query = { token: input.string('token') };\n const request = send(this.#http, ENDPOINTS.checkToken, { query, signal }, decodeTokenUsable);\n return orOnMiss(request, ENDPOINTS.checkToken, false);\n }\n\n /**\n * Sets the merchant API username and password and returns the issued credentials\n * (`POST /merchant/onboarding/?token=`). The token is single-use and `consumerSecret` is shown\n * only once: persist the whole result before doing anything else. The account stays inactive\n * until Paylov activates it; until then a `PaylovClient` with these credentials fails with\n * `invalid_grant`.\n *\n * Recovery: never retried. When `isPaylovOutcomeUnknown(error)`, the credentials may have been\n * issued and lost: call `checkToken`; `true` means `complete` can run again, `false` that the\n * token was used, so ask Paylov to reissue the credentials.\n *\n * @throws {@link PaylovApiError} `validation_error` (see `fields`), or `invalid_or_expired`\n * for an unknown, used or expired token.\n *\n * @example\n * const credentials = await onboarding.complete({\n * token: onboardingToken,\n * username: merchantUsername,\n * password: merchantPassword,\n * });\n * await secretManager.store('paylov', credentials);\n */\n async complete(\n params: CompleteOnboardingParams,\n options?: PaylovCallOptions,\n ): Promise<OnboardingCompleted> {\n const method = 'onboarding.complete';\n const { input, signal } = readCall(params, options, method);\n const query = { token: input.string('token') };\n const body = {\n username: input.string('username'),\n password: input.string('password'),\n };\n return send(this.#http, ENDPOINTS.complete, { query, body, signal }, decodeOnboardingCompleted);\n }\n}\n"],"mappings":";;;AAqDA,IAAe,kBAAf,cAAuC,MAAM;CAK3C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,MAAM,kBAAkB,MAAM,UAAU;CAC1C;;;;;;;CAQA,SAAgC;EAC9B,OAAO;GACL,MAAM,KAAK;GACX,MAAM,KAAK;GACX,MAAM,KAAK;GACX,SAAS,KAAK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