@takeal/cusfront-sdk 0.8.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +46 -5
  3. package/dist/analytics.cjs +74 -22
  4. package/dist/analytics.cjs.map +1 -1
  5. package/dist/analytics.d.cts +43 -4
  6. package/dist/analytics.d.ts +43 -4
  7. package/dist/analytics.js +71 -23
  8. package/dist/analytics.js.map +1 -1
  9. package/dist/{cards-DwxkVJUB.d.cts → cards-C5rk0XkI.d.cts} +47 -5
  10. package/dist/{cards-VkS_2lPe.d.ts → cards-CS-oxqLS.d.ts} +47 -5
  11. package/dist/index.cjs +94 -26
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +13 -5
  14. package/dist/index.d.ts +13 -5
  15. package/dist/index.js +91 -27
  16. package/dist/index.js.map +1 -1
  17. package/dist/react/index.d.cts +1 -1
  18. package/dist/react/index.d.ts +1 -1
  19. package/dist/resources/auth.cjs.map +1 -1
  20. package/dist/resources/auth.d.cts +1 -1
  21. package/dist/resources/auth.d.ts +1 -1
  22. package/dist/resources/auth.js.map +1 -1
  23. package/dist/resources/branding.cjs.map +1 -1
  24. package/dist/resources/branding.d.cts +6 -0
  25. package/dist/resources/branding.d.ts +6 -0
  26. package/dist/resources/branding.js.map +1 -1
  27. package/dist/resources/cards.cjs.map +1 -1
  28. package/dist/resources/cards.d.cts +1 -1
  29. package/dist/resources/cards.d.ts +1 -1
  30. package/dist/resources/cards.js.map +1 -1
  31. package/dist/resources/deposits.cjs.map +1 -1
  32. package/dist/resources/deposits.d.cts +1 -1
  33. package/dist/resources/deposits.d.ts +1 -1
  34. package/dist/resources/deposits.js.map +1 -1
  35. package/dist/resources/funding-options.d.cts +1 -1
  36. package/dist/resources/funding-options.d.ts +1 -1
  37. package/dist/resources/me.d.cts +1 -1
  38. package/dist/resources/me.d.ts +1 -1
  39. package/dist/telegram.cjs +20 -4
  40. package/dist/telegram.cjs.map +1 -1
  41. package/dist/telegram.d.cts +1 -1
  42. package/dist/telegram.d.ts +1 -1
  43. package/dist/telegram.js +20 -4
  44. package/dist/telegram.js.map +1 -1
  45. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/error.ts","../src/http.ts","../src/resources/attribution.ts","../src/resources/cards.ts","../src/resources/auth.ts","../src/resources/deposits.ts","../src/resources/balance.ts","../src/resources/bonus.ts","../src/resources/debt.ts","../src/resources/close-requests.ts","../src/resources/claims.ts","../src/resources/codes.ts","../src/resources/referral.ts","../src/resources/subscription.ts","../src/resources/branding.ts","../src/resources/wallet.ts","../src/resources/blog.ts","../src/resources/documents.ts","../src/resources/subscriptions.ts","../src/resources/sessions.ts","../src/resources/push.ts","../src/resources/me.ts","../src/resources/notifications.ts","../src/resources/devices.ts","../src/resources/history.ts","../src/resources/consents.ts","../src/resources/receipts.ts","../src/resources/support.ts","../src/resources/funding-options.ts","../src/version.ts","../src/client-platform.ts","../src/token-store.ts","../src/assets.ts","../src/compat.ts","../src/index.ts","../src/telegram.ts"],"names":["stored","ls"],"mappings":";;;AAQO,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA,EAGlC,WAAA,CAEkB,MAAA,EAIA,IAAA,EAGhB,OAAA,EAGgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAZG,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAIA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAMA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAdlB,IAAA,IAAA,CAAS,UAAA,GAAa,IAAA;AAiBpB,IAAA,IAAA,CAAK,IAAA,GAAO,UAAA;AAAA,EACd;AACF,CAAA;AAEO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAGtC,WAAA,CACE,SACgB,KAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,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AA,EACA,IAAA,GAA4B,EAAC,EACJ;AACzB,EAAA,MAAM,EAAE,QAAQ,OAAA,EAAQ,GAAI,MAAM,gBAAA,CAAiB,QAAA,EAAU,QAAQ,IAAI,CAAA;AACzE,EAAA,IAAI,QAAQ,KAAA,KAAU,SAAA,EAAW,MAAM,IAAI,qBAAqB,QAAQ,CAAA;AACxE,EAAA,OAAO,MAAA;AACT;AAIO,SAAS,kBAAA,GAAoC;AAClD,EAAA,MAAM,KACJ,UAAA,CAGA,QAAA;AACF,EAAA,MAAM,IAAA,GAAO,IAAI,MAAA,EAAQ,QAAA;AACzB,EAAA,OAAO,IAAA,IAAQ,IAAA,CAAK,MAAA,GAAS,CAAA,GAAI,IAAA,GAAO,IAAA;AAC1C;AAQA,eAAsB,kBAAA,CACpB,MAAA,EACA,IAAA,GAA4B,EAAC,EACJ;AACzB,EAAA,MAAM,WAAW,kBAAA,EAAmB;AACpC,EAAA,IAAI,CAAC,QAAA;AACH,IAAA,MAAM,IAAI,aAAA;AAAA,MACR,mFAAA;AAAA,MACA;AAAA,KACF;AACF,EAAA,OAAO,YAAA,CAAa,QAAA,EAAU,MAAA,EAAQ,IAAI,CAAA;AAC5C","file":"telegram.cjs","sourcesContent":["/**\n * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;\n * network-level / abort / serialisation failures get the generic\n * `NetworkError`. Consumers catch on the discriminator field\n * (`isApiError` / `isNetworkError`) rather than `instanceof` — works\n * across bundler boundaries where multiple copies of the class can\n * coexist.\n */\nexport class ApiError extends Error {\n readonly isApiError = true as const;\n\n constructor(\n /** HTTP status code returned by the Takeal API. */\n public readonly status: number,\n /** Stable machine-readable code (e.g. `\"insufficient_funds\"`,\n * `\"permission_required\"`, `\"validation\"`). Same enum the\n * TypeScript types pin via openapi-typescript. */\n public readonly code: string,\n /** Human-readable message. English; the consumer maps to its\n * own i18n layer before showing to end-users. */\n message: string,\n /** Full parsed response body when available. Carries field-level\n * validation details for `code = \"validation\"`. */\n public readonly body?: unknown,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport class NetworkError extends Error {\n readonly isNetworkError = true as const;\n\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** Type guard — preferred over `instanceof` (bundler-safe). */\nexport function isApiError(e: unknown): e is ApiError {\n return typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true;\n}\n\nexport function isNetworkError(e: unknown): e is NetworkError {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { isNetworkError?: boolean }).isNetworkError === true\n );\n}\n","import { ApiError, NetworkError } from \"./error.js\";\nimport type { TokenStore } from \"./token-store.js\";\n\n/**\n * Internal HTTP client. One per SDK instance; injected into each\n * resource. Responsibilities:\n *\n * - Construct absolute URLs from `baseUrl` + API version + path.\n * Resources pass contract paths (`/me/deposits`); the `/v1` prefix is\n * added here, in one place. Only the deployment-level endpoints\n * (`/ready`, `/branding`, …) stay unversioned.\n * - Set `Authorization: Bearer <jwt>` from the `TokenStore`.\n * - Set `Content-Type: application/json` on bodies.\n * - Parse JSON responses + map non-2xx to `ApiError`.\n * - Forward `Idempotency-Key` when the caller passes one.\n * - Send the constructor's `defaultHeaders` (the `X-Takeal-Client`\n * descriptor) on every request.\n * - Surface network failures (DNS, abort, broken pipe) as\n * `NetworkError`.\n *\n * A 401 on an authenticated call asks the refresher (set by the auth\n * resource when a remembered sign-in exists) for a new session once, and\n * repeats the call when it got one. Concurrent 401s share one refresh.\n */\n\nexport type FetchLike = typeof fetch;\n\n/** Current public contract revision of the Takeal API. */\nexport const API_VERSION = \"/v1\";\n\n/** Host-level endpoints that are not part of a versioned contract. */\nconst UNVERSIONED = new Set([\"/health\", \"/ready\", \"/branding\", \"/favicon.ico\"]);\n\n/**\n * `/me/deposits` → `/v1/me/deposits`. Already-versioned paths and the\n * unversioned ops endpoints pass through untouched.\n */\nexport function versionedPath(path: string): string {\n const p = path.startsWith(\"/\") ? path : `/${path}`;\n const bare = p.split(\"?\")[0]!;\n if (UNVERSIONED.has(bare)) return p;\n if (bare === API_VERSION || bare.startsWith(`${API_VERSION}/`)) return p;\n return `${API_VERSION}${p}`;\n}\n\nexport interface HttpOptions {\n /** Request body. Will be JSON-serialised if not already a\n * string / FormData / Blob. */\n body?: unknown;\n /** Idempotency key forwarded as the `Idempotency-Key` header.\n * Required by the Takeal API on most write endpoints. */\n idempotencyKey?: string;\n /** Extra headers merged after the SDK's defaults — caller wins. */\n headers?: Record<string, string>;\n /** Bypass the token store for one call (login, refresh). */\n skipAuth?: boolean;\n /** AbortSignal forwarded to fetch. */\n signal?: AbortSignal;\n /** Internal: this is the repeat after a refresh. */\n retried?: boolean;\n}\n\nexport class HttpClient {\n constructor(\n private readonly baseUrl: string,\n private readonly tokens: TokenStore,\n private readonly fetchImpl: FetchLike,\n /** Headers sent on every request, below the per-call `headers`\n * (a caller can still override one). */\n private readonly defaultHeaders: Record<string, string> = {},\n ) {\n if (!baseUrl) throw new Error(\"HttpClient: baseUrl is required\");\n }\n\n private refresher: (() => Promise<boolean>) | undefined;\n private refreshing: Promise<boolean> | undefined;\n\n /** Called once on a 401; resolves `true` when a new session was stored. */\n setRefresher(fn: (() => Promise<boolean>) | undefined): void {\n this.refresher = fn;\n }\n\n /** One refresh at a time, whoever asks. */\n refreshOnce(): Promise<boolean> {\n if (!this.refresher) return Promise.resolve(false);\n if (!this.refreshing) {\n this.refreshing = this.refresher()\n .catch(() => false)\n .finally(() => {\n this.refreshing = undefined;\n });\n }\n return this.refreshing;\n }\n\n async get<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"GET\", path, opts);\n }\n\n async post<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"POST\", path, opts);\n }\n\n async put<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"PUT\", path, opts);\n }\n\n async patch<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"PATCH\", path, opts);\n }\n\n async delete<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"DELETE\", path, opts);\n }\n\n /** GET a file. Same auth and refresh as the JSON calls; an error status\n * throws `ApiError` the same way. */\n async getBlob(path: string, opts: HttpOptions = {}): Promise<Blob> {\n const resp = await this.send(\"GET\", path, { ...opts, accept: \"*/*\" });\n if (!resp.ok) return parseResponse<never>(resp);\n return resp.blob();\n }\n\n private async request<T>(method: string, path: string, opts: HttpOptions): Promise<T> {\n return parseResponse<T>(await this.send(method, path, opts));\n }\n\n private async send(\n method: string,\n path: string,\n opts: HttpOptions & { accept?: string },\n ): Promise<Response> {\n const url = this.absolute(path);\n const headers: Record<string, string> = {\n Accept: opts.accept ?? \"application/json\",\n ...this.defaultHeaders,\n };\n if (opts.body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n if (opts.idempotencyKey) headers[\"Idempotency-Key\"] = opts.idempotencyKey;\n if (!opts.skipAuth) {\n const token = await Promise.resolve(this.tokens.get());\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n }\n Object.assign(headers, opts.headers ?? {});\n\n const init: RequestInit = {\n method,\n headers,\n ...(opts.signal ? { signal: opts.signal } : {}),\n };\n if (opts.body !== undefined) {\n init.body = typeof opts.body === \"string\" ? opts.body : JSON.stringify(opts.body);\n }\n\n let resp: Response;\n try {\n resp = await this.fetchImpl(url, init);\n } catch (e) {\n // DNS failure, connection refused, abort — anything before the\n // server returns a status. Map to NetworkError for the consumer.\n throw new NetworkError(e instanceof Error ? e.message : \"network error\", e);\n }\n\n if (resp.status === 401 && !opts.skipAuth && !opts.retried && this.refresher) {\n if (await this.refreshOnce()) {\n return this.send(method, path, { ...opts, retried: true });\n }\n }\n return resp;\n }\n\n private absolute(path: string): string {\n if (path.startsWith(\"http://\") || path.startsWith(\"https://\")) return path;\n const base = this.baseUrl.replace(/\\/+$/, \"\");\n return `${base}${versionedPath(path)}`;\n }\n}\n\nasync function parseResponse<T>(resp: Response): Promise<T> {\n // Read body once — the Takeal API either returns JSON or an empty body\n // (204 No Content on some DELETEs). Empty body → undefined cast.\n const text = await resp.text();\n let body: unknown;\n if (text.length === 0) {\n body = undefined;\n } else {\n try {\n body = JSON.parse(text);\n } catch {\n // Non-JSON response. On 2xx that's unexpected but not fatal —\n // hand back the raw text under a synthetic field. On error\n // status, fold into the ApiError body.\n body = { raw: text };\n }\n }\n\n if (!resp.ok) {\n const errBody = (body ?? {}) as { code?: string; message?: string };\n throw new ApiError(\n resp.status,\n errBody.code ?? `http_${resp.status}`,\n errBody.message ?? resp.statusText ?? \"request failed\",\n body,\n );\n }\n return body as T;\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n \"friend\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"skipped\";\n\n/**\n * The visitor's ids at the analytics platforms (TKL-329). The SDK keeps\n * them from the moment the visitor agreed to analytics cookies and sends\n * them with an order, a top-up and a sign-in, so the server can report the\n * payment and the issued card to the platforms after the person has left\n * for the bank or Telegram. See {@link analyticsIds}.\n */\nexport interface AnalyticsIds {\n /** Yandex Metrica's ClientID, from `getClientID`. A string: it does not fit a number. */\n metrika_client_id?: string;\n /** Google Analytics' client id, from the `_ga` cookie: `1234567890.1700000000`. */\n ga_client_id?: string;\n}\n\nexport interface HandoffToken {\n /** Goes into the Mini App link's `startapp` after two underscores. */\n token: string;\n expires_at: string;\n}\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** A one-day token that carries the visitor's analytics ids into the\n * Telegram Mini App, whose sign-in reads it back. Most callers want\n * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of\n * the ids is valid. */\n async handoff(ids: AnalyticsIds): Promise<HandoffToken> {\n return this.http.post<HandoffToken>(\"/attribution/handoff\", { body: ids, skipAuth: true });\n }\n\n /**\n * The `startapp` value for a link from the site to the Mini App: the code\n * as it is, followed by `__<token>` when the visitor has analytics ids, so\n * a payment made in Telegram is still credited to the visit it came from.\n * Without ids, or when the token can't be had, just the code.\n *\n * ```ts\n * const start = await client.attribution.telegramStartParam(\"SPRING\");\n * location.href = `https://t.me/our_bot/app?startapp=${start}`;\n * ```\n */\n async telegramStartParam(code = \"\"): Promise<string> {\n const ids = analyticsIds();\n if (!ids) return code;\n try {\n const { token } = await this.handoff(ids);\n return `${code}__${token}`;\n } catch {\n return code;\n }\n }\n\n /** Send the visitor's analytics ids for the signed-in account, e.g. right\n * after they agreed to analytics cookies in the cabinet. Without an\n * argument the ids this browser holds are sent; nothing is sent when it\n * holds none. */\n async sendAnalyticsIds(ids: AnalyticsIds | undefined = analyticsIds()): Promise<void> {\n if (!ids) return;\n await this.http.post<void>(\"/me/analytics/ids\", { body: ids });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Analytics ids (TKL-329)\n// ---------------------------------------------------------------------------\n\nconst IDS_KEY = \"takeal_analytics_ids\";\n\nfunction storage(): Storage | undefined {\n try {\n return (globalThis as { localStorage?: Storage }).localStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction stored(): AnalyticsIds {\n try {\n const raw = storage()?.getItem(IDS_KEY);\n const v = raw ? (JSON.parse(raw) as AnalyticsIds) : {};\n return typeof v === \"object\" && v !== null ? v : {};\n } catch {\n return {};\n }\n}\n\nfunction clean(ids: AnalyticsIds): AnalyticsIds | undefined {\n const out: AnalyticsIds = {};\n const ym = ids.metrika_client_id?.trim();\n if (ym && /^\\d{1,32}$/.test(ym)) out.metrika_client_id = ym;\n const ga = ids.ga_client_id?.trim();\n if (ga && /^\\d+\\.\\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;\n return out.metrika_client_id || out.ga_client_id ? out : undefined;\n}\n\n/**\n * Keep analytics ids for this browser, on top of the ones kept before. The\n * Metrica sink of `initAnalytics` calls it with `getClientID`'s answer once\n * the visitor agreed to analytics; call it yourself for another platform.\n */\nexport function rememberAnalyticsIds(ids: AnalyticsIds): void {\n const merged = clean({ ...stored(), ...ids });\n if (!merged) return;\n try {\n storage()?.setItem(IDS_KEY, JSON.stringify(merged));\n } catch {\n // Storage full or blocked: the cookies still hold them.\n }\n}\n\n/** Forget the kept analytics ids: the visitor declined analytics. */\nexport function forgetAnalyticsIds(): void {\n try {\n storage()?.removeItem(IDS_KEY);\n } catch {\n // Nothing kept, or nothing to reach.\n }\n}\n\n/**\n * The visitor's analytics ids: the ones kept by {@link rememberAnalyticsIds},\n * and failing those the platforms' own cookies (`_ym_uid`, `_ga`), which\n * exist only once the visitor agreed to analytics. `undefined` when there\n * are none. The site and the cabinet share them when they share the origin.\n */\nexport function analyticsIds(): AnalyticsIds | undefined {\n const kept = stored();\n return clean({\n metrika_client_id: kept.metrika_client_id ?? readCookie(\"_ym_uid\"),\n ga_client_id: kept.ga_client_id ?? readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\"),\n });\n}\n\n/** `attribution` with the visitor's analytics ids filled in where it has none. */\nexport function withAnalyticsIds(\n attribution: SignupAttribution | undefined,\n): SignupAttribution | undefined {\n const ids = analyticsIds();\n if (!ids) return attribution;\n return {\n ...attribution,\n metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,\n ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id,\n };\n}\n","import type { Claim } from \"./claims.js\";\nimport type { CodeDiscount, CodeEffect, CodeRejection } from \"./codes.js\";\nimport type { ConsentChannel, ConsentKind } from \"./consents.js\";\nimport type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\nimport type { Deposit, DepositMethod } from \"./deposits.js\";\nimport { analyticsIds, type AnalyticsIds } from \"./attribution.js\";\nimport { isApiError } from \"../error.js\";\n\n/**\n * Cards resource — `client.cards.*`.\n *\n * The end-user \"money OUT\" surface: a user issues themselves a card backed by\n * their wallet balance via an issuer connector. Mirrors the Takeal API's\n * `/me/cards` routes:\n *\n * GET /card-products → catalog (public, before sign-in)\n * GET /me/card-products → listProducts (the catalog, personal price)\n * GET /me/card-products/{id} → getProduct\n * GET /me/cards/{id}/topup → topUpTerms\n * POST /me/cards/{id}/topup → topUp\n * POST /me/cards → create\n * GET /me/cards → list (most recent first)\n * GET /me/cards/{id} → get\n * PATCH /me/cards/{id} → update (name, design)\n * GET /me/cards/{id}/balance → balance (prepaid remaining)\n * POST /me/cards/{id}/freeze → freeze\n * POST /me/cards/{id}/unfreeze → unfreeze\n * POST /me/cards/{id}/report-lost → reportLost (lost or stolen: frozen at once)\n * POST /me/cards/{id}/transfer → transfer (to another of their cards)\n * POST /me/cards/{id}/terminate → terminate (one-way)\n * POST /me/cards/{id}/reveal → reveal (the numbers, or a provider page)\n * POST /me/cards/{id}/pin → setPin (physical cards)\n *\n * The lifecycle actions are ownership-gated server-side: a caller can only\n * freeze / unfreeze / terminate a card that belongs to them (else 404).\n *\n * Today only PREPAID is wired end-to-end; CREDIT and GIFT return 400 from\n * the Takeal API until their issuer flows land.\n */\n\n/** Card product. Only `prepaid` is fully implemented today. */\nexport type CardType = \"credit\" | \"prepaid\" | \"gift\";\n\n/**\n * Card lifecycle state.\n *\n * - `pending_payment`: an order waiting for its payment, not a card yet.\n * It has no digits and no expiry, and nothing can be done with it:\n * revealing, freezing, closing or renaming it answers 409 `card_pending`.\n * Show it as \"waiting for payment\", without a way into the card's page.\n * - `pending`: the issuer accepted the order and has not issued the card\n * yet. The price is charged. Show the card as \"being issued\" with no\n * numbers; it becomes `active` on its own, or `failed` with the price\n * back on the wallet. Some issuers take minutes, some a day.\n * - `active`, `frozen`: the usual states. Read `status_source` before\n * offering to unfreeze.\n * - `terminating`: the holder (or the issuer) closed the card and the\n * issuer has not finished: the balance comes back to the wallet when it\n * does. Show it as closing; no actions apply.\n * - `terminated`, `redeemed`, `failed`: final.\n */\nexport type CardStatus =\n | \"pending_payment\"\n | \"pending\"\n | \"active\"\n | \"frozen\"\n | \"terminating\"\n | \"terminated\"\n | \"redeemed\"\n | \"failed\";\n\n/**\n * Who made the card's last status change. `provider` on a `frozen` card\n * means the issuer froze it (a risk check, a lost-card report): the holder\n * cannot unfreeze it, so do not offer the button; say the freeze is lifted\n * through the issuer's support. `holder` and `operator` freezes are undone\n * with `unfreeze()` as usual.\n */\nexport type CardStatusSource = \"holder\" | \"operator\" | \"provider\";\n\n/** `virtual` cards show their numbers in the app; `physical` cards are plastic and have a PIN. */\nexport type CardForm = \"virtual\" | \"physical\";\n\n/**\n * Why `terminate()` is refused right now: `first_purchase_required` (the\n * card closes after its first purchase) or `card_locked` (only support can\n * change it).\n */\nexport type CloseBlockedReason = \"first_purchase_required\" | \"card_locked\";\n\n/**\n * A card design: the artwork a card is shown with. `image_url` is the front,\n * `image_url_back` the back; both are either absolute URLs or paths relative\n * to the API origin (the deployment's default design is\n * `/card-designs/default.svg`, its back `/card-designs/default.svg?side=back`)\n * — pass them through `client.assetUrl()` before rendering. `image_url_back`\n * is `null` or absent for a one-sided design: show the front on both sides.\n * The picture is in the proportions of a plastic card (1586×1000) and draws\n * no chip or card data; the client renders the number, name and expiry on\n * top. `id` is `null` for the deployment default, which is rendered from the\n * branding settings.\n */\nexport interface CardDesignRef {\n id: string | null;\n name?: string;\n image_url: string;\n image_url_back?: string | null;\n}\n\n/**\n * What issuing a card costs the caller. `amount` is the price after the\n * user's subscription discount; `base_amount` is the list price and\n * `discount_bps` the discount in basis points (1000 = 10 %). `label` is the\n * operator's wording for the fee line (\"Card issuance\").\n */\nexport interface CardProductPrice {\n /** What the user pays, decimal string, after their subscription discount. */\n amount: string;\n /**\n * ISO 4217 code: the currency the operator priced the card in, the same\n * before and after sign-in. A card order paid in this currency costs\n * exactly `amount`. It is not necessarily the currency the card is held\n * in (`CardProduct.currency`).\n */\n currency: string;\n /** Wording for the fee line, e.g. \"Card issuance\". */\n label: string;\n /** The list price before the discount, decimal string, in the same currency. */\n base_amount: string;\n /** Discount applied, in basis points (1000 = 10%). */\n discount_bps: number;\n /**\n * What issuing costs when paid from the wallet, converted the way that\n * purchase charges it. Only for a signed-in user whose wallet holds another\n * currency than the price; absent otherwise, and when there is no rate.\n */\n from_wallet?: { amount: string; currency: string } | null;\n}\n\n/**\n * A card the user can order, as listed by `GET /me/card-products`. The id is\n * opaque — it names a product, never a provider. The list comes in the\n * order the operator arranged the storefront; `is_default` marks the\n * product issued when none is chosen, wherever it sits. `designs` is the\n * set the user may pick from (may be empty when only the default applies);\n * `design` is what the card gets when no choice is made. `price` is `null`\n * for a free card. `features` is an operator-defined object (scheme, wallet\n * support, load limits, …) with no fixed keys.\n */\nexport interface CardProduct {\n id: string;\n name: string;\n /** One line under the name on the tile, or `null`. */\n tagline: string | null;\n description: string | null;\n /** Selling points to list on the product card, in order. May be empty. */\n benefits: string[];\n /**\n * Picture for the product tile, absolute URL, or `null`: show the card\n * design (`design.image_url`) then.\n */\n tile_image_url: string | null;\n card_type: CardType;\n currency: string | null;\n features: Record<string, unknown>;\n design: CardDesignRef;\n designs: CardDesignRef[];\n price: CardProductPrice | null;\n /**\n * The balance a new card comes with, already included in `price`; `null`\n * when the card starts empty and is funded with `topUp()` afterwards.\n */\n starting_balance: CardBalance | null;\n /** True for the product the deployment issues when none is chosen. */\n is_default: boolean;\n /**\n * Issuing this card sends the user's real personal details to the card\n * issuer. Show the consent screen before the order and send\n * `holder_data_transfer` in its `consents` (or give it once with\n * `client.consents.allowHolderData()`); without it the order fails with\n * 409 `holder_data_consent_required`. `false`: the issuer gets no real\n * details and no extra consent is asked.\n */\n holder_data_required: boolean;\n /**\n * What a card on this product costs to use, on top of the payments\n * themselves. A fee the card can't cover is owed and paid from the next\n * top-up (see `client.debt`). Every line is `\"0\"` when the product\n * charges nothing for it.\n */\n tariff: CardTariff;\n}\n\n/**\n * A card product's fees for using the card. Decimal strings: the fixed\n * amounts are in `currency` (the card's), the shares in percent of the\n * operation's amount.\n */\nexport interface CardTariff {\n /** `null` for a product held in several currencies: the card's own then. */\n currency: string | null;\n /** Per settled card payment, fixed. */\n operation_fixed: string;\n /** Per settled card payment, percent of its amount. */\n operation_percent: string;\n /**\n * Per payment declined through the user's own doing: not enough money,\n * wrong card details, a frozen card, a subscription not cancelled with the\n * merchant. A decline caused by the issuer or the platform costs nothing.\n */\n decline: string;\n /** Per cash withdrawal, fixed; charged instead of the payment fee. */\n cash_withdrawal_fixed: string;\n /** Per cash withdrawal, percent of its amount. */\n cash_withdrawal_percent: string;\n}\n\n/**\n * A card record as the Takeal API returns it. Mirrors the `cards` table. Note the\n * SDK never receives the full PAN or CVV here — only `last4` + expiry. The\n * gift-card `redemption_code` is returned exactly once (on create) and\n * scrubbed from subsequent list/get responses.\n */\nexport interface Card {\n id: string;\n user_id: string;\n card_type: CardType;\n status: CardStatus;\n /** Last four digits of the PAN — safe to display. Null until the card is paid for and issued. */\n last4: string | null;\n expiry_month: number | null;\n expiry_year: number | null;\n /** Gift cards only, present once on create then scrubbed. */\n redemption_code?: string;\n /** The balance the card was issued with, decimal string; `null` or `\"0\"` for a card issued empty. */\n initial_amount: string | null;\n currency: string;\n failure_reason: string | null;\n /** Who changed the status last; `null` when it never changed. See {@link CardStatusSource}. */\n status_source: CardStatusSource | null;\n /** Virtual or plastic. A `physical` card takes a PIN with {@link CardsResource.setPin}. */\n card_form: CardForm;\n /** Why the card cannot be closed right now, or `null` when it can. */\n close_blocked: CloseBlockedReason | null;\n /**\n * Top-ups the issuer has accepted and not loaded yet, summed, decimal\n * string in `currency`; `null` when there are none. It counts top-ups from\n * the wallet and top-ups paid straight to the card. Show it next to the\n * balance as money on its way to the card.\n */\n topups_pending: string | null;\n /**\n * `true` while the card's details are being prepared: the card can be\n * used and topped up, but its number can't be shown yet. Show \"Details\n * are being prepared\" instead of the reveal button and refresh the card\n * later; it turns `false` on its own, usually within minutes. Absent\n * from platforms before 0.7.6.\n */\n details_pending?: boolean;\n /**\n * Top-ups the issuer has held for too long, summed, decimal string in\n * `currency`; `null` when there are none. The money is safe and waits for\n * support to settle it; say so instead of offering a retry.\n */\n topups_held: string | null;\n /**\n * The card this one replaced: support reissued it for free because that\n * card stopped working before its term. `null` otherwise.\n */\n reissued_from_card_id?: string | null;\n /** The card support issued to replace this one, or `null`. */\n reissued_to_card_id?: string | null;\n /**\n * What was left on the card this one replaced, on its way here. Show it as\n * money in transit next to the balance, not as part of it. `null` when\n * nothing is on its way.\n */\n in_transit?: CardInTransit | null;\n /** The name the user gave the card, or `null`. */\n name: string | null;\n /** The artwork the card is shown with. Always present. */\n design: CardDesignRef;\n /** The product the card was issued from; `null` for cards issued without one. */\n product: { id: string; name: string } | null;\n created_at: string;\n updated_at: string;\n /** Only on the result of `create`, when bonuses paid part of the price. */\n bonus?: IssuanceBonus;\n}\n\n/**\n * The balance of a closed card on its way to the card that replaced it. It\n * waits for the old card's issuer to return the money (`stage: \"issuer\"`),\n * then it is loaded onto this card (`stage: \"loading\"`); once it is there,\n * `in_transit` is `null` and the card's balance has it. The move is in the\n * history as a `closed_card_balance` entry.\n */\nexport interface CardInTransit {\n /** Decimal string in `currency`. What the issuer returned once it did; before that, what the old card held. */\n amount: string;\n currency: string;\n /** The closed card the money comes from. */\n from_card_id: string;\n stage: \"issuer\" | \"loading\" | (string & {});\n}\n\n/** How bonuses changed a new card's price (\"was / now\"). Decimal strings in `currency`. */\nexport interface IssuanceBonus {\n /** Bonuses used. */\n units: string;\n /** The price before bonuses (\"was\"). */\n price: string;\n /** What the bonuses covered. */\n covered: string;\n /** What the wallet paid (\"now\"). */\n paid: string;\n currency: string;\n}\n\nexport interface CreateCardInput {\n /**\n * A product id from {@link CardsResource.listProducts}. Sent as\n * `product_id`. When given, `type` and `issuer_slug` may be omitted; when\n * both are given they must agree with the product (400 `product_mismatch`).\n * Unknown, disabled or hidden product → 400 `unknown_product`.\n */\n productId?: string;\n /** A name for the card, 1–40 characters. Sent as `name`. */\n name?: string;\n /**\n * One of the product's `designs`. Sent as `design_id`. `null` or omitted\n * picks the product's default design; a design outside the product's set →\n * 400 `design_not_allowed`.\n */\n designId?: string | null;\n /**\n * `prepaid` (the only fully-wired type today), `credit`, or `gift`.\n * Optional when `productId` is given, required otherwise.\n */\n type?: CardType;\n /**\n * @deprecated Ignored since 0.3.21. A card is issued for its product price;\n * the balance it starts with, if the product includes one, is part of that\n * price (see `CardProduct.starting_balance`). Money is added afterwards\n * with {@link CardsResource.topUp}. The field is no longer sent.\n */\n initial_amount?: string;\n /** ISO 4217 code, e.g. `\"USD\"`. */\n currency: string;\n /**\n * Optional. Slug of a specific issuer to mint with. Omit to let\n * the Takeal API pick the first active issuer. Unknown slug → 400; empty issuer\n * list → 503.\n */\n issuer_slug?: string;\n metadata?: Record<string, string>;\n /** Structured billing details — real issuers require these for 3DS / KYC. */\n customer?: CustomerInfo;\n /**\n * Pay part of the price with bonuses. Sent as `use_bonus`. On by default\n * whenever the user has bonuses; `false` pays it all from the wallet.\n */\n useBonus?: boolean;\n /** The most bonuses to use, decimal string. Sent as `bonus_amount`. */\n bonusAmount?: string;\n /**\n * A promo code for the card's price. Sent as `promo_code`. Its discount\n * comes off before bonuses; `client.codes.validate` shows it first. A code\n * that can't be used fails the request with 400 `promo_code_*` and the\n * reason. Without one, the code the user signed up with applies when it\n * covers cards. Ignored inside `deposits.initiate({ issue_card })`: send\n * `promo_code` on the top-up there.\n */\n promoCode?: string;\n /**\n * Consents the user gave with the order (`terms`, `personal_data`,\n * `marketing`, `holder_data_transfer`). Recorded with the card, or with the\n * top-up inside `deposits.initiate({ issue_card })`, at the version of\n * their documents in force now. A product with `holder_data_required`\n * needs `holder_data_transfer` here unless it was given before.\n */\n consents?: ConsentKind[];\n /** Where they were given. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\n /**\n * Required by the Takeal API on this write endpoint. Same key + body replays the\n * original card; same key + different body returns 409.\n */\n idempotencyKey: string;\n}\n\n/**\n * The wire body of a card request: the camelCase fields renamed to what\n * the API reads. Shared by {@link CardsResource.create} and the\n * `issue_card` block of `deposits.initiate`.\n */\nexport function cardRequestBody(\n input: Omit<CreateCardInput, \"idempotencyKey\" | \"currency\"> & { currency?: string },\n): Record<string, unknown> {\n const {\n productId,\n name,\n designId,\n useBonus,\n bonusAmount,\n promoCode,\n consentChannel,\n initial_amount: _ignored,\n ...rest\n } = input;\n const body: Record<string, unknown> = { ...rest };\n if (productId !== undefined) body[\"product_id\"] = productId;\n if (name !== undefined) body[\"name\"] = name;\n if (designId !== undefined) body[\"design_id\"] = designId;\n if (useBonus !== undefined) body[\"use_bonus\"] = useBonus;\n if (bonusAmount !== undefined) body[\"bonus_amount\"] = bonusAmount;\n if (promoCode !== undefined) body[\"promo_code\"] = promoCode;\n if (consentChannel !== undefined) body[\"consent_channel\"] = consentChannel;\n return body;\n}\n\n/**\n * A card bought in one step with {@link CardsResource.order}: the product and\n * how the user pays. The platform works out the amount to pay in the\n * payment's currency, locks the rate and opens the top-up that issues the\n * card.\n */\nexport interface CardOrderInput {\n /** A product id from {@link CardsResource.listProducts}. Sent as `product_id`. */\n productId: string;\n /** One of the product's designs; omit for its default. Sent as `design_id`. */\n designId?: string;\n /** A name for the card, 1 to 40 characters; defaults to the product name. */\n name?: string;\n /** How the user pays, e.g. `\"sbp\"`. */\n method: DepositMethod;\n /** The funding connector to pay through; omit to let the API pick one that takes `method`. Sent as `funder_slug`. */\n funderSlug?: string;\n /** ISO 4217 code of the payment; defaults to the currency the method is priced in. */\n currency?: string;\n /** Money to put on the card on top of its price, decimal string in the card's currency. Sent as `extra_load`. */\n extraLoad?: string;\n /** A promo code for the payment. Sent as `promo_code`. */\n promoCode?: string;\n /** Pay part of the price with bonuses; on by default. Sent as `use_bonus`. */\n useBonus?: boolean;\n /**\n * Consents given with the order. A product with `holder_data_required`\n * needs `holder_data_transfer` here unless it was given before.\n */\n consents?: ConsentKind[];\n /** Where they were given. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\n /** Passed to the payment provider; `return_url` is where the payment page sends the user back. */\n metadata?: Record<string, string>;\n /** The visitor's analytics ids for the order's server-side conversions.\n * Leave out to send the ones this browser holds (see `analyticsIds`). */\n analyticsIds?: AnalyticsIds;\n /**\n * The amount the user was shown and agreed to pay: `amount` of the\n * quote. If the order comes to anything else, no payment is opened and\n * the API answers 409 `price_changed` with the new quote (see\n * {@link priceChangedQuote}). Leave it out and the payment opens for\n * whatever the order comes to. Sent as `expected_amount`.\n */\n expectedAmount?: string;\n /** `currency` of the same quote. Sent as `expected_currency`. */\n expectedCurrency?: string;\n}\n\n/**\n * A card order to price with {@link CardsResource.quote} or\n * {@link CardsResource.quotePublic}: the same fields as the order.\n */\nexport interface CardOrderQuoteInput {\n /** Sent as `product_id`. */\n productId: string;\n /** Sent as `design_id`. */\n designId?: string;\n method: DepositMethod;\n /** Sent as `funder_slug`. */\n funderSlug?: string;\n currency?: string;\n /** Sent as `extra_load`. */\n extraLoad?: string;\n /** The code the user typed. Sent as `promo_code`. */\n promoCode?: string;\n /** Signed in only: pay part of the price with bonuses, on by default. Sent as `use_bonus`. */\n useBonus?: boolean;\n}\n\n/**\n * Where a promo code stands in a quote. `applied`: its discount is in the\n * amount. `conditional` (before sign-in only): it works for someone who\n * meets `conditions`, which are checked after sign-in, and the amount is\n * provisional. `rejected`: it can't be used, for `reason`; an order that\n * keeps the code is refused, so drop it from the order. `unavailable`: it\n * couldn't be checked right now; the amount is without it.\n */\nexport type PromoCodeStatus = \"applied\" | \"conditional\" | \"rejected\" | \"unavailable\";\n\n/** What a promo code does to a card order. */\nexport interface PromoCodeQuote {\n /** The code as stored, or as typed when it wasn't found. */\n code: string;\n status: PromoCodeStatus;\n /** For `rejected`. */\n reason: CodeRejection | null;\n /**\n * For `conditional`: `not_first_operation` (first card only) or\n * `own_code` (not for the person it belongs to).\n */\n conditions: CodeRejection[];\n /** A sentence to show next to the code, in English. Null when the discount says it all. */\n message: string | null;\n /**\n * The discount and what it comes off: `card_issuance` (the card's price,\n * in `discount` of the quote) or `funding_commission` (the payment's\n * commission: the amount stays the same and more goes onto the card).\n */\n discount: CodeDiscount | null;\n /** What else the code gives, once the card is issued. */\n effects: CodeEffect[];\n /** The code the user signed up with, applied without being typed. */\n from_sign_up: boolean;\n}\n\n/** What a card order would cost now, from {@link CardsResource.quote} or {@link CardsResource.quotePublic}. */\nexport interface CardOrderQuote {\n /** What the user pays, decimal string, in `currency`. Pass it to the order as `expectedAmount`. */\n amount: string;\n /** Pass it to the order as `expectedCurrency`. */\n currency: string;\n /** The same order without the promo code, decimal string, in `currency`. */\n price: string;\n /** `price` less `amount`: what the code takes off. `\"0\"` without one. */\n discount: string;\n /** What the payment brings, in `card_currency`, as in {@link CardOrder}. */\n card_amount: string;\n card_currency: string;\n /** Card fees owed, in `card_currency`, included in `card_amount`. Always `\"0\"` before sign-in. */\n debt_withheld: string;\n /** Bonuses that pay part of the price; null before sign-in. */\n bonus_units: string | null;\n /** The amount may still change after sign-in: show it as provisional. */\n preliminary: boolean;\n /** Null when no code was typed and none applies by itself. */\n promo_code: PromoCodeQuote | null;\n}\n\n/** What {@link CardsResource.order} returns: the top-up to pay and its price. */\nexport interface CardOrder {\n /** Send the user to `deposit.redirect_url` when `deposit.status` is `redirect_required`. The card is issued once the payment is confirmed. */\n deposit: Deposit;\n /** What the user pays, decimal string, in `currency`. */\n amount: string;\n currency: string;\n /** What the payment brings: the card's price, what goes onto the card and `debt_withheld`, in `card_currency`. A payment in the price's own currency pays the price as it is set; only the rest is converted. */\n card_amount: string;\n card_currency: string;\n /**\n * What the user owes in card fees, in `card_currency`: included in\n * `card_amount` and paid from it first. `\"0\"` when nothing is owed. Show\n * it before the payment. Older platforms leave it out.\n */\n debt_withheld?: string;\n}\n\n/** Why a card ordered with the sign-up was not placed. The account exists all the same. */\nexport interface CardOrderError {\n code: string;\n message: string;\n /** With `code: \"price_changed\"`: what the card costs now. */\n quote?: CardOrderQuote;\n}\n\n/**\n * The new quote of an order that opened no payment because its price\n * changed (`price_changed`), from either a thrown {@link ApiError} of\n * {@link CardsResource.order} or the `card_order_error` of a sign-in.\n * Show its amount; once the user agrees, send the order again with\n * `expectedAmount` set to it. `undefined` for any other error.\n */\nexport function priceChangedQuote(error: unknown): CardOrderQuote | undefined {\n const body = isApiError(error) ? error.body : error;\n if (typeof body !== \"object\" || body === null) return undefined;\n const { code, quote } = body as { code?: unknown; quote?: unknown };\n if (code !== \"price_changed\" || typeof quote !== \"object\" || quote === null) return undefined;\n return quote as CardOrderQuote;\n}\n\n/** Build the API body of a card order quote. */\nexport function cardOrderQuoteBody(input: CardOrderQuoteInput): Record<string, unknown> {\n const body: Record<string, unknown> = {\n product_id: input.productId,\n method: input.method,\n };\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n if (input.funderSlug !== undefined) body[\"funder_slug\"] = input.funderSlug;\n if (input.currency !== undefined) body[\"currency\"] = input.currency;\n if (input.extraLoad !== undefined) body[\"extra_load\"] = input.extraLoad;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.useBonus !== undefined) body[\"use_bonus\"] = input.useBonus;\n return body;\n}\n\n/** Build the API body of a card order. */\nexport function cardOrderBody(input: CardOrderInput): Record<string, unknown> {\n const body: Record<string, unknown> = {\n product_id: input.productId,\n method: input.method,\n };\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n if (input.name !== undefined) body[\"name\"] = input.name;\n if (input.funderSlug !== undefined) body[\"funder_slug\"] = input.funderSlug;\n if (input.currency !== undefined) body[\"currency\"] = input.currency;\n if (input.extraLoad !== undefined) body[\"extra_load\"] = input.extraLoad;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.useBonus !== undefined) body[\"use_bonus\"] = input.useBonus;\n if (input.consents !== undefined) body[\"consents\"] = input.consents;\n if (input.consentChannel !== undefined) body[\"consent_channel\"] = input.consentChannel;\n if (input.metadata !== undefined) body[\"metadata\"] = input.metadata;\n const ids = input.analyticsIds ?? analyticsIds();\n if (ids !== undefined) body[\"analytics_ids\"] = ids;\n if (input.expectedAmount !== undefined) body[\"expected_amount\"] = input.expectedAmount;\n if (input.expectedCurrency !== undefined) body[\"expected_currency\"] = input.expectedCurrency;\n return body;\n}\n\n/** Remaining balance of a prepaid card. */\nexport interface CardBalance {\n amount: string;\n currency: string;\n /**\n * From `cards.balance()` only: top-ups the issuer has accepted and not\n * confirmed yet, summed, decimal string in `currency`; `null` when there\n * are none. Not part of `amount`, even when the issuer already shows the\n * money: show it next to the balance as on its way.\n */\n pending?: string | null;\n}\n\n/** What a top-up of a card can be right now, from `GET /me/cards/{id}/topup`. */\nexport interface TopUpTerms {\n /** Whether the card can be topped up at this moment. */\n available: boolean;\n /** Why not, in plain words, when `available` is false. */\n reason: string | null;\n /** Currency top-ups are made in: the card's. */\n currency: string;\n /** What the wallet holds right now, in the wallet's currency. */\n wallet_available: CardBalance;\n /** Smallest single top-up the product allows, or `null` for no floor. */\n min: CardBalance | null;\n /** Largest single top-up the product allows, or `null` for no cap. */\n max: CardBalance | null;\n /**\n * What the user owes in card fees, in the card's currency, or `null` when\n * nothing is. A top-up from a wallet in the same currency pays it first\n * and the card gets the rest: show it before the top-up. Older platforms\n * leave it out.\n */\n debt?: CardBalance | null;\n}\n\nexport interface TopUpInput {\n /** Amount to add, decimal string, in the card's currency. */\n amount: string;\n /**\n * Required. Same key + same amount replays the first outcome; same key +\n * different amount is 409. Use a stable UUID per attempt so a retried\n * network call cannot move the money twice.\n */\n idempotencyKey: string;\n}\n\n/**\n * Where a top-up stands.\n *\n * - `pending`: the issuer accepted it and has not loaded the card yet. The\n * wallet is debited, the card balance is unchanged, the amount shows in\n * `Card.topups_pending`. Most issuers finish within minutes.\n * - `confirmed`: the money is on the card.\n * - `failed`: the issuer refused; the wallet is credited back.\n * - `stalled`: pending for longer than the deployment allows. The money is\n * safe and waits for support; it shows in `Card.topups_held`.\n * - `returned`: support sent the money back to the wallet.\n * - `written_off`: support closed it without the money coming back (the\n * issuer kept it); `failure_reason` says so.\n */\nexport type CardTopUpStatus =\n \"pending\" | \"confirmed\" | \"failed\" | \"stalled\" | \"returned\" | \"written_off\";\n\n/** One top-up attempt as the API records it. */\nexport interface CardTopUp {\n id: string;\n card_id: string;\n status: CardTopUpStatus;\n /** What landed on the card, decimal string, in `currency`. */\n amount: string;\n currency: string;\n /** What the wallet paid, decimal string, in `wallet_currency`. */\n wallet_amount: string;\n wallet_currency: string;\n failure_reason: string | null;\n created_at: string;\n updated_at: string;\n}\n\n/**\n * The outcome of a top-up with the state to redraw: card, its balance, the\n * wallet. When `topup.status` is `pending`, the wallet has paid and\n * `card_balance` has not moved yet: show the amount as on its way\n * (`card.topups_pending`) and refresh the card later or on the\n * `card_topup` notification.\n */\nexport interface TopUpResult {\n topup: CardTopUp;\n card: Card;\n card_balance: CardBalance;\n wallet: CardBalance;\n}\n\n/** Fields a user can change on their own card. Omitted fields are left as they are. */\nexport interface UpdateCardInput {\n /** New name, 1–40 characters. Sent as `name`. */\n name?: string;\n /**\n * New design (one of the product's `designs`), or `null` for the product's\n * default. Sent as `design_id`.\n */\n designId?: string | null;\n}\n\n/**\n * Kept for callers written against 0.3.x: the API no longer asks for a\n * password or a code on reveal, the session is enough. Both fields are\n * ignored and will be dropped in the next major.\n * @deprecated\n */\nexport interface RevealCardInput {\n password?: string;\n totpCode?: string;\n}\n\n/**\n * What a reveal gave, so a client can switch on one field:\n *\n * - `numbers`: `pan`, `cvv` and the expiry are filled in;\n * - `page`: the issuer shows the numbers on a page of its own, `reveal_url`\n * is set and `pan` and `cvv` are empty;\n * - `pending`: the card's details are still being prepared, nothing else\n * is filled in. Show \"Details are being prepared\" and try again in a\n * minute or two; the attempt didn't count against the reveal limit.\n */\nexport type RevealState = \"numbers\" | \"page\" | \"pending\";\n\n/**\n * Full card data from a successful reveal. **Security**: never persist this,\n * keep it in volatile memory only, clear it within `expires_in_seconds`, and\n * never write it to localStorage / logs (the API marks the response no-store).\n *\n * `state` says which of three answers this is (see {@link RevealState}).\n * Some issuers hand out a page that shows the numbers instead of the\n * numbers themselves; for some cards the details are still being prepared\n * right after issuance.\n */\nexport interface RevealedCard {\n /** Which answer this is; set by the SDK from the fields below. */\n state: RevealState;\n /** The card number; empty when `reveal_url` is set. */\n pan: string;\n /** The security code; empty when `reveal_url` is set. */\n cvv: string;\n expiry_month: number;\n expiry_year: number;\n holder_name: string;\n /**\n * A page at the card issuer that shows the details to the holder. Present\n * only for issuers that give a page instead of the numbers. Short-lived,\n * often single use: open it at once in an `<iframe>` and never store it.\n */\n reveal_url?: string;\n /**\n * The person the card is registered to at its issuer: what a checkout\n * asks for. Absent for cards issued before holders were kept.\n */\n cardholder?: Cardholder;\n /**\n * The address the card is registered at — what a merchant's checkout asks\n * for, and the postal code some of them decline a payment over. Absent\n * when the deployment has not set one.\n */\n billing_address?: BillingAddress;\n /** Display window before the client should auto-clear the data. */\n expires_in_seconds: number;\n /**\n * `true` when the details are still being prepared (`state: \"pending\"`).\n * Absent from platforms before 0.7.6.\n */\n details_pending?: boolean;\n}\n\n/** The three answers of a reveal told apart; see {@link RevealState}. */\nexport function revealState(r: Omit<RevealedCard, \"state\">): RevealState {\n if (r.details_pending) return \"pending\";\n if (r.reveal_url) return \"page\";\n return \"numbers\";\n}\n\n/** Postal address a card is registered at. Which parts exist depends on the country. */\nexport interface BillingAddress {\n line1?: string;\n line2?: string;\n city?: string;\n state?: string;\n postal_code?: string;\n country?: string;\n}\n\n/**\n * The cardholder the issuer knows: the details to type into a checkout\n * that asks for the name, phone or address on the card. `source` says\n * whether the platform made them up (`generated`), the user supplied them\n * (`provided`) or both (`mixed`).\n */\nexport interface Cardholder {\n id: string;\n first_name: string;\n last_name: string;\n /** `YYYY-MM-DD`. */\n birth_date: string;\n /** E.164. */\n phone: string;\n /** A mailbox the platform owns; mail the issuer sends there reaches the user. */\n email: string;\n address: BillingAddress;\n source: \"generated\" | \"provided\" | \"mixed\";\n}\n\n/** The new PIN for a physical card. */\nexport interface SetPinInput {\n /**\n * Four to six digits, as the user typed them. Sent once to the issuer and\n * kept nowhere: not by the SDK, not by the API. Never log it.\n */\n pin: string;\n}\n\n/** What to move, and the key that makes a retry safe. */\nexport interface TransferInput {\n /** The card the money lands on. Must be the caller's, and of the same kind and currency. */\n toCardId: string;\n /** Amount to move, decimal string, in the cards' currency. */\n amount: string;\n /**\n * Required. The same key with the same body replays the first outcome; a\n * different body on the same key is 409.\n */\n idempotencyKey: string;\n}\n\n/** One transfer attempt as the API records it. */\nexport interface CardTransfer {\n id: string;\n from_card_id: string;\n to_card_id: string;\n /**\n * `confirmed` — the money is on the other card. `on_wallet` — it came off\n * the first card but the second did not take it, so it is on the wallet\n * and `failure_reason` says so in words. `pending` / `failed` otherwise.\n */\n status: \"pending\" | \"confirmed\" | \"on_wallet\" | \"failed\";\n amount: string;\n currency: string;\n failure_reason: string | null;\n created_at: string;\n updated_at: string;\n}\n\n/** A finished transfer with the balances to redraw both cards and the wallet. */\nexport interface TransferResult {\n transfer: CardTransfer;\n from_balance: CardBalance;\n to_balance: CardBalance;\n /** Holds the money when `transfer.status` is `on_wallet`. */\n wallet: CardBalance;\n}\n\nexport class CardsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Issue a card backed by the user's wallet balance. Resolves to the new\n * `Card`. On a ledger failure after provider creation, the Takeal API rolls the row\n * to `failed` (never an orphaned active card); inspect `status` /\n * `failure_reason` on the result.\n * Errors: 409 `holder_data_consent_required` when the product has\n * `holder_data_required` and the user has not agreed to it.\n */\n async create(input: CreateCardInput): Promise<Card> {\n const { idempotencyKey, ...card } = input;\n return this.http.post<Card>(\"/me/cards\", {\n body: cardRequestBody(card),\n idempotencyKey,\n });\n }\n\n /**\n * Buy a card in one step: the API prices the product in the payment's\n * currency, locks the rate and opens the top-up that issues the card.\n * Send the user to `order.deposit.redirect_url`; the card shows as\n * `pending_payment` until the payment is confirmed. The same\n * `idempotencyKey` returns the same order.\n * Errors: 400 `unknown_product` / `method_not_available` / a limit of the\n * way of paying, 409 `holder_data_consent_required` (the product has\n * `holder_data_required` and the user has not agreed to it), 409\n * `payments_on_hold` (a payment on this account was not accepted and new\n * ones wait until support sorts it out: show the message and point the\n * user to support), 409 `price_changed` (the order came to another amount\n * than `expectedAmount`; no payment was opened, and\n * {@link priceChangedQuote} gives the new quote), 503 no funding connector\n * or no exchange rate.\n */\n async order(input: CardOrderInput & { idempotencyKey: string }): Promise<CardOrder> {\n const { idempotencyKey, ...order } = input;\n return this.http.post<CardOrder>(\"/me/card-orders\", {\n body: cardOrderBody(order),\n idempotencyKey,\n });\n }\n\n /**\n * What an order of this card would cost the signed-in user now, with the\n * promo code: the same calculation {@link order} makes, with every\n * condition of the code checked. Nothing is reserved or used up. Pass\n * `amount` and `currency` to the order as `expectedAmount` and\n * `expectedCurrency`.\n */\n async quote(input: CardOrderQuoteInput): Promise<CardOrderQuote> {\n return this.http.post<CardOrderQuote>(\"/me/card-orders/quote\", {\n body: cardOrderQuoteBody(input),\n });\n }\n\n /**\n * The same quote before sign-in, for a landing page or the purchase form\n * before the e-mail code. Prices are list prices, and a code whose\n * conditions depend on the person (first card only, say) comes back\n * `conditional`, with `preliminary` set. Send `expectedAmount` with the\n * order placed at sign-in: if the price turns out different, no payment\n * is opened and `card_order_error` carries the new quote. The API limits\n * how often one address can ask (429 `too_many_requests`).\n */\n async quotePublic(input: Omit<CardOrderQuoteInput, \"useBonus\">): Promise<CardOrderQuote> {\n return this.http.post<CardOrderQuote>(\"/card-orders/quote\", {\n body: cardOrderQuoteBody(input),\n skipAuth: true,\n });\n }\n\n /**\n * The cards the caller can order, in the order the storefront shows them\n * (`is_default` marks the one issued when none is chosen). Each item\n * carries its product card (name, tagline, benefits, tile picture),\n * artwork, and the issuance price after the caller's subscription\n * discount, in the currency the operator set it in (`price.from_wallet`\n * is the same price from the wallet, when that holds another currency).\n * Pass an item's `id` as\n * `productId` to {@link create}.\n */\n async listProducts(): Promise<CardProduct[]> {\n return this.http.get<CardProduct[]>(\"/me/card-products\");\n }\n\n /** One product from the catalog. 404 when unknown, disabled or hidden. */\n async getProduct(id: string): Promise<CardProduct> {\n return this.http.get<CardProduct>(`/me/card-products/${encodeURIComponent(id)}`);\n }\n\n /**\n * The public catalog: the same products, order and default as\n * {@link listProducts}, but readable before sign-in, for a landing page or\n * the cabinet's first screen. Prices are list prices (`discount_bps` is\n * always 0); once the user is signed in, {@link listProducts} shows what\n * they pay. The API lets caches keep this response for a minute.\n */\n async catalog(): Promise<CardProduct[]> {\n return this.http.get<CardProduct[]>(\"/card-products\");\n }\n\n /**\n * Rename the caller's own card or change its design. Resolves to the\n * updated card. 404 if the card isn't the caller's; 400 `invalid_name` /\n * `design_not_allowed` on a bad value.\n */\n async update(id: string, input: UpdateCardInput): Promise<Card> {\n const body: Record<string, unknown> = {};\n if (input.name !== undefined) body[\"name\"] = input.name;\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n return this.http.patch<Card>(`/me/cards/${encodeURIComponent(id)}`, {\n body,\n });\n }\n\n /** Fetch one card by id. */\n async get(id: string): Promise<Card> {\n return this.http.get<Card>(`/me/cards/${encodeURIComponent(id)}`);\n }\n\n /** List the caller's cards, most recent first. */\n async list(): Promise<Card[]> {\n return this.http.get<Card[]>(\"/me/cards\");\n }\n\n /**\n * Remaining balance of a prepaid card. `currency` is required by the Takeal API and\n * forwarded as a query param.\n */\n async balance(id: string, currency: string): Promise<CardBalance> {\n const q = new URLSearchParams({ currency }).toString();\n return this.http.get<CardBalance>(`/me/cards/${encodeURIComponent(id)}/balance?${q}`);\n }\n\n /**\n * What a top-up of this card can be right now: whether it is possible, the\n * currency, the wallet balance, and the product's floor and cap for one\n * top-up. Read it before drawing the form. 404 if the card isn't the caller's.\n */\n async topUpTerms(id: string): Promise<TopUpTerms> {\n return this.http.get<TopUpTerms>(`/me/cards/${encodeURIComponent(id)}/topup`);\n }\n\n /**\n * Move money from the wallet onto the caller's own card. The wallet is\n * debited first, then the card's provider loads the card; if the provider\n * refuses, the money is back on the wallet and the error says so. Resolves\n * to the card, its new balance and the wallet balance, so no second call\n * is needed. Errors carry a sentence the user can read: 400 outside the\n * floor or cap · 402 not enough in the wallet · 404 not the caller's card ·\n * 409 card frozen, closed or still being issued · 501 provider can't top\n * up · 502/503 provider declined or unreachable (wallet untouched).\n */\n async topUp(id: string, input: TopUpInput): Promise<TopUpResult> {\n const { idempotencyKey, amount } = input;\n return this.http.post<TopUpResult>(`/me/cards/${encodeURIComponent(id)}/topup`, {\n body: { amount },\n idempotencyKey,\n });\n }\n\n /**\n * Move money from one of the caller's cards to another. Both must be\n * theirs, active, in the same currency and of the same kind. The money\n * travels through the wallet one leg at a time: when the second leg does\n * not go through, the call still resolves, `transfer.status` is\n * `on_wallet` and the money is on the wallet — never between two cards.\n * Errors carry a sentence the user can read: 400 the same card twice,\n * different currencies or different kinds · 402 the card holds less than\n * that · 404 one of the cards isn't theirs · 409 a card is frozen, closed\n * or still being issued, or the key was reused with a different body ·\n * 501/502/503 the provider cannot or will not move it.\n */\n async transfer(fromCardId: string, input: TransferInput): Promise<TransferResult> {\n const { toCardId, amount, idempotencyKey } = input;\n return this.http.post<TransferResult>(`/me/cards/${encodeURIComponent(fromCardId)}/transfer`, {\n body: { to_card_id: toCardId, amount },\n idempotencyKey,\n });\n }\n\n /**\n * Freeze the caller's own card. Reversible via {@link unfreeze} while\n * `status_source` is `holder` or `operator`. The optional `reason` is\n * recorded on the audit trail. Resolves to the updated card. 404 if the\n * card isn't the caller's; 409 `card_locked` when support holds it; 501 if\n * the issuer can't freeze.\n */\n async freeze(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/freeze`, { body: { reason } });\n }\n\n /**\n * Reveal the FULL PAN + CVV for the caller's own card. The signed-in\n * session is all the API asks for; the call is rate-limited and audited\n * server-side. The Takeal API never persists this data and marks the\n * response no-store; the SDK returns it verbatim and holds nothing.\n *\n * **Consumer security duties** (the SDK can't enforce these for you):\n * keep the result in volatile memory only, never write it to\n * localStorage / logs, and clear it within `expires_in_seconds`.\n *\n * `state` tells the three answers apart: `numbers`; `page`, with\n * `reveal_url` and empty `pan` and `cvv` when the issuer shows them on a\n * page of its own (open that page in a frame right away, it is\n * short-lived); or `pending` while the card's details are still being\n * prepared, which doesn't count against the limit. A card says the same\n * in {@link Card.details_pending}, so there is no need to call this just\n * to find out.\n *\n * 403 not your card · 409 `card_locked` · 429 rate-limited · 501 connector\n * has no sensitive-data endpoint · 503 `provider_unavailable`.\n */\n async reveal(id: string, _input?: RevealCardInput): Promise<RevealedCard> {\n const r = await this.http.post<Omit<RevealedCard, \"state\">>(\n `/me/cards/${encodeURIComponent(id)}/reveal`,\n );\n return { ...r, state: revealState(r) };\n }\n\n /**\n * Unfreeze a previously-frozen card. Idempotent on an already-active card.\n * A card the issuer froze (`status_source: \"provider\"`) is not the\n * holder's to unfreeze: the API answers 409 `card_locked`, so hide the\n * button and say the freeze is lifted through the issuer's support.\n */\n async unfreeze(id: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/unfreeze`, { body: {} });\n }\n\n /**\n * Report the card lost or stolen. Works at any time, on an active or a\n * frozen card. The report is recorded first with the server's time, which\n * decides who pays for operations someone else made; then the card is\n * frozen at its issuer and only support can unfreeze it. Resolves to the\n * claim (`client.claims`): show its `number` and `reported_at`. When the\n * issuer can't be reached, `card_freeze` is `\"pending\"`: the report still\n * counts and support freezes the card by hand. Reporting again while the\n * report is open returns the same claim. 404 / 403 not the user's card ·\n * 409 `card_not_open`: the card is closed or was never issued.\n */\n async reportLost(\n id: string,\n input: { kind: \"lost\" | \"stolen\"; details?: string },\n ): Promise<Claim> {\n return this.http.post<Claim>(`/me/cards/${encodeURIComponent(id)}/report-lost`, {\n body: { kind: input.kind, details: input.details },\n });\n }\n\n /**\n * Set the PIN of the caller's own physical card. The session is enough; the\n * call is rate-limited like {@link reveal} and the PIN is kept nowhere.\n * Resolves to the card; the user also gets a notification that the PIN\n * was set. 400 not four to six digits or the card is not active · 403 not\n * your card · 409 `card_locked`, or `provider_refused` when the issuer did\n * not take it · 429 too many attempts · 501 a virtual card has no PIN.\n */\n async setPin(id: string, input: SetPinInput): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/pin`, {\n body: { pin: input.pin },\n });\n }\n\n /**\n * Terminate the caller's own card. **One-way** — a terminated card cannot be\n * reactivated. The optional `reason` is audited. Idempotent on an\n * already-terminated card. A card that still holds money is refused (409\n * `move_balance_first` or `contact_support_to_close`): close it with\n * `client.closeRequests.request(id)` instead, and the money goes back the\n * way it was paid.\n */\n async terminate(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/terminate`, {\n body: { reason },\n });\n }\n}\n","import type { ConsentChannel, ConsentKind } from \"./consents.js\";\nimport type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\nimport { withAnalyticsIds, type SignupAttribution } from \"./attribution.js\";\nimport type { CodeResult } from \"./codes.js\";\nimport {\n cardOrderBody,\n type CardOrder,\n type CardOrderError,\n type CardOrderInput,\n} from \"./cards.js\";\n\n/**\n * Auth resource — `client.auth.*`.\n *\n * Covers the end-user-facing staged auth flow: password login\n * with optional TOTP/OTP step-up, and signing in (or up) with a code sent\n * to the e-mail, no password. The shape mirrors the responses\n * the Takeal API returns from `/auth/login`, `/auth/login/totp`,\n * `/auth/login/otp/verify`, `/auth/login/2fa/switch`, and `/auth/me`.\n *\n * The login methods stash the JWT in the configured `TokenStore` on\n * success so subsequent `client.*` calls authenticate automatically.\n * Step-up responses (TotpRequired / OtpSent) carry their own short-\n * lived challenge token which the caller passes to the next method\n * — those tokens DO NOT go through the TokenStore (they're not the\n * end-state JWT).\n */\n\nexport interface User {\n id: string;\n email: string;\n role: string;\n is_active: boolean;\n /** True for users auto-provisioned via the Telegram Mini App who still hold\n * a synthetic placeholder email. The client should prompt for a real email\n * and attach it via `auth.linkEmail` — this flips the flag to false. */\n email_pending?: boolean;\n created_at: string;\n updated_at: string;\n /** ISO 4217 code the user's wallet is held in (their own choice, else the\n * deployment default). Present on `GET /auth/me`. */\n wallet_currency?: string;\n /** The Telegram account linked to this user, or `null` when none is.\n * Present on `GET /auth/me` and inside every `stage: \"jwt\"` envelope. */\n telegram?: TelegramLink | null;\n /** Whether the account has a password. `false` for an account that signs\n * in with codes only: offer \"set a password\"\n * ({@link AuthResource.requestPasswordSetup}) instead of \"change password\"\n * ({@link AuthResource.changePassword}). Present on `GET /auth/me` and\n * inside every `stage: \"jwt\"` envelope from platform 0.8.2; absent on\n * older servers. */\n has_password?: boolean;\n}\n\n/** A Telegram account attached to a user. One Telegram per account and one\n * account per Telegram. */\nexport interface TelegramLink {\n /** Telegram username without the `@`, or `null` when the user has none. */\n username: string | null;\n /** When the link was made, ISO-8601. */\n linked_at: string;\n}\n\nexport interface ExchangeTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n /** Analytics ids for a new account. The Telegram id is the anonymous key\n * here, and a `startapp` code in `initData` is read by the server. */\n attribution?: SignupAttribution;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false` the exchange resolves to\n * `{ stage: \"unknown\" }` instead, so the app can offer \"create an account\"\n * or \"I already have one\". */\n provision?: boolean;\n /** A promo or referral code for a new account. Without it the server\n * reads the `startapp` of the link the Mini App was opened with, when\n * that is a code. The result comes back as `code_result`. */\n code?: string;\n /** Consents for a new account, as in `register`. Sent as `consents`;\n * ignored for an account that already exists. */\n consents?: ConsentKind[];\n /** Sent as `consent_channel`; the server takes `miniapp` when omitted. */\n consentChannel?: ConsentChannel;\n}\n\n/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has\n * signed in with yet. No account was created and no JWT was stored. */\nexport interface TelegramUnknown {\n stage: \"unknown\";\n}\n\nexport interface LinkTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n email: string;\n password: string;\n}\n\nexport interface LoginInput {\n email: string;\n password: string;\n /** Keep this browser signed in: the SDK stores the remember token it gets\n * and renews the session by itself when it ends. For accounts with a\n * second factor, pass it again to `verifyTotp` / `verifyOtp` /\n * `completeTotpSetup`. */\n remember?: boolean;\n}\n\n/** Discriminated union — `stage` is the discriminator. */\nexport type LoginResponse = JwtIssued | TotpRequired | TotpSetupEmailRequired | TotpSetupRequired;\n\nexport interface JwtIssued {\n stage: \"jwt\";\n access_token: string;\n expires_at: string;\n user: User;\n /** `exchangeTelegram` for a new account opened with a code (`startapp`\n * or `code`): whether it was applied and what it gave. */\n code_result?: CodeResult;\n /** Present when the sign-in was remembered. The SDK keeps it in the\n * remember store; you don't need to. */\n remember_token?: string;\n remember_expires_at?: string;\n /** True iff the user's role grants `system.view_hub`.\n * Cusfront ignores this; the operator console uses it to gate `/dashboard`. */\n hub_access?: boolean;\n}\n\nexport interface TotpRequired {\n stage: \"totp_required\";\n challenge_token: string;\n expires_at: string;\n /** Alternate second factors. Pick one with `/2fa/switch`. */\n available_methods: AvailableMethod[];\n}\n\n/** A staff account is about to connect an authenticator: its first one, or\n * a new one after a backup code. The password alone is not enough, so a\n * six-digit code went to the account's e-mail first and no secret exists\n * yet. Send the code with {@link AuthResource.confirmTotpSetupEmail}; the\n * answer is `totp_setup_required` with the QR. Needs platform 0.8.4; older\n * servers answer `totp_setup_required` straight away. */\nexport interface TotpSetupEmailRequired {\n stage: \"totp_setup_email_required\";\n challenge_token: string;\n /** When the challenge ends; sign in again after that. */\n challenge_expires_at: string;\n /** Where the code went, partly hidden: `al***@example.com`. */\n destination_hint: string;\n /** When this code stops working. */\n code_expires_at: string;\n}\n\n/** The `code` of an `ApiError` from the e-mail step before an\n * authenticator is connected (`login`, `verifyTotp` with a backup code,\n * `confirmTotpSetupEmail`, `resendTotpSetupEmail`):\n * - `email_required` (409): the account has no e-mail address; an\n * administrator has to add one;\n * - `too_many_requests` (429): five codes went out in the last hour;\n * - `delivery_failed` (503): the code could not be sent, try again;\n * - `invalid_code` (401): wrong, expired, used or replaced code;\n * - `sign_in_again` (409): the account changed while the code was on its\n * way (its address, or an authenticator was connected meanwhile);\n * - `too_many_attempts` (429): locked after too many wrong codes. */\nexport type TotpSetupEmailErrorCode =\n | \"email_required\"\n | \"too_many_requests\"\n | \"delivery_failed\"\n | \"invalid_code\"\n | \"sign_in_again\"\n | \"too_many_attempts\";\n\nexport interface TotpSetupEmailInput {\n /** From the `totp_setup_email_required` answer. */\n challenge_token: string;\n /** The six digits from the e-mail. */\n code: string;\n}\n\nexport interface TotpSetupRequired {\n stage: \"totp_setup_required\";\n challenge_token: string;\n expires_at: string;\n /** OTPAuth URI rendered as a QR by the consumer. */\n otpauth_url: string;\n /** Same secret base32-encoded — for manual entry alongside QR. */\n secret_base32: string;\n}\n\nexport interface AvailableMethod {\n kind: \"totp\" | \"telegram_otp\" | \"email_otp\";\n /** Short user-facing hint, e.g. `\"Telegram (@user)\"` or `\"e****@example.com\"`. */\n hint?: string;\n}\n\nexport interface TotpVerifyInput {\n challenge_token: string;\n /** 6-digit TOTP code OR `XXXX-XXXX` backup code. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface SwitchMethodInput {\n challenge_token: string;\n method: AvailableMethod[\"kind\"];\n}\n\nexport interface RegisterInput {\n email: string;\n password: string;\n /** ISO 4217 code for the new wallet; must be offered by the deployment. */\n wallet_currency?: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Where the new user came from: the anonymous key their visits were\n * sent with (`client.attribution.touch`) and the analytics ids. Without\n * it the account is recorded with an unknown source. */\n attribution?: SignupAttribution;\n /** A promo or referral code. An unknown or expired code doesn't stop the\n * sign-up: the account is created and `code_result` says why the code\n * was not applied, so the app can show it. */\n code?: string;\n /** The boxes the user ticked: `terms` (offer, tariffs and privacy policy),\n * `personal_data`, `marketing`. A deployment can require the first two\n * (400 `consents_required` without them). */\n consents?: ConsentKind[];\n /** Where they were ticked. Read from the client header when omitted. */\n consent_channel?: ConsentChannel;\n /** Buy this card right after signing up, as `cards.order` would. The\n * sign-up's consents go with the order. The result then carries\n * `card_order` (send the user to its `deposit.redirect_url`) or, when the\n * order could not be placed, `card_order_error`; the account is created\n * either way. */\n cardOrder?: Omit<CardOrderInput, \"consents\" | \"consentChannel\">;\n}\n\nexport interface RequestEmailCodeInput {\n email: string;\n /** Language of the e-mail when the address has no account yet (`ru`,\n * `en`, …). An account's own language wins; without either the server\n * reads the browser's. */\n locale?: string;\n}\n\n/** What `requestEmailCode` returns. The same for an address with an account\n * and one without. */\nexport interface EmailCodeSent {\n /** Send it back with the code to `verifyEmailCode`. */\n challenge_id: string;\n /** When the code stops working, ISO-8601. */\n expires_at: string;\n /** When another code can be asked for, ISO-8601: keep \"send again\" off\n * until then. */\n resend_at: string;\n}\n\nexport interface VerifyEmailCodeInput {\n /** From `requestEmailCode`. Sent as `challenge_id`. */\n challengeId: string;\n /** The six digits from the e-mail. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Wallet currency for a new account; ignored for an existing one. Sent\n * as `wallet_currency`. */\n walletCurrency?: string;\n /** Where a new user came from, as in `register`. */\n attribution?: SignupAttribution;\n /** A promo or referral code for a new account, as `code` in `register`.\n * One that covers cards also lowers the price of `cardOrder`. Sent as\n * `promo_code`; the result comes back as `code_result`. */\n promoCode?: string;\n /** The boxes ticked on the form. A new account records them with its\n * sign-up and the card order with itself. A deployment can require\n * `terms` and `personal_data` for a new account: 400\n * `consents_required`, and the same code works again with them. */\n consents?: ConsentKind[];\n /** Where they were ticked. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\n /** Buy this card right after signing in, as `cards.order` would, with\n * the consents above. The result carries `card_order` (send the user to\n * its `deposit.redirect_url`) or `card_order_error` when no payment was\n * opened; the sign-in stands either way. Set `expectedAmount` and\n * `expectedCurrency` from `cards.quotePublic`: when the price after\n * sign-in differs (a code for first cards only, say),\n * `card_order_error.code` is `price_changed` and its `quote` holds the\n * new price. Show it, and once the user agrees, order with\n * `cards.order` and the new `expectedAmount`. */\n cardOrder?: Omit<CardOrderInput, \"consents\" | \"consentChannel\">;\n}\n\n/** What `verifyEmailCode` returns: a `stage: \"jwt\"` session, plus whether\n * the account was made just now and the card order. */\nexport type EmailCodeSession = JwtIssued & {\n /** `true` when the address had no account and got one with this code. */\n account_created: boolean;\n /** `true` when this code proved the mailbox of an existing account for\n * the first time and the password and linked sign-ins set before that\n * were removed. */\n credentials_reset?: boolean;\n card_order?: CardOrder;\n card_order_error?: CardOrderError;\n};\n\n/** What `requestEmailChange` returns: send `challenge_id` back with the code. */\nexport interface EmailChangeRequested {\n challenge_id: string;\n /** Where the code went, partly hidden: `al***@example.com`. */\n destination_hint: string;\n expires_at: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. With a `code`, `code_result` is set; with a\n * `cardOrder`, `card_order` or `card_order_error`. */\nexport type Session = Omit<JwtIssued, \"stage\"> & {\n card_order?: CardOrder;\n card_order_error?: CardOrderError;\n};\n\nexport interface TotpSetupComplete extends Session {\n /** Ten one-time `XXXX-XXXX` codes, returned only this once. */\n backup_codes: string[];\n}\n\n/** What `requestPasswordSetup` returns: send `challengeId` back with the\n * code and the new password. */\nexport interface PasswordSetupRequested {\n challenge_id: string;\n /** Where the code went, partly hidden: `al***@example.com`. */\n destination_hint: string;\n expires_at: string;\n}\n\nexport interface ConfirmPasswordSetupInput {\n challengeId: string;\n /** The six digits from the e-mail. */\n code: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit. */\n newPassword: string;\n}\n\nexport interface ChangePasswordInput {\n current_password: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit; must differ from the current password. */\n new_password: string;\n}\n\nexport interface OtpSentResponse {\n stage: \"otp_sent\";\n challenge_token: string;\n expires_at: string;\n method: AvailableMethod[\"kind\"];\n hint?: string;\n available_methods: AvailableMethod[];\n}\n\n/** Send `remember` as the API's `remember_me`. */\nfunction withRemember<T extends { remember?: boolean }>(\n input: T,\n): Omit<T, \"remember\"> & { remember_me?: boolean } {\n const { remember, ...rest } = input;\n return remember ? { ...rest, remember_me: true } : rest;\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n private readonly remembered?: TokenStore,\n ) {\n if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== \"gone\"));\n }\n\n /** Store what a finished sign-in returned. */\n private async keep(resp: { access_token: string; remember_token?: string }): Promise<void> {\n await Promise.resolve(this.tokens.set(resp.access_token));\n if (resp.remember_token && this.remembered) {\n await Promise.resolve(this.remembered.set(resp.remember_token));\n }\n }\n\n /** Renew a remembered sign-in: a new session and a new remember token,\n * both stored. Resolves `null` (and forgets the remember token) when there\n * is none or it no longer works; the app then shows the sign-in form.\n * The SDK does this by itself on a 401; call it on app start to resume a\n * session without a request failing first. */\n async refresh(): Promise<JwtIssued | null> {\n const r = await this.renew();\n if (r.kind === \"renewed\") return r.resp;\n if (r.kind === \"taken_over\") {\n // Another tab renewed first: its session is already stored.\n const access = await Promise.resolve(this.tokens.get());\n const user = await this.me();\n return { stage: \"jwt\", access_token: access ?? \"\", expires_at: \"\", user };\n }\n return null;\n }\n\n /** The renewal itself, for the 401 path: it must not call the API again\n * through the client, or a second 401 would wait on this very renewal. */\n private async renew(): Promise<\n { kind: \"renewed\"; resp: JwtIssued } | { kind: \"taken_over\" } | { kind: \"gone\" }\n > {\n const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n if (!token) return { kind: \"gone\" };\n try {\n const resp = await this.http.post<JwtIssued>(\"/auth/refresh\", {\n body: { remember_token: token },\n skipAuth: true,\n });\n await this.keep(resp);\n return { kind: \"renewed\", resp };\n } catch (e) {\n if (isApiError(e) && e.status === 401) {\n // Another tab of the same browser may have renewed first; its\n // tokens are then already in the (shared) stores.\n const now = await Promise.resolve(this.remembered!.get());\n if (now && now !== token && (await Promise.resolve(this.tokens.get()))) {\n return { kind: \"taken_over\" };\n }\n await Promise.resolve(this.remembered!.clear());\n await Promise.resolve(this.tokens.clear());\n return { kind: \"gone\" };\n }\n throw e;\n }\n }\n\n /** Password-auth entry. May resolve to a JWT, or to a step-up\n * challenge that needs `verifyTotp` / `verifyOtp` next. */\n async login(input: LoginInput): Promise<LoginResponse> {\n const body: Record<string, unknown> = withRemember(input);\n // The analytics ids go with a sign-in too: the server reports the\n // account's later payments with them.\n const attribution = withAnalyticsIds(undefined);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body,\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await this.keep(resp);\n }\n return resp;\n }\n\n /** Verify a TOTP code (or XXXX-XXXX backup code) against a\n * `totp_required` challenge. On success the JWT is stored. A backup code\n * signs nobody in: it is used up and the answer is\n * `totp_setup_email_required`, the start of connecting a new\n * authenticator ({@link confirmTotpSetupEmail}). Nothing is stored then.\n * Errors after a backup code: see {@link TotpSetupEmailErrorCode}. */\n async verifyTotp(input: TotpVerifyInput): Promise<JwtIssued | TotpSetupEmailRequired> {\n const resp = await this.http.post<JwtIssued | TotpSetupEmailRequired>(\"/auth/login/totp\", {\n body: withRemember(input),\n skipAuth: true,\n });\n if (resp.stage === \"totp_setup_email_required\") return resp;\n await this.keep(resp);\n return resp;\n }\n\n /** Verify a 6-digit OTP code (Telegram / email) against an\n * `otp_sent` challenge. */\n async verifyOtp(input: OtpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/otp/verify\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Create an end-user account and sign it in. The JWT is stored.\n * `wallet_currency` must be one the deployment offers; omit it to take\n * the deployment default (it can be switched later via `client.wallet`\n * while the wallet is empty).\n * Errors: 400 `validation` / `currency_not_allowed` / `consents_required`\n * / `unknown_consent`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const { cardOrder, ...rest } = input;\n const body: Record<string, unknown> = withRemember(rest);\n const attribution = withAnalyticsIds(rest.attribution);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n if (cardOrder !== undefined) body[\"card_order\"] = cardOrderBody(cardOrder);\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body,\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Step one of signing in without a password: a six-digit code goes to\n * the address. It works for an address with an account and for a new one\n * alike, and the answer doesn't say which. The code works for 10 minutes;\n * another can be asked for after `resend_at` and replaces it.\n * Errors: 400 `validation` (not an address), 429 `resend_too_soon` /\n * `too_many_requests` (the message says when to try again), 503\n * `delivery_failed`. */\n async requestEmailCode(input: RequestEmailCodeInput): Promise<EmailCodeSent> {\n const body: Record<string, unknown> = { email: input.email };\n if (input.locale !== undefined) body[\"locale\"] = input.locale;\n return this.http.post<EmailCodeSent>(\"/auth/email-code\", { body, skipAuth: true });\n }\n\n /** Step two: the code signs in to the account with that address, or\n * creates one (no password) when there is none; `account_created` says\n * which. The JWT is stored. With `cardOrder`, the card is ordered for\n * that account in the same call.\n * Errors: 401 `invalid_code` (wrong, expired or used; after five checks a\n * new code is needed), 400 `consents_required` for a new account, 403\n * `user_disabled` / `second_factor_required` (operator accounts sign in\n * with a password and their authenticator). */\n async verifyEmailCode(input: VerifyEmailCodeInput): Promise<EmailCodeSession> {\n const body: Record<string, unknown> = {\n challenge_id: input.challengeId,\n code: input.code,\n };\n if (input.remember) body[\"remember_me\"] = true;\n if (input.walletCurrency !== undefined) body[\"wallet_currency\"] = input.walletCurrency;\n const attribution = withAnalyticsIds(input.attribution);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.consents !== undefined) body[\"consents\"] = input.consents;\n if (input.consentChannel !== undefined) body[\"consent_channel\"] = input.consentChannel;\n if (input.cardOrder !== undefined) body[\"card_order\"] = cardOrderBody(input.cardOrder);\n const resp = await this.http.post<EmailCodeSession>(\"/auth/email-code/verify\", {\n body,\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Send the code from the e-mail of a `totp_setup_email_required`\n * answer. A right code answers `totp_setup_required`: show its\n * `otpauth_url` as a QR, then finish with {@link completeTotpSetup}.\n * Each code works for 5 minutes and takes five tries; only the newest\n * one works. Nothing is stored. Errors: {@link TotpSetupEmailErrorCode}. */\n async confirmTotpSetupEmail(input: TotpSetupEmailInput): Promise<TotpSetupRequired> {\n return this.http.post<TotpSetupRequired>(\"/auth/login/totp-setup/email\", {\n body: { challenge_token: input.challenge_token, code: input.code },\n skipAuth: true,\n });\n }\n\n /** A new e-mail code for the same `totp_setup_email_required` sign-in;\n * the one before it stops working. Use the `challenge_token` of the\n * answer from now on. Five codes an hour at most.\n * Errors: {@link TotpSetupEmailErrorCode}; 401 means the sign-in is over,\n * so start again with {@link login}. */\n async resendTotpSetupEmail(input: { challenge_token: string }): Promise<TotpSetupEmailRequired> {\n return this.http.post<TotpSetupEmailRequired>(\"/auth/login/totp-setup/email/resend\", {\n body: { challenge_token: input.challenge_token },\n skipAuth: true,\n });\n }\n\n /** Finish a `totp_setup_required` login: send the first code from the\n * authenticator app. The JWT is stored. The response carries ten\n * one-time `backup_codes` that are never returned again, so show them to\n * the user right away and don't keep them on the device. */\n async completeTotpSetup(input: TotpVerifyInput): Promise<TotpSetupComplete> {\n const resp = await this.http.post<TotpSetupComplete>(\"/auth/login/totp-setup\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Change the signed-in user's password. Every other session of the\n * account is signed out; this one stays valid.\n * Errors: 400 `weak_password` when the new password fails the policy,\n * 400 `no_password` when the account has none yet (use\n * {@link requestPasswordSetup}), 401 when the current one is wrong. */\n async changePassword(input: ChangePasswordInput): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password\", {\n body: input,\n });\n }\n\n /** Step one of setting the first password of an account that has none\n * (`user.has_password === false`, e.g. made by signing in with an e-mail\n * code): a six-digit code goes to the account's address and works for 5\n * minutes. Nothing changes yet.\n * Errors: 409 `password_exists` (use {@link changePassword}),\n * `email_required` (a Telegram account with no address yet: attach one\n * with {@link requestEmailChange} first), `email_not_proven` (sign in\n * with an e-mail code first); 429 `too_many_requests` (five codes an\n * hour); 503 `delivery_failed`. Platform 0.8.2 and newer. */\n async requestPasswordSetup(): Promise<PasswordSetupRequested> {\n return this.http.post<PasswordSetupRequested>(\"/auth/password/setup\", {});\n }\n\n /** Step two: the code from the e-mail and the new password set the\n * account's first password. Every other session of the account is signed\n * out; this one stays valid, and signing in with a code keeps working.\n * Errors: 400 `weak_password` (the code is not used up, fix the password\n * and send again), 401 `invalid_code` (after five wrong codes ask for a\n * new one), 409 `password_exists`. */\n async confirmPasswordSetup(\n input: ConfirmPasswordSetupInput,\n ): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password/setup/confirm\", {\n body: {\n challenge_id: input.challengeId,\n code: input.code,\n new_password: input.newPassword,\n },\n });\n }\n\n /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for\n * telegram/email; for TOTP it short-circuits back to the challenge. */\n async switchMethod(input: SwitchMethodInput): Promise<OtpSentResponse> {\n return this.http.post<OtpSentResponse>(\"/auth/login/2fa/switch\", {\n body: input,\n skipAuth: true,\n });\n }\n\n /** Exchange a signed Telegram Mini App `initData` payload for a session\n * JWT. The server validates the initData HMAC against the deployment's bot\n * token, then looks the Telegram id up. A known id signs in. An unknown id\n * gets a fresh account (`user.email_pending === true` — prompt for a real\n * email and call {@link linkEmail}) unless `provision: false` is passed, in\n * which case the call resolves to `{ stage: \"unknown\" }`, nothing is\n * created and nothing is stored; the app then offers to create the account\n * (call again with `provision: true`) or to attach the Telegram to an\n * existing one ({@link linkTelegram}). Stores the JWT on `stage: \"jwt\"`.\n *\n * Every other error still throws an `ApiError` (401 `invalid_init_data`,\n * 503 `telegram_not_configured`, …).\n *\n * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`\n * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when\n * you already hold a configured client. */\n exchangeTelegram(input: { initData: string; provision?: true }): Promise<JwtIssued>;\n exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown>;\n async exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown> {\n const body: {\n init_data: string;\n provision?: boolean;\n attribution?: SignupAttribution;\n code?: string;\n consents?: ConsentKind[];\n consent_channel?: ConsentChannel;\n } = {\n init_data: input.initData,\n };\n if (input.provision !== undefined) body.provision = input.provision;\n const attribution = withAnalyticsIds(input.attribution);\n if (attribution !== undefined) body.attribution = attribution;\n if (input.code !== undefined) body.code = input.code;\n if (input.consents !== undefined) body.consents = input.consents;\n if (input.consentChannel !== undefined) body.consent_channel = input.consentChannel;\n let resp: JwtIssued;\n try {\n resp = await this.http.post<JwtIssued>(\"/auth/telegram/exchange\", {\n body,\n skipAuth: true,\n });\n } catch (e) {\n if (isApiError(e) && e.status === 404 && e.code === \"telegram_unknown\") {\n return { stage: \"unknown\" };\n }\n throw e;\n }\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the Telegram account behind `initData` to an existing email +\n * password account and sign in as that account. No bearer needed; the\n * password is checked the same way `login` checks it. The JWT is stored.\n *\n * Errors: 401 `unauthenticated` (wrong email or password, as with\n * `login`) / `invalid_init_data`; 403\n * `user_disabled` / `second_factor_required` (accounts that sign in with\n * a second factor can't be linked from a Mini App); 409\n * `telegram_already_linked_other` (this account already has a different\n * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to\n * another account); 503 `telegram_not_configured`. */\n async linkTelegram(input: LinkTelegramInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/telegram/link\", {\n body: { init_data: input.initData, email: input.email, password: input.password },\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Always answers 409 `email_change_needs_code` on platform 0.8.1 and\n * newer: an address is attached only after a code sent to it comes back.\n * For the first real email of a Telegram-made account use\n * {@link requestEmailChange} and {@link confirmEmailChange}; they clear\n * `email_pending` too.\n * @deprecated Use {@link requestEmailChange} and {@link confirmEmailChange}. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Step one of an email change: a six-digit code goes to the new address\n * and works for 5 minutes. Nothing changes yet.\n * Errors: 400 `same_email`, 409 address taken, 429 `too_many_requests`\n * (five codes an hour). */\n async requestEmailChange(input: { email: string }): Promise<EmailChangeRequested> {\n return this.http.post<EmailChangeRequested>(\"/me/email/change\", {\n body: { email: input.email },\n });\n }\n\n /** Step two: the code from the e-mail changes the address; the old one\n * gets a notice. Errors: 401 `invalid_code` (after five wrong codes a new\n * request is needed), 409 the address was taken meanwhile. */\n async confirmEmailChange(input: { challengeId: string; code: string }): Promise<User> {\n return this.http.post<User>(\"/me/email/change/confirm\", {\n body: { challenge_id: input.challengeId, code: input.code },\n });\n }\n\n /** Current user — fails 401 when the stored JWT is expired or\n * missing. Useful as a \"do I have a session\" probe on app boot. */\n async me(): Promise<User> {\n return this.http.get<User>(\"/auth/me\");\n }\n\n /** Sign out: ends this session and the remembered sign-in on the\n * server (best effort: a network failure still signs out locally), then\n * forgets both tokens. */\n async signOut(): Promise<void> {\n const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n try {\n await this.http.post<void>(\"/auth/logout\", {\n body: remember ? { remember_token: remember } : {},\n retried: true,\n });\n } catch {\n // Signed out locally either way.\n }\n await Promise.resolve(this.tokens.clear());\n if (this.remembered) await Promise.resolve(this.remembered.clear());\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\nimport { cardRequestBody, type CreateCardInput } from \"./cards.js\";\nimport type { DepositTarget, FunderMode } from \"./funding-options.js\";\nimport { analyticsIds, type AnalyticsIds } from \"./attribution.js\";\n\n/**\n * Deposits resource — `client.deposits.*`.\n *\n * The \"money IN\" surface: an end user tops up their wallet balance via a\n * funder connector, or one of their cards straight away, past the wallet\n * (`card_id`, or `issue_card` for a new card). Which of the two a\n * deployment allows is in `client.fundingOptions.list()`. Mirrors the\n * Takeal API's `/me/deposits` routes:\n *\n * POST /me/deposits → initiate\n * GET /me/deposits → list (most recent first)\n * GET /me/deposits/{id} → get\n * POST /me/deposits/{id}/refunds → refund\n *\n * A deposit is rarely terminal on the initiate call: real PSPs return\n * `redirect_required` (3DS / APM redirect) and flip to `confirmed` later via\n * a connector → Takeal API inbound event. Poll `get(id)` or watch the user's\n * webhook stream for the `deposit.confirmed` / `deposit.failed` outcome.\n */\n\n/**\n * Lifecycle of a deposit. `redirect_required` carries `redirect_url`.\n * `expired`: nobody paid before `expires_at`; the user starts over with a\n * new quote. A payment that still arrives is credited at the stored rate\n * and the deposit turns `confirmed` after all.\n */\nexport type DepositStatus = \"pending\" | \"redirect_required\" | \"confirmed\" | \"failed\" | \"expired\";\n\n/**\n * Top-up rail. The chosen funder decides which it supports; `sbp` is\n * Russia's instant payments through a payment page, paid in roubles.\n */\nexport type DepositMethod = \"card\" | \"crypto\" | \"bank_transfer\" | \"sbp\";\n\n/**\n * A deposit record as the Takeal API returns it. Mirrors the `deposits` table; the\n * server-side `id` is the stable handle the SDK polls against. `idempotency_key`\n * and `request_fingerprint` are server-internal and never serialised.\n */\n/** Input for `quote()` — price a cross-currency deposit before paying. */\nexport interface CreateQuoteInput {\n /** Decimal string, e.g. `\"5000.00\"`. */\n amount: string;\n /** ISO 4217 source currency — must differ from the currency credited. */\n currency: string;\n /**\n * Quote a top-up of this card: credited in the card's currency. Pass the\n * same `card_id` to `initiate()`.\n */\n card_id?: string;\n /**\n * Quote into this currency instead of the wallet's: the currency of a\n * card issued with the top-up (`issue_card`). Ignored with `card_id`.\n */\n target_currency?: string;\n /**\n * The funding connector the deposit will go through (`funder_slug` of\n * `initiate()`). With `method`, the quote is priced on that method's own\n * terms from `fundingOptions.list()`: its fee and kind, its rate source,\n * its lifetime, its limits. Sent as `connector_slug`.\n */\n connectorSlug?: string;\n /** The way the user pays. Pass the same method to `initiate()`. */\n method?: DepositMethod;\n /**\n * A promo code for the top-up. Where the method's fee is in the rate\n * (`fee_kind: \"markup\"`), the code's percentage discount lowers that fee,\n * so the rate is priced with it and `promo_code` comes back on the quote.\n * The top-up made from the quote uses the same code: pass it again to\n * `initiate()` or leave it out. Without one, the code the user signed up\n * with is used when it works here. A code that can't be used fails with\n * 400 `promo_code_*` and the reason. Needs platform 0.8.4.\n */\n promo_code?: string;\n}\n\n/**\n * How a method's fee reads. `spread`: taken off the credited amount at the\n * deployment's rate. `markup`: in the rate the user sees, so show the rate\n * and nothing else. `commission`: the rate is the provider's and the fee is\n * a line of its own on the credited amount.\n */\nexport type FeeKind = \"spread\" | \"markup\" | \"commission\";\n\n/**\n * How far a top-up meant for a card has got. `waiting`: the card's provider\n * took the load and hasn't done it yet. `stalled`: it has taken longer than\n * the platform waits. `refunding` / `refunded`: the card never got the money,\n * and the payment is going back, or has gone back, to where it was paid from.\n */\nexport type CardLoadStatus =\n \"pending\" | \"waiting\" | \"stalled\" | \"succeeded\" | \"failed\" | \"refunding\" | \"refunded\";\n\n/**\n * A card to issue with the top-up: the fields of `cards.create` without\n * its idempotency key (the deposit's covers both). The card's price is\n * paid from the top-up and the rest becomes its starting balance.\n */\nexport type IssueCardInput = Omit<CreateCardInput, \"idempotencyKey\" | \"currency\"> & {\n /** Optional with `productId`: the product names the currency. */\n currency?: string;\n};\n\n/**\n * A rate-locked funding quote: pay `source_amount source_currency`, the\n * wallet is credited `credited_amount credited_currency` (net of the\n * platform's conversion spread). Execute by passing `id` as `quote_id` to\n * `initiate()` before `expires_at`; after that the API returns 409 and a new\n * quote is needed.\n */\nexport interface FundingQuote {\n id: string;\n source_amount: string;\n source_currency: string;\n credited_amount: string;\n credited_currency: string;\n /**\n * Provider rate before the fee, credited units per 1 source unit. Don't\n * show it: the user's rate is `effective_rate`.\n */\n rate: string;\n /**\n * The rate the user gets, credited units per 1 source unit, with the fee\n * and any discount of the user's plan or promo code in it. Show this one\n * (or its inverse, see the README) rather than working a rate out from\n * the method's `fee_bps`. Older platforms leave it out; there it is\n * `credited_amount / source_amount`.\n */\n effective_rate?: string;\n /** The fee in basis points; the same figure as `fee_bps`, under its old name. */\n spread_bps: number;\n /** The fee in basis points (2000 = 20 %). */\n fee_bps: number;\n fee_kind: FeeKind;\n provider: string;\n /** The pair the quote was priced for, when the request named one. */\n connector_slug?: string;\n method?: DepositMethod;\n /** The rate is locked until then; the deposit made with it waits for its payment as long. */\n expires_at: string;\n /**\n * Set when the user's plan or a promo code lowered the fee in the rate:\n * the method's fee before that, in basis points. `fee_bps` is what the\n * user pays.\n */\n list_fee_bps?: number;\n /** What the lower fee adds to `credited_amount`, decimal string in `credited_currency`. */\n fee_discount?: string;\n /** The promo code the rate was priced with; the top-up made from this quote uses it. */\n promo_code?: string;\n /**\n * What the user owes in card fees, in `credited_currency`, that this\n * top-up pays first: it comes off `credited_amount` and the rest is\n * credited. `\"0\"` when nothing is owed. Show it before the payment. Older\n * platforms leave it out.\n */\n debt_withheld?: string;\n}\n\nexport interface Deposit {\n id: string;\n user_id: string;\n /** Slug of the funder that handled this deposit, as configured by the deployment. */\n connector_slug: string;\n /** The connector's own reference, populated once it responds. */\n provider_reference: string | null;\n status: DepositStatus;\n /** Decimal serialised as a string to avoid float drift. */\n amount: string;\n currency: string;\n method: DepositMethod;\n /** Present when `status === \"redirect_required\"` — send the user here. */\n redirect_url: string | null;\n failure_reason: string | null;\n /** Final settled amount once confirmed (may differ from `amount` on FX). */\n confirmed_amount: string | null;\n confirmed_at: string | null;\n /** Set on cross-currency deposits: the quote this deposit executed against. */\n quote_id?: string | null;\n /** Locked provider rate (credited units per 1 source unit). */\n fx_rate?: string | null;\n fx_spread_bps?: number | null;\n /** How `fx_spread_bps` was taken; see `FeeKind`. */\n fx_fee_kind?: FeeKind | null;\n /** When the deposit stops waiting for its payment; `null` for one without a term. */\n expires_at?: string | null;\n /** The wallet's local currency the deposit converted into. */\n credited_currency?: string | null;\n /** What the wallet was actually credited, net of spread. */\n credited_amount?: string | null;\n /** Bonuses added on top of the top-up, when any were. */\n bonus_units?: string | null;\n /** What those bonuses added to the wallet, in the credited currency. */\n bonus_value?: string | null;\n /** The promo code the top-up was made with; its discount came off the commission. */\n promo_code?: string | null;\n /** Where the money goes. Older deployments leave it out: the wallet. */\n target?: DepositTarget;\n /** For a top-up onto a card: the card. */\n card_id?: string | null;\n /** The funding connector's mode when the top-up was made. */\n funder_mode?: FunderMode | null;\n /** True when the card was issued with this top-up. */\n issues_card?: boolean;\n /**\n * For a top-up onto a card: `pending` until the card provider has loaded\n * the card, then `succeeded` or `failed`. Show the top-up as done only\n * once it is `succeeded`, or once `returned_to_wallet_at` is set.\n */\n card_load_status?: CardLoadStatus | null;\n /** Why the card could not take it, when `card_load_status` is `failed`. */\n card_load_error?: string | null;\n /** What went towards the card, in its currency, bonuses included. */\n card_amount?: string | null;\n /** The commission taken from a top-up onto a card, in the card's currency. */\n card_commission?: string | null;\n /** The money part of the price of a card issued with the top-up. */\n issue_fee?: string | null;\n /** The bonus part of that price. */\n issue_bonus_units?: string | null;\n issue_bonus_value?: string | null;\n card_loaded_at?: string | null;\n /**\n * Set when the card could not take the top-up and the money went to the\n * wallet instead (funding connectors in `mixed` mode). The user is told.\n */\n returned_to_wallet_at?: string | null;\n /**\n * The user's debt in card fees shown before the payment, in the credited\n * currency: the most this top-up pays towards it before the rest is\n * credited. Absent when nothing was owed.\n */\n debt_quoted?: string | null;\n /**\n * What the top-up did pay towards the debt. For a top-up onto a card,\n * `card_amount` is already net of it.\n */\n debt_withheld?: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface InitiateDepositInput {\n /** Decimal as a string (`\"100.00\"`) — avoids float-precision loss on the wire. */\n amount: string;\n /** ISO 4217 code, e.g. `\"USD\"`. */\n currency: string;\n method: DepositMethod;\n /**\n * Optional. Slug of a specific funder to route through. Omit to\n * let the Takeal API pick the first active funder. Unknown slug → 400; empty\n * funder list → 503.\n */\n funder_slug?: string;\n /**\n * Passed to the funding connector and stored with the deposit. Two keys\n * work across connectors: `return_url`, where the provider sends the user\n * back after a 3-D Secure step (pair it with `redirect_required`), and on\n * test deployments with the mock funder `mock_scenario`, which picks the\n * outcome: `happy` (confirmed at once, the default), `pending` (confirmed\n * about 15 s later), `redirect` (a hosted page where the user approves or\n * declines), `late` (paid after the term) or `fail`.\n */\n metadata?: Record<string, string>;\n /** Structured billing details — real PSPs require these for 3DS / compliance. */\n customer?: CustomerInfo;\n /**\n * Required by the Takeal API on this write endpoint. Same key + body replays the\n * original deposit; same key + different body returns 409. Supply a stable\n * UUID per logical attempt so a retried network call is safe.\n */\n idempotencyKey: string;\n /**\n * Required when `currency` differs from the wallet's local currency: a\n * fresh quote id from `quote()`. Cross-currency deposits without one are\n * rejected with 400; expired quotes with 409.\n */\n quote_id?: string;\n /**\n * Add bonuses on top of the top-up: the user pays `amount`, the wallet\n * gets `amount` plus what the bonuses add. On by default whenever the\n * user has bonuses that can go to a top-up (only ones that came with a\n * payment can); `false` tops up without them.\n */\n use_bonus?: boolean;\n /** The most bonuses to add, decimal string. Omit to add as many as allowed. */\n bonus_amount?: string;\n /**\n * Top up this card instead of the wallet. It must be the user's, active\n * and prepaid. A funding connector that tops up the wallet only answers\n * 400 `target_not_allowed`; one that tops up cards only needs `card_id`\n * or `issue_card`. Paying in another currency than the card's needs a\n * quote made with the same `card_id`.\n */\n card_id?: string;\n /**\n * Issue a new card and put this top-up on it. The card shows up as\n * `pending_payment` and is issued once the top-up is confirmed; if the\n * top-up fails, so does the card. Too small to cover the price → 400\n * `amount_too_small`. Not together with `card_id`.\n */\n issue_card?: IssueCardInput;\n /**\n * A promo code for this top-up, to the wallet or to a card. Its discount\n * comes off the commission; bonuses or a gift that come with the code\n * arrive once the top-up is confirmed. A code that can't be used fails the\n * request with 400 `promo_code_*` and the reason. `client.codes.validate`\n * checks it first.\n *\n * Where the method's fee is in the rate, the discount lowers the rate, and\n * only the quote prices the rate: send the code to `quote()`. A top-up\n * from that quote uses the quote's `promo_code` without being told; another\n * code here is refused (400 `validation`), and a code the quote was made\n * without is refused with 400 `promo_code_not_applicable`.\n */\n promo_code?: string;\n /** The visitor's analytics ids for the payment's server-side conversions.\n * Leave out to send the ones this browser holds (see `analyticsIds`). */\n analytics_ids?: AnalyticsIds;\n}\n\nexport interface CreateDepositRefundInput {\n /** Omit for a full refund of the original confirmed amount; same currency. */\n amount?: string;\n /** Human-readable reason, e.g. `\"customer_request\"`. */\n reason?: string;\n metadata?: Record<string, string>;\n /** Required. Replays are keyed on this. */\n idempotencyKey: string;\n}\n\n/** A refund row as the Takeal API returns it (`refunds` table, deposit-targeted). */\nexport interface Refund {\n id: string;\n target_type: string;\n deposit_id?: string;\n payment_id?: string;\n connector_slug: string;\n amount: string;\n currency: string;\n reason: string;\n status: string;\n provider_refund_reference?: string;\n failure_reason?: string;\n /** `user`, `operator`, or `system` when the platform refunded by itself. */\n requestor_type: string;\n requestor_id: string;\n created_at: string;\n updated_at: string;\n}\n\nexport class DepositsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Initiate a top-up. Resolves to the freshly-created `Deposit`, whose\n * `status` may already be `confirmed` (synchronous rails / mock) or\n * `redirect_required` (3DS / APM — forward the user to `redirect_url`).\n */\n /**\n * Price a cross-currency deposit BEFORE paying. The rate is locked\n * server-side until `expires_at`; deposits already in the currency they\n * credit (the wallet's, or the card's with `card_id`) need no quote (the\n * API answers 400 `no_quote_needed`).\n */\n async quote(input: CreateQuoteInput): Promise<FundingQuote> {\n const { connectorSlug, ...rest } = input;\n const body: Record<string, unknown> = { ...rest };\n if (connectorSlug !== undefined) body[\"connector_slug\"] = connectorSlug;\n return this.http.post<FundingQuote>(\"/me/deposits/quotes\", { body });\n }\n\n /**\n * Start a top-up. 409 `payments_on_hold`: a payment on this account was\n * not accepted and new ones wait until support sorts it out. Show the\n * message as it comes and point the user to support.\n */\n async initiate(input: InitiateDepositInput): Promise<Deposit> {\n const { idempotencyKey, issue_card, ...rest } = input;\n const body: Record<string, unknown> = { ...rest };\n if (issue_card !== undefined) body[\"issue_card\"] = cardRequestBody(issue_card);\n const ids = input.analytics_ids ?? analyticsIds();\n if (ids !== undefined) body[\"analytics_ids\"] = ids;\n return this.http.post<Deposit>(\"/me/deposits\", {\n body,\n idempotencyKey,\n });\n }\n\n /** Fetch one deposit by id — the poll target while a redirect resolves. */\n async get(id: string): Promise<Deposit> {\n return this.http.get<Deposit>(`/me/deposits/${encodeURIComponent(id)}`);\n }\n\n /** List the caller's deposits, most recent first. */\n async list(): Promise<Deposit[]> {\n return this.http.get<Deposit[]>(\"/me/deposits\");\n }\n\n /**\n * Refund a previously-confirmed deposit. Synchronous when the\n * connector settles inline; otherwise the row stays `pending` and flips\n * later via the inbound `deposit.refunded` event.\n */\n async refund(depositId: string, input: CreateDepositRefundInput): Promise<Refund> {\n const { idempotencyKey, ...body } = input;\n return this.http.post<Refund>(`/me/deposits/${encodeURIComponent(depositId)}/refunds`, {\n body,\n idempotencyKey,\n });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Balance resource — `client.balance.*`.\n *\n * The user's wallet balance, tracked in the ledger. Mirrors the Takeal API's\n * `GET /me/balance[?currency=<code>]` route. Balances are per-currency; with\n * no `currency` the wallet's own currency is returned (see `client.wallet`).\n */\n\n/** Wallet balance for one currency. `amount` is a decimal string. */\nexport interface Balance {\n amount: string;\n currency: string;\n}\n\nexport class BalanceResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Fetch the user's wallet balance. Omit `currency` for the wallet's own\n * currency; pass an ISO 4217 code (e.g. `\"USD\"`) to read another one —\n * the ledger holds a separate balance per currency.\n */\n async get(currency?: string): Promise<Balance> {\n if (!currency) return this.http.get<Balance>(\"/me/balance\");\n const q = new URLSearchParams({ currency }).toString();\n return this.http.get<Balance>(`/me/balance?${q}`);\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Bonus resource — `client.bonus.*`.\n *\n * Bonuses are a discount on the platform's services, not money. They pay\n * for part of a new card's price or of the subscription fee, and bonuses\n * that came with a payment can also be added on top of a top-up. Spending\n * happens on the operation itself: `useBonus` / `bonusAmount` on\n * `cards.create`, `use_bonus` / `bonus_amount` on `deposits.initiate`, and\n * the subscription fee takes them on its own.\n *\n * Show the balance as a number of bonuses and nothing else: no money\n * figure next to it. Money belongs next to a price only (\"was / now\",\n * \"N bonuses will be used\"), which is what {@link BonusResource.preview}\n * works out on the server.\n *\n * Mirrors `GET /me/bonus` and `POST /me/bonus/preview`.\n */\n\n/** What bonuses can pay for. */\nexport type BonusPurpose = \"card_issuance\" | \"subscription\" | \"deposit\";\n\n/** One credit of bonuses and what is left of it. */\nexport interface BonusLot {\n id: string;\n /** Where the bonuses came from, e.g. `manual`. */\n source: string;\n /** True when they came without a payment: a card or the subscription only, never a top-up. */\n restricted: boolean;\n /** Bonuses credited, decimal string. */\n amount: string;\n /** Bonuses left, decimal string. */\n remaining: string;\n /** When what is left expires; `null` = never. */\n expires_at: string | null;\n created_at: string;\n}\n\n/** One change to the bonus balance. */\nexport interface BonusMovement {\n id: string;\n /** `credit`, `debit` (taken back by support), `spend` or `expire`. */\n kind: \"credit\" | \"debit\" | \"spend\" | \"expire\" | (string & {});\n /** For a `spend`: what the bonuses went towards. */\n purpose: BonusPurpose | null;\n /** `posted`, or `reserved` while the payment they are held for goes through. */\n status: \"posted\" | \"reserved\" | (string & {});\n /** Bonuses, decimal string, always positive. */\n units: string;\n /** For a spend: the price the bonuses went against (a top-up: the amount paid). */\n price: string | null;\n /** For a spend: what the bonuses covered (a top-up: what they added). */\n value: string | null;\n /** Currency of `price` and `value`. */\n currency: string | null;\n /** The card, deposit or subscription paid for. */\n operation_id: string | null;\n created_at: string;\n}\n\n/** Where bonuses may go right now. */\nexport interface BonusTarget {\n purpose: BonusPurpose;\n /** Bonuses that may go towards it, decimal string. */\n available: string;\n /** Largest share of a price bonuses may cover, basis points (10000 = all). */\n share_bps: number;\n}\n\n/** `GET /me/bonus`. */\nexport interface BonusWallet {\n /** Bonuses the user can use now. Show it on its own, without a money figure. */\n balance: string;\n /** Bonuses held for a payment still going through. */\n pending: string;\n /** One bonus is a discount of one unit of this currency. For prices only. */\n unit_currency: string;\n spend_on: BonusTarget[];\n /** Credits with bonuses left, the soonest to expire first. */\n lots: BonusLot[];\n /** Latest changes, newest first. */\n history: BonusMovement[];\n}\n\nexport interface BonusPreviewInput {\n purpose: BonusPurpose;\n /** The price as shown, or for `deposit` the amount paid; decimal string. */\n amount: string;\n /** ISO 4217 code of `amount`. */\n currency: string;\n /** For `card_issuance`: the product, which may cap the bonus share. */\n productId?: string;\n /** The most bonuses to use; omit to use as many as allowed. */\n bonusAmount?: string;\n}\n\n/** How bonuses change one price. All amounts are decimal strings in `currency`. */\nexport interface BonusPreview {\n purpose: BonusPurpose;\n /** The price before bonuses (\"was\"); for `deposit`, the amount paid. */\n amount: string;\n /** Bonuses that would be used. */\n bonus_units: string;\n /** What they cover (or, for `deposit`, add). */\n bonus_value: string;\n /** What is left to pay (\"now\"); for `deposit`, the amount paid. */\n due: string;\n /** For `deposit`: what reaches the wallet. `null` otherwise. */\n credited: string | null;\n currency: string;\n}\n\nexport class BonusResource {\n constructor(private readonly http: HttpClient) {}\n\n /** The user's bonuses: balance, where they can go, credits and history. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<BonusWallet> {\n return this.http.get<BonusWallet>(\"/me/bonus\", { signal: opts.signal });\n }\n\n /**\n * Work out how bonuses would change a price, at the rate the payment\n * would use. Nothing is held; the numbers may move by the time the user\n * pays if prices, rates or bonuses change.\n */\n async preview(input: BonusPreviewInput): Promise<BonusPreview> {\n const { productId, bonusAmount, ...rest } = input;\n const body: Record<string, unknown> = { ...rest };\n if (productId !== undefined) body[\"product_id\"] = productId;\n if (bonusAmount !== undefined) body[\"bonus_amount\"] = bonusAmount;\n return this.http.post<BonusPreview>(\"/me/bonus/preview\", { body });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Debt resource — `client.debt.*`: card fees the user's cards could not\n * cover.\n *\n * GET /me/debt → get\n *\n * A card product's tariff (`CardProduct.tariff`) charges fees for using the\n * card: per payment, per decline that was the user's doing, per cash\n * withdrawal. A fee comes off the card; what the card can't cover is owed by\n * the user, not by the card. The next top-up of any of their cards (or of\n * their wallet) pays it first and credits the rest. Show that amount before\n * the payment:\n *\n * - a deposit quote: `FundingQuote.debt_withheld`, off `credited_amount`;\n * - a card order: `CardOrder.debt_withheld`, already in `card_amount`;\n * - a card top-up: `TopUpTerms.debt`;\n * - the deposit itself: `Deposit.debt_quoted`, then `debt_withheld` once paid.\n *\n * The user is notified when a debt arises (`debt_created`) and when it is\n * paid (`debt_settled`).\n */\n\n/** An amount with its currency, decimal string. */\nexport interface DebtAmount {\n amount: string;\n currency: string;\n}\n\n/** What a fee was charged for. */\nexport type CardFeeKind = \"operation\" | \"decline\" | \"cash_withdrawal\" | (string & {});\n\n/** One amount owed. */\nexport interface DebtLine {\n id: string;\n /** What it is owed for: `card_fee`. */\n basis: string;\n /** The fee behind it: `operation`, `decline` or `cash_withdrawal`. */\n fee_kind: CardFeeKind | null;\n /** The amount owed when it arose, decimal string. */\n amount: string;\n /** What is still owed of it, decimal string. */\n outstanding: string;\n currency: string;\n /** The card the fee was for. */\n card_id: string | null;\n card_last4: string | null;\n /** The card operation the fee was for. */\n transaction_id: string | null;\n merchant_name: string | null;\n /** The operation's amount, decimal string, never negative. */\n operation_amount: string | null;\n operation_currency: string | null;\n created_at: string;\n /** When it was paid in full; `null` while something is owed. */\n settled_at: string | null;\n}\n\n/** What the user owes, from `GET /me/debt`. */\nexport interface Debt {\n /** Per currency; empty when nothing is owed. */\n total: DebtAmount[];\n /** The amounts still owed, newest first. */\n items: DebtLine[];\n}\n\nexport class DebtResource {\n constructor(private readonly http: HttpClient) {}\n\n /** What the user owes in card fees, per currency, and what for. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Debt> {\n return this.http.get<Debt>(\"/me/debt\", { signal: opts.signal });\n }\n\n /** What the user owes in `currency`, decimal string; `\"0\"` when nothing. */\n async owedIn(currency: string, opts: { signal?: AbortSignal } = {}): Promise<string> {\n const debt = await this.get(opts);\n const want = currency.trim().toUpperCase();\n return debt.total.find((d) => d.currency.toUpperCase() === want)?.amount ?? \"0\";\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Close requests — `client.closeRequests.*`: close a card that still holds\n * money and get what is left back the way it was paid.\n *\n * POST /me/cards/{id}/close-request → request\n * GET /me/close-requests → list\n * GET /me/close-requests/{id} → get\n * POST /me/close-requests/{id}/payout-details → submitPayoutDetails\n *\n * `cards.terminate()` refuses a card with money on it (409\n * `move_balance_first` or `contact_support_to_close`). Offer\n * `closeRequests.request(cardId)` instead: the card is closed at its issuer\n * right away, and once the issuer returns what was left on it the money goes\n * back to the payments the card was topped up with, in the currency they\n * were paid in, newest first. Unspent bonuses are not refunded, and a debt\n * the user was told about (`client.debt`) is withheld first.\n *\n * The request moves through `status`:\n *\n * - `accepted`: the card is being closed;\n * - `awaiting_issuer`: closed; the issuer has not returned the balance yet;\n * - `refunding`: the money is on its way back (`refunds`, `on_the_way`);\n * - `payout_details_required`: it can't go back the way it came. Ask the\n * user for a bank account or a card in their own name and send it with\n * {@link CloseRequestsResource.submitPayoutDetails};\n * - `identity_check`: the details are being checked (they can still be\n * corrected);\n * - `manual_payout`: checked; the transfer is being made;\n * - `refunded`: everything due went back.\n *\n * Amounts only, never rates: the user sees what the card held\n * (`balance`), what is kept back (`bonus_excluded`, `debt_withheld`), what\n * goes back in all once it is known (`refund_total`) and what went back so\n * far (`refunded`). `deadline_at` is when the refund is due by. The user is\n * notified when the close is accepted (`card_close_requested`), each time\n * money is sent back (`card_close_refund_sent`), when details are needed\n * (`card_close_payout_details_needed`) and when a transfer by hand was made\n * (`card_close_paid_manually`).\n */\n\n/** An amount with its currency, decimal string. */\nexport interface CloseAmount {\n amount: string;\n currency: string;\n}\n\n/** Where a close request stands. */\nexport type CloseRequestStatus =\n | \"accepted\"\n | \"awaiting_issuer\"\n | \"refunding\"\n | \"payout_details_required\"\n | \"identity_check\"\n | \"manual_payout\"\n | \"refunded\"\n | (string & {});\n\n/** One part of the refund. */\nexport interface CloseRefund {\n id: string;\n /** Decimal string, in `currency`. */\n amount: string;\n currency: string;\n /** `pending` (sent, the bank has not confirmed it yet) or `succeeded`. */\n status: \"pending\" | \"succeeded\" | (string & {});\n /** `original_payment`: back to a payment's details; `manual`: transferred to the details the user gave. */\n method: \"original_payment\" | \"manual\" | (string & {});\n created_at: string;\n /** When it went through; `null` while pending. */\n completed_at: string | null;\n}\n\n/** The details given for a transfer by hand, as shown back: never the whole number. */\nexport interface PayoutDetailsShown {\n kind: \"account\" | \"card\" | (string & {});\n /** The last four digits, e.g. `•••• 4312`. */\n masked: string;\n given_at: string | null;\n}\n\n/** A request to close a card with money on it. */\nexport interface CloseRequest {\n id: string;\n card_id: string;\n card_last4: string | null;\n status: CloseRequestStatus;\n /** What the card held: what the issuer returned once it did, before that what the card showed. */\n balance: CloseAmount;\n /** Unspent bonuses, not refunded, in the card's currency; `null` until the issuer returned the balance. */\n bonus_excluded: string | null;\n /** The debt withheld, in the card's currency; `null` until the issuer returned the balance. */\n debt_withheld: string | null;\n /** Everything that goes back, in the currency the card was paid in; `null` until known. */\n refund_total: CloseAmount | null;\n /** What went back already. */\n refunded: CloseAmount;\n /** Sent and not confirmed yet. */\n on_the_way: CloseAmount;\n /** The parts of the refund, oldest first. */\n refunds: CloseRefund[];\n /** The details given for a transfer by hand, if any. */\n payout_details: PayoutDetailsShown | null;\n /** The refund is due by then. */\n deadline_at: string;\n created_at: string;\n /** When the issuer took the close. */\n closed_at: string | null;\n /** When the issuer returned the balance. */\n returned_at: string | null;\n refunded_at: string | null;\n}\n\n/**\n * Where to send the money when it can't go back the way it came. Either kind\n * must be in the user's own name. Spaces and dashes in numbers are fine.\n */\nexport type PayoutDetailsInput =\n | {\n kind: \"account\";\n /** The account holder's full name as the bank has it. */\n holder_name: string;\n account_number: string;\n /** The bank's code (BIC). */\n bank_code: string;\n bank_name?: string;\n }\n | {\n kind: \"card\";\n /** The cardholder's full name as on the card. */\n holder_name: string;\n card_number: string;\n };\n\n/** Why a close request can't be made right now (409 `code`). */\nexport type CloseRequestError =\n | \"card_locked\"\n | \"first_purchase_required\"\n | \"card_not_closable\"\n | \"topup_in_progress\"\n | \"card_closing\"\n | \"no_balance\"\n | \"provider_refused\"\n | (string & {});\n\nexport class CloseRequestsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Close a card that holds money, the rest going back the way it was paid.\n * Asking again for the same card returns the same request. 404 no such\n * card · 409 {@link CloseRequestError}: `no_balance` means the card holds\n * nothing, close it with `cards.terminate()` · 503 the issuer can't be\n * reached; the card stays as it was.\n */\n async request(cardId: string, input: { reason?: string } = {}): Promise<CloseRequest> {\n return this.http.post<CloseRequest>(`/me/cards/${encodeURIComponent(cardId)}/close-request`, {\n body: { reason: input.reason },\n });\n }\n\n /** Every card close request of the user, newest first. */\n async list(opts: { signal?: AbortSignal } = {}): Promise<CloseRequest[]> {\n const res = await this.http.get<{ items: CloseRequest[] }>(\"/me/close-requests\", {\n signal: opts.signal,\n });\n return res.items;\n }\n\n /** One close request. 404 when it isn't the user's. */\n async get(id: string, opts: { signal?: AbortSignal } = {}): Promise<CloseRequest> {\n return this.http.get<CloseRequest>(`/me/close-requests/${encodeURIComponent(id)}`, {\n signal: opts.signal,\n });\n }\n\n /** The request for this card, if the user made one. */\n async forCard(cardId: string, opts: { signal?: AbortSignal } = {}): Promise<CloseRequest | null> {\n const all = await this.list(opts);\n return all.find((r) => r.card_id === cardId) ?? null;\n }\n\n /**\n * Give a bank account or a card in the user's own name, when the request\n * is `payout_details_required` (or `identity_check`, to correct them). 400\n * `validation`: a name, number or bank code that doesn't look right · 409\n * `details_not_needed`.\n */\n async submitPayoutDetails(id: string, details: PayoutDetailsInput): Promise<CloseRequest> {\n return this.http.post<CloseRequest>(\n `/me/close-requests/${encodeURIComponent(id)}/payout-details`,\n { body: details },\n );\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Claims — `client.claims.*`: dispute a card operation or complain, and\n * follow the claim by its number and status. A card lost or stolen is\n * reported with `client.cards.reportLost()`, which opens a claim too.\n *\n * POST /me/cards/{id}/report-lost → cards.reportLost\n * POST /me/claims → create\n * GET /me/claims → list\n * GET /me/claims/{id} → get\n *\n * Every claim has a `number` (e.g. `C-000123`) the user can quote to\n * support, and a `status`:\n *\n * - `open`: received, nobody has taken it yet;\n * - `in_review`: support is working on it;\n * - `resolved`: done, support's answer is in `resolution`;\n * - `rejected`: declined, the reason is in `resolution`.\n *\n * `reported_at` is when the platform took the claim. For a lost or stolen\n * card that time decides who pays for operations someone else made with it,\n * so show it. Such a card is frozen at its issuer at once (`card_freeze:\n * \"frozen\"`) and only support can unfreeze it; `cards.unfreeze()` answers\n * 409 `card_locked`. If the issuer could not be reached, `card_freeze` is\n * `\"pending\"`: the report counts all the same and support freezes the card\n * by hand.\n *\n * The user is notified when a claim comes in (`card_reported_lost`,\n * `card_claim_opened`) and when its status changes (`card_claim_updated`).\n */\n\n/** What a claim is about. */\nexport type ClaimKind = \"lost\" | \"stolen\" | \"dispute\" | \"complaint\" | (string & {});\n\n/** Where a claim stands. */\nexport type ClaimStatus = \"open\" | \"in_review\" | \"resolved\" | \"rejected\" | (string & {});\n\n/** The card operation a claim is about. */\nexport interface ClaimTransaction {\n /** The operation's id in `client.history` (`txn_<id>`). */\n id: string;\n /** Decimal string, without a sign. */\n amount: string;\n currency: string;\n merchant_name: string | null;\n /** `pending`, `cleared`, `reversed` or `declined`. */\n status: string;\n occurred_at: string;\n}\n\n/** A claim. */\nexport interface Claim {\n id: string;\n /** What support calls it, e.g. `C-000123`. */\n number: string;\n kind: ClaimKind;\n status: ClaimStatus;\n card_id: string | null;\n card_last4: string | null;\n /** The operation disputed or complained about, if one was named. */\n transaction: ClaimTransaction | null;\n /** The user's own words. */\n description: string;\n /** When the platform took the claim (the server's time, never the device's). */\n reported_at: string;\n /** Lost or stolen only: `frozen`, or `pending` while the issuer hasn't frozen the card. `null` for other kinds. */\n card_freeze: \"frozen\" | \"pending\" | null;\n /** Lost or stolen only: when the card was frozen. */\n card_frozen_at: string | null;\n /** Support's answer, once there is one. */\n resolution: string | null;\n created_at: string;\n updated_at: string;\n /** When the claim was resolved or rejected. */\n resolved_at: string | null;\n}\n\n/** A page of the user's claims, newest first. */\nexport interface ClaimPage {\n items: Claim[];\n total: number;\n}\n\n/** A dispute or a complaint. */\nexport interface CreateClaimInput {\n /** `dispute`: a card operation the user doesn't agree with; `complaint`: anything else. */\n kind: \"dispute\" | \"complaint\";\n /** What happened, 10 to 4000 characters. */\n description: string;\n /** The card it is about. Optional; found from the operation when one is named. */\n cardId?: string;\n /** The operation it is about, as `client.history` names it (`txn_<id>`). Optional. */\n transactionId?: string;\n}\n\n/** Why a claim can't be made right now (409 `code`). */\nexport type ClaimError = \"card_not_open\" | \"too_many_claims\" | (string & {});\n\nexport class ClaimsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Dispute a card operation, or complain. 400 `validation`: a description\n * that is too short or too long, an operation that isn't on the user's\n * cards, or a lost or stolen card (use `cards.reportLost()`) · 404 no\n * such card · 409 `too_many_claims`: 20 claims are waiting for an answer.\n */\n async create(input: CreateClaimInput): Promise<Claim> {\n return this.http.post<Claim>(\"/me/claims\", {\n body: {\n kind: input.kind,\n description: input.description,\n card_id: input.cardId,\n transaction_id: input.transactionId,\n },\n });\n }\n\n /** The user's claims, lost and stolen cards included, newest first. */\n async list(\n opts: { limit?: number; offset?: number; signal?: AbortSignal } = {},\n ): Promise<ClaimPage> {\n const qs = new URLSearchParams();\n if (opts.limit != null) qs.set(\"limit\", String(opts.limit));\n if (opts.offset != null) qs.set(\"offset\", String(opts.offset));\n const q = qs.toString();\n return this.http.get<ClaimPage>(`/me/claims${q ? `?${q}` : \"\"}`, { signal: opts.signal });\n }\n\n /** One claim. 404 when it isn't the user's. */\n async get(id: string, opts: { signal?: AbortSignal } = {}): Promise<Claim> {\n return this.http.get<Claim>(`/me/claims/${encodeURIComponent(id)}`, { signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Codes resource — `client.codes.*`.\n *\n * Promo and referral codes. A code is used on the operation itself:\n * `code` on `auth.register` / `auth.exchangeTelegram`, `promo_code` on\n * `deposits.initiate`, `promoCode` on `cards.create`, and\n * `client.subscription.setPromoCode` for the monthly fee. On a card bought\n * with a payment, a code that works on issuing a card lowers the card's\n * price; one that works on top-ups lowers the payment's commission.\n * {@link CodesResource.validate} checks one first and says what it would do,\n * without using it up.\n *\n * What a code gives besides a discount (bonuses, a gift subscription) comes\n * once the operation goes through. Bonuses are a discount on our services,\n * never money: show them as a number of bonuses.\n *\n * Mirrors `POST /me/codes/validate`.\n */\n\n/** The operations a code can be used on. */\nexport type CodeOperation = \"signup\" | \"deposit\" | \"card_issuance\" | \"subscription\";\n\n/** Why a code can't be used. Show `message` from the response as is. */\nexport type CodeRejection =\n | \"unknown\"\n | \"disabled\"\n | \"not_started\"\n | \"expired\"\n | \"not_applicable\"\n | \"exhausted\"\n | \"already_used\"\n | \"not_first_operation\"\n | \"below_minimum\"\n | \"currency_mismatch\"\n | \"own_code\"\n | \"already_registered\"\n | (string & {});\n\n/** What one effect of a code did, as a sign-up reports it. */\nexport interface CodeEffectOutcome {\n /** `bonus_credit`, `gift_subscription`, `grant_referral_code` or `referral_link`. */\n kind: string;\n /** `applied`, `skipped` (a gift when a subscription was already running) or `failed`. */\n status: \"applied\" | \"skipped\" | \"failed\" | (string & {});\n reason?: string;\n /** Details by kind: `units` for bonuses, `tier` and `until` for a gift, `code` for a referral code of one's own. */\n [detail: string]: unknown;\n}\n\n/** What the code sent with a sign-up did. The account is created either way. */\nexport interface CodeResult {\n code: string;\n status: \"applied\" | \"rejected\";\n reason: CodeRejection | null;\n /** A sentence to show when the code was not applied. */\n message: string | null;\n effects: CodeEffectOutcome[];\n}\n\n/** One effect a code carries, as `validate` lists it. */\nexport type CodeEffect =\n | { kind: \"gift_subscription\"; tier_id: string; days: number | null }\n | { kind: \"bonus_credit\"; amount: string }\n | { kind: \"grant_referral_code\"; program_id: string }\n | { kind: string; [k: string]: unknown };\n\nexport interface CodeDiscount {\n kind: \"percent\" | \"fixed\";\n /** For `percent`: basis points off (1000 = 10%). */\n bps: number | null;\n /** For `fixed`: the amount off, decimal string. */\n amount: string | null;\n currency: string | null;\n /** What comes off: `card_issuance`, `funding_commission` (the top-up commission) or `subscription`. */\n applies_to: \"card_issuance\" | \"funding_commission\" | \"subscription\" | null;\n}\n\nexport interface ValidateCodeInput {\n code: string;\n operation: CodeOperation;\n /** The operation's amount, decimal string: needed for a code with a minimum or a fixed discount. */\n amount?: string;\n /** ISO 4217 code of `amount`; for a top-up, the currency it is credited in. */\n currency?: string;\n /**\n * For a top-up paid in another currency than it is credited in: what is\n * paid, decimal string. A code's minimum may be set in either currency;\n * with both amounts sent it is checked the way the top-up itself checks it.\n */\n paid_amount?: string;\n /** ISO 4217 code of `paid_amount`. */\n paid_currency?: string;\n /**\n * For a card bought with a payment (`cardOrders.create`, or\n * `deposits.initiate` with `issue_card`): the product. The code is then\n * checked the way that purchase takes it: as a card issuance, against the\n * product's price, when the code works on issuing a card, and as a top-up\n * otherwise. `discount.applies_to` in the answer says which, and\n * `discount_value` is what comes off the card's price. `operation` may be\n * `deposit` or `card_issuance`.\n */\n product_id?: string;\n}\n\n/** `POST /me/codes/validate`. */\nexport interface CodeCheck {\n valid: boolean;\n code: string | null;\n /** `promo` or `referral`. */\n kind: string | null;\n reason: CodeRejection | null;\n message: string | null;\n discount: CodeDiscount | null;\n /** For a card or the monthly fee with `amount` sent: what comes off it. */\n discount_value: string | null;\n /** Everything else the code gives, once the operation goes through. */\n effects: CodeEffect[];\n}\n\nexport class CodesResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Whether a code can be used on an operation now and what it would do.\n * Nothing is used up. For sign-up there is nothing to check here: send\n * the code with `auth.register` and read `code_result`.\n */\n async validate(input: ValidateCodeInput): Promise<CodeCheck> {\n return this.http.post<CodeCheck>(\"/me/codes/validate\", { body: input });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Referral resource — `client.referral.*`.\n *\n * For the people allowed to invite: their referral code, the link to\n * share, the people who signed up with it (no names or contacts, only\n * when they joined and how far they got) and what each reward was for.\n * Referral codes are given by invitation, so `code` is `null` for most\n * users. Rewards are bonuses, a discount on our services, not money.\n *\n * Mirrors `GET /me/referral`.\n */\n\n/** Someone the user invited, without anything that identifies them. */\nexport interface InvitedFriend {\n joined_at: string;\n /** Bonuses they brought so far, decimal string. */\n rewarded: string;\n has_card: boolean;\n has_topped_up: boolean;\n}\n\n/** One reward. */\nexport interface ReferralReward {\n id: string;\n /** `signup`, `card_issuance`, `first_deposit` or `deposit`. */\n event: \"signup\" | \"card_issuance\" | \"first_deposit\" | \"deposit\" | (string & {});\n /** The friend's operation a percent was taken of. */\n basis_amount: string | null;\n basis_currency: string | null;\n /** Bonuses, decimal string. */\n units: string;\n /** Always `bonus`. */\n payout_kind: string;\n /** `pending` until the bonuses are on the account. */\n status: \"pending\" | \"credited\" | (string & {});\n created_at: string;\n}\n\nexport interface Referral {\n code: string | null;\n /** The invitation link, or `null` when the deployment has none: share the code then. */\n link: string | null;\n invited_count: number;\n /** The latest invited, newest first. */\n invited: InvitedFriend[];\n /** Bonuses earned in total, decimal string. */\n total_rewarded: string;\n rewards: ReferralReward[];\n}\n\nexport class ReferralResource {\n constructor(private readonly http: HttpClient) {}\n\n /** The user's referral code, link, invited friends and rewards. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Referral> {\n return this.http.get<Referral>(\"/me/referral\", { signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Subscription resource — `client.subscription.*`.\n *\n * The user's own paid tier or gift: the discounts it gives and, for a\n * gift, when it ends. Not to be confused with `client.subscriptions`, which\n * is about announcement channels.\n *\n * Mirrors `GET /me/subscription`, `PUT /me/subscription/promo-code` and\n * `POST /me/subscription/cancel`.\n */\n\nexport interface UserSubscription {\n id: string;\n tier_id: string;\n tier_name: string;\n /** The plan's own picture, WebP or SVG, as an absolute URL. `null` when\n * the plan has none: show your generic one. Platforms before 0.8.4 leave\n * it out. */\n tier_icon_url?: string | null;\n /** `active`, `tryout`, `grace`, `cancelled` or `expired`. */\n status: string;\n /** `billing` (charged monthly) or `gift` (never charged). */\n kind: \"billing\" | \"gift\" | (string & {});\n /** For a gift: when it ends; `null` = no end date. */\n gift_until: string | null;\n monthly_fee: string;\n currency: string;\n /** Discount on card prices, basis points. */\n issuance_discount_bps: number;\n /** Discount on the top-up commission, basis points. */\n funding_discount_bps: number;\n started_at: string;\n current_period_end: string | null;\n /** The promo code the monthly fee is charged with, if any. */\n promo_code_id: string | null;\n}\n\n/** What cancelling did. */\nexport interface CancelledSubscription {\n /** The subscription, now `cancelled`. */\n subscription: UserSubscription | null;\n /** What went back to the balance for the unused days of the paid period,\n * decimal string; `\"0\"` for a gift, a trial or an unpaid renewal. */\n refund: string;\n currency: string;\n}\n\nexport class SubscriptionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** The user's subscription, or `null` when there is none. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<UserSubscription | null> {\n return this.http.get<UserSubscription | null>(\"/me/subscription\", { signal: opts.signal });\n }\n\n /**\n * Charge the monthly fee with a promo code, as long as the code allows.\n * `null` removes it. A code that can't be used on the fee fails with 400\n * `promo_code_*`; no paid subscription running → 404.\n */\n async setPromoCode(code: string | null): Promise<UserSubscription> {\n return this.http.put<UserSubscription>(\"/me/subscription/promo-code\", { body: { code } });\n }\n\n /**\n * Cancel the subscription now, in one step. What was paid for the current\n * period comes back to the balance for the days not used. No subscription\n * running → 404; 503 `refund_unavailable` when the refund can't be made\n * right now (the subscription keeps running; try again).\n */\n async cancel(): Promise<CancelledSubscription> {\n return this.http.post<CancelledSubscription>(\"/me/subscription/cancel\", {});\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Branding resource — `client.branding.*`.\n *\n * Runtime white-label config published by the deployment at `GET /branding`\n * (public, no auth). Lets a Cusfront re-theme itself on the fly — platform\n * name, logo, favicon, brand colours and the label used for the end-user's balance — without\n * a rebuild. Pairs with the build-time `BrandConfig`: the server-side values\n * win whenever both are present.\n */\n\n/** Public brand config of the deployment. All strings; empty = use the client default. */\nexport interface Branding {\n /** Platform display name (e.g. the white-label brand). */\n platform_name: string;\n /** Name of the merchant-facing portal. */\n merchant_portal_name: string;\n /** Logo image — absolute URL or `data:` URI. Empty → client default. */\n logo_url: string;\n /** Favicon — absolute URL or `data:` URI. Empty → client default. */\n favicon_url: string;\n /** User-facing name of the balance, e.g. `\"Wallet\"` or `\"Acme Wallet\"`.\n * Display-only: the `balance` API shape never changes with it. */\n wallet_label: string;\n /** Primary brand colour as `#rrggbb`. Empty → client default palette. */\n primary_color: string;\n /** Secondary brand colour as `#rrggbb`. Empty → client default palette. */\n secondary_color: string;\n /** Accent colour as `#rrggbb`. Empty → client default palette. */\n accent_color: string;\n}\n\nexport class BrandingResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Fetch the deployment's public brand config. Safe to call before login. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Branding> {\n return this.http.get<Branding>(\"/branding\", { skipAuth: true, signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Wallet resource — `client.wallet.*`.\n *\n * Which currency the user's wallet is held in. Deposits in any other\n * currency are converted on funding (quote first, see `client.deposits`);\n * cards issued in another currency are paid from the wallet with an FX leg\n * at issuance. A user may switch currency only while every balance is zero\n * and only to a currency the deployment offers (`allowed`).\n */\n\n/** The user's wallet currency and what they may switch to. */\nexport interface Wallet {\n /** ISO 4217 code the wallet is held in. */\n currency: string;\n /** `true` when chosen by the user (or set by an operator), `false` when it\n * is the deployment default. */\n explicit: boolean;\n /** Currencies accepted by `set()`. */\n allowed: string[];\n}\n\nexport class WalletResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Current wallet currency + the currencies the user may switch to. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Wallet> {\n return this.http.get<Wallet>(\"/me/wallet\", { signal: opts.signal });\n }\n\n /**\n * Switch the wallet currency. Fails with `409 wallet_not_empty` while any\n * balance is non-zero, and `400 currency_not_allowed` for a currency the\n * deployment does not offer.\n */\n async set(currency: string, opts: { signal?: AbortSignal } = {}): Promise<Wallet> {\n return this.http.put<Wallet>(\"/me/wallet\", { body: { currency }, signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Blog resource — `client.blog.*`.\n *\n * @deprecated The blog is a category of Documents now. Use\n * `client.documents.list({ category: \"blog\" })` and `client.documents.get(slug)`:\n * same posts, same slugs, same block shape, plus the folder trail and the\n * version history. `/blog/*` on the API answers for one more release and then\n * goes away; this class goes with it.\n *\n * Posts are public: these calls work before the user logs in, which is what\n * a marketing page or a Mini App landing screen needs.\n *\n * A post arrives as a **structured document**, not as HTML. `body_blocks` is\n * a flat list of typed nodes; map each `type` onto your own component and the\n * post inherits your site's styling. `body_markdown` is there too if you'd\n * rather run your own renderer.\n *\n * ```ts\n * const { posts } = await client.blog.list({ perPage: 5 });\n * const post = await client.blog.get(posts[0].slug);\n *\n * post.body_blocks.map((b) => {\n * switch (b.type) {\n * case \"heading\": return <Heading level={b.level}>{b.text}</Heading>;\n * case \"paragraph\": return <P>{b.text}</P>;\n * case \"image\": return <Figure src={b.url} alt={b.alt} caption={b.caption} />;\n * case \"list\": return <List ordered={b.ordered} items={b.items} />;\n * case \"quote\": return <Quote>{b.text}</Quote>;\n * case \"code\": return <Code lang={b.lang}>{b.text}</Code>;\n * case \"divider\": return <Hr />;\n * }\n * });\n * ```\n *\n * Inline emphasis (`**bold**`, `[link](url)`) is left as Markdown inside\n * block text — every renderer already knows what to do with it.\n */\n\n/** One node of a post body. Discriminated on `type`. */\nexport type BlogBlock =\n | { type: \"heading\"; level: number; text: string }\n | { type: \"paragraph\"; text: string }\n | { type: \"image\"; url: string; alt?: string; caption?: string }\n | { type: \"list\"; ordered: boolean; items: string[] }\n | { type: \"quote\"; text: string }\n | { type: \"code\"; lang?: string; text: string }\n | { type: \"divider\" };\n\nexport interface BlogPost {\n /** Stable public key — link by this. */\n slug: string;\n title: string;\n /** Teaser for cards; falls back to the first paragraph. */\n excerpt: string;\n /** Image URL, relative to the API origin. Absent when no cover is set. */\n cover_url?: string;\n /** Raw Markdown, for consumers that bring their own renderer. */\n body_markdown: string;\n /** The recommended input for rendering — see the module docs. */\n body_blocks: BlogBlock[];\n tags: string[];\n /** Present only when the post declares one. */\n locale?: string;\n /** Rough read time in minutes (minimum 1). */\n reading_minutes: number;\n published_at: string | null;\n updated_at: string;\n}\n\nexport interface BlogListInput {\n /** 1-based. Default 1. */\n page?: number;\n /** 1..=50. Default 10. */\n perPage?: number;\n /** Only posts carrying this tag. */\n tag?: string;\n /** Only posts in this locale. */\n locale?: string;\n}\n\nexport interface BlogList {\n posts: BlogPost[];\n total: number;\n page: number;\n per_page: number;\n}\n\n/** @deprecated See the module docs: use `client.documents`. */\nexport class BlogResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Published posts, newest first. No authentication required. */\n async list(input: BlogListInput = {}): Promise<BlogList> {\n const q = new URLSearchParams();\n if (input.page) q.set(\"page\", String(input.page));\n if (input.perPage) q.set(\"per_page\", String(input.perPage));\n if (input.tag) q.set(\"tag\", input.tag);\n if (input.locale) q.set(\"locale\", input.locale);\n const qs = q.toString();\n return this.http.get<BlogList>(`/blog/posts${qs ? `?${qs}` : \"\"}`, {\n skipAuth: true,\n });\n }\n\n /** One post by slug. No authentication required. */\n async get(slug: string): Promise<BlogPost> {\n return this.http.get<BlogPost>(`/blog/posts/${encodeURIComponent(slug)}`, {\n skipAuth: true,\n });\n }\n\n /**\n * Absolute URL for an image path returned inside a post (`cover_url`, or an\n * image block's `url`). Handy when the app renders on a different origin\n * than the API.\n */\n imageUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return `${baseUrl.replace(/\\/$/, \"\")}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Documents resource: `client.documents.*`.\n *\n * Everything the operators write lives in one tree: blog posts, the\n * knowledge base, legal pages, internal notes. Every call here works before\n * the user signs in and shows more once they have: a signed-in user sees the\n * documents marked for users, staff see theirs. The SDK sends the session\n * token when it has one, so the same call serves the public site and the\n * signed-in cabinet.\n *\n * A document arrives as a list of typed blocks. `body_blocks` is flat; map\n * each `type` onto your own component and the document inherits your site's\n * styling. `body_markdown` is there too if you'd rather run your own renderer.\n *\n * ```ts\n * // The knowledge base: folders and articles for a sidebar.\n * const tree = await client.documents.tree({ category: \"knowledge-base\" });\n *\n * // One article, with the text in force today.\n * const doc = await client.documents.get(\"how-to-top-up\");\n *\n * // A legal page as it read on a given day, and its history.\n * const then = await client.documents.get(\"offer\", { at: \"2026-01-01T00:00:00Z\" });\n * const versions = await client.documents.versions(\"offer\");\n *\n * doc.body_blocks.map((b) => {\n * switch (b.type) {\n * case \"heading\": return <Heading level={b.level}>{b.text}</Heading>;\n * case \"paragraph\": return <P>{b.text}</P>;\n * case \"image\": return <Figure src={client.assetUrl(b.url)} alt={b.alt} caption={b.caption} />;\n * case \"list\": return <List ordered={b.ordered} items={b.items} />;\n * case \"quote\": return <Quote>{b.text}</Quote>;\n * case \"code\": return <Code lang={b.lang}>{b.text}</Code>;\n * case \"divider\": return <Hr />;\n * }\n * });\n * ```\n *\n * Links between documents come out as site paths: `/blog/<slug>` for a post,\n * `/docs/<slug>` for everything else (`site_path` on each document says which\n * one it is). Route those two prefixes to your document pages and links keep\n * working after a document is renamed or moved.\n */\n\n/** Category keys: the four folders at the top of the tree. */\nexport type DocumentCategory = \"blog\" | \"knowledge-base\" | \"legal\" | \"internal\";\n\n/** Who may read a document. */\nexport type DocumentScope = \"public\" | \"users\" | \"staff\" | \"operators\";\n\n/** One node of a document body. Discriminated on `type`. */\nexport type DocumentBlock =\n | { type: \"heading\"; level: number; text: string }\n | { type: \"paragraph\"; text: string }\n | { type: \"image\"; url: string; alt?: string; caption?: string }\n | { type: \"list\"; ordered: boolean; items: string[] }\n | { type: \"quote\"; text: string }\n | { type: \"code\"; lang?: string; text: string }\n | { type: \"divider\" };\n\n/** One step of the folder trail, root first. */\nexport interface DocumentPathStep {\n id: string;\n key: string;\n title: string;\n}\n\nexport interface Document {\n /** Permanent address. Link by this; it survives renames and moves. */\n slug: string;\n title: string;\n /** Teaser for cards; falls back to the first paragraph. */\n excerpt: string;\n /** Image URL, relative to the API origin. Absent when no cover is set. */\n cover_url?: string;\n /** Raw Markdown, for consumers that bring their own renderer. */\n body_markdown: string;\n /** The recommended input for rendering; see the module docs. */\n body_blocks: DocumentBlock[];\n tags: string[];\n /** Present only when the document declares one. */\n locale?: string;\n /** Rough read time in minutes (minimum 1). */\n reading_minutes: number;\n published_at: string | null;\n updated_at: string;\n /** Category the document sits in. */\n category: DocumentCategory | string;\n /** Folder trail, root first. */\n path: DocumentPathStep[];\n /** Who may read it. */\n read_scope: DocumentScope;\n /** Number of the text shown. */\n version: number;\n /** When the text shown took effect. */\n effective_from: string;\n /** Path under the site root where this document is read. */\n site_path: string;\n}\n\nexport interface DocumentListInput {\n /** Category key. */\n category?: DocumentCategory | string;\n /** Only documents in this folder and the folders under it. */\n folderId?: string;\n /** Only documents carrying this tag. */\n tag?: string;\n /** Only documents in this locale. */\n locale?: string;\n /** Words to search for in the title and the text. */\n q?: string;\n /** 1-based. Default 1. */\n page?: number;\n /** 1..=50. Default 10. */\n perPage?: number;\n}\n\nexport interface DocumentList {\n documents: Document[];\n total: number;\n page: number;\n per_page: number;\n}\n\n/** A folder as it appears in the navigation tree. */\nexport interface DocumentFolder {\n id: string;\n parent_id: string | null;\n key: string;\n title: string;\n description: string;\n position: number;\n}\n\n/** A document as it appears in the navigation tree: enough for a link. */\nexport interface DocumentTreeEntry {\n folder_id: string;\n slug: string;\n title: string;\n excerpt: string;\n tags: string[];\n position: number;\n updated_at: string;\n site_path: string;\n}\n\nexport interface DocumentTree {\n /** Folders with at least one document you may read under them, plus the categories. */\n folders: DocumentFolder[];\n /** Published documents you may read, in folder order. */\n documents: DocumentTreeEntry[];\n}\n\n/** One saved text of a document, without the text itself. */\nexport interface DocumentVersionSummary {\n version: number;\n title: string;\n /** When this text took effect. */\n effective_from: string;\n /** What changed, in the editor's words. Often empty. */\n note: string;\n changed_at: string;\n}\n\nexport interface DocumentTag {\n tag: string;\n /** Published documents you may read that carry it. */\n count: number;\n}\n\nexport class DocumentsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Published documents you may read, paged. The blog comes newest first,\n * other categories in the order set by the editors.\n */\n async list(input: DocumentListInput = {}): Promise<DocumentList> {\n const q = new URLSearchParams();\n if (input.category) q.set(\"category\", input.category);\n if (input.folderId) q.set(\"folder_id\", input.folderId);\n if (input.tag) q.set(\"tag\", input.tag);\n if (input.locale) q.set(\"locale\", input.locale);\n if (input.q) q.set(\"q\", input.q);\n if (input.page) q.set(\"page\", String(input.page));\n if (input.perPage) q.set(\"per_page\", String(input.perPage));\n const qs = q.toString();\n return this.http.get<DocumentList>(`/documents${qs ? `?${qs}` : \"\"}`);\n }\n\n /** Folders and documents for a sidebar or a table of contents. */\n async tree(input: { category?: DocumentCategory | string } = {}): Promise<DocumentTree> {\n const qs = input.category ? `?category=${encodeURIComponent(input.category)}` : \"\";\n return this.http.get<DocumentTree>(`/documents/tree${qs}`);\n }\n\n /** Every tag on a document you may read, most used first. */\n async tags(): Promise<DocumentTag[]> {\n return this.http.get<DocumentTag[]>(\"/documents/tags\");\n }\n\n /**\n * One document by its address. Without `at`, the text in force now; with\n * `at` (an ISO 8601 moment), the text that was in force then. Unknown\n * addresses and documents above your level are a 404.\n */\n async get(slug: string, opts: { at?: string | Date } = {}): Promise<Document> {\n const at = opts.at instanceof Date ? opts.at.toISOString() : opts.at;\n const qs = at ? `?at=${encodeURIComponent(at)}` : \"\";\n return this.http.get<Document>(`/documents/${encodeURIComponent(slug)}${qs}`);\n }\n\n /** Every saved text of a document, newest first, with the date each took effect. */\n async versions(slug: string): Promise<DocumentVersionSummary[]> {\n return this.http.get<DocumentVersionSummary[]>(\n `/documents/${encodeURIComponent(slug)}/versions`,\n );\n }\n\n /** The document as it read in one version. */\n async version(slug: string, version: number): Promise<Document> {\n return this.http.get<Document>(`/documents/${encodeURIComponent(slug)}/versions/${version}`);\n }\n\n /**\n * Absolute URL for an image path returned inside a document (`cover_url`,\n * or an image block's `url`). Handy when the app renders on a different\n * origin than the API.\n */\n imageUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return `${baseUrl.replace(/\\/$/, \"\")}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Subscriptions resource — `client.subscriptions.*`.\n *\n * Which channels the signed-in user agreed to receive announcements on.\n * `available` tells you which toggles to render: a deployment with no\n * Telegram bot configured can't deliver there, so offering the switch would\n * be a lie.\n *\n * ```ts\n * const { channels, available } = await client.subscriptions.get();\n * await client.subscriptions.set([...channels, \"telegram\"]);\n * ```\n *\n * Unrelated to paid/VIP tiers — this is only about announcements.\n *\n * @deprecated Announcements are now the `marketing` category of the\n * notification preferences. Read them with\n * `client.notifications.getPreferences()` and change them with\n * `client.notifications.setPreferences({ categories: { marketing: { email: true, telegram: false } } })`.\n * This endpoint keeps working as an alias over that setting.\n */\n\nexport type BroadcastChannel = \"email\" | \"telegram\" | (string & {});\n\nexport interface Subscriptions {\n /** Channels the user currently receives announcements on. */\n channels: BroadcastChannel[];\n /** Channels this deployment can actually deliver on. */\n available: BroadcastChannel[];\n}\n\n/** @deprecated See the note at the top of this module. */\nexport class SubscriptionsResource {\n constructor(private readonly http: HttpClient) {}\n\n async get(): Promise<Subscriptions> {\n return this.http.get<Subscriptions>(\"/me/subscriptions\");\n }\n\n /**\n * Replace the whole set — this is a PUT, not a merge. Pass `[]` to opt out\n * of everything.\n */\n async set(channels: BroadcastChannel[]): Promise<Subscriptions> {\n return this.http.put<Subscriptions>(\"/me/subscriptions\", {\n body: { channels },\n });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Sessions resource — `client.sessions.*`.\n *\n * Every device or browser the user is signed in on. Lets a settings screen\n * show \"where you're signed in\" and sign one or all of them out.\n *\n * ```ts\n * const sessions = await client.sessions.list();\n * const others = sessions.filter((s) => !s.current);\n * await client.sessions.revokeOthers();\n * ```\n */\n\nexport interface UserSession {\n /** Session id; pass it to `revoke`. */\n jti: string;\n issued_at: string;\n expires_at: string;\n last_seen_at: string;\n /** Client IP recorded for the session, if known. */\n remote_ip?: string | null;\n /** Browser or app that opened the session, if known. */\n user_agent?: string | null;\n /** `true` for the session this client is using. */\n current: boolean;\n}\n\nexport class SessionsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** All live sessions of the account, this one included. */\n async list(): Promise<UserSession[]> {\n return this.http.get<UserSession[]>(\"/me/sessions\");\n }\n\n /** Sign out one session. Works on the current one too; the stored JWT\n * stops working, so follow with `client.auth.signOut()`.\n * 404 when the session is unknown or already signed out. */\n async revoke(jti: string): Promise<void> {\n await this.http.delete<void>(`/me/sessions/${encodeURIComponent(jti)}`);\n }\n\n /** Sign out every session except this one. */\n async revokeOthers(): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/me/sessions/terminate-others\");\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Push resource — `client.push.*`.\n *\n * Web Push for the signed-in user, through the older single-subscription\n * endpoint. The API now keeps one device per browser (see\n * `client.devices`), and this endpoint is an alias over the Web Push\n * devices: it keeps working, but new code should call\n * `client.devices.registerWebPush(reg)` / `unregisterWebPush(reg)` instead.\n *\n * Your service worker shows the notification: the payload is JSON with\n * `title`, `body` and `url` (where a click should lead).\n */\n\nexport interface PushStatus {\n /** `true` when a subscription is stored for this user. */\n subscribed: boolean;\n /** Host of the stored endpoint, e.g. `fcm.googleapis.com`. */\n endpoint_host?: string | null;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`.\n * `null` when push is not set up on this deployment. */\n vapid_public_key?: string | null;\n}\n\nexport interface PushSubscriptionInput {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** The part of `ServiceWorkerRegistration` the SDK needs. Typed\n * structurally so the core stays free of DOM lib types. */\nexport interface PushCapableRegistration {\n pushManager: {\n getSubscription(): Promise<{ unsubscribe(): Promise<boolean> } | null>;\n subscribe(options: {\n userVisibleOnly: boolean;\n applicationServerKey: Uint8Array;\n }): Promise<{ toJSON(): { endpoint?: string; keys?: Record<string, string> } }>;\n };\n}\n\nexport class PushResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Whether the user is subscribed, plus the VAPID key to subscribe with. */\n async status(): Promise<PushStatus> {\n return this.http.get<PushStatus>(\"/me/push-subscription\");\n }\n\n /** Store a subscription you created yourself.\n * 409 `push_disabled` when the deployment has no VAPID keys.\n * @deprecated Use `client.devices.register({ kind: \"webpush\", ... })`. */\n async save(input: PushSubscriptionInput): Promise<PushStatus> {\n return this.http.put<PushStatus>(\"/me/push-subscription\", { body: input });\n }\n\n /** Delete the stored subscription. Safe when nothing is stored.\n * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */\n async remove(): Promise<void> {\n await this.http.delete<void>(\"/me/push-subscription\");\n }\n\n /** Subscribe this browser and store the subscription. Ask for\n * notification permission before calling. Throws when push isn't set up\n * on the deployment.\n * @deprecated Use `client.devices.registerWebPush(registration)`. */\n async enable(registration: PushCapableRegistration): Promise<PushStatus> {\n const { vapid_public_key } = await this.status();\n if (!vapid_public_key) {\n throw new Error(\n \"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\",\n );\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(vapid_public_key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.save({\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n });\n }\n\n /** Unsubscribe this browser and delete the stored subscription.\n * @deprecated Use `client.devices.unregisterWebPush(registration)`. */\n async disable(registration: PushCapableRegistration): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n await this.remove();\n }\n}\n\n/** URL-safe base64 (padding optional) → bytes. */\nexport function base64UrlToBytes(input: string): Uint8Array {\n const b64 = input.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = b64 + \"=\".repeat((4 - (b64.length % 4)) % 4);\n const bin = atob(padded);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { User } from \"./auth.js\";\n\n/**\n * Me resource — `client.me.*`.\n *\n * Profile-level actions for the signed-in user that don't belong to another\n * resource. Today: the Telegram link.\n *\n * ```ts\n * // Inside a Mini App, with a signed-in client (e.g. opened via a deep link):\n * const me = await client.me.linkTelegram(window.Telegram.WebApp.initData);\n * me.telegram; // { username, linked_at }\n *\n * // From a settings screen:\n * await client.me.unlinkTelegram();\n * ```\n */\nexport class MeResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Attach the Telegram account behind `initData` to the signed-in user.\n * Returns the updated user (`telegram` is set). Repeating the call with\n * the same Telegram is fine.\n *\n * Errors: 401 `invalid_init_data`; 403 `user_disabled` /\n * `second_factor_required`; 409 `telegram_already_linked_other` (the\n * account already has a different Telegram; `unlinkTelegram` first) /\n * `telegram_in_use` (that Telegram belongs to another account); 503\n * `telegram_not_configured`. */\n async linkTelegram(initData: string): Promise<User> {\n return this.http.post<User>(\"/me/telegram\", { body: { init_data: initData } });\n }\n\n /** Detach the Telegram account from the signed-in user. Returns the\n * updated user (`telegram` is `null`).\n *\n * Errors: 404 `telegram_not_linked`; 409 `last_credential` when the\n * account has no password, so Telegram is its only way to sign in. */\n async unlinkTelegram(): Promise<User> {\n return this.http.delete<User>(\"/me/telegram\");\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Notifications resource — `client.notifications.*`.\n *\n * Every notification a user gets is also kept server-side as an inbox item,\n * whatever else was sent (a push, a Telegram message, an email). The inbox\n * is what the app shows; the other channels are the nudge to open it.\n *\n * ```ts\n * const page = await client.notifications.list({ limit: 20 });\n * for (const item of page.items) {\n * render(item.title, item.body, item.href); // href: a path inside your app, or null\n * }\n * await client.notifications.markRead(page.items[0].id);\n * ```\n *\n * Preferences decide where the nudge goes: a primary channel (or automatic\n * when `null`), per-category switches, and the user's language.\n */\n\n/** What an item is about. `security` and `money` can't be switched off\n * completely; `marketing` is off until the user opts in. */\nexport type NotificationCategory = \"money\" | \"card\" | \"security\" | \"account\" | \"marketing\";\n\n/** A way to reach the user outside the inbox. */\nexport type NotificationChannel = \"push\" | \"telegram\" | \"email\" | \"sms\";\n\n/** Language the user reads notifications in. */\nexport type NotificationLocale = \"en\" | \"ru\" | (string & {});\n\n/**\n * `data` of a `card_otp` item: a confirmation code the card issuer sent for a\n * 3-D Secure payment (`purpose: \"payment\"`) or for adding the card to Apple\n * Pay / Google Pay (`purpose: \"wallet\"`). The code is what the user needs\n * right now, so show it prominently with a copy button and a countdown from\n * `expires_in_minutes`; `merchant_name`, `amount` and `currency` are absent\n * for wallet codes. Narrow with `isCardOtp(item)`.\n */\nexport interface CardOtpData {\n otp: string;\n purpose: \"payment\" | \"wallet\";\n merchant_name?: string;\n amount?: string;\n currency?: string;\n last4?: string;\n card_id?: string;\n expires_in_minutes?: number;\n}\n\n/** True when the item carries a card confirmation code (`CardOtpData`). */\nexport function isCardOtp(\n item: InboxItem,\n): item is InboxItem & { event_type: \"card_otp\"; data: CardOtpData } {\n return item.event_type === \"card_otp\" && typeof item.data?.otp === \"string\";\n}\n\nexport interface InboxItem {\n id: string;\n /** What happened, e.g. `deposit_confirmed`, `card_transaction`,\n * `login_new_device`, `card_otp` (see `CardOtpData`). */\n event_type: string;\n category: NotificationCategory;\n title: string;\n body: string;\n /** A path inside the client app to open on tap (`/cards/<id>`,\n * `/deposits/<id>`, `/subscription`, `/settings/sessions`), or `null`. */\n href: string | null;\n /** Event details (amount, currency, card last four and so on); the keys\n * depend on `event_type`. */\n data: Record<string, unknown>;\n /** Language the item was rendered in. */\n locale: string;\n /** When the user read it, or `null` while unread. */\n read_at: string | null;\n created_at: string;\n}\n\nexport interface NotificationPage {\n /** Newest first. */\n items: InboxItem[];\n /** Pass back as `cursor` to get the next page; `null` on the last one. */\n next_cursor: string | null;\n /** Unread items across the whole inbox, not just this page. */\n unread_count: number;\n}\n\nexport interface ListNotificationsParams {\n /** `next_cursor` from the previous page. */\n cursor?: string;\n /** Page size; the server caps it. */\n limit?: number;\n /** Only items without `read_at`. */\n unreadOnly?: boolean;\n category?: NotificationCategory;\n}\n\n/** Per-category channel switches: `{ money: { push: true, email: false } }`.\n * A channel missing from a category keeps its default. */\nexport type NotificationCategoryPreferences = Partial<\n Record<NotificationCategory, Partial<Record<NotificationChannel, boolean>>>\n>;\n\nexport interface NotificationPreferences {\n /** The channel to use first; `null` means automatic (the server picks by\n * the user's devices). */\n primary_channel: NotificationChannel | null;\n categories: NotificationCategoryPreferences;\n /** `null` when unset: the server falls back to the Telegram profile's\n * language, then the deployment default. */\n locale: NotificationLocale | null;\n /** Channels this deployment can deliver on. Render toggles only for\n * these. */\n available_channels: NotificationChannel[];\n}\n\n/** Body of `setPreferences`. Every field is optional; only the given ones\n * change. `primary_channel: null` switches back to automatic. */\nexport interface NotificationPreferencesInput {\n primary_channel?: NotificationChannel | null;\n categories?: NotificationCategoryPreferences;\n locale?: NotificationLocale | null;\n}\n\nexport class NotificationsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** One page of the inbox, newest first. */\n async list(params: ListNotificationsParams = {}): Promise<NotificationPage> {\n const q = new URLSearchParams();\n if (params.cursor) q.set(\"cursor\", params.cursor);\n if (params.limit !== undefined) q.set(\"limit\", String(params.limit));\n if (params.unreadOnly) q.set(\"unread\", \"true\");\n if (params.category) q.set(\"category\", params.category);\n const qs = q.toString();\n return this.http.get<NotificationPage>(`/me/notifications${qs ? `?${qs}` : \"\"}`);\n }\n\n /** How many items are unread. Cheap; fine to poll for a badge. */\n async unreadCount(): Promise<number> {\n const { unread } = await this.http.get<{ unread: number }>(\"/me/notifications/unread-count\");\n return unread;\n }\n\n /** Mark one item read. Returns the item; calling it again is harmless. */\n async markRead(id: string): Promise<InboxItem> {\n return this.http.post<InboxItem>(`/me/notifications/${encodeURIComponent(id)}/read`);\n }\n\n /** Mark every unread item read, or only those created before `before`\n * (ISO timestamp). Returns how many changed. */\n async markAllRead(before?: string): Promise<{ marked: number }> {\n return this.http.post<{ marked: number }>(\"/me/notifications/read-all\", {\n body: before ? { before } : {},\n });\n }\n\n /** Delete one item. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/notifications/${encodeURIComponent(id)}`);\n }\n\n /** The user's channel and language settings. */\n async getPreferences(): Promise<NotificationPreferences> {\n return this.http.get<NotificationPreferences>(\"/me/notification-preferences\");\n }\n\n /** Change some settings; the rest stay. Returns the stored view.\n * 400 `validation` for an unknown category, channel or locale. */\n async setPreferences(input: NotificationPreferencesInput): Promise<NotificationPreferences> {\n return this.http.put<NotificationPreferences>(\"/me/notification-preferences\", {\n body: input,\n });\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { ClientPlatform, ResolvedClientDescriptor } from \"../client-platform.js\";\nimport { base64UrlToBytes, type PushCapableRegistration } from \"./push.js\";\n\n/**\n * Devices resource — `client.devices.*`.\n *\n * A user has many devices: each browser with a Web Push subscription, each\n * phone with an FCM / APNs token, and a marker for \"uses the Telegram Mini\n * App\". The server picks the notification channel from them: a mobile app\n * first, otherwise the device seen most recently.\n *\n * The usual browser flow, once notification permission is granted:\n *\n * ```ts\n * const reg = await navigator.serviceWorker.ready;\n * const device = await client.devices.registerWebPush(reg, { label: \"Chrome on Mac\" });\n * // later, from a settings screen:\n * await client.devices.unregisterWebPush(reg);\n * ```\n */\n\nexport type DeviceKind = \"webpush\" | \"fcm\" | \"apns\" | \"telegram_miniapp\";\n\nexport type DevicePlatform = \"pwa\" | \"web\" | \"ios\" | \"android\" | \"telegram\";\n\nexport interface Device {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** Free-form name the app gave it (\"Chrome on Mac\"), or `null`. */\n label: string | null;\n locale: string | null;\n app_version: string | null;\n created_at: string;\n last_seen_at: string;\n /** Set when the device no longer receives anything (the push endpoint is\n * gone, or someone switched it off). */\n disabled_at: string | null;\n /** `true` when it was registered from the session this client holds. */\n is_current: boolean;\n}\n\n/** `PushSubscription.toJSON()` minus the parts the server doesn't need. */\nexport interface WebPushCredential {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** FCM registration token or APNs device token. */\nexport interface MobilePushCredential {\n token: string;\n}\n\nexport type RegisterDeviceInput =\n | {\n kind: \"webpush\";\n platform: DevicePlatform;\n credential: WebPushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"fcm\" | \"apns\";\n platform: DevicePlatform;\n credential: MobilePushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"telegram_miniapp\";\n platform: DevicePlatform;\n /** Nothing to send: the device is a marker. */\n credential: Record<string, never>;\n label?: string;\n locale?: string;\n app_version?: string;\n };\n\nexport interface RegisteredDevice {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`;\n * `null` when push is not set up on this deployment. */\n vapid_public_key: string | null;\n}\n\nexport interface RegisterWebPushOptions {\n /** A name to show in the user's device list (\"Chrome on Mac\"). */\n label?: string;\n /** Skip the key lookup when you already hold the deployment's VAPID\n * public key (from an earlier `register` result, for example). */\n vapidPublicKey?: string;\n}\n\nexport interface UnregisterWebPushOptions {\n /** The device to delete, from an earlier `registerWebPush` result. When\n * omitted, every Web Push device registered from this session goes. */\n deviceId?: string;\n}\n\n/** Client platform → the platform the device list uses. */\nexport function devicePlatformOf(platform: ClientPlatform): DevicePlatform {\n return platform === \"telegram-miniapp\" ? \"telegram\" : platform;\n}\n\nexport class DevicesResource {\n constructor(\n private readonly http: HttpClient,\n private readonly client: ResolvedClientDescriptor,\n ) {}\n\n /** Every device the user has, disabled ones included. */\n async list(): Promise<Device[]> {\n return this.http.get<Device[]>(\"/me/devices\");\n }\n\n /** Register a device, or refresh it when the same credential is already\n * known (then `last_seen_at`, `label` and `app_version` update and a\n * disabled device comes back). `app_version` defaults to the client\n * version sent in `X-Takeal-Client`.\n *\n * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the\n * deployment has no VAPID keys. */\n async register(input: RegisterDeviceInput): Promise<RegisteredDevice> {\n return this.http.put<RegisteredDevice>(\"/me/devices\", {\n body: { app_version: this.client.version, ...input },\n });\n }\n\n /** Delete one device. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/devices/${encodeURIComponent(id)}`);\n }\n\n /** Subscribe this browser to Web Push and register it as a device. Ask\n * for notification permission before calling. Throws when push isn't\n * set up on the deployment. */\n async registerWebPush(\n registration: PushCapableRegistration,\n opts: RegisterWebPushOptions = {},\n ): Promise<RegisteredDevice> {\n const key = opts.vapidPublicKey ?? (await this.vapidPublicKey());\n if (!key) {\n throw new Error(\n \"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\",\n );\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.register({\n kind: \"webpush\",\n platform: devicePlatformOf(this.client.platform),\n credential: {\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n },\n ...(opts.label ? { label: opts.label } : {}),\n });\n }\n\n /** Unsubscribe this browser from Web Push and delete the matching device\n * (see {@link UnregisterWebPushOptions}). Safe when nothing is\n * registered. */\n async unregisterWebPush(\n registration: PushCapableRegistration,\n opts: UnregisterWebPushOptions = {},\n ): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n if (opts.deviceId) {\n await this.remove(opts.deviceId);\n return;\n }\n const mine = (await this.list()).filter((d) => d.kind === \"webpush\" && d.is_current);\n for (const d of mine) await this.remove(d.id);\n }\n\n private async vapidPublicKey(): Promise<string | null> {\n const { vapid_public_key } = await this.http.get<{ vapid_public_key?: string | null }>(\n \"/me/push-subscription\",\n );\n return vapid_public_key ?? null;\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * History resource — `client.history.*`: everything that happened to the\n * user's money in one list, newest first.\n *\n * ```ts\n * const page = await client.history.list({ limit: 30 });\n * const more = await client.history.list({ cursor: page.next_cursor! });\n * const oneCard = await client.history.list({ cardId: card.id });\n * for await (const item of client.history.all()) { … }\n * ```\n *\n * New kinds are added over time. Render an unknown `kind` from its `title`,\n * `amount`, `direction` and `status`; don't drop it.\n */\n\nexport type HistoryKind =\n | \"card_purchase\"\n | \"card_refund\"\n | \"card_issued\"\n | \"card_topup\"\n | \"card_transfer\"\n | \"wallet_deposit\"\n | \"deposit_refund\"\n | \"fee\"\n | \"balance_adjustment\"\n | \"bonus\"\n /**\n * What was left on a closed card moving to the card that replaced it:\n * `card` is the old card, `to_card` the new one. `pending` until the\n * issuer returns the money and it is on the new card. If the new card\n * could not take it, the money went to the wallet and `title` says so.\n */\n | \"closed_card_balance\"\n /** A fee for using the card: a payment, a declined payment, a cash withdrawal. */\n | \"card_fee\"\n /** Money that paid card fees owed. */\n | \"debt_payment\"\n // Any kind added later still type-checks.\n | (string & {});\n\nexport type HistoryStatus =\n \"completed\" | \"pending\" | \"declined\" | \"reversed\" | \"failed\" | (string & {});\n\nexport interface HistoryAmount {\n /** Decimal string, never negative; see `direction`. */\n amount: string;\n /** ISO 4217 code. */\n currency: string;\n}\n\nexport interface HistoryCard {\n id: string;\n name: string | null;\n last4: string | null;\n}\n\nexport interface HistoryItem {\n /** Unique across kinds. */\n id: string;\n kind: HistoryKind;\n occurred_at: string;\n /** `pending` is not finished yet; `reversed` is an authorisation that was released. */\n status: HistoryStatus;\n /** `out` money left the user, `in` it came in, `internal` it moved between the wallet and the user's cards. */\n direction: \"out\" | \"in\" | \"internal\" | (string & {});\n /** The merchant, or what the operation was, in the language asked for. */\n title: string;\n /**\n * In the currency the operation happened in. For `bonus` the currency is\n * `BNS` and the amount is a number of bonuses, not money.\n */\n amount: HistoryAmount;\n /**\n * The other side of a conversion (what the card was billed, what the\n * wallet or card received). For a `bonus` spend: the part of the price\n * the bonuses covered, or what they added to a top-up.\n */\n counter_amount: HistoryAmount | null;\n /** Rate between `amount` and `counter_amount`, decimal string. */\n fx_rate: string | null;\n /** A fee charged with the operation, in the wallet's currency. */\n fee: HistoryAmount | null;\n /** The card; the source card of a transfer. */\n card: HistoryCard | null;\n /** The destination card of a transfer. */\n to_card: HistoryCard | null;\n merchant: { name: string | null; city: string | null; country: string | null } | null;\n /** On a declined payment: a stable code and the reason in plain words. */\n decline_reason: {\n code:\n | \"insufficient_funds\"\n | \"limit_exceeded\"\n | \"card_blocked\"\n | \"card_expired\"\n | \"wrong_details\"\n | \"merchant_not_allowed\"\n | \"other\"\n | (string & {});\n text: string;\n } | null;\n}\n\nexport interface HistoryPage {\n items: HistoryItem[];\n /** Pass as `cursor` for the next, older page; `null` on the last one. */\n next_cursor: string | null;\n}\n\nexport interface ListHistoryParams {\n /** Only this card's operations, transfers to and from it included. */\n cardId?: string;\n cursor?: string;\n /** 1 to 100, default 30. */\n limit?: number;\n /** `en` or `ru` for titles and decline reasons. Defaults to the browser's language header. */\n lang?: \"en\" | \"ru\";\n signal?: AbortSignal;\n}\n\nexport class HistoryResource {\n constructor(private readonly http: HttpClient) {}\n\n /** One page of the history. Errors: 400 bad cursor or limit, 404 `cardId` is not the user's card. */\n async list(params: ListHistoryParams = {}): Promise<HistoryPage> {\n const q = new URLSearchParams();\n if (params.cardId) q.set(\"card_id\", params.cardId);\n if (params.cursor) q.set(\"cursor\", params.cursor);\n if (params.limit !== undefined) q.set(\"limit\", String(params.limit));\n if (params.lang) q.set(\"lang\", params.lang);\n const qs = q.toString();\n return this.http.get<HistoryPage>(`/me/history${qs ? `?${qs}` : \"\"}`, {\n signal: params.signal,\n });\n }\n\n /** Every entry, page after page, newest first. */\n async *all(params: Omit<ListHistoryParams, \"cursor\"> = {}): AsyncGenerator<HistoryItem> {\n let cursor: string | undefined;\n do {\n const page = await this.list({ ...params, cursor });\n yield* page.items;\n cursor = page.next_cursor ?? undefined;\n } while (cursor);\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport { anonymousKey, forgetAnalyticsIds } from \"./attribution.js\";\n\n/**\n * Consents resource — `client.consents.*`: what the user agreed to.\n *\n * ```ts\n * const { consents } = await client.consents.get();\n * await client.consents.set(\"marketing\", false); // advertising off everywhere\n * ```\n *\n * Consents are first given with the sign-up (`auth.register({ consents })`,\n * `auth.exchangeTelegram({ consents })`) and with a card order\n * (`cards.create({ consents })`). Each one is recorded with the version of\n * its documents in force at that moment; the client sends kinds only.\n *\n * Two of them guard what reaches a card issuer:\n *\n * - `holder_data_transfer`: the user's real personal details go to the card\n * issuer. A product with `holder_data_required` is issued only while it\n * stands; show the consent screen before the order and send the kind in\n * the order's `consents` (or give it with {@link ConsentsResource.allowHolderData}).\n * Without it the order fails with 409 `holder_data_consent_required`.\n * - `dispute_documents_transfer`: the user's documents go to the card issuer\n * when a payment is disputed. Nothing is sent without it; give it with\n * {@link ConsentsResource.allowDisputeDocuments}, naming the disputed card.\n */\n\n/** The user's real personal details go to the card issuer. */\nexport const HOLDER_DATA_CONSENT = \"holder_data_transfer\";\n/** The user's documents go to the card issuer in a dispute. */\nexport const DISPUTE_DOCUMENTS_CONSENT = \"dispute_documents_transfer\";\n\n/** `terms` covers the offer, the tariffs and the privacy policy together. */\nexport type ConsentKind =\n | \"terms\"\n | \"personal_data\"\n | \"marketing\"\n | \"cookies_analytics\"\n | typeof HOLDER_DATA_CONSENT\n | typeof DISPUTE_DOCUMENTS_CONSENT\n // Kinds added later still type-check.\n | (string & {});\n\n/** Where a consent was given. Read from the client header when omitted. */\nexport type ConsentChannel = \"site\" | \"cabinet\" | \"miniapp\" | \"bot\";\n\n/** A document a consent refers to, at the version the user accepted. */\nexport interface ConsentDocument {\n slug: string;\n version: number;\n}\n\nexport interface ConsentState {\n kind: ConsentKind;\n /** Given and not withdrawn since. */\n given: boolean;\n /** When it was last given; `null` if never. */\n given_at: string | null;\n /** When it was withdrawn after that; `null` while it stands. */\n withdrawn_at: string | null;\n /** The documents it referred to when last given. */\n documents: ConsentDocument[];\n /** Can be withdrawn with {@link ConsentsResource.set}. The required ones\n * (`terms`, `personal_data`) can't: closing the account withdraws them. */\n optional: boolean;\n}\n\nexport interface Consents {\n consents: ConsentState[];\n}\n\n/** Where and for what a consent is given with {@link ConsentsResource.set}. */\nexport interface ConsentOptions {\n /** Where it was given. Read from the client header when omitted. */\n channel?: ConsentChannel;\n /**\n * One of the user's cards, for `holder_data_transfer` and\n * `dispute_documents_transfer` only: the card the consent is given for,\n * such as the card a dispute is about. Sent as `card_id` and kept with the\n * consent; a consent given for a card is recorded every time, even when\n * one already stands.\n */\n cardId?: string;\n}\n\nexport interface CookieChoiceInput {\n /** `true`: analytics cookies allowed; `false`: declined. */\n analytics: boolean;\n /** The visitor's anonymous key. Defaults to the one `anonymousKey()`\n * keeps (the key visits are sent with); ignored for a signed-in user. */\n anonymousKey?: string;\n /** Where the choice was made. Read from the client header when omitted. */\n channel?: ConsentChannel;\n}\n\nexport class ConsentsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Where each consent stands. */\n async get(): Promise<Consents> {\n return this.http.get<Consents>(\"/me/consents\");\n }\n\n /** Whether `kind` stands now: given and not withdrawn since. */\n async stands(kind: ConsentKind): Promise<boolean> {\n const { consents } = await this.get();\n return consents.some((c) => c.kind === kind && c.given);\n }\n\n /**\n * Give (`true`) or withdraw (`false`) an optional consent: `marketing`,\n * `cookies_analytics`, `holder_data_transfer` or\n * `dispute_documents_transfer`. Withdrawing `marketing` turns advertising\n * off in every channel at once; giving it turns on advertising by e-mail.\n * Withdrawing `holder_data_transfer` leaves the user's cards alone and\n * stops new cards whose product has `holder_data_required`. A call that\n * changes nothing records nothing, unless it names a card.\n *\n * The third argument is the channel, or {@link ConsentOptions} with the\n * channel and the card.\n *\n * Errors: 400 `consent_required` for `terms` or `personal_data`,\n * 400 `unknown_consent`, 400 `card_not_allowed` (a card named with a kind\n * that takes none), 404 `not_found` (not one of the user's cards).\n */\n async set(\n kind: ConsentKind,\n given: boolean,\n options?: ConsentChannel | ConsentOptions,\n ): Promise<Consents> {\n const opts: ConsentOptions =\n typeof options === \"string\" ? { channel: options } : (options ?? {});\n const body: { kind: ConsentKind; given: boolean; channel?: ConsentChannel; card_id?: string } =\n { kind, given };\n if (opts.channel !== undefined) body.channel = opts.channel;\n if (opts.cardId !== undefined) body.card_id = opts.cardId;\n return this.http.post<Consents>(\"/me/consents\", { body });\n }\n\n /**\n * The user agreed on the consent screen that their real personal details\n * go to the card issuer (`holder_data_transfer`). Needed before ordering a\n * product with `holder_data_required`, unless the order itself carries the\n * kind in its `consents`.\n */\n async allowHolderData(options?: ConsentOptions): Promise<Consents> {\n return this.set(HOLDER_DATA_CONSENT, true, options);\n }\n\n /**\n * The user agreed that their documents go to the card issuer for a\n * dispute (`dispute_documents_transfer`). Name the disputed card with\n * `cardId`; each call is then recorded on its own.\n */\n async allowDisputeDocuments(options?: ConsentOptions): Promise<Consents> {\n return this.set(DISPUTE_DOCUMENTS_CONSENT, true, options);\n }\n\n /**\n * Record what the cookie banner or the cookie settings say about\n * analytics. Works signed in or not: before sign-in the choice is kept\n * under the anonymous key and moves to the account at sign-up (send the\n * same key in `register({ attribution })`). Declining deletes the\n * visitor's recorded visits and analytics ids and stops their conversions\n * going to Metrica. Call it on every change, not on every page load; the\n * same answer twice records nothing (`recorded: false`).\n *\n * Errors: 400 `invalid_anonymous_key` when not signed in and no key could\n * be found.\n */\n async setCookies(input: CookieChoiceInput): Promise<{ recorded: boolean }> {\n const body: { analytics: boolean; anonymous_key?: string; channel?: ConsentChannel } = {\n analytics: input.analytics,\n };\n const key = input.anonymousKey ?? anonymousKey();\n if (key !== undefined) body.anonymous_key = key;\n if (input.channel !== undefined) body.channel = input.channel;\n if (!input.analytics) forgetAnalyticsIds();\n return this.http.post<{ recorded: boolean }>(\"/consents/cookies\", { body });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Receipts resource — `client.receipts.*`: one numbered receipt for every\n * payment: a wallet top-up, a card top-up and a card's issue price.\n *\n * ```ts\n * const all = await client.receipts.list();\n * const [forDeposit] = await client.receipts.list({ refId: deposit.id });\n * const one = await client.receipts.get(id);\n * ```\n *\n * A receipt appears within a minute of the payment going through and is\n * mailed to the user at the same time. The rate on it is the one the money\n * was credited at; the platform's margin is not shown.\n */\n\nexport type ReceiptKind = \"wallet_deposit\" | \"card_topup\" | \"card_issue\" | (string & {});\n\nexport interface Receipt {\n id: string;\n /** Shown as `R-000123`. */\n number: string;\n kind: ReceiptKind;\n /** The deposit, card top-up or card the payment was for. */\n ref_id: string;\n paid_at: string;\n /** Decimal string. */\n paid_amount: string;\n paid_currency: string;\n /** `card`, `sbp`, `crypto`, `bank_transfer` or `wallet`. */\n method: string;\n credited_amount: string | null;\n credited_currency: string | null;\n /** What one unit of `credited_currency` cost in `paid_currency`; only when they differ. */\n rate: string | null;\n card_id: string | null;\n card_last4: string | null;\n}\n\nexport interface ListReceiptsParams {\n /** Only the receipt of this deposit, card top-up or card. */\n refId?: string;\n /** Newest first; default 50, at most 200. */\n limit?: number;\n}\n\nexport class ReceiptsResource {\n constructor(private readonly http: HttpClient) {}\n\n async list(params: ListReceiptsParams = {}): Promise<Receipt[]> {\n const q = new URLSearchParams();\n if (params.refId !== undefined) q.set(\"ref_id\", params.refId);\n if (params.limit !== undefined) q.set(\"limit\", String(params.limit));\n const qs = q.toString();\n return this.http.get<Receipt[]>(`/me/receipts${qs ? `?${qs}` : \"\"}`);\n }\n\n async get(id: string): Promise<Receipt> {\n return this.http.get<Receipt>(`/me/receipts/${encodeURIComponent(id)}`);\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Support resource — `client.support.*`: the chat with support.\n *\n * GET /me/support/messages → list\n * POST /me/support/messages → send\n * GET /me/support/attachments/{id} → attachment\n * POST /me/support/ratings/{id} → rate\n *\n * What the person writes shows in the conversation at once, with the status\n * `queued`, and goes to support right after (`delivered`). Support answers\n * come back in the same conversation, with the text ready as cleaned HTML in\n * `html`: show it as it is, it carries only paragraphs, line breaks, bold,\n * italic, strikethrough, code, links, lists and quotes. A new answer also\n * comes as a `support_reply` notification.\n *\n * The person may write from the Telegram bot too; it is one conversation,\n * and `channel` says where each message came from. A message written in\n * Telegram keeps its formatting: `html` has it, `text` the plain words.\n * An answer sent to the person's Telegram is `queued` until all of it got\n * there, and `failed` if it could not get there.\n */\n\n/** Where a message came from, or where an answer was sent. */\nexport type SupportChannel = \"cabinet\" | \"telegram\" | (string & {});\n\n/** How far a message got: `queued` until support has it (for an answer\n * sent to Telegram, until the person has it). */\nexport type SupportMessageStatus = \"queued\" | \"delivered\" | \"failed\" | (string & {});\n\n/** The conversation's state: `none` until the person writes for the first\n * time, `resolved` once support closed it. Writing again reopens it. */\nexport type SupportConversationStatus = \"none\" | \"open\" | \"resolved\" | (string & {});\n\n/** A file in the conversation. Download it with `attachment(id)`. */\nexport interface SupportAttachment {\n id: string;\n file_name: string;\n content_type: string;\n /** Bytes. */\n size: number;\n}\n\n/** One message. */\nexport interface SupportMessage {\n id: string;\n /** `user` for what the person wrote, `support` for an answer. */\n author: \"user\" | \"support\" | (string & {});\n /** The name the support agent goes by; answers only. */\n operator_name: string | null;\n channel: SupportChannel | null;\n /** What the person wrote, plain text. Empty on answers. */\n text: string;\n /** The answer as cleaned HTML. On the person's own messages it is set\n * only for those written in Telegram, which keep their formatting. */\n html: string;\n attachments: SupportAttachment[];\n status: SupportMessageStatus;\n created_at: string;\n}\n\n/** Support closed the conversation and asks how it went. */\nexport interface SupportRatingRequest {\n id: string;\n asked_at: string;\n}\n\n/** A page of the conversation, oldest first. */\nexport interface SupportConversation {\n status: SupportConversationStatus;\n items: SupportMessage[];\n /** Older messages exist: `list({ before: items[0].created_at })`. */\n has_more: boolean;\n /** Show a 1–5 rating when set; answer with `rate()`. `null` otherwise. */\n rating_request: SupportRatingRequest | null;\n}\n\n/** A file to send. `data` may be a `Blob` (a `File` from an input), bytes,\n * or base64 already. */\nexport interface SupportFile {\n fileName: string;\n /** E.g. `image/png`. Pictures and PDF up to 20 MB by default; the platform\n * sets the list and the size. */\n contentType: string;\n data: Blob | ArrayBuffer | Uint8Array | string;\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunk));\n }\n return btoa(binary);\n}\n\nasync function toBase64(data: SupportFile[\"data\"]): Promise<string> {\n if (typeof data === \"string\") return data;\n if (data instanceof Uint8Array) return bytesToBase64(data);\n if (data instanceof ArrayBuffer) return bytesToBase64(new Uint8Array(data));\n return bytesToBase64(new Uint8Array(await data.arrayBuffer()));\n}\n\nexport class SupportResource {\n constructor(private readonly http: HttpClient) {}\n\n /** The latest messages, oldest first, and the conversation's status.\n * `before` reads further back; `limit` is 1 to 100 (50). */\n async list(\n opts: { before?: string; limit?: number; signal?: AbortSignal } = {},\n ): Promise<SupportConversation> {\n const q = new URLSearchParams();\n if (opts.before) q.set(\"before\", opts.before);\n if (opts.limit !== undefined) q.set(\"limit\", String(opts.limit));\n const qs = q.toString();\n return this.http.get<SupportConversation>(`/me/support/messages${qs ? `?${qs}` : \"\"}`, {\n signal: opts.signal,\n });\n }\n\n /** Write to support. Text, files or both; up to 10 files. */\n async send(\n message: { text?: string; files?: SupportFile[] },\n opts: { signal?: AbortSignal } = {},\n ): Promise<SupportMessage> {\n const attachments = await Promise.all(\n (message.files ?? []).map(async (f) => ({\n file_name: f.fileName,\n content_type: f.contentType,\n data_base64: await toBase64(f.data),\n })),\n );\n return this.http.post<SupportMessage>(\"/me/support/messages\", {\n body: { text: message.text ?? \"\", attachments },\n signal: opts.signal,\n });\n }\n\n /** A file from the conversation: the person's own or one support sent. */\n async attachment(id: string, opts: { signal?: AbortSignal } = {}): Promise<Blob> {\n return this.http.getBlob(`/me/support/attachments/${encodeURIComponent(id)}`, {\n signal: opts.signal,\n });\n }\n\n /** Answer `rating_request`: 1 (bad) to 5 (great), a comment if the person\n * wrote one. Each question takes one answer; a second one is a 404. */\n async rate(\n id: string,\n answer: { rating: 1 | 2 | 3 | 4 | 5; comment?: string },\n opts: { signal?: AbortSignal } = {},\n ): Promise<void> {\n await this.http.post<void>(`/me/support/ratings/${encodeURIComponent(id)}`, {\n body: { rating: answer.rating, ...(answer.comment ? { comment: answer.comment } : {}) },\n signal: opts.signal,\n });\n }\n\n /** Just the conversation's status. */\n async status(opts: { signal?: AbortSignal } = {}): Promise<SupportConversationStatus> {\n return (await this.list({ limit: 1, signal: opts.signal })).status;\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { DepositMethod, FeeKind } from \"./deposits.js\";\n\n/**\n * Funding options resource — `client.fundingOptions.*`.\n *\n * The ways the user can top up on this deployment: each funding connector,\n * where its top-ups may land and which payment methods it takes. Build the\n * top-up screen from this list instead of fixed connector names: a\n * deployment may top up the wallet only, cards only (no wallet at all), or\n * let the user choose.\n *\n * Mirrors `GET /me/funding-options`.\n */\n\n/**\n * Where a funding connector's top-ups may land: `wallet` (the wallet\n * only), `spool` (straight onto cards only) or `mixed` (either).\n */\nexport type FunderMode = \"wallet\" | \"spool\" | \"mixed\";\n\n/** Where one top-up goes: the wallet, or one of the user's cards. */\nexport type DepositTarget = \"wallet\" | \"card\";\n\n/**\n * What one way of paying through a funding connector costs and allows.\n * Draw the top-up form from it: the currency to ask for, the fee to show\n * (or not, for a markup), the floor, the cap and the day's limit.\n */\nexport interface MethodTerms {\n method: DepositMethod;\n /** ISO 4217 code the user pays in this way; `null` when any the quote accepts. */\n source_currency: string | null;\n fee_kind: FeeKind;\n /** The fee in basis points (2000 = 20 %). */\n fee_bps: number;\n /** How long a quote through this method stays executable, and the deposit waits for its payment. */\n quote_ttl_seconds: number;\n /** Smallest single top-up in the source currency; `null` for no floor. */\n min_amount: string | null;\n /** Largest single top-up in the source currency; `null` for no cap. */\n max_amount: string | null;\n /** What one user may top up this way over 24 hours; `null` for no limit. */\n daily_limit_per_user: string | null;\n}\n\n/** One way to top up. */\nexport interface FundingOption {\n /** Pass it as `funder_slug` to `deposits.initiate`. */\n slug: string;\n mode: FunderMode;\n /** Where a top-up through it may land. */\n targets: DepositTarget[];\n /** Payment methods it takes. */\n methods: DepositMethod[];\n /**\n * Whether a new card can be issued with a top-up through it\n * (`issue_card` on `deposits.initiate`).\n */\n issue_card: boolean;\n /** The terms of each method in `methods`. */\n method_terms: MethodTerms[];\n}\n\nexport class FundingOptionsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** The ways to top up, preferred first. Empty when none is configured. */\n async list(): Promise<FundingOption[]> {\n return this.http.get<FundingOption[]>(\"/me/funding-options\");\n }\n}\n","/**\n * The SDK's own version, sent as the default `X-Takeal-Client` version.\n *\n * Kept as a plain constant so every entry point (ESM, CJS, the\n * sub-exports) reads the same value without a JSON import or a bundler\n * `define`. `src/version.test.ts` checks it matches `package.json`, so a\n * release bump that forgets this file fails the test run.\n */\nexport const SDK_VERSION = \"0.8.4\";\n","import { SDK_VERSION } from \"./version.js\";\n\n/**\n * Which kind of app is talking to the API. Sent on every request as\n * `X-Takeal-Client: <platform>; <version>`. The server keeps it on the\n * session: it decides whether a sign-in counts as a new device, and which\n * channel a notification goes out on (a Mini App gets Telegram messages, a\n * PWA gets Web Push, and so on).\n */\nexport type ClientPlatform = \"pwa\" | \"web\" | \"telegram-miniapp\" | \"ios\" | \"android\";\n\n/** The `client` option of `createClient`. */\nexport interface ClientDescriptor {\n /** What the app is. Detected at runtime when omitted; see\n * {@link detectClientPlatform}. */\n platform: ClientPlatform;\n /** The app's own version. Defaults to the SDK version. */\n version?: string;\n}\n\n/** A descriptor with every field filled in. `client.client` on a\n * {@link CusfrontClient} has this shape. */\nexport interface ResolvedClientDescriptor {\n platform: ClientPlatform;\n version: string;\n}\n\n/** Header name carrying the client descriptor. */\nexport const CLIENT_HEADER = \"X-Takeal-Client\";\n\n/**\n * Best-effort platform detection for browser runtimes:\n *\n * - `telegram-miniapp` when `window.Telegram.WebApp.initData` is non-empty\n * (the app was launched from Telegram);\n * - `pwa` when the page runs installed: iOS Safari's `navigator.standalone`\n * or a `display-mode: standalone` media query;\n * - `web` otherwise, and always outside a browser (Node, workers without a\n * `navigator`).\n *\n * Native wrappers (Capacitor, React Native) should pass `ios` / `android`\n * explicitly; there is no reliable way to tell them apart from a browser.\n */\nexport function detectClientPlatform(): ClientPlatform {\n const g = globalThis as unknown as {\n Telegram?: { WebApp?: { initData?: unknown } };\n navigator?: { standalone?: unknown };\n matchMedia?: (query: string) => { matches: boolean };\n };\n const initData = g.Telegram?.WebApp?.initData;\n if (typeof initData === \"string\" && initData.length > 0) return \"telegram-miniapp\";\n\n if (g.navigator?.standalone === true) return \"pwa\";\n if (typeof g.matchMedia === \"function\") {\n try {\n if (g.matchMedia(\"(display-mode: standalone)\").matches) return \"pwa\";\n } catch {\n // Some non-browser runtimes stub matchMedia and throw; treat as web.\n }\n }\n return \"web\";\n}\n\n/** Fill in the blanks of a `client` option. */\nexport function resolveClientDescriptor(\n given: ClientDescriptor | undefined,\n): ResolvedClientDescriptor {\n return {\n platform: given?.platform ?? detectClientPlatform(),\n version: given?.version || SDK_VERSION,\n };\n}\n\n/** `{ platform: \"pwa\", version: \"0.3.0\" }` → `\"pwa; 0.3.0\"`. */\nexport function clientHeaderValue(desc: ResolvedClientDescriptor): string {\n return `${desc.platform}; ${desc.version}`;\n}\n","/**\n * Pluggable storage for the JWT.\n *\n * Default behaviour by environment:\n * - browser → `localStorage` (synchronous, persists across reloads)\n * - Node / SSR / worker → in-memory (no global state to leak)\n * - mobile (Capacitor / RN) → consumer must inject Keychain /\n * EncryptedSharedPreferences via `createClient({ tokenStore })`\n *\n * The store is intentionally tiny — three methods, no eviction\n * policy, no encryption. Encryption is the consumer's call (mobile\n * adapters wrap platform-native secure storage). Persistence shape\n * is opaque to the SDK; tokens are passed through verbatim.\n */\nexport interface TokenStore {\n get(): string | null | Promise<string | null>;\n set(token: string): void | Promise<void>;\n clear(): void | Promise<void>;\n}\n\n/** Sync `localStorage`-backed store. Falls through to in-memory when\n * `window.localStorage` is unavailable (private mode quota, SSR). */\nexport function defaultBrowserStore(key = \"takeal_jwt\"): TokenStore {\n const fallback = inMemoryStore();\n // Probe once at construction — avoid the try/catch on every call.\n let usable = false;\n try {\n if (typeof globalThis !== \"undefined\" && \"localStorage\" in globalThis) {\n const ls = (globalThis as { localStorage: Storage }).localStorage;\n const probe = \"__takeal_probe__\";\n ls.setItem(probe, \"1\");\n ls.removeItem(probe);\n usable = true;\n }\n } catch {\n usable = false;\n }\n if (!usable) return fallback;\n const ls = (globalThis as { localStorage: Storage }).localStorage;\n return {\n get: () => ls.getItem(key),\n set: (token) => ls.setItem(key, token),\n clear: () => ls.removeItem(key),\n };\n}\n\n/** In-memory store. Use for SSR / tests / when persistence isn't\n * desired (e.g. ephemeral kiosk sessions). */\nexport function inMemoryStore(): TokenStore {\n let value: string | null = null;\n return {\n get: () => value,\n set: (token) => {\n value = token;\n },\n clear: () => {\n value = null;\n },\n };\n}\n","/**\n * Resolve an image URL the API hands back (`design.image_url`, a logo, …)\n * into something a browser can load.\n *\n * The API returns either an absolute URL (uploaded artwork served from\n * object storage) or a path relative to the API origin (the deployment's\n * default card design, `/card-designs/default.svg`). Absolute URLs — and\n * `data:` / `blob:` URIs — come back unchanged; a relative path is joined\n * onto `baseUrl`, which is the bare API origin the client was built with.\n * These paths are host-level, so no `/v1` prefix is added.\n *\n * `baseUrl` is the same value passed to `createClient`; a trailing slash is\n * tolerated. `client.assetUrl()` calls this with the client's own base.\n */\nexport function resolveAssetUrl(baseUrl: string, url: string): string {\n if (isAbsolute(url)) return url;\n const base = baseUrl.replace(/\\/+$/, \"\");\n const path = url.startsWith(\"/\") ? url : `/${url}`;\n return `${base}${path}`;\n}\n\n/** `https://…`, `http://…`, protocol-relative `//…`, `data:` and `blob:` all count as absolute. */\nfunction isAbsolute(url: string): boolean {\n return /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(url);\n}\n","import { isApiError } from \"./error.js\";\nimport type { HttpClient } from \"./http.js\";\n\n/**\n * Which platform versions this SDK works with, as a semver range:\n * comparators separated by \", \". Keep this the only definition.\n */\nexport const SUPPORTED_MEISTER = \">=0.8.0, <1.0.0\";\n\n/** What `client.ready()` returns. */\nexport interface ReadyInfo {\n /** `true` when the platform reported a version inside `supportedMeister`. */\n compatible: boolean;\n /** The platform version the deployment reported, or `null` when it didn't. */\n platformVersion: string | null;\n /** The range this SDK supports (`SUPPORTED_MEISTER`). */\n supportedMeister: string;\n /** Why `compatible` is false, in one English sentence for logs or a banner. */\n warning?: string;\n /** `true` when every platform dependency answered (HTTP 200), `false` on 503. */\n healthy: boolean;\n /** `ready` or `degraded`, as the platform reports it. */\n status: string;\n /** The raw `GET /ready` body, for fields this type doesn't name. */\n raw: ReadyBody;\n}\n\n/** The part of the `GET /ready` body the SDK reads. */\nexport interface ReadyBody {\n status?: string;\n ops?: {\n /** Build version of the API process. */\n version?: string;\n /** The platform version. Missing on platforms before 0.5.0. */\n platform_version?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\ntype Parsed = { core: [number, number, number]; pre: string | null };\n\nconst SEMVER =\n /^v?(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/;\n\nfunction parse(v: string): Parsed | null {\n const m = SEMVER.exec(v.trim());\n if (!m) return null;\n return { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ?? null };\n}\n\nfunction cmpCore(a: Parsed, b: Parsed): number {\n for (let i = 0; i < 3; i++) {\n if (a.core[i] !== b.core[i]) return a.core[i]! < b.core[i]! ? -1 : 1;\n }\n return 0;\n}\n\n/**\n * `satisfies(\"0.5.3\", \">=0.5.0, <0.6.0\")` → `true`.\n *\n * The range is comma-separated comparators (`>=`, `>`, `<=`, `<`, `=`) or a\n * bare version meaning exactly that version; all must hold. A prerelease\n * (`0.5.1-rc.1`) never satisfies a range unless a comparator names it\n * exactly. Anything unparseable gives `false`.\n */\nexport function satisfies(version: string, range: string): boolean {\n const v = parse(version);\n if (!v) return false;\n const parts = range\n .split(\",\")\n .map((p) => p.trim())\n .filter(Boolean);\n if (parts.length === 0) return false;\n\n let exactPre = false;\n for (const part of parts) {\n const m = /^(>=|<=|>|<|=)?\\s*(.+)$/.exec(part);\n if (!m) return false;\n const op = m[1] ?? \"=\";\n const target = parse(m[2]!);\n if (!target) return false;\n\n const c = cmpCore(v, target);\n if (op === \"=\") {\n if (c !== 0 || v.pre !== target.pre) return false;\n if (v.pre !== null) exactPre = true;\n continue;\n }\n const ok = op === \">=\" ? c >= 0 : op === \">\" ? c > 0 : op === \"<=\" ? c <= 0 : c < 0;\n if (!ok) return false;\n }\n return v.pre === null || exactPre;\n}\n\n/** Judge a `GET /ready` body against `SUPPORTED_MEISTER`. */\nexport function readyInfo(raw: ReadyBody, healthy: boolean): ReadyInfo {\n const reported = raw?.ops?.platform_version;\n const platformVersion = typeof reported === \"string\" && reported ? reported : null;\n const base = {\n platformVersion,\n supportedMeister: SUPPORTED_MEISTER,\n healthy,\n status: typeof raw?.status === \"string\" ? raw.status : healthy ? \"ready\" : \"degraded\",\n raw,\n };\n if (platformVersion === null) {\n return {\n ...base,\n compatible: false,\n warning: `The platform didn't report its version; this SDK supports ${SUPPORTED_MEISTER}.`,\n };\n }\n if (!satisfies(platformVersion, SUPPORTED_MEISTER)) {\n return {\n ...base,\n compatible: false,\n warning: `This SDK supports platform ${SUPPORTED_MEISTER}, the platform runs ${platformVersion}. Some calls may fail until the SDK is updated.`,\n };\n }\n return { ...base, compatible: true };\n}\n\n/**\n * `GET /ready` (public, unversioned). A 503 still carries the body, so a\n * degraded platform answers with `healthy: false` instead of throwing.\n * Network failures and other statuses throw as usual.\n */\nexport async function fetchReady(\n http: HttpClient,\n opts: { signal?: AbortSignal } = {},\n): Promise<ReadyInfo> {\n try {\n const body = await http.get<ReadyBody>(\"/ready\", { skipAuth: true, signal: opts.signal });\n return readyInfo(body ?? {}, true);\n } catch (e) {\n if (isApiError(e) && e.status === 503 && typeof e.body === \"object\" && e.body !== null) {\n return readyInfo(e.body as ReadyBody, false);\n }\n throw e;\n }\n}\n","/**\n * `@takeal/cusfront-sdk` — typed client for the Takeal end-user API.\n *\n * Entry point: `createClient({ baseUrl, brand?, client?, tokenStore?, fetch? })`.\n * Resources are accessed off the returned client (`client.auth.login`,\n * `client.cards.list`, …). Sub-exports under `@takeal/cusfront-sdk/<resource>`\n * publish each resource independently so a Cusfront only pulls what\n * it imports.\n *\n * Brand-neutral by design. No customer / deployment names embedded.\n * Brand swap happens at runtime via `BrandConfig`.\n */\n\nimport { HttpClient, type FetchLike } from \"./http.js\";\nimport { AuthResource } from \"./resources/auth.js\";\nimport { DepositsResource } from \"./resources/deposits.js\";\nimport { CardsResource } from \"./resources/cards.js\";\nexport { revealState, priceChangedQuote } from \"./resources/cards.js\";\nimport { BalanceResource } from \"./resources/balance.js\";\nimport { BonusResource } from \"./resources/bonus.js\";\nimport { DebtResource } from \"./resources/debt.js\";\nimport { CloseRequestsResource } from \"./resources/close-requests.js\";\nimport { ClaimsResource } from \"./resources/claims.js\";\nimport { CodesResource } from \"./resources/codes.js\";\nimport { ReferralResource } from \"./resources/referral.js\";\nimport { SubscriptionResource } from \"./resources/subscription.js\";\nimport { BrandingResource } from \"./resources/branding.js\";\nimport { WalletResource } from \"./resources/wallet.js\";\nimport { BlogResource } from \"./resources/blog.js\";\nimport { DocumentsResource } from \"./resources/documents.js\";\nimport { SubscriptionsResource } from \"./resources/subscriptions.js\";\nimport { SessionsResource } from \"./resources/sessions.js\";\nimport { PushResource } from \"./resources/push.js\";\nimport { MeResource } from \"./resources/me.js\";\nimport { NotificationsResource } from \"./resources/notifications.js\";\nimport { DevicesResource } from \"./resources/devices.js\";\nimport { AttributionResource } from \"./resources/attribution.js\";\nimport { HistoryResource } from \"./resources/history.js\";\nimport { ConsentsResource } from \"./resources/consents.js\";\nimport { ReceiptsResource } from \"./resources/receipts.js\";\nimport { SupportResource } from \"./resources/support.js\";\nimport { FundingOptionsResource } from \"./resources/funding-options.js\";\nimport {\n CLIENT_HEADER,\n clientHeaderValue,\n resolveClientDescriptor,\n type ClientDescriptor,\n type ResolvedClientDescriptor,\n} from \"./client-platform.js\";\nimport { defaultBrowserStore, inMemoryStore, type TokenStore } from \"./token-store.js\";\nimport type { BrandConfig } from \"./brand.js\";\nimport { resolveAssetUrl } from \"./assets.js\";\nimport { fetchReady, type ReadyInfo } from \"./compat.js\";\n\nexport type { BrandConfig } from \"./brand.js\";\nexport { resolveAssetUrl } from \"./assets.js\";\nexport { ApiError, NetworkError, isApiError, isNetworkError } from \"./error.js\";\nexport { defaultBrowserStore, inMemoryStore, type TokenStore } from \"./token-store.js\";\nexport { SDK_VERSION } from \"./version.js\";\nexport { SUPPORTED_MEISTER, satisfies } from \"./compat.js\";\nexport type { ReadyInfo, ReadyBody } from \"./compat.js\";\nexport {\n CLIENT_HEADER,\n detectClientPlatform,\n type ClientDescriptor,\n type ClientPlatform,\n type ResolvedClientDescriptor,\n} from \"./client-platform.js\";\n\n// Re-export resource types so consumers can `import { Deposit } from\n// \"@takeal/cusfront-sdk\"` without reaching into sub-paths.\nexport type { Address, CustomerInfo } from \"./types/customer.js\";\nexport type {\n Deposit,\n DepositStatus,\n DepositMethod,\n InitiateDepositInput,\n CreateDepositRefundInput,\n Refund,\n CreateQuoteInput,\n FundingQuote,\n CardLoadStatus,\n IssueCardInput,\n FeeKind,\n} from \"./resources/deposits.js\";\nexport type {\n DepositTarget,\n FunderMode,\n FundingOption,\n MethodTerms,\n} from \"./resources/funding-options.js\";\nexport type {\n Card,\n CardType,\n CardStatus,\n CardStatusSource,\n CardForm,\n CloseBlockedReason,\n CardDesignRef,\n CardProduct,\n CardProductPrice,\n CreateCardInput,\n UpdateCardInput,\n CardBalance,\n TopUpTerms,\n TopUpInput,\n CardTopUp,\n CardTopUpStatus,\n TopUpResult,\n RevealCardInput,\n RevealedCard,\n RevealState,\n BillingAddress,\n Cardholder,\n SetPinInput,\n TransferInput,\n CardTransfer,\n TransferResult,\n IssuanceBonus,\n CardInTransit,\n CardOrderInput,\n CardOrder,\n CardOrderError,\n CardOrderQuoteInput,\n CardOrderQuote,\n PromoCodeQuote,\n PromoCodeStatus,\n CardTariff,\n} from \"./resources/cards.js\";\nexport type { Debt, DebtAmount, DebtLine, CardFeeKind } from \"./resources/debt.js\";\nexport type {\n CloseAmount,\n CloseRefund,\n CloseRequest,\n CloseRequestError,\n CloseRequestStatus,\n PayoutDetailsInput,\n PayoutDetailsShown,\n} from \"./resources/close-requests.js\";\nexport type {\n Claim,\n ClaimError,\n ClaimKind,\n ClaimPage,\n ClaimStatus,\n ClaimTransaction,\n CreateClaimInput,\n} from \"./resources/claims.js\";\nexport type { Balance } from \"./resources/balance.js\";\nexport type {\n BonusLot,\n BonusMovement,\n BonusPreview,\n BonusPreviewInput,\n BonusPurpose,\n BonusTarget,\n BonusWallet,\n} from \"./resources/bonus.js\";\nexport type {\n CodeCheck,\n CodeDiscount,\n CodeEffect,\n CodeEffectOutcome,\n CodeOperation,\n CodeRejection,\n CodeResult,\n ValidateCodeInput,\n} from \"./resources/codes.js\";\nexport type { InvitedFriend, Referral, ReferralReward } from \"./resources/referral.js\";\nexport type { UserSubscription, CancelledSubscription } from \"./resources/subscription.js\";\nexport type { Branding } from \"./resources/branding.js\";\nexport type { Wallet } from \"./resources/wallet.js\";\nexport type { BlogPost, BlogBlock, BlogList, BlogListInput } from \"./resources/blog.js\";\nexport type {\n Document,\n DocumentBlock,\n DocumentCategory,\n DocumentScope,\n DocumentPathStep,\n DocumentList,\n DocumentListInput,\n DocumentFolder,\n DocumentTree,\n DocumentTreeEntry,\n DocumentVersionSummary,\n DocumentTag,\n} from \"./resources/documents.js\";\nexport type { Subscriptions, BroadcastChannel } from \"./resources/subscriptions.js\";\nexport type {\n User,\n LoginInput,\n LoginResponse,\n JwtIssued,\n TotpRequired,\n TotpSetupEmailRequired,\n TotpSetupEmailErrorCode,\n TotpSetupEmailInput,\n TotpSetupRequired,\n OtpSentResponse,\n RegisterInput,\n Session,\n TotpSetupComplete,\n ChangePasswordInput,\n PasswordSetupRequested,\n ConfirmPasswordSetupInput,\n TelegramLink,\n TelegramUnknown,\n ExchangeTelegramInput,\n LinkTelegramInput,\n EmailChangeRequested,\n RequestEmailCodeInput,\n EmailCodeSent,\n VerifyEmailCodeInput,\n EmailCodeSession,\n} from \"./resources/auth.js\";\nexport type { MeResource } from \"./resources/me.js\";\nexport type {\n HistoryKind,\n HistoryStatus,\n HistoryAmount,\n HistoryCard,\n HistoryItem,\n HistoryPage,\n ListHistoryParams,\n} from \"./resources/history.js\";\nexport type {\n ConsentKind,\n ConsentChannel,\n ConsentDocument,\n ConsentOptions,\n ConsentState,\n Consents,\n ConsentsResource,\n CookieChoiceInput,\n} from \"./resources/consents.js\";\nexport { HOLDER_DATA_CONSENT, DISPUTE_DOCUMENTS_CONSENT } from \"./resources/consents.js\";\nexport type {\n Receipt,\n ReceiptKind,\n ReceiptsResource,\n ListReceiptsParams,\n} from \"./resources/receipts.js\";\nexport type {\n SupportAttachment,\n SupportChannel,\n SupportConversation,\n SupportConversationStatus,\n SupportFile,\n SupportMessage,\n SupportMessageStatus,\n SupportRatingRequest,\n SupportResource,\n} from \"./resources/support.js\";\nexport {\n analyticsIds,\n anonymousKey,\n currentTouch,\n forgetAnalyticsIds,\n rememberAnalyticsIds,\n withAnalyticsIds,\n} from \"./resources/attribution.js\";\nexport type {\n TouchFields,\n TouchInput,\n TouchResult,\n SignupAttribution,\n SurveyAnswer,\n AttributionStatus,\n AnonymousKeyOptions,\n AnalyticsIds,\n HandoffToken,\n} from \"./resources/attribution.js\";\nexport {\n ANALYTICS_EVENTS,\n METRIKA_GOALS,\n NO_CAPTURE_CLASS,\n initAnalytics,\n setAnalyticsZone,\n track,\n page,\n identify,\n resetAnalytics,\n posthogDistinctId,\n sanitizeUrl,\n sanitizeProperties,\n} from \"./analytics.js\";\nexport type {\n AnalyticsZone,\n AnalyticsEvent,\n AnalyticsProperties,\n AnalyticsOptions,\n PostHogOptions,\n MetrikaOptions,\n PostHogLike,\n} from \"./analytics.js\";\nexport type { UserSession } from \"./resources/sessions.js\";\nexport type {\n PushStatus,\n PushSubscriptionInput,\n PushCapableRegistration,\n} from \"./resources/push.js\";\nexport { isCardOtp } from \"./resources/notifications.js\";\nexport type {\n NotificationCategory,\n NotificationChannel,\n NotificationLocale,\n InboxItem,\n CardOtpData,\n NotificationPage,\n ListNotificationsParams,\n NotificationCategoryPreferences,\n NotificationPreferences,\n NotificationPreferencesInput,\n} from \"./resources/notifications.js\";\nexport type {\n DeviceKind,\n DevicePlatform,\n Device,\n WebPushCredential,\n MobilePushCredential,\n RegisterDeviceInput,\n RegisteredDevice,\n RegisterWebPushOptions,\n UnregisterWebPushOptions,\n} from \"./resources/devices.js\";\n\nexport interface CreateClientOptions {\n /** Absolute origin of the Takeal API deployment, no trailing slash.\n * e.g. `\"https://api.takeal.example.com\"`. */\n baseUrl: string;\n /** Runtime brand config. Optional; consumer renders its own brand\n * if omitted. */\n brand?: BrandConfig;\n /** What kind of app this is, sent on every request as\n * `X-Takeal-Client: <platform>; <version>`. The server uses it to spot\n * a sign-in from a new device and to pick the notification channel.\n * `platform` is detected at runtime when omitted (`telegram-miniapp`\n * inside Telegram, `pwa` when installed, `web` otherwise); `version`\n * defaults to the SDK version. Native wrappers should pass\n * `{ platform: \"ios\" | \"android\", version }`. */\n client?: ClientDescriptor;\n /** Token persistence. Defaults to `defaultBrowserStore()` when\n * `window.localStorage` is present, else `inMemoryStore()`. */\n tokenStore?: TokenStore;\n /** Where the remember token of a \"remember me\" sign-in is kept. Defaults\n * to `localStorage` under `takeal_remember` in a browser, in memory\n * elsewhere. Native wrappers should pass secure storage. */\n rememberStore?: TokenStore;\n /** Override the `fetch` implementation — useful for Node < 18,\n * React Native < 0.74, MSW intercept layers, etc. */\n fetch?: FetchLike;\n /** When true, the SDK runs every response through a zod schema\n * before handing it to the caller. Requires `zod` >= 3.22 as a\n * peer dep. Off by default; types-only validation is sufficient\n * for the steady-state case. */\n validate?: boolean;\n}\n\nexport interface CusfrontClient {\n /** Read-only brand config — pass through from createClient args. */\n readonly brand: BrandConfig | undefined;\n /** The platform and version this client announces in `X-Takeal-Client`. */\n readonly client: ResolvedClientDescriptor;\n /** Auth resource: login, refresh, current user, logout. */\n readonly auth: AuthResource;\n /** Deposits (money IN via a funder connector, to the wallet or straight onto a card): initiate, get, list, refund. */\n readonly deposits: DepositsResource;\n /** The ways to top up: each funding connector, where its top-ups land and the methods it takes. */\n readonly fundingOptions: FundingOptionsResource;\n /** Cards (money OUT via an issuer connector): the product catalog, create, get, list, update, balance. */\n readonly cards: CardsResource;\n /** Wallet balance lookup (defaults to the wallet's own currency). */\n readonly balance: BalanceResource;\n /** Bonuses: a discount on the platform's services. Balance, credits, history and a price preview. */\n readonly bonus: BonusResource;\n /** Card fees the user's cards could not cover: paid first from the next top-up. */\n readonly debt: DebtResource;\n /** Close a card that still holds money: the rest goes back the way it was paid. */\n readonly closeRequests: CloseRequestsResource;\n /** Dispute a card operation or complain, and follow claims (lost and stolen cards included) by number and status. */\n readonly claims: ClaimsResource;\n /** Promo and referral codes: check what a code would do before using it. */\n readonly codes: CodesResource;\n /** For referrers: the referral code, the link to share, invited friends and rewards. */\n readonly referral: ReferralResource;\n /** The user's own subscription tier or gift, a promo code for its monthly fee, and cancelling it. */\n readonly subscription: SubscriptionResource;\n /** The wallet's currency: read it, switch it while the wallet is empty. */\n readonly wallet: WalletResource;\n /** Runtime white-label config (`GET /branding`, public): names, logo, wallet label. */\n readonly branding: BrandingResource;\n /** Documents: blog posts, the knowledge base, legal pages. Public before sign-in, more once signed in. */\n readonly documents: DocumentsResource;\n /** Public blog posts, returned as structured blocks to render in your own style.\n * @deprecated Use `documents.list({ category: \"blog\" })` and `documents.get(slug)`; the blog is a category of Documents now. The old paths answer for one more release. */\n readonly blog: BlogResource;\n /** The user's announcement channel subscriptions.\n * @deprecated Use `notifications.setPreferences({ categories: { marketing: {...} } })`. */\n readonly subscriptions: SubscriptionsResource;\n /** Where the user is signed in: list sessions, sign one or all others out. */\n readonly sessions: SessionsResource;\n /** Web Push subscription for the signed-in user.\n * @deprecated Use `devices.registerWebPush` / `devices.unregisterWebPush`. */\n readonly push: PushResource;\n /** The user's inbox and notification preferences. */\n readonly notifications: NotificationsResource;\n /** The user's devices: browsers with Web Push, phones, the Telegram Mini App. */\n readonly devices: DevicesResource;\n /** Profile actions for the signed-in user: link or unlink Telegram. */\n readonly me: MeResource;\n /** Where users come from: record visits, ask \"how did you hear about us\". */\n readonly attribution: AttributionResource;\n /** Everything that happened to the user's money in one list, or one card's part of it. */\n readonly history: HistoryResource;\n /** What the user agreed to; give or withdraw the optional consents. */\n readonly consents: ConsentsResource;\n /** A numbered receipt for every payment. */\n readonly receipts: ReceiptsResource;\n /** The chat with support: messages, files, the conversation's status. */\n readonly support: SupportResource;\n /** Direct access to the token store (e.g. for an explicit sign-out\n * on Capacitor's lifecycle \"app pausing\" event). */\n readonly tokens: TokenStore;\n /**\n * Turn an image URL from the API (`card.design.image_url`,\n * `product.design.image_url`) into one a browser can load. Absolute URLs\n * pass through; a path relative to the API origin (the default card\n * design, `/card-designs/default.svg`) is joined onto `baseUrl`.\n */\n assetUrl(url: string): string;\n /**\n * Ask the deployment whether it is up and which platform version it runs\n * (`GET /ready`, public). `compatible` is false, with a `warning`, when the\n * version is outside `SUPPORTED_MEISTER` or the platform didn't report one.\n * A degraded platform (503) answers with `healthy: false`, not an error.\n */\n ready(opts?: { signal?: AbortSignal }): Promise<ReadyInfo>;\n}\n\n/**\n * Build a new client. Stateless across calls — multiple clients can\n * coexist (e.g. an admin Cusfront with a different baseUrl than the\n * end-user one). Each gets its own `TokenStore`.\n *\n * `validate: true` is honoured by individual resources that ship\n * matching zod schemas; resources without a schema ignore it.\n */\nexport function createClient(opts: CreateClientOptions): CusfrontClient {\n const tokens = opts.tokenStore ?? pickDefaultStore();\n const remembered = opts.rememberStore ?? pickDefaultStore(\"takeal_remember\");\n const fetchImpl = opts.fetch ?? defaultFetch();\n const client = resolveClientDescriptor(opts.client);\n const http = new HttpClient(opts.baseUrl, tokens, fetchImpl, {\n [CLIENT_HEADER]: clientHeaderValue(client),\n });\n\n return {\n brand: opts.brand,\n client,\n tokens,\n assetUrl: (url: string) => resolveAssetUrl(opts.baseUrl, url),\n ready: (o?: { signal?: AbortSignal }) => fetchReady(http, o),\n auth: new AuthResource(http, tokens, remembered),\n deposits: new DepositsResource(http),\n fundingOptions: new FundingOptionsResource(http),\n cards: new CardsResource(http),\n balance: new BalanceResource(http),\n bonus: new BonusResource(http),\n debt: new DebtResource(http),\n closeRequests: new CloseRequestsResource(http),\n claims: new ClaimsResource(http),\n codes: new CodesResource(http),\n referral: new ReferralResource(http),\n subscription: new SubscriptionResource(http),\n wallet: new WalletResource(http),\n branding: new BrandingResource(http),\n documents: new DocumentsResource(http),\n blog: new BlogResource(http),\n subscriptions: new SubscriptionsResource(http),\n sessions: new SessionsResource(http),\n push: new PushResource(http),\n me: new MeResource(http),\n notifications: new NotificationsResource(http),\n devices: new DevicesResource(http, client),\n attribution: new AttributionResource(http),\n history: new HistoryResource(http),\n consents: new ConsentsResource(http),\n receipts: new ReceiptsResource(http),\n support: new SupportResource(http),\n };\n}\n\nfunction pickDefaultStore(key?: string): TokenStore {\n if (typeof globalThis !== \"undefined\" && \"localStorage\" in globalThis) {\n return defaultBrowserStore(key);\n }\n return inMemoryStore();\n}\n\nfunction defaultFetch(): FetchLike {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.fetch === \"function\") {\n // Bind to globalThis so `this` is correct inside the implementation\n // (some polyfills choke on a detached reference).\n return globalThis.fetch.bind(globalThis);\n }\n throw new Error(\n \"@takeal/cusfront-sdk: native fetch is not available in this runtime. \" +\n \"Pass a polyfill via createClient({ fetch }).\",\n );\n}\n","/**\n * `@takeal/cusfront-sdk/telegram` — Telegram Mini App adapter.\n *\n * A Mini App receives a signed `initData` string from the Telegram client\n * (`window.Telegram.WebApp.initData`). This module turns that string into an\n * authenticated SDK client:\n *\n * import { fromTelegramWebApp } from \"@takeal/cusfront-sdk/telegram\";\n * const client = await fromTelegramWebApp({ baseUrl: \"https://api.example.com\" });\n * const me = await client.auth.me(); // me.email_pending? prompt for email\n *\n * Signature validation: the HMAC over `initData` can only be verified with the\n * bot token, which lives on the server. So the **authoritative** check happens\n * server-side at `POST /auth/telegram/exchange`. Here we only do a structural,\n * fail-fast well-formedness check (`hash` + `auth_date` present, not stale)\n * before spending a network round-trip on an obviously-bad payload.\n */\n\nimport { createClient, type CreateClientOptions, type CusfrontClient } from \"./index.js\";\nimport type { JwtIssued, TelegramUnknown } from \"./resources/auth.js\";\n\n/** The Telegram `user` object embedded (URL-encoded JSON) in initData. */\nexport interface TelegramUser {\n id: number;\n first_name?: string;\n last_name?: string;\n username?: string;\n language_code?: string;\n photo_url?: string;\n is_premium?: boolean;\n}\n\n/** Structurally-parsed initData. `raw` is the original string passed to the\n * server verbatim — the server re-derives the HMAC from it, so we never\n * re-serialise. */\nexport interface ParsedInitData {\n raw: string;\n params: Record<string, string>;\n hash?: string;\n auth_date?: number;\n query_id?: string;\n user?: TelegramUser;\n}\n\n/** Thrown by {@link assertWellFormed} when initData is structurally invalid or\n * stale. A signature mismatch is NOT detectable here (no bot token) — that\n * surfaces as a 401 `ApiError` from the exchange call instead. */\nexport class InitDataError extends Error {\n constructor(\n message: string,\n readonly reason: \"empty\" | \"missing_hash\" | \"missing_auth_date\" | \"bad_user\" | \"stale\",\n ) {\n super(message);\n this.name = \"InitDataError\";\n }\n}\n\n/** Parse a raw `initData` query string into its fields (best-effort — does\n * not validate). `user` is JSON-decoded when present and parseable. */\nexport function parseInitData(initData: string): ParsedInitData {\n const params: Record<string, string> = {};\n const sp = new URLSearchParams(initData);\n for (const [k, v] of sp.entries()) params[k] = v;\n\n let user: TelegramUser | undefined;\n if (params.user) {\n try {\n user = JSON.parse(params.user) as TelegramUser;\n } catch {\n user = undefined;\n }\n }\n\n const authDateRaw = params.auth_date;\n const auth_date = authDateRaw && /^\\d+$/.test(authDateRaw) ? Number(authDateRaw) : undefined;\n\n return {\n raw: initData,\n params,\n ...(params.hash ? { hash: params.hash } : {}),\n ...(auth_date !== undefined ? { auth_date } : {}),\n ...(params.query_id ? { query_id: params.query_id } : {}),\n ...(user ? { user } : {}),\n };\n}\n\nexport interface WellFormedOptions {\n /** Reject initData whose `auth_date` is older than this many seconds.\n * Defaults to 86400 (24h) — match or stay under the server's\n * `auth.telegram.initdata_max_age_secs`. Pass 0 to skip the freshness\n * check client-side (the server still enforces its own window). */\n maxAgeSeconds?: number;\n /** Injectable clock (unix seconds) for testing. Defaults to `Date.now()`. */\n nowUnix?: number;\n}\n\n/** Fail-fast structural check: `hash` present, `auth_date` present + a valid\n * `user`, and (optionally) not stale. Throws {@link InitDataError}. Does NOT\n * verify the HMAC — only the server can. */\nexport function assertWellFormed(initData: string, opts: WellFormedOptions = {}): ParsedInitData {\n if (!initData) throw new InitDataError(\"initData is empty\", \"empty\");\n const parsed = parseInitData(initData);\n if (!parsed.hash) throw new InitDataError(\"initData is missing `hash`\", \"missing_hash\");\n if (parsed.auth_date === undefined)\n throw new InitDataError(\"initData is missing a valid `auth_date`\", \"missing_auth_date\");\n if (!parsed.user || typeof parsed.user.id !== \"number\")\n throw new InitDataError(\"initData is missing a valid `user`\", \"bad_user\");\n\n const maxAge = opts.maxAgeSeconds ?? 86_400;\n if (maxAge > 0) {\n const now = opts.nowUnix ?? Math.floor(Date.now() / 1000);\n if (now - parsed.auth_date > maxAge)\n throw new InitDataError(\n \"initData is stale (auth_date older than the freshness window)\",\n \"stale\",\n );\n }\n return parsed;\n}\n\n/** What can be logged about an `initData` value without logging it: no\n * values, no signatures, no user fields. Built by {@link describeInitData}. */\nexport interface InitDataDiagnostics {\n /** `typeof` of what was received (`\"string\"` for anything usable). */\n type: string;\n /** Length of the string, 0 for anything else. */\n length: number;\n /** Names of the fields present, sorted. Values are left out. */\n fields: string[];\n hasHash: boolean;\n hasSignature: boolean;\n /** `auth_date` is present and a unix timestamp. */\n hasAuthDate: boolean;\n /** Seconds since `auth_date`, when it parses. Negative means a clock ahead. */\n authDateAgeSeconds?: number;\n /** `user` is present and its `id` is a number. */\n hasUserId: boolean;\n /** Why {@link assertWellFormed} would refuse it, or `null` when it would not.\n * `\"not_a_string\"` when the value is not a string at all. */\n reason: InitDataError[\"reason\"] | \"not_a_string\" | null;\n}\n\n/**\n * Describe an `initData` value for a log line, without the value itself.\n * Use it where the payload is refused, so the log says which check failed:\n *\n * console.warn(\"telegram sign-in refused\", describeInitData(body.initData));\n *\n * The signature is checked only by the server; a payload this reports as\n * well formed can still be refused there, with the reason in the 401.\n */\nexport function describeInitData(\n initData: unknown,\n opts: WellFormedOptions = {},\n): InitDataDiagnostics {\n if (typeof initData !== \"string\") {\n return {\n type: typeof initData,\n length: 0,\n fields: [],\n hasHash: false,\n hasSignature: false,\n hasAuthDate: false,\n hasUserId: false,\n reason: \"not_a_string\",\n };\n }\n const parsed = parseInitData(initData);\n const now = opts.nowUnix ?? Math.floor(Date.now() / 1000);\n let reason: InitDataDiagnostics[\"reason\"] = null;\n try {\n assertWellFormed(initData, opts);\n } catch (e) {\n if (e instanceof InitDataError) reason = e.reason;\n else throw e;\n }\n return {\n type: \"string\",\n length: initData.length,\n fields: Object.keys(parsed.params).sort(),\n hasHash: parsed.hash !== undefined,\n hasSignature: typeof parsed.params.signature === \"string\" && parsed.params.signature !== \"\",\n hasAuthDate: parsed.auth_date !== undefined,\n ...(parsed.auth_date !== undefined ? { authDateAgeSeconds: now - parsed.auth_date } : {}),\n hasUserId: typeof parsed.user?.id === \"number\",\n reason,\n };\n}\n\nexport interface FromInitDataOptions extends WellFormedOptions {\n /** Skip the client-side well-formedness check and let the server be the\n * sole judge. Default false — the fail-fast check saves a round-trip on\n * obviously-bad input. */\n skipWellFormedCheck?: boolean;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false`, an unknown id makes {@link fromInitData} /\n * {@link fromTelegramWebApp} throw {@link TelegramUnknownError} (and\n * {@link exchangeInitData} resolve with `session.stage === \"unknown\"`)\n * instead of creating anything. */\n provision?: boolean;\n /** After a successful exchange, register this Mini App as a\n * `telegram_miniapp` device so notifications reach the user as bot\n * messages. Default `true`. Best-effort: a failure is logged as a\n * warning and never fails the sign-in. */\n registerDevice?: boolean;\n}\n\n/** Thrown by {@link fromInitData} / {@link fromTelegramWebApp} when\n * `provision: false` was passed and the Telegram id has no account yet.\n * Nothing was created and no JWT was stored. `initData` is the payload that\n * was exchanged, so the app can go on with\n * `client.auth.linkTelegram({ initData, email, password })` or retry with\n * `provision: true`. */\nexport class TelegramUnknownError extends Error {\n constructor(readonly initData: string) {\n super(\"this Telegram account is not linked to any user (provision: false)\");\n this.name = \"TelegramUnknownError\";\n }\n}\n\n/** What {@link exchangeInitData} resolves to. When `session.stage` is\n * `\"jwt\"` the client is signed in; when it is `\"unknown\"` the client is\n * built but has no session. */\nexport interface InitDataExchange {\n client: CusfrontClient;\n session: JwtIssued | TelegramUnknown;\n}\n\n/**\n * Build a client from a raw `initData` string and exchange the payload,\n * returning both the client and the exchange result.\n *\n * 1. (unless skipped) structurally validate the payload — throws\n * {@link InitDataError} on malformed/stale input.\n * 2. exchange it at `POST /auth/telegram/exchange` — the server validates the\n * HMAC; a bad signature throws a 401 `ApiError`.\n * 3. on `stage: \"jwt\"` the JWT is stored and the client is ready. With\n * `provision: false` and a Telegram id nobody has signed in with,\n * `session` is `{ stage: \"unknown\" }` and the client is unauthenticated;\n * continue with `client.auth.linkTelegram(...)` or\n * `client.auth.exchangeTelegram({ initData, provision: true })`.\n * 4. on `stage: \"jwt\"` the Mini App is registered as a `telegram_miniapp`\n * device (unless `registerDevice: false`), so the user's notifications\n * arrive as bot messages. Errors here are only logged.\n *\n * The client announces itself as `telegram-miniapp` in `X-Takeal-Client`\n * whatever `config.client.platform` says; a given `config.client.version`\n * is kept.\n *\n * Use this when the app wants to branch on the outcome itself;\n * {@link fromInitData} is the throwing shorthand.\n */\nexport async function exchangeInitData(\n initData: string,\n config: CreateClientOptions,\n opts: FromInitDataOptions = {},\n): Promise<InitDataExchange> {\n if (!opts.skipWellFormedCheck) assertWellFormed(initData, opts);\n const client = createClient({\n ...config,\n client: { ...config.client, platform: \"telegram-miniapp\" },\n });\n const session = await client.auth.exchangeTelegram({\n initData,\n ...(opts.provision !== undefined ? { provision: opts.provision } : {}),\n });\n if (session.stage === \"jwt\" && opts.registerDevice !== false) {\n await registerMiniAppDevice(client, initData);\n }\n return { client, session };\n}\n\n/** Best-effort `telegram_miniapp` device registration. The Telegram\n * profile's `language_code` goes along as the device locale when present. */\nasync function registerMiniAppDevice(client: CusfrontClient, initData: string): Promise<void> {\n const locale = parseInitData(initData).user?.language_code;\n try {\n await client.devices.register({\n kind: \"telegram_miniapp\",\n platform: \"telegram\",\n credential: {},\n ...(locale ? { locale } : {}),\n });\n } catch (e) {\n console.warn(\n \"@takeal/cusfront-sdk/telegram: could not register the Mini App as a device; \" +\n \"notifications may not reach this user in Telegram\",\n e,\n );\n }\n}\n\n/**\n * Build an authenticated client from a raw `initData` string. Thin wrapper\n * over {@link exchangeInitData} that never hands back a client without a\n * session: with `provision: false` and an unknown Telegram id it throws\n * {@link TelegramUnknownError} (carrying `initData`) instead.\n *\n * Read `client.auth.me()` (or call `client.auth.exchangeTelegram` directly for\n * the raw session) to check `email_pending` and prompt for an email.\n */\nexport async function fromInitData(\n initData: string,\n config: CreateClientOptions,\n opts: FromInitDataOptions = {},\n): Promise<CusfrontClient> {\n const { client, session } = await exchangeInitData(initData, config, opts);\n if (session.stage === \"unknown\") throw new TelegramUnknownError(initData);\n return client;\n}\n\n/** Read `window.Telegram.WebApp.initData` if running inside a Telegram Mini\n * App. Returns null when absent or empty (e.g. opened outside Telegram). */\nexport function readWebAppInitData(): string | null {\n const tg = (\n globalThis as unknown as {\n Telegram?: { WebApp?: { initData?: string } };\n }\n ).Telegram;\n const data = tg?.WebApp?.initData;\n return data && data.length > 0 ? data : null;\n}\n\n/**\n * Convenience entry for a Mini App: read `initData` from the Telegram WebApp\n * SDK and exchange it. Throws {@link InitDataError} if not running inside a\n * Telegram Mini App, and {@link TelegramUnknownError} when `provision: false`\n * was passed and the Telegram id has no account yet.\n */\nexport async function fromTelegramWebApp(\n config: CreateClientOptions,\n opts: FromInitDataOptions = {},\n): Promise<CusfrontClient> {\n const initData = readWebAppInitData();\n if (!initData)\n throw new InitDataError(\n \"not running inside a Telegram Mini App (window.Telegram.WebApp.initData is empty)\",\n \"empty\",\n );\n return fromInitData(initData, config, opts);\n}\n\n/** Convenience accessor for the typed exchange session (incl. `email_pending`)\n * when you need the envelope rather than just the client. */\nexport type TelegramExchangeSession = JwtIssued;\n"]}
1
+ {"version":3,"sources":["../src/error.ts","../src/http.ts","../src/resources/attribution.ts","../src/resources/cards.ts","../src/resources/auth.ts","../src/resources/deposits.ts","../src/resources/balance.ts","../src/resources/bonus.ts","../src/resources/debt.ts","../src/resources/close-requests.ts","../src/resources/claims.ts","../src/resources/codes.ts","../src/resources/referral.ts","../src/resources/subscription.ts","../src/resources/branding.ts","../src/resources/wallet.ts","../src/resources/blog.ts","../src/resources/documents.ts","../src/resources/subscriptions.ts","../src/resources/sessions.ts","../src/resources/push.ts","../src/resources/me.ts","../src/resources/notifications.ts","../src/resources/devices.ts","../src/resources/history.ts","../src/resources/consents.ts","../src/resources/receipts.ts","../src/resources/support.ts","../src/resources/funding-options.ts","../src/version.ts","../src/client-platform.ts","../src/token-store.ts","../src/assets.ts","../src/compat.ts","../src/index.ts","../src/telegram.ts"],"names":["stored","ls"],"mappings":";;;AAQO,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA,EAGlC,WAAA,CAEkB,MAAA,EAIA,IAAA,EAGhB,OAAA,EAGgB,MAIA,iBAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAhBG,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAIA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAMA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAIA,IAAA,IAAA,CAAA,iBAAA,GAAA,iBAAA;AAlBlB,IAAA,IAAA,CAAS,UAAA,GAAa,IAAA;AAqBpB,IAAA,IAAA,CAAK,IAAA,GAAO,UAAA;AAAA,EACd;AACF,CAAA;AAEO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAGtC,WAAA,CACE,SACgB,KAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAJlB,IAAA,IAAA,CAAS,cAAA,GAAiB,IAAA;AAOxB,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AAAA,EACd;AACF,CAAA;AAGO,SAAS,WAAW,CAAA,EAA2B;AACpD,EAAA,OAAO,OAAO,CAAA,KAA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1C;AAQA,eAAsB,kBAAA,CACpB,MAAA,EACA,IAAA,GAA4B,EAAC,EACJ;AACzB,EAAA,MAAM,WAAW,kBAAA,EAAmB;AACpC,EAAA,IAAI,CAAC,QAAA;AACH,IAAA,MAAM,IAAI,aAAA;AAAA,MACR,mFAAA;AAAA,MACA;AAAA,KACF;AACF,EAAA,OAAO,YAAA,CAAa,QAAA,EAAU,MAAA,EAAQ,IAAI,CAAA;AAC5C","file":"telegram.cjs","sourcesContent":["/**\n * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;\n * network-level / abort / serialisation failures get the generic\n * `NetworkError`. Consumers catch on the discriminator field\n * (`isApiError` / `isNetworkError`) rather than `instanceof` — works\n * across bundler boundaries where multiple copies of the class can\n * coexist.\n */\nexport class ApiError extends Error {\n readonly isApiError = true as const;\n\n constructor(\n /** HTTP status code returned by the Takeal API. */\n public readonly status: number,\n /** Stable machine-readable code (e.g. `\"insufficient_funds\"`,\n * `\"permission_required\"`, `\"validation\"`). Same enum the\n * TypeScript types pin via openapi-typescript. */\n public readonly code: string,\n /** Human-readable message. English; the consumer maps to its\n * own i18n layer before showing to end-users. */\n message: string,\n /** Full parsed response body when available. Carries field-level\n * validation details for `code = \"validation\"`. */\n public readonly body?: unknown,\n /** Seconds the server asked to wait before trying again (its\n * `Retry-After` header), when it sent one. The SDK never retries by\n * itself. */\n public readonly retryAfterSeconds?: number,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport class NetworkError extends Error {\n readonly isNetworkError = true as const;\n\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** Type guard — preferred over `instanceof` (bundler-safe). */\nexport function isApiError(e: unknown): e is ApiError {\n return typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true;\n}\n\nexport function isNetworkError(e: unknown): e is NetworkError {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { isNetworkError?: boolean }).isNetworkError === true\n );\n}\n","import { ApiError, NetworkError } from \"./error.js\";\nimport type { TokenStore } from \"./token-store.js\";\n\n/**\n * Internal HTTP client. One per SDK instance; injected into each\n * resource. Responsibilities:\n *\n * - Construct absolute URLs from `baseUrl` + API version + path.\n * Resources pass contract paths (`/me/deposits`); the `/v1` prefix is\n * added here, in one place. Only the deployment-level endpoints\n * (`/ready`, `/branding`, …) stay unversioned.\n * - Set `Authorization: Bearer <jwt>` from the `TokenStore`.\n * - Set `Content-Type: application/json` on bodies.\n * - Parse JSON responses + map non-2xx to `ApiError`.\n * - Forward `Idempotency-Key` when the caller passes one.\n * - Send the constructor's `defaultHeaders` (the `X-Takeal-Client`\n * descriptor) on every request.\n * - Surface network failures (DNS, abort, broken pipe) as\n * `NetworkError`.\n *\n * A 401 on an authenticated call asks the refresher (set by the auth\n * resource when a remembered sign-in exists) for a new session once, and\n * repeats the call when it got one. Concurrent 401s share one refresh.\n */\n\nexport type FetchLike = typeof fetch;\n\n/** Current public contract revision of the Takeal API. */\nexport const API_VERSION = \"/v1\";\n\n/** Host-level endpoints that are not part of a versioned contract. */\nconst UNVERSIONED = new Set([\"/health\", \"/ready\", \"/branding\", \"/favicon.ico\"]);\n\n/**\n * `/me/deposits` → `/v1/me/deposits`. Already-versioned paths and the\n * unversioned ops endpoints pass through untouched.\n */\nexport function versionedPath(path: string): string {\n const p = path.startsWith(\"/\") ? path : `/${path}`;\n const bare = p.split(\"?\")[0]!;\n if (UNVERSIONED.has(bare)) return p;\n if (bare === API_VERSION || bare.startsWith(`${API_VERSION}/`)) return p;\n return `${API_VERSION}${p}`;\n}\n\nexport interface HttpOptions {\n /** Request body. Will be JSON-serialised if not already a\n * string / FormData / Blob. */\n body?: unknown;\n /** Idempotency key forwarded as the `Idempotency-Key` header.\n * Required by the Takeal API on most write endpoints. */\n idempotencyKey?: string;\n /** Extra headers merged after the SDK's defaults — caller wins. */\n headers?: Record<string, string>;\n /** Bypass the token store for one call (login, refresh). */\n skipAuth?: boolean;\n /** AbortSignal forwarded to fetch. */\n signal?: AbortSignal;\n /** Internal: this is the repeat after a refresh. */\n retried?: boolean;\n}\n\nexport class HttpClient {\n constructor(\n private readonly baseUrl: string,\n private readonly tokens: TokenStore,\n private readonly fetchImpl: FetchLike,\n /** Headers sent on every request, below the per-call `headers`\n * (a caller can still override one). */\n private readonly defaultHeaders: Record<string, string> = {},\n ) {\n if (!baseUrl) throw new Error(\"HttpClient: baseUrl is required\");\n }\n\n private refresher: (() => Promise<boolean>) | undefined;\n private refreshing: Promise<boolean> | undefined;\n\n /** Called once on a 401; resolves `true` when a new session was stored. */\n setRefresher(fn: (() => Promise<boolean>) | undefined): void {\n this.refresher = fn;\n }\n\n /** One refresh at a time, whoever asks. */\n refreshOnce(): Promise<boolean> {\n if (!this.refresher) return Promise.resolve(false);\n if (!this.refreshing) {\n this.refreshing = this.refresher()\n .catch(() => false)\n .finally(() => {\n this.refreshing = undefined;\n });\n }\n return this.refreshing;\n }\n\n async get<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"GET\", path, opts);\n }\n\n async post<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"POST\", path, opts);\n }\n\n async put<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"PUT\", path, opts);\n }\n\n async patch<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"PATCH\", path, opts);\n }\n\n async delete<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"DELETE\", path, opts);\n }\n\n /** GET a file. Same auth and refresh as the JSON calls; an error status\n * throws `ApiError` the same way. */\n async getBlob(path: string, opts: HttpOptions = {}): Promise<Blob> {\n const resp = await this.send(\"GET\", path, { ...opts, accept: \"*/*\" });\n if (!resp.ok) return parseResponse<never>(resp);\n return resp.blob();\n }\n\n private async request<T>(method: string, path: string, opts: HttpOptions): Promise<T> {\n return parseResponse<T>(await this.send(method, path, opts));\n }\n\n private async send(\n method: string,\n path: string,\n opts: HttpOptions & { accept?: string },\n ): Promise<Response> {\n const url = this.absolute(path);\n const headers: Record<string, string> = {\n Accept: opts.accept ?? \"application/json\",\n ...this.defaultHeaders,\n };\n if (opts.body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n if (opts.idempotencyKey) headers[\"Idempotency-Key\"] = opts.idempotencyKey;\n if (!opts.skipAuth) {\n const token = await Promise.resolve(this.tokens.get());\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n }\n Object.assign(headers, opts.headers ?? {});\n\n const init: RequestInit = {\n method,\n headers,\n ...(opts.signal ? { signal: opts.signal } : {}),\n };\n if (opts.body !== undefined) {\n init.body = typeof opts.body === \"string\" ? opts.body : JSON.stringify(opts.body);\n }\n\n let resp: Response;\n try {\n resp = await this.fetchImpl(url, init);\n } catch (e) {\n // DNS failure, connection refused, abort — anything before the\n // server returns a status. Map to NetworkError for the consumer.\n throw new NetworkError(e instanceof Error ? e.message : \"network error\", e);\n }\n\n if (resp.status === 401 && !opts.skipAuth && !opts.retried && this.refresher) {\n if (await this.refreshOnce()) {\n return this.send(method, path, { ...opts, retried: true });\n }\n }\n return resp;\n }\n\n private absolute(path: string): string {\n if (path.startsWith(\"http://\") || path.startsWith(\"https://\")) return path;\n const base = this.baseUrl.replace(/\\/+$/, \"\");\n return `${base}${versionedPath(path)}`;\n }\n}\n\nasync function parseResponse<T>(resp: Response): Promise<T> {\n // Read body once — the Takeal API either returns JSON or an empty body\n // (204 No Content on some DELETEs). Empty body → undefined cast.\n const text = await resp.text();\n let body: unknown;\n if (text.length === 0) {\n body = undefined;\n } else {\n try {\n body = JSON.parse(text);\n } catch {\n // Non-JSON response. On 2xx that's unexpected but not fatal —\n // hand back the raw text under a synthetic field. On error\n // status, fold into the ApiError body.\n body = { raw: text };\n }\n }\n\n if (!resp.ok) {\n const errBody = (body ?? {}) as { code?: string; message?: string };\n throw new ApiError(\n resp.status,\n errBody.code ?? `http_${resp.status}`,\n errBody.message ?? resp.statusText ?? \"request failed\",\n body,\n retryAfter(resp.headers?.get(\"Retry-After\")),\n );\n }\n return body as T;\n}\n\n/** `Retry-After` in seconds: a number of seconds or an HTTP date. */\nexport function retryAfter(v: string | null | undefined, now = Date.now()): number | undefined {\n if (!v) return undefined;\n const t = v.trim();\n if (/^\\d+$/.test(t)) return Number(t);\n const at = Date.parse(t);\n if (Number.isNaN(at)) return undefined;\n return Math.max(0, Math.ceil((at - now) / 1000));\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n \"friend\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"skipped\";\n\n/**\n * The visitor's ids at the analytics platforms (TKL-329). The SDK keeps\n * them from the moment the visitor agreed to analytics cookies and sends\n * them with an order, a top-up and a sign-in, so the server can report the\n * payment and the issued card to the platforms after the person has left\n * for the bank or Telegram. See {@link analyticsIds}.\n */\nexport interface AnalyticsIds {\n /** Yandex Metrica's ClientID, from `getClientID`. A string: it does not fit a number. */\n metrika_client_id?: string;\n /** Google Analytics' client id, from the `_ga` cookie: `1234567890.1700000000`. */\n ga_client_id?: string;\n}\n\nexport interface HandoffToken {\n /** Goes into the Mini App link's `startapp` after two underscores. */\n token: string;\n expires_at: string;\n}\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** A one-day token that carries the visitor's analytics ids into the\n * Telegram Mini App, whose sign-in reads it back. Most callers want\n * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of\n * the ids is valid. */\n async handoff(ids: AnalyticsIds): Promise<HandoffToken> {\n return this.http.post<HandoffToken>(\"/attribution/handoff\", { body: ids, skipAuth: true });\n }\n\n /**\n * The `startapp` value for a link from the site to the Mini App: the code\n * as it is, followed by `__<token>` when the visitor has analytics ids, so\n * a payment made in Telegram is still credited to the visit it came from.\n * Without ids, or when the token can't be had, just the code.\n *\n * ```ts\n * const start = await client.attribution.telegramStartParam(\"SPRING\");\n * location.href = `https://t.me/our_bot/app?startapp=${start}`;\n * ```\n */\n async telegramStartParam(code = \"\"): Promise<string> {\n const ids = analyticsIds();\n if (!ids) return code;\n try {\n const { token } = await this.handoff(ids);\n return `${code}__${token}`;\n } catch {\n return code;\n }\n }\n\n /** Send the visitor's analytics ids for the signed-in account, e.g. right\n * after they agreed to analytics cookies in the cabinet. Without an\n * argument the ids this browser holds are sent; nothing is sent when it\n * holds none. */\n async sendAnalyticsIds(ids: AnalyticsIds | undefined = analyticsIds()): Promise<void> {\n if (!ids) return;\n await this.http.post<void>(\"/me/analytics/ids\", { body: ids });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Analytics ids (TKL-329)\n// ---------------------------------------------------------------------------\n\nconst IDS_KEY = \"takeal_analytics_ids\";\n\nfunction storage(): Storage | undefined {\n try {\n return (globalThis as { localStorage?: Storage }).localStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction stored(): AnalyticsIds {\n try {\n const raw = storage()?.getItem(IDS_KEY);\n const v = raw ? (JSON.parse(raw) as AnalyticsIds) : {};\n return typeof v === \"object\" && v !== null ? v : {};\n } catch {\n return {};\n }\n}\n\nfunction clean(ids: AnalyticsIds): AnalyticsIds | undefined {\n const out: AnalyticsIds = {};\n const ym = ids.metrika_client_id?.trim();\n if (ym && /^\\d{1,32}$/.test(ym)) out.metrika_client_id = ym;\n const ga = ids.ga_client_id?.trim();\n if (ga && /^\\d+\\.\\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;\n return out.metrika_client_id || out.ga_client_id ? out : undefined;\n}\n\n/**\n * Keep analytics ids for this browser, on top of the ones kept before. The\n * Metrica sink of `initAnalytics` calls it with `getClientID`'s answer once\n * the visitor agreed to analytics; call it yourself for another platform.\n */\nexport function rememberAnalyticsIds(ids: AnalyticsIds): void {\n const merged = clean({ ...stored(), ...ids });\n if (!merged) return;\n try {\n storage()?.setItem(IDS_KEY, JSON.stringify(merged));\n } catch {\n // Storage full or blocked: the cookies still hold them.\n }\n}\n\n/** Forget the kept analytics ids: the visitor declined analytics. */\nexport function forgetAnalyticsIds(): void {\n try {\n storage()?.removeItem(IDS_KEY);\n } catch {\n // Nothing kept, or nothing to reach.\n }\n}\n\n/**\n * The visitor's analytics ids: the ones kept by {@link rememberAnalyticsIds},\n * and failing those the platforms' own cookies (`_ym_uid`, `_ga`), which\n * exist only once the visitor agreed to analytics. `undefined` when there\n * are none. The site and the cabinet share them when they share the origin.\n */\nexport function analyticsIds(): AnalyticsIds | undefined {\n const kept = stored();\n return clean({\n metrika_client_id: kept.metrika_client_id ?? readCookie(\"_ym_uid\"),\n ga_client_id: kept.ga_client_id ?? readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\"),\n });\n}\n\n/** `attribution` with the visitor's analytics ids filled in where it has none. */\nexport function withAnalyticsIds(\n attribution: SignupAttribution | undefined,\n): SignupAttribution | undefined {\n const ids = analyticsIds();\n if (!ids) return attribution;\n return {\n ...attribution,\n metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,\n ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id,\n };\n}\n","import type { Claim } from \"./claims.js\";\nimport type { CodeDiscount, CodeEffect, CodeRejection } from \"./codes.js\";\nimport type { ConsentChannel, ConsentKind } from \"./consents.js\";\nimport type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\nimport type { Deposit, DepositMethod } from \"./deposits.js\";\nimport { analyticsIds, type AnalyticsIds } from \"./attribution.js\";\nimport { isApiError } from \"../error.js\";\n\n/**\n * Cards resource — `client.cards.*`.\n *\n * The end-user \"money OUT\" surface: a user issues themselves a card backed by\n * their wallet balance via an issuer connector. Mirrors the Takeal API's\n * `/me/cards` routes:\n *\n * GET /card-products → catalog (public, before sign-in)\n * GET /me/card-products → listProducts (the catalog, personal price)\n * GET /me/card-products/{id} → getProduct\n * GET /me/cards/{id}/topup → topUpTerms\n * POST /me/cards/{id}/topup → topUp\n * POST /me/cards → create\n * GET /me/cards → list (most recent first)\n * GET /me/cards/{id} → get\n * PATCH /me/cards/{id} → update (name, design)\n * GET /me/cards/{id}/balance → balance (prepaid remaining)\n * POST /me/cards/{id}/freeze → freeze\n * POST /me/cards/{id}/unfreeze → unfreeze\n * POST /me/cards/{id}/report-lost → reportLost (lost or stolen: frozen at once)\n * POST /me/cards/{id}/transfer → transfer (to another of their cards)\n * POST /me/cards/{id}/terminate → terminate (one-way)\n * POST /me/cards/{id}/reveal → reveal (the numbers, or a provider page)\n * POST /me/cards/{id}/pin → setPin (physical cards)\n *\n * The lifecycle actions are ownership-gated server-side: a caller can only\n * freeze / unfreeze / terminate a card that belongs to them (else 404).\n *\n * Today only PREPAID is wired end-to-end; CREDIT and GIFT return 400 from\n * the Takeal API until their issuer flows land.\n */\n\n/** Card product. Only `prepaid` is fully implemented today. */\nexport type CardType = \"credit\" | \"prepaid\" | \"gift\";\n\n/**\n * Card lifecycle state.\n *\n * - `pending_payment`: an order waiting for its payment, not a card yet.\n * It has no digits and no expiry, and nothing can be done with it:\n * revealing, freezing, closing or renaming it answers 409 `card_pending`.\n * Show it as \"waiting for payment\", without a way into the card's page.\n * - `pending`: the issuer accepted the order and has not issued the card\n * yet. The price is charged. Show the card as \"being issued\" with no\n * numbers; it becomes `active` on its own, or `failed` with the price\n * back on the wallet. Some issuers take minutes, some a day.\n * - `active`, `frozen`: the usual states. Read `status_source` before\n * offering to unfreeze.\n * - `terminating`: the holder (or the issuer) closed the card and the\n * issuer has not finished: the balance comes back to the wallet when it\n * does. Show it as closing; no actions apply.\n * - `terminated`, `redeemed`, `failed`: final.\n */\nexport type CardStatus =\n | \"pending_payment\"\n | \"pending\"\n | \"active\"\n | \"frozen\"\n | \"terminating\"\n | \"terminated\"\n | \"redeemed\"\n | \"failed\";\n\n/**\n * Who made the card's last status change. `provider` on a `frozen` card\n * means the issuer froze it (a risk check, a lost-card report): the holder\n * cannot unfreeze it, so do not offer the button; say the freeze is lifted\n * through the issuer's support. `holder` and `operator` freezes are undone\n * with `unfreeze()` as usual.\n */\nexport type CardStatusSource = \"holder\" | \"operator\" | \"provider\";\n\n/** `virtual` cards show their numbers in the app; `physical` cards are plastic and have a PIN. */\nexport type CardForm = \"virtual\" | \"physical\";\n\n/**\n * Why `terminate()` is refused right now: `first_purchase_required` (the\n * card closes after its first purchase) or `card_locked` (only support can\n * change it).\n */\nexport type CloseBlockedReason = \"first_purchase_required\" | \"card_locked\";\n\n/**\n * A card design: the artwork a card is shown with. `image_url` is the front,\n * `image_url_back` the back; both are either absolute URLs or paths relative\n * to the API origin (the deployment's default design is\n * `/card-designs/default.svg`, its back `/card-designs/default.svg?side=back`)\n * — pass them through `client.assetUrl()` before rendering. `image_url_back`\n * is `null` or absent for a one-sided design: show the front on both sides.\n * The picture is in the proportions of a plastic card (1586×1000) and draws\n * no chip or card data; the client renders the number, name and expiry on\n * top. `id` is `null` for the deployment default, which is rendered from the\n * branding settings.\n */\nexport interface CardDesignRef {\n id: string | null;\n name?: string;\n image_url: string;\n image_url_back?: string | null;\n}\n\n/**\n * What issuing a card costs the caller. `amount` is the price after the\n * user's subscription discount; `base_amount` is the list price and\n * `discount_bps` the discount in basis points (1000 = 10 %). `label` is the\n * operator's wording for the fee line (\"Card issuance\").\n */\nexport interface CardProductPrice {\n /** What the user pays, decimal string, after their subscription discount. */\n amount: string;\n /**\n * ISO 4217 code: the currency the operator priced the card in, the same\n * before and after sign-in. A card order paid in this currency costs\n * exactly `amount`. It is not necessarily the currency the card is held\n * in (`CardProduct.currency`).\n */\n currency: string;\n /** Wording for the fee line, e.g. \"Card issuance\". */\n label: string;\n /** The list price before the discount, decimal string, in the same currency. */\n base_amount: string;\n /** Discount applied, in basis points (1000 = 10%). */\n discount_bps: number;\n /**\n * What issuing costs when paid from the wallet, converted the way that\n * purchase charges it. Only for a signed-in user whose wallet holds another\n * currency than the price; absent otherwise, and when there is no rate.\n */\n from_wallet?: { amount: string; currency: string } | null;\n}\n\n/**\n * A card the user can order, as listed by `GET /me/card-products`. The id is\n * opaque — it names a product, never a provider. The list comes in the\n * order the operator arranged the storefront; `is_default` marks the\n * product issued when none is chosen, wherever it sits. `designs` is the\n * set the user may pick from (may be empty when only the default applies);\n * `design` is what the card gets when no choice is made. `price` is `null`\n * for a free card. `features` is an operator-defined object (scheme, wallet\n * support, load limits, …) with no fixed keys.\n */\nexport interface CardProduct {\n id: string;\n name: string;\n /** One line under the name on the tile, or `null`. */\n tagline: string | null;\n description: string | null;\n /** Selling points to list on the product card, in order. May be empty. */\n benefits: string[];\n /**\n * Picture for the product tile, absolute URL, or `null`: show the card\n * design (`design.image_url`) then.\n */\n tile_image_url: string | null;\n card_type: CardType;\n currency: string | null;\n features: Record<string, unknown>;\n design: CardDesignRef;\n designs: CardDesignRef[];\n price: CardProductPrice | null;\n /**\n * The balance a new card comes with, already included in `price`; `null`\n * when the card starts empty and is funded with `topUp()` afterwards.\n */\n starting_balance: CardBalance | null;\n /** True for the product the deployment issues when none is chosen. */\n is_default: boolean;\n /**\n * Issuing this card sends the user's real personal details to the card\n * issuer. Show the consent screen before the order and send\n * `holder_data_transfer` in its `consents` (or give it once with\n * `client.consents.allowHolderData()`); without it the order fails with\n * 409 `holder_data_consent_required`. `false`: the issuer gets no real\n * details and no extra consent is asked.\n */\n holder_data_required: boolean;\n /**\n * What a card on this product costs to use, on top of the payments\n * themselves. A fee the card can't cover is owed and paid from the next\n * top-up (see `client.debt`). Every line is `\"0\"` when the product\n * charges nothing for it.\n */\n tariff: CardTariff;\n}\n\n/**\n * A card product's fees for using the card. Decimal strings: the fixed\n * amounts are in `currency` (the card's), the shares in percent of the\n * operation's amount.\n */\nexport interface CardTariff {\n /** `null` for a product held in several currencies: the card's own then. */\n currency: string | null;\n /** Per settled card payment, fixed. */\n operation_fixed: string;\n /** Per settled card payment, percent of its amount. */\n operation_percent: string;\n /**\n * Per payment declined through the user's own doing: not enough money,\n * wrong card details, a frozen card, a subscription not cancelled with the\n * merchant. A decline caused by the issuer or the platform costs nothing.\n */\n decline: string;\n /** Per cash withdrawal, fixed; charged instead of the payment fee. */\n cash_withdrawal_fixed: string;\n /** Per cash withdrawal, percent of its amount. */\n cash_withdrawal_percent: string;\n}\n\n/**\n * A card record as the Takeal API returns it. Mirrors the `cards` table. Note the\n * SDK never receives the full PAN or CVV here — only `last4` + expiry. The\n * gift-card `redemption_code` is returned exactly once (on create) and\n * scrubbed from subsequent list/get responses.\n */\nexport interface Card {\n id: string;\n user_id: string;\n card_type: CardType;\n status: CardStatus;\n /** Last four digits of the PAN — safe to display. Null until the card is paid for and issued. */\n last4: string | null;\n expiry_month: number | null;\n expiry_year: number | null;\n /** Gift cards only, present once on create then scrubbed. */\n redemption_code?: string;\n /** The balance the card was issued with, decimal string; `null` or `\"0\"` for a card issued empty. */\n initial_amount: string | null;\n currency: string;\n failure_reason: string | null;\n /** Who changed the status last; `null` when it never changed. See {@link CardStatusSource}. */\n status_source: CardStatusSource | null;\n /** Virtual or plastic. A `physical` card takes a PIN with {@link CardsResource.setPin}. */\n card_form: CardForm;\n /** Why the card cannot be closed right now, or `null` when it can. */\n close_blocked: CloseBlockedReason | null;\n /**\n * Top-ups the issuer has accepted and not loaded yet, summed, decimal\n * string in `currency`; `null` when there are none. It counts top-ups from\n * the wallet and top-ups paid straight to the card. Show it next to the\n * balance as money on its way to the card.\n */\n topups_pending: string | null;\n /**\n * `true` while the card's details are being prepared: the card can be\n * used and topped up, but its number can't be shown yet. Show \"Details\n * are being prepared\" instead of the reveal button and refresh the card\n * later; it turns `false` on its own, usually within minutes. Absent\n * from platforms before 0.7.6.\n */\n details_pending?: boolean;\n /**\n * Top-ups the issuer has held for too long, summed, decimal string in\n * `currency`; `null` when there are none. The money is safe and waits for\n * support to settle it; say so instead of offering a retry.\n */\n topups_held: string | null;\n /**\n * The card this one replaced: support reissued it for free because that\n * card stopped working before its term. `null` otherwise.\n */\n reissued_from_card_id?: string | null;\n /** The card support issued to replace this one, or `null`. */\n reissued_to_card_id?: string | null;\n /**\n * What was left on the card this one replaced, on its way here. Show it as\n * money in transit next to the balance, not as part of it. `null` when\n * nothing is on its way.\n */\n in_transit?: CardInTransit | null;\n /** The name the user gave the card, or `null`. */\n name: string | null;\n /** The artwork the card is shown with. Always present. */\n design: CardDesignRef;\n /** The product the card was issued from; `null` for cards issued without one. */\n product: { id: string; name: string } | null;\n created_at: string;\n updated_at: string;\n /** Only on the result of `create`, when bonuses paid part of the price. */\n bonus?: IssuanceBonus;\n}\n\n/**\n * The balance of a closed card on its way to the card that replaced it. It\n * waits for the old card's issuer to return the money (`stage: \"issuer\"`),\n * then it is loaded onto this card (`stage: \"loading\"`); once it is there,\n * `in_transit` is `null` and the card's balance has it. The move is in the\n * history as a `closed_card_balance` entry.\n */\nexport interface CardInTransit {\n /** Decimal string in `currency`. What the issuer returned once it did; before that, what the old card held. */\n amount: string;\n currency: string;\n /** The closed card the money comes from. */\n from_card_id: string;\n stage: \"issuer\" | \"loading\" | (string & {});\n}\n\n/** How bonuses changed a new card's price (\"was / now\"). Decimal strings in `currency`. */\nexport interface IssuanceBonus {\n /** Bonuses used. */\n units: string;\n /** The price before bonuses (\"was\"). */\n price: string;\n /** What the bonuses covered. */\n covered: string;\n /** What the wallet paid (\"now\"). */\n paid: string;\n currency: string;\n}\n\nexport interface CreateCardInput {\n /**\n * A product id from {@link CardsResource.listProducts}. Sent as\n * `product_id`. When given, `type` and `issuer_slug` may be omitted; when\n * both are given they must agree with the product (400 `product_mismatch`).\n * Unknown, disabled or hidden product → 400 `unknown_product`.\n */\n productId?: string;\n /** A name for the card, 1–40 characters. Sent as `name`. */\n name?: string;\n /**\n * One of the product's `designs`. Sent as `design_id`. `null` or omitted\n * picks the product's default design; a design outside the product's set →\n * 400 `design_not_allowed`.\n */\n designId?: string | null;\n /**\n * `prepaid` (the only fully-wired type today), `credit`, or `gift`.\n * Optional when `productId` is given, required otherwise.\n */\n type?: CardType;\n /**\n * @deprecated Ignored since 0.3.21. A card is issued for its product price;\n * the balance it starts with, if the product includes one, is part of that\n * price (see `CardProduct.starting_balance`). Money is added afterwards\n * with {@link CardsResource.topUp}. The field is no longer sent.\n */\n initial_amount?: string;\n /** ISO 4217 code, e.g. `\"USD\"`. */\n currency: string;\n /**\n * Optional. Slug of a specific issuer to mint with. Omit to let\n * the Takeal API pick the first active issuer. Unknown slug → 400; empty issuer\n * list → 503.\n */\n issuer_slug?: string;\n metadata?: Record<string, string>;\n /** Structured billing details — real issuers require these for 3DS / KYC. */\n customer?: CustomerInfo;\n /**\n * Pay part of the price with bonuses. Sent as `use_bonus`. On by default\n * whenever the user has bonuses; `false` pays it all from the wallet.\n */\n useBonus?: boolean;\n /** The most bonuses to use, decimal string. Sent as `bonus_amount`. */\n bonusAmount?: string;\n /**\n * A promo code for the card's price. Sent as `promo_code`. Its discount\n * comes off before bonuses; `client.codes.validate` shows it first. A code\n * that can't be used fails the request with 400 `promo_code_*` and the\n * reason. Without one, the code the user signed up with applies when it\n * covers cards. Ignored inside `deposits.initiate({ issue_card })`: send\n * `promo_code` on the top-up there.\n */\n promoCode?: string;\n /**\n * Consents the user gave with the order (`terms`, `personal_data`,\n * `marketing`, `holder_data_transfer`). Recorded with the card, or with the\n * top-up inside `deposits.initiate({ issue_card })`, at the version of\n * their documents in force now. A product with `holder_data_required`\n * needs `holder_data_transfer` here unless it was given before.\n */\n consents?: ConsentKind[];\n /** Where they were given. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\n /**\n * Required by the Takeal API on this write endpoint. Same key + body replays the\n * original card; same key + different body returns 409.\n */\n idempotencyKey: string;\n}\n\n/**\n * The wire body of a card request: the camelCase fields renamed to what\n * the API reads. Shared by {@link CardsResource.create} and the\n * `issue_card` block of `deposits.initiate`.\n */\nexport function cardRequestBody(\n input: Omit<CreateCardInput, \"idempotencyKey\" | \"currency\"> & { currency?: string },\n): Record<string, unknown> {\n const {\n productId,\n name,\n designId,\n useBonus,\n bonusAmount,\n promoCode,\n consentChannel,\n initial_amount: _ignored,\n ...rest\n } = input;\n const body: Record<string, unknown> = { ...rest };\n if (productId !== undefined) body[\"product_id\"] = productId;\n if (name !== undefined) body[\"name\"] = name;\n if (designId !== undefined) body[\"design_id\"] = designId;\n if (useBonus !== undefined) body[\"use_bonus\"] = useBonus;\n if (bonusAmount !== undefined) body[\"bonus_amount\"] = bonusAmount;\n if (promoCode !== undefined) body[\"promo_code\"] = promoCode;\n if (consentChannel !== undefined) body[\"consent_channel\"] = consentChannel;\n return body;\n}\n\n/**\n * A card bought in one step with {@link CardsResource.order}: the product and\n * how the user pays. The platform works out the amount to pay in the\n * payment's currency, locks the rate and opens the top-up that issues the\n * card.\n */\nexport interface CardOrderInput {\n /** A product id from {@link CardsResource.listProducts}. Sent as `product_id`. */\n productId: string;\n /** One of the product's designs; omit for its default. Sent as `design_id`. */\n designId?: string;\n /** A name for the card, 1 to 40 characters; defaults to the product name. */\n name?: string;\n /** How the user pays, e.g. `\"sbp\"`. */\n method: DepositMethod;\n /** The funding connector to pay through; omit to let the API pick one that takes `method`. Sent as `funder_slug`. */\n funderSlug?: string;\n /** ISO 4217 code of the payment; defaults to the currency the method is priced in. */\n currency?: string;\n /** Money to put on the card on top of its price, decimal string in the card's currency. Sent as `extra_load`. */\n extraLoad?: string;\n /**\n * A promo code for the order. A code for cards lowers the card's price.\n * A code for top-ups lowers the fee on the payment: for a way of paying\n * with its fee in the exchange rate it lowers the rate, and the amount\n * with it (see `rate` of the order and of the quote). A minimum amount of\n * such a code is checked against the money that goes onto the card, not\n * against the card's price; below it the order is refused with\n * `promo_code_below_minimum` and a sentence to show. Sent as `promo_code`.\n */\n promoCode?: string;\n /** Pay part of the price with bonuses; on by default. Sent as `use_bonus`. */\n useBonus?: boolean;\n /**\n * Consents given with the order. A product with `holder_data_required`\n * needs `holder_data_transfer` here unless it was given before.\n */\n consents?: ConsentKind[];\n /** Where they were given. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\n /** Passed to the payment provider; `return_url` is where the payment page sends the user back. */\n metadata?: Record<string, string>;\n /** The visitor's analytics ids for the order's server-side conversions.\n * Leave out to send the ones this browser holds (see `analyticsIds`). */\n analyticsIds?: AnalyticsIds;\n /**\n * The amount the user was shown and agreed to pay: `amount` of the\n * quote. If the order comes to anything else, no payment is opened and\n * the API answers 409 `price_changed` with the new quote (see\n * {@link priceChangedQuote}). Leave it out and the payment opens for\n * whatever the order comes to. Sent as `expected_amount`.\n */\n expectedAmount?: string;\n /** `currency` of the same quote. Sent as `expected_currency`. */\n expectedCurrency?: string;\n}\n\n/**\n * A card order to price with {@link CardsResource.quote} or\n * {@link CardsResource.quotePublic}: the same fields as the order.\n */\nexport interface CardOrderQuoteInput {\n /** Sent as `product_id`. */\n productId: string;\n /** Sent as `design_id`. */\n designId?: string;\n method: DepositMethod;\n /** Sent as `funder_slug`. */\n funderSlug?: string;\n currency?: string;\n /** Sent as `extra_load`. */\n extraLoad?: string;\n /** The code the user typed. Sent as `promo_code`. */\n promoCode?: string;\n /** Signed in only: pay part of the price with bonuses, on by default. Sent as `use_bonus`. */\n useBonus?: boolean;\n}\n\n/**\n * Where a promo code stands in a quote. `applied`: its discount is in the\n * amount. `conditional` (before sign-in only): it works for someone who\n * meets `conditions`, which are checked after sign-in, and the amount is\n * provisional. `rejected`: it can't be used, for `reason`; an order that\n * keeps the code is refused, so drop it from the order. `unavailable`: it\n * couldn't be checked right now; the amount is without it.\n */\nexport type PromoCodeStatus = \"applied\" | \"conditional\" | \"rejected\" | \"unavailable\";\n\n/** What a promo code does to a card order. */\nexport interface PromoCodeQuote {\n /** The code as stored, or as typed when it wasn't found. */\n code: string;\n status: PromoCodeStatus;\n /** For `rejected`. */\n reason: CodeRejection | null;\n /**\n * For `conditional`: `not_first_operation` (first card only) or\n * `own_code` (not for the person it belongs to).\n */\n conditions: CodeRejection[];\n /** A sentence to show next to the code, in English. Null when the discount says it all. */\n message: string | null;\n /**\n * The discount and what it comes off: `card_issuance` (the card's price,\n * in `discount` of the quote) or `funding_commission` (the fee on the\n * payment). A fee in the exchange rate gets lower and the amount with it,\n * so it is in `discount` of the quote too; a separate commission gets\n * lower while the amount stays the same, and more goes onto the card.\n */\n discount: CodeDiscount | null;\n /** What else the code gives, once the card is issued. */\n effects: CodeEffect[];\n /** The code the user signed up with, applied without being typed. */\n from_sign_up: boolean;\n}\n\n/**\n * The exchange rate a card order was priced at, when the payment is in\n * another currency than the card's.\n */\nexport interface CardOrderRate {\n /**\n * The rate the user gets, the fee included: units of `card_currency` per\n * 1 unit of `currency`, decimal string. Show this one; `1 / effective_rate`\n * is the price of one unit of the card's currency.\n */\n effective_rate: string;\n /** The fee in basis points (1900 = 19 %), as the order was priced. */\n fee_bps: number;\n /** `markup` (the fee is in the rate), `spread` or `commission`. */\n fee_kind: string;\n /** When the user's plan or a promo code lowered the fee in the rate: the fee before that. */\n list_fee_bps?: number | null;\n /** The promo code the rate was priced with. */\n promo_code?: string | null;\n}\n\n/** What a card order would cost now, from {@link CardsResource.quote} or {@link CardsResource.quotePublic}. */\nexport interface CardOrderQuote {\n /** What the user pays, decimal string, in `currency`. Pass it to the order as `expectedAmount`. */\n amount: string;\n /** Pass it to the order as `expectedCurrency`. */\n currency: string;\n /** The same order without the promo code, decimal string, in `currency`. */\n price: string;\n /** `price` less `amount`: what the code takes off. `\"0\"` without one. */\n discount: string;\n /** What the payment brings, in `card_currency`, as in {@link CardOrder}. */\n card_amount: string;\n card_currency: string;\n /** Card fees owed, in `card_currency`, included in `card_amount`. Always `\"0\"` before sign-in. */\n debt_withheld: string;\n /** Bonuses that pay part of the price; null before sign-in. */\n bonus_units: string | null;\n /** The amount may still change after sign-in: show it as provisional. */\n preliminary: boolean;\n /** Null when no code was typed and none applies by itself. */\n promo_code: PromoCodeQuote | null;\n /**\n * The rate the amount was worked out at, with the promo code's share\n * taken off the fee. Null when the payment is in the card's currency;\n * older platforms leave it out.\n */\n rate?: CardOrderRate | null;\n}\n\n/** What {@link CardsResource.order} returns: the top-up to pay and its price. */\nexport interface CardOrder {\n /** Send the user to `deposit.redirect_url` when `deposit.status` is `redirect_required`. The card is issued once the payment is confirmed. */\n deposit: Deposit;\n /** What the user pays, decimal string, in `currency`. */\n amount: string;\n currency: string;\n /** What the payment brings: the card's price, what goes onto the card and `debt_withheld`, in `card_currency`. A payment in the price's own currency pays the price as it is set; only the rest is converted. */\n card_amount: string;\n card_currency: string;\n /**\n * What the user owes in card fees, in `card_currency`: included in\n * `card_amount` and paid from it first. `\"0\"` when nothing is owed. Show\n * it before the payment. Older platforms leave it out.\n */\n debt_withheld?: string;\n /**\n * The rate the order was priced at. Null when the payment is in the\n * card's currency; older platforms leave it out.\n */\n rate?: CardOrderRate | null;\n}\n\n/** Why a card ordered with the sign-up was not placed. The account exists all the same. */\nexport interface CardOrderError {\n code: string;\n message: string;\n /** With `code: \"price_changed\"`: what the card costs now. */\n quote?: CardOrderQuote;\n}\n\n/**\n * The new quote of an order that opened no payment because its price\n * changed (`price_changed`), from either a thrown {@link ApiError} of\n * {@link CardsResource.order} or the `card_order_error` of a sign-in.\n * Show its amount; once the user agrees, send the order again with\n * `expectedAmount` set to it. `undefined` for any other error.\n */\nexport function priceChangedQuote(error: unknown): CardOrderQuote | undefined {\n const body = isApiError(error) ? error.body : error;\n if (typeof body !== \"object\" || body === null) return undefined;\n const { code, quote } = body as { code?: unknown; quote?: unknown };\n if (code !== \"price_changed\" || typeof quote !== \"object\" || quote === null) return undefined;\n return quote as CardOrderQuote;\n}\n\n/** Build the API body of a card order quote. */\nexport function cardOrderQuoteBody(input: CardOrderQuoteInput): Record<string, unknown> {\n const body: Record<string, unknown> = {\n product_id: input.productId,\n method: input.method,\n };\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n if (input.funderSlug !== undefined) body[\"funder_slug\"] = input.funderSlug;\n if (input.currency !== undefined) body[\"currency\"] = input.currency;\n if (input.extraLoad !== undefined) body[\"extra_load\"] = input.extraLoad;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.useBonus !== undefined) body[\"use_bonus\"] = input.useBonus;\n return body;\n}\n\n/** Build the API body of a card order. */\nexport function cardOrderBody(input: CardOrderInput): Record<string, unknown> {\n const body: Record<string, unknown> = {\n product_id: input.productId,\n method: input.method,\n };\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n if (input.name !== undefined) body[\"name\"] = input.name;\n if (input.funderSlug !== undefined) body[\"funder_slug\"] = input.funderSlug;\n if (input.currency !== undefined) body[\"currency\"] = input.currency;\n if (input.extraLoad !== undefined) body[\"extra_load\"] = input.extraLoad;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.useBonus !== undefined) body[\"use_bonus\"] = input.useBonus;\n if (input.consents !== undefined) body[\"consents\"] = input.consents;\n if (input.consentChannel !== undefined) body[\"consent_channel\"] = input.consentChannel;\n if (input.metadata !== undefined) body[\"metadata\"] = input.metadata;\n const ids = input.analyticsIds ?? analyticsIds();\n if (ids !== undefined) body[\"analytics_ids\"] = ids;\n if (input.expectedAmount !== undefined) body[\"expected_amount\"] = input.expectedAmount;\n if (input.expectedCurrency !== undefined) body[\"expected_currency\"] = input.expectedCurrency;\n return body;\n}\n\n/** Remaining balance of a prepaid card. */\nexport interface CardBalance {\n amount: string;\n currency: string;\n /**\n * From `cards.balance()` only: top-ups the issuer has accepted and not\n * confirmed yet, summed, decimal string in `currency`; `null` when there\n * are none. Not part of `amount`, even when the issuer already shows the\n * money: show it next to the balance as on its way.\n */\n pending?: string | null;\n}\n\n/** What a top-up of a card can be right now, from `GET /me/cards/{id}/topup`. */\nexport interface TopUpTerms {\n /** Whether the card can be topped up at this moment. */\n available: boolean;\n /** Why not, in plain words, when `available` is false. */\n reason: string | null;\n /** Currency top-ups are made in: the card's. */\n currency: string;\n /** What the wallet holds right now, in the wallet's currency. */\n wallet_available: CardBalance;\n /** Smallest single top-up the product allows, or `null` for no floor. */\n min: CardBalance | null;\n /** Largest single top-up the product allows, or `null` for no cap. */\n max: CardBalance | null;\n /**\n * What the user owes in card fees, in the card's currency, or `null` when\n * nothing is. A top-up from a wallet in the same currency pays it first\n * and the card gets the rest: show it before the top-up. Older platforms\n * leave it out.\n */\n debt?: CardBalance | null;\n}\n\nexport interface TopUpInput {\n /** Amount to add, decimal string, in the card's currency. */\n amount: string;\n /**\n * Required. Same key + same amount replays the first outcome; same key +\n * different amount is 409. Use a stable UUID per attempt so a retried\n * network call cannot move the money twice.\n */\n idempotencyKey: string;\n}\n\n/**\n * Where a top-up stands.\n *\n * - `pending`: the issuer accepted it and has not loaded the card yet. The\n * wallet is debited, the card balance is unchanged, the amount shows in\n * `Card.topups_pending`. Most issuers finish within minutes.\n * - `confirmed`: the money is on the card.\n * - `failed`: the issuer refused; the wallet is credited back.\n * - `stalled`: pending for longer than the deployment allows. The money is\n * safe and waits for support; it shows in `Card.topups_held`.\n * - `returned`: support sent the money back to the wallet.\n * - `written_off`: support closed it without the money coming back (the\n * issuer kept it); `failure_reason` says so.\n */\nexport type CardTopUpStatus =\n \"pending\" | \"confirmed\" | \"failed\" | \"stalled\" | \"returned\" | \"written_off\";\n\n/** One top-up attempt as the API records it. */\nexport interface CardTopUp {\n id: string;\n card_id: string;\n status: CardTopUpStatus;\n /** What landed on the card, decimal string, in `currency`. */\n amount: string;\n currency: string;\n /** What the wallet paid, decimal string, in `wallet_currency`. */\n wallet_amount: string;\n wallet_currency: string;\n failure_reason: string | null;\n created_at: string;\n updated_at: string;\n}\n\n/**\n * The outcome of a top-up with the state to redraw: card, its balance, the\n * wallet. When `topup.status` is `pending`, the wallet has paid and\n * `card_balance` has not moved yet: show the amount as on its way\n * (`card.topups_pending`) and refresh the card later or on the\n * `card_topup` notification.\n */\nexport interface TopUpResult {\n topup: CardTopUp;\n card: Card;\n card_balance: CardBalance;\n wallet: CardBalance;\n}\n\n/** Fields a user can change on their own card. Omitted fields are left as they are. */\nexport interface UpdateCardInput {\n /** New name, 1–40 characters. Sent as `name`. */\n name?: string;\n /**\n * New design (one of the product's `designs`), or `null` for the product's\n * default. Sent as `design_id`.\n */\n designId?: string | null;\n}\n\n/**\n * Kept for callers written against 0.3.x: the API no longer asks for a\n * password or a code on reveal, the session is enough. Both fields are\n * ignored and will be dropped in the next major.\n * @deprecated\n */\nexport interface RevealCardInput {\n password?: string;\n totpCode?: string;\n}\n\n/**\n * What a reveal gave, so a client can switch on one field:\n *\n * - `numbers`: `pan`, `cvv` and the expiry are filled in;\n * - `page`: the issuer shows the numbers on a page of its own, `reveal_url`\n * is set and `pan` and `cvv` are empty;\n * - `pending`: the card's details are still being prepared, nothing else\n * is filled in. Show \"Details are being prepared\" and try again in a\n * minute or two; the attempt didn't count against the reveal limit.\n */\nexport type RevealState = \"numbers\" | \"page\" | \"pending\";\n\n/**\n * Full card data from a successful reveal. **Security**: never persist this,\n * keep it in volatile memory only, clear it within `expires_in_seconds`, and\n * never write it to localStorage / logs (the API marks the response no-store).\n *\n * `state` says which of three answers this is (see {@link RevealState}).\n * Some issuers hand out a page that shows the numbers instead of the\n * numbers themselves; for some cards the details are still being prepared\n * right after issuance.\n */\nexport interface RevealedCard {\n /** Which answer this is; set by the SDK from the fields below. */\n state: RevealState;\n /** The card number; empty when `reveal_url` is set. */\n pan: string;\n /** The security code; empty when `reveal_url` is set. */\n cvv: string;\n expiry_month: number;\n expiry_year: number;\n holder_name: string;\n /**\n * A page at the card issuer that shows the details to the holder. Present\n * only for issuers that give a page instead of the numbers. Short-lived,\n * often single use: open it at once in an `<iframe>` and never store it.\n */\n reveal_url?: string;\n /**\n * The person the card is registered to at its issuer: what a checkout\n * asks for. Absent for cards issued before holders were kept.\n */\n cardholder?: Cardholder;\n /**\n * The address the card is registered at — what a merchant's checkout asks\n * for, and the postal code some of them decline a payment over. Absent\n * when the deployment has not set one.\n */\n billing_address?: BillingAddress;\n /** Display window before the client should auto-clear the data. */\n expires_in_seconds: number;\n /**\n * `true` when the details are still being prepared (`state: \"pending\"`).\n * Absent from platforms before 0.7.6.\n */\n details_pending?: boolean;\n}\n\n/** The three answers of a reveal told apart; see {@link RevealState}. */\nexport function revealState(r: Omit<RevealedCard, \"state\">): RevealState {\n if (r.details_pending) return \"pending\";\n if (r.reveal_url) return \"page\";\n return \"numbers\";\n}\n\n/** Postal address a card is registered at. Which parts exist depends on the country. */\nexport interface BillingAddress {\n line1?: string;\n line2?: string;\n city?: string;\n state?: string;\n postal_code?: string;\n country?: string;\n}\n\n/**\n * The cardholder the issuer knows: the details to type into a checkout\n * that asks for the name, phone or address on the card. `source` says\n * whether the platform made them up (`generated`), the user supplied them\n * (`provided`) or both (`mixed`).\n */\nexport interface Cardholder {\n id: string;\n first_name: string;\n last_name: string;\n /** `YYYY-MM-DD`. */\n birth_date: string;\n /** E.164. */\n phone: string;\n /** A mailbox the platform owns; mail the issuer sends there reaches the user. */\n email: string;\n address: BillingAddress;\n source: \"generated\" | \"provided\" | \"mixed\";\n}\n\n/** The new PIN for a physical card. */\nexport interface SetPinInput {\n /**\n * Four to six digits, as the user typed them. Sent once to the issuer and\n * kept nowhere: not by the SDK, not by the API. Never log it.\n */\n pin: string;\n}\n\n/** What to move, and the key that makes a retry safe. */\nexport interface TransferInput {\n /** The card the money lands on. Must be the caller's, and of the same kind and currency. */\n toCardId: string;\n /** Amount to move, decimal string, in the cards' currency. */\n amount: string;\n /**\n * Required. The same key with the same body replays the first outcome; a\n * different body on the same key is 409.\n */\n idempotencyKey: string;\n}\n\n/** One transfer attempt as the API records it. */\nexport interface CardTransfer {\n id: string;\n from_card_id: string;\n to_card_id: string;\n /**\n * `confirmed` — the money is on the other card. `on_wallet` — it came off\n * the first card but the second did not take it, so it is on the wallet\n * and `failure_reason` says so in words. `pending` / `failed` otherwise.\n */\n status: \"pending\" | \"confirmed\" | \"on_wallet\" | \"failed\";\n amount: string;\n currency: string;\n failure_reason: string | null;\n created_at: string;\n updated_at: string;\n}\n\n/** A finished transfer with the balances to redraw both cards and the wallet. */\nexport interface TransferResult {\n transfer: CardTransfer;\n from_balance: CardBalance;\n to_balance: CardBalance;\n /** Holds the money when `transfer.status` is `on_wallet`. */\n wallet: CardBalance;\n}\n\nexport class CardsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Issue a card backed by the user's wallet balance. Resolves to the new\n * `Card`. On a ledger failure after provider creation, the Takeal API rolls the row\n * to `failed` (never an orphaned active card); inspect `status` /\n * `failure_reason` on the result.\n * Errors: 409 `holder_data_consent_required` when the product has\n * `holder_data_required` and the user has not agreed to it.\n */\n async create(input: CreateCardInput): Promise<Card> {\n const { idempotencyKey, ...card } = input;\n return this.http.post<Card>(\"/me/cards\", {\n body: cardRequestBody(card),\n idempotencyKey,\n });\n }\n\n /**\n * Buy a card in one step: the API prices the product in the payment's\n * currency, locks the rate and opens the top-up that issues the card.\n * Send the user to `order.deposit.redirect_url`; the card shows as\n * `pending_payment` until the payment is confirmed. The same\n * `idempotencyKey` returns the same order.\n * Errors: 400 `unknown_product` / `method_not_available` / a limit of the\n * way of paying, 409 `holder_data_consent_required` (the product has\n * `holder_data_required` and the user has not agreed to it), 409\n * `payments_on_hold` (a payment on this account was not accepted and new\n * ones wait until support sorts it out: show the message and point the\n * user to support), 409 `price_changed` (the order came to another amount\n * than `expectedAmount`; no payment was opened, and\n * {@link priceChangedQuote} gives the new quote), 503 no funding connector\n * or no exchange rate.\n */\n async order(input: CardOrderInput & { idempotencyKey: string }): Promise<CardOrder> {\n const { idempotencyKey, ...order } = input;\n return this.http.post<CardOrder>(\"/me/card-orders\", {\n body: cardOrderBody(order),\n idempotencyKey,\n });\n }\n\n /**\n * What an order of this card would cost the signed-in user now, with the\n * promo code: the same calculation {@link order} makes, with every\n * condition of the code checked. Nothing is reserved or used up. Pass\n * `amount` and `currency` to the order as `expectedAmount` and\n * `expectedCurrency`.\n */\n async quote(input: CardOrderQuoteInput): Promise<CardOrderQuote> {\n return this.http.post<CardOrderQuote>(\"/me/card-orders/quote\", {\n body: cardOrderQuoteBody(input),\n });\n }\n\n /**\n * The same quote before sign-in, for a landing page or the purchase form\n * before the e-mail code. Prices are list prices, and a code whose\n * conditions depend on the person (first card only, say) comes back\n * `conditional`, with `preliminary` set. Send `expectedAmount` with the\n * order placed at sign-in: if the price turns out different, no payment\n * is opened and `card_order_error` carries the new quote. The API limits\n * how often one address can ask (429 `too_many_requests`).\n */\n async quotePublic(input: Omit<CardOrderQuoteInput, \"useBonus\">): Promise<CardOrderQuote> {\n return this.http.post<CardOrderQuote>(\"/card-orders/quote\", {\n body: cardOrderQuoteBody(input),\n skipAuth: true,\n });\n }\n\n /**\n * The cards the caller can order, in the order the storefront shows them\n * (`is_default` marks the one issued when none is chosen). Each item\n * carries its product card (name, tagline, benefits, tile picture),\n * artwork, and the issuance price after the caller's subscription\n * discount, in the currency the operator set it in (`price.from_wallet`\n * is the same price from the wallet, when that holds another currency).\n * Pass an item's `id` as\n * `productId` to {@link create}.\n */\n async listProducts(): Promise<CardProduct[]> {\n return this.http.get<CardProduct[]>(\"/me/card-products\");\n }\n\n /** One product from the catalog. 404 when unknown, disabled or hidden. */\n async getProduct(id: string): Promise<CardProduct> {\n return this.http.get<CardProduct>(`/me/card-products/${encodeURIComponent(id)}`);\n }\n\n /**\n * The public catalog: the same products, order and default as\n * {@link listProducts}, but readable before sign-in, for a landing page or\n * the cabinet's first screen. Prices are list prices (`discount_bps` is\n * always 0); once the user is signed in, {@link listProducts} shows what\n * they pay. The API lets caches keep this response for a minute.\n */\n async catalog(): Promise<CardProduct[]> {\n return this.http.get<CardProduct[]>(\"/card-products\");\n }\n\n /**\n * Rename the caller's own card or change its design. Resolves to the\n * updated card. 404 if the card isn't the caller's; 400 `invalid_name` /\n * `design_not_allowed` on a bad value.\n */\n async update(id: string, input: UpdateCardInput): Promise<Card> {\n const body: Record<string, unknown> = {};\n if (input.name !== undefined) body[\"name\"] = input.name;\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n return this.http.patch<Card>(`/me/cards/${encodeURIComponent(id)}`, {\n body,\n });\n }\n\n /** Fetch one card by id. */\n async get(id: string): Promise<Card> {\n return this.http.get<Card>(`/me/cards/${encodeURIComponent(id)}`);\n }\n\n /** List the caller's cards, most recent first. */\n async list(): Promise<Card[]> {\n return this.http.get<Card[]>(\"/me/cards\");\n }\n\n /**\n * Remaining balance of a prepaid card. `currency` is required by the Takeal API and\n * forwarded as a query param.\n */\n async balance(id: string, currency: string): Promise<CardBalance> {\n const q = new URLSearchParams({ currency }).toString();\n return this.http.get<CardBalance>(`/me/cards/${encodeURIComponent(id)}/balance?${q}`);\n }\n\n /**\n * What a top-up of this card can be right now: whether it is possible, the\n * currency, the wallet balance, and the product's floor and cap for one\n * top-up. Read it before drawing the form. 404 if the card isn't the caller's.\n */\n async topUpTerms(id: string): Promise<TopUpTerms> {\n return this.http.get<TopUpTerms>(`/me/cards/${encodeURIComponent(id)}/topup`);\n }\n\n /**\n * Move money from the wallet onto the caller's own card. The wallet is\n * debited first, then the card's provider loads the card; if the provider\n * refuses, the money is back on the wallet and the error says so. Resolves\n * to the card, its new balance and the wallet balance, so no second call\n * is needed. Errors carry a sentence the user can read: 400 outside the\n * floor or cap · 402 not enough in the wallet · 404 not the caller's card ·\n * 409 card frozen, closed or still being issued · 501 provider can't top\n * up · 502/503 provider declined or unreachable (wallet untouched).\n */\n async topUp(id: string, input: TopUpInput): Promise<TopUpResult> {\n const { idempotencyKey, amount } = input;\n return this.http.post<TopUpResult>(`/me/cards/${encodeURIComponent(id)}/topup`, {\n body: { amount },\n idempotencyKey,\n });\n }\n\n /**\n * Move money from one of the caller's cards to another. Both must be\n * theirs, active, in the same currency and of the same kind. The money\n * travels through the wallet one leg at a time: when the second leg does\n * not go through, the call still resolves, `transfer.status` is\n * `on_wallet` and the money is on the wallet — never between two cards.\n * Errors carry a sentence the user can read: 400 the same card twice,\n * different currencies or different kinds · 402 the card holds less than\n * that · 404 one of the cards isn't theirs · 409 a card is frozen, closed\n * or still being issued, or the key was reused with a different body ·\n * 501/502/503 the provider cannot or will not move it.\n */\n async transfer(fromCardId: string, input: TransferInput): Promise<TransferResult> {\n const { toCardId, amount, idempotencyKey } = input;\n return this.http.post<TransferResult>(`/me/cards/${encodeURIComponent(fromCardId)}/transfer`, {\n body: { to_card_id: toCardId, amount },\n idempotencyKey,\n });\n }\n\n /**\n * Freeze the caller's own card. Reversible via {@link unfreeze} while\n * `status_source` is `holder` or `operator`. The optional `reason` is\n * recorded on the audit trail. Resolves to the updated card. 404 if the\n * card isn't the caller's; 409 `card_locked` when support holds it; 501 if\n * the issuer can't freeze.\n */\n async freeze(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/freeze`, { body: { reason } });\n }\n\n /**\n * Reveal the FULL PAN + CVV for the caller's own card. The signed-in\n * session is all the API asks for; the call is rate-limited and audited\n * server-side. The Takeal API never persists this data and marks the\n * response no-store; the SDK returns it verbatim and holds nothing.\n *\n * **Consumer security duties** (the SDK can't enforce these for you):\n * keep the result in volatile memory only, never write it to\n * localStorage / logs, and clear it within `expires_in_seconds`.\n *\n * `state` tells the three answers apart: `numbers`; `page`, with\n * `reveal_url` and empty `pan` and `cvv` when the issuer shows them on a\n * page of its own (open that page in a frame right away, it is\n * short-lived); or `pending` while the card's details are still being\n * prepared, which doesn't count against the limit. A card says the same\n * in {@link Card.details_pending}, so there is no need to call this just\n * to find out.\n *\n * 403 not your card · 409 `card_locked` · 429 rate-limited · 501 connector\n * has no sensitive-data endpoint · 503 `provider_unavailable`.\n */\n async reveal(id: string, _input?: RevealCardInput): Promise<RevealedCard> {\n const r = await this.http.post<Omit<RevealedCard, \"state\">>(\n `/me/cards/${encodeURIComponent(id)}/reveal`,\n );\n return { ...r, state: revealState(r) };\n }\n\n /**\n * Unfreeze a previously-frozen card. Idempotent on an already-active card.\n * A card the issuer froze (`status_source: \"provider\"`) is not the\n * holder's to unfreeze: the API answers 409 `card_locked`, so hide the\n * button and say the freeze is lifted through the issuer's support.\n */\n async unfreeze(id: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/unfreeze`, { body: {} });\n }\n\n /**\n * Report the card lost or stolen. Works at any time, on an active or a\n * frozen card. The report is recorded first with the server's time, which\n * decides who pays for operations someone else made; then the card is\n * frozen at its issuer and only support can unfreeze it. Resolves to the\n * claim (`client.claims`): show its `number` and `reported_at`. When the\n * issuer can't be reached, `card_freeze` is `\"pending\"`: the report still\n * counts and support freezes the card by hand. Reporting again while the\n * report is open returns the same claim. 404 / 403 not the user's card ·\n * 409 `card_not_open`: the card is closed or was never issued.\n */\n async reportLost(\n id: string,\n input: { kind: \"lost\" | \"stolen\"; details?: string },\n ): Promise<Claim> {\n return this.http.post<Claim>(`/me/cards/${encodeURIComponent(id)}/report-lost`, {\n body: { kind: input.kind, details: input.details },\n });\n }\n\n /**\n * Set the PIN of the caller's own physical card. The session is enough; the\n * call is rate-limited like {@link reveal} and the PIN is kept nowhere.\n * Resolves to the card; the user also gets a notification that the PIN\n * was set. 400 not four to six digits or the card is not active · 403 not\n * your card · 409 `card_locked`, or `provider_refused` when the issuer did\n * not take it · 429 too many attempts · 501 a virtual card has no PIN.\n */\n async setPin(id: string, input: SetPinInput): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/pin`, {\n body: { pin: input.pin },\n });\n }\n\n /**\n * Terminate the caller's own card. **One-way** — a terminated card cannot be\n * reactivated. The optional `reason` is audited. Idempotent on an\n * already-terminated card. A card that still holds money is refused (409\n * `move_balance_first` or `contact_support_to_close`): close it with\n * `client.closeRequests.request(id)` instead, and the money goes back the\n * way it was paid.\n */\n async terminate(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/terminate`, {\n body: { reason },\n });\n }\n}\n","import type { ConsentChannel, ConsentKind } from \"./consents.js\";\nimport type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\nimport { withAnalyticsIds, type SignupAttribution } from \"./attribution.js\";\nimport type { CodeResult } from \"./codes.js\";\nimport {\n cardOrderBody,\n type CardOrder,\n type CardOrderError,\n type CardOrderInput,\n} from \"./cards.js\";\n\n/**\n * Auth resource — `client.auth.*`.\n *\n * Covers the end-user-facing staged auth flow: password login\n * with optional TOTP/OTP step-up, and signing in (or up) with a code sent\n * to the e-mail, no password. The shape mirrors the responses\n * the Takeal API returns from `/auth/login`, `/auth/login/totp`,\n * `/auth/login/otp/verify`, `/auth/login/2fa/switch`, and `/auth/me`.\n *\n * The login methods stash the JWT in the configured `TokenStore` on\n * success so subsequent `client.*` calls authenticate automatically.\n * Step-up responses (TotpRequired / OtpSent) carry their own short-\n * lived challenge token which the caller passes to the next method\n * — those tokens DO NOT go through the TokenStore (they're not the\n * end-state JWT).\n */\n\nexport interface User {\n id: string;\n email: string;\n role: string;\n is_active: boolean;\n /** True for users auto-provisioned via the Telegram Mini App who still hold\n * a synthetic placeholder email. The client should prompt for a real email\n * and attach it via `auth.linkEmail` — this flips the flag to false. */\n email_pending?: boolean;\n created_at: string;\n updated_at: string;\n /** ISO 4217 code the user's wallet is held in (their own choice, else the\n * deployment default). Present on `GET /auth/me`. */\n wallet_currency?: string;\n /** The Telegram account linked to this user, or `null` when none is.\n * Present on `GET /auth/me` and inside every `stage: \"jwt\"` envelope. */\n telegram?: TelegramLink | null;\n /** Whether the account has a password. `false` for an account that signs\n * in with codes only: offer \"set a password\"\n * ({@link AuthResource.requestPasswordSetup}) instead of \"change password\"\n * ({@link AuthResource.changePassword}). Present on `GET /auth/me` and\n * inside every `stage: \"jwt\"` envelope from platform 0.8.2; absent on\n * older servers. */\n has_password?: boolean;\n}\n\n/** A Telegram account attached to a user. One Telegram per account and one\n * account per Telegram. */\nexport interface TelegramLink {\n /** Telegram username without the `@`, or `null` when the user has none. */\n username: string | null;\n /** When the link was made, ISO-8601. */\n linked_at: string;\n}\n\nexport interface ExchangeTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n /** Analytics ids for a new account. The Telegram id is the anonymous key\n * here, and a `startapp` code in `initData` is read by the server. */\n attribution?: SignupAttribution;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false` the exchange resolves to\n * `{ stage: \"unknown\" }` instead, so the app can offer \"create an account\"\n * or \"I already have one\". */\n provision?: boolean;\n /** A promo or referral code for a new account. Without it the server\n * reads the `startapp` of the link the Mini App was opened with, when\n * that is a code. The result comes back as `code_result`. */\n code?: string;\n /** Consents for a new account, as in `register`. Sent as `consents`;\n * ignored for an account that already exists. */\n consents?: ConsentKind[];\n /** Sent as `consent_channel`; the server takes `miniapp` when omitted. */\n consentChannel?: ConsentChannel;\n}\n\n/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has\n * signed in with yet. No account was created and no JWT was stored. */\nexport interface TelegramUnknown {\n stage: \"unknown\";\n}\n\nexport interface LinkTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n email: string;\n password: string;\n}\n\nexport interface LoginInput {\n email: string;\n password: string;\n /** Keep this browser signed in: the SDK stores the remember token it gets\n * and renews the session by itself when it ends. For accounts with a\n * second factor, pass it again to `verifyTotp` / `verifyOtp` /\n * `completeTotpSetup`. */\n remember?: boolean;\n}\n\n/** Discriminated union — `stage` is the discriminator. */\nexport type LoginResponse = JwtIssued | TotpRequired | TotpSetupEmailRequired | TotpSetupRequired;\n\nexport interface JwtIssued {\n stage: \"jwt\";\n access_token: string;\n expires_at: string;\n user: User;\n /** `exchangeTelegram` for a new account opened with a code (`startapp`\n * or `code`): whether it was applied and what it gave. */\n code_result?: CodeResult;\n /** Present when the sign-in was remembered. The SDK keeps it in the\n * remember store; you don't need to. */\n remember_token?: string;\n remember_expires_at?: string;\n /** True iff the user's role grants `system.view_hub`.\n * Cusfront ignores this; the operator console uses it to gate `/dashboard`. */\n hub_access?: boolean;\n}\n\nexport interface TotpRequired {\n stage: \"totp_required\";\n challenge_token: string;\n expires_at: string;\n /** Alternate second factors. Pick one with `/2fa/switch`. */\n available_methods: AvailableMethod[];\n}\n\n/** A staff account is about to connect an authenticator: its first one, or\n * a new one after a backup code. The password alone is not enough, so a\n * six-digit code went to the account's e-mail first and no secret exists\n * yet. Send the code with {@link AuthResource.confirmTotpSetupEmail}; the\n * answer is `totp_setup_required` with the QR. Needs platform 0.8.4; older\n * servers answer `totp_setup_required` straight away. */\nexport interface TotpSetupEmailRequired {\n stage: \"totp_setup_email_required\";\n challenge_token: string;\n /** When the challenge ends; sign in again after that. */\n challenge_expires_at: string;\n /** Where the code went, partly hidden: `al***@example.com`. */\n destination_hint: string;\n /** When this code stops working. */\n code_expires_at: string;\n}\n\n/** The `code` of an `ApiError` from the e-mail step before an\n * authenticator is connected (`login`, `verifyTotp` with a backup code,\n * `confirmTotpSetupEmail`, `resendTotpSetupEmail`):\n * - `email_required` (409): the account has no e-mail address; an\n * administrator has to add one;\n * - `too_many_requests` (429): five codes went out in the last hour;\n * - `delivery_failed` (503): the code could not be sent, try again;\n * - `invalid_code` (401): wrong, expired, used or replaced code;\n * - `sign_in_again` (409): the account changed while the code was on its\n * way (its address, or an authenticator was connected meanwhile);\n * - `too_many_attempts` (429): locked after too many wrong codes. */\nexport type TotpSetupEmailErrorCode =\n | \"email_required\"\n | \"too_many_requests\"\n | \"delivery_failed\"\n | \"invalid_code\"\n | \"sign_in_again\"\n | \"too_many_attempts\";\n\nexport interface TotpSetupEmailInput {\n /** From the `totp_setup_email_required` answer. */\n challenge_token: string;\n /** The six digits from the e-mail. */\n code: string;\n}\n\nexport interface TotpSetupRequired {\n stage: \"totp_setup_required\";\n challenge_token: string;\n expires_at: string;\n /** OTPAuth URI rendered as a QR by the consumer. */\n otpauth_url: string;\n /** Same secret base32-encoded — for manual entry alongside QR. */\n secret_base32: string;\n}\n\nexport interface AvailableMethod {\n kind: \"totp\" | \"telegram_otp\" | \"email_otp\";\n /** Short user-facing hint, e.g. `\"Telegram (@user)\"` or `\"e****@example.com\"`. */\n hint?: string;\n}\n\nexport interface TotpVerifyInput {\n challenge_token: string;\n /** 6-digit TOTP code OR `XXXX-XXXX` backup code. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface SwitchMethodInput {\n challenge_token: string;\n method: AvailableMethod[\"kind\"];\n}\n\nexport interface RegisterInput {\n email: string;\n password: string;\n /** ISO 4217 code for the new wallet; must be offered by the deployment. */\n wallet_currency?: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Where the new user came from: the anonymous key their visits were\n * sent with (`client.attribution.touch`) and the analytics ids. Without\n * it the account is recorded with an unknown source. */\n attribution?: SignupAttribution;\n /** A promo or referral code. An unknown or expired code doesn't stop the\n * sign-up: the account is created and `code_result` says why the code\n * was not applied, so the app can show it. */\n code?: string;\n /** The boxes the user ticked: `terms` (offer, tariffs and privacy policy),\n * `personal_data`, `marketing`. A deployment can require the first two\n * (400 `consents_required` without them). */\n consents?: ConsentKind[];\n /** Where they were ticked. Read from the client header when omitted. */\n consent_channel?: ConsentChannel;\n /** Buy this card right after signing up, as `cards.order` would. The\n * sign-up's consents go with the order. The result then carries\n * `card_order` (send the user to its `deposit.redirect_url`) or, when the\n * order could not be placed, `card_order_error`; the account is created\n * either way. */\n cardOrder?: Omit<CardOrderInput, \"consents\" | \"consentChannel\">;\n}\n\nexport interface RequestEmailCodeInput {\n email: string;\n /** Language of the e-mail when the address has no account yet (`ru`,\n * `en`, …). An account's own language wins; without either the server\n * reads the browser's. */\n locale?: string;\n}\n\n/** What `requestEmailCode` returns. The same for an address with an account\n * and one without. */\nexport interface EmailCodeSent {\n /** Send it back with the code to `verifyEmailCode`. */\n challenge_id: string;\n /** When the code stops working, ISO-8601. */\n expires_at: string;\n /** When another code can be asked for, ISO-8601: keep \"send again\" off\n * until then. */\n resend_at: string;\n}\n\nexport interface VerifyEmailCodeInput {\n /** From `requestEmailCode`. Sent as `challenge_id`. */\n challengeId: string;\n /** The six digits from the e-mail. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Wallet currency for a new account; ignored for an existing one. Sent\n * as `wallet_currency`. */\n walletCurrency?: string;\n /** Where a new user came from, as in `register`. */\n attribution?: SignupAttribution;\n /** A promo or referral code for a new account, as `code` in `register`.\n * One that covers cards also lowers the price of `cardOrder`. Sent as\n * `promo_code`; the result comes back as `code_result`. */\n promoCode?: string;\n /** The boxes ticked on the form. A new account records them with its\n * sign-up and the card order with itself. A deployment can require\n * `terms` and `personal_data` for a new account: 400\n * `consents_required`, and the same code works again with them. */\n consents?: ConsentKind[];\n /** Where they were ticked. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\n /** Buy this card right after signing in, as `cards.order` would, with\n * the consents above. The result carries `card_order` (send the user to\n * its `deposit.redirect_url`) or `card_order_error` when no payment was\n * opened; the sign-in stands either way. Set `expectedAmount` and\n * `expectedCurrency` from `cards.quotePublic`: when the price after\n * sign-in differs (a code for first cards only, say),\n * `card_order_error.code` is `price_changed` and its `quote` holds the\n * new price. Show it, and once the user agrees, order with\n * `cards.order` and the new `expectedAmount`. */\n cardOrder?: Omit<CardOrderInput, \"consents\" | \"consentChannel\">;\n}\n\n/** What `verifyEmailCode` returns: a `stage: \"jwt\"` session, plus whether\n * the account was made just now and the card order. */\nexport type EmailCodeSession = JwtIssued & {\n /** `true` when the address had no account and got one with this code. */\n account_created: boolean;\n /** `true` when this code proved the mailbox of an existing account for\n * the first time and the password and linked sign-ins set before that\n * were removed. */\n credentials_reset?: boolean;\n card_order?: CardOrder;\n card_order_error?: CardOrderError;\n};\n\n/** What `requestEmailChange` returns: send `challenge_id` back with the code. */\nexport interface EmailChangeRequested {\n challenge_id: string;\n /** Where the code went, partly hidden: `al***@example.com`. */\n destination_hint: string;\n expires_at: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. With a `code`, `code_result` is set; with a\n * `cardOrder`, `card_order` or `card_order_error`. */\nexport type Session = Omit<JwtIssued, \"stage\"> & {\n card_order?: CardOrder;\n card_order_error?: CardOrderError;\n};\n\nexport interface TotpSetupComplete extends Session {\n /** Ten one-time `XXXX-XXXX` codes, returned only this once. */\n backup_codes: string[];\n}\n\n/** What `requestPasswordSetup` returns: send `challengeId` back with the\n * code and the new password. */\nexport interface PasswordSetupRequested {\n challenge_id: string;\n /** Where the code went, partly hidden: `al***@example.com`. */\n destination_hint: string;\n expires_at: string;\n}\n\nexport interface ConfirmPasswordSetupInput {\n challengeId: string;\n /** The six digits from the e-mail. */\n code: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit. */\n newPassword: string;\n}\n\nexport interface ChangePasswordInput {\n current_password: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit; must differ from the current password. */\n new_password: string;\n}\n\nexport interface OtpSentResponse {\n stage: \"otp_sent\";\n challenge_token: string;\n expires_at: string;\n method: AvailableMethod[\"kind\"];\n hint?: string;\n available_methods: AvailableMethod[];\n}\n\n/** Send `remember` as the API's `remember_me`. */\nfunction withRemember<T extends { remember?: boolean }>(\n input: T,\n): Omit<T, \"remember\"> & { remember_me?: boolean } {\n const { remember, ...rest } = input;\n return remember ? { ...rest, remember_me: true } : rest;\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n private readonly remembered?: TokenStore,\n ) {\n if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== \"gone\"));\n }\n\n /** Store what a finished sign-in returned. */\n private async keep(resp: { access_token: string; remember_token?: string }): Promise<void> {\n await Promise.resolve(this.tokens.set(resp.access_token));\n if (resp.remember_token && this.remembered) {\n await Promise.resolve(this.remembered.set(resp.remember_token));\n }\n }\n\n /** Renew a remembered sign-in: a new session and a new remember token,\n * both stored. Resolves `null` (and forgets the remember token) when there\n * is none or it no longer works; the app then shows the sign-in form.\n * The SDK does this by itself on a 401; call it on app start to resume a\n * session without a request failing first. */\n async refresh(): Promise<JwtIssued | null> {\n const r = await this.renew();\n if (r.kind === \"renewed\") return r.resp;\n if (r.kind === \"taken_over\") {\n // Another tab renewed first: its session is already stored.\n const access = await Promise.resolve(this.tokens.get());\n const user = await this.me();\n return { stage: \"jwt\", access_token: access ?? \"\", expires_at: \"\", user };\n }\n return null;\n }\n\n /** The renewal itself, for the 401 path: it must not call the API again\n * through the client, or a second 401 would wait on this very renewal. */\n private async renew(): Promise<\n { kind: \"renewed\"; resp: JwtIssued } | { kind: \"taken_over\" } | { kind: \"gone\" }\n > {\n const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n if (!token) return { kind: \"gone\" };\n try {\n const resp = await this.http.post<JwtIssued>(\"/auth/refresh\", {\n body: { remember_token: token },\n skipAuth: true,\n });\n await this.keep(resp);\n return { kind: \"renewed\", resp };\n } catch (e) {\n if (isApiError(e) && e.status === 401) {\n // Another tab of the same browser may have renewed first; its\n // tokens are then already in the (shared) stores.\n const now = await Promise.resolve(this.remembered!.get());\n if (now && now !== token && (await Promise.resolve(this.tokens.get()))) {\n return { kind: \"taken_over\" };\n }\n await Promise.resolve(this.remembered!.clear());\n await Promise.resolve(this.tokens.clear());\n return { kind: \"gone\" };\n }\n throw e;\n }\n }\n\n /** Password-auth entry. May resolve to a JWT, or to a step-up\n * challenge that needs `verifyTotp` / `verifyOtp` next. */\n async login(input: LoginInput): Promise<LoginResponse> {\n const body: Record<string, unknown> = withRemember(input);\n // The analytics ids go with a sign-in too: the server reports the\n // account's later payments with them.\n const attribution = withAnalyticsIds(undefined);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body,\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await this.keep(resp);\n }\n return resp;\n }\n\n /** Verify a TOTP code (or XXXX-XXXX backup code) against a\n * `totp_required` challenge. On success the JWT is stored. A backup code\n * signs nobody in: it is used up and the answer is\n * `totp_setup_email_required`, the start of connecting a new\n * authenticator ({@link confirmTotpSetupEmail}). Nothing is stored then.\n * Errors after a backup code: see {@link TotpSetupEmailErrorCode}. */\n async verifyTotp(input: TotpVerifyInput): Promise<JwtIssued | TotpSetupEmailRequired> {\n const resp = await this.http.post<JwtIssued | TotpSetupEmailRequired>(\"/auth/login/totp\", {\n body: withRemember(input),\n skipAuth: true,\n });\n if (resp.stage === \"totp_setup_email_required\") return resp;\n await this.keep(resp);\n return resp;\n }\n\n /** Verify a 6-digit OTP code (Telegram / email) against an\n * `otp_sent` challenge. */\n async verifyOtp(input: OtpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/otp/verify\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Create an end-user account and sign it in. The JWT is stored.\n * `wallet_currency` must be one the deployment offers; omit it to take\n * the deployment default (it can be switched later via `client.wallet`\n * while the wallet is empty).\n * Errors: 400 `validation` / `currency_not_allowed` / `consents_required`\n * / `unknown_consent`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const { cardOrder, ...rest } = input;\n const body: Record<string, unknown> = withRemember(rest);\n const attribution = withAnalyticsIds(rest.attribution);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n if (cardOrder !== undefined) body[\"card_order\"] = cardOrderBody(cardOrder);\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body,\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Step one of signing in without a password: a six-digit code goes to\n * the address. It works for an address with an account and for a new one\n * alike, and the answer doesn't say which. The code works for 10 minutes;\n * another can be asked for after `resend_at` and replaces it.\n * Errors: 400 `validation` (not an address), 429 `resend_too_soon` /\n * `too_many_requests` (the message says when to try again), 503\n * `delivery_failed`. */\n async requestEmailCode(input: RequestEmailCodeInput): Promise<EmailCodeSent> {\n const body: Record<string, unknown> = { email: input.email };\n if (input.locale !== undefined) body[\"locale\"] = input.locale;\n return this.http.post<EmailCodeSent>(\"/auth/email-code\", { body, skipAuth: true });\n }\n\n /** Step two: the code signs in to the account with that address, or\n * creates one (no password) when there is none; `account_created` says\n * which. The JWT is stored. With `cardOrder`, the card is ordered for\n * that account in the same call.\n * Errors: 401 `invalid_code` (wrong, expired or used; after five checks a\n * new code is needed), 400 `consents_required` for a new account, 403\n * `user_disabled` / `second_factor_required` (operator accounts sign in\n * with a password and their authenticator). */\n async verifyEmailCode(input: VerifyEmailCodeInput): Promise<EmailCodeSession> {\n const body: Record<string, unknown> = {\n challenge_id: input.challengeId,\n code: input.code,\n };\n if (input.remember) body[\"remember_me\"] = true;\n if (input.walletCurrency !== undefined) body[\"wallet_currency\"] = input.walletCurrency;\n const attribution = withAnalyticsIds(input.attribution);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.consents !== undefined) body[\"consents\"] = input.consents;\n if (input.consentChannel !== undefined) body[\"consent_channel\"] = input.consentChannel;\n if (input.cardOrder !== undefined) body[\"card_order\"] = cardOrderBody(input.cardOrder);\n const resp = await this.http.post<EmailCodeSession>(\"/auth/email-code/verify\", {\n body,\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Send the code from the e-mail of a `totp_setup_email_required`\n * answer. A right code answers `totp_setup_required`: show its\n * `otpauth_url` as a QR, then finish with {@link completeTotpSetup}.\n * Each code works for 5 minutes and takes five tries; only the newest\n * one works. Nothing is stored. Errors: {@link TotpSetupEmailErrorCode}. */\n async confirmTotpSetupEmail(input: TotpSetupEmailInput): Promise<TotpSetupRequired> {\n return this.http.post<TotpSetupRequired>(\"/auth/login/totp-setup/email\", {\n body: { challenge_token: input.challenge_token, code: input.code },\n skipAuth: true,\n });\n }\n\n /** A new e-mail code for the same `totp_setup_email_required` sign-in;\n * the one before it stops working. Use the `challenge_token` of the\n * answer from now on. Five codes an hour at most.\n * Errors: {@link TotpSetupEmailErrorCode}; 401 means the sign-in is over,\n * so start again with {@link login}. */\n async resendTotpSetupEmail(input: { challenge_token: string }): Promise<TotpSetupEmailRequired> {\n return this.http.post<TotpSetupEmailRequired>(\"/auth/login/totp-setup/email/resend\", {\n body: { challenge_token: input.challenge_token },\n skipAuth: true,\n });\n }\n\n /** Finish a `totp_setup_required` login: send the first code from the\n * authenticator app. The JWT is stored. The response carries ten\n * one-time `backup_codes` that are never returned again, so show them to\n * the user right away and don't keep them on the device. */\n async completeTotpSetup(input: TotpVerifyInput): Promise<TotpSetupComplete> {\n const resp = await this.http.post<TotpSetupComplete>(\"/auth/login/totp-setup\", {\n body: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Change the signed-in user's password. Every other session of the\n * account is signed out; this one stays valid.\n * Errors: 400 `weak_password` when the new password fails the policy,\n * 400 `no_password` when the account has none yet (use\n * {@link requestPasswordSetup}), 401 when the current one is wrong. */\n async changePassword(input: ChangePasswordInput): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password\", {\n body: input,\n });\n }\n\n /** Step one of setting the first password of an account that has none\n * (`user.has_password === false`, e.g. made by signing in with an e-mail\n * code): a six-digit code goes to the account's address and works for 5\n * minutes. Nothing changes yet.\n * Errors: 409 `password_exists` (use {@link changePassword}),\n * `email_required` (a Telegram account with no address yet: attach one\n * with {@link requestEmailChange} first), `email_not_proven` (sign in\n * with an e-mail code first); 429 `too_many_requests` (five codes an\n * hour); 503 `delivery_failed`. Platform 0.8.2 and newer. */\n async requestPasswordSetup(): Promise<PasswordSetupRequested> {\n return this.http.post<PasswordSetupRequested>(\"/auth/password/setup\", {});\n }\n\n /** Step two: the code from the e-mail and the new password set the\n * account's first password. Every other session of the account is signed\n * out; this one stays valid, and signing in with a code keeps working.\n * Errors: 400 `weak_password` (the code is not used up, fix the password\n * and send again), 401 `invalid_code` (after five wrong codes ask for a\n * new one), 409 `password_exists`. */\n async confirmPasswordSetup(\n input: ConfirmPasswordSetupInput,\n ): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password/setup/confirm\", {\n body: {\n challenge_id: input.challengeId,\n code: input.code,\n new_password: input.newPassword,\n },\n });\n }\n\n /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for\n * telegram/email; for TOTP it short-circuits back to the challenge. */\n async switchMethod(input: SwitchMethodInput): Promise<OtpSentResponse> {\n return this.http.post<OtpSentResponse>(\"/auth/login/2fa/switch\", {\n body: input,\n skipAuth: true,\n });\n }\n\n /** Exchange a signed Telegram Mini App `initData` payload for a session\n * JWT. The server validates the initData HMAC against the deployment's bot\n * token, then looks the Telegram id up. A known id signs in. An unknown id\n * gets a fresh account (`user.email_pending === true` — prompt for a real\n * email and call {@link linkEmail}) unless `provision: false` is passed, in\n * which case the call resolves to `{ stage: \"unknown\" }`, nothing is\n * created and nothing is stored; the app then offers to create the account\n * (call again with `provision: true`) or to attach the Telegram to an\n * existing one ({@link linkTelegram}). Stores the JWT on `stage: \"jwt\"`.\n *\n * Every other error still throws an `ApiError` (401 `invalid_init_data`,\n * 503 `telegram_not_configured`, …).\n *\n * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`\n * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when\n * you already hold a configured client. */\n exchangeTelegram(input: { initData: string; provision?: true }): Promise<JwtIssued>;\n exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown>;\n async exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown> {\n const body: {\n init_data: string;\n provision?: boolean;\n attribution?: SignupAttribution;\n code?: string;\n consents?: ConsentKind[];\n consent_channel?: ConsentChannel;\n } = {\n init_data: input.initData,\n };\n if (input.provision !== undefined) body.provision = input.provision;\n const attribution = withAnalyticsIds(input.attribution);\n if (attribution !== undefined) body.attribution = attribution;\n if (input.code !== undefined) body.code = input.code;\n if (input.consents !== undefined) body.consents = input.consents;\n if (input.consentChannel !== undefined) body.consent_channel = input.consentChannel;\n let resp: JwtIssued;\n try {\n resp = await this.http.post<JwtIssued>(\"/auth/telegram/exchange\", {\n body,\n skipAuth: true,\n });\n } catch (e) {\n if (isApiError(e) && e.status === 404 && e.code === \"telegram_unknown\") {\n return { stage: \"unknown\" };\n }\n throw e;\n }\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the Telegram account behind `initData` to an existing email +\n * password account and sign in as that account. No bearer needed; the\n * password is checked the same way `login` checks it. The JWT is stored.\n *\n * Errors: 401 `unauthenticated` (wrong email or password, as with\n * `login`) / `invalid_init_data`; 403\n * `user_disabled` / `second_factor_required` (accounts that sign in with\n * a second factor can't be linked from a Mini App); 409\n * `telegram_already_linked_other` (this account already has a different\n * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to\n * another account); 503 `telegram_not_configured`. */\n async linkTelegram(input: LinkTelegramInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/telegram/link\", {\n body: { init_data: input.initData, email: input.email, password: input.password },\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Always answers 409 `email_change_needs_code` on platform 0.8.1 and\n * newer: an address is attached only after a code sent to it comes back.\n * For the first real email of a Telegram-made account use\n * {@link requestEmailChange} and {@link confirmEmailChange}; they clear\n * `email_pending` too.\n * @deprecated Use {@link requestEmailChange} and {@link confirmEmailChange}. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Step one of an email change: a six-digit code goes to the new address\n * and works for 5 minutes. Nothing changes yet.\n * Errors: 400 `same_email`, 409 address taken, 429 `too_many_requests`\n * (five codes an hour). */\n async requestEmailChange(input: { email: string }): Promise<EmailChangeRequested> {\n return this.http.post<EmailChangeRequested>(\"/me/email/change\", {\n body: { email: input.email },\n });\n }\n\n /** Step two: the code from the e-mail changes the address; the old one\n * gets a notice. Errors: 401 `invalid_code` (after five wrong codes a new\n * request is needed), 409 the address was taken meanwhile. */\n async confirmEmailChange(input: { challengeId: string; code: string }): Promise<User> {\n return this.http.post<User>(\"/me/email/change/confirm\", {\n body: { challenge_id: input.challengeId, code: input.code },\n });\n }\n\n /** Current user — fails 401 when the stored JWT is expired or\n * missing. Useful as a \"do I have a session\" probe on app boot. */\n async me(): Promise<User> {\n return this.http.get<User>(\"/auth/me\");\n }\n\n /** Sign out: ends this session and the remembered sign-in on the\n * server (best effort: a network failure still signs out locally), then\n * forgets both tokens. */\n async signOut(): Promise<void> {\n const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n try {\n await this.http.post<void>(\"/auth/logout\", {\n body: remember ? { remember_token: remember } : {},\n retried: true,\n });\n } catch {\n // Signed out locally either way.\n }\n await Promise.resolve(this.tokens.clear());\n if (this.remembered) await Promise.resolve(this.remembered.clear());\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\nimport { cardRequestBody, type CreateCardInput } from \"./cards.js\";\nimport type { DepositTarget, FunderMode } from \"./funding-options.js\";\nimport { analyticsIds, type AnalyticsIds } from \"./attribution.js\";\n\n/**\n * Deposits resource — `client.deposits.*`.\n *\n * The \"money IN\" surface: an end user tops up their wallet balance via a\n * funder connector, or one of their cards straight away, past the wallet\n * (`card_id`, or `issue_card` for a new card). Which of the two a\n * deployment allows is in `client.fundingOptions.list()`. Mirrors the\n * Takeal API's `/me/deposits` routes:\n *\n * POST /me/deposits → initiate\n * GET /me/deposits → list (most recent first)\n * GET /me/deposits/{id} → get\n * POST /me/deposits/{id}/refunds → refund\n *\n * A deposit is rarely terminal on the initiate call: real PSPs return\n * `redirect_required` (3DS / APM redirect) and flip to `confirmed` later via\n * a connector → Takeal API inbound event. Poll `get(id)` or watch the user's\n * webhook stream for the `deposit.confirmed` / `deposit.failed` outcome.\n */\n\n/**\n * Lifecycle of a deposit. `redirect_required` carries `redirect_url`.\n * `expired`: nobody paid before `expires_at`; the user starts over with a\n * new quote. A payment that still arrives is credited at the stored rate\n * and the deposit turns `confirmed` after all.\n */\nexport type DepositStatus = \"pending\" | \"redirect_required\" | \"confirmed\" | \"failed\" | \"expired\";\n\n/**\n * Top-up rail. The chosen funder decides which it supports; `sbp` is\n * Russia's instant payments through a payment page, paid in roubles.\n */\nexport type DepositMethod = \"card\" | \"crypto\" | \"bank_transfer\" | \"sbp\";\n\n/**\n * A deposit record as the Takeal API returns it. Mirrors the `deposits` table; the\n * server-side `id` is the stable handle the SDK polls against. `idempotency_key`\n * and `request_fingerprint` are server-internal and never serialised.\n */\n/** Input for `quote()` — price a cross-currency deposit before paying. */\nexport interface CreateQuoteInput {\n /** Decimal string, e.g. `\"5000.00\"`. */\n amount: string;\n /** ISO 4217 source currency — must differ from the currency credited. */\n currency: string;\n /**\n * Quote a top-up of this card: credited in the card's currency. Pass the\n * same `card_id` to `initiate()`.\n */\n card_id?: string;\n /**\n * Quote into this currency instead of the wallet's: the currency of a\n * card issued with the top-up (`issue_card`). Ignored with `card_id`.\n */\n target_currency?: string;\n /**\n * The funding connector the deposit will go through (`funder_slug` of\n * `initiate()`). With `method`, the quote is priced on that method's own\n * terms from `fundingOptions.list()`: its fee and kind, its rate source,\n * its lifetime, its limits. Sent as `connector_slug`.\n */\n connectorSlug?: string;\n /** The way the user pays. Pass the same method to `initiate()`. */\n method?: DepositMethod;\n /**\n * A promo code for the top-up. Where the method's fee is in the rate\n * (`fee_kind: \"markup\"`), the code's percentage discount lowers that fee,\n * so the rate is priced with it and `promo_code` comes back on the quote.\n * The top-up made from the quote uses the same code: pass it again to\n * `initiate()` or leave it out. Without one, the code the user signed up\n * with is used when it works here. A code that can't be used fails with\n * 400 `promo_code_*` and the reason. Needs platform 0.8.4.\n */\n promo_code?: string;\n}\n\n/**\n * How a method's fee reads. `spread`: taken off the credited amount at the\n * deployment's rate. `markup`: in the rate the user sees, so show the rate\n * and nothing else. `commission`: the rate is the provider's and the fee is\n * a line of its own on the credited amount.\n */\nexport type FeeKind = \"spread\" | \"markup\" | \"commission\";\n\n/**\n * How far a top-up meant for a card has got. `waiting`: the card's provider\n * took the load and hasn't done it yet. `stalled`: it has taken longer than\n * the platform waits. `refunding` / `refunded`: the card never got the money,\n * and the payment is going back, or has gone back, to where it was paid from.\n */\nexport type CardLoadStatus =\n \"pending\" | \"waiting\" | \"stalled\" | \"succeeded\" | \"failed\" | \"refunding\" | \"refunded\";\n\n/**\n * A card to issue with the top-up: the fields of `cards.create` without\n * its idempotency key (the deposit's covers both). The card's price is\n * paid from the top-up and the rest becomes its starting balance.\n */\nexport type IssueCardInput = Omit<CreateCardInput, \"idempotencyKey\" | \"currency\"> & {\n /** Optional with `productId`: the product names the currency. */\n currency?: string;\n};\n\n/**\n * A rate-locked funding quote: pay `source_amount source_currency`, the\n * wallet is credited `credited_amount credited_currency` (net of the\n * platform's conversion spread). Execute by passing `id` as `quote_id` to\n * `initiate()` before `expires_at`; after that the API returns 409 and a new\n * quote is needed.\n */\nexport interface FundingQuote {\n id: string;\n source_amount: string;\n source_currency: string;\n credited_amount: string;\n credited_currency: string;\n /**\n * Provider rate before the fee, credited units per 1 source unit. Don't\n * show it: the user's rate is `effective_rate`.\n */\n rate: string;\n /**\n * The rate the user gets, credited units per 1 source unit, with the fee\n * and any discount of the user's plan or promo code in it. Show this one\n * (or its inverse, see the README) rather than working a rate out from\n * the method's `fee_bps`. Older platforms leave it out; there it is\n * `credited_amount / source_amount`.\n */\n effective_rate?: string;\n /** The fee in basis points; the same figure as `fee_bps`, under its old name. */\n spread_bps: number;\n /** The fee in basis points (2000 = 20 %). */\n fee_bps: number;\n fee_kind: FeeKind;\n provider: string;\n /** The pair the quote was priced for, when the request named one. */\n connector_slug?: string;\n method?: DepositMethod;\n /** The rate is locked until then; the deposit made with it waits for its payment as long. */\n expires_at: string;\n /**\n * Set when the user's plan or a promo code lowered the fee in the rate:\n * the method's fee before that, in basis points. `fee_bps` is what the\n * user pays.\n */\n list_fee_bps?: number;\n /** What the lower fee adds to `credited_amount`, decimal string in `credited_currency`. */\n fee_discount?: string;\n /** The promo code the rate was priced with; the top-up made from this quote uses it. */\n promo_code?: string;\n /**\n * What the user owes in card fees, in `credited_currency`, that this\n * top-up pays first: it comes off `credited_amount` and the rest is\n * credited. `\"0\"` when nothing is owed. Show it before the payment. Older\n * platforms leave it out.\n */\n debt_withheld?: string;\n}\n\nexport interface Deposit {\n id: string;\n user_id: string;\n /** Slug of the funder that handled this deposit, as configured by the deployment. */\n connector_slug: string;\n /** The connector's own reference, populated once it responds. */\n provider_reference: string | null;\n status: DepositStatus;\n /** Decimal serialised as a string to avoid float drift. */\n amount: string;\n currency: string;\n method: DepositMethod;\n /** Present when `status === \"redirect_required\"` — send the user here. */\n redirect_url: string | null;\n failure_reason: string | null;\n /** Final settled amount once confirmed (may differ from `amount` on FX). */\n confirmed_amount: string | null;\n confirmed_at: string | null;\n /** Set on cross-currency deposits: the quote this deposit executed against. */\n quote_id?: string | null;\n /** Locked provider rate (credited units per 1 source unit). */\n fx_rate?: string | null;\n fx_spread_bps?: number | null;\n /** How `fx_spread_bps` was taken; see `FeeKind`. */\n fx_fee_kind?: FeeKind | null;\n /** When the deposit stops waiting for its payment; `null` for one without a term. */\n expires_at?: string | null;\n /** The wallet's local currency the deposit converted into. */\n credited_currency?: string | null;\n /** What the wallet was actually credited, net of spread. */\n credited_amount?: string | null;\n /** Bonuses added on top of the top-up, when any were. */\n bonus_units?: string | null;\n /** What those bonuses added to the wallet, in the credited currency. */\n bonus_value?: string | null;\n /** The promo code the top-up was made with; its discount came off the commission. */\n promo_code?: string | null;\n /** Where the money goes. Older deployments leave it out: the wallet. */\n target?: DepositTarget;\n /** For a top-up onto a card: the card. */\n card_id?: string | null;\n /** The funding connector's mode when the top-up was made. */\n funder_mode?: FunderMode | null;\n /** True when the card was issued with this top-up. */\n issues_card?: boolean;\n /**\n * For a top-up onto a card: `pending` until the card provider has loaded\n * the card, then `succeeded` or `failed`. Show the top-up as done only\n * once it is `succeeded`, or once `returned_to_wallet_at` is set. Empty\n * for a top-up that was never paid: nothing was there to load.\n */\n card_load_status?: CardLoadStatus | null;\n /** Why the card could not take it, when `card_load_status` is `failed`. */\n card_load_error?: string | null;\n /** What went towards the card, in its currency, bonuses included. */\n card_amount?: string | null;\n /** The commission taken from a top-up onto a card, in the card's currency. */\n card_commission?: string | null;\n /** The money part of the price of a card issued with the top-up. */\n issue_fee?: string | null;\n /** The bonus part of that price. */\n issue_bonus_units?: string | null;\n issue_bonus_value?: string | null;\n card_loaded_at?: string | null;\n /**\n * Set when the card could not take the top-up and the money went to the\n * wallet instead (funding connectors in `mixed` mode). The user is told.\n */\n returned_to_wallet_at?: string | null;\n /**\n * The user's debt in card fees shown before the payment, in the credited\n * currency: the most this top-up pays towards it before the rest is\n * credited. Absent when nothing was owed.\n */\n debt_quoted?: string | null;\n /**\n * What the top-up did pay towards the debt. For a top-up onto a card,\n * `card_amount` is already net of it.\n */\n debt_withheld?: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface InitiateDepositInput {\n /** Decimal as a string (`\"100.00\"`) — avoids float-precision loss on the wire. */\n amount: string;\n /** ISO 4217 code, e.g. `\"USD\"`. */\n currency: string;\n method: DepositMethod;\n /**\n * Optional. Slug of a specific funder to route through. Omit to\n * let the Takeal API pick the first active funder. Unknown slug → 400; empty\n * funder list → 503.\n */\n funder_slug?: string;\n /**\n * Passed to the funding connector and stored with the deposit. Two keys\n * work across connectors: `return_url`, where the provider sends the user\n * back after a 3-D Secure step (pair it with `redirect_required`), and on\n * test deployments with the mock funder `mock_scenario`, which picks the\n * outcome: `happy` (confirmed at once, the default), `pending` (confirmed\n * about 15 s later), `redirect` (a hosted page where the user approves or\n * declines), `late` (paid after the term) or `fail`.\n */\n metadata?: Record<string, string>;\n /** Structured billing details — real PSPs require these for 3DS / compliance. */\n customer?: CustomerInfo;\n /**\n * Required by the Takeal API on this write endpoint. Same key + body replays the\n * original deposit; same key + different body returns 409. Supply a stable\n * UUID per logical attempt so a retried network call is safe.\n */\n idempotencyKey: string;\n /**\n * Required when `currency` differs from the wallet's local currency: a\n * fresh quote id from `quote()`. Cross-currency deposits without one are\n * rejected with 400; expired quotes with 409.\n */\n quote_id?: string;\n /**\n * Add bonuses on top of the top-up: the user pays `amount`, the wallet\n * gets `amount` plus what the bonuses add. On by default whenever the\n * user has bonuses that can go to a top-up (only ones that came with a\n * payment can); `false` tops up without them.\n */\n use_bonus?: boolean;\n /** The most bonuses to add, decimal string. Omit to add as many as allowed. */\n bonus_amount?: string;\n /**\n * Top up this card instead of the wallet. It must be the user's, active\n * and prepaid. A funding connector that tops up the wallet only answers\n * 400 `target_not_allowed`; one that tops up cards only needs `card_id`\n * or `issue_card`. Paying in another currency than the card's needs a\n * quote made with the same `card_id`.\n */\n card_id?: string;\n /**\n * Issue a new card and put this top-up on it. The card shows up as\n * `pending_payment` and is issued once the top-up is confirmed; if the\n * top-up fails, so does the card. Too small to cover the price → 400\n * `amount_too_small`. Not together with `card_id`.\n */\n issue_card?: IssueCardInput;\n /**\n * A promo code for this top-up, to the wallet or to a card. Its discount\n * comes off the commission; bonuses or a gift that come with the code\n * arrive once the top-up is confirmed. A code that can't be used fails the\n * request with 400 `promo_code_*` and the reason. `client.codes.validate`\n * checks it first.\n *\n * Where the method's fee is in the rate, the discount lowers the rate, and\n * only the quote prices the rate: send the code to `quote()`. A top-up\n * from that quote uses the quote's `promo_code` without being told; another\n * code here is refused (400 `validation`), and a code the quote was made\n * without is refused with 400 `promo_code_not_applicable`.\n */\n promo_code?: string;\n /** The visitor's analytics ids for the payment's server-side conversions.\n * Leave out to send the ones this browser holds (see `analyticsIds`). */\n analytics_ids?: AnalyticsIds;\n}\n\nexport interface CreateDepositRefundInput {\n /** Omit for a full refund of the original confirmed amount; same currency. */\n amount?: string;\n /** Human-readable reason, e.g. `\"customer_request\"`. */\n reason?: string;\n metadata?: Record<string, string>;\n /** Required. Replays are keyed on this. */\n idempotencyKey: string;\n}\n\n/** A refund row as the Takeal API returns it (`refunds` table, deposit-targeted). */\nexport interface Refund {\n id: string;\n target_type: string;\n deposit_id?: string;\n payment_id?: string;\n connector_slug: string;\n amount: string;\n currency: string;\n reason: string;\n status: string;\n provider_refund_reference?: string;\n failure_reason?: string;\n /** `user`, `operator`, or `system` when the platform refunded by itself. */\n requestor_type: string;\n requestor_id: string;\n created_at: string;\n updated_at: string;\n}\n\nexport class DepositsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Initiate a top-up. Resolves to the freshly-created `Deposit`, whose\n * `status` may already be `confirmed` (synchronous rails / mock) or\n * `redirect_required` (3DS / APM — forward the user to `redirect_url`).\n */\n /**\n * Price a cross-currency deposit BEFORE paying. The rate is locked\n * server-side until `expires_at`; deposits already in the currency they\n * credit (the wallet's, or the card's with `card_id`) need no quote (the\n * API answers 400 `no_quote_needed`).\n */\n async quote(input: CreateQuoteInput): Promise<FundingQuote> {\n const { connectorSlug, ...rest } = input;\n const body: Record<string, unknown> = { ...rest };\n if (connectorSlug !== undefined) body[\"connector_slug\"] = connectorSlug;\n return this.http.post<FundingQuote>(\"/me/deposits/quotes\", { body });\n }\n\n /**\n * Start a top-up. 409 `payments_on_hold`: a payment on this account was\n * not accepted and new ones wait until support sorts it out. Show the\n * message as it comes and point the user to support.\n */\n async initiate(input: InitiateDepositInput): Promise<Deposit> {\n const { idempotencyKey, issue_card, ...rest } = input;\n const body: Record<string, unknown> = { ...rest };\n if (issue_card !== undefined) body[\"issue_card\"] = cardRequestBody(issue_card);\n const ids = input.analytics_ids ?? analyticsIds();\n if (ids !== undefined) body[\"analytics_ids\"] = ids;\n return this.http.post<Deposit>(\"/me/deposits\", {\n body,\n idempotencyKey,\n });\n }\n\n /** Fetch one deposit by id — the poll target while a redirect resolves. */\n async get(id: string): Promise<Deposit> {\n return this.http.get<Deposit>(`/me/deposits/${encodeURIComponent(id)}`);\n }\n\n /** List the caller's deposits, most recent first. */\n async list(): Promise<Deposit[]> {\n return this.http.get<Deposit[]>(\"/me/deposits\");\n }\n\n /**\n * Refund a previously-confirmed deposit. Synchronous when the\n * connector settles inline; otherwise the row stays `pending` and flips\n * later via the inbound `deposit.refunded` event.\n */\n async refund(depositId: string, input: CreateDepositRefundInput): Promise<Refund> {\n const { idempotencyKey, ...body } = input;\n return this.http.post<Refund>(`/me/deposits/${encodeURIComponent(depositId)}/refunds`, {\n body,\n idempotencyKey,\n });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Balance resource — `client.balance.*`.\n *\n * The user's wallet balance, tracked in the ledger. Mirrors the Takeal API's\n * `GET /me/balance[?currency=<code>]` route. Balances are per-currency; with\n * no `currency` the wallet's own currency is returned (see `client.wallet`).\n */\n\n/** Wallet balance for one currency. `amount` is a decimal string. */\nexport interface Balance {\n amount: string;\n currency: string;\n}\n\nexport class BalanceResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Fetch the user's wallet balance. Omit `currency` for the wallet's own\n * currency; pass an ISO 4217 code (e.g. `\"USD\"`) to read another one —\n * the ledger holds a separate balance per currency.\n */\n async get(currency?: string): Promise<Balance> {\n if (!currency) return this.http.get<Balance>(\"/me/balance\");\n const q = new URLSearchParams({ currency }).toString();\n return this.http.get<Balance>(`/me/balance?${q}`);\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Bonus resource — `client.bonus.*`.\n *\n * Bonuses are a discount on the platform's services, not money. They pay\n * for part of a new card's price or of the subscription fee, and bonuses\n * that came with a payment can also be added on top of a top-up. Spending\n * happens on the operation itself: `useBonus` / `bonusAmount` on\n * `cards.create`, `use_bonus` / `bonus_amount` on `deposits.initiate`, and\n * the subscription fee takes them on its own.\n *\n * Show the balance as a number of bonuses and nothing else: no money\n * figure next to it. Money belongs next to a price only (\"was / now\",\n * \"N bonuses will be used\"), which is what {@link BonusResource.preview}\n * works out on the server.\n *\n * Mirrors `GET /me/bonus` and `POST /me/bonus/preview`.\n */\n\n/** What bonuses can pay for. */\nexport type BonusPurpose = \"card_issuance\" | \"subscription\" | \"deposit\";\n\n/** One credit of bonuses and what is left of it. */\nexport interface BonusLot {\n id: string;\n /** Where the bonuses came from, e.g. `manual`. */\n source: string;\n /** True when they came without a payment: a card or the subscription only, never a top-up. */\n restricted: boolean;\n /** Bonuses credited, decimal string. */\n amount: string;\n /** Bonuses left, decimal string. */\n remaining: string;\n /** When what is left expires; `null` = never. */\n expires_at: string | null;\n created_at: string;\n}\n\n/** One change to the bonus balance. */\nexport interface BonusMovement {\n id: string;\n /** `credit`, `debit` (taken back by support), `spend` or `expire`. */\n kind: \"credit\" | \"debit\" | \"spend\" | \"expire\" | (string & {});\n /** For a `spend`: what the bonuses went towards. */\n purpose: BonusPurpose | null;\n /** `posted`, or `reserved` while the payment they are held for goes through. */\n status: \"posted\" | \"reserved\" | (string & {});\n /** Bonuses, decimal string, always positive. */\n units: string;\n /** For a spend: the price the bonuses went against (a top-up: the amount paid). */\n price: string | null;\n /** For a spend: what the bonuses covered (a top-up: what they added). */\n value: string | null;\n /** Currency of `price` and `value`. */\n currency: string | null;\n /** The card, deposit or subscription paid for. */\n operation_id: string | null;\n created_at: string;\n}\n\n/** Where bonuses may go right now. */\nexport interface BonusTarget {\n purpose: BonusPurpose;\n /** Bonuses that may go towards it, decimal string. */\n available: string;\n /** Largest share of a price bonuses may cover, basis points (10000 = all). */\n share_bps: number;\n}\n\n/** `GET /me/bonus`. */\nexport interface BonusWallet {\n /** Bonuses the user can use now. Show it on its own, without a money figure. */\n balance: string;\n /** Bonuses held for a payment still going through. */\n pending: string;\n /** One bonus is a discount of one unit of this currency. For prices only. */\n unit_currency: string;\n spend_on: BonusTarget[];\n /** Credits with bonuses left, the soonest to expire first. */\n lots: BonusLot[];\n /** Latest changes, newest first. */\n history: BonusMovement[];\n}\n\nexport interface BonusPreviewInput {\n purpose: BonusPurpose;\n /** The price as shown, or for `deposit` the amount paid; decimal string. */\n amount: string;\n /** ISO 4217 code of `amount`. */\n currency: string;\n /** For `card_issuance`: the product, which may cap the bonus share. */\n productId?: string;\n /** The most bonuses to use; omit to use as many as allowed. */\n bonusAmount?: string;\n}\n\n/** How bonuses change one price. All amounts are decimal strings in `currency`. */\nexport interface BonusPreview {\n purpose: BonusPurpose;\n /** The price before bonuses (\"was\"); for `deposit`, the amount paid. */\n amount: string;\n /** Bonuses that would be used. */\n bonus_units: string;\n /** What they cover (or, for `deposit`, add). */\n bonus_value: string;\n /** What is left to pay (\"now\"); for `deposit`, the amount paid. */\n due: string;\n /** For `deposit`: what reaches the wallet. `null` otherwise. */\n credited: string | null;\n currency: string;\n}\n\nexport class BonusResource {\n constructor(private readonly http: HttpClient) {}\n\n /** The user's bonuses: balance, where they can go, credits and history. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<BonusWallet> {\n return this.http.get<BonusWallet>(\"/me/bonus\", { signal: opts.signal });\n }\n\n /**\n * Work out how bonuses would change a price, at the rate the payment\n * would use. Nothing is held; the numbers may move by the time the user\n * pays if prices, rates or bonuses change.\n */\n async preview(input: BonusPreviewInput): Promise<BonusPreview> {\n const { productId, bonusAmount, ...rest } = input;\n const body: Record<string, unknown> = { ...rest };\n if (productId !== undefined) body[\"product_id\"] = productId;\n if (bonusAmount !== undefined) body[\"bonus_amount\"] = bonusAmount;\n return this.http.post<BonusPreview>(\"/me/bonus/preview\", { body });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Debt resource — `client.debt.*`: card fees the user's cards could not\n * cover.\n *\n * GET /me/debt → get\n *\n * A card product's tariff (`CardProduct.tariff`) charges fees for using the\n * card: per payment, per decline that was the user's doing, per cash\n * withdrawal. A fee comes off the card; what the card can't cover is owed by\n * the user, not by the card. The next top-up of any of their cards (or of\n * their wallet) pays it first and credits the rest. Show that amount before\n * the payment:\n *\n * - a deposit quote: `FundingQuote.debt_withheld`, off `credited_amount`;\n * - a card order: `CardOrder.debt_withheld`, already in `card_amount`;\n * - a card top-up: `TopUpTerms.debt`;\n * - the deposit itself: `Deposit.debt_quoted`, then `debt_withheld` once paid.\n *\n * The user is notified when a debt arises (`debt_created`) and when it is\n * paid (`debt_settled`).\n */\n\n/** An amount with its currency, decimal string. */\nexport interface DebtAmount {\n amount: string;\n currency: string;\n}\n\n/** What a fee was charged for. */\nexport type CardFeeKind = \"operation\" | \"decline\" | \"cash_withdrawal\" | (string & {});\n\n/** One amount owed. */\nexport interface DebtLine {\n id: string;\n /** What it is owed for: `card_fee`. */\n basis: string;\n /** The fee behind it: `operation`, `decline` or `cash_withdrawal`. */\n fee_kind: CardFeeKind | null;\n /** The amount owed when it arose, decimal string. */\n amount: string;\n /** What is still owed of it, decimal string. */\n outstanding: string;\n currency: string;\n /** The card the fee was for. */\n card_id: string | null;\n card_last4: string | null;\n /** The card operation the fee was for. */\n transaction_id: string | null;\n merchant_name: string | null;\n /** The operation's amount, decimal string, never negative. */\n operation_amount: string | null;\n operation_currency: string | null;\n created_at: string;\n /** When it was paid in full; `null` while something is owed. */\n settled_at: string | null;\n}\n\n/** What the user owes, from `GET /me/debt`. */\nexport interface Debt {\n /** Per currency; empty when nothing is owed. */\n total: DebtAmount[];\n /** The amounts still owed, newest first. */\n items: DebtLine[];\n}\n\nexport class DebtResource {\n constructor(private readonly http: HttpClient) {}\n\n /** What the user owes in card fees, per currency, and what for. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Debt> {\n return this.http.get<Debt>(\"/me/debt\", { signal: opts.signal });\n }\n\n /** What the user owes in `currency`, decimal string; `\"0\"` when nothing. */\n async owedIn(currency: string, opts: { signal?: AbortSignal } = {}): Promise<string> {\n const debt = await this.get(opts);\n const want = currency.trim().toUpperCase();\n return debt.total.find((d) => d.currency.toUpperCase() === want)?.amount ?? \"0\";\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Close requests — `client.closeRequests.*`: close a card that still holds\n * money and get what is left back the way it was paid.\n *\n * POST /me/cards/{id}/close-request → request\n * GET /me/close-requests → list\n * GET /me/close-requests/{id} → get\n * POST /me/close-requests/{id}/payout-details → submitPayoutDetails\n *\n * `cards.terminate()` refuses a card with money on it (409\n * `move_balance_first` or `contact_support_to_close`). Offer\n * `closeRequests.request(cardId)` instead: the card is closed at its issuer\n * right away, and once the issuer returns what was left on it the money goes\n * back to the payments the card was topped up with, in the currency they\n * were paid in, newest first. Unspent bonuses are not refunded, and a debt\n * the user was told about (`client.debt`) is withheld first.\n *\n * The request moves through `status`:\n *\n * - `accepted`: the card is being closed;\n * - `awaiting_issuer`: closed; the issuer has not returned the balance yet;\n * - `refunding`: the money is on its way back (`refunds`, `on_the_way`);\n * - `payout_details_required`: it can't go back the way it came. Ask the\n * user for a bank account or a card in their own name and send it with\n * {@link CloseRequestsResource.submitPayoutDetails};\n * - `identity_check`: the details are being checked (they can still be\n * corrected);\n * - `manual_payout`: checked; the transfer is being made;\n * - `refunded`: everything due went back.\n *\n * Amounts only, never rates: the user sees what the card held\n * (`balance`), what is kept back (`bonus_excluded`, `debt_withheld`), what\n * goes back in all once it is known (`refund_total`) and what went back so\n * far (`refunded`). `deadline_at` is when the refund is due by. The user is\n * notified when the close is accepted (`card_close_requested`), each time\n * money is sent back (`card_close_refund_sent`), when details are needed\n * (`card_close_payout_details_needed`) and when a transfer by hand was made\n * (`card_close_paid_manually`).\n */\n\n/** An amount with its currency, decimal string. */\nexport interface CloseAmount {\n amount: string;\n currency: string;\n}\n\n/** Where a close request stands. */\nexport type CloseRequestStatus =\n | \"accepted\"\n | \"awaiting_issuer\"\n | \"refunding\"\n | \"payout_details_required\"\n | \"identity_check\"\n | \"manual_payout\"\n | \"refunded\"\n | (string & {});\n\n/** One part of the refund. */\nexport interface CloseRefund {\n id: string;\n /** Decimal string, in `currency`. */\n amount: string;\n currency: string;\n /** `pending` (sent, the bank has not confirmed it yet) or `succeeded`. */\n status: \"pending\" | \"succeeded\" | (string & {});\n /** `original_payment`: back to a payment's details; `manual`: transferred to the details the user gave. */\n method: \"original_payment\" | \"manual\" | (string & {});\n created_at: string;\n /** When it went through; `null` while pending. */\n completed_at: string | null;\n}\n\n/** The details given for a transfer by hand, as shown back: never the whole number. */\nexport interface PayoutDetailsShown {\n kind: \"account\" | \"card\" | (string & {});\n /** The last four digits, e.g. `•••• 4312`. */\n masked: string;\n given_at: string | null;\n}\n\n/** A request to close a card with money on it. */\nexport interface CloseRequest {\n id: string;\n card_id: string;\n card_last4: string | null;\n status: CloseRequestStatus;\n /** What the card held: what the issuer returned once it did, before that what the card showed. */\n balance: CloseAmount;\n /** Unspent bonuses, not refunded, in the card's currency; `null` until the issuer returned the balance. */\n bonus_excluded: string | null;\n /** The debt withheld, in the card's currency; `null` until the issuer returned the balance. */\n debt_withheld: string | null;\n /** Everything that goes back, in the currency the card was paid in; `null` until known. */\n refund_total: CloseAmount | null;\n /** What went back already. */\n refunded: CloseAmount;\n /** Sent and not confirmed yet. */\n on_the_way: CloseAmount;\n /** The parts of the refund, oldest first. */\n refunds: CloseRefund[];\n /** The details given for a transfer by hand, if any. */\n payout_details: PayoutDetailsShown | null;\n /** The refund is due by then. */\n deadline_at: string;\n created_at: string;\n /** When the issuer took the close. */\n closed_at: string | null;\n /** When the issuer returned the balance. */\n returned_at: string | null;\n refunded_at: string | null;\n}\n\n/**\n * Where to send the money when it can't go back the way it came. Either kind\n * must be in the user's own name. Spaces and dashes in numbers are fine.\n */\nexport type PayoutDetailsInput =\n | {\n kind: \"account\";\n /** The account holder's full name as the bank has it. */\n holder_name: string;\n account_number: string;\n /** The bank's code (BIC). */\n bank_code: string;\n bank_name?: string;\n }\n | {\n kind: \"card\";\n /** The cardholder's full name as on the card. */\n holder_name: string;\n card_number: string;\n };\n\n/** Why a close request can't be made right now (409 `code`). */\nexport type CloseRequestError =\n | \"card_locked\"\n | \"first_purchase_required\"\n | \"card_not_closable\"\n | \"topup_in_progress\"\n | \"card_closing\"\n | \"no_balance\"\n | \"provider_refused\"\n | (string & {});\n\nexport class CloseRequestsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Close a card that holds money, the rest going back the way it was paid.\n * Asking again for the same card returns the same request. 404 no such\n * card · 409 {@link CloseRequestError}: `no_balance` means the card holds\n * nothing, close it with `cards.terminate()` · 503 the issuer can't be\n * reached; the card stays as it was.\n */\n async request(cardId: string, input: { reason?: string } = {}): Promise<CloseRequest> {\n return this.http.post<CloseRequest>(`/me/cards/${encodeURIComponent(cardId)}/close-request`, {\n body: { reason: input.reason },\n });\n }\n\n /** Every card close request of the user, newest first. */\n async list(opts: { signal?: AbortSignal } = {}): Promise<CloseRequest[]> {\n const res = await this.http.get<{ items: CloseRequest[] }>(\"/me/close-requests\", {\n signal: opts.signal,\n });\n return res.items;\n }\n\n /** One close request. 404 when it isn't the user's. */\n async get(id: string, opts: { signal?: AbortSignal } = {}): Promise<CloseRequest> {\n return this.http.get<CloseRequest>(`/me/close-requests/${encodeURIComponent(id)}`, {\n signal: opts.signal,\n });\n }\n\n /** The request for this card, if the user made one. */\n async forCard(cardId: string, opts: { signal?: AbortSignal } = {}): Promise<CloseRequest | null> {\n const all = await this.list(opts);\n return all.find((r) => r.card_id === cardId) ?? null;\n }\n\n /**\n * Give a bank account or a card in the user's own name, when the request\n * is `payout_details_required` (or `identity_check`, to correct them). 400\n * `validation`: a name, number or bank code that doesn't look right · 409\n * `details_not_needed`.\n */\n async submitPayoutDetails(id: string, details: PayoutDetailsInput): Promise<CloseRequest> {\n return this.http.post<CloseRequest>(\n `/me/close-requests/${encodeURIComponent(id)}/payout-details`,\n { body: details },\n );\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Claims — `client.claims.*`: dispute a card operation or complain, and\n * follow the claim by its number and status. A card lost or stolen is\n * reported with `client.cards.reportLost()`, which opens a claim too.\n *\n * POST /me/cards/{id}/report-lost → cards.reportLost\n * POST /me/claims → create\n * GET /me/claims → list\n * GET /me/claims/{id} → get\n *\n * Every claim has a `number` (e.g. `C-000123`) the user can quote to\n * support, and a `status`:\n *\n * - `open`: received, nobody has taken it yet;\n * - `in_review`: support is working on it;\n * - `resolved`: done, support's answer is in `resolution`;\n * - `rejected`: declined, the reason is in `resolution`.\n *\n * `reported_at` is when the platform took the claim. For a lost or stolen\n * card that time decides who pays for operations someone else made with it,\n * so show it. Such a card is frozen at its issuer at once (`card_freeze:\n * \"frozen\"`) and only support can unfreeze it; `cards.unfreeze()` answers\n * 409 `card_locked`. If the issuer could not be reached, `card_freeze` is\n * `\"pending\"`: the report counts all the same and support freezes the card\n * by hand.\n *\n * The user is notified when a claim comes in (`card_reported_lost`,\n * `card_claim_opened`) and when its status changes (`card_claim_updated`).\n */\n\n/** What a claim is about. */\nexport type ClaimKind = \"lost\" | \"stolen\" | \"dispute\" | \"complaint\" | (string & {});\n\n/** Where a claim stands. */\nexport type ClaimStatus = \"open\" | \"in_review\" | \"resolved\" | \"rejected\" | (string & {});\n\n/** The card operation a claim is about. */\nexport interface ClaimTransaction {\n /** The operation's id in `client.history` (`txn_<id>`). */\n id: string;\n /** Decimal string, without a sign. */\n amount: string;\n currency: string;\n merchant_name: string | null;\n /** `pending`, `cleared`, `reversed` or `declined`. */\n status: string;\n occurred_at: string;\n}\n\n/** A claim. */\nexport interface Claim {\n id: string;\n /** What support calls it, e.g. `C-000123`. */\n number: string;\n kind: ClaimKind;\n status: ClaimStatus;\n card_id: string | null;\n card_last4: string | null;\n /** The operation disputed or complained about, if one was named. */\n transaction: ClaimTransaction | null;\n /** The user's own words. */\n description: string;\n /** When the platform took the claim (the server's time, never the device's). */\n reported_at: string;\n /** Lost or stolen only: `frozen`, or `pending` while the issuer hasn't frozen the card. `null` for other kinds. */\n card_freeze: \"frozen\" | \"pending\" | null;\n /** Lost or stolen only: when the card was frozen. */\n card_frozen_at: string | null;\n /** Support's answer, once there is one. */\n resolution: string | null;\n created_at: string;\n updated_at: string;\n /** When the claim was resolved or rejected. */\n resolved_at: string | null;\n}\n\n/** A page of the user's claims, newest first. */\nexport interface ClaimPage {\n items: Claim[];\n total: number;\n}\n\n/** A dispute or a complaint. */\nexport interface CreateClaimInput {\n /** `dispute`: a card operation the user doesn't agree with; `complaint`: anything else. */\n kind: \"dispute\" | \"complaint\";\n /** What happened, 10 to 4000 characters. */\n description: string;\n /** The card it is about. Optional; found from the operation when one is named. */\n cardId?: string;\n /** The operation it is about, as `client.history` names it (`txn_<id>`). Optional. */\n transactionId?: string;\n}\n\n/** Why a claim can't be made right now (409 `code`). */\nexport type ClaimError = \"card_not_open\" | \"too_many_claims\" | (string & {});\n\nexport class ClaimsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Dispute a card operation, or complain. 400 `validation`: a description\n * that is too short or too long, an operation that isn't on the user's\n * cards, or a lost or stolen card (use `cards.reportLost()`) · 404 no\n * such card · 409 `too_many_claims`: 20 claims are waiting for an answer.\n */\n async create(input: CreateClaimInput): Promise<Claim> {\n return this.http.post<Claim>(\"/me/claims\", {\n body: {\n kind: input.kind,\n description: input.description,\n card_id: input.cardId,\n transaction_id: input.transactionId,\n },\n });\n }\n\n /** The user's claims, lost and stolen cards included, newest first. */\n async list(\n opts: { limit?: number; offset?: number; signal?: AbortSignal } = {},\n ): Promise<ClaimPage> {\n const qs = new URLSearchParams();\n if (opts.limit != null) qs.set(\"limit\", String(opts.limit));\n if (opts.offset != null) qs.set(\"offset\", String(opts.offset));\n const q = qs.toString();\n return this.http.get<ClaimPage>(`/me/claims${q ? `?${q}` : \"\"}`, { signal: opts.signal });\n }\n\n /** One claim. 404 when it isn't the user's. */\n async get(id: string, opts: { signal?: AbortSignal } = {}): Promise<Claim> {\n return this.http.get<Claim>(`/me/claims/${encodeURIComponent(id)}`, { signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Codes resource — `client.codes.*`.\n *\n * Promo and referral codes. A code is used on the operation itself:\n * `code` on `auth.register` / `auth.exchangeTelegram`, `promo_code` on\n * `deposits.initiate`, `promoCode` on `cards.create`, and\n * `client.subscription.setPromoCode` for the monthly fee. On a card bought\n * with a payment, a code that works on issuing a card lowers the card's\n * price; one that works on top-ups lowers the payment's commission.\n * {@link CodesResource.validate} checks one first and says what it would do,\n * without using it up.\n *\n * What a code gives besides a discount (bonuses, a gift subscription) comes\n * once the operation goes through. Bonuses are a discount on our services,\n * never money: show them as a number of bonuses.\n *\n * Mirrors `POST /me/codes/validate`.\n */\n\n/** The operations a code can be used on. */\nexport type CodeOperation = \"signup\" | \"deposit\" | \"card_issuance\" | \"subscription\";\n\n/** Why a code can't be used. Show `message` from the response as is. */\nexport type CodeRejection =\n | \"unknown\"\n | \"disabled\"\n | \"not_started\"\n | \"expired\"\n | \"not_applicable\"\n | \"exhausted\"\n | \"already_used\"\n | \"not_first_operation\"\n | \"below_minimum\"\n | \"currency_mismatch\"\n | \"own_code\"\n | \"already_registered\"\n | (string & {});\n\n/** What one effect of a code did, as a sign-up reports it. */\nexport interface CodeEffectOutcome {\n /** `bonus_credit`, `gift_subscription`, `grant_referral_code` or `referral_link`. */\n kind: string;\n /** `applied`, `skipped` (a gift when a subscription was already running) or `failed`. */\n status: \"applied\" | \"skipped\" | \"failed\" | (string & {});\n reason?: string;\n /** Details by kind: `units` for bonuses, `tier` and `until` for a gift, `code` for a referral code of one's own. */\n [detail: string]: unknown;\n}\n\n/** What the code sent with a sign-up did. The account is created either way. */\nexport interface CodeResult {\n code: string;\n status: \"applied\" | \"rejected\";\n reason: CodeRejection | null;\n /** A sentence to show when the code was not applied. */\n message: string | null;\n effects: CodeEffectOutcome[];\n}\n\n/** One effect a code carries, as `validate` lists it. */\nexport type CodeEffect =\n | { kind: \"gift_subscription\"; tier_id: string; days: number | null }\n | { kind: \"bonus_credit\"; amount: string }\n | { kind: \"grant_referral_code\"; program_id: string }\n | { kind: string; [k: string]: unknown };\n\nexport interface CodeDiscount {\n kind: \"percent\" | \"fixed\";\n /** For `percent`: basis points off (1000 = 10%). */\n bps: number | null;\n /** For `fixed`: the amount off, decimal string. */\n amount: string | null;\n currency: string | null;\n /** What comes off: `card_issuance`, `funding_commission` (the top-up commission) or `subscription`. */\n applies_to: \"card_issuance\" | \"funding_commission\" | \"subscription\" | null;\n}\n\nexport interface ValidateCodeInput {\n code: string;\n operation: CodeOperation;\n /** The operation's amount, decimal string: needed for a code with a minimum or a fixed discount. */\n amount?: string;\n /** ISO 4217 code of `amount`; for a top-up, the currency it is credited in. */\n currency?: string;\n /**\n * For a top-up paid in another currency than it is credited in: what is\n * paid, decimal string. A code's minimum may be set in either currency;\n * with both amounts sent it is checked the way the top-up itself checks it.\n */\n paid_amount?: string;\n /** ISO 4217 code of `paid_amount`. */\n paid_currency?: string;\n /**\n * For a card bought with a payment (`cardOrders.create`, or\n * `deposits.initiate` with `issue_card`): the product. The code is then\n * checked the way that purchase takes it: as a card issuance, against the\n * product's price, when the code works on issuing a card, and as a top-up\n * otherwise. `discount.applies_to` in the answer says which, and\n * `discount_value` is what comes off the card's price. `operation` may be\n * `deposit` or `card_issuance`.\n */\n product_id?: string;\n}\n\n/** `POST /me/codes/validate`. */\nexport interface CodeCheck {\n valid: boolean;\n code: string | null;\n /** `promo` or `referral`. */\n kind: string | null;\n reason: CodeRejection | null;\n message: string | null;\n discount: CodeDiscount | null;\n /** For a card or the monthly fee with `amount` sent: what comes off it. */\n discount_value: string | null;\n /** Everything else the code gives, once the operation goes through. */\n effects: CodeEffect[];\n}\n\nexport class CodesResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Whether a code can be used on an operation now and what it would do.\n * Nothing is used up. For sign-up there is nothing to check here: send\n * the code with `auth.register` and read `code_result`.\n */\n async validate(input: ValidateCodeInput): Promise<CodeCheck> {\n return this.http.post<CodeCheck>(\"/me/codes/validate\", { body: input });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Referral resource — `client.referral.*`.\n *\n * For the people allowed to invite: their referral code, the link to\n * share, the people who signed up with it (no names or contacts, only\n * when they joined and how far they got) and what each reward was for.\n * Referral codes are given by invitation, so `code` is `null` for most\n * users. Rewards are bonuses, a discount on our services, not money.\n *\n * Mirrors `GET /me/referral`.\n */\n\n/** Someone the user invited, without anything that identifies them. */\nexport interface InvitedFriend {\n joined_at: string;\n /** Bonuses they brought so far, decimal string. */\n rewarded: string;\n has_card: boolean;\n has_topped_up: boolean;\n}\n\n/** One reward. */\nexport interface ReferralReward {\n id: string;\n /** `signup`, `card_issuance`, `first_deposit` or `deposit`. */\n event: \"signup\" | \"card_issuance\" | \"first_deposit\" | \"deposit\" | (string & {});\n /** The friend's operation a percent was taken of. */\n basis_amount: string | null;\n basis_currency: string | null;\n /** Bonuses, decimal string. */\n units: string;\n /** Always `bonus`. */\n payout_kind: string;\n /** `pending` until the bonuses are on the account. */\n status: \"pending\" | \"credited\" | (string & {});\n created_at: string;\n}\n\nexport interface Referral {\n code: string | null;\n /** The invitation link, or `null` when the deployment has none: share the code then. */\n link: string | null;\n invited_count: number;\n /** The latest invited, newest first. */\n invited: InvitedFriend[];\n /** Bonuses earned in total, decimal string. */\n total_rewarded: string;\n rewards: ReferralReward[];\n}\n\nexport class ReferralResource {\n constructor(private readonly http: HttpClient) {}\n\n /** The user's referral code, link, invited friends and rewards. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Referral> {\n return this.http.get<Referral>(\"/me/referral\", { signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Subscription resource — `client.subscription.*`.\n *\n * The user's own paid tier or gift: the discounts it gives and, for a\n * gift, when it ends. Not to be confused with `client.subscriptions`, which\n * is about announcement channels.\n *\n * Mirrors `GET /me/subscription`, `PUT /me/subscription/promo-code` and\n * `POST /me/subscription/cancel`.\n */\n\nexport interface UserSubscription {\n id: string;\n tier_id: string;\n tier_name: string;\n /** The plan's own picture, WebP or SVG, as an absolute URL. `null` when\n * the plan has none: show your generic one. Platforms before 0.8.4 leave\n * it out. */\n tier_icon_url?: string | null;\n /** `active`, `tryout`, `grace`, `cancelled` or `expired`. */\n status: string;\n /** `billing` (charged monthly) or `gift` (never charged). */\n kind: \"billing\" | \"gift\" | (string & {});\n /** For a gift: when it ends; `null` = no end date. */\n gift_until: string | null;\n monthly_fee: string;\n currency: string;\n /** Discount on card prices, basis points. */\n issuance_discount_bps: number;\n /** Discount on the top-up commission, basis points. */\n funding_discount_bps: number;\n started_at: string;\n current_period_end: string | null;\n /** The promo code the monthly fee is charged with, if any. */\n promo_code_id: string | null;\n}\n\n/** What cancelling did. */\nexport interface CancelledSubscription {\n /** The subscription, now `cancelled`. */\n subscription: UserSubscription | null;\n /** What went back to the balance for the unused days of the paid period,\n * decimal string; `\"0\"` for a gift, a trial or an unpaid renewal. */\n refund: string;\n currency: string;\n}\n\nexport class SubscriptionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** The user's subscription, or `null` when there is none. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<UserSubscription | null> {\n return this.http.get<UserSubscription | null>(\"/me/subscription\", { signal: opts.signal });\n }\n\n /**\n * Charge the monthly fee with a promo code, as long as the code allows.\n * `null` removes it. A code that can't be used on the fee fails with 400\n * `promo_code_*`; no paid subscription running → 404.\n */\n async setPromoCode(code: string | null): Promise<UserSubscription> {\n return this.http.put<UserSubscription>(\"/me/subscription/promo-code\", { body: { code } });\n }\n\n /**\n * Cancel the subscription now, in one step. What was paid for the current\n * period comes back to the balance for the days not used. No subscription\n * running → 404; 503 `refund_unavailable` when the refund can't be made\n * right now (the subscription keeps running; try again).\n */\n async cancel(): Promise<CancelledSubscription> {\n return this.http.post<CancelledSubscription>(\"/me/subscription/cancel\", {});\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Branding resource — `client.branding.*`.\n *\n * Runtime white-label config published by the deployment at `GET /branding`\n * (public, no auth). Lets a Cusfront re-theme itself on the fly — platform\n * name, logo, favicon, brand colours and the label used for the end-user's balance — without\n * a rebuild. Pairs with the build-time `BrandConfig`: the server-side values\n * win whenever both are present.\n */\n\n/** Public brand config of the deployment. All strings; empty = use the client default. */\nexport interface Branding {\n /** Platform display name (e.g. the white-label brand). */\n platform_name: string;\n /** Name of the merchant-facing portal. */\n merchant_portal_name: string;\n /** Logo image — absolute URL or `data:` URI. Empty → client default. */\n logo_url: string;\n /** Favicon — absolute URL or `data:` URI. Empty → client default. */\n favicon_url: string;\n /** User-facing name of the balance, e.g. `\"Wallet\"` or `\"Acme Wallet\"`.\n * Display-only: the `balance` API shape never changes with it. */\n wallet_label: string;\n /** Primary brand colour as `#rrggbb`. Empty → client default palette. */\n primary_color: string;\n /** Secondary brand colour as `#rrggbb`. Empty → client default palette. */\n secondary_color: string;\n /** Accent colour as `#rrggbb`. Empty → client default palette. */\n accent_color: string;\n /**\n * Address of the deployment's public status page, when it has one. Show a\n * \"Status\" link only when this is set. Platforms before 0.9.0 don't send\n * the field.\n */\n status_url?: string | null;\n}\n\nexport class BrandingResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Fetch the deployment's public brand config. Safe to call before login. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Branding> {\n return this.http.get<Branding>(\"/branding\", { skipAuth: true, signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Wallet resource — `client.wallet.*`.\n *\n * Which currency the user's wallet is held in. Deposits in any other\n * currency are converted on funding (quote first, see `client.deposits`);\n * cards issued in another currency are paid from the wallet with an FX leg\n * at issuance. A user may switch currency only while every balance is zero\n * and only to a currency the deployment offers (`allowed`).\n */\n\n/** The user's wallet currency and what they may switch to. */\nexport interface Wallet {\n /** ISO 4217 code the wallet is held in. */\n currency: string;\n /** `true` when chosen by the user (or set by an operator), `false` when it\n * is the deployment default. */\n explicit: boolean;\n /** Currencies accepted by `set()`. */\n allowed: string[];\n}\n\nexport class WalletResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Current wallet currency + the currencies the user may switch to. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Wallet> {\n return this.http.get<Wallet>(\"/me/wallet\", { signal: opts.signal });\n }\n\n /**\n * Switch the wallet currency. Fails with `409 wallet_not_empty` while any\n * balance is non-zero, and `400 currency_not_allowed` for a currency the\n * deployment does not offer.\n */\n async set(currency: string, opts: { signal?: AbortSignal } = {}): Promise<Wallet> {\n return this.http.put<Wallet>(\"/me/wallet\", { body: { currency }, signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Blog resource — `client.blog.*`.\n *\n * @deprecated The blog is a category of Documents now. Use\n * `client.documents.list({ category: \"blog\" })` and `client.documents.get(slug)`:\n * same posts, same slugs, same block shape, plus the folder trail and the\n * version history. `/blog/*` on the API answers for one more release and then\n * goes away; this class goes with it.\n *\n * Posts are public: these calls work before the user logs in, which is what\n * a marketing page or a Mini App landing screen needs.\n *\n * A post arrives as a **structured document**, not as HTML. `body_blocks` is\n * a flat list of typed nodes; map each `type` onto your own component and the\n * post inherits your site's styling. `body_markdown` is there too if you'd\n * rather run your own renderer.\n *\n * ```ts\n * const { posts } = await client.blog.list({ perPage: 5 });\n * const post = await client.blog.get(posts[0].slug);\n *\n * post.body_blocks.map((b) => {\n * switch (b.type) {\n * case \"heading\": return <Heading level={b.level}>{b.text}</Heading>;\n * case \"paragraph\": return <P>{b.text}</P>;\n * case \"image\": return <Figure src={b.url} alt={b.alt} caption={b.caption} />;\n * case \"list\": return <List ordered={b.ordered} items={b.items} />;\n * case \"quote\": return <Quote>{b.text}</Quote>;\n * case \"code\": return <Code lang={b.lang}>{b.text}</Code>;\n * case \"divider\": return <Hr />;\n * }\n * });\n * ```\n *\n * Inline emphasis (`**bold**`, `[link](url)`) is left as Markdown inside\n * block text — every renderer already knows what to do with it.\n */\n\n/** One node of a post body. Discriminated on `type`. */\nexport type BlogBlock =\n | { type: \"heading\"; level: number; text: string }\n | { type: \"paragraph\"; text: string }\n | { type: \"image\"; url: string; alt?: string; caption?: string }\n | { type: \"list\"; ordered: boolean; items: string[] }\n | { type: \"quote\"; text: string }\n | { type: \"code\"; lang?: string; text: string }\n | { type: \"divider\" };\n\nexport interface BlogPost {\n /** Stable public key — link by this. */\n slug: string;\n title: string;\n /** Teaser for cards; falls back to the first paragraph. */\n excerpt: string;\n /** Image URL, relative to the API origin. Absent when no cover is set. */\n cover_url?: string;\n /** Raw Markdown, for consumers that bring their own renderer. */\n body_markdown: string;\n /** The recommended input for rendering — see the module docs. */\n body_blocks: BlogBlock[];\n tags: string[];\n /** Present only when the post declares one. */\n locale?: string;\n /** Rough read time in minutes (minimum 1). */\n reading_minutes: number;\n published_at: string | null;\n updated_at: string;\n}\n\nexport interface BlogListInput {\n /** 1-based. Default 1. */\n page?: number;\n /** 1..=50. Default 10. */\n perPage?: number;\n /** Only posts carrying this tag. */\n tag?: string;\n /** Only posts in this locale. */\n locale?: string;\n}\n\nexport interface BlogList {\n posts: BlogPost[];\n total: number;\n page: number;\n per_page: number;\n}\n\n/** @deprecated See the module docs: use `client.documents`. */\nexport class BlogResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Published posts, newest first. No authentication required. */\n async list(input: BlogListInput = {}): Promise<BlogList> {\n const q = new URLSearchParams();\n if (input.page) q.set(\"page\", String(input.page));\n if (input.perPage) q.set(\"per_page\", String(input.perPage));\n if (input.tag) q.set(\"tag\", input.tag);\n if (input.locale) q.set(\"locale\", input.locale);\n const qs = q.toString();\n return this.http.get<BlogList>(`/blog/posts${qs ? `?${qs}` : \"\"}`, {\n skipAuth: true,\n });\n }\n\n /** One post by slug. No authentication required. */\n async get(slug: string): Promise<BlogPost> {\n return this.http.get<BlogPost>(`/blog/posts/${encodeURIComponent(slug)}`, {\n skipAuth: true,\n });\n }\n\n /**\n * Absolute URL for an image path returned inside a post (`cover_url`, or an\n * image block's `url`). Handy when the app renders on a different origin\n * than the API.\n */\n imageUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return `${baseUrl.replace(/\\/$/, \"\")}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Documents resource: `client.documents.*`.\n *\n * Everything the operators write lives in one tree: blog posts, the\n * knowledge base, legal pages, internal notes. Every call here works before\n * the user signs in and shows more once they have: a signed-in user sees the\n * documents marked for users, staff see theirs. The SDK sends the session\n * token when it has one, so the same call serves the public site and the\n * signed-in cabinet.\n *\n * A document arrives as a list of typed blocks. `body_blocks` is flat; map\n * each `type` onto your own component and the document inherits your site's\n * styling. `body_markdown` is there too if you'd rather run your own renderer.\n *\n * ```ts\n * // The knowledge base: folders and articles for a sidebar.\n * const tree = await client.documents.tree({ category: \"knowledge-base\" });\n *\n * // One article, with the text in force today.\n * const doc = await client.documents.get(\"how-to-top-up\");\n *\n * // A legal page as it read on a given day, and its history.\n * const then = await client.documents.get(\"offer\", { at: \"2026-01-01T00:00:00Z\" });\n * const versions = await client.documents.versions(\"offer\");\n *\n * doc.body_blocks.map((b) => {\n * switch (b.type) {\n * case \"heading\": return <Heading level={b.level}>{b.text}</Heading>;\n * case \"paragraph\": return <P>{b.text}</P>;\n * case \"image\": return <Figure src={client.assetUrl(b.url)} alt={b.alt} caption={b.caption} />;\n * case \"list\": return <List ordered={b.ordered} items={b.items} />;\n * case \"quote\": return <Quote>{b.text}</Quote>;\n * case \"code\": return <Code lang={b.lang}>{b.text}</Code>;\n * case \"divider\": return <Hr />;\n * }\n * });\n * ```\n *\n * Links between documents come out as site paths: `/blog/<slug>` for a post,\n * `/docs/<slug>` for everything else (`site_path` on each document says which\n * one it is). Route those two prefixes to your document pages and links keep\n * working after a document is renamed or moved.\n */\n\n/** Category keys: the four folders at the top of the tree. */\nexport type DocumentCategory = \"blog\" | \"knowledge-base\" | \"legal\" | \"internal\";\n\n/** Who may read a document. */\nexport type DocumentScope = \"public\" | \"users\" | \"staff\" | \"operators\";\n\n/** One node of a document body. Discriminated on `type`. */\nexport type DocumentBlock =\n | { type: \"heading\"; level: number; text: string }\n | { type: \"paragraph\"; text: string }\n | { type: \"image\"; url: string; alt?: string; caption?: string }\n | { type: \"list\"; ordered: boolean; items: string[] }\n | { type: \"quote\"; text: string }\n | { type: \"code\"; lang?: string; text: string }\n | { type: \"divider\" };\n\n/** One step of the folder trail, root first. */\nexport interface DocumentPathStep {\n id: string;\n key: string;\n title: string;\n}\n\nexport interface Document {\n /** Permanent address. Link by this; it survives renames and moves. */\n slug: string;\n title: string;\n /** Teaser for cards; falls back to the first paragraph. */\n excerpt: string;\n /** Image URL, relative to the API origin. Absent when no cover is set. */\n cover_url?: string;\n /** Raw Markdown, for consumers that bring their own renderer. */\n body_markdown: string;\n /** The recommended input for rendering; see the module docs. */\n body_blocks: DocumentBlock[];\n tags: string[];\n /** Present only when the document declares one. */\n locale?: string;\n /** Rough read time in minutes (minimum 1). */\n reading_minutes: number;\n published_at: string | null;\n updated_at: string;\n /** Category the document sits in. */\n category: DocumentCategory | string;\n /** Folder trail, root first. */\n path: DocumentPathStep[];\n /** Who may read it. */\n read_scope: DocumentScope;\n /** Number of the text shown. */\n version: number;\n /** When the text shown took effect. */\n effective_from: string;\n /** Path under the site root where this document is read. */\n site_path: string;\n}\n\nexport interface DocumentListInput {\n /** Category key. */\n category?: DocumentCategory | string;\n /** Only documents in this folder and the folders under it. */\n folderId?: string;\n /** Only documents carrying this tag. */\n tag?: string;\n /** Only documents in this locale. */\n locale?: string;\n /** Words to search for in the title and the text. */\n q?: string;\n /** 1-based. Default 1. */\n page?: number;\n /** 1..=50. Default 10. */\n perPage?: number;\n}\n\nexport interface DocumentList {\n documents: Document[];\n total: number;\n page: number;\n per_page: number;\n}\n\n/** A folder as it appears in the navigation tree. */\nexport interface DocumentFolder {\n id: string;\n parent_id: string | null;\n key: string;\n title: string;\n description: string;\n position: number;\n}\n\n/** A document as it appears in the navigation tree: enough for a link. */\nexport interface DocumentTreeEntry {\n folder_id: string;\n slug: string;\n title: string;\n excerpt: string;\n tags: string[];\n position: number;\n updated_at: string;\n site_path: string;\n}\n\nexport interface DocumentTree {\n /** Folders with at least one document you may read under them, plus the categories. */\n folders: DocumentFolder[];\n /** Published documents you may read, in folder order. */\n documents: DocumentTreeEntry[];\n}\n\n/** One saved text of a document, without the text itself. */\nexport interface DocumentVersionSummary {\n version: number;\n title: string;\n /** When this text took effect. */\n effective_from: string;\n /** What changed, in the editor's words. Often empty. */\n note: string;\n changed_at: string;\n}\n\nexport interface DocumentTag {\n tag: string;\n /** Published documents you may read that carry it. */\n count: number;\n}\n\nexport class DocumentsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Published documents you may read, paged. The blog comes newest first,\n * other categories in the order set by the editors.\n */\n async list(input: DocumentListInput = {}): Promise<DocumentList> {\n const q = new URLSearchParams();\n if (input.category) q.set(\"category\", input.category);\n if (input.folderId) q.set(\"folder_id\", input.folderId);\n if (input.tag) q.set(\"tag\", input.tag);\n if (input.locale) q.set(\"locale\", input.locale);\n if (input.q) q.set(\"q\", input.q);\n if (input.page) q.set(\"page\", String(input.page));\n if (input.perPage) q.set(\"per_page\", String(input.perPage));\n const qs = q.toString();\n return this.http.get<DocumentList>(`/documents${qs ? `?${qs}` : \"\"}`);\n }\n\n /** Folders and documents for a sidebar or a table of contents. */\n async tree(input: { category?: DocumentCategory | string } = {}): Promise<DocumentTree> {\n const qs = input.category ? `?category=${encodeURIComponent(input.category)}` : \"\";\n return this.http.get<DocumentTree>(`/documents/tree${qs}`);\n }\n\n /** Every tag on a document you may read, most used first. */\n async tags(): Promise<DocumentTag[]> {\n return this.http.get<DocumentTag[]>(\"/documents/tags\");\n }\n\n /**\n * One document by its address. Without `at`, the text in force now; with\n * `at` (an ISO 8601 moment), the text that was in force then. Unknown\n * addresses and documents above your level are a 404.\n */\n async get(slug: string, opts: { at?: string | Date } = {}): Promise<Document> {\n const at = opts.at instanceof Date ? opts.at.toISOString() : opts.at;\n const qs = at ? `?at=${encodeURIComponent(at)}` : \"\";\n return this.http.get<Document>(`/documents/${encodeURIComponent(slug)}${qs}`);\n }\n\n /** Every saved text of a document, newest first, with the date each took effect. */\n async versions(slug: string): Promise<DocumentVersionSummary[]> {\n return this.http.get<DocumentVersionSummary[]>(\n `/documents/${encodeURIComponent(slug)}/versions`,\n );\n }\n\n /** The document as it read in one version. */\n async version(slug: string, version: number): Promise<Document> {\n return this.http.get<Document>(`/documents/${encodeURIComponent(slug)}/versions/${version}`);\n }\n\n /**\n * Absolute URL for an image path returned inside a document (`cover_url`,\n * or an image block's `url`). Handy when the app renders on a different\n * origin than the API.\n */\n imageUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return `${baseUrl.replace(/\\/$/, \"\")}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Subscriptions resource — `client.subscriptions.*`.\n *\n * Which channels the signed-in user agreed to receive announcements on.\n * `available` tells you which toggles to render: a deployment with no\n * Telegram bot configured can't deliver there, so offering the switch would\n * be a lie.\n *\n * ```ts\n * const { channels, available } = await client.subscriptions.get();\n * await client.subscriptions.set([...channels, \"telegram\"]);\n * ```\n *\n * Unrelated to paid/VIP tiers — this is only about announcements.\n *\n * @deprecated Announcements are now the `marketing` category of the\n * notification preferences. Read them with\n * `client.notifications.getPreferences()` and change them with\n * `client.notifications.setPreferences({ categories: { marketing: { email: true, telegram: false } } })`.\n * This endpoint keeps working as an alias over that setting.\n */\n\nexport type BroadcastChannel = \"email\" | \"telegram\" | (string & {});\n\nexport interface Subscriptions {\n /** Channels the user currently receives announcements on. */\n channels: BroadcastChannel[];\n /** Channels this deployment can actually deliver on. */\n available: BroadcastChannel[];\n}\n\n/** @deprecated See the note at the top of this module. */\nexport class SubscriptionsResource {\n constructor(private readonly http: HttpClient) {}\n\n async get(): Promise<Subscriptions> {\n return this.http.get<Subscriptions>(\"/me/subscriptions\");\n }\n\n /**\n * Replace the whole set — this is a PUT, not a merge. Pass `[]` to opt out\n * of everything.\n */\n async set(channels: BroadcastChannel[]): Promise<Subscriptions> {\n return this.http.put<Subscriptions>(\"/me/subscriptions\", {\n body: { channels },\n });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Sessions resource — `client.sessions.*`.\n *\n * Every device or browser the user is signed in on. Lets a settings screen\n * show \"where you're signed in\" and sign one or all of them out.\n *\n * ```ts\n * const sessions = await client.sessions.list();\n * const others = sessions.filter((s) => !s.current);\n * await client.sessions.revokeOthers();\n * ```\n */\n\nexport interface UserSession {\n /** Session id; pass it to `revoke`. */\n jti: string;\n issued_at: string;\n expires_at: string;\n last_seen_at: string;\n /** Client IP recorded for the session, if known. */\n remote_ip?: string | null;\n /** Browser or app that opened the session, if known. */\n user_agent?: string | null;\n /** `true` for the session this client is using. */\n current: boolean;\n}\n\nexport class SessionsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** All live sessions of the account, this one included. */\n async list(): Promise<UserSession[]> {\n return this.http.get<UserSession[]>(\"/me/sessions\");\n }\n\n /** Sign out one session. Works on the current one too; the stored JWT\n * stops working, so follow with `client.auth.signOut()`.\n * 404 when the session is unknown or already signed out. */\n async revoke(jti: string): Promise<void> {\n await this.http.delete<void>(`/me/sessions/${encodeURIComponent(jti)}`);\n }\n\n /** Sign out every session except this one. */\n async revokeOthers(): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/me/sessions/terminate-others\");\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Push resource — `client.push.*`.\n *\n * Web Push for the signed-in user, through the older single-subscription\n * endpoint. The API now keeps one device per browser (see\n * `client.devices`), and this endpoint is an alias over the Web Push\n * devices: it keeps working, but new code should call\n * `client.devices.registerWebPush(reg)` / `unregisterWebPush(reg)` instead.\n *\n * Your service worker shows the notification: the payload is JSON with\n * `title`, `body` and `url` (where a click should lead).\n */\n\nexport interface PushStatus {\n /** `true` when a subscription is stored for this user. */\n subscribed: boolean;\n /** Host of the stored endpoint, e.g. `fcm.googleapis.com`. */\n endpoint_host?: string | null;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`.\n * `null` when push is not set up on this deployment. */\n vapid_public_key?: string | null;\n}\n\nexport interface PushSubscriptionInput {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** The part of `ServiceWorkerRegistration` the SDK needs. Typed\n * structurally so the core stays free of DOM lib types. */\nexport interface PushCapableRegistration {\n pushManager: {\n getSubscription(): Promise<{ unsubscribe(): Promise<boolean> } | null>;\n subscribe(options: {\n userVisibleOnly: boolean;\n applicationServerKey: Uint8Array;\n }): Promise<{ toJSON(): { endpoint?: string; keys?: Record<string, string> } }>;\n };\n}\n\nexport class PushResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Whether the user is subscribed, plus the VAPID key to subscribe with. */\n async status(): Promise<PushStatus> {\n return this.http.get<PushStatus>(\"/me/push-subscription\");\n }\n\n /** Store a subscription you created yourself.\n * 409 `push_disabled` when the deployment has no VAPID keys.\n * @deprecated Use `client.devices.register({ kind: \"webpush\", ... })`. */\n async save(input: PushSubscriptionInput): Promise<PushStatus> {\n return this.http.put<PushStatus>(\"/me/push-subscription\", { body: input });\n }\n\n /** Delete the stored subscription. Safe when nothing is stored.\n * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */\n async remove(): Promise<void> {\n await this.http.delete<void>(\"/me/push-subscription\");\n }\n\n /** Subscribe this browser and store the subscription. Ask for\n * notification permission before calling. Throws when push isn't set up\n * on the deployment.\n * @deprecated Use `client.devices.registerWebPush(registration)`. */\n async enable(registration: PushCapableRegistration): Promise<PushStatus> {\n const { vapid_public_key } = await this.status();\n if (!vapid_public_key) {\n throw new Error(\n \"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\",\n );\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(vapid_public_key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.save({\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n });\n }\n\n /** Unsubscribe this browser and delete the stored subscription.\n * @deprecated Use `client.devices.unregisterWebPush(registration)`. */\n async disable(registration: PushCapableRegistration): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n await this.remove();\n }\n}\n\n/** URL-safe base64 (padding optional) → bytes. */\nexport function base64UrlToBytes(input: string): Uint8Array {\n const b64 = input.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = b64 + \"=\".repeat((4 - (b64.length % 4)) % 4);\n const bin = atob(padded);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { User } from \"./auth.js\";\n\n/**\n * Me resource — `client.me.*`.\n *\n * Profile-level actions for the signed-in user that don't belong to another\n * resource. Today: the Telegram link.\n *\n * ```ts\n * // Inside a Mini App, with a signed-in client (e.g. opened via a deep link):\n * const me = await client.me.linkTelegram(window.Telegram.WebApp.initData);\n * me.telegram; // { username, linked_at }\n *\n * // From a settings screen:\n * await client.me.unlinkTelegram();\n * ```\n */\nexport class MeResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Attach the Telegram account behind `initData` to the signed-in user.\n * Returns the updated user (`telegram` is set). Repeating the call with\n * the same Telegram is fine.\n *\n * Errors: 401 `invalid_init_data`; 403 `user_disabled` /\n * `second_factor_required`; 409 `telegram_already_linked_other` (the\n * account already has a different Telegram; `unlinkTelegram` first) /\n * `telegram_in_use` (that Telegram belongs to another account); 503\n * `telegram_not_configured`. */\n async linkTelegram(initData: string): Promise<User> {\n return this.http.post<User>(\"/me/telegram\", { body: { init_data: initData } });\n }\n\n /** Detach the Telegram account from the signed-in user. Returns the\n * updated user (`telegram` is `null`).\n *\n * Errors: 404 `telegram_not_linked`; 409 `last_credential` when the\n * account has no password, so Telegram is its only way to sign in. */\n async unlinkTelegram(): Promise<User> {\n return this.http.delete<User>(\"/me/telegram\");\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Notifications resource — `client.notifications.*`.\n *\n * Every notification a user gets is also kept server-side as an inbox item,\n * whatever else was sent (a push, a Telegram message, an email). The inbox\n * is what the app shows; the other channels are the nudge to open it.\n *\n * ```ts\n * const page = await client.notifications.list({ limit: 20 });\n * for (const item of page.items) {\n * render(item.title, item.body, item.href); // href: a path inside your app, or null\n * }\n * await client.notifications.markRead(page.items[0].id);\n * ```\n *\n * Preferences decide where the nudge goes: a primary channel (or automatic\n * when `null`), per-category switches, and the user's language.\n */\n\n/** What an item is about. `security` and `money` can't be switched off\n * completely; `marketing` is off until the user opts in. */\nexport type NotificationCategory = \"money\" | \"card\" | \"security\" | \"account\" | \"marketing\";\n\n/** A way to reach the user outside the inbox. */\nexport type NotificationChannel = \"push\" | \"telegram\" | \"email\" | \"sms\";\n\n/** Language the user reads notifications in. */\nexport type NotificationLocale = \"en\" | \"ru\" | (string & {});\n\n/**\n * `data` of a `card_otp` item: a confirmation code the card issuer sent for a\n * 3-D Secure payment (`purpose: \"payment\"`) or for adding the card to Apple\n * Pay / Google Pay (`purpose: \"wallet\"`). The code is what the user needs\n * right now, so show it prominently with a copy button and a countdown from\n * `expires_in_minutes`; `merchant_name`, `amount` and `currency` are absent\n * for wallet codes. Narrow with `isCardOtp(item)`.\n */\nexport interface CardOtpData {\n otp: string;\n purpose: \"payment\" | \"wallet\";\n merchant_name?: string;\n amount?: string;\n currency?: string;\n last4?: string;\n card_id?: string;\n expires_in_minutes?: number;\n}\n\n/** True when the item carries a card confirmation code (`CardOtpData`). */\nexport function isCardOtp(\n item: InboxItem,\n): item is InboxItem & { event_type: \"card_otp\"; data: CardOtpData } {\n return item.event_type === \"card_otp\" && typeof item.data?.otp === \"string\";\n}\n\nexport interface InboxItem {\n id: string;\n /** What happened, e.g. `deposit_confirmed`, `card_transaction`,\n * `login_new_device`, `card_otp` (see `CardOtpData`). */\n event_type: string;\n category: NotificationCategory;\n title: string;\n body: string;\n /** A path inside the client app to open on tap (`/cards/<id>`,\n * `/deposits/<id>`, `/subscription`, `/settings/sessions`), or `null`. */\n href: string | null;\n /** Event details (amount, currency, card last four and so on); the keys\n * depend on `event_type`. */\n data: Record<string, unknown>;\n /** Language the item was rendered in. */\n locale: string;\n /** When the user read it, or `null` while unread. */\n read_at: string | null;\n created_at: string;\n}\n\nexport interface NotificationPage {\n /** Newest first. */\n items: InboxItem[];\n /** Pass back as `cursor` to get the next page; `null` on the last one. */\n next_cursor: string | null;\n /** Unread items across the whole inbox, not just this page. */\n unread_count: number;\n}\n\nexport interface ListNotificationsParams {\n /** `next_cursor` from the previous page. */\n cursor?: string;\n /** Page size; the server caps it. */\n limit?: number;\n /** Only items without `read_at`. */\n unreadOnly?: boolean;\n category?: NotificationCategory;\n}\n\n/** Per-category channel switches: `{ money: { push: true, email: false } }`.\n * A channel missing from a category keeps its default. */\nexport type NotificationCategoryPreferences = Partial<\n Record<NotificationCategory, Partial<Record<NotificationChannel, boolean>>>\n>;\n\nexport interface NotificationPreferences {\n /** The channel to use first; `null` means automatic (the server picks by\n * the user's devices). */\n primary_channel: NotificationChannel | null;\n categories: NotificationCategoryPreferences;\n /** `null` when unset: the server falls back to the Telegram profile's\n * language, then the deployment default. */\n locale: NotificationLocale | null;\n /** Channels this deployment can deliver on. Render toggles only for\n * these. */\n available_channels: NotificationChannel[];\n}\n\n/** Body of `setPreferences`. Every field is optional; only the given ones\n * change. `primary_channel: null` switches back to automatic. */\nexport interface NotificationPreferencesInput {\n primary_channel?: NotificationChannel | null;\n categories?: NotificationCategoryPreferences;\n locale?: NotificationLocale | null;\n}\n\nexport class NotificationsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** One page of the inbox, newest first. */\n async list(params: ListNotificationsParams = {}): Promise<NotificationPage> {\n const q = new URLSearchParams();\n if (params.cursor) q.set(\"cursor\", params.cursor);\n if (params.limit !== undefined) q.set(\"limit\", String(params.limit));\n if (params.unreadOnly) q.set(\"unread\", \"true\");\n if (params.category) q.set(\"category\", params.category);\n const qs = q.toString();\n return this.http.get<NotificationPage>(`/me/notifications${qs ? `?${qs}` : \"\"}`);\n }\n\n /** How many items are unread. Cheap; fine to poll for a badge. */\n async unreadCount(): Promise<number> {\n const { unread } = await this.http.get<{ unread: number }>(\"/me/notifications/unread-count\");\n return unread;\n }\n\n /** Mark one item read. Returns the item; calling it again is harmless. */\n async markRead(id: string): Promise<InboxItem> {\n return this.http.post<InboxItem>(`/me/notifications/${encodeURIComponent(id)}/read`);\n }\n\n /** Mark every unread item read, or only those created before `before`\n * (ISO timestamp). Returns how many changed. */\n async markAllRead(before?: string): Promise<{ marked: number }> {\n return this.http.post<{ marked: number }>(\"/me/notifications/read-all\", {\n body: before ? { before } : {},\n });\n }\n\n /** Delete one item. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/notifications/${encodeURIComponent(id)}`);\n }\n\n /** The user's channel and language settings. */\n async getPreferences(): Promise<NotificationPreferences> {\n return this.http.get<NotificationPreferences>(\"/me/notification-preferences\");\n }\n\n /** Change some settings; the rest stay. Returns the stored view.\n * 400 `validation` for an unknown category, channel or locale. */\n async setPreferences(input: NotificationPreferencesInput): Promise<NotificationPreferences> {\n return this.http.put<NotificationPreferences>(\"/me/notification-preferences\", {\n body: input,\n });\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { ClientPlatform, ResolvedClientDescriptor } from \"../client-platform.js\";\nimport { base64UrlToBytes, type PushCapableRegistration } from \"./push.js\";\n\n/**\n * Devices resource — `client.devices.*`.\n *\n * A user has many devices: each browser with a Web Push subscription, each\n * phone with an FCM / APNs token, and a marker for \"uses the Telegram Mini\n * App\". The server picks the notification channel from them: a mobile app\n * first, otherwise the device seen most recently.\n *\n * The usual browser flow, once notification permission is granted:\n *\n * ```ts\n * const reg = await navigator.serviceWorker.ready;\n * const device = await client.devices.registerWebPush(reg, { label: \"Chrome on Mac\" });\n * // later, from a settings screen:\n * await client.devices.unregisterWebPush(reg);\n * ```\n */\n\nexport type DeviceKind = \"webpush\" | \"fcm\" | \"apns\" | \"telegram_miniapp\";\n\nexport type DevicePlatform = \"pwa\" | \"web\" | \"ios\" | \"android\" | \"telegram\";\n\nexport interface Device {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** Free-form name the app gave it (\"Chrome on Mac\"), or `null`. */\n label: string | null;\n locale: string | null;\n app_version: string | null;\n created_at: string;\n last_seen_at: string;\n /** Set when the device no longer receives anything (the push endpoint is\n * gone, or someone switched it off). */\n disabled_at: string | null;\n /** `true` when it was registered from the session this client holds. */\n is_current: boolean;\n}\n\n/** `PushSubscription.toJSON()` minus the parts the server doesn't need. */\nexport interface WebPushCredential {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** FCM registration token or APNs device token. */\nexport interface MobilePushCredential {\n token: string;\n}\n\nexport type RegisterDeviceInput =\n | {\n kind: \"webpush\";\n platform: DevicePlatform;\n credential: WebPushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"fcm\" | \"apns\";\n platform: DevicePlatform;\n credential: MobilePushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"telegram_miniapp\";\n platform: DevicePlatform;\n /** Nothing to send: the device is a marker. */\n credential: Record<string, never>;\n label?: string;\n locale?: string;\n app_version?: string;\n };\n\nexport interface RegisteredDevice {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`;\n * `null` when push is not set up on this deployment. */\n vapid_public_key: string | null;\n}\n\nexport interface RegisterWebPushOptions {\n /** A name to show in the user's device list (\"Chrome on Mac\"). */\n label?: string;\n /** Skip the key lookup when you already hold the deployment's VAPID\n * public key (from an earlier `register` result, for example). */\n vapidPublicKey?: string;\n}\n\nexport interface UnregisterWebPushOptions {\n /** The device to delete, from an earlier `registerWebPush` result. When\n * omitted, every Web Push device registered from this session goes. */\n deviceId?: string;\n}\n\n/** Client platform → the platform the device list uses. */\nexport function devicePlatformOf(platform: ClientPlatform): DevicePlatform {\n return platform === \"telegram-miniapp\" ? \"telegram\" : platform;\n}\n\nexport class DevicesResource {\n constructor(\n private readonly http: HttpClient,\n private readonly client: ResolvedClientDescriptor,\n ) {}\n\n /** Every device the user has, disabled ones included. */\n async list(): Promise<Device[]> {\n return this.http.get<Device[]>(\"/me/devices\");\n }\n\n /** Register a device, or refresh it when the same credential is already\n * known (then `last_seen_at`, `label` and `app_version` update and a\n * disabled device comes back). `app_version` defaults to the client\n * version sent in `X-Takeal-Client`.\n *\n * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the\n * deployment has no VAPID keys. */\n async register(input: RegisterDeviceInput): Promise<RegisteredDevice> {\n return this.http.put<RegisteredDevice>(\"/me/devices\", {\n body: { app_version: this.client.version, ...input },\n });\n }\n\n /** Delete one device. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/devices/${encodeURIComponent(id)}`);\n }\n\n /** Subscribe this browser to Web Push and register it as a device. Ask\n * for notification permission before calling. Throws when push isn't\n * set up on the deployment. */\n async registerWebPush(\n registration: PushCapableRegistration,\n opts: RegisterWebPushOptions = {},\n ): Promise<RegisteredDevice> {\n const key = opts.vapidPublicKey ?? (await this.vapidPublicKey());\n if (!key) {\n throw new Error(\n \"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\",\n );\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.register({\n kind: \"webpush\",\n platform: devicePlatformOf(this.client.platform),\n credential: {\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n },\n ...(opts.label ? { label: opts.label } : {}),\n });\n }\n\n /** Unsubscribe this browser from Web Push and delete the matching device\n * (see {@link UnregisterWebPushOptions}). Safe when nothing is\n * registered. */\n async unregisterWebPush(\n registration: PushCapableRegistration,\n opts: UnregisterWebPushOptions = {},\n ): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n if (opts.deviceId) {\n await this.remove(opts.deviceId);\n return;\n }\n const mine = (await this.list()).filter((d) => d.kind === \"webpush\" && d.is_current);\n for (const d of mine) await this.remove(d.id);\n }\n\n private async vapidPublicKey(): Promise<string | null> {\n const { vapid_public_key } = await this.http.get<{ vapid_public_key?: string | null }>(\n \"/me/push-subscription\",\n );\n return vapid_public_key ?? null;\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * History resource — `client.history.*`: everything that happened to the\n * user's money in one list, newest first.\n *\n * ```ts\n * const page = await client.history.list({ limit: 30 });\n * const more = await client.history.list({ cursor: page.next_cursor! });\n * const oneCard = await client.history.list({ cardId: card.id });\n * for await (const item of client.history.all()) { … }\n * ```\n *\n * New kinds are added over time. Render an unknown `kind` from its `title`,\n * `amount`, `direction` and `status`; don't drop it.\n */\n\nexport type HistoryKind =\n | \"card_purchase\"\n | \"card_refund\"\n | \"card_issued\"\n | \"card_topup\"\n | \"card_transfer\"\n | \"wallet_deposit\"\n | \"deposit_refund\"\n | \"fee\"\n | \"balance_adjustment\"\n | \"bonus\"\n /**\n * What was left on a closed card moving to the card that replaced it:\n * `card` is the old card, `to_card` the new one. `pending` until the\n * issuer returns the money and it is on the new card. If the new card\n * could not take it, the money went to the wallet and `title` says so.\n */\n | \"closed_card_balance\"\n /** A fee for using the card: a payment, a declined payment, a cash withdrawal. */\n | \"card_fee\"\n /** Money that paid card fees owed. */\n | \"debt_payment\"\n // Any kind added later still type-checks.\n | (string & {});\n\nexport type HistoryStatus =\n \"completed\" | \"pending\" | \"declined\" | \"reversed\" | \"failed\" | (string & {});\n\nexport interface HistoryAmount {\n /** Decimal string, never negative; see `direction`. */\n amount: string;\n /** ISO 4217 code. */\n currency: string;\n}\n\nexport interface HistoryCard {\n id: string;\n name: string | null;\n last4: string | null;\n}\n\nexport interface HistoryItem {\n /** Unique across kinds. */\n id: string;\n kind: HistoryKind;\n occurred_at: string;\n /** `pending` is not finished yet; `reversed` is an authorisation that was released. */\n status: HistoryStatus;\n /** `out` money left the user, `in` it came in, `internal` it moved between the wallet and the user's cards. */\n direction: \"out\" | \"in\" | \"internal\" | (string & {});\n /** The merchant, or what the operation was, in the language asked for. */\n title: string;\n /**\n * In the currency the operation happened in. For `bonus` the currency is\n * `BNS` and the amount is a number of bonuses, not money.\n */\n amount: HistoryAmount;\n /**\n * The other side of a conversion (what the card was billed, what the\n * wallet or card received). For a `bonus` spend: the part of the price\n * the bonuses covered, or what they added to a top-up.\n */\n counter_amount: HistoryAmount | null;\n /** Rate between `amount` and `counter_amount`, decimal string. */\n fx_rate: string | null;\n /** A fee charged with the operation, in the wallet's currency. */\n fee: HistoryAmount | null;\n /** The card; the source card of a transfer. */\n card: HistoryCard | null;\n /** The destination card of a transfer. */\n to_card: HistoryCard | null;\n merchant: { name: string | null; city: string | null; country: string | null } | null;\n /** On a declined payment: a stable code and the reason in plain words. */\n decline_reason: {\n code:\n | \"insufficient_funds\"\n | \"limit_exceeded\"\n | \"card_blocked\"\n | \"card_expired\"\n | \"wrong_details\"\n | \"merchant_not_allowed\"\n | \"other\"\n | (string & {});\n text: string;\n } | null;\n}\n\nexport interface HistoryPage {\n items: HistoryItem[];\n /** Pass as `cursor` for the next, older page; `null` on the last one. */\n next_cursor: string | null;\n}\n\nexport interface ListHistoryParams {\n /** Only this card's operations, transfers to and from it included. */\n cardId?: string;\n cursor?: string;\n /** 1 to 100, default 30. */\n limit?: number;\n /** `en` or `ru` for titles and decline reasons. Defaults to the browser's language header. */\n lang?: \"en\" | \"ru\";\n signal?: AbortSignal;\n}\n\nexport class HistoryResource {\n constructor(private readonly http: HttpClient) {}\n\n /** One page of the history. Errors: 400 bad cursor or limit, 404 `cardId` is not the user's card. */\n async list(params: ListHistoryParams = {}): Promise<HistoryPage> {\n const q = new URLSearchParams();\n if (params.cardId) q.set(\"card_id\", params.cardId);\n if (params.cursor) q.set(\"cursor\", params.cursor);\n if (params.limit !== undefined) q.set(\"limit\", String(params.limit));\n if (params.lang) q.set(\"lang\", params.lang);\n const qs = q.toString();\n return this.http.get<HistoryPage>(`/me/history${qs ? `?${qs}` : \"\"}`, {\n signal: params.signal,\n });\n }\n\n /** Every entry, page after page, newest first. */\n async *all(params: Omit<ListHistoryParams, \"cursor\"> = {}): AsyncGenerator<HistoryItem> {\n let cursor: string | undefined;\n do {\n const page = await this.list({ ...params, cursor });\n yield* page.items;\n cursor = page.next_cursor ?? undefined;\n } while (cursor);\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport { anonymousKey, forgetAnalyticsIds } from \"./attribution.js\";\n\n/**\n * Consents resource — `client.consents.*`: what the user agreed to.\n *\n * ```ts\n * const { consents } = await client.consents.get();\n * await client.consents.set(\"marketing\", false); // advertising off everywhere\n * ```\n *\n * Consents are first given with the sign-up (`auth.register({ consents })`,\n * `auth.exchangeTelegram({ consents })`) and with a card order\n * (`cards.create({ consents })`). Each one is recorded with the version of\n * its documents in force at that moment; the client sends kinds only.\n *\n * Two of them guard what reaches a card issuer:\n *\n * - `holder_data_transfer`: the user's real personal details go to the card\n * issuer. A product with `holder_data_required` is issued only while it\n * stands; show the consent screen before the order and send the kind in\n * the order's `consents` (or give it with {@link ConsentsResource.allowHolderData}).\n * Without it the order fails with 409 `holder_data_consent_required`.\n * - `dispute_documents_transfer`: the user's documents go to the card issuer\n * when a payment is disputed. Nothing is sent without it; give it with\n * {@link ConsentsResource.allowDisputeDocuments}, naming the disputed card.\n */\n\n/** The user's real personal details go to the card issuer. */\nexport const HOLDER_DATA_CONSENT = \"holder_data_transfer\";\n/** The user's documents go to the card issuer in a dispute. */\nexport const DISPUTE_DOCUMENTS_CONSENT = \"dispute_documents_transfer\";\n\n/** `terms` covers the offer, the tariffs and the privacy policy together. */\nexport type ConsentKind =\n | \"terms\"\n | \"personal_data\"\n | \"marketing\"\n | \"cookies_analytics\"\n | typeof HOLDER_DATA_CONSENT\n | typeof DISPUTE_DOCUMENTS_CONSENT\n // Kinds added later still type-check.\n | (string & {});\n\n/** Where a consent was given. Read from the client header when omitted. */\nexport type ConsentChannel = \"site\" | \"cabinet\" | \"miniapp\" | \"bot\";\n\n/** A document a consent refers to, at the version the user accepted. */\nexport interface ConsentDocument {\n slug: string;\n version: number;\n}\n\nexport interface ConsentState {\n kind: ConsentKind;\n /** Given and not withdrawn since. */\n given: boolean;\n /** When it was last given; `null` if never. */\n given_at: string | null;\n /** When it was withdrawn after that; `null` while it stands. */\n withdrawn_at: string | null;\n /** The documents it referred to when last given. */\n documents: ConsentDocument[];\n /** Can be withdrawn with {@link ConsentsResource.set}. The required ones\n * (`terms`, `personal_data`) can't: closing the account withdraws them. */\n optional: boolean;\n}\n\nexport interface Consents {\n consents: ConsentState[];\n}\n\n/** Where and for what a consent is given with {@link ConsentsResource.set}. */\nexport interface ConsentOptions {\n /** Where it was given. Read from the client header when omitted. */\n channel?: ConsentChannel;\n /**\n * One of the user's cards, for `holder_data_transfer` and\n * `dispute_documents_transfer` only: the card the consent is given for,\n * such as the card a dispute is about. Sent as `card_id` and kept with the\n * consent; a consent given for a card is recorded every time, even when\n * one already stands.\n */\n cardId?: string;\n}\n\nexport interface CookieChoiceInput {\n /** `true`: analytics cookies allowed; `false`: declined. */\n analytics: boolean;\n /** The visitor's anonymous key. Defaults to the one `anonymousKey()`\n * keeps (the key visits are sent with); ignored for a signed-in user. */\n anonymousKey?: string;\n /** Where the choice was made. Read from the client header when omitted. */\n channel?: ConsentChannel;\n}\n\nexport class ConsentsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Where each consent stands. */\n async get(): Promise<Consents> {\n return this.http.get<Consents>(\"/me/consents\");\n }\n\n /** Whether `kind` stands now: given and not withdrawn since. */\n async stands(kind: ConsentKind): Promise<boolean> {\n const { consents } = await this.get();\n return consents.some((c) => c.kind === kind && c.given);\n }\n\n /**\n * Give (`true`) or withdraw (`false`) an optional consent: `marketing`,\n * `cookies_analytics`, `holder_data_transfer` or\n * `dispute_documents_transfer`. Withdrawing `marketing` turns advertising\n * off in every channel at once; giving it turns on advertising by e-mail.\n * Withdrawing `holder_data_transfer` leaves the user's cards alone and\n * stops new cards whose product has `holder_data_required`. A call that\n * changes nothing records nothing, unless it names a card.\n *\n * The third argument is the channel, or {@link ConsentOptions} with the\n * channel and the card.\n *\n * Errors: 400 `consent_required` for `terms` or `personal_data`,\n * 400 `unknown_consent`, 400 `card_not_allowed` (a card named with a kind\n * that takes none), 404 `not_found` (not one of the user's cards).\n */\n async set(\n kind: ConsentKind,\n given: boolean,\n options?: ConsentChannel | ConsentOptions,\n ): Promise<Consents> {\n const opts: ConsentOptions =\n typeof options === \"string\" ? { channel: options } : (options ?? {});\n const body: { kind: ConsentKind; given: boolean; channel?: ConsentChannel; card_id?: string } =\n { kind, given };\n if (opts.channel !== undefined) body.channel = opts.channel;\n if (opts.cardId !== undefined) body.card_id = opts.cardId;\n return this.http.post<Consents>(\"/me/consents\", { body });\n }\n\n /**\n * The user agreed on the consent screen that their real personal details\n * go to the card issuer (`holder_data_transfer`). Needed before ordering a\n * product with `holder_data_required`, unless the order itself carries the\n * kind in its `consents`.\n */\n async allowHolderData(options?: ConsentOptions): Promise<Consents> {\n return this.set(HOLDER_DATA_CONSENT, true, options);\n }\n\n /**\n * The user agreed that their documents go to the card issuer for a\n * dispute (`dispute_documents_transfer`). Name the disputed card with\n * `cardId`; each call is then recorded on its own.\n */\n async allowDisputeDocuments(options?: ConsentOptions): Promise<Consents> {\n return this.set(DISPUTE_DOCUMENTS_CONSENT, true, options);\n }\n\n /**\n * Record what the cookie banner or the cookie settings say about\n * analytics. Works signed in or not: before sign-in the choice is kept\n * under the anonymous key and moves to the account at sign-up (send the\n * same key in `register({ attribution })`). Declining deletes the\n * visitor's recorded visits and analytics ids and stops their conversions\n * going to Metrica. Call it on every change, not on every page load; the\n * same answer twice records nothing (`recorded: false`).\n *\n * Errors: 400 `invalid_anonymous_key` when not signed in and no key could\n * be found.\n */\n async setCookies(input: CookieChoiceInput): Promise<{ recorded: boolean }> {\n const body: { analytics: boolean; anonymous_key?: string; channel?: ConsentChannel } = {\n analytics: input.analytics,\n };\n const key = input.anonymousKey ?? anonymousKey();\n if (key !== undefined) body.anonymous_key = key;\n if (input.channel !== undefined) body.channel = input.channel;\n if (!input.analytics) forgetAnalyticsIds();\n return this.http.post<{ recorded: boolean }>(\"/consents/cookies\", { body });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Receipts resource — `client.receipts.*`: one numbered receipt for every\n * payment: a wallet top-up, a card top-up and a card's issue price.\n *\n * ```ts\n * const all = await client.receipts.list();\n * const [forDeposit] = await client.receipts.list({ refId: deposit.id });\n * const one = await client.receipts.get(id);\n * ```\n *\n * A receipt appears within a minute of the payment going through and is\n * mailed to the user at the same time. The rate on it is the one the money\n * was credited at; the platform's margin is not shown.\n */\n\nexport type ReceiptKind = \"wallet_deposit\" | \"card_topup\" | \"card_issue\" | (string & {});\n\nexport interface Receipt {\n id: string;\n /** Shown as `R-000123`. */\n number: string;\n kind: ReceiptKind;\n /** The deposit, card top-up or card the payment was for. */\n ref_id: string;\n paid_at: string;\n /** Decimal string. */\n paid_amount: string;\n paid_currency: string;\n /** `card`, `sbp`, `crypto`, `bank_transfer` or `wallet`. */\n method: string;\n credited_amount: string | null;\n credited_currency: string | null;\n /** What one unit of `credited_currency` cost in `paid_currency`; only when they differ. */\n rate: string | null;\n card_id: string | null;\n card_last4: string | null;\n}\n\nexport interface ListReceiptsParams {\n /** Only the receipt of this deposit, card top-up or card. */\n refId?: string;\n /** Newest first; default 50, at most 200. */\n limit?: number;\n}\n\nexport class ReceiptsResource {\n constructor(private readonly http: HttpClient) {}\n\n async list(params: ListReceiptsParams = {}): Promise<Receipt[]> {\n const q = new URLSearchParams();\n if (params.refId !== undefined) q.set(\"ref_id\", params.refId);\n if (params.limit !== undefined) q.set(\"limit\", String(params.limit));\n const qs = q.toString();\n return this.http.get<Receipt[]>(`/me/receipts${qs ? `?${qs}` : \"\"}`);\n }\n\n async get(id: string): Promise<Receipt> {\n return this.http.get<Receipt>(`/me/receipts/${encodeURIComponent(id)}`);\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Support resource — `client.support.*`: the chat with support.\n *\n * GET /me/support/messages → list\n * POST /me/support/messages → send\n * GET /me/support/attachments/{id} → attachment\n * POST /me/support/ratings/{id} → rate\n *\n * What the person writes shows in the conversation at once, with the status\n * `queued`, and goes to support right after (`delivered`). Support answers\n * come back in the same conversation, with the text ready as cleaned HTML in\n * `html`: show it as it is, it carries only paragraphs, line breaks, bold,\n * italic, strikethrough, code, links, lists and quotes. A new answer also\n * comes as a `support_reply` notification.\n *\n * The person may write from the Telegram bot too; it is one conversation,\n * and `channel` says where each message came from. A message written in\n * Telegram keeps its formatting: `html` has it, `text` the plain words.\n * An answer sent to the person's Telegram is `queued` until all of it got\n * there, and `failed` if it could not get there.\n */\n\n/** Where a message came from, or where an answer was sent. */\nexport type SupportChannel = \"cabinet\" | \"telegram\" | (string & {});\n\n/** How far a message got: `queued` until support has it (for an answer\n * sent to Telegram, until the person has it). */\nexport type SupportMessageStatus = \"queued\" | \"delivered\" | \"failed\" | (string & {});\n\n/** The conversation's state: `none` until the person writes for the first\n * time, `resolved` once support closed it. Writing again reopens it. */\nexport type SupportConversationStatus = \"none\" | \"open\" | \"resolved\" | (string & {});\n\n/** A file in the conversation. Download it with `attachment(id)`. */\nexport interface SupportAttachment {\n id: string;\n file_name: string;\n content_type: string;\n /** Bytes. */\n size: number;\n}\n\n/** One message. */\nexport interface SupportMessage {\n id: string;\n /** `user` for what the person wrote, `support` for an answer. */\n author: \"user\" | \"support\" | (string & {});\n /** The name the support agent goes by; answers only. */\n operator_name: string | null;\n channel: SupportChannel | null;\n /** What the person wrote, plain text. Empty on answers. */\n text: string;\n /** The answer as cleaned HTML. On the person's own messages it is set\n * only for those written in Telegram, which keep their formatting. */\n html: string;\n attachments: SupportAttachment[];\n status: SupportMessageStatus;\n created_at: string;\n}\n\n/** Support closed the conversation and asks how it went. */\nexport interface SupportRatingRequest {\n id: string;\n asked_at: string;\n}\n\n/** A page of the conversation, oldest first. */\nexport interface SupportConversation {\n status: SupportConversationStatus;\n items: SupportMessage[];\n /** Older messages exist: `list({ before: items[0].created_at })`. */\n has_more: boolean;\n /** Show a 1–5 rating when set; answer with `rate()`. `null` otherwise. */\n rating_request: SupportRatingRequest | null;\n}\n\n/** A file to send. `data` may be a `Blob` (a `File` from an input), bytes,\n * or base64 already. */\nexport interface SupportFile {\n fileName: string;\n /** E.g. `image/png`. Pictures and PDF up to 20 MB by default; the platform\n * sets the list and the size. */\n contentType: string;\n data: Blob | ArrayBuffer | Uint8Array | string;\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunk));\n }\n return btoa(binary);\n}\n\nasync function toBase64(data: SupportFile[\"data\"]): Promise<string> {\n if (typeof data === \"string\") return data;\n if (data instanceof Uint8Array) return bytesToBase64(data);\n if (data instanceof ArrayBuffer) return bytesToBase64(new Uint8Array(data));\n return bytesToBase64(new Uint8Array(await data.arrayBuffer()));\n}\n\nexport class SupportResource {\n constructor(private readonly http: HttpClient) {}\n\n /** The latest messages, oldest first, and the conversation's status.\n * `before` reads further back; `limit` is 1 to 100 (50). */\n async list(\n opts: { before?: string; limit?: number; signal?: AbortSignal } = {},\n ): Promise<SupportConversation> {\n const q = new URLSearchParams();\n if (opts.before) q.set(\"before\", opts.before);\n if (opts.limit !== undefined) q.set(\"limit\", String(opts.limit));\n const qs = q.toString();\n return this.http.get<SupportConversation>(`/me/support/messages${qs ? `?${qs}` : \"\"}`, {\n signal: opts.signal,\n });\n }\n\n /** Write to support. Text, files or both; up to 10 files. */\n async send(\n message: { text?: string; files?: SupportFile[] },\n opts: { signal?: AbortSignal } = {},\n ): Promise<SupportMessage> {\n const attachments = await Promise.all(\n (message.files ?? []).map(async (f) => ({\n file_name: f.fileName,\n content_type: f.contentType,\n data_base64: await toBase64(f.data),\n })),\n );\n return this.http.post<SupportMessage>(\"/me/support/messages\", {\n body: { text: message.text ?? \"\", attachments },\n signal: opts.signal,\n });\n }\n\n /** A file from the conversation: the person's own or one support sent. */\n async attachment(id: string, opts: { signal?: AbortSignal } = {}): Promise<Blob> {\n return this.http.getBlob(`/me/support/attachments/${encodeURIComponent(id)}`, {\n signal: opts.signal,\n });\n }\n\n /** Answer `rating_request`: 1 (bad) to 5 (great), a comment if the person\n * wrote one. Each question takes one answer; a second one is a 404. */\n async rate(\n id: string,\n answer: { rating: 1 | 2 | 3 | 4 | 5; comment?: string },\n opts: { signal?: AbortSignal } = {},\n ): Promise<void> {\n await this.http.post<void>(`/me/support/ratings/${encodeURIComponent(id)}`, {\n body: { rating: answer.rating, ...(answer.comment ? { comment: answer.comment } : {}) },\n signal: opts.signal,\n });\n }\n\n /** Just the conversation's status. */\n async status(opts: { signal?: AbortSignal } = {}): Promise<SupportConversationStatus> {\n return (await this.list({ limit: 1, signal: opts.signal })).status;\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { DepositMethod, FeeKind } from \"./deposits.js\";\n\n/**\n * Funding options resource — `client.fundingOptions.*`.\n *\n * The ways the user can top up on this deployment: each funding connector,\n * where its top-ups may land and which payment methods it takes. Build the\n * top-up screen from this list instead of fixed connector names: a\n * deployment may top up the wallet only, cards only (no wallet at all), or\n * let the user choose.\n *\n * Mirrors `GET /me/funding-options`.\n */\n\n/**\n * Where a funding connector's top-ups may land: `wallet` (the wallet\n * only), `spool` (straight onto cards only) or `mixed` (either).\n */\nexport type FunderMode = \"wallet\" | \"spool\" | \"mixed\";\n\n/** Where one top-up goes: the wallet, or one of the user's cards. */\nexport type DepositTarget = \"wallet\" | \"card\";\n\n/**\n * What one way of paying through a funding connector costs and allows.\n * Draw the top-up form from it: the currency to ask for, the fee to show\n * (or not, for a markup), the floor, the cap and the day's limit.\n */\nexport interface MethodTerms {\n method: DepositMethod;\n /** ISO 4217 code the user pays in this way; `null` when any the quote accepts. */\n source_currency: string | null;\n fee_kind: FeeKind;\n /** The fee in basis points (2000 = 20 %). */\n fee_bps: number;\n /** How long a quote through this method stays executable, and the deposit waits for its payment. */\n quote_ttl_seconds: number;\n /** Smallest single top-up in the source currency; `null` for no floor. */\n min_amount: string | null;\n /** Largest single top-up in the source currency; `null` for no cap. */\n max_amount: string | null;\n /** What one user may top up this way over 24 hours; `null` for no limit. */\n daily_limit_per_user: string | null;\n}\n\n/** One way to top up. */\nexport interface FundingOption {\n /** Pass it as `funder_slug` to `deposits.initiate`. */\n slug: string;\n mode: FunderMode;\n /** Where a top-up through it may land. */\n targets: DepositTarget[];\n /** Payment methods it takes. */\n methods: DepositMethod[];\n /**\n * Whether a new card can be issued with a top-up through it\n * (`issue_card` on `deposits.initiate`).\n */\n issue_card: boolean;\n /** The terms of each method in `methods`. */\n method_terms: MethodTerms[];\n}\n\nexport class FundingOptionsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** The ways to top up, preferred first. Empty when none is configured. */\n async list(): Promise<FundingOption[]> {\n return this.http.get<FundingOption[]>(\"/me/funding-options\");\n }\n}\n","/**\n * The SDK's own version, sent as the default `X-Takeal-Client` version.\n *\n * Kept as a plain constant so every entry point (ESM, CJS, the\n * sub-exports) reads the same value without a JSON import or a bundler\n * `define`. `src/version.test.ts` checks it matches `package.json`, so a\n * release bump that forgets this file fails the test run.\n */\nexport const SDK_VERSION = \"0.9.0\";\n","import { SDK_VERSION } from \"./version.js\";\n\n/**\n * Which kind of app is talking to the API. Sent on every request as\n * `X-Takeal-Client: <platform>; <version>`. The server keeps it on the\n * session: it decides whether a sign-in counts as a new device, and which\n * channel a notification goes out on (a Mini App gets Telegram messages, a\n * PWA gets Web Push, and so on).\n */\nexport type ClientPlatform = \"pwa\" | \"web\" | \"telegram-miniapp\" | \"ios\" | \"android\";\n\n/** The `client` option of `createClient`. */\nexport interface ClientDescriptor {\n /** What the app is. Detected at runtime when omitted; see\n * {@link detectClientPlatform}. */\n platform: ClientPlatform;\n /** The app's own version. Defaults to the SDK version. */\n version?: string;\n}\n\n/** A descriptor with every field filled in. `client.client` on a\n * {@link CusfrontClient} has this shape. */\nexport interface ResolvedClientDescriptor {\n platform: ClientPlatform;\n version: string;\n}\n\n/** Header name carrying the client descriptor. */\nexport const CLIENT_HEADER = \"X-Takeal-Client\";\n\n/**\n * Best-effort platform detection for browser runtimes:\n *\n * - `telegram-miniapp` when `window.Telegram.WebApp.initData` is non-empty\n * (the app was launched from Telegram);\n * - `pwa` when the page runs installed: iOS Safari's `navigator.standalone`\n * or a `display-mode: standalone` media query;\n * - `web` otherwise, and always outside a browser (Node, workers without a\n * `navigator`).\n *\n * Native wrappers (Capacitor, React Native) should pass `ios` / `android`\n * explicitly; there is no reliable way to tell them apart from a browser.\n */\nexport function detectClientPlatform(): ClientPlatform {\n const g = globalThis as unknown as {\n Telegram?: { WebApp?: { initData?: unknown } };\n navigator?: { standalone?: unknown };\n matchMedia?: (query: string) => { matches: boolean };\n };\n const initData = g.Telegram?.WebApp?.initData;\n if (typeof initData === \"string\" && initData.length > 0) return \"telegram-miniapp\";\n\n if (g.navigator?.standalone === true) return \"pwa\";\n if (typeof g.matchMedia === \"function\") {\n try {\n if (g.matchMedia(\"(display-mode: standalone)\").matches) return \"pwa\";\n } catch {\n // Some non-browser runtimes stub matchMedia and throw; treat as web.\n }\n }\n return \"web\";\n}\n\n/** Fill in the blanks of a `client` option. */\nexport function resolveClientDescriptor(\n given: ClientDescriptor | undefined,\n): ResolvedClientDescriptor {\n return {\n platform: given?.platform ?? detectClientPlatform(),\n version: given?.version || SDK_VERSION,\n };\n}\n\n/** `{ platform: \"pwa\", version: \"0.3.0\" }` → `\"pwa; 0.3.0\"`. */\nexport function clientHeaderValue(desc: ResolvedClientDescriptor): string {\n return `${desc.platform}; ${desc.version}`;\n}\n","/**\n * Pluggable storage for the JWT.\n *\n * Default behaviour by environment:\n * - browser → `localStorage` (synchronous, persists across reloads)\n * - Node / SSR / worker → in-memory (no global state to leak)\n * - mobile (Capacitor / RN) → consumer must inject Keychain /\n * EncryptedSharedPreferences via `createClient({ tokenStore })`\n *\n * The store is intentionally tiny — three methods, no eviction\n * policy, no encryption. Encryption is the consumer's call (mobile\n * adapters wrap platform-native secure storage). Persistence shape\n * is opaque to the SDK; tokens are passed through verbatim.\n */\nexport interface TokenStore {\n get(): string | null | Promise<string | null>;\n set(token: string): void | Promise<void>;\n clear(): void | Promise<void>;\n}\n\n/** Sync `localStorage`-backed store. Falls through to in-memory when\n * `window.localStorage` is unavailable (private mode quota, SSR). */\nexport function defaultBrowserStore(key = \"takeal_jwt\"): TokenStore {\n const fallback = inMemoryStore();\n // Probe once at construction — avoid the try/catch on every call.\n let usable = false;\n try {\n if (typeof globalThis !== \"undefined\" && \"localStorage\" in globalThis) {\n const ls = (globalThis as { localStorage: Storage }).localStorage;\n const probe = \"__takeal_probe__\";\n ls.setItem(probe, \"1\");\n ls.removeItem(probe);\n usable = true;\n }\n } catch {\n usable = false;\n }\n if (!usable) return fallback;\n const ls = (globalThis as { localStorage: Storage }).localStorage;\n return {\n get: () => ls.getItem(key),\n set: (token) => ls.setItem(key, token),\n clear: () => ls.removeItem(key),\n };\n}\n\n/** In-memory store. Use for SSR / tests / when persistence isn't\n * desired (e.g. ephemeral kiosk sessions). */\nexport function inMemoryStore(): TokenStore {\n let value: string | null = null;\n return {\n get: () => value,\n set: (token) => {\n value = token;\n },\n clear: () => {\n value = null;\n },\n };\n}\n","/**\n * Resolve an image URL the API hands back (`design.image_url`, a logo, …)\n * into something a browser can load.\n *\n * The API returns either an absolute URL (uploaded artwork served from\n * object storage) or a path relative to the API origin (the deployment's\n * default card design, `/card-designs/default.svg`). Absolute URLs — and\n * `data:` / `blob:` URIs — come back unchanged; a relative path is joined\n * onto `baseUrl`, which is the bare API origin the client was built with.\n * These paths are host-level, so no `/v1` prefix is added.\n *\n * `baseUrl` is the same value passed to `createClient`; a trailing slash is\n * tolerated. `client.assetUrl()` calls this with the client's own base.\n */\nexport function resolveAssetUrl(baseUrl: string, url: string): string {\n if (isAbsolute(url)) return url;\n const base = baseUrl.replace(/\\/+$/, \"\");\n const path = url.startsWith(\"/\") ? url : `/${url}`;\n return `${base}${path}`;\n}\n\n/** `https://…`, `http://…`, protocol-relative `//…`, `data:` and `blob:` all count as absolute. */\nfunction isAbsolute(url: string): boolean {\n return /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(url);\n}\n","import { isApiError } from \"./error.js\";\nimport type { HttpClient } from \"./http.js\";\n\n/**\n * Which platform versions this SDK works with, as a semver range:\n * comparators separated by \", \". Keep this the only definition.\n */\nexport const SUPPORTED_MEISTER = \">=0.8.0, <1.0.0\";\n\n/** What `client.ready()` returns. */\nexport interface ReadyInfo {\n /** `true` when the platform reported a version inside `supportedMeister`. */\n compatible: boolean;\n /** The platform version the deployment reported, or `null` when it didn't. */\n platformVersion: string | null;\n /** The range this SDK supports (`SUPPORTED_MEISTER`). */\n supportedMeister: string;\n /** Why `compatible` is false, in one English sentence for logs or a banner. */\n warning?: string;\n /** `true` when every platform dependency answered (HTTP 200), `false` on 503. */\n healthy: boolean;\n /** `ready` or `degraded`, as the platform reports it. */\n status: string;\n /** The raw `GET /ready` body, for fields this type doesn't name. */\n raw: ReadyBody;\n}\n\n/** The part of the `GET /ready` body the SDK reads. */\nexport interface ReadyBody {\n status?: string;\n ops?: {\n /** Build version of the API process. */\n version?: string;\n /** The platform version. Missing on platforms before 0.5.0. */\n platform_version?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\ntype Parsed = { core: [number, number, number]; pre: string | null };\n\nconst SEMVER =\n /^v?(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/;\n\nfunction parse(v: string): Parsed | null {\n const m = SEMVER.exec(v.trim());\n if (!m) return null;\n return { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ?? null };\n}\n\nfunction cmpCore(a: Parsed, b: Parsed): number {\n for (let i = 0; i < 3; i++) {\n if (a.core[i] !== b.core[i]) return a.core[i]! < b.core[i]! ? -1 : 1;\n }\n return 0;\n}\n\n/**\n * `satisfies(\"0.5.3\", \">=0.5.0, <0.6.0\")` → `true`.\n *\n * The range is comma-separated comparators (`>=`, `>`, `<=`, `<`, `=`) or a\n * bare version meaning exactly that version; all must hold. A prerelease\n * (`0.5.1-rc.1`) never satisfies a range unless a comparator names it\n * exactly. Anything unparseable gives `false`.\n */\nexport function satisfies(version: string, range: string): boolean {\n const v = parse(version);\n if (!v) return false;\n const parts = range\n .split(\",\")\n .map((p) => p.trim())\n .filter(Boolean);\n if (parts.length === 0) return false;\n\n let exactPre = false;\n for (const part of parts) {\n const m = /^(>=|<=|>|<|=)?\\s*(.+)$/.exec(part);\n if (!m) return false;\n const op = m[1] ?? \"=\";\n const target = parse(m[2]!);\n if (!target) return false;\n\n const c = cmpCore(v, target);\n if (op === \"=\") {\n if (c !== 0 || v.pre !== target.pre) return false;\n if (v.pre !== null) exactPre = true;\n continue;\n }\n const ok = op === \">=\" ? c >= 0 : op === \">\" ? c > 0 : op === \"<=\" ? c <= 0 : c < 0;\n if (!ok) return false;\n }\n return v.pre === null || exactPre;\n}\n\n/** Judge a `GET /ready` body against `SUPPORTED_MEISTER`. */\nexport function readyInfo(raw: ReadyBody, healthy: boolean): ReadyInfo {\n const reported = raw?.ops?.platform_version;\n const platformVersion = typeof reported === \"string\" && reported ? reported : null;\n const base = {\n platformVersion,\n supportedMeister: SUPPORTED_MEISTER,\n healthy,\n status: typeof raw?.status === \"string\" ? raw.status : healthy ? \"ready\" : \"degraded\",\n raw,\n };\n if (platformVersion === null) {\n return {\n ...base,\n compatible: false,\n warning: `The platform didn't report its version; this SDK supports ${SUPPORTED_MEISTER}.`,\n };\n }\n if (!satisfies(platformVersion, SUPPORTED_MEISTER)) {\n return {\n ...base,\n compatible: false,\n warning: `This SDK supports platform ${SUPPORTED_MEISTER}, the platform runs ${platformVersion}. Some calls may fail until the SDK is updated.`,\n };\n }\n return { ...base, compatible: true };\n}\n\n/**\n * A body the platform's own `/ready` wrote: always a `status` and a `checks`\n * or `ops` block. The edge proxy's \"temporarily unavailable\" answer\n * (`{\"code\":\"service_unavailable\",…}`, also a 503) is not one.\n */\nfunction isReadyBody(body: unknown): body is ReadyBody {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) return false;\n const b = body as Record<string, unknown>;\n const block = (v: unknown) => typeof v === \"object\" && v !== null;\n return (\n b.code !== \"service_unavailable\" &&\n typeof b.status === \"string\" &&\n (block(b.checks) || block(b.ops))\n );\n}\n\n/**\n * `GET /ready` (public, unversioned). A 503 from the platform still carries\n * its body, so a degraded platform answers with `healthy: false` instead of\n * throwing. A 503 from the edge proxy while the platform is down throws, as\n * network failures and other statuses do; its `retryAfterSeconds` says when\n * to look again.\n */\nexport async function fetchReady(\n http: HttpClient,\n opts: { signal?: AbortSignal } = {},\n): Promise<ReadyInfo> {\n try {\n const body = await http.get<ReadyBody>(\"/ready\", { skipAuth: true, signal: opts.signal });\n return readyInfo(body ?? {}, true);\n } catch (e) {\n if (isApiError(e) && e.status === 503 && isReadyBody(e.body)) {\n return readyInfo(e.body, false);\n }\n throw e;\n }\n}\n","/**\n * `@takeal/cusfront-sdk` — typed client for the Takeal end-user API.\n *\n * Entry point: `createClient({ baseUrl, brand?, client?, tokenStore?, fetch? })`.\n * Resources are accessed off the returned client (`client.auth.login`,\n * `client.cards.list`, …). Sub-exports under `@takeal/cusfront-sdk/<resource>`\n * publish each resource independently so a Cusfront only pulls what\n * it imports.\n *\n * Brand-neutral by design. No customer / deployment names embedded.\n * Brand swap happens at runtime via `BrandConfig`.\n */\n\nimport { HttpClient, type FetchLike } from \"./http.js\";\nimport { AuthResource } from \"./resources/auth.js\";\nimport { DepositsResource } from \"./resources/deposits.js\";\nimport { CardsResource } from \"./resources/cards.js\";\nexport { revealState, priceChangedQuote } from \"./resources/cards.js\";\nimport { BalanceResource } from \"./resources/balance.js\";\nimport { BonusResource } from \"./resources/bonus.js\";\nimport { DebtResource } from \"./resources/debt.js\";\nimport { CloseRequestsResource } from \"./resources/close-requests.js\";\nimport { ClaimsResource } from \"./resources/claims.js\";\nimport { CodesResource } from \"./resources/codes.js\";\nimport { ReferralResource } from \"./resources/referral.js\";\nimport { SubscriptionResource } from \"./resources/subscription.js\";\nimport { BrandingResource } from \"./resources/branding.js\";\nimport { WalletResource } from \"./resources/wallet.js\";\nimport { BlogResource } from \"./resources/blog.js\";\nimport { DocumentsResource } from \"./resources/documents.js\";\nimport { SubscriptionsResource } from \"./resources/subscriptions.js\";\nimport { SessionsResource } from \"./resources/sessions.js\";\nimport { PushResource } from \"./resources/push.js\";\nimport { MeResource } from \"./resources/me.js\";\nimport { NotificationsResource } from \"./resources/notifications.js\";\nimport { DevicesResource } from \"./resources/devices.js\";\nimport { AttributionResource } from \"./resources/attribution.js\";\nimport { HistoryResource } from \"./resources/history.js\";\nimport { ConsentsResource } from \"./resources/consents.js\";\nimport { ReceiptsResource } from \"./resources/receipts.js\";\nimport { SupportResource } from \"./resources/support.js\";\nimport { FundingOptionsResource } from \"./resources/funding-options.js\";\nimport {\n CLIENT_HEADER,\n clientHeaderValue,\n resolveClientDescriptor,\n type ClientDescriptor,\n type ResolvedClientDescriptor,\n} from \"./client-platform.js\";\nimport { defaultBrowserStore, inMemoryStore, type TokenStore } from \"./token-store.js\";\nimport type { BrandConfig } from \"./brand.js\";\nimport { resolveAssetUrl } from \"./assets.js\";\nimport { fetchReady, type ReadyInfo } from \"./compat.js\";\n\nexport type { BrandConfig } from \"./brand.js\";\nexport { resolveAssetUrl } from \"./assets.js\";\nexport { ApiError, NetworkError, isApiError, isNetworkError } from \"./error.js\";\nexport { defaultBrowserStore, inMemoryStore, type TokenStore } from \"./token-store.js\";\nexport { SDK_VERSION } from \"./version.js\";\nexport { SUPPORTED_MEISTER, satisfies } from \"./compat.js\";\nexport type { ReadyInfo, ReadyBody } from \"./compat.js\";\nexport {\n CLIENT_HEADER,\n detectClientPlatform,\n type ClientDescriptor,\n type ClientPlatform,\n type ResolvedClientDescriptor,\n} from \"./client-platform.js\";\n\n// Re-export resource types so consumers can `import { Deposit } from\n// \"@takeal/cusfront-sdk\"` without reaching into sub-paths.\nexport type { Address, CustomerInfo } from \"./types/customer.js\";\nexport type {\n Deposit,\n DepositStatus,\n DepositMethod,\n InitiateDepositInput,\n CreateDepositRefundInput,\n Refund,\n CreateQuoteInput,\n FundingQuote,\n CardLoadStatus,\n IssueCardInput,\n FeeKind,\n} from \"./resources/deposits.js\";\nexport type {\n DepositTarget,\n FunderMode,\n FundingOption,\n MethodTerms,\n} from \"./resources/funding-options.js\";\nexport type {\n Card,\n CardType,\n CardStatus,\n CardStatusSource,\n CardForm,\n CloseBlockedReason,\n CardDesignRef,\n CardProduct,\n CardProductPrice,\n CreateCardInput,\n UpdateCardInput,\n CardBalance,\n TopUpTerms,\n TopUpInput,\n CardTopUp,\n CardTopUpStatus,\n TopUpResult,\n RevealCardInput,\n RevealedCard,\n RevealState,\n BillingAddress,\n Cardholder,\n SetPinInput,\n TransferInput,\n CardTransfer,\n TransferResult,\n IssuanceBonus,\n CardInTransit,\n CardOrderInput,\n CardOrder,\n CardOrderError,\n CardOrderQuoteInput,\n CardOrderQuote,\n CardOrderRate,\n PromoCodeQuote,\n PromoCodeStatus,\n CardTariff,\n} from \"./resources/cards.js\";\nexport type { Debt, DebtAmount, DebtLine, CardFeeKind } from \"./resources/debt.js\";\nexport type {\n CloseAmount,\n CloseRefund,\n CloseRequest,\n CloseRequestError,\n CloseRequestStatus,\n PayoutDetailsInput,\n PayoutDetailsShown,\n} from \"./resources/close-requests.js\";\nexport type {\n Claim,\n ClaimError,\n ClaimKind,\n ClaimPage,\n ClaimStatus,\n ClaimTransaction,\n CreateClaimInput,\n} from \"./resources/claims.js\";\nexport type { Balance } from \"./resources/balance.js\";\nexport type {\n BonusLot,\n BonusMovement,\n BonusPreview,\n BonusPreviewInput,\n BonusPurpose,\n BonusTarget,\n BonusWallet,\n} from \"./resources/bonus.js\";\nexport type {\n CodeCheck,\n CodeDiscount,\n CodeEffect,\n CodeEffectOutcome,\n CodeOperation,\n CodeRejection,\n CodeResult,\n ValidateCodeInput,\n} from \"./resources/codes.js\";\nexport type { InvitedFriend, Referral, ReferralReward } from \"./resources/referral.js\";\nexport type { UserSubscription, CancelledSubscription } from \"./resources/subscription.js\";\nexport type { Branding } from \"./resources/branding.js\";\nexport type { Wallet } from \"./resources/wallet.js\";\nexport type { BlogPost, BlogBlock, BlogList, BlogListInput } from \"./resources/blog.js\";\nexport type {\n Document,\n DocumentBlock,\n DocumentCategory,\n DocumentScope,\n DocumentPathStep,\n DocumentList,\n DocumentListInput,\n DocumentFolder,\n DocumentTree,\n DocumentTreeEntry,\n DocumentVersionSummary,\n DocumentTag,\n} from \"./resources/documents.js\";\nexport type { Subscriptions, BroadcastChannel } from \"./resources/subscriptions.js\";\nexport type {\n User,\n LoginInput,\n LoginResponse,\n JwtIssued,\n TotpRequired,\n TotpSetupEmailRequired,\n TotpSetupEmailErrorCode,\n TotpSetupEmailInput,\n TotpSetupRequired,\n OtpSentResponse,\n RegisterInput,\n Session,\n TotpSetupComplete,\n ChangePasswordInput,\n PasswordSetupRequested,\n ConfirmPasswordSetupInput,\n TelegramLink,\n TelegramUnknown,\n ExchangeTelegramInput,\n LinkTelegramInput,\n EmailChangeRequested,\n RequestEmailCodeInput,\n EmailCodeSent,\n VerifyEmailCodeInput,\n EmailCodeSession,\n} from \"./resources/auth.js\";\nexport type { MeResource } from \"./resources/me.js\";\nexport type {\n HistoryKind,\n HistoryStatus,\n HistoryAmount,\n HistoryCard,\n HistoryItem,\n HistoryPage,\n ListHistoryParams,\n} from \"./resources/history.js\";\nexport type {\n ConsentKind,\n ConsentChannel,\n ConsentDocument,\n ConsentOptions,\n ConsentState,\n Consents,\n ConsentsResource,\n CookieChoiceInput,\n} from \"./resources/consents.js\";\nexport { HOLDER_DATA_CONSENT, DISPUTE_DOCUMENTS_CONSENT } from \"./resources/consents.js\";\nexport type {\n Receipt,\n ReceiptKind,\n ReceiptsResource,\n ListReceiptsParams,\n} from \"./resources/receipts.js\";\nexport type {\n SupportAttachment,\n SupportChannel,\n SupportConversation,\n SupportConversationStatus,\n SupportFile,\n SupportMessage,\n SupportMessageStatus,\n SupportRatingRequest,\n SupportResource,\n} from \"./resources/support.js\";\nexport {\n analyticsIds,\n anonymousKey,\n currentTouch,\n forgetAnalyticsIds,\n rememberAnalyticsIds,\n withAnalyticsIds,\n} from \"./resources/attribution.js\";\nexport type {\n TouchFields,\n TouchInput,\n TouchResult,\n SignupAttribution,\n SurveyAnswer,\n AttributionStatus,\n AnonymousKeyOptions,\n AnalyticsIds,\n HandoffToken,\n} from \"./resources/attribution.js\";\nexport {\n ANALYTICS_EVENTS,\n METRIKA_GOALS,\n NO_CAPTURE_CLASS,\n MASK_TEXT_CLASS,\n ZONE_ATTRIBUTE,\n initAnalytics,\n setAnalyticsZone,\n setAnalyticsConsent,\n maskRecordedText,\n track,\n page,\n identify,\n resetAnalytics,\n posthogDistinctId,\n sanitizeUrl,\n sanitizeProperties,\n} from \"./analytics.js\";\nexport type {\n AnalyticsZone,\n AnalyticsEvent,\n AnalyticsProperties,\n AnalyticsOptions,\n PostHogOptions,\n MetrikaOptions,\n PostHogLike,\n} from \"./analytics.js\";\nexport type { UserSession } from \"./resources/sessions.js\";\nexport type {\n PushStatus,\n PushSubscriptionInput,\n PushCapableRegistration,\n} from \"./resources/push.js\";\nexport { isCardOtp } from \"./resources/notifications.js\";\nexport type {\n NotificationCategory,\n NotificationChannel,\n NotificationLocale,\n InboxItem,\n CardOtpData,\n NotificationPage,\n ListNotificationsParams,\n NotificationCategoryPreferences,\n NotificationPreferences,\n NotificationPreferencesInput,\n} from \"./resources/notifications.js\";\nexport type {\n DeviceKind,\n DevicePlatform,\n Device,\n WebPushCredential,\n MobilePushCredential,\n RegisterDeviceInput,\n RegisteredDevice,\n RegisterWebPushOptions,\n UnregisterWebPushOptions,\n} from \"./resources/devices.js\";\n\nexport interface CreateClientOptions {\n /** Absolute origin of the Takeal API deployment, no trailing slash.\n * e.g. `\"https://api.takeal.example.com\"`. */\n baseUrl: string;\n /** Runtime brand config. Optional; consumer renders its own brand\n * if omitted. */\n brand?: BrandConfig;\n /** What kind of app this is, sent on every request as\n * `X-Takeal-Client: <platform>; <version>`. The server uses it to spot\n * a sign-in from a new device and to pick the notification channel.\n * `platform` is detected at runtime when omitted (`telegram-miniapp`\n * inside Telegram, `pwa` when installed, `web` otherwise); `version`\n * defaults to the SDK version. Native wrappers should pass\n * `{ platform: \"ios\" | \"android\", version }`. */\n client?: ClientDescriptor;\n /** Token persistence. Defaults to `defaultBrowserStore()` when\n * `window.localStorage` is present, else `inMemoryStore()`. */\n tokenStore?: TokenStore;\n /** Where the remember token of a \"remember me\" sign-in is kept. Defaults\n * to `localStorage` under `takeal_remember` in a browser, in memory\n * elsewhere. Native wrappers should pass secure storage. */\n rememberStore?: TokenStore;\n /** Override the `fetch` implementation — useful for Node < 18,\n * React Native < 0.74, MSW intercept layers, etc. */\n fetch?: FetchLike;\n /** When true, the SDK runs every response through a zod schema\n * before handing it to the caller. Requires `zod` >= 3.22 as a\n * peer dep. Off by default; types-only validation is sufficient\n * for the steady-state case. */\n validate?: boolean;\n}\n\nexport interface CusfrontClient {\n /** Read-only brand config — pass through from createClient args. */\n readonly brand: BrandConfig | undefined;\n /** The platform and version this client announces in `X-Takeal-Client`. */\n readonly client: ResolvedClientDescriptor;\n /** Auth resource: login, refresh, current user, logout. */\n readonly auth: AuthResource;\n /** Deposits (money IN via a funder connector, to the wallet or straight onto a card): initiate, get, list, refund. */\n readonly deposits: DepositsResource;\n /** The ways to top up: each funding connector, where its top-ups land and the methods it takes. */\n readonly fundingOptions: FundingOptionsResource;\n /** Cards (money OUT via an issuer connector): the product catalog, create, get, list, update, balance. */\n readonly cards: CardsResource;\n /** Wallet balance lookup (defaults to the wallet's own currency). */\n readonly balance: BalanceResource;\n /** Bonuses: a discount on the platform's services. Balance, credits, history and a price preview. */\n readonly bonus: BonusResource;\n /** Card fees the user's cards could not cover: paid first from the next top-up. */\n readonly debt: DebtResource;\n /** Close a card that still holds money: the rest goes back the way it was paid. */\n readonly closeRequests: CloseRequestsResource;\n /** Dispute a card operation or complain, and follow claims (lost and stolen cards included) by number and status. */\n readonly claims: ClaimsResource;\n /** Promo and referral codes: check what a code would do before using it. */\n readonly codes: CodesResource;\n /** For referrers: the referral code, the link to share, invited friends and rewards. */\n readonly referral: ReferralResource;\n /** The user's own subscription tier or gift, a promo code for its monthly fee, and cancelling it. */\n readonly subscription: SubscriptionResource;\n /** The wallet's currency: read it, switch it while the wallet is empty. */\n readonly wallet: WalletResource;\n /** Runtime white-label config (`GET /branding`, public): names, logo, wallet label. */\n readonly branding: BrandingResource;\n /** Documents: blog posts, the knowledge base, legal pages. Public before sign-in, more once signed in. */\n readonly documents: DocumentsResource;\n /** Public blog posts, returned as structured blocks to render in your own style.\n * @deprecated Use `documents.list({ category: \"blog\" })` and `documents.get(slug)`; the blog is a category of Documents now. The old paths answer for one more release. */\n readonly blog: BlogResource;\n /** The user's announcement channel subscriptions.\n * @deprecated Use `notifications.setPreferences({ categories: { marketing: {...} } })`. */\n readonly subscriptions: SubscriptionsResource;\n /** Where the user is signed in: list sessions, sign one or all others out. */\n readonly sessions: SessionsResource;\n /** Web Push subscription for the signed-in user.\n * @deprecated Use `devices.registerWebPush` / `devices.unregisterWebPush`. */\n readonly push: PushResource;\n /** The user's inbox and notification preferences. */\n readonly notifications: NotificationsResource;\n /** The user's devices: browsers with Web Push, phones, the Telegram Mini App. */\n readonly devices: DevicesResource;\n /** Profile actions for the signed-in user: link or unlink Telegram. */\n readonly me: MeResource;\n /** Where users come from: record visits, ask \"how did you hear about us\". */\n readonly attribution: AttributionResource;\n /** Everything that happened to the user's money in one list, or one card's part of it. */\n readonly history: HistoryResource;\n /** What the user agreed to; give or withdraw the optional consents. */\n readonly consents: ConsentsResource;\n /** A numbered receipt for every payment. */\n readonly receipts: ReceiptsResource;\n /** The chat with support: messages, files, the conversation's status. */\n readonly support: SupportResource;\n /** Direct access to the token store (e.g. for an explicit sign-out\n * on Capacitor's lifecycle \"app pausing\" event). */\n readonly tokens: TokenStore;\n /**\n * Turn an image URL from the API (`card.design.image_url`,\n * `product.design.image_url`) into one a browser can load. Absolute URLs\n * pass through; a path relative to the API origin (the default card\n * design, `/card-designs/default.svg`) is joined onto `baseUrl`.\n */\n assetUrl(url: string): string;\n /**\n * Ask the deployment whether it is up and which platform version it runs\n * (`GET /ready`, public). `compatible` is false, with a `warning`, when the\n * version is outside `SUPPORTED_MEISTER` or the platform didn't report one.\n * A degraded platform (503) answers with `healthy: false`, not an error.\n */\n ready(opts?: { signal?: AbortSignal }): Promise<ReadyInfo>;\n}\n\n/**\n * Build a new client. Stateless across calls — multiple clients can\n * coexist (e.g. an admin Cusfront with a different baseUrl than the\n * end-user one). Each gets its own `TokenStore`.\n *\n * `validate: true` is honoured by individual resources that ship\n * matching zod schemas; resources without a schema ignore it.\n */\nexport function createClient(opts: CreateClientOptions): CusfrontClient {\n const tokens = opts.tokenStore ?? pickDefaultStore();\n const remembered = opts.rememberStore ?? pickDefaultStore(\"takeal_remember\");\n const fetchImpl = opts.fetch ?? defaultFetch();\n const client = resolveClientDescriptor(opts.client);\n const http = new HttpClient(opts.baseUrl, tokens, fetchImpl, {\n [CLIENT_HEADER]: clientHeaderValue(client),\n });\n\n return {\n brand: opts.brand,\n client,\n tokens,\n assetUrl: (url: string) => resolveAssetUrl(opts.baseUrl, url),\n ready: (o?: { signal?: AbortSignal }) => fetchReady(http, o),\n auth: new AuthResource(http, tokens, remembered),\n deposits: new DepositsResource(http),\n fundingOptions: new FundingOptionsResource(http),\n cards: new CardsResource(http),\n balance: new BalanceResource(http),\n bonus: new BonusResource(http),\n debt: new DebtResource(http),\n closeRequests: new CloseRequestsResource(http),\n claims: new ClaimsResource(http),\n codes: new CodesResource(http),\n referral: new ReferralResource(http),\n subscription: new SubscriptionResource(http),\n wallet: new WalletResource(http),\n branding: new BrandingResource(http),\n documents: new DocumentsResource(http),\n blog: new BlogResource(http),\n subscriptions: new SubscriptionsResource(http),\n sessions: new SessionsResource(http),\n push: new PushResource(http),\n me: new MeResource(http),\n notifications: new NotificationsResource(http),\n devices: new DevicesResource(http, client),\n attribution: new AttributionResource(http),\n history: new HistoryResource(http),\n consents: new ConsentsResource(http),\n receipts: new ReceiptsResource(http),\n support: new SupportResource(http),\n };\n}\n\nfunction pickDefaultStore(key?: string): TokenStore {\n if (typeof globalThis !== \"undefined\" && \"localStorage\" in globalThis) {\n return defaultBrowserStore(key);\n }\n return inMemoryStore();\n}\n\nfunction defaultFetch(): FetchLike {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.fetch === \"function\") {\n // Bind to globalThis so `this` is correct inside the implementation\n // (some polyfills choke on a detached reference).\n return globalThis.fetch.bind(globalThis);\n }\n throw new Error(\n \"@takeal/cusfront-sdk: native fetch is not available in this runtime. \" +\n \"Pass a polyfill via createClient({ fetch }).\",\n );\n}\n","/**\n * `@takeal/cusfront-sdk/telegram` — Telegram Mini App adapter.\n *\n * A Mini App receives a signed `initData` string from the Telegram client\n * (`window.Telegram.WebApp.initData`). This module turns that string into an\n * authenticated SDK client:\n *\n * import { fromTelegramWebApp } from \"@takeal/cusfront-sdk/telegram\";\n * const client = await fromTelegramWebApp({ baseUrl: \"https://api.example.com\" });\n * const me = await client.auth.me(); // me.email_pending? prompt for email\n *\n * Signature validation: the HMAC over `initData` can only be verified with the\n * bot token, which lives on the server. So the **authoritative** check happens\n * server-side at `POST /auth/telegram/exchange`. Here we only do a structural,\n * fail-fast well-formedness check (`hash` + `auth_date` present, not stale)\n * before spending a network round-trip on an obviously-bad payload.\n */\n\nimport { createClient, type CreateClientOptions, type CusfrontClient } from \"./index.js\";\nimport type { JwtIssued, TelegramUnknown } from \"./resources/auth.js\";\n\n/** The Telegram `user` object embedded (URL-encoded JSON) in initData. */\nexport interface TelegramUser {\n id: number;\n first_name?: string;\n last_name?: string;\n username?: string;\n language_code?: string;\n photo_url?: string;\n is_premium?: boolean;\n}\n\n/** Structurally-parsed initData. `raw` is the original string passed to the\n * server verbatim — the server re-derives the HMAC from it, so we never\n * re-serialise. */\nexport interface ParsedInitData {\n raw: string;\n params: Record<string, string>;\n hash?: string;\n auth_date?: number;\n query_id?: string;\n user?: TelegramUser;\n}\n\n/** Thrown by {@link assertWellFormed} when initData is structurally invalid or\n * stale. A signature mismatch is NOT detectable here (no bot token) — that\n * surfaces as a 401 `ApiError` from the exchange call instead. */\nexport class InitDataError extends Error {\n constructor(\n message: string,\n readonly reason: \"empty\" | \"missing_hash\" | \"missing_auth_date\" | \"bad_user\" | \"stale\",\n ) {\n super(message);\n this.name = \"InitDataError\";\n }\n}\n\n/** Parse a raw `initData` query string into its fields (best-effort — does\n * not validate). `user` is JSON-decoded when present and parseable. */\nexport function parseInitData(initData: string): ParsedInitData {\n const params: Record<string, string> = {};\n const sp = new URLSearchParams(initData);\n for (const [k, v] of sp.entries()) params[k] = v;\n\n let user: TelegramUser | undefined;\n if (params.user) {\n try {\n user = JSON.parse(params.user) as TelegramUser;\n } catch {\n user = undefined;\n }\n }\n\n const authDateRaw = params.auth_date;\n const auth_date = authDateRaw && /^\\d+$/.test(authDateRaw) ? Number(authDateRaw) : undefined;\n\n return {\n raw: initData,\n params,\n ...(params.hash ? { hash: params.hash } : {}),\n ...(auth_date !== undefined ? { auth_date } : {}),\n ...(params.query_id ? { query_id: params.query_id } : {}),\n ...(user ? { user } : {}),\n };\n}\n\nexport interface WellFormedOptions {\n /** Reject initData whose `auth_date` is older than this many seconds.\n * Defaults to 86400 (24h) — match or stay under the server's\n * `auth.telegram.initdata_max_age_secs`. Pass 0 to skip the freshness\n * check client-side (the server still enforces its own window). */\n maxAgeSeconds?: number;\n /** Injectable clock (unix seconds) for testing. Defaults to `Date.now()`. */\n nowUnix?: number;\n}\n\n/** Fail-fast structural check: `hash` present, `auth_date` present + a valid\n * `user`, and (optionally) not stale. Throws {@link InitDataError}. Does NOT\n * verify the HMAC — only the server can. */\nexport function assertWellFormed(initData: string, opts: WellFormedOptions = {}): ParsedInitData {\n if (!initData) throw new InitDataError(\"initData is empty\", \"empty\");\n const parsed = parseInitData(initData);\n if (!parsed.hash) throw new InitDataError(\"initData is missing `hash`\", \"missing_hash\");\n if (parsed.auth_date === undefined)\n throw new InitDataError(\"initData is missing a valid `auth_date`\", \"missing_auth_date\");\n if (!parsed.user || typeof parsed.user.id !== \"number\")\n throw new InitDataError(\"initData is missing a valid `user`\", \"bad_user\");\n\n const maxAge = opts.maxAgeSeconds ?? 86_400;\n if (maxAge > 0) {\n const now = opts.nowUnix ?? Math.floor(Date.now() / 1000);\n if (now - parsed.auth_date > maxAge)\n throw new InitDataError(\n \"initData is stale (auth_date older than the freshness window)\",\n \"stale\",\n );\n }\n return parsed;\n}\n\n/** What can be logged about an `initData` value without logging it: no\n * values, no signatures, no user fields. Built by {@link describeInitData}. */\nexport interface InitDataDiagnostics {\n /** `typeof` of what was received (`\"string\"` for anything usable). */\n type: string;\n /** Length of the string, 0 for anything else. */\n length: number;\n /** Names of the fields present, sorted. Values are left out. */\n fields: string[];\n hasHash: boolean;\n hasSignature: boolean;\n /** `auth_date` is present and a unix timestamp. */\n hasAuthDate: boolean;\n /** Seconds since `auth_date`, when it parses. Negative means a clock ahead. */\n authDateAgeSeconds?: number;\n /** `user` is present and its `id` is a number. */\n hasUserId: boolean;\n /** Why {@link assertWellFormed} would refuse it, or `null` when it would not.\n * `\"not_a_string\"` when the value is not a string at all. */\n reason: InitDataError[\"reason\"] | \"not_a_string\" | null;\n}\n\n/**\n * Describe an `initData` value for a log line, without the value itself.\n * Use it where the payload is refused, so the log says which check failed:\n *\n * console.warn(\"telegram sign-in refused\", describeInitData(body.initData));\n *\n * The signature is checked only by the server; a payload this reports as\n * well formed can still be refused there, with the reason in the 401.\n */\nexport function describeInitData(\n initData: unknown,\n opts: WellFormedOptions = {},\n): InitDataDiagnostics {\n if (typeof initData !== \"string\") {\n return {\n type: typeof initData,\n length: 0,\n fields: [],\n hasHash: false,\n hasSignature: false,\n hasAuthDate: false,\n hasUserId: false,\n reason: \"not_a_string\",\n };\n }\n const parsed = parseInitData(initData);\n const now = opts.nowUnix ?? Math.floor(Date.now() / 1000);\n let reason: InitDataDiagnostics[\"reason\"] = null;\n try {\n assertWellFormed(initData, opts);\n } catch (e) {\n if (e instanceof InitDataError) reason = e.reason;\n else throw e;\n }\n return {\n type: \"string\",\n length: initData.length,\n fields: Object.keys(parsed.params).sort(),\n hasHash: parsed.hash !== undefined,\n hasSignature: typeof parsed.params.signature === \"string\" && parsed.params.signature !== \"\",\n hasAuthDate: parsed.auth_date !== undefined,\n ...(parsed.auth_date !== undefined ? { authDateAgeSeconds: now - parsed.auth_date } : {}),\n hasUserId: typeof parsed.user?.id === \"number\",\n reason,\n };\n}\n\nexport interface FromInitDataOptions extends WellFormedOptions {\n /** Skip the client-side well-formedness check and let the server be the\n * sole judge. Default false — the fail-fast check saves a round-trip on\n * obviously-bad input. */\n skipWellFormedCheck?: boolean;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false`, an unknown id makes {@link fromInitData} /\n * {@link fromTelegramWebApp} throw {@link TelegramUnknownError} (and\n * {@link exchangeInitData} resolve with `session.stage === \"unknown\"`)\n * instead of creating anything. */\n provision?: boolean;\n /** After a successful exchange, register this Mini App as a\n * `telegram_miniapp` device so notifications reach the user as bot\n * messages. Default `true`. Best-effort: a failure is logged as a\n * warning and never fails the sign-in. */\n registerDevice?: boolean;\n}\n\n/** Thrown by {@link fromInitData} / {@link fromTelegramWebApp} when\n * `provision: false` was passed and the Telegram id has no account yet.\n * Nothing was created and no JWT was stored. `initData` is the payload that\n * was exchanged, so the app can go on with\n * `client.auth.linkTelegram({ initData, email, password })` or retry with\n * `provision: true`. */\nexport class TelegramUnknownError extends Error {\n constructor(readonly initData: string) {\n super(\"this Telegram account is not linked to any user (provision: false)\");\n this.name = \"TelegramUnknownError\";\n }\n}\n\n/** What {@link exchangeInitData} resolves to. When `session.stage` is\n * `\"jwt\"` the client is signed in; when it is `\"unknown\"` the client is\n * built but has no session. */\nexport interface InitDataExchange {\n client: CusfrontClient;\n session: JwtIssued | TelegramUnknown;\n}\n\n/**\n * Build a client from a raw `initData` string and exchange the payload,\n * returning both the client and the exchange result.\n *\n * 1. (unless skipped) structurally validate the payload — throws\n * {@link InitDataError} on malformed/stale input.\n * 2. exchange it at `POST /auth/telegram/exchange` — the server validates the\n * HMAC; a bad signature throws a 401 `ApiError`.\n * 3. on `stage: \"jwt\"` the JWT is stored and the client is ready. With\n * `provision: false` and a Telegram id nobody has signed in with,\n * `session` is `{ stage: \"unknown\" }` and the client is unauthenticated;\n * continue with `client.auth.linkTelegram(...)` or\n * `client.auth.exchangeTelegram({ initData, provision: true })`.\n * 4. on `stage: \"jwt\"` the Mini App is registered as a `telegram_miniapp`\n * device (unless `registerDevice: false`), so the user's notifications\n * arrive as bot messages. Errors here are only logged.\n *\n * The client announces itself as `telegram-miniapp` in `X-Takeal-Client`\n * whatever `config.client.platform` says; a given `config.client.version`\n * is kept.\n *\n * Use this when the app wants to branch on the outcome itself;\n * {@link fromInitData} is the throwing shorthand.\n */\nexport async function exchangeInitData(\n initData: string,\n config: CreateClientOptions,\n opts: FromInitDataOptions = {},\n): Promise<InitDataExchange> {\n if (!opts.skipWellFormedCheck) assertWellFormed(initData, opts);\n const client = createClient({\n ...config,\n client: { ...config.client, platform: \"telegram-miniapp\" },\n });\n const session = await client.auth.exchangeTelegram({\n initData,\n ...(opts.provision !== undefined ? { provision: opts.provision } : {}),\n });\n if (session.stage === \"jwt\" && opts.registerDevice !== false) {\n await registerMiniAppDevice(client, initData);\n }\n return { client, session };\n}\n\n/** Best-effort `telegram_miniapp` device registration. The Telegram\n * profile's `language_code` goes along as the device locale when present. */\nasync function registerMiniAppDevice(client: CusfrontClient, initData: string): Promise<void> {\n const locale = parseInitData(initData).user?.language_code;\n try {\n await client.devices.register({\n kind: \"telegram_miniapp\",\n platform: \"telegram\",\n credential: {},\n ...(locale ? { locale } : {}),\n });\n } catch (e) {\n console.warn(\n \"@takeal/cusfront-sdk/telegram: could not register the Mini App as a device; \" +\n \"notifications may not reach this user in Telegram\",\n e,\n );\n }\n}\n\n/**\n * Build an authenticated client from a raw `initData` string. Thin wrapper\n * over {@link exchangeInitData} that never hands back a client without a\n * session: with `provision: false` and an unknown Telegram id it throws\n * {@link TelegramUnknownError} (carrying `initData`) instead.\n *\n * Read `client.auth.me()` (or call `client.auth.exchangeTelegram` directly for\n * the raw session) to check `email_pending` and prompt for an email.\n */\nexport async function fromInitData(\n initData: string,\n config: CreateClientOptions,\n opts: FromInitDataOptions = {},\n): Promise<CusfrontClient> {\n const { client, session } = await exchangeInitData(initData, config, opts);\n if (session.stage === \"unknown\") throw new TelegramUnknownError(initData);\n return client;\n}\n\n/** Read `window.Telegram.WebApp.initData` if running inside a Telegram Mini\n * App. Returns null when absent or empty (e.g. opened outside Telegram). */\nexport function readWebAppInitData(): string | null {\n const tg = (\n globalThis as unknown as {\n Telegram?: { WebApp?: { initData?: string } };\n }\n ).Telegram;\n const data = tg?.WebApp?.initData;\n return data && data.length > 0 ? data : null;\n}\n\n/**\n * Convenience entry for a Mini App: read `initData` from the Telegram WebApp\n * SDK and exchange it. Throws {@link InitDataError} if not running inside a\n * Telegram Mini App, and {@link TelegramUnknownError} when `provision: false`\n * was passed and the Telegram id has no account yet.\n */\nexport async function fromTelegramWebApp(\n config: CreateClientOptions,\n opts: FromInitDataOptions = {},\n): Promise<CusfrontClient> {\n const initData = readWebAppInitData();\n if (!initData)\n throw new InitDataError(\n \"not running inside a Telegram Mini App (window.Telegram.WebApp.initData is empty)\",\n \"empty\",\n );\n return fromInitData(initData, config, opts);\n}\n\n/** Convenience accessor for the typed exchange session (incl. `email_pending`)\n * when you need the envelope rather than just the client. */\nexport type TelegramExchangeSession = JwtIssued;\n"]}