@takeal/cusfront-sdk 0.2.8 → 0.3.7

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 (77) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +367 -5
  3. package/dist/devices-C3JHi2Hi.d.cts +165 -0
  4. package/dist/devices-DP_hxwmW.d.ts +165 -0
  5. package/dist/{http-BkCfOCR0.d.cts → http-B-OQwMYn.d.cts} +9 -1
  6. package/dist/{http-BkCfOCR0.d.ts → http-B-OQwMYn.d.ts} +9 -1
  7. package/dist/index.cjs +284 -20
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +65 -9
  10. package/dist/index.d.ts +65 -9
  11. package/dist/index.js +280 -21
  12. package/dist/index.js.map +1 -1
  13. package/dist/react/index.cjs +133 -6
  14. package/dist/react/index.cjs.map +1 -1
  15. package/dist/react/index.d.cts +62 -3
  16. package/dist/react/index.d.ts +62 -3
  17. package/dist/react/index.js +131 -8
  18. package/dist/react/index.js.map +1 -1
  19. package/dist/resources/auth.cjs +36 -11
  20. package/dist/resources/auth.cjs.map +1 -1
  21. package/dist/resources/auth.d.cts +57 -5
  22. package/dist/resources/auth.d.ts +57 -5
  23. package/dist/resources/auth.js +36 -11
  24. package/dist/resources/auth.js.map +1 -1
  25. package/dist/resources/balance.d.cts +1 -1
  26. package/dist/resources/balance.d.ts +1 -1
  27. package/dist/resources/blog.d.cts +1 -1
  28. package/dist/resources/blog.d.ts +1 -1
  29. package/dist/resources/branding.d.cts +1 -1
  30. package/dist/resources/branding.d.ts +1 -1
  31. package/dist/resources/cards.cjs +33 -1
  32. package/dist/resources/cards.cjs.map +1 -1
  33. package/dist/resources/cards.d.cts +111 -4
  34. package/dist/resources/cards.d.ts +111 -4
  35. package/dist/resources/cards.js +33 -1
  36. package/dist/resources/cards.js.map +1 -1
  37. package/dist/resources/deposits.d.cts +1 -1
  38. package/dist/resources/deposits.d.ts +1 -1
  39. package/dist/resources/devices.cjs +92 -0
  40. package/dist/resources/devices.cjs.map +1 -0
  41. package/dist/resources/devices.d.cts +3 -0
  42. package/dist/resources/devices.d.ts +3 -0
  43. package/dist/resources/devices.js +89 -0
  44. package/dist/resources/devices.js.map +1 -0
  45. package/dist/resources/me.cjs +32 -0
  46. package/dist/resources/me.cjs.map +1 -0
  47. package/dist/resources/me.d.cts +40 -0
  48. package/dist/resources/me.d.ts +40 -0
  49. package/dist/resources/me.js +30 -0
  50. package/dist/resources/me.js.map +1 -0
  51. package/dist/resources/notifications.cjs +57 -0
  52. package/dist/resources/notifications.cjs.map +1 -0
  53. package/dist/resources/notifications.d.cts +133 -0
  54. package/dist/resources/notifications.d.ts +133 -0
  55. package/dist/resources/notifications.js +54 -0
  56. package/dist/resources/notifications.js.map +1 -0
  57. package/dist/resources/push.cjs +8 -4
  58. package/dist/resources/push.cjs.map +1 -1
  59. package/dist/resources/push.d.cts +14 -17
  60. package/dist/resources/push.d.ts +14 -17
  61. package/dist/resources/push.js +8 -4
  62. package/dist/resources/push.js.map +1 -1
  63. package/dist/resources/sessions.d.cts +1 -1
  64. package/dist/resources/sessions.d.ts +1 -1
  65. package/dist/resources/subscriptions.cjs.map +1 -1
  66. package/dist/resources/subscriptions.d.cts +8 -1
  67. package/dist/resources/subscriptions.d.ts +8 -1
  68. package/dist/resources/subscriptions.js.map +1 -1
  69. package/dist/resources/wallet.d.cts +1 -1
  70. package/dist/resources/wallet.d.ts +1 -1
  71. package/dist/telegram.cjs +321 -23
  72. package/dist/telegram.cjs.map +1 -1
  73. package/dist/telegram.d.cts +62 -7
  74. package/dist/telegram.d.ts +62 -7
  75. package/dist/telegram.js +320 -24
  76. package/dist/telegram.js.map +1 -1
  77. package/package.json +23 -4
package/CHANGELOG.md CHANGED
@@ -4,6 +4,106 @@ All notable changes to `@takeal/cusfront-sdk` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.3.7] — 2026-09-16
8
+
9
+ Checked against platform `v0.3.7` (API `0.3.6`, nothing in the end-user
10
+ surface changed between the two).
11
+
12
+ ### Added
13
+
14
+ - `CardDesignRef.image_url_back`: the back of the card, when the design has
15
+ one (`null` or absent for a one-sided design — show the front on both
16
+ sides). The default design's back is `/card-designs/default.svg?side=back`.
17
+ Pass it through `client.assetUrl()` like `image_url`.
18
+ - `CardOtpData` and `isCardOtp(item)` for the `card_otp` inbox item: the
19
+ confirmation code the issuer sent for a 3-D Secure payment (`purpose:
20
+ "payment"`) or for adding the card to Apple Pay / Google Pay (`purpose:
21
+ "wallet"`), with the merchant, amount, card last four and
22
+ `expires_in_minutes`.
23
+
24
+ ### Changed
25
+
26
+ - Types regenerated from the `v0.3.6` API: card designs are two-sided and
27
+ WebP only; `PATCH /me/cards/{id}` also accepts the designs a deployment
28
+ offers on every product. `client.cards.update(id, { designId })` is the
29
+ helper for that; there is no reissue.
30
+
31
+ ## [0.3.0] — 2026-09-15
32
+
33
+ ### Added
34
+
35
+ - `client.notifications` (sub-export `@takeal/cusfront-sdk/notifications`):
36
+ the inbox and notification preferences. `list({ cursor?, limit?,
37
+ unreadOnly?, category? })`, `unreadCount()`, `markRead(id)`,
38
+ `markAllRead(before?)`, `remove(id)`, `getPreferences()` and
39
+ `setPreferences({ primary_channel?, categories?, locale? })`. Types
40
+ `InboxItem`, `NotificationPage`, `NotificationPreferences`,
41
+ `NotificationCategory`, `NotificationChannel`.
42
+ - `client.devices` (sub-export `@takeal/cusfront-sdk/devices`): `list()`,
43
+ `register(input)`, `remove(id)`, plus `registerWebPush(registration,
44
+ { label?, vapidPublicKey? })` and `unregisterWebPush(registration,
45
+ { deviceId? })`, which subscribe or unsubscribe the browser and keep the
46
+ device list in step. Types `Device`, `DeviceKind`, `DevicePlatform`,
47
+ `RegisterDeviceInput`, `RegisteredDevice`.
48
+ - `createClient({ client: { platform, version? } })`. Every request now
49
+ carries `X-Takeal-Client: <platform>; <version>`. `platform` is detected
50
+ when omitted (`telegram-miniapp` inside Telegram, `pwa` when installed,
51
+ `web` otherwise); `version` defaults to the SDK version. The resolved
52
+ descriptor is readable as `client.client`; `SDK_VERSION`,
53
+ `detectClientPlatform` and `CLIENT_HEADER` are exported from the root.
54
+ - `@takeal/cusfront-sdk/telegram`: the Mini App helpers announce
55
+ `telegram-miniapp` and, after a successful exchange, register the app as a
56
+ `telegram_miniapp` device (best-effort; `registerDevice: false` skips it).
57
+ - `useNotifications(opts?)` and `useUnreadCount({ pollMs? })` in
58
+ `@takeal/cusfront-sdk/react`. The badge count refreshes on an interval and
59
+ on a `{ type: "takeal:push" }` message from the service worker;
60
+ `PUSH_MESSAGE_TYPE` carries the string.
61
+
62
+ - Card catalog: `client.cards.listProducts()` and `client.cards.getProduct(id)`
63
+ return the cards a user can order (`CardProduct`: name, description, type,
64
+ currency, artwork, the designs to choose from, the issuance price after the
65
+ user's subscription discount, free-form `features`).
66
+ - `client.cards.create()` takes `productId`, `name` and `designId`; with a
67
+ `productId`, `type` is optional. `client.cards.update(id, { name?, designId? })`
68
+ renames a card or changes its design.
69
+ - `Card` gains `name`, `design` and `product`.
70
+ - `client.assetUrl(url)` and the standalone `resolveAssetUrl(baseUrl, url)`
71
+ turn the image URLs the API returns (absolute, or relative to the API origin
72
+ like the default card design) into ones a browser can load.
73
+ - `useCardProducts()` in `@takeal/cusfront-sdk/react`.
74
+ - `client.auth.exchangeTelegram()` takes `provision` (default `true`). With
75
+ `provision: false` an unknown Telegram id resolves to `{ stage: "unknown" }`
76
+ instead of creating an account, so a Mini App can ask the user whether to
77
+ create one or attach the Telegram to an account they already have.
78
+ - `client.auth.linkTelegram({ initData, email, password })` attaches the
79
+ Telegram account behind `initData` to an existing email + password account
80
+ and signs in. Same envelope as `login`; the JWT is stored.
81
+ - `client.me` (sub-export `@takeal/cusfront-sdk/me`): `linkTelegram(initData)`
82
+ and `unlinkTelegram()` for a signed-in user.
83
+ - `User.telegram` — `{ username, linked_at }` or `null`.
84
+ - `@takeal/cusfront-sdk/telegram`: `provision` in the options of
85
+ `fromInitData` / `fromTelegramWebApp`; a new `exchangeInitData()` that
86
+ returns `{ client, session }` for apps that want to branch on the outcome;
87
+ `TelegramUnknownError` (carries `initData`), thrown by `fromInitData` /
88
+ `fromTelegramWebApp` when `provision: false` is set and the Telegram id
89
+ has no account.
90
+
91
+ ### Deprecated
92
+
93
+ - `client.push` (`enable`, `disable`, `save`, `remove`, `status`): the
94
+ endpoint keeps working as an alias over Web Push devices, but new code
95
+ should call `client.devices.registerWebPush` / `unregisterWebPush`.
96
+ - `client.subscriptions`: announcement channels are now the `marketing`
97
+ category of the notification preferences. The endpoint keeps working; use
98
+ `client.notifications.setPreferences({ categories: { marketing: { ... } } })`.
99
+
100
+ ### Changed
101
+
102
+ - `exchangeTelegram()` is typed to return `JwtIssued | TelegramUnknown` when
103
+ `provision` is passed as a `boolean`. Calls without `provision` (or with
104
+ `provision: true`) keep returning `JwtIssued`, so existing code compiles
105
+ unchanged.
106
+
7
107
  ## [0.2.8] — 2026-09-13
8
108
 
9
109
  The version number now matches the Takeal platform release the SDK was
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @takeal/cusfront-sdk
2
2
 
3
- Typed TypeScript client for the **Takeal end-user API**: sign-up and login, wallet, deposits, cards, sessions, push notifications and webhook signature verification.
3
+ Typed TypeScript client for the **Takeal end-user API**: sign-up and login, wallet, deposits, cards, sessions, the notification inbox, devices and webhook signature verification.
4
4
 
5
5
  The SDK powers any end-user client app on top of a Takeal deployment: a PWA, a Capacitor-wrapped mobile app, a Telegram Mini App, or anything else that talks to the `/auth/*` + `/me/*` surface. One client, runtime brand swap, zero runtime deps in the core.
6
6
 
@@ -59,6 +59,67 @@ await client.auth.register({
59
59
  });
60
60
  ```
61
61
 
62
+ ## Choosing a card
63
+
64
+ The API publishes a catalog of the cards a user can order, and the client
65
+ walks it from the list to the issued card:
66
+
67
+ ```ts
68
+ // 1. The catalog: what the user can order, default product first.
69
+ const products = await client.cards.listProducts();
70
+
71
+ for (const p of products) {
72
+ // Artwork: `image_url` is absolute for uploaded designs and a path
73
+ // relative to the API for the deployment default. `assetUrl` handles both.
74
+ const img = client.assetUrl(p.design.image_url);
75
+
76
+ // Price after the user's subscription discount; `null` means free.
77
+ const price = p.price
78
+ ? p.price.discount_bps > 0
79
+ ? `${p.price.amount} ${p.price.currency} (was ${p.price.base_amount}, ${p.price.discount_bps / 100}% off)`
80
+ : `${p.price.amount} ${p.price.currency}`
81
+ : "free";
82
+
83
+ console.log(p.name, p.card_type, p.currency, price, img, p.description);
84
+ }
85
+
86
+ // 2. Issue from a product. `type` and `issuer_slug` are no longer needed:
87
+ // the product settles both. The user picks a name and, when the product
88
+ // offers a choice, one of `p.designs`.
89
+ const product = products.find((p) => p.is_default) ?? products[0];
90
+ const card = await client.cards.create({
91
+ productId: product.id,
92
+ name: "Groceries",
93
+ designId: product.designs[0]?.id ?? null, // null = the product's default design
94
+ initial_amount: "50.00",
95
+ currency: product.currency ?? "USD",
96
+ idempotencyKey: crypto.randomUUID(),
97
+ customer: { email: "user@example.com", first_name: "Alice", last_name: "Tester" },
98
+ });
99
+
100
+ // The card carries what was chosen.
101
+ card.name; // "Groceries"
102
+ client.assetUrl(card.design.image_url); // ready for <img src>
103
+ card.product; // { id, name } or null for older cards
104
+
105
+ // 3. Rename or change the design later.
106
+ await client.cards.update(card.id, { name: "Coffee" });
107
+ await client.cards.update(card.id, { designId: null });
108
+ ```
109
+
110
+ `cards.getProduct(id)` fetches one entry. `product.features` is a free-form
111
+ object the operator fills in (payment scheme, wallet support, load limits and
112
+ so on), so read the keys you need and ignore the rest. Names are 1 to 40
113
+ characters; a design outside the product's `designs` and an unknown or hidden
114
+ product are rejected with a 400 whose `code` says which check failed
115
+ (`invalid_name`, `design_not_allowed`, `unknown_product`, `product_mismatch`).
116
+
117
+ Calls without `productId` keep working as before: `type` is then required and
118
+ the deployment picks the product.
119
+
120
+ `resolveAssetUrl(baseUrl, url)` is the same helper as a standalone function,
121
+ exported from the package root, for code that has no client at hand.
122
+
62
123
  ## Telegram Mini App
63
124
 
64
125
  Run inside a Telegram Mini App? Exchange the Telegram-signed `initData` for a
@@ -103,11 +164,272 @@ How it works end-to-end:
103
164
  4. First-time Telegram users are **auto-provisioned**. They have no email yet, so
104
165
  `me.email_pending === true` — prompt for an address and call
105
166
  `client.auth.linkEmail` to clear it.
167
+ 5. Once signed in, the Mini App registers itself as a `telegram_miniapp`
168
+ device, so the user's notifications arrive as messages from the bot. A
169
+ failure here is logged as a warning and never blocks the sign-in; pass
170
+ `{ registerDevice: false }` to skip it. The client also announces itself as
171
+ `telegram-miniapp` in `X-Takeal-Client` (see [Client platform](#client-platform-x-takeal-client)).
106
172
 
107
173
  For the lower-level call returning the raw session envelope (including
108
174
  `email_pending`), use `client.auth.exchangeTelegram({ initData })` on a client
109
175
  you built yourself.
110
176
 
177
+ ### "I already have an account"
178
+
179
+ By default an unknown Telegram id gets a fresh account. That's wrong for a user
180
+ who signed up on the website with an email and a password and then opens the
181
+ Mini App: they'd end up with a second, empty account. Pass `provision: false`
182
+ to find out first, then let the user choose:
183
+
184
+ ```ts
185
+ import {
186
+ fromTelegramWebApp,
187
+ TelegramUnknownError,
188
+ } from "@takeal/cusfront-sdk/telegram";
189
+ import { createClient } from "@takeal/cusfront-sdk";
190
+
191
+ const config = { baseUrl: "https://api.your-deployment.example.com" };
192
+
193
+ try {
194
+ // Known Telegram → signed-in client, as before.
195
+ const client = await fromTelegramWebApp(config, { provision: false });
196
+ } catch (e) {
197
+ if (!(e instanceof TelegramUnknownError)) throw e;
198
+
199
+ // Nobody has signed in with this Telegram yet. Nothing was created.
200
+ const client = createClient(config);
201
+ const choice = await askUser(); // "create" | "link"
202
+
203
+ if (choice === "create") {
204
+ // Same as the default flow: a new account, email_pending === true.
205
+ await client.auth.exchangeTelegram({ initData: e.initData, provision: true });
206
+ } else {
207
+ // Attach this Telegram to the existing email + password account.
208
+ const { email, password } = await askCredentials();
209
+ await client.auth.linkTelegram({ initData: e.initData, email, password });
210
+ }
211
+ // client is signed in either way.
212
+ }
213
+ ```
214
+
215
+ If you'd rather branch on a value than catch an error, `exchangeInitData`
216
+ returns both the client and the outcome:
217
+
218
+ ```ts
219
+ import { exchangeInitData, readWebAppInitData } from "@takeal/cusfront-sdk/telegram";
220
+
221
+ const initData = readWebAppInitData()!;
222
+ const { client, session } = await exchangeInitData(initData, config, { provision: false });
223
+ if (session.stage === "unknown") {
224
+ // client has no session yet; call client.auth.linkTelegram or
225
+ // client.auth.exchangeTelegram({ initData, provision: true }).
226
+ }
227
+ ```
228
+
229
+ `linkTelegram` checks the password the same way `login` does and returns the
230
+ same `stage: "jwt"` envelope. On the next launch the plain exchange finds the
231
+ link and signs the user straight in. Errors to expect:
232
+
233
+ - `401 unauthenticated` — wrong email or password.
234
+ - `403 second_factor_required` — the account signs in with a second factor;
235
+ such accounts can't be linked from a Mini App.
236
+ - `409 telegram_already_linked_other` — the account already has a different
237
+ Telegram. Unlink it first.
238
+ - `409 telegram_in_use` — this Telegram already belongs to another account
239
+ that has been used. A Telegram can be attached to one account only, and the
240
+ API does not merge accounts.
241
+
242
+ Two more calls for a signed-in user:
243
+
244
+ ```ts
245
+ // Attach Telegram to the current session (e.g. the Mini App was opened
246
+ // through a deep link that already carried a session):
247
+ await client.me.linkTelegram(window.Telegram.WebApp.initData);
248
+
249
+ // Detach it. Refused with 409 `last_credential` when the account has no
250
+ // password, because Telegram would be its only way to sign in.
251
+ await client.me.unlinkTelegram();
252
+ ```
253
+
254
+ The user object (`client.auth.me()` and the `user` in every `stage: "jwt"`
255
+ envelope) carries the state, so a settings screen needs no extra request:
256
+
257
+ ```ts
258
+ type User = {
259
+ // ...
260
+ telegram: { username: string | null; linked_at: string } | null;
261
+ };
262
+ ```
263
+
264
+ ## Notifications (inbox)
265
+
266
+ Everything the API tells a user (a confirmed deposit, a card transaction, a
267
+ sign-in from a new device) is kept as an inbox item, whatever else was sent
268
+ as a nudge (a push, a Telegram message, an email). The inbox is what your app
269
+ shows; `client.notifications` reads it.
270
+
271
+ ```ts
272
+ const page = await client.notifications.list({ limit: 20 });
273
+ // page.items (newest first), page.next_cursor, page.unread_count
274
+
275
+ const more = await client.notifications.list({ cursor: page.next_cursor! });
276
+ const onlyMoney = await client.notifications.list({ unreadOnly: true, category: "money" });
277
+
278
+ await client.notifications.markRead(page.items[0].id);
279
+ await client.notifications.markAllRead(); // or markAllRead(isoTimestamp)
280
+ await client.notifications.remove(page.items[1].id);
281
+ const badge = await client.notifications.unreadCount();
282
+ ```
283
+
284
+ An item has `title`, `body`, a `category` (`money`, `card`, `security`,
285
+ `account`, `marketing`), `read_at` (`null` while unread), free-form `data`
286
+ about the event, and `href`: a path inside your app to open on tap
287
+ (`/cards/<id>`, `/deposits/<id>`, `/subscription`, `/settings/sessions`) or
288
+ `null`. Route `href` through your own router; the SDK doesn't navigate.
289
+
290
+ A small inbox screen:
291
+
292
+ ```tsx
293
+ function Inbox() {
294
+ const [page, setPage] = useState<NotificationPage | null>(null);
295
+ useEffect(() => { client.notifications.list({ limit: 20 }).then(setPage); }, []);
296
+ if (!page) return <Spinner />;
297
+ return (
298
+ <ul>
299
+ {page.items.map((n) => (
300
+ <li key={n.id} className={n.read_at ? "" : "unread"}
301
+ onClick={async () => { await client.notifications.markRead(n.id); if (n.href) router.push(n.href); }}>
302
+ <strong>{n.title}</strong>
303
+ <p>{n.body}</p>
304
+ </li>
305
+ ))}
306
+ </ul>
307
+ );
308
+ }
309
+ ```
310
+
311
+ (The React entry has `useNotifications()` and `useUnreadCount()`, which do the
312
+ state handling for you; see [React hooks](#react-hooks-takealcusfront-sdkreact).)
313
+
314
+ ### Preferences
315
+
316
+ Where the nudge goes is up to the user:
317
+
318
+ ```ts
319
+ const prefs = await client.notifications.getPreferences();
320
+ // prefs.primary_channel: "push" | "telegram" | "email" | "sms" | null (automatic)
321
+ // prefs.categories: { money: { push: true, email: false }, ... }
322
+ // prefs.locale: "en" | "ru" | null
323
+ // prefs.available_channels: what this deployment can deliver on; render toggles only for these
324
+
325
+ await client.notifications.setPreferences({
326
+ primary_channel: "telegram",
327
+ categories: { marketing: { email: true, telegram: false } },
328
+ locale: "ru",
329
+ });
330
+ ```
331
+
332
+ Every field of `setPreferences` is optional; only what you pass changes.
333
+ `primary_channel: null` goes back to automatic (the server picks by the user's
334
+ devices). `security` and `money` can't be switched off completely: the inbox
335
+ always gets them and at least one outward channel stays on. `marketing` is off
336
+ until the user opts in. A `locale` of `null` means "use the language of the
337
+ Telegram profile, else the deployment's default".
338
+
339
+ `client.subscriptions` (announcement channels) is deprecated: it now reads and
340
+ writes `categories.marketing` and keeps working, but new code should use
341
+ `setPreferences({ categories: { marketing: { ... } } })`.
342
+
343
+ ## Devices
344
+
345
+ A user has many devices: each browser with a Web Push subscription, each phone
346
+ with an FCM or APNs token, and a marker that says "uses the Telegram Mini App".
347
+ The server picks where a notification goes from them: a mobile app first,
348
+ otherwise the device seen most recently. What each platform can receive:
349
+
350
+ | Platform | Outward channel | Inbox |
351
+ |---|---|---|
352
+ | PWA / browser | Web Push | yes |
353
+ | Telegram Mini App | messages from the bot (no Web Push) | yes |
354
+ | iOS / Android app | FCM / APNs (tokens are accepted now; delivery comes later) | yes |
355
+
356
+ Web Push in a browser, once notification permission is granted:
357
+
358
+ ```ts
359
+ const reg = await navigator.serviceWorker.ready;
360
+ if ((await Notification.requestPermission()) === "granted") {
361
+ const device = await client.devices.registerWebPush(reg, { label: "Chrome on Mac" });
362
+ // device.id, device.vapid_public_key
363
+ }
364
+
365
+ // Settings screen, later:
366
+ await client.devices.unregisterWebPush(reg); // this session's Web Push devices
367
+ await client.devices.unregisterWebPush(reg, { deviceId }); // or exactly one
368
+ ```
369
+
370
+ `registerWebPush` fetches the deployment's VAPID key, subscribes the browser
371
+ and registers the subscription as a `webpush` device on the client's platform
372
+ (`pwa` or `web`). It throws when push isn't set up on the deployment. Pass
373
+ `vapidPublicKey` in the options to skip the key lookup when you already hold it.
374
+
375
+ Anything else goes through `register` / `list` / `remove`:
376
+
377
+ ```ts
378
+ // A native app with a push token:
379
+ await client.devices.register({ kind: "fcm", platform: "android", credential: { token }, app_version: "1.4.0" });
380
+ // A Telegram Mini App (done for you by @takeal/cusfront-sdk/telegram):
381
+ await client.devices.register({ kind: "telegram_miniapp", platform: "telegram", credential: {} });
382
+
383
+ const devices = await client.devices.list(); // is_current marks the ones from this session
384
+ await client.devices.remove(devices[0].id);
385
+ ```
386
+
387
+ Registering the same credential twice refreshes the device (and re-enables a
388
+ disabled one) instead of creating another. `app_version` defaults to the
389
+ version in `X-Takeal-Client`.
390
+
391
+ `client.push` (`enable`, `disable`, `save`, `remove`, `status`) is deprecated.
392
+ The endpoint behind it keeps working as an alias over Web Push devices, but
393
+ new code should use `devices.registerWebPush` / `devices.unregisterWebPush`.
394
+
395
+ Your service worker shows the notification; the payload is JSON with `title`,
396
+ `body` and `url`. To keep an open tab's badge fresh, also post a message to
397
+ the open clients:
398
+
399
+ ```js
400
+ self.addEventListener("push", (event) => {
401
+ const payload = event.data.json();
402
+ event.waitUntil(Promise.all([
403
+ self.registration.showNotification(payload.title, { body: payload.body, data: { url: payload.url } }),
404
+ self.clients.matchAll({ type: "window" }).then((clients) =>
405
+ clients.forEach((c) => c.postMessage({ type: "takeal:push" }))),
406
+ ]));
407
+ });
408
+ ```
409
+
410
+ ## Client platform (`X-Takeal-Client`)
411
+
412
+ Every request carries `X-Takeal-Client: <platform>; <version>`, for example
413
+ `pwa; 0.3.0` or `telegram-miniapp; 0.2.8`. The server stores it on the session
414
+ and uses it to notice a sign-in from a new device and to choose the
415
+ notification channel. Set it with the `client` option:
416
+
417
+ ```ts
418
+ const client = createClient({
419
+ baseUrl: "https://api.your-deployment.example.com",
420
+ client: { platform: "ios", version: "1.4.0" },
421
+ });
422
+ client.client; // { platform: "ios", version: "1.4.0" }
423
+ ```
424
+
425
+ `platform` is one of `pwa`, `web`, `telegram-miniapp`, `ios`, `android`.
426
+ When you leave the option out, the SDK detects it: `telegram-miniapp` when
427
+ `window.Telegram.WebApp.initData` is present, `pwa` when the page runs
428
+ installed (`navigator.standalone` or a `display-mode: standalone` media
429
+ query), `web` otherwise and on any non-browser runtime. Native wrappers
430
+ (Capacitor, React Native) can't be told apart from a browser, so pass `ios`
431
+ or `android` yourself. `version` defaults to the SDK version (`SDK_VERSION`).
432
+
111
433
  ## Brand config
112
434
 
113
435
  Whitelabel-friendly by design — the SDK ships no embedded brand. Pass `brand` at runtime and the client app reads it back via `client.brand`:
@@ -148,12 +470,15 @@ Available now:
148
470
  - `@takeal/cusfront-sdk/cards` — `CardsResource` (cards backed by the wallet balance).
149
471
  - `@takeal/cusfront-sdk/balance` — `BalanceResource` (per-currency wallet balance).
150
472
  - `@takeal/cusfront-sdk/blog` — `BlogResource` (public posts as structured blocks).
151
- - `@takeal/cusfront-sdk/subscriptions` — `SubscriptionsResource` (announcement channels).
473
+ - `@takeal/cusfront-sdk/subscriptions` — `SubscriptionsResource` (announcement channels; deprecated, see [Preferences](#preferences)).
152
474
  - `@takeal/cusfront-sdk/wallet` — `WalletResource` (the wallet's currency).
153
475
  - `@takeal/cusfront-sdk/sessions` — `SessionsResource` (where the user is signed in).
154
- - `@takeal/cusfront-sdk/push` — `PushResource` (Web Push subscription).
476
+ - `@takeal/cusfront-sdk/push` — `PushResource` (Web Push subscription; deprecated, see [Devices](#devices)).
477
+ - `@takeal/cusfront-sdk/notifications` — `NotificationsResource` (the inbox and notification preferences).
478
+ - `@takeal/cusfront-sdk/devices` — `DevicesResource` (Web Push, mobile push tokens, the Telegram Mini App marker).
479
+ - `@takeal/cusfront-sdk/me` — `MeResource` (link or unlink Telegram for the signed-in user).
155
480
  - `@takeal/cusfront-sdk/webhooks` — HMAC-SHA256 signature verifier (no network, isomorphic).
156
- - `@takeal/cusfront-sdk/react` — optional React hooks layer (`ClientProvider` + `useMe` / `useDeposits` / `useCards` / `useBalance`). React is a `peerDependency`, never bundled.
481
+ - `@takeal/cusfront-sdk/react` — optional React hooks layer (`ClientProvider` + `useMe` / `useDeposits` / `useCards` / `useCardProducts` / `useBalance` / `useNotifications` / `useUnreadCount`). React is a `peerDependency`, never bundled.
157
482
  - `@takeal/cusfront-sdk/telegram` — Telegram Mini App `initData` → authenticated client bridge.
158
483
 
159
484
  ### Verifying webhooks
@@ -179,7 +504,8 @@ the raw body bytes (no timestamp). Comparison is constant-time.
179
504
  > **Card details:** `client.cards.reveal()` returns the full card number and
180
505
  > CVV. It asks for the user's password again (and a TOTP code if they have one
181
506
  > enrolled), and the API rate-limits and logs every call. The rest of
182
- > `client.cards` is create, get, list, balance, freeze, unfreeze and terminate.
507
+ > `client.cards` is listProducts, getProduct, create, get, list, update,
508
+ > balance, freeze, unfreeze and terminate.
183
509
 
184
510
  ## React hooks (`@takeal/cusfront-sdk/react`)
185
511
 
@@ -229,8 +555,44 @@ Every hook returns the same shape — `{ data, error, loading, refetch }`:
229
555
  - `useMe()` — current authenticated user (`client.auth.me()`).
230
556
  - `useDeposits()` — the user's deposits (`client.deposits.list()`).
231
557
  - `useCards()` — the user's cards (`client.cards.list()`).
558
+ - `useCardProducts()` — the cards the user can order (`client.cards.listProducts()`).
232
559
  - `useBalance(currency)` — wallet balance for one currency
233
560
  (`client.balance.get(currency)`); re-fetches when `currency` changes.
561
+ - `useUnreadCount({ pollMs? })` — unread inbox items for a badge
562
+ (`client.notifications.unreadCount()`). Refreshes in the background every
563
+ `pollMs` (default 30000; `0` turns polling off) and whenever the page's
564
+ service worker posts `{ type: "takeal:push" }` (see [Devices](#devices)),
565
+ without flipping `loading`.
566
+
567
+ `useNotifications({ unreadOnly?, category?, limit? })` returns the same shape
568
+ plus `markRead(id)`, `markAllRead()`, `loadMore()` and `loadingMore`.
569
+ `loadMore` fetches the next page by `next_cursor` and appends its items to
570
+ `data.items`; the two mark helpers update `data` right away so the list
571
+ doesn't flicker.
572
+
573
+ ```tsx
574
+ function Inbox() {
575
+ const inbox = useNotifications({ limit: 20 });
576
+ const unread = useUnreadCount();
577
+
578
+ if (inbox.loading) return <Spinner />;
579
+ if (inbox.error) return <ErrorBanner onRetry={inbox.refetch} />;
580
+ return (
581
+ <>
582
+ <h2>Inbox {unread.data ? `(${unread.data})` : ""}</h2>
583
+ <button onClick={() => void inbox.markAllRead()}>Mark all read</button>
584
+ {inbox.data!.items.map((n) => (
585
+ <Row key={n.id} unread={!n.read_at} onClick={() => void inbox.markRead(n.id)}>
586
+ {n.title}
587
+ </Row>
588
+ ))}
589
+ {inbox.data!.next_cursor && (
590
+ <button disabled={inbox.loadingMore} onClick={() => void inbox.loadMore()}>More</button>
591
+ )}
592
+ </>
593
+ );
594
+ }
595
+ ```
234
596
 
235
597
  `useClient()` exposes the raw client from context for one-off writes
236
598
  (e.g. `client.deposits.initiate(...)`) — it throws a clear error if called