@takeal/cusfront-sdk 0.6.8 → 0.6.14

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 (59) hide show
  1. package/CHANGELOG.md +112 -2
  2. package/README.md +26 -9
  3. package/dist/analytics.cjs +44 -6
  4. package/dist/analytics.cjs.map +1 -1
  5. package/dist/analytics.js +44 -6
  6. package/dist/analytics.js.map +1 -1
  7. package/dist/{cards-BgY00UpU.d.ts → cards-DPlgx76p.d.ts} +86 -18
  8. package/dist/{cards-DGz4Rqu1.d.cts → cards-D_krTWzr.d.cts} +86 -18
  9. package/dist/index.cjs +225 -93
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +5 -5
  12. package/dist/index.d.ts +5 -5
  13. package/dist/index.js +221 -94
  14. package/dist/index.js.map +1 -1
  15. package/dist/react/index.d.cts +1 -1
  16. package/dist/react/index.d.ts +1 -1
  17. package/dist/resources/attribution.cjs +99 -4
  18. package/dist/resources/attribution.cjs.map +1 -1
  19. package/dist/resources/attribution.d.cts +58 -1
  20. package/dist/resources/attribution.d.ts +58 -1
  21. package/dist/resources/attribution.js +96 -5
  22. package/dist/resources/attribution.js.map +1 -1
  23. package/dist/resources/auth.cjs +64 -3
  24. package/dist/resources/auth.cjs.map +1 -1
  25. package/dist/resources/auth.d.cts +1 -1
  26. package/dist/resources/auth.d.ts +1 -1
  27. package/dist/resources/auth.js +64 -3
  28. package/dist/resources/auth.js.map +1 -1
  29. package/dist/resources/cards.cjs +69 -7
  30. package/dist/resources/cards.cjs.map +1 -1
  31. package/dist/resources/cards.d.cts +2 -1
  32. package/dist/resources/cards.d.ts +2 -1
  33. package/dist/resources/cards.js +69 -8
  34. package/dist/resources/cards.js.map +1 -1
  35. package/dist/resources/codes.cjs.map +1 -1
  36. package/dist/resources/codes.d.cts +21 -1
  37. package/dist/resources/codes.d.ts +21 -1
  38. package/dist/resources/codes.js.map +1 -1
  39. package/dist/resources/consents.cjs +15 -0
  40. package/dist/resources/consents.cjs.map +1 -1
  41. package/dist/resources/consents.js +15 -0
  42. package/dist/resources/consents.js.map +1 -1
  43. package/dist/resources/deposits.cjs +50 -0
  44. package/dist/resources/deposits.cjs.map +1 -1
  45. package/dist/resources/deposits.d.cts +2 -1
  46. package/dist/resources/deposits.d.ts +2 -1
  47. package/dist/resources/deposits.js +50 -0
  48. package/dist/resources/deposits.js.map +1 -1
  49. package/dist/resources/funding-options.d.cts +2 -1
  50. package/dist/resources/funding-options.d.ts +2 -1
  51. package/dist/resources/me.d.cts +1 -1
  52. package/dist/resources/me.d.ts +1 -1
  53. package/dist/telegram.cjs +224 -73
  54. package/dist/telegram.cjs.map +1 -1
  55. package/dist/telegram.d.cts +34 -3
  56. package/dist/telegram.d.ts +34 -3
  57. package/dist/telegram.js +224 -74
  58. package/dist/telegram.js.map +1 -1
  59. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/resources/attribution.ts","../../src/resources/consents.ts"],"names":[],"mappings":";AA4GA,SAAS,QAAA,GAAW;AAClB,EAAA,OAAQ,UAAA,CAAyC,UAAU,MAAA,EAAQ,cAAA;AACrE;AAEA,SAAS,WAAW,IAAA,EAAkC;AACpD,EAAA,MAAM,MAAO,UAAA,CAAuC,QAAA;AACpD,EAAA,IAAI,CAAC,GAAA,EAAK,MAAA,EAAQ,OAAO,MAAA;AACzB,EAAA,KAAA,MAAW,IAAA,IAAQ,GAAA,CAAI,MAAA,CAAO,KAAA,CAAM,GAAG,CAAA,EAAG;AACxC,IAAA,MAAM,CAAC,GAAG,GAAG,CAAC,IAAI,IAAA,CAAK,IAAA,EAAK,CAAE,KAAA,CAAM,GAAG,CAAA;AACvC,IAAA,IAAI,MAAM,IAAA,EAAM,OAAO,mBAAmB,CAAA,CAAE,IAAA,CAAK,GAAG,CAAC,CAAA;AAAA,EACvD;AACA,EAAA,OAAO,MAAA;AACT;AASA,IAAM,SAAA,GAAY,uBAAA;AASX,SAAS,YAAA,CAAa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,KAAK,IAAA,CAAK,IAAA,CAAe,cAAA,EAAgB,EAAE,MAAM,CAAA;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,gBAAgB,OAAA,EAA6C;AACjE,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,mBAAA,EAAqB,IAAA,EAAM,OAAO,CAAA;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,sBAAsB,OAAA,EAA6C;AACvE,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,yBAAA,EAA2B,IAAA,EAAM,OAAO,CAAA;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,MAAM,WAAW,KAAA,EAA0D;AACzE,IAAA,MAAM,IAAA,GAAiF;AAAA,MACrF,WAAW,KAAA,CAAM;AAAA,KACnB;AACA,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,YAAA,IAAgB,YAAA,EAAa;AAC/C,IAAA,IAAI,GAAA,KAAQ,MAAA,EAAW,IAAA,CAAK,aAAA,GAAgB,GAAA;AAC5C,IAAA,IAAI,KAAA,CAAM,OAAA,KAAY,MAAA,EAAW,IAAA,CAAK,UAAU,KAAA,CAAM,OAAA;AACtD,IAAA,OAAO,KAAK,IAAA,CAAK,IAAA,CAA4B,mBAAA,EAAqB,EAAE,MAAM,CAAA;AAAA,EAC5E;AACF","file":"consents.js","sourcesContent":["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\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 /** 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","import type { HttpClient } from \"../http.js\";\nimport { anonymousKey } 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 return this.http.post<{ recorded: boolean }>(\"/consents/cookies\", { body });\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/resources/attribution.ts","../../src/resources/consents.ts"],"names":[],"mappings":";AAuKA,SAAS,QAAA,GAAW;AAClB,EAAA,OAAQ,UAAA,CAAyC,UAAU,MAAA,EAAQ,cAAA;AACrE;AAEA,SAAS,WAAW,IAAA,EAAkC;AACpD,EAAA,MAAM,MAAO,UAAA,CAAuC,QAAA;AACpD,EAAA,IAAI,CAAC,GAAA,EAAK,MAAA,EAAQ,OAAO,MAAA;AACzB,EAAA,KAAA,MAAW,IAAA,IAA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AAW,KAAA,CAAM;AAAA,KACnB;AACA,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,YAAA,IAAgB,YAAA,EAAa;AAC/C,IAAA,IAAI,GAAA,KAAQ,MAAA,EAAW,IAAA,CAAK,aAAA,GAAgB,GAAA;AAC5C,IAAA,IAAI,KAAA,CAAM,OAAA,KAAY,MAAA,EAAW,IAAA,CAAK,UAAU,KAAA,CAAM,OAAA;AACtD,IAAA,IAAI,CAAC,KAAA,CAAM,SAAA,EAAW,kBAAA,EAAmB;AACzC,IAAA,OAAO,KAAK,IAAA,CAAK,IAAA,CAA4B,mBAAA,EAAqB,EAAE,MAAM,CAAA;AAAA,EAC5E;AACF","file":"consents.js","sourcesContent":["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 { 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"]}
@@ -1,5 +1,48 @@
1
1
  'use strict';
2
2
 
3
+ // src/resources/attribution.ts
4
+ function readCookie(name) {
5
+ const doc = globalThis.document;
6
+ if (!doc?.cookie) return void 0;
7
+ for (const part of doc.cookie.split(";")) {
8
+ const [k, ...v] = part.trim().split("=");
9
+ if (k === name) return decodeURIComponent(v.join("="));
10
+ }
11
+ return void 0;
12
+ }
13
+ var IDS_KEY = "takeal_analytics_ids";
14
+ function storage() {
15
+ try {
16
+ return globalThis.localStorage;
17
+ } catch {
18
+ return void 0;
19
+ }
20
+ }
21
+ function stored() {
22
+ try {
23
+ const raw = storage()?.getItem(IDS_KEY);
24
+ const v = raw ? JSON.parse(raw) : {};
25
+ return typeof v === "object" && v !== null ? v : {};
26
+ } catch {
27
+ return {};
28
+ }
29
+ }
30
+ function clean(ids) {
31
+ const out = {};
32
+ const ym = ids.metrika_client_id?.trim();
33
+ if (ym && /^\d{1,32}$/.test(ym)) out.metrika_client_id = ym;
34
+ const ga = ids.ga_client_id?.trim();
35
+ if (ga && /^\d+\.\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;
36
+ return out.metrika_client_id || out.ga_client_id ? out : void 0;
37
+ }
38
+ function analyticsIds() {
39
+ const kept = stored();
40
+ return clean({
41
+ metrika_client_id: kept.metrika_client_id ?? readCookie("_ym_uid"),
42
+ ga_client_id: kept.ga_client_id ?? readCookie("_ga")?.split(".").slice(-2).join(".")
43
+ });
44
+ }
45
+
3
46
  // src/resources/cards.ts
4
47
  function cardRequestBody(input) {
5
48
  const {
@@ -46,10 +89,17 @@ var DepositsResource = class {
46
89
  if (connectorSlug !== void 0) body["connector_slug"] = connectorSlug;
47
90
  return this.http.post("/me/deposits/quotes", { body });
48
91
  }
92
+ /**
93
+ * Start a top-up. 409 `payments_on_hold`: a payment on this account was
94
+ * not accepted and new ones wait until support sorts it out. Show the
95
+ * message as it comes and point the user to support.
96
+ */
49
97
  async initiate(input) {
50
98
  const { idempotencyKey, issue_card, ...rest } = input;
51
99
  const body = { ...rest };
52
100
  if (issue_card !== void 0) body["issue_card"] = cardRequestBody(issue_card);
101
+ const ids = input.analytics_ids ?? analyticsIds();
102
+ if (ids !== void 0) body["analytics_ids"] = ids;
53
103
  return this.http.post("/me/deposits", {
54
104
  body,
55
105
  idempotencyKey
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/resources/cards.ts","../../src/resources/deposits.ts"],"names":[],"mappings":";;;AAyXO,SAAS,gBACd,KAAA,EACyB;AACzB,EAAA,MAAM;AAAA,IACJ,SAAA;AAAA,IACA,IAAA;AAAA,IACA,QAAA;AAAA,IACA,QAAA;AAAA,IACA,WAAA;AAAA,IACA,SAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA,EAAgB,QAAA;AAAA,IAChB,GAAG;AAAA,GACL,GAAI,KAAA;AACJ,EAAA,MAAM,IAAA,GAAgC,EAAE,GAAG,IAAA,EAAK;AAChD,EAAA,IAAI,SAAA,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AG,IAAA,EAAK;AAChD,IAAA,IAAI,eAAe,MAAA,EAAW,IAAA,CAAK,YAAY,CAAA,GAAI,gBAAgB,UAAU,CAAA;AAC7E,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAc,cAAA,EAAgB;AAAA,MAC7C,IAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AAAA;AAAA,EAGA,MAAM,IAAI,EAAA,EAA8B;AACtC,IAAA,OAAO,KAAK,IAAA,CAAK,GAAA,CAAa,gBAAgB,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAE,CAAA;AAAA,EACxE;AAAA;AAAA,EAGA,MAAM,IAAA,GAA2B;AAC/B,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAe,cAAc,CAAA;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,MAAA,CAAO,SAAA,EAAmB,KAAA,EAAkD;AAChF,IAAA,MAAM,EAAE,cAAA,EAAgB,GAAG,IAAA,EAAK,GAAI,KAAA;AACpC,IAAA,OAAO,KAAK,IAAA,CAAK,IAAA,CAAa,gBAAgB,kBAAA,CAAmB,SAAS,CAAC,CAAA,QAAA,CAAA,EAAY;AAAA,MACrF,IAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AACF","file":"deposits.cjs","sourcesContent":["import type { Claim } from \"./claims.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\";\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`: the row exists but the issuance fee has not been\n * paid yet; the provider has not been called and nothing is visible.\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 buyer pays in. A signed-in user sees\n * their wallet currency, converted the way issuance will charge it; the\n * public catalog shows the currency the operator priced the card in. It\n * is not necessarily the currency the card is held 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\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. */\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. Show it next to the\n * balance as money on its way to the card.\n */\n topups_pending: string | null;\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}\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, its starting balance and `debt_withheld`, in `card_currency`. */\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}\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 return body;\n}\n\n/** Remaining balance of a prepaid card. */\nexport interface CardBalance {\n amount: string;\n currency: string;\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 * 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 * Some issuers hand out a page that shows the numbers instead of the\n * numbers themselves. Then `reveal_url` is set, `pan` and `cvv` are empty,\n * and the client opens the page in a frame; see the README for the frame.\n */\nexport interface RevealedCard {\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\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), 503 no\n * funding connector 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 * 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 caller's wallet currency. 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 * The result is the numbers, or `reveal_url` with empty `pan` and `cvv`\n * when the issuer shows them on a page of its own: open that page in a\n * frame right away, it is short-lived.\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 return this.http.post<RevealedCard>(`/me/cards/${encodeURIComponent(id)}/reveal`);\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 { 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\";\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\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. The\n * rate to show the user is `credited_amount / source_amount`, which has\n * the fee in it; see the README for the rouble-per-dollar form.\n */\n 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 * 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 promo_code?: string;\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 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 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"]}
1
+ {"version":3,"sources":["../../src/resources/attribution.ts","../../src/resources/cards.ts","../../src/resources/deposits.ts"],"names":[],"mappings":";;;AA2KA,SAAS,WAAW,IAAA,EAAkC;AACpD,EAAA,MAAM,MAAO,UAAA,CAAuC,QAAA;AACpD,EAAA,IAAI,CAAC,GAAA,EAAK,MAAA,EAAQ,OAAO,MAAA;AACzB,EAAA,KAAA,MAAW,IAAA,IAAQ,GAAA,CAAI,MAAA,CAAO,KAAA,CAAM,GAAG,CAAA,EAAG;AACxC,IAAA,MAAM,CAAC,GAAG,GAAG,CAAC,IAAI,IAAA,CAAK,IAAA,EAAK,CAAE,KAAA,CAAM,GAAG,CAAA;AACvC,IAAA,IAAI,MAAM,IAAA,EAAM,OAAO,mBAAmB,CAAA,CAAE,IAAA,CAAK,GAAG,CAAC,CAAA;AAAA,EACvD;AACA,EAAA,OAAO,MAAA;AACT;AAqEA,IAAM,OAAA,GAAU,sBAAA;AAEhB,SAAS,OAAA,GAA+B;AACtC,EAAA,IAAI;AACF,IAAA,OAAQ,UAAA,CAA0C,YAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAEA,SAAS,MAAA,GAAuB;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,OAAA,EAAQ,EAAG,OAAA,CAAQ,OAAO,CAAA;AACtC,IAAA,MAAM,IAAI,GAAA,GAAO,IAAA,CAAK,KAAA,CAAM,GAAG,IAAqB,EAAC;AACrD,IAAA,OAAO,OAAO,CAAA,KA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E,cAAA,EAAgB,UAAA,EAAY,GAAG,MAAK,GAAI,KAAA;AAChD,IAAA,MAAM,IAAA,GAAgC,EAAE,GAAG,IAAA,EAAK;AAChD,IAAA,IAAI,eAAe,MAAA,EAAW,IAAA,CAAK,YAAY,CAAA,GAAI,gBAAgB,UAAU,CAAA;AAC7E,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,aAAA,IAAiB,YAAA,EAAa;AAChD,IAAA,IAAI,GAAA,KAAQ,MAAA,EAAW,IAAA,CAAK,eAAe,CAAA,GAAI,GAAA;AAC/C,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAc,cAAA,EAAgB;AAAA,MAC7C,IAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AAAA;AAAA,EAGA,MAAM,IAAI,EAAA,EAA8B;AACtC,IAAA,OAAO,KAAK,IAAA,CAAK,GAAA,CAAa,gBAAgB,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAE,CAAA;AAAA,EACxE;AAAA;AAAA,EAGA,MAAM,IAAA,GAA2B;AAC/B,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAe,cAAc,CAAA;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,MAAA,CAAO,SAAA,EAAmB,KAAA,EAAkD;AAChF,IAAA,MAAM,EAAE,cAAA,EAAgB,GAAG,IAAA,EAAK,GAAI,KAAA;AACpC,IAAA,OAAO,KAAK,IAAA,CAAK,IAAA,CAAa,gBAAgB,kBAAA,CAAmB,SAAS,CAAC,CAAA,QAAA,CAAA,EAAY;AAAA,MACrF,IAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AACF","file":"deposits.cjs","sourcesContent":["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 { 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\";\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\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}\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 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), 503 no funding connector 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 * 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 { 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\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. The\n * rate to show the user is `credited_amount / source_amount`, which has\n * the fee in it; see the README for the rouble-per-dollar form.\n */\n 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 * 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 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"]}
@@ -1,4 +1,5 @@
1
1
  import '../http-CL97TjMO.cjs';
2
- export { h as CardLoadStatus, w as CreateDepositRefundInput, x as CreateQuoteInput, D as Deposit, z as DepositMethod, E as DepositStatus, b as DepositsResource, H as FeeKind, K as FundingQuote, L as InitiateDepositInput, N as IssueCardInput, R as Refund } from '../cards-DGz4Rqu1.cjs';
2
+ export { h as CardLoadStatus, w as CreateDepositRefundInput, x as CreateQuoteInput, D as Deposit, z as DepositMethod, E as DepositStatus, b as DepositsResource, H as FeeKind, K as FundingQuote, L as InitiateDepositInput, N as IssueCardInput, R as Refund } from '../cards-D_krTWzr.cjs';
3
+ import './attribution.cjs';
3
4
  import './claims.cjs';
4
5
  import './consents.cjs';
@@ -1,4 +1,5 @@
1
1
  import '../http-CL97TjMO.js';
2
- export { h as CardLoadStatus, w as CreateDepositRefundInput, x as CreateQuoteInput, D as Deposit, z as DepositMethod, E as DepositStatus, b as DepositsResource, H as FeeKind, K as FundingQuote, L as InitiateDepositInput, N as IssueCardInput, R as Refund } from '../cards-BgY00UpU.js';
2
+ export { h as CardLoadStatus, w as CreateDepositRefundInput, x as CreateQuoteInput, D as Deposit, z as DepositMethod, E as DepositStatus, b as DepositsResource, H as FeeKind, K as FundingQuote, L as InitiateDepositInput, N as IssueCardInput, R as Refund } from '../cards-DPlgx76p.js';
3
+ import './attribution.js';
3
4
  import './claims.js';
4
5
  import './consents.js';
@@ -1,3 +1,46 @@
1
+ // src/resources/attribution.ts
2
+ function readCookie(name) {
3
+ const doc = globalThis.document;
4
+ if (!doc?.cookie) return void 0;
5
+ for (const part of doc.cookie.split(";")) {
6
+ const [k, ...v] = part.trim().split("=");
7
+ if (k === name) return decodeURIComponent(v.join("="));
8
+ }
9
+ return void 0;
10
+ }
11
+ var IDS_KEY = "takeal_analytics_ids";
12
+ function storage() {
13
+ try {
14
+ return globalThis.localStorage;
15
+ } catch {
16
+ return void 0;
17
+ }
18
+ }
19
+ function stored() {
20
+ try {
21
+ const raw = storage()?.getItem(IDS_KEY);
22
+ const v = raw ? JSON.parse(raw) : {};
23
+ return typeof v === "object" && v !== null ? v : {};
24
+ } catch {
25
+ return {};
26
+ }
27
+ }
28
+ function clean(ids) {
29
+ const out = {};
30
+ const ym = ids.metrika_client_id?.trim();
31
+ if (ym && /^\d{1,32}$/.test(ym)) out.metrika_client_id = ym;
32
+ const ga = ids.ga_client_id?.trim();
33
+ if (ga && /^\d+\.\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;
34
+ return out.metrika_client_id || out.ga_client_id ? out : void 0;
35
+ }
36
+ function analyticsIds() {
37
+ const kept = stored();
38
+ return clean({
39
+ metrika_client_id: kept.metrika_client_id ?? readCookie("_ym_uid"),
40
+ ga_client_id: kept.ga_client_id ?? readCookie("_ga")?.split(".").slice(-2).join(".")
41
+ });
42
+ }
43
+
1
44
  // src/resources/cards.ts
2
45
  function cardRequestBody(input) {
3
46
  const {
@@ -44,10 +87,17 @@ var DepositsResource = class {
44
87
  if (connectorSlug !== void 0) body["connector_slug"] = connectorSlug;
45
88
  return this.http.post("/me/deposits/quotes", { body });
46
89
  }
90
+ /**
91
+ * Start a top-up. 409 `payments_on_hold`: a payment on this account was
92
+ * not accepted and new ones wait until support sorts it out. Show the
93
+ * message as it comes and point the user to support.
94
+ */
47
95
  async initiate(input) {
48
96
  const { idempotencyKey, issue_card, ...rest } = input;
49
97
  const body = { ...rest };
50
98
  if (issue_card !== void 0) body["issue_card"] = cardRequestBody(issue_card);
99
+ const ids = input.analytics_ids ?? analyticsIds();
100
+ if (ids !== void 0) body["analytics_ids"] = ids;
51
101
  return this.http.post("/me/deposits", {
52
102
  body,
53
103
  idempotencyKey