@takeal/cusfront-sdk 0.6.8 → 0.6.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +112 -2
  2. package/README.md +26 -9
  3. package/dist/analytics.cjs +44 -6
  4. package/dist/analytics.cjs.map +1 -1
  5. package/dist/analytics.js +44 -6
  6. package/dist/analytics.js.map +1 -1
  7. package/dist/{cards-BgY00UpU.d.ts → cards-DPlgx76p.d.ts} +86 -18
  8. package/dist/{cards-DGz4Rqu1.d.cts → cards-D_krTWzr.d.cts} +86 -18
  9. package/dist/index.cjs +225 -93
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +5 -5
  12. package/dist/index.d.ts +5 -5
  13. package/dist/index.js +221 -94
  14. package/dist/index.js.map +1 -1
  15. package/dist/react/index.d.cts +1 -1
  16. package/dist/react/index.d.ts +1 -1
  17. package/dist/resources/attribution.cjs +99 -4
  18. package/dist/resources/attribution.cjs.map +1 -1
  19. package/dist/resources/attribution.d.cts +58 -1
  20. package/dist/resources/attribution.d.ts +58 -1
  21. package/dist/resources/attribution.js +96 -5
  22. package/dist/resources/attribution.js.map +1 -1
  23. package/dist/resources/auth.cjs +64 -3
  24. package/dist/resources/auth.cjs.map +1 -1
  25. package/dist/resources/auth.d.cts +1 -1
  26. package/dist/resources/auth.d.ts +1 -1
  27. package/dist/resources/auth.js +64 -3
  28. package/dist/resources/auth.js.map +1 -1
  29. package/dist/resources/cards.cjs +69 -7
  30. package/dist/resources/cards.cjs.map +1 -1
  31. package/dist/resources/cards.d.cts +2 -1
  32. package/dist/resources/cards.d.ts +2 -1
  33. package/dist/resources/cards.js +69 -8
  34. package/dist/resources/cards.js.map +1 -1
  35. package/dist/resources/codes.cjs.map +1 -1
  36. package/dist/resources/codes.d.cts +21 -1
  37. package/dist/resources/codes.d.ts +21 -1
  38. package/dist/resources/codes.js.map +1 -1
  39. package/dist/resources/consents.cjs +15 -0
  40. package/dist/resources/consents.cjs.map +1 -1
  41. package/dist/resources/consents.js +15 -0
  42. package/dist/resources/consents.js.map +1 -1
  43. package/dist/resources/deposits.cjs +50 -0
  44. package/dist/resources/deposits.cjs.map +1 -1
  45. package/dist/resources/deposits.d.cts +2 -1
  46. package/dist/resources/deposits.d.ts +2 -1
  47. package/dist/resources/deposits.js +50 -0
  48. package/dist/resources/deposits.js.map +1 -1
  49. package/dist/resources/funding-options.d.cts +2 -1
  50. package/dist/resources/funding-options.d.ts +2 -1
  51. package/dist/resources/me.d.cts +1 -1
  52. package/dist/resources/me.d.ts +1 -1
  53. package/dist/telegram.cjs +224 -73
  54. package/dist/telegram.cjs.map +1 -1
  55. package/dist/telegram.d.cts +34 -3
  56. package/dist/telegram.d.ts +34 -3
  57. package/dist/telegram.js +224 -74
  58. package/dist/telegram.js.map +1 -1
  59. package/package.json +4 -4
@@ -2,7 +2,7 @@ import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
3
  import { CusfrontClient } from '../index.cjs';
4
4
  import { User } from '../resources/auth.cjs';
5
- import { C as CardProduct, a as Card, D as Deposit } from '../cards-DGz4Rqu1.cjs';
5
+ import { C as CardProduct, a as Card, D as Deposit } from '../cards-D_krTWzr.cjs';
6
6
  import { Balance } from '../resources/balance.cjs';
7
7
  import { NotificationPage, InboxItem, NotificationCategory } from '../resources/notifications.cjs';
8
8
  import '../http-CL97TjMO.cjs';
@@ -2,7 +2,7 @@ import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
3
  import { CusfrontClient } from '../index.js';
4
4
  import { User } from '../resources/auth.js';
5
- import { C as CardProduct, a as Card, D as Deposit } from '../cards-BgY00UpU.js';
5
+ import { C as CardProduct, a as Card, D as Deposit } from '../cards-DPlgx76p.js';
6
6
  import { Balance } from '../resources/balance.js';
7
7
  import { NotificationPage, InboxItem, NotificationCategory } from '../resources/notifications.js';
8
8
  import '../http-CL97TjMO.js';
@@ -9,6 +9,42 @@ var AttributionResource = class {
9
9
  async touch(input) {
10
10
  return this.http.post("/attribution/touches", { body: input, skipAuth: true });
11
11
  }
12
+ /** A one-day token that carries the visitor's analytics ids into the
13
+ * Telegram Mini App, whose sign-in reads it back. Most callers want
14
+ * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of
15
+ * the ids is valid. */
16
+ async handoff(ids) {
17
+ return this.http.post("/attribution/handoff", { body: ids, skipAuth: true });
18
+ }
19
+ /**
20
+ * The `startapp` value for a link from the site to the Mini App: the code
21
+ * as it is, followed by `__<token>` when the visitor has analytics ids, so
22
+ * a payment made in Telegram is still credited to the visit it came from.
23
+ * Without ids, or when the token can't be had, just the code.
24
+ *
25
+ * ```ts
26
+ * const start = await client.attribution.telegramStartParam("SPRING");
27
+ * location.href = `https://t.me/our_bot/app?startapp=${start}`;
28
+ * ```
29
+ */
30
+ async telegramStartParam(code = "") {
31
+ const ids = analyticsIds();
32
+ if (!ids) return code;
33
+ try {
34
+ const { token } = await this.handoff(ids);
35
+ return `${code}__${token}`;
36
+ } catch {
37
+ return code;
38
+ }
39
+ }
40
+ /** Send the visitor's analytics ids for the signed-in account, e.g. right
41
+ * after they agreed to analytics cookies in the cabinet. Without an
42
+ * argument the ids this browser holds are sent; nothing is sent when it
43
+ * holds none. */
44
+ async sendAnalyticsIds(ids = analyticsIds()) {
45
+ if (!ids) return;
46
+ await this.http.post("/me/analytics/ids", { body: ids });
47
+ }
12
48
  /** Whether to ask the signed-in user how they heard about us. */
13
49
  async status() {
14
50
  return this.http.get("/me/attribution");
@@ -41,14 +77,14 @@ function anonymousKey(opts = {}) {
41
77
  const g = globalThis;
42
78
  if (!g.document) return void 0;
43
79
  const name = opts.name ?? "takeal_anon";
44
- let stored;
80
+ let stored2;
45
81
  try {
46
- stored = g.localStorage?.getItem(name) ?? void 0;
82
+ stored2 = g.localStorage?.getItem(name) ?? void 0;
47
83
  } catch {
48
- stored = void 0;
84
+ stored2 = void 0;
49
85
  }
50
86
  const fromCookie = readCookie(name);
51
- let key = [fromCookie, stored].find((k) => !!k && KEY_SHAPE.test(k));
87
+ let key = [fromCookie, stored2].find((k) => !!k && KEY_SHAPE.test(k));
52
88
  if (!key) {
53
89
  key = g.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;
54
90
  }
@@ -74,9 +110,68 @@ function currentTouch() {
74
110
  if (ga) out.ga_client_id = ga;
75
111
  return out;
76
112
  }
113
+ var IDS_KEY = "takeal_analytics_ids";
114
+ function storage() {
115
+ try {
116
+ return globalThis.localStorage;
117
+ } catch {
118
+ return void 0;
119
+ }
120
+ }
121
+ function stored() {
122
+ try {
123
+ const raw = storage()?.getItem(IDS_KEY);
124
+ const v = raw ? JSON.parse(raw) : {};
125
+ return typeof v === "object" && v !== null ? v : {};
126
+ } catch {
127
+ return {};
128
+ }
129
+ }
130
+ function clean(ids) {
131
+ const out = {};
132
+ const ym = ids.metrika_client_id?.trim();
133
+ if (ym && /^\d{1,32}$/.test(ym)) out.metrika_client_id = ym;
134
+ const ga = ids.ga_client_id?.trim();
135
+ if (ga && /^\d+\.\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;
136
+ return out.metrika_client_id || out.ga_client_id ? out : void 0;
137
+ }
138
+ function rememberAnalyticsIds(ids) {
139
+ const merged = clean({ ...stored(), ...ids });
140
+ if (!merged) return;
141
+ try {
142
+ storage()?.setItem(IDS_KEY, JSON.stringify(merged));
143
+ } catch {
144
+ }
145
+ }
146
+ function forgetAnalyticsIds() {
147
+ try {
148
+ storage()?.removeItem(IDS_KEY);
149
+ } catch {
150
+ }
151
+ }
152
+ function analyticsIds() {
153
+ const kept = stored();
154
+ return clean({
155
+ metrika_client_id: kept.metrika_client_id ?? readCookie("_ym_uid"),
156
+ ga_client_id: kept.ga_client_id ?? readCookie("_ga")?.split(".").slice(-2).join(".")
157
+ });
158
+ }
159
+ function withAnalyticsIds(attribution) {
160
+ const ids = analyticsIds();
161
+ if (!ids) return attribution;
162
+ return {
163
+ ...attribution,
164
+ metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,
165
+ ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id
166
+ };
167
+ }
77
168
 
78
169
  exports.AttributionResource = AttributionResource;
170
+ exports.analyticsIds = analyticsIds;
79
171
  exports.anonymousKey = anonymousKey;
80
172
  exports.currentTouch = currentTouch;
173
+ exports.forgetAnalyticsIds = forgetAnalyticsIds;
174
+ exports.rememberAnalyticsIds = rememberAnalyticsIds;
175
+ exports.withAnalyticsIds = withAnalyticsIds;
81
176
  //# sourceMappingURL=attribution.cjs.map
82
177
  //# sourceMappingURL=attribution.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/resources/attribution.ts"],"names":[],"mappings":";;;AA6EO,IAAM,sBAAN,MAA0B;AAAA,EAC/B,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAmB;AAAA;AAAA,EAGhD,MAAM,MAAM,KAAA,EAAyC;AACnD,IAAA,OAAO,IAAA,CAAK,KAAK,IAAA,CAAkB,sBAAA,EAAwB,EAAE,IAAA,EAAM,KAAA,EAAO,QAAA,EAAU,IAAA,EAAM,CAAA;AAAA,EAC5F;AAAA;AAAA,EAGA,MAAM,MAAA,GAAqC;AACzC,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAuB,iBAAiB,CAAA;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,YAAA,CAAa,MAAA,EAAsB,SAAA,EAAgD;AACvF,IAAA,MAAM,IAAA,GAAsD,EAAE,MAAA,EAAO;AACrE,IAAA,IAAI,SAAA,KAAc,MAAA,EAAW,IAAA,CAAK,UAAA,GAAa,SAAA;AAC/C,IAAA,OAAO,KAAK,IAAA,CAAK,GAAA,CAAuB,wBAAA,EAA0B,EAAE,MAAM,CAAA;AAAA,EAC5E;AACF;AAUA,SAAS,QAAA,GAAW;AAClB,EAAA,OAAQ,UAAA,CAAyC,UAAU,M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A,GAAK,WAAW,SAAS,CAAA;AAC/B,EAAA,IAAI,EAAA,MAAQ,iBAAA,GAAoB,EAAA;AAEhC,EAAA,MAAM,EAAA,GAAK,UAAA,CAAW,KAAK,CAAA,EAAG,KAAA,CAAM,GAAG,CAAA,CAAE,KAAA,CAAM,EAAE,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA;AAC3D,EAAA,IAAI,EAAA,MAAQ,YAAA,GAAe,EAAA;AAC3B,EAAA,OAAO,GAAA;AACT","file":"attribution.cjs","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n \"friend\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"skipped\";\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n"]}
1
+ {"version":3,"sources":["../../src/resources/attribution.ts"],"names":["stored"],"mappings":";;;AAiGO,IAAM,sBAAN,MAA0B;AAAA,EAC/B,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAmB;AAAA;AAAA,EAGhD,MAAM,MAAM,KAAA,EAAyC;AACnD,IAAA,OAAO,IAAA,CAAK,KAAK,IAAA,CAAkB,sBAAA,EAAwB,EAAE,IAAA,EAAM,KAAA,EAAO,QAAA,EAAU,IAAA,EAAM,CAAA;AAAA,EAC5F;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,QAAQ,GAAA,EAA0C;AACtD,IAAA,OAAO,IAAA,CAAK,KAAK,IAAA,CAAmB,sBAAA,EAAwB,EAAE,IAAA,EAAM,GAAA,EAAK,QAAA,EAAU,IAAA,EAAM,CAAA;AAAA,EAC3F;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAM,kBAAA,CAAmB,IAAA,GAAO,EAAA,EAAqB;AACnD,IAAA,MAAM,MAAM,YAAA,EAAa;AACzB,IAAA,IAAI,CAAC,KAAK,OAAO,IAAA;AACjB,IAAA,IAAI;AACF,MAAA,MAAM,EAAE,KAAA,EAAM,GAAI,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AAA,CAAK,SAAA,CAAU,MAAM,CAAC,CAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AAGO,SAAS,kBAAA,GAA2B;AACzC,EAAA,IAAI;AACF,IAAA,OAAA,EAAQ,EAAG,WAAW,OAAO,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AAQO,SAAS,YAAA,GAAyC;AACvD,EAAA,MAAM,OAAO,MAAA,EAAO;AACpB,EAAA,OAAO,KAAA,CAAM;AAAA,IACX,iBAAA,EAAmB,IAAA,CAAK,iBAAA,IAAqB,UAAA,CAAW,SAAS,CAAA;AAAA,IACjE,YAAA,EAAc,IAAA,CAAK,YAAA,IAAgB,UAAA,CAAW,KAAK,CAAA,EAAG,KAAA,CAAM,GAAG,CAAA,CAAE,KAAA,CAAM,EAAE,CAAA,CAAE,KAAK,GAAG;AAAA,GACpF,CAAA;AACH;AAGO,SAAS,iBACd,WAAA,EAC+B;AAC/B,EAAA,MAAM,MAAM,YAAA,EAAa;AACzB,EAAA,IAAI,CAAC,KAAK,OAAO,WAAA;AACjB,EAAA,OAAO;AAAA,IACL,GAAG,WAAA;AAAA,IACH,iBAAA,EAAmB,WAAA,EAAa,iBAAA,IAAqB,GAAA,CAAI,iBAAA;AAAA,IACzD,YAAA,EAAc,WAAA,EAAa,YAAA,IAAgB,GAAA,CAAI;AAAA,GACjD;AACF","file":"attribution.cjs","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n \"friend\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"skipped\";\n\n/**\n * The visitor's ids at the analytics platforms (TKL-329). The SDK keeps\n * them from the moment the visitor agreed to analytics cookies and sends\n * them with an order, a top-up and a sign-in, so the server can report the\n * payment and the issued card to the platforms after the person has left\n * for the bank or Telegram. See {@link analyticsIds}.\n */\nexport interface AnalyticsIds {\n /** Yandex Metrica's ClientID, from `getClientID`. A string: it does not fit a number. */\n metrika_client_id?: string;\n /** Google Analytics' client id, from the `_ga` cookie: `1234567890.1700000000`. */\n ga_client_id?: string;\n}\n\nexport interface HandoffToken {\n /** Goes into the Mini App link's `startapp` after two underscores. */\n token: string;\n expires_at: string;\n}\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** A one-day token that carries the visitor's analytics ids into the\n * Telegram Mini App, whose sign-in reads it back. Most callers want\n * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of\n * the ids is valid. */\n async handoff(ids: AnalyticsIds): Promise<HandoffToken> {\n return this.http.post<HandoffToken>(\"/attribution/handoff\", { body: ids, skipAuth: true });\n }\n\n /**\n * The `startapp` value for a link from the site to the Mini App: the code\n * as it is, followed by `__<token>` when the visitor has analytics ids, so\n * a payment made in Telegram is still credited to the visit it came from.\n * Without ids, or when the token can't be had, just the code.\n *\n * ```ts\n * const start = await client.attribution.telegramStartParam(\"SPRING\");\n * location.href = `https://t.me/our_bot/app?startapp=${start}`;\n * ```\n */\n async telegramStartParam(code = \"\"): Promise<string> {\n const ids = analyticsIds();\n if (!ids) return code;\n try {\n const { token } = await this.handoff(ids);\n return `${code}__${token}`;\n } catch {\n return code;\n }\n }\n\n /** Send the visitor's analytics ids for the signed-in account, e.g. right\n * after they agreed to analytics cookies in the cabinet. Without an\n * argument the ids this browser holds are sent; nothing is sent when it\n * holds none. */\n async sendAnalyticsIds(ids: AnalyticsIds | undefined = analyticsIds()): Promise<void> {\n if (!ids) return;\n await this.http.post<void>(\"/me/analytics/ids\", { body: ids });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Analytics ids (TKL-329)\n// ---------------------------------------------------------------------------\n\nconst IDS_KEY = \"takeal_analytics_ids\";\n\nfunction storage(): Storage | undefined {\n try {\n return (globalThis as { localStorage?: Storage }).localStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction stored(): AnalyticsIds {\n try {\n const raw = storage()?.getItem(IDS_KEY);\n const v = raw ? (JSON.parse(raw) as AnalyticsIds) : {};\n return typeof v === \"object\" && v !== null ? v : {};\n } catch {\n return {};\n }\n}\n\nfunction clean(ids: AnalyticsIds): AnalyticsIds | undefined {\n const out: AnalyticsIds = {};\n const ym = ids.metrika_client_id?.trim();\n if (ym && /^\\d{1,32}$/.test(ym)) out.metrika_client_id = ym;\n const ga = ids.ga_client_id?.trim();\n if (ga && /^\\d+\\.\\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;\n return out.metrika_client_id || out.ga_client_id ? out : undefined;\n}\n\n/**\n * Keep analytics ids for this browser, on top of the ones kept before. The\n * Metrica sink of `initAnalytics` calls it with `getClientID`'s answer once\n * the visitor agreed to analytics; call it yourself for another platform.\n */\nexport function rememberAnalyticsIds(ids: AnalyticsIds): void {\n const merged = clean({ ...stored(), ...ids });\n if (!merged) return;\n try {\n storage()?.setItem(IDS_KEY, JSON.stringify(merged));\n } catch {\n // Storage full or blocked: the cookies still hold them.\n }\n}\n\n/** Forget the kept analytics ids: the visitor declined analytics. */\nexport function forgetAnalyticsIds(): void {\n try {\n storage()?.removeItem(IDS_KEY);\n } catch {\n // Nothing kept, or nothing to reach.\n }\n}\n\n/**\n * The visitor's analytics ids: the ones kept by {@link rememberAnalyticsIds},\n * and failing those the platforms' own cookies (`_ym_uid`, `_ga`), which\n * exist only once the visitor agreed to analytics. `undefined` when there\n * are none. The site and the cabinet share them when they share the origin.\n */\nexport function analyticsIds(): AnalyticsIds | undefined {\n const kept = stored();\n return clean({\n metrika_client_id: kept.metrika_client_id ?? readCookie(\"_ym_uid\"),\n ga_client_id: kept.ga_client_id ?? readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\"),\n });\n}\n\n/** `attribution` with the visitor's analytics ids filled in where it has none. */\nexport function withAnalyticsIds(\n attribution: SignupAttribution | undefined,\n): SignupAttribution | undefined {\n const ids = analyticsIds();\n if (!ids) return attribution;\n return {\n ...attribution,\n metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,\n ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id,\n };\n}\n"]}
@@ -61,6 +61,24 @@ interface SignupAttribution {
61
61
  posthog_distinct_id?: string;
62
62
  }
63
63
  type SurveyAnswer = "friend" | "telegram_channel" | "search" | "ads" | "review" | "other" | "skipped";
64
+ /**
65
+ * The visitor's ids at the analytics platforms (TKL-329). The SDK keeps
66
+ * them from the moment the visitor agreed to analytics cookies and sends
67
+ * them with an order, a top-up and a sign-in, so the server can report the
68
+ * payment and the issued card to the platforms after the person has left
69
+ * for the bank or Telegram. See {@link analyticsIds}.
70
+ */
71
+ interface AnalyticsIds {
72
+ /** Yandex Metrica's ClientID, from `getClientID`. A string: it does not fit a number. */
73
+ metrika_client_id?: string;
74
+ /** Google Analytics' client id, from the `_ga` cookie: `1234567890.1700000000`. */
75
+ ga_client_id?: string;
76
+ }
77
+ interface HandoffToken {
78
+ /** Goes into the Mini App link's `startapp` after two underscores. */
79
+ token: string;
80
+ expires_at: string;
81
+ }
64
82
  interface AttributionStatus {
65
83
  /** `true` while the app should ask "how did you hear about us". */
66
84
  survey_pending: boolean;
@@ -72,6 +90,28 @@ declare class AttributionResource {
72
90
  constructor(http: HttpClient);
73
91
  /** Record a visit. No session needed; safe to call on every page load. */
74
92
  touch(input: TouchInput): Promise<TouchResult>;
93
+ /** A one-day token that carries the visitor's analytics ids into the
94
+ * Telegram Mini App, whose sign-in reads it back. Most callers want
95
+ * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of
96
+ * the ids is valid. */
97
+ handoff(ids: AnalyticsIds): Promise<HandoffToken>;
98
+ /**
99
+ * The `startapp` value for a link from the site to the Mini App: the code
100
+ * as it is, followed by `__<token>` when the visitor has analytics ids, so
101
+ * a payment made in Telegram is still credited to the visit it came from.
102
+ * Without ids, or when the token can't be had, just the code.
103
+ *
104
+ * ```ts
105
+ * const start = await client.attribution.telegramStartParam("SPRING");
106
+ * location.href = `https://t.me/our_bot/app?startapp=${start}`;
107
+ * ```
108
+ */
109
+ telegramStartParam(code?: string): Promise<string>;
110
+ /** Send the visitor's analytics ids for the signed-in account, e.g. right
111
+ * after they agreed to analytics cookies in the cabinet. Without an
112
+ * argument the ids this browser holds are sent; nothing is sent when it
113
+ * holds none. */
114
+ sendAnalyticsIds(ids?: AnalyticsIds | undefined): Promise<void>;
75
115
  /** Whether to ask the signed-in user how they heard about us. */
76
116
  status(): Promise<AttributionStatus>;
77
117
  /** Answer the question once. Send `"skipped"` when the user closes it.
@@ -96,5 +136,22 @@ declare function anonymousKey(opts?: AnonymousKeyOptions): string | undefined;
96
136
  /** The current page as a touch: address, referrer, the Mini App's start
97
137
  * code and the analytics cookies. Empty outside a browser. */
98
138
  declare function currentTouch(): TouchFields;
139
+ /**
140
+ * Keep analytics ids for this browser, on top of the ones kept before. The
141
+ * Metrica sink of `initAnalytics` calls it with `getClientID`'s answer once
142
+ * the visitor agreed to analytics; call it yourself for another platform.
143
+ */
144
+ declare function rememberAnalyticsIds(ids: AnalyticsIds): void;
145
+ /** Forget the kept analytics ids: the visitor declined analytics. */
146
+ declare function forgetAnalyticsIds(): void;
147
+ /**
148
+ * The visitor's analytics ids: the ones kept by {@link rememberAnalyticsIds},
149
+ * and failing those the platforms' own cookies (`_ym_uid`, `_ga`), which
150
+ * exist only once the visitor agreed to analytics. `undefined` when there
151
+ * are none. The site and the cabinet share them when they share the origin.
152
+ */
153
+ declare function analyticsIds(): AnalyticsIds | undefined;
154
+ /** `attribution` with the visitor's analytics ids filled in where it has none. */
155
+ declare function withAnalyticsIds(attribution: SignupAttribution | undefined): SignupAttribution | undefined;
99
156
 
100
- export { type AnonymousKeyOptions, AttributionResource, type AttributionStatus, type SignupAttribution, type SurveyAnswer, type TouchFields, type TouchInput, type TouchResult, anonymousKey, currentTouch };
157
+ export { type AnalyticsIds, type AnonymousKeyOptions, AttributionResource, type AttributionStatus, type HandoffToken, type SignupAttribution, type SurveyAnswer, type TouchFields, type TouchInput, type TouchResult, analyticsIds, anonymousKey, currentTouch, forgetAnalyticsIds, rememberAnalyticsIds, withAnalyticsIds };
@@ -61,6 +61,24 @@ interface SignupAttribution {
61
61
  posthog_distinct_id?: string;
62
62
  }
63
63
  type SurveyAnswer = "friend" | "telegram_channel" | "search" | "ads" | "review" | "other" | "skipped";
64
+ /**
65
+ * The visitor's ids at the analytics platforms (TKL-329). The SDK keeps
66
+ * them from the moment the visitor agreed to analytics cookies and sends
67
+ * them with an order, a top-up and a sign-in, so the server can report the
68
+ * payment and the issued card to the platforms after the person has left
69
+ * for the bank or Telegram. See {@link analyticsIds}.
70
+ */
71
+ interface AnalyticsIds {
72
+ /** Yandex Metrica's ClientID, from `getClientID`. A string: it does not fit a number. */
73
+ metrika_client_id?: string;
74
+ /** Google Analytics' client id, from the `_ga` cookie: `1234567890.1700000000`. */
75
+ ga_client_id?: string;
76
+ }
77
+ interface HandoffToken {
78
+ /** Goes into the Mini App link's `startapp` after two underscores. */
79
+ token: string;
80
+ expires_at: string;
81
+ }
64
82
  interface AttributionStatus {
65
83
  /** `true` while the app should ask "how did you hear about us". */
66
84
  survey_pending: boolean;
@@ -72,6 +90,28 @@ declare class AttributionResource {
72
90
  constructor(http: HttpClient);
73
91
  /** Record a visit. No session needed; safe to call on every page load. */
74
92
  touch(input: TouchInput): Promise<TouchResult>;
93
+ /** A one-day token that carries the visitor's analytics ids into the
94
+ * Telegram Mini App, whose sign-in reads it back. Most callers want
95
+ * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of
96
+ * the ids is valid. */
97
+ handoff(ids: AnalyticsIds): Promise<HandoffToken>;
98
+ /**
99
+ * The `startapp` value for a link from the site to the Mini App: the code
100
+ * as it is, followed by `__<token>` when the visitor has analytics ids, so
101
+ * a payment made in Telegram is still credited to the visit it came from.
102
+ * Without ids, or when the token can't be had, just the code.
103
+ *
104
+ * ```ts
105
+ * const start = await client.attribution.telegramStartParam("SPRING");
106
+ * location.href = `https://t.me/our_bot/app?startapp=${start}`;
107
+ * ```
108
+ */
109
+ telegramStartParam(code?: string): Promise<string>;
110
+ /** Send the visitor's analytics ids for the signed-in account, e.g. right
111
+ * after they agreed to analytics cookies in the cabinet. Without an
112
+ * argument the ids this browser holds are sent; nothing is sent when it
113
+ * holds none. */
114
+ sendAnalyticsIds(ids?: AnalyticsIds | undefined): Promise<void>;
75
115
  /** Whether to ask the signed-in user how they heard about us. */
76
116
  status(): Promise<AttributionStatus>;
77
117
  /** Answer the question once. Send `"skipped"` when the user closes it.
@@ -96,5 +136,22 @@ declare function anonymousKey(opts?: AnonymousKeyOptions): string | undefined;
96
136
  /** The current page as a touch: address, referrer, the Mini App's start
97
137
  * code and the analytics cookies. Empty outside a browser. */
98
138
  declare function currentTouch(): TouchFields;
139
+ /**
140
+ * Keep analytics ids for this browser, on top of the ones kept before. The
141
+ * Metrica sink of `initAnalytics` calls it with `getClientID`'s answer once
142
+ * the visitor agreed to analytics; call it yourself for another platform.
143
+ */
144
+ declare function rememberAnalyticsIds(ids: AnalyticsIds): void;
145
+ /** Forget the kept analytics ids: the visitor declined analytics. */
146
+ declare function forgetAnalyticsIds(): void;
147
+ /**
148
+ * The visitor's analytics ids: the ones kept by {@link rememberAnalyticsIds},
149
+ * and failing those the platforms' own cookies (`_ym_uid`, `_ga`), which
150
+ * exist only once the visitor agreed to analytics. `undefined` when there
151
+ * are none. The site and the cabinet share them when they share the origin.
152
+ */
153
+ declare function analyticsIds(): AnalyticsIds | undefined;
154
+ /** `attribution` with the visitor's analytics ids filled in where it has none. */
155
+ declare function withAnalyticsIds(attribution: SignupAttribution | undefined): SignupAttribution | undefined;
99
156
 
100
- export { type AnonymousKeyOptions, AttributionResource, type AttributionStatus, type SignupAttribution, type SurveyAnswer, type TouchFields, type TouchInput, type TouchResult, anonymousKey, currentTouch };
157
+ export { type AnalyticsIds, type AnonymousKeyOptions, AttributionResource, type AttributionStatus, type HandoffToken, type SignupAttribution, type SurveyAnswer, type TouchFields, type TouchInput, type TouchResult, analyticsIds, anonymousKey, currentTouch, forgetAnalyticsIds, rememberAnalyticsIds, withAnalyticsIds };
@@ -7,6 +7,42 @@ var AttributionResource = class {
7
7
  async touch(input) {
8
8
  return this.http.post("/attribution/touches", { body: input, skipAuth: true });
9
9
  }
10
+ /** A one-day token that carries the visitor's analytics ids into the
11
+ * Telegram Mini App, whose sign-in reads it back. Most callers want
12
+ * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of
13
+ * the ids is valid. */
14
+ async handoff(ids) {
15
+ return this.http.post("/attribution/handoff", { body: ids, skipAuth: true });
16
+ }
17
+ /**
18
+ * The `startapp` value for a link from the site to the Mini App: the code
19
+ * as it is, followed by `__<token>` when the visitor has analytics ids, so
20
+ * a payment made in Telegram is still credited to the visit it came from.
21
+ * Without ids, or when the token can't be had, just the code.
22
+ *
23
+ * ```ts
24
+ * const start = await client.attribution.telegramStartParam("SPRING");
25
+ * location.href = `https://t.me/our_bot/app?startapp=${start}`;
26
+ * ```
27
+ */
28
+ async telegramStartParam(code = "") {
29
+ const ids = analyticsIds();
30
+ if (!ids) return code;
31
+ try {
32
+ const { token } = await this.handoff(ids);
33
+ return `${code}__${token}`;
34
+ } catch {
35
+ return code;
36
+ }
37
+ }
38
+ /** Send the visitor's analytics ids for the signed-in account, e.g. right
39
+ * after they agreed to analytics cookies in the cabinet. Without an
40
+ * argument the ids this browser holds are sent; nothing is sent when it
41
+ * holds none. */
42
+ async sendAnalyticsIds(ids = analyticsIds()) {
43
+ if (!ids) return;
44
+ await this.http.post("/me/analytics/ids", { body: ids });
45
+ }
10
46
  /** Whether to ask the signed-in user how they heard about us. */
11
47
  async status() {
12
48
  return this.http.get("/me/attribution");
@@ -39,14 +75,14 @@ function anonymousKey(opts = {}) {
39
75
  const g = globalThis;
40
76
  if (!g.document) return void 0;
41
77
  const name = opts.name ?? "takeal_anon";
42
- let stored;
78
+ let stored2;
43
79
  try {
44
- stored = g.localStorage?.getItem(name) ?? void 0;
80
+ stored2 = g.localStorage?.getItem(name) ?? void 0;
45
81
  } catch {
46
- stored = void 0;
82
+ stored2 = void 0;
47
83
  }
48
84
  const fromCookie = readCookie(name);
49
- let key = [fromCookie, stored].find((k) => !!k && KEY_SHAPE.test(k));
85
+ let key = [fromCookie, stored2].find((k) => !!k && KEY_SHAPE.test(k));
50
86
  if (!key) {
51
87
  key = g.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;
52
88
  }
@@ -72,7 +108,62 @@ function currentTouch() {
72
108
  if (ga) out.ga_client_id = ga;
73
109
  return out;
74
110
  }
111
+ var IDS_KEY = "takeal_analytics_ids";
112
+ function storage() {
113
+ try {
114
+ return globalThis.localStorage;
115
+ } catch {
116
+ return void 0;
117
+ }
118
+ }
119
+ function stored() {
120
+ try {
121
+ const raw = storage()?.getItem(IDS_KEY);
122
+ const v = raw ? JSON.parse(raw) : {};
123
+ return typeof v === "object" && v !== null ? v : {};
124
+ } catch {
125
+ return {};
126
+ }
127
+ }
128
+ function clean(ids) {
129
+ const out = {};
130
+ const ym = ids.metrika_client_id?.trim();
131
+ if (ym && /^\d{1,32}$/.test(ym)) out.metrika_client_id = ym;
132
+ const ga = ids.ga_client_id?.trim();
133
+ if (ga && /^\d+\.\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;
134
+ return out.metrika_client_id || out.ga_client_id ? out : void 0;
135
+ }
136
+ function rememberAnalyticsIds(ids) {
137
+ const merged = clean({ ...stored(), ...ids });
138
+ if (!merged) return;
139
+ try {
140
+ storage()?.setItem(IDS_KEY, JSON.stringify(merged));
141
+ } catch {
142
+ }
143
+ }
144
+ function forgetAnalyticsIds() {
145
+ try {
146
+ storage()?.removeItem(IDS_KEY);
147
+ } catch {
148
+ }
149
+ }
150
+ function analyticsIds() {
151
+ const kept = stored();
152
+ return clean({
153
+ metrika_client_id: kept.metrika_client_id ?? readCookie("_ym_uid"),
154
+ ga_client_id: kept.ga_client_id ?? readCookie("_ga")?.split(".").slice(-2).join(".")
155
+ });
156
+ }
157
+ function withAnalyticsIds(attribution) {
158
+ const ids = analyticsIds();
159
+ if (!ids) return attribution;
160
+ return {
161
+ ...attribution,
162
+ metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,
163
+ ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id
164
+ };
165
+ }
75
166
 
76
- export { AttributionResource, anonymousKey, currentTouch };
167
+ export { AttributionResource, analyticsIds, anonymousKey, currentTouch, forgetAnalyticsIds, rememberAnalyticsIds, withAnalyticsIds };
77
168
  //# sourceMappingURL=attribution.js.map
78
169
  //# sourceMappingURL=attribution.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/resources/attribution.ts"],"names":[],"mappings":";AA6EO,IAAM,sBAAN,MAA0B;AAAA,EAC/B,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAmB;AAAA;AAAA,EAGhD,MAAM,MAAM,KAAA,EAAyC;AACnD,IAAA,OAAO,IAAA,CAAK,KAAK,IAAA,CAAkB,sBAAA,EAAwB,EAAE,IAAA,EAAM,KAAA,EAAO,QAAA,EAAU,IAAA,EAAM,CAAA;AAAA,EAC5F;AAAA;AAAA,EAGA,MAAM,MAAA,GAAqC;AACzC,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAuB,iBAAiB,CAAA;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,YAAA,CAAa,MAAA,EAAsB,SAAA,EAAgD;AACvF,IAAA,MAAM,IAAA,GAAsD,EAAE,MAAA,EAAO;AACrE,IAAA,IAAI,SAAA,KAAc,MAAA,EAAW,IAAA,CAAK,UAAA,GAAa,SAAA;AAC/C,IAAA,OAAO,KAAK,IAAA,CAAK,GAAA,CAAuB,wBAAA,EAA0B,EAAE,MAAM,CAAA;AAAA,EAC5E;AACF;AAUA,SAAS,QAAA,GAAW;AAClB,EAAA,OAAQ,UAAA,CAAyC,UAAU,MAAA,EAAQ,cAAA;AACrE;AAEA,SAAS,WAAW,IAAA,EAAkC;AACpD,EAAA,MAAM,MAAO,UAAA,CAAuC,QAAA;AACpD,EAAA,IAAI,CAAC,GAAA,EAAK,MAAA,EAAQ,OAAO,MA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G,CAAA,CAAE,KAAA,CAAM,EAAE,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA;AAC3D,EAAA,IAAI,EAAA,MAAQ,YAAA,GAAe,EAAA;AAC3B,EAAA,OAAO,GAAA;AACT","file":"attribution.js","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n \"friend\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"skipped\";\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n"]}
1
+ {"version":3,"sources":["../../src/resources/attribution.ts"],"names":["stored"],"mappings":";AAiGO,IAAM,sBAAN,MAA0B;AAAA,EAC/B,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAmB;AAAA;AAAA,EAGhD,MAAM,MAAM,KAAA,EAAyC;AACnD,IAAA,OAAO,IAAA,CAAK,KAAK,IAAA,CAAkB,sBAAA,EAAwB,EAAE,IAAA,EAAM,KAAA,EAAO,QAAA,EAAU,IAAA,EAAM,CAAA;AAAA,EAC5F;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,QAAQ,GAAA,EAA0C;AACtD,IAAA,OAAO,IAAA,CAAK,KAAK,IAAA,CAAmB,sBAAA,EAAwB,EAAE,IAAA,EAAM,GAAA,EAAK,QAAA,EAAU,IAAA,EAAM,CAAA;AAAA,EAC3F;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAM,kBAAA,CAAmB,IAAA,GAAO,EAAA,EAAqB;AACnD,IAAA,MAAM,MAAM,YAAA,EAAa;AACzB,IAAA,IAAI,CAAC,KAAK,OAAO,IAAA;AACjB,IAAA,IAAI;AACF,MAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,IAAA,CAAK,QAAQ,GAAG,CAAA;AACxC,MAAA,OAAO,CAAA,EAAG,IAAI,CAAA,EAAA,EAAK,KAAK,CAAA,CAAA;AAAA,IAC1B,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IA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,WAAW,OAAO,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AAQO,SAAS,YAAA,GAAyC;AACvD,EAAA,MAAM,OAAO,MAAA,EAAO;AACpB,EAAA,OAAO,KAAA,CAAM;AAAA,IACX,iBAAA,EAAmB,IAAA,CAAK,iBAAA,IAAqB,UAAA,CAAW,SAAS,CAAA;AAAA,IACjE,YAAA,EAAc,IAAA,CAAK,YAAA,IAAgB,UAAA,CAAW,KAAK,CAAA,EAAG,KAAA,CAAM,GAAG,CAAA,CAAE,KAAA,CAAM,EAAE,CAAA,CAAE,KAAK,GAAG;AAAA,GACpF,CAAA;AACH;AAGO,SAAS,iBACd,WAAA,EAC+B;AAC/B,EAAA,MAAM,MAAM,YAAA,EAAa;AACzB,EAAA,IAAI,CAAC,KAAK,OAAO,WAAA;AACjB,EAAA,OAAO;AAAA,IACL,GAAG,WAAA;AAAA,IACH,iBAAA,EAAmB,WAAA,EAAa,iBAAA,IAAqB,GAAA,CAAI,iBAAA;AAAA,IACzD,YAAA,EAAc,WAAA,EAAa,YAAA,IAAgB,GAAA,CAAI;AAAA,GACjD;AACF","file":"attribution.js","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n \"friend\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"skipped\";\n\n/**\n * The visitor's ids at the analytics platforms (TKL-329). The SDK keeps\n * them from the moment the visitor agreed to analytics cookies and sends\n * them with an order, a top-up and a sign-in, so the server can report the\n * payment and the issued card to the platforms after the person has left\n * for the bank or Telegram. See {@link analyticsIds}.\n */\nexport interface AnalyticsIds {\n /** Yandex Metrica's ClientID, from `getClientID`. A string: it does not fit a number. */\n metrika_client_id?: string;\n /** Google Analytics' client id, from the `_ga` cookie: `1234567890.1700000000`. */\n ga_client_id?: string;\n}\n\nexport interface HandoffToken {\n /** Goes into the Mini App link's `startapp` after two underscores. */\n token: string;\n expires_at: string;\n}\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** A one-day token that carries the visitor's analytics ids into the\n * Telegram Mini App, whose sign-in reads it back. Most callers want\n * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of\n * the ids is valid. */\n async handoff(ids: AnalyticsIds): Promise<HandoffToken> {\n return this.http.post<HandoffToken>(\"/attribution/handoff\", { body: ids, skipAuth: true });\n }\n\n /**\n * The `startapp` value for a link from the site to the Mini App: the code\n * as it is, followed by `__<token>` when the visitor has analytics ids, so\n * a payment made in Telegram is still credited to the visit it came from.\n * Without ids, or when the token can't be had, just the code.\n *\n * ```ts\n * const start = await client.attribution.telegramStartParam(\"SPRING\");\n * location.href = `https://t.me/our_bot/app?startapp=${start}`;\n * ```\n */\n async telegramStartParam(code = \"\"): Promise<string> {\n const ids = analyticsIds();\n if (!ids) return code;\n try {\n const { token } = await this.handoff(ids);\n return `${code}__${token}`;\n } catch {\n return code;\n }\n }\n\n /** Send the visitor's analytics ids for the signed-in account, e.g. right\n * after they agreed to analytics cookies in the cabinet. Without an\n * argument the ids this browser holds are sent; nothing is sent when it\n * holds none. */\n async sendAnalyticsIds(ids: AnalyticsIds | undefined = analyticsIds()): Promise<void> {\n if (!ids) return;\n await this.http.post<void>(\"/me/analytics/ids\", { body: ids });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Analytics ids (TKL-329)\n// ---------------------------------------------------------------------------\n\nconst IDS_KEY = \"takeal_analytics_ids\";\n\nfunction storage(): Storage | undefined {\n try {\n return (globalThis as { localStorage?: Storage }).localStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction stored(): AnalyticsIds {\n try {\n const raw = storage()?.getItem(IDS_KEY);\n const v = raw ? (JSON.parse(raw) as AnalyticsIds) : {};\n return typeof v === \"object\" && v !== null ? v : {};\n } catch {\n return {};\n }\n}\n\nfunction clean(ids: AnalyticsIds): AnalyticsIds | undefined {\n const out: AnalyticsIds = {};\n const ym = ids.metrika_client_id?.trim();\n if (ym && /^\\d{1,32}$/.test(ym)) out.metrika_client_id = ym;\n const ga = ids.ga_client_id?.trim();\n if (ga && /^\\d+\\.\\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;\n return out.metrika_client_id || out.ga_client_id ? out : undefined;\n}\n\n/**\n * Keep analytics ids for this browser, on top of the ones kept before. The\n * Metrica sink of `initAnalytics` calls it with `getClientID`'s answer once\n * the visitor agreed to analytics; call it yourself for another platform.\n */\nexport function rememberAnalyticsIds(ids: AnalyticsIds): void {\n const merged = clean({ ...stored(), ...ids });\n if (!merged) return;\n try {\n storage()?.setItem(IDS_KEY, JSON.stringify(merged));\n } catch {\n // Storage full or blocked: the cookies still hold them.\n }\n}\n\n/** Forget the kept analytics ids: the visitor declined analytics. */\nexport function forgetAnalyticsIds(): void {\n try {\n storage()?.removeItem(IDS_KEY);\n } catch {\n // Nothing kept, or nothing to reach.\n }\n}\n\n/**\n * The visitor's analytics ids: the ones kept by {@link rememberAnalyticsIds},\n * and failing those the platforms' own cookies (`_ym_uid`, `_ga`), which\n * exist only once the visitor agreed to analytics. `undefined` when there\n * are none. The site and the cabinet share them when they share the origin.\n */\nexport function analyticsIds(): AnalyticsIds | undefined {\n const kept = stored();\n return clean({\n metrika_client_id: kept.metrika_client_id ?? readCookie(\"_ym_uid\"),\n ga_client_id: kept.ga_client_id ?? readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\"),\n });\n}\n\n/** `attribution` with the visitor's analytics ids filled in where it has none. */\nexport function withAnalyticsIds(\n attribution: SignupAttribution | undefined,\n): SignupAttribution | undefined {\n const ids = analyticsIds();\n if (!ids) return attribution;\n return {\n ...attribution,\n metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,\n ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id,\n };\n}\n"]}