@takeal/cusfront-sdk 0.1.0 → 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 (91) hide show
  1. package/CHANGELOG.md +104 -2
  2. package/README.md +393 -14
  3. package/dist/devices-C3JHi2Hi.d.cts +165 -0
  4. package/dist/devices-DP_hxwmW.d.ts +165 -0
  5. package/dist/{http-BkZZZI8K.d.cts → http-B-OQwMYn.d.cts} +13 -2
  6. package/dist/{http-BkZZZI8K.d.ts → http-B-OQwMYn.d.ts} +13 -2
  7. package/dist/index.cjs +425 -25
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +77 -8
  10. package/dist/index.d.ts +77 -8
  11. package/dist/index.js +422 -26
  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 +65 -3
  16. package/dist/react/index.d.ts +65 -3
  17. package/dist/react/index.js +131 -8
  18. package/dist/react/index.js.map +1 -1
  19. package/dist/resources/auth.cjs +73 -15
  20. package/dist/resources/auth.cjs.map +1 -1
  21. package/dist/resources/auth.d.cts +100 -9
  22. package/dist/resources/auth.d.ts +100 -9
  23. package/dist/resources/auth.js +73 -15
  24. package/dist/resources/auth.js.map +1 -1
  25. package/dist/resources/balance.cjs +4 -3
  26. package/dist/resources/balance.cjs.map +1 -1
  27. package/dist/resources/balance.d.cts +8 -9
  28. package/dist/resources/balance.d.ts +8 -9
  29. package/dist/resources/balance.js +4 -3
  30. package/dist/resources/balance.js.map +1 -1
  31. package/dist/resources/blog.d.cts +1 -1
  32. package/dist/resources/blog.d.ts +1 -1
  33. package/dist/resources/branding.cjs.map +1 -1
  34. package/dist/resources/branding.d.cts +8 -2
  35. package/dist/resources/branding.d.ts +8 -2
  36. package/dist/resources/branding.js.map +1 -1
  37. package/dist/resources/cards.cjs +33 -1
  38. package/dist/resources/cards.cjs.map +1 -1
  39. package/dist/resources/cards.d.cts +105 -4
  40. package/dist/resources/cards.d.ts +105 -4
  41. package/dist/resources/cards.js +33 -1
  42. package/dist/resources/cards.js.map +1 -1
  43. package/dist/resources/deposits.d.cts +1 -1
  44. package/dist/resources/deposits.d.ts +1 -1
  45. package/dist/resources/devices.cjs +92 -0
  46. package/dist/resources/devices.cjs.map +1 -0
  47. package/dist/resources/devices.d.cts +3 -0
  48. package/dist/resources/devices.d.ts +3 -0
  49. package/dist/resources/devices.js +89 -0
  50. package/dist/resources/devices.js.map +1 -0
  51. package/dist/resources/me.cjs +32 -0
  52. package/dist/resources/me.cjs.map +1 -0
  53. package/dist/resources/me.d.cts +40 -0
  54. package/dist/resources/me.d.ts +40 -0
  55. package/dist/resources/me.js +30 -0
  56. package/dist/resources/me.js.map +1 -0
  57. package/dist/resources/notifications.cjs +53 -0
  58. package/dist/resources/notifications.cjs.map +1 -0
  59. package/dist/resources/notifications.d.cts +109 -0
  60. package/dist/resources/notifications.d.ts +109 -0
  61. package/dist/resources/notifications.js +51 -0
  62. package/dist/resources/notifications.js.map +1 -0
  63. package/dist/resources/push.cjs +65 -0
  64. package/dist/resources/push.cjs.map +1 -0
  65. package/dist/resources/push.d.cts +76 -0
  66. package/dist/resources/push.d.ts +76 -0
  67. package/dist/resources/push.js +62 -0
  68. package/dist/resources/push.js.map +1 -0
  69. package/dist/resources/sessions.cjs +26 -0
  70. package/dist/resources/sessions.cjs.map +1 -0
  71. package/dist/resources/sessions.d.cts +43 -0
  72. package/dist/resources/sessions.d.ts +43 -0
  73. package/dist/resources/sessions.js +24 -0
  74. package/dist/resources/sessions.js.map +1 -0
  75. package/dist/resources/subscriptions.cjs.map +1 -1
  76. package/dist/resources/subscriptions.d.cts +8 -1
  77. package/dist/resources/subscriptions.d.ts +8 -1
  78. package/dist/resources/subscriptions.js.map +1 -1
  79. package/dist/resources/wallet.cjs +24 -0
  80. package/dist/resources/wallet.cjs.map +1 -0
  81. package/dist/resources/wallet.d.cts +39 -0
  82. package/dist/resources/wallet.d.ts +39 -0
  83. package/dist/resources/wallet.js +22 -0
  84. package/dist/resources/wallet.js.map +1 -0
  85. package/dist/telegram.cjs +466 -28
  86. package/dist/telegram.cjs.map +1 -1
  87. package/dist/telegram.d.cts +65 -7
  88. package/dist/telegram.d.ts +65 -7
  89. package/dist/telegram.js +465 -29
  90. package/dist/telegram.js.map +1 -1
  91. package/package.json +37 -3
package/dist/telegram.js CHANGED
@@ -17,13 +17,26 @@ var NetworkError = class extends Error {
17
17
  this.name = "NetworkError";
18
18
  }
19
19
  };
20
+ function isApiError(e) {
21
+ return typeof e === "object" && e !== null && e.isApiError === true;
22
+ }
20
23
 
21
24
  // src/http.ts
25
+ var API_VERSION = "/v1";
26
+ var UNVERSIONED = /* @__PURE__ */ new Set(["/health", "/ready", "/branding", "/favicon.ico"]);
27
+ function versionedPath(path) {
28
+ const p = path.startsWith("/") ? path : `/${path}`;
29
+ const bare = p.split("?")[0];
30
+ if (UNVERSIONED.has(bare)) return p;
31
+ if (bare === API_VERSION || bare.startsWith(`${API_VERSION}/`)) return p;
32
+ return `${API_VERSION}${p}`;
33
+ }
22
34
  var HttpClient = class {
23
- constructor(baseUrl, tokens, fetchImpl) {
35
+ constructor(baseUrl, tokens, fetchImpl, defaultHeaders = {}) {
24
36
  this.baseUrl = baseUrl;
25
37
  this.tokens = tokens;
26
38
  this.fetchImpl = fetchImpl;
39
+ this.defaultHeaders = defaultHeaders;
27
40
  if (!baseUrl) throw new Error("HttpClient: baseUrl is required");
28
41
  }
29
42
  async get(path, opts = {}) {
@@ -44,7 +57,8 @@ var HttpClient = class {
44
57
  async request(method, path, opts) {
45
58
  const url = this.absolute(path);
46
59
  const headers = {
47
- Accept: "application/json"
60
+ Accept: "application/json",
61
+ ...this.defaultHeaders
48
62
  };
49
63
  if (opts.body !== void 0) headers["Content-Type"] = "application/json";
50
64
  if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
@@ -75,8 +89,7 @@ var HttpClient = class {
75
89
  absolute(path) {
76
90
  if (path.startsWith("http://") || path.startsWith("https://")) return path;
77
91
  const base = this.baseUrl.replace(/\/+$/, "");
78
- const tail = path.startsWith("/") ? path : `/${path}`;
79
- return `${base}${tail}`;
92
+ return `${base}${versionedPath(path)}`;
80
93
  }
81
94
  };
82
95
  async function parseResponse(resp) {
@@ -141,6 +154,40 @@ var AuthResource = class {
141
154
  await Promise.resolve(this.tokens.set(resp.access_token));
142
155
  return resp;
143
156
  }
157
+ /** Create an end-user account and sign it in. The JWT is stored.
158
+ * `wallet_currency` must be one the deployment offers; omit it to take
159
+ * the deployment default (it can be switched later via `client.wallet`
160
+ * while the wallet is empty).
161
+ * Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */
162
+ async register(input) {
163
+ const resp = await this.http.post("/auth/register", {
164
+ body: input,
165
+ skipAuth: true
166
+ });
167
+ await Promise.resolve(this.tokens.set(resp.access_token));
168
+ return resp;
169
+ }
170
+ /** Finish a `totp_setup_required` login: send the first code from the
171
+ * authenticator app. The JWT is stored. The response carries ten
172
+ * one-time `backup_codes` that are never returned again, so show them to
173
+ * the user right away and don't keep them on the device. */
174
+ async completeTotpSetup(input) {
175
+ const resp = await this.http.post("/auth/login/totp-setup", {
176
+ body: input,
177
+ skipAuth: true
178
+ });
179
+ await Promise.resolve(this.tokens.set(resp.access_token));
180
+ return resp;
181
+ }
182
+ /** Change the signed-in user's password. Every other session of the
183
+ * account is signed out; this one stays valid.
184
+ * Errors: 400 when the new password fails the policy, 401 when the
185
+ * current one is wrong. */
186
+ async changePassword(input) {
187
+ return this.http.post("/auth/password", {
188
+ body: input
189
+ });
190
+ }
144
191
  /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for
145
192
  * telegram/email; for TOTP it short-circuits back to the challenge. */
146
193
  async switchMethod(input) {
@@ -149,18 +196,38 @@ var AuthResource = class {
149
196
  skipAuth: true
150
197
  });
151
198
  }
152
- /** Exchange a signed Telegram Mini App `initData` payload for a session
153
- * JWT. The server validates the initData HMAC against the deployment's bot
154
- * token, then find-or-creates the end-user. First-time Telegram users are
155
- * auto-provisioned with `user.email_pending === true` — prompt them for a
156
- * real email and call {@link linkEmail}. Stores the JWT on success.
157
- *
158
- * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`
159
- * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when
160
- * you already hold a configured client. */
161
199
  async exchangeTelegram(input) {
162
- const resp = await this.http.post("/auth/telegram/exchange", {
163
- body: { init_data: input.initData },
200
+ const body = { init_data: input.initData };
201
+ if (input.provision !== void 0) body.provision = input.provision;
202
+ let resp;
203
+ try {
204
+ resp = await this.http.post("/auth/telegram/exchange", {
205
+ body,
206
+ skipAuth: true
207
+ });
208
+ } catch (e) {
209
+ if (isApiError(e) && e.status === 404 && e.code === "telegram_unknown") {
210
+ return { stage: "unknown" };
211
+ }
212
+ throw e;
213
+ }
214
+ await Promise.resolve(this.tokens.set(resp.access_token));
215
+ return resp;
216
+ }
217
+ /** Attach the Telegram account behind `initData` to an existing email +
218
+ * password account and sign in as that account. No bearer needed; the
219
+ * password is checked the same way `login` checks it. The JWT is stored.
220
+ *
221
+ * Errors: 401 `unauthenticated` (wrong email or password, as with
222
+ * `login`) / `invalid_init_data`; 403
223
+ * `user_disabled` / `second_factor_required` (accounts that sign in with
224
+ * a second factor can't be linked from a Mini App); 409
225
+ * `telegram_already_linked_other` (this account already has a different
226
+ * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to
227
+ * another account); 503 `telegram_not_configured`. */
228
+ async linkTelegram(input) {
229
+ const resp = await this.http.post("/auth/telegram/link", {
230
+ body: { init_data: input.initData, email: input.email, password: input.password },
164
231
  skipAuth: true
165
232
  });
166
233
  await Promise.resolve(this.tokens.set(resp.access_token));
@@ -177,10 +244,9 @@ var AuthResource = class {
177
244
  async me() {
178
245
  return this.http.get("/auth/me");
179
246
  }
180
- /** Local sign-out. The SDK doesn't currently call a server-side
181
- * endpoint (the Takeal API issues stateless JWTs); clearing the
182
- * store is enough. Server-side session invalidation may land
183
- * with a future session table. */
247
+ /** Local sign-out: forgets the stored JWT. To end the session on the
248
+ * server as well, revoke it first with `client.sessions.revoke(jti)`
249
+ * (the current one is marked `current: true` in `client.sessions.list()`). */
184
250
  async signOut() {
185
251
  await Promise.resolve(this.tokens.clear());
186
252
  }
@@ -245,12 +311,44 @@ var CardsResource = class {
245
311
  * `failure_reason` on the result.
246
312
  */
247
313
  async create(input) {
248
- const { idempotencyKey, ...body } = input;
314
+ const { idempotencyKey, productId, name, designId, ...rest } = input;
315
+ const body = { ...rest };
316
+ if (productId !== void 0) body["product_id"] = productId;
317
+ if (name !== void 0) body["name"] = name;
318
+ if (designId !== void 0) body["design_id"] = designId;
249
319
  return this.http.post("/me/cards", {
250
320
  body,
251
321
  idempotencyKey
252
322
  });
253
323
  }
324
+ /**
325
+ * The cards the caller can order, in the order the deployment offers them
326
+ * (the default product first). Each item carries its name, description,
327
+ * artwork, the issuance price after the caller's subscription discount,
328
+ * and the currency. Pass an item's `id` as `productId` to {@link create}.
329
+ */
330
+ async listProducts() {
331
+ return this.http.get("/me/card-products");
332
+ }
333
+ /** One product from the catalog. 404 when unknown, disabled or hidden. */
334
+ async getProduct(id) {
335
+ return this.http.get(
336
+ `/me/card-products/${encodeURIComponent(id)}`
337
+ );
338
+ }
339
+ /**
340
+ * Rename the caller's own card or change its design. Resolves to the
341
+ * updated card. 404 if the card isn't the caller's; 400 `invalid_name` /
342
+ * `design_not_allowed` on a bad value.
343
+ */
344
+ async update(id, input) {
345
+ const body = {};
346
+ if (input.name !== void 0) body["name"] = input.name;
347
+ if (input.designId !== void 0) body["design_id"] = input.designId;
348
+ return this.http.patch(`/me/cards/${encodeURIComponent(id)}`, {
349
+ body
350
+ });
351
+ }
254
352
  /** Fetch one card by id. */
255
353
  async get(id) {
256
354
  return this.http.get(`/me/cards/${encodeURIComponent(id)}`);
@@ -325,11 +423,12 @@ var BalanceResource = class {
325
423
  this.http = http;
326
424
  }
327
425
  /**
328
- * Fetch the user's wallet balance for `currency` (ISO 4217, e.g. `"USD"`).
329
- * Required — the ledger holds a separate balance per currency, so there is
330
- * no "total" without one.
426
+ * Fetch the user's wallet balance. Omit `currency` for the wallet's own
427
+ * currency; pass an ISO 4217 code (e.g. `"USD"`) to read another one —
428
+ * the ledger holds a separate balance per currency.
331
429
  */
332
430
  async get(currency) {
431
+ if (!currency) return this.http.get("/me/balance");
333
432
  const q = new URLSearchParams({ currency }).toString();
334
433
  return this.http.get(`/me/balance?${q}`);
335
434
  }
@@ -346,6 +445,25 @@ var BrandingResource = class {
346
445
  }
347
446
  };
348
447
 
448
+ // src/resources/wallet.ts
449
+ var WalletResource = class {
450
+ constructor(http) {
451
+ this.http = http;
452
+ }
453
+ /** Current wallet currency + the currencies the user may switch to. */
454
+ async get(opts = {}) {
455
+ return this.http.get("/me/wallet", { signal: opts.signal });
456
+ }
457
+ /**
458
+ * Switch the wallet currency. Fails with `409 wallet_not_empty` while any
459
+ * balance is non-zero, and `400 currency_not_allowed` for a currency the
460
+ * deployment does not offer.
461
+ */
462
+ async set(currency, opts = {}) {
463
+ return this.http.put("/me/wallet", { body: { currency }, signal: opts.signal });
464
+ }
465
+ };
466
+
349
467
  // src/resources/blog.ts
350
468
  var BlogResource = class {
351
469
  constructor(http) {
@@ -399,6 +517,265 @@ var SubscriptionsResource = class {
399
517
  }
400
518
  };
401
519
 
520
+ // src/resources/sessions.ts
521
+ var SessionsResource = class {
522
+ constructor(http) {
523
+ this.http = http;
524
+ }
525
+ /** All live sessions of the account, this one included. */
526
+ async list() {
527
+ return this.http.get("/me/sessions");
528
+ }
529
+ /** Sign out one session. Works on the current one too; the stored JWT
530
+ * stops working, so follow with `client.auth.signOut()`.
531
+ * 404 when the session is unknown or already signed out. */
532
+ async revoke(jti) {
533
+ await this.http.delete(`/me/sessions/${encodeURIComponent(jti)}`);
534
+ }
535
+ /** Sign out every session except this one. */
536
+ async revokeOthers() {
537
+ return this.http.post("/me/sessions/terminate-others");
538
+ }
539
+ };
540
+
541
+ // src/resources/push.ts
542
+ var PushResource = class {
543
+ constructor(http) {
544
+ this.http = http;
545
+ }
546
+ /** Whether the user is subscribed, plus the VAPID key to subscribe with. */
547
+ async status() {
548
+ return this.http.get("/me/push-subscription");
549
+ }
550
+ /** Store a subscription you created yourself.
551
+ * 409 `push_disabled` when the deployment has no VAPID keys.
552
+ * @deprecated Use `client.devices.register({ kind: "webpush", ... })`. */
553
+ async save(input) {
554
+ return this.http.put("/me/push-subscription", { body: input });
555
+ }
556
+ /** Delete the stored subscription. Safe when nothing is stored.
557
+ * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */
558
+ async remove() {
559
+ await this.http.delete("/me/push-subscription");
560
+ }
561
+ /** Subscribe this browser and store the subscription. Ask for
562
+ * notification permission before calling. Throws when push isn't set up
563
+ * on the deployment.
564
+ * @deprecated Use `client.devices.registerWebPush(registration)`. */
565
+ async enable(registration) {
566
+ const { vapid_public_key } = await this.status();
567
+ if (!vapid_public_key) {
568
+ throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
569
+ }
570
+ const sub = await registration.pushManager.subscribe({
571
+ userVisibleOnly: true,
572
+ applicationServerKey: base64UrlToBytes(vapid_public_key)
573
+ });
574
+ const json = sub.toJSON();
575
+ if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {
576
+ throw new Error("@takeal/cusfront-sdk: the browser returned an incomplete push subscription");
577
+ }
578
+ return this.save({
579
+ endpoint: json.endpoint,
580
+ keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
581
+ });
582
+ }
583
+ /** Unsubscribe this browser and delete the stored subscription.
584
+ * @deprecated Use `client.devices.unregisterWebPush(registration)`. */
585
+ async disable(registration) {
586
+ const sub = await registration.pushManager.getSubscription();
587
+ if (sub) await sub.unsubscribe();
588
+ await this.remove();
589
+ }
590
+ };
591
+ function base64UrlToBytes(input) {
592
+ const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
593
+ const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
594
+ const bin = atob(padded);
595
+ const out = new Uint8Array(bin.length);
596
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
597
+ return out;
598
+ }
599
+
600
+ // src/resources/me.ts
601
+ var MeResource = class {
602
+ constructor(http) {
603
+ this.http = http;
604
+ }
605
+ /** Attach the Telegram account behind `initData` to the signed-in user.
606
+ * Returns the updated user (`telegram` is set). Repeating the call with
607
+ * the same Telegram is fine.
608
+ *
609
+ * Errors: 401 `invalid_init_data`; 403 `user_disabled` /
610
+ * `second_factor_required`; 409 `telegram_already_linked_other` (the
611
+ * account already has a different Telegram; `unlinkTelegram` first) /
612
+ * `telegram_in_use` (that Telegram belongs to another account); 503
613
+ * `telegram_not_configured`. */
614
+ async linkTelegram(initData) {
615
+ return this.http.post("/me/telegram", { body: { init_data: initData } });
616
+ }
617
+ /** Detach the Telegram account from the signed-in user. Returns the
618
+ * updated user (`telegram` is `null`).
619
+ *
620
+ * Errors: 404 `telegram_not_linked`; 409 `last_credential` when the
621
+ * account has no password, so Telegram is its only way to sign in. */
622
+ async unlinkTelegram() {
623
+ return this.http.delete("/me/telegram");
624
+ }
625
+ };
626
+
627
+ // src/resources/notifications.ts
628
+ var NotificationsResource = class {
629
+ constructor(http) {
630
+ this.http = http;
631
+ }
632
+ /** One page of the inbox, newest first. */
633
+ async list(params = {}) {
634
+ const q = new URLSearchParams();
635
+ if (params.cursor) q.set("cursor", params.cursor);
636
+ if (params.limit !== void 0) q.set("limit", String(params.limit));
637
+ if (params.unreadOnly) q.set("unread", "true");
638
+ if (params.category) q.set("category", params.category);
639
+ const qs = q.toString();
640
+ return this.http.get(`/me/notifications${qs ? `?${qs}` : ""}`);
641
+ }
642
+ /** How many items are unread. Cheap; fine to poll for a badge. */
643
+ async unreadCount() {
644
+ const { unread } = await this.http.get("/me/notifications/unread-count");
645
+ return unread;
646
+ }
647
+ /** Mark one item read. Returns the item; calling it again is harmless. */
648
+ async markRead(id) {
649
+ return this.http.post(`/me/notifications/${encodeURIComponent(id)}/read`);
650
+ }
651
+ /** Mark every unread item read, or only those created before `before`
652
+ * (ISO timestamp). Returns how many changed. */
653
+ async markAllRead(before) {
654
+ return this.http.post("/me/notifications/read-all", {
655
+ body: before ? { before } : {}
656
+ });
657
+ }
658
+ /** Delete one item. 404 when it isn't the user's. */
659
+ async remove(id) {
660
+ await this.http.delete(`/me/notifications/${encodeURIComponent(id)}`);
661
+ }
662
+ /** The user's channel and language settings. */
663
+ async getPreferences() {
664
+ return this.http.get("/me/notification-preferences");
665
+ }
666
+ /** Change some settings; the rest stay. Returns the stored view.
667
+ * 400 `validation` for an unknown category, channel or locale. */
668
+ async setPreferences(input) {
669
+ return this.http.put("/me/notification-preferences", {
670
+ body: input
671
+ });
672
+ }
673
+ };
674
+
675
+ // src/resources/devices.ts
676
+ function devicePlatformOf(platform) {
677
+ return platform === "telegram-miniapp" ? "telegram" : platform;
678
+ }
679
+ var DevicesResource = class {
680
+ constructor(http, client) {
681
+ this.http = http;
682
+ this.client = client;
683
+ }
684
+ /** Every device the user has, disabled ones included. */
685
+ async list() {
686
+ return this.http.get("/me/devices");
687
+ }
688
+ /** Register a device, or refresh it when the same credential is already
689
+ * known (then `last_seen_at`, `label` and `app_version` update and a
690
+ * disabled device comes back). `app_version` defaults to the client
691
+ * version sent in `X-Takeal-Client`.
692
+ *
693
+ * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the
694
+ * deployment has no VAPID keys. */
695
+ async register(input) {
696
+ return this.http.put("/me/devices", {
697
+ body: { app_version: this.client.version, ...input }
698
+ });
699
+ }
700
+ /** Delete one device. 404 when it isn't the user's. */
701
+ async remove(id) {
702
+ await this.http.delete(`/me/devices/${encodeURIComponent(id)}`);
703
+ }
704
+ /** Subscribe this browser to Web Push and register it as a device. Ask
705
+ * for notification permission before calling. Throws when push isn't
706
+ * set up on the deployment. */
707
+ async registerWebPush(registration, opts = {}) {
708
+ const key = opts.vapidPublicKey ?? await this.vapidPublicKey();
709
+ if (!key) {
710
+ throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
711
+ }
712
+ const sub = await registration.pushManager.subscribe({
713
+ userVisibleOnly: true,
714
+ applicationServerKey: base64UrlToBytes(key)
715
+ });
716
+ const json = sub.toJSON();
717
+ if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {
718
+ throw new Error("@takeal/cusfront-sdk: the browser returned an incomplete push subscription");
719
+ }
720
+ return this.register({
721
+ kind: "webpush",
722
+ platform: devicePlatformOf(this.client.platform),
723
+ credential: {
724
+ endpoint: json.endpoint,
725
+ keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
726
+ },
727
+ ...opts.label ? { label: opts.label } : {}
728
+ });
729
+ }
730
+ /** Unsubscribe this browser from Web Push and delete the matching device
731
+ * (see {@link UnregisterWebPushOptions}). Safe when nothing is
732
+ * registered. */
733
+ async unregisterWebPush(registration, opts = {}) {
734
+ const sub = await registration.pushManager.getSubscription();
735
+ if (sub) await sub.unsubscribe();
736
+ if (opts.deviceId) {
737
+ await this.remove(opts.deviceId);
738
+ return;
739
+ }
740
+ const mine = (await this.list()).filter((d) => d.kind === "webpush" && d.is_current);
741
+ for (const d of mine) await this.remove(d.id);
742
+ }
743
+ async vapidPublicKey() {
744
+ const { vapid_public_key } = await this.http.get(
745
+ "/me/push-subscription"
746
+ );
747
+ return vapid_public_key ?? null;
748
+ }
749
+ };
750
+
751
+ // src/version.ts
752
+ var SDK_VERSION = "0.3.0";
753
+
754
+ // src/client-platform.ts
755
+ var CLIENT_HEADER = "X-Takeal-Client";
756
+ function detectClientPlatform() {
757
+ const g = globalThis;
758
+ const initData = g.Telegram?.WebApp?.initData;
759
+ if (typeof initData === "string" && initData.length > 0) return "telegram-miniapp";
760
+ if (g.navigator?.standalone === true) return "pwa";
761
+ if (typeof g.matchMedia === "function") {
762
+ try {
763
+ if (g.matchMedia("(display-mode: standalone)").matches) return "pwa";
764
+ } catch {
765
+ }
766
+ }
767
+ return "web";
768
+ }
769
+ function resolveClientDescriptor(given) {
770
+ return {
771
+ platform: given?.platform ?? detectClientPlatform(),
772
+ version: given?.version || SDK_VERSION
773
+ };
774
+ }
775
+ function clientHeaderValue(desc) {
776
+ return `${desc.platform}; ${desc.version}`;
777
+ }
778
+
402
779
  // src/token-store.ts
403
780
  function defaultBrowserStore(key = "takeal_jwt") {
404
781
  const fallback = inMemoryStore();
@@ -435,21 +812,43 @@ function inMemoryStore() {
435
812
  };
436
813
  }
437
814
 
815
+ // src/assets.ts
816
+ function resolveAssetUrl(baseUrl, url) {
817
+ if (isAbsolute(url)) return url;
818
+ const base = baseUrl.replace(/\/+$/, "");
819
+ const path = url.startsWith("/") ? url : `/${url}`;
820
+ return `${base}${path}`;
821
+ }
822
+ function isAbsolute(url) {
823
+ return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(url);
824
+ }
825
+
438
826
  // src/index.ts
439
827
  function createClient(opts) {
440
828
  const tokens = opts.tokenStore ?? pickDefaultStore();
441
829
  const fetchImpl = opts.fetch ?? defaultFetch();
442
- const http = new HttpClient(opts.baseUrl, tokens, fetchImpl);
830
+ const client = resolveClientDescriptor(opts.client);
831
+ const http = new HttpClient(opts.baseUrl, tokens, fetchImpl, {
832
+ [CLIENT_HEADER]: clientHeaderValue(client)
833
+ });
443
834
  return {
444
835
  brand: opts.brand,
836
+ client,
445
837
  tokens,
838
+ assetUrl: (url) => resolveAssetUrl(opts.baseUrl, url),
446
839
  auth: new AuthResource(http, tokens),
447
840
  deposits: new DepositsResource(http),
448
841
  cards: new CardsResource(http),
449
842
  balance: new BalanceResource(http),
843
+ wallet: new WalletResource(http),
450
844
  branding: new BrandingResource(http),
451
845
  blog: new BlogResource(http),
452
- subscriptions: new SubscriptionsResource(http)
846
+ subscriptions: new SubscriptionsResource(http),
847
+ sessions: new SessionsResource(http),
848
+ push: new PushResource(http),
849
+ me: new MeResource(http),
850
+ notifications: new NotificationsResource(http),
851
+ devices: new DevicesResource(http, client)
453
852
  };
454
853
  }
455
854
  function pickDefaultStore() {
@@ -524,10 +923,47 @@ function assertWellFormed(initData, opts = {}) {
524
923
  }
525
924
  return parsed;
526
925
  }
527
- async function fromInitData(initData, config, opts = {}) {
926
+ var TelegramUnknownError = class extends Error {
927
+ constructor(initData) {
928
+ super("this Telegram account is not linked to any user (provision: false)");
929
+ this.initData = initData;
930
+ this.name = "TelegramUnknownError";
931
+ }
932
+ };
933
+ async function exchangeInitData(initData, config, opts = {}) {
528
934
  if (!opts.skipWellFormedCheck) assertWellFormed(initData, opts);
529
- const client = createClient(config);
530
- await client.auth.exchangeTelegram({ initData });
935
+ const client = createClient({
936
+ ...config,
937
+ client: { ...config.client, platform: "telegram-miniapp" }
938
+ });
939
+ const session = await client.auth.exchangeTelegram({
940
+ initData,
941
+ ...opts.provision !== void 0 ? { provision: opts.provision } : {}
942
+ });
943
+ if (session.stage === "jwt" && opts.registerDevice !== false) {
944
+ await registerMiniAppDevice(client, initData);
945
+ }
946
+ return { client, session };
947
+ }
948
+ async function registerMiniAppDevice(client, initData) {
949
+ const locale = parseInitData(initData).user?.language_code;
950
+ try {
951
+ await client.devices.register({
952
+ kind: "telegram_miniapp",
953
+ platform: "telegram",
954
+ credential: {},
955
+ ...locale ? { locale } : {}
956
+ });
957
+ } catch (e) {
958
+ console.warn(
959
+ "@takeal/cusfront-sdk/telegram: could not register the Mini App as a device; notifications may not reach this user in Telegram",
960
+ e
961
+ );
962
+ }
963
+ }
964
+ async function fromInitData(initData, config, opts = {}) {
965
+ const { client, session } = await exchangeInitData(initData, config, opts);
966
+ if (session.stage === "unknown") throw new TelegramUnknownError(initData);
531
967
  return client;
532
968
  }
533
969
  function readWebAppInitData() {
@@ -545,6 +981,6 @@ async function fromTelegramWebApp(config, opts = {}) {
545
981
  return fromInitData(initData, config, opts);
546
982
  }
547
983
 
548
- export { InitDataError, assertWellFormed, fromInitData, fromTelegramWebApp, parseInitData, readWebAppInitData };
984
+ export { InitDataError, TelegramUnknownError, assertWellFormed, exchangeInitData, fromInitData, fromTelegramWebApp, parseInitData, readWebAppInitData };
549
985
  //# sourceMappingURL=telegram.js.map
550
986
  //# sourceMappingURL=telegram.js.map