@takeal/cusfront-sdk 0.2.8 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +76 -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 +280 -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 +277 -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 +105 -4
  34. package/dist/resources/cards.d.ts +105 -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 +53 -0
  52. package/dist/resources/notifications.cjs.map +1 -0
  53. package/dist/resources/notifications.d.cts +109 -0
  54. package/dist/resources/notifications.d.ts +109 -0
  55. package/dist/resources/notifications.js +51 -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 +17 -2
package/CHANGELOG.md CHANGED
@@ -4,6 +4,82 @@ 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.0] — 2026-09-15
8
+
9
+ ### Added
10
+
11
+ - `client.notifications` (sub-export `@takeal/cusfront-sdk/notifications`):
12
+ the inbox and notification preferences. `list({ cursor?, limit?,
13
+ unreadOnly?, category? })`, `unreadCount()`, `markRead(id)`,
14
+ `markAllRead(before?)`, `remove(id)`, `getPreferences()` and
15
+ `setPreferences({ primary_channel?, categories?, locale? })`. Types
16
+ `InboxItem`, `NotificationPage`, `NotificationPreferences`,
17
+ `NotificationCategory`, `NotificationChannel`.
18
+ - `client.devices` (sub-export `@takeal/cusfront-sdk/devices`): `list()`,
19
+ `register(input)`, `remove(id)`, plus `registerWebPush(registration,
20
+ { label?, vapidPublicKey? })` and `unregisterWebPush(registration,
21
+ { deviceId? })`, which subscribe or unsubscribe the browser and keep the
22
+ device list in step. Types `Device`, `DeviceKind`, `DevicePlatform`,
23
+ `RegisterDeviceInput`, `RegisteredDevice`.
24
+ - `createClient({ client: { platform, version? } })`. Every request now
25
+ carries `X-Takeal-Client: <platform>; <version>`. `platform` is detected
26
+ when omitted (`telegram-miniapp` inside Telegram, `pwa` when installed,
27
+ `web` otherwise); `version` defaults to the SDK version. The resolved
28
+ descriptor is readable as `client.client`; `SDK_VERSION`,
29
+ `detectClientPlatform` and `CLIENT_HEADER` are exported from the root.
30
+ - `@takeal/cusfront-sdk/telegram`: the Mini App helpers announce
31
+ `telegram-miniapp` and, after a successful exchange, register the app as a
32
+ `telegram_miniapp` device (best-effort; `registerDevice: false` skips it).
33
+ - `useNotifications(opts?)` and `useUnreadCount({ pollMs? })` in
34
+ `@takeal/cusfront-sdk/react`. The badge count refreshes on an interval and
35
+ on a `{ type: "takeal:push" }` message from the service worker;
36
+ `PUSH_MESSAGE_TYPE` carries the string.
37
+
38
+ - Card catalog: `client.cards.listProducts()` and `client.cards.getProduct(id)`
39
+ return the cards a user can order (`CardProduct`: name, description, type,
40
+ currency, artwork, the designs to choose from, the issuance price after the
41
+ user's subscription discount, free-form `features`).
42
+ - `client.cards.create()` takes `productId`, `name` and `designId`; with a
43
+ `productId`, `type` is optional. `client.cards.update(id, { name?, designId? })`
44
+ renames a card or changes its design.
45
+ - `Card` gains `name`, `design` and `product`.
46
+ - `client.assetUrl(url)` and the standalone `resolveAssetUrl(baseUrl, url)`
47
+ turn the image URLs the API returns (absolute, or relative to the API origin
48
+ like the default card design) into ones a browser can load.
49
+ - `useCardProducts()` in `@takeal/cusfront-sdk/react`.
50
+ - `client.auth.exchangeTelegram()` takes `provision` (default `true`). With
51
+ `provision: false` an unknown Telegram id resolves to `{ stage: "unknown" }`
52
+ instead of creating an account, so a Mini App can ask the user whether to
53
+ create one or attach the Telegram to an account they already have.
54
+ - `client.auth.linkTelegram({ initData, email, password })` attaches the
55
+ Telegram account behind `initData` to an existing email + password account
56
+ and signs in. Same envelope as `login`; the JWT is stored.
57
+ - `client.me` (sub-export `@takeal/cusfront-sdk/me`): `linkTelegram(initData)`
58
+ and `unlinkTelegram()` for a signed-in user.
59
+ - `User.telegram` — `{ username, linked_at }` or `null`.
60
+ - `@takeal/cusfront-sdk/telegram`: `provision` in the options of
61
+ `fromInitData` / `fromTelegramWebApp`; a new `exchangeInitData()` that
62
+ returns `{ client, session }` for apps that want to branch on the outcome;
63
+ `TelegramUnknownError` (carries `initData`), thrown by `fromInitData` /
64
+ `fromTelegramWebApp` when `provision: false` is set and the Telegram id
65
+ has no account.
66
+
67
+ ### Deprecated
68
+
69
+ - `client.push` (`enable`, `disable`, `save`, `remove`, `status`): the
70
+ endpoint keeps working as an alias over Web Push devices, but new code
71
+ should call `client.devices.registerWebPush` / `unregisterWebPush`.
72
+ - `client.subscriptions`: announcement channels are now the `marketing`
73
+ category of the notification preferences. The endpoint keeps working; use
74
+ `client.notifications.setPreferences({ categories: { marketing: { ... } } })`.
75
+
76
+ ### Changed
77
+
78
+ - `exchangeTelegram()` is typed to return `JwtIssued | TelegramUnknown` when
79
+ `provision` is passed as a `boolean`. Calls without `provision` (or with
80
+ `provision: true`) keep returning `JwtIssued`, so existing code compiles
81
+ unchanged.
82
+
7
83
  ## [0.2.8] — 2026-09-13
8
84
 
9
85
  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
@@ -0,0 +1,165 @@
1
+ import { H as HttpClient } from './http-B-OQwMYn.cjs';
2
+ import { PushCapableRegistration } from './resources/push.cjs';
3
+
4
+ /**
5
+ * Which kind of app is talking to the API. Sent on every request as
6
+ * `X-Takeal-Client: <platform>; <version>`. The server keeps it on the
7
+ * session: it decides whether a sign-in counts as a new device, and which
8
+ * channel a notification goes out on (a Mini App gets Telegram messages, a
9
+ * PWA gets Web Push, and so on).
10
+ */
11
+ type ClientPlatform = "pwa" | "web" | "telegram-miniapp" | "ios" | "android";
12
+ /** The `client` option of `createClient`. */
13
+ interface ClientDescriptor {
14
+ /** What the app is. Detected at runtime when omitted; see
15
+ * {@link detectClientPlatform}. */
16
+ platform: ClientPlatform;
17
+ /** The app's own version. Defaults to the SDK version. */
18
+ version?: string;
19
+ }
20
+ /** A descriptor with every field filled in. `client.client` on a
21
+ * {@link CusfrontClient} has this shape. */
22
+ interface ResolvedClientDescriptor {
23
+ platform: ClientPlatform;
24
+ version: string;
25
+ }
26
+ /** Header name carrying the client descriptor. */
27
+ declare const CLIENT_HEADER = "X-Takeal-Client";
28
+ /**
29
+ * Best-effort platform detection for browser runtimes:
30
+ *
31
+ * - `telegram-miniapp` when `window.Telegram.WebApp.initData` is non-empty
32
+ * (the app was launched from Telegram);
33
+ * - `pwa` when the page runs installed: iOS Safari's `navigator.standalone`
34
+ * or a `display-mode: standalone` media query;
35
+ * - `web` otherwise, and always outside a browser (Node, workers without a
36
+ * `navigator`).
37
+ *
38
+ * Native wrappers (Capacitor, React Native) should pass `ios` / `android`
39
+ * explicitly; there is no reliable way to tell them apart from a browser.
40
+ */
41
+ declare function detectClientPlatform(): ClientPlatform;
42
+
43
+ /**
44
+ * Devices resource — `client.devices.*`.
45
+ *
46
+ * A user has many devices: each browser with a Web Push subscription, each
47
+ * phone with an FCM / APNs token, and a marker for "uses the Telegram Mini
48
+ * App". The server picks the notification channel from them: a mobile app
49
+ * first, otherwise the device seen most recently.
50
+ *
51
+ * The usual browser flow, once notification permission is granted:
52
+ *
53
+ * ```ts
54
+ * const reg = await navigator.serviceWorker.ready;
55
+ * const device = await client.devices.registerWebPush(reg, { label: "Chrome on Mac" });
56
+ * // later, from a settings screen:
57
+ * await client.devices.unregisterWebPush(reg);
58
+ * ```
59
+ */
60
+ type DeviceKind = "webpush" | "fcm" | "apns" | "telegram_miniapp";
61
+ type DevicePlatform = "pwa" | "web" | "ios" | "android" | "telegram";
62
+ interface Device {
63
+ id: string;
64
+ kind: DeviceKind;
65
+ platform: DevicePlatform;
66
+ /** Free-form name the app gave it ("Chrome on Mac"), or `null`. */
67
+ label: string | null;
68
+ locale: string | null;
69
+ app_version: string | null;
70
+ created_at: string;
71
+ last_seen_at: string;
72
+ /** Set when the device no longer receives anything (the push endpoint is
73
+ * gone, or someone switched it off). */
74
+ disabled_at: string | null;
75
+ /** `true` when it was registered from the session this client holds. */
76
+ is_current: boolean;
77
+ }
78
+ /** `PushSubscription.toJSON()` minus the parts the server doesn't need. */
79
+ interface WebPushCredential {
80
+ /** `PushSubscription.endpoint`; must be https. */
81
+ endpoint: string;
82
+ keys: {
83
+ /** URL-safe base64. */
84
+ p256dh: string;
85
+ /** URL-safe base64. */
86
+ auth: string;
87
+ };
88
+ }
89
+ /** FCM registration token or APNs device token. */
90
+ interface MobilePushCredential {
91
+ token: string;
92
+ }
93
+ type RegisterDeviceInput = {
94
+ kind: "webpush";
95
+ platform: DevicePlatform;
96
+ credential: WebPushCredential;
97
+ label?: string;
98
+ locale?: string;
99
+ app_version?: string;
100
+ } | {
101
+ kind: "fcm" | "apns";
102
+ platform: DevicePlatform;
103
+ credential: MobilePushCredential;
104
+ label?: string;
105
+ locale?: string;
106
+ app_version?: string;
107
+ } | {
108
+ kind: "telegram_miniapp";
109
+ platform: DevicePlatform;
110
+ /** Nothing to send: the device is a marker. */
111
+ credential: Record<string, never>;
112
+ label?: string;
113
+ locale?: string;
114
+ app_version?: string;
115
+ };
116
+ interface RegisteredDevice {
117
+ id: string;
118
+ kind: DeviceKind;
119
+ platform: DevicePlatform;
120
+ /** VAPID public key (URL-safe base64) for `pushManager.subscribe`;
121
+ * `null` when push is not set up on this deployment. */
122
+ vapid_public_key: string | null;
123
+ }
124
+ interface RegisterWebPushOptions {
125
+ /** A name to show in the user's device list ("Chrome on Mac"). */
126
+ label?: string;
127
+ /** Skip the key lookup when you already hold the deployment's VAPID
128
+ * public key (from an earlier `register` result, for example). */
129
+ vapidPublicKey?: string;
130
+ }
131
+ interface UnregisterWebPushOptions {
132
+ /** The device to delete, from an earlier `registerWebPush` result. When
133
+ * omitted, every Web Push device registered from this session goes. */
134
+ deviceId?: string;
135
+ }
136
+ /** Client platform → the platform the device list uses. */
137
+ declare function devicePlatformOf(platform: ClientPlatform): DevicePlatform;
138
+ declare class DevicesResource {
139
+ private readonly http;
140
+ private readonly client;
141
+ constructor(http: HttpClient, client: ResolvedClientDescriptor);
142
+ /** Every device the user has, disabled ones included. */
143
+ list(): Promise<Device[]>;
144
+ /** Register a device, or refresh it when the same credential is already
145
+ * known (then `last_seen_at`, `label` and `app_version` update and a
146
+ * disabled device comes back). `app_version` defaults to the client
147
+ * version sent in `X-Takeal-Client`.
148
+ *
149
+ * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the
150
+ * deployment has no VAPID keys. */
151
+ register(input: RegisterDeviceInput): Promise<RegisteredDevice>;
152
+ /** Delete one device. 404 when it isn't the user's. */
153
+ remove(id: string): Promise<void>;
154
+ /** Subscribe this browser to Web Push and register it as a device. Ask
155
+ * for notification permission before calling. Throws when push isn't
156
+ * set up on the deployment. */
157
+ registerWebPush(registration: PushCapableRegistration, opts?: RegisterWebPushOptions): Promise<RegisteredDevice>;
158
+ /** Unsubscribe this browser from Web Push and delete the matching device
159
+ * (see {@link UnregisterWebPushOptions}). Safe when nothing is
160
+ * registered. */
161
+ unregisterWebPush(registration: PushCapableRegistration, opts?: UnregisterWebPushOptions): Promise<void>;
162
+ private vapidPublicKey;
163
+ }
164
+
165
+ export { type ClientDescriptor as C, DevicesResource as D, type MobilePushCredential as M, type ResolvedClientDescriptor as R, type UnregisterWebPushOptions as U, type WebPushCredential as W, CLIENT_HEADER as a, type ClientPlatform as b, type Device as c, type DeviceKind as d, type DevicePlatform as e, type RegisterDeviceInput as f, type RegisterWebPushOptions as g, type RegisteredDevice as h, detectClientPlatform as i, devicePlatformOf as j };