@takeal/cusfront-sdk 0.6.14 → 0.8.1

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 (45) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +53 -1
  3. package/dist/analytics.cjs +88 -7
  4. package/dist/analytics.cjs.map +1 -1
  5. package/dist/analytics.d.cts +30 -2
  6. package/dist/analytics.d.ts +30 -2
  7. package/dist/analytics.js +86 -8
  8. package/dist/analytics.js.map +1 -1
  9. package/dist/{cards-D_krTWzr.d.cts → cards-BPu8Ill7.d.cts} +122 -2
  10. package/dist/{cards-DPlgx76p.d.ts → cards-DP1fJc_c.d.ts} +122 -2
  11. package/dist/index.cjs +147 -14
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +4 -4
  14. package/dist/index.d.ts +4 -4
  15. package/dist/index.js +147 -15
  16. package/dist/index.js.map +1 -1
  17. package/dist/react/index.d.cts +1 -1
  18. package/dist/react/index.d.ts +1 -1
  19. package/dist/resources/auth.cjs +8 -4
  20. package/dist/resources/auth.cjs.map +1 -1
  21. package/dist/resources/auth.d.cts +17 -6
  22. package/dist/resources/auth.d.ts +17 -6
  23. package/dist/resources/auth.js +8 -4
  24. package/dist/resources/auth.js.map +1 -1
  25. package/dist/resources/cards.cjs +60 -1
  26. package/dist/resources/cards.cjs.map +1 -1
  27. package/dist/resources/cards.d.cts +2 -1
  28. package/dist/resources/cards.d.ts +2 -1
  29. package/dist/resources/cards.js +59 -2
  30. package/dist/resources/cards.js.map +1 -1
  31. package/dist/resources/deposits.cjs.map +1 -1
  32. package/dist/resources/deposits.d.cts +2 -1
  33. package/dist/resources/deposits.d.ts +2 -1
  34. package/dist/resources/deposits.js.map +1 -1
  35. package/dist/resources/funding-options.d.cts +2 -1
  36. package/dist/resources/funding-options.d.ts +2 -1
  37. package/dist/resources/me.d.cts +1 -1
  38. package/dist/resources/me.d.ts +1 -1
  39. package/dist/telegram.cjs +54 -7
  40. package/dist/telegram.cjs.map +1 -1
  41. package/dist/telegram.d.cts +2 -2
  42. package/dist/telegram.d.ts +2 -2
  43. package/dist/telegram.js +54 -7
  44. package/dist/telegram.js.map +1 -1
  45. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -4,6 +4,63 @@ All notable changes to `@takeal/cusfront-sdk` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [Unreleased]
8
+
9
+ ## [0.8.1] — 2026-11-23
10
+
11
+ ### Changed
12
+
13
+ - `auth.linkEmail` is deprecated. On platform 0.8.1 and newer it always answers
14
+ 409 `email_change_needs_code`: the first e-mail of an account made in the
15
+ Telegram Mini App is attached with a code, through `auth.requestEmailChange`
16
+ and `auth.confirmEmailChange`, the same two calls that change an address.
17
+ - Password sign-in can answer 429 `too_many_attempts` after ten wrong
18
+ passwords for one address in an hour. Sign-in with an e-mail code keeps
19
+ working meanwhile.
20
+ - `auth.verifyEmailCode` may return `credentials_reset: true`: the code
21
+ proved the mailbox of an account for the first time, and the password and
22
+ linked sign-ins set before that were removed.
23
+
24
+ ### Fixed
25
+
26
+ - Page views sent to Yandex Metrica and PostHog keep the ad tags as they
27
+ arrived. Before, a campaign or ad id of 9 digits or more in `utm_campaign`
28
+ or `utm_content` (`yd-123456789`, `{campaign_name}_{campaign_id}`) made the
29
+ whole tag disappear, and `yclid` was sent as `:id`. Now `utm_source`,
30
+ `utm_medium`, `utm_campaign`, `utm_content` and `utm_term` keep ids of any
31
+ length, and the click ids (`yclid`, `ysclid`, `gclid`, `gbraid`, `wbraid`,
32
+ `fbclid`, `ttclid`, `msclkid`, `rb_clickid`) go out exactly as they came,
33
+ a 20-digit `yclid` included.
34
+ - A tag is still left out when it holds an e-mail address, a phone number
35
+ written as one (`+7 900 …`, `8 (900) 123-45-67`), a card number or
36
+ something that looks like a token, and a click id is left out when it has
37
+ characters a click id never has. Every other parameter is filtered as
38
+ before.
39
+
40
+ ## [0.8.0] — 2026-11-21
41
+
42
+ The SDK now carries the same minor version as the platform it targets.
43
+
44
+ ### Added
45
+
46
+ - `cards.quotePublic(input)` prices a card order before sign-in: product,
47
+ payment method, currency, an extra load and a promo code go in; the price,
48
+ the discount, the amount to pay and what the code does come back. Nothing
49
+ is reserved and the code isn't used up. `cards.quote(input)` does the same
50
+ for a signed-in person, with every condition of the code checked and bonus
51
+ points counted.
52
+ - `expectedAmount` / `expectedCurrency` on a card order, in `cards.order`
53
+ and in the `cardOrder` of a sign-in or sign-up. If the price changed since
54
+ the person saw it, no payment is opened: the call fails with
55
+ `price_changed`, and `priceChangedQuote(error)` returns the new price to
56
+ show before they confirm again.
57
+
58
+ ### Changed
59
+
60
+ - Works with platform (TKL) 0.8.0 and newer. `client.ready()` reports an
61
+ older platform as incompatible.
62
+ - Types regenerated from platform 0.8.0.
63
+
7
64
  ## [0.6.14] — 2026-11-20
8
65
 
9
66
  ### Added
package/README.md CHANGED
@@ -333,6 +333,57 @@ signed in gets the same with `client.cards.order({ productId, method,
333
333
  idempotencyKey })`. The card shows as `pending_payment` until the payment is
334
334
  confirmed and is issued after that.
335
335
 
336
+ ## The price before the payment
337
+
338
+ The form can show what the card costs with the promo code before the user
339
+ signs in. `cards.quotePublic` takes the same fields as the order and no
340
+ e-mail, and answers with the price, the discount and the amount to pay:
341
+
342
+ ```ts
343
+ const q = await client.cards.quotePublic({ productId, method: "sbp", promoCode });
344
+ // q.price "1949", q.discount "500", q.amount "1449", q.currency "RUB"
345
+ // q.promo_code.status: "applied" | "conditional" | "rejected" | "unavailable"
346
+ if (q.preliminary) {
347
+ // A code with a condition only checked after sign-in, such as first card
348
+ // only: show q.amount as provisional, next to q.promo_code.message.
349
+ }
350
+ ```
351
+
352
+ A quote reserves nothing. Drop a `rejected` code from the order: an order
353
+ that keeps it is refused.
354
+
355
+ Send the amount the user saw with the order. If the order comes to something
356
+ else (the code was for first cards only and this user has one, or the rate
357
+ moved), no payment is opened and the new quote comes back:
358
+
359
+ ```ts
360
+ import { priceChangedQuote } from "@takeal/cusfront-sdk";
361
+
362
+ const session = await client.auth.verifyEmailCode({
363
+ challengeId: challenge_id,
364
+ code,
365
+ consents: ["terms", "personal_data"],
366
+ cardOrder: { productId, method: "sbp", promoCode, expectedAmount: q.amount, expectedCurrency: q.currency },
367
+ });
368
+ const changed = priceChangedQuote(session.card_order_error);
369
+ if (changed) {
370
+ // Show changed.amount. Once the user agrees:
371
+ await client.cards.order({
372
+ productId,
373
+ method: "sbp",
374
+ promoCode: changed.promo_code?.status === "rejected" ? undefined : promoCode,
375
+ expectedAmount: changed.amount,
376
+ expectedCurrency: changed.currency,
377
+ idempotencyKey,
378
+ });
379
+ }
380
+ ```
381
+
382
+ A signed-in user gets the confirmed amount from `cards.quote`, with their
383
+ bonuses and anything they owe. `cards.order` with an `expectedAmount` that no
384
+ longer holds throws 409 `price_changed`, and `priceChangedQuote(error)` reads
385
+ the new quote from it. Without `expectedAmount` an order works as before.
386
+
336
387
  ## Topping up by SBP
337
388
 
338
389
  A rouble top-up through Russia's instant payments goes like this: the user
@@ -1063,7 +1114,8 @@ Identify users by the platform's user id (`session.user.id`), never by e-mail. P
1063
1114
 
1064
1115
  Every event goes through one filter, PostHog's autocapture included:
1065
1116
 
1066
- - in page addresses, UUIDs, numeric ids and long tokens become `:id`, query parameters with secrets or personal data are dropped, and so is the fragment. Campaign tags stay;
1117
+ - in page addresses, UUIDs, numeric ids and long tokens become `:id`, query parameters with secrets or personal data are dropped, and so is the fragment;
1118
+ - campaign tags (`utm_source`, `utm_medium`, `utm_campaign`, `utm_content`, `utm_term`) and click ids (`yclid`, `gclid`, `fbclid`, `msclkid` and the like) stay exactly as they came, ids of any length included. A tag goes only when it holds an e-mail address, a phone number written as one (`+7 900 …`, `8 (900) 123-45-67`), a card number or a token; a click id goes when it has characters a click id never has;
1067
1119
  - properties named `email`, `phone`, `name`, `first_name` and the like are dropped, and so is any value that looks like an e-mail address, a phone number or a card number;
1068
1120
  - amounts and currencies pass.
1069
1121
 
@@ -158,6 +158,67 @@ function digitCount(s) {
158
158
  function redactText(v) {
159
159
  return v.replace(EMAIL, "[email]").replace(DIGIT_RUN, (m) => digitCount(m) >= 9 && digitCount(m) <= 19 ? "[number]" : m);
160
160
  }
161
+ var UTM_PARAMS = [
162
+ "utm_source",
163
+ "utm_medium",
164
+ "utm_campaign",
165
+ "utm_content",
166
+ "utm_term"
167
+ ];
168
+ var CLICK_ID_PARAMS = [
169
+ "yclid",
170
+ "ysclid",
171
+ "gclid",
172
+ "gbraid",
173
+ "wbraid",
174
+ "fbclid",
175
+ "ttclid",
176
+ "msclkid",
177
+ "rb_clickid"
178
+ ];
179
+ var UTM_SET = new Set(UTM_PARAMS);
180
+ var CLICK_ID_SET = new Set(CLICK_ID_PARAMS);
181
+ var CLICK_ID_VALUE = /^[A-Za-z0-9._~-]{1,256}$/;
182
+ function adField(key) {
183
+ const k = key.replace(/^\$+/, "").toLowerCase().replace(/^initial_/, "");
184
+ if (UTM_SET.has(k)) return "utm";
185
+ if (CLICK_ID_SET.has(k)) return "click";
186
+ return void 0;
187
+ }
188
+ function luhn(digits) {
189
+ let sum = 0;
190
+ for (let i = 0; i < digits.length; i++) {
191
+ let d = digits.charCodeAt(digits.length - 1 - i) - 48;
192
+ if (i % 2 === 1) {
193
+ d *= 2;
194
+ if (d > 9) d -= 9;
195
+ }
196
+ sum += d;
197
+ }
198
+ return sum % 10 === 0;
199
+ }
200
+ var NUMBER_RUN = /(?:\+\s*)?\d(?:[\d\s().-]*\d)?/g;
201
+ function adValuePersonal(v) {
202
+ if (v.includes("@")) return true;
203
+ for (const m of v.match(NUMBER_RUN) ?? []) {
204
+ const groups = m.split(/\D+/).filter(Boolean);
205
+ const n = groups.join("").length;
206
+ if (m.startsWith("+")) {
207
+ if (n >= 9 && n <= 15) return true;
208
+ continue;
209
+ }
210
+ if (groups.length === 1) {
211
+ if (n >= 16 && n <= 19 && luhn(groups[0])) return true;
212
+ continue;
213
+ }
214
+ if (n >= 9 && n <= 19 && (/[()]/.test(m) || groups.every((g) => g.length <= 4))) return true;
215
+ }
216
+ return v.split(/[\s_.~+-]+/).some((seg) => seg.length >= 20 && /\d.*\d/.test(seg) && /[A-Za-z].*[A-Za-z]/.test(seg));
217
+ }
218
+ function adValue(kind, v) {
219
+ if (kind === "click") return CLICK_ID_VALUE.test(v) ? v : void 0;
220
+ return adValuePersonal(v) ? void 0 : v;
221
+ }
161
222
  function idSegment(seg) {
162
223
  let s = seg;
163
224
  try {
@@ -169,6 +230,13 @@ function idSegment(seg) {
169
230
  if (replaced !== s) return replaced;
170
231
  return redactText(s) === s ? seg : PLACEHOLDER;
171
232
  }
233
+ function decodeQueryPart(s) {
234
+ try {
235
+ return decodeURIComponent(s.replace(/\+/g, " "));
236
+ } catch {
237
+ return s;
238
+ }
239
+ }
172
240
  function sanitizeUrl(raw) {
173
241
  const absolute = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw);
174
242
  let u;
@@ -179,14 +247,22 @@ function sanitizeUrl(raw) {
179
247
  }
180
248
  const path = u.pathname.split("/").map((seg) => seg ? idSegment(seg) : seg).join("/");
181
249
  const query = [];
182
- u.searchParams.forEach((value, key) => {
250
+ for (const pair of u.search.replace(/^\?/, "").split("&")) {
251
+ if (!pair) continue;
252
+ const eq = pair.indexOf("=");
253
+ const rawKey = eq < 0 ? pair : pair.slice(0, eq);
254
+ const key = decodeQueryPart(rawKey);
255
+ const value = eq < 0 ? "" : decodeQueryPart(pair.slice(eq + 1));
256
+ const ad = adField(key);
257
+ if (ad) {
258
+ if (adValue(ad, value) !== void 0) query.push(pair);
259
+ continue;
260
+ }
183
261
  const k = words(key);
184
- if (k.some((w) => SECRET_QUERY_WORDS.has(w)) || personalKey(key)) return;
185
- if (redactText(value) !== value) return;
186
- query.push(
187
- `${encodeURIComponent(key)}=${isId(value) ? PLACEHOLDER : encodeURIComponent(value)}`
188
- );
189
- });
262
+ if (k.some((w) => SECRET_QUERY_WORDS.has(w)) || personalKey(key)) continue;
263
+ if (redactText(value) !== value) continue;
264
+ query.push(isId(value) ? `${rawKey}=${PLACEHOLDER}` : pair);
265
+ }
190
266
  const search = query.length ? `?${query.join("&")}` : "";
191
267
  return (absolute ? `${u.protocol}//${u.host}` : "") + path + search;
192
268
  }
@@ -194,6 +270,8 @@ function cleanValue(key, v, depth) {
194
270
  if (v === null || v === void 0 || typeof v === "number" || typeof v === "boolean") return v;
195
271
  if (typeof v === "string") {
196
272
  if (MONEY_KEYS.has(key.toLowerCase()) || UUID_ONLY.test(v)) return v;
273
+ const ad = adField(key);
274
+ if (ad) return adValue(ad, v);
197
275
  if (urlKey(key) || /^https?:\/\//i.test(v)) return sanitizeUrl(v);
198
276
  if (key === "$elements_chain") {
199
277
  return redactText(v).replace(
@@ -460,9 +538,12 @@ function _resetAnalyticsForTests() {
460
538
  }
461
539
 
462
540
  exports.ANALYTICS_EVENTS = ANALYTICS_EVENTS;
541
+ exports.CLICK_ID_PARAMS = CLICK_ID_PARAMS;
463
542
  exports.METRIKA_GOALS = METRIKA_GOALS;
464
543
  exports.NO_CAPTURE_CLASS = NO_CAPTURE_CLASS;
544
+ exports.UTM_PARAMS = UTM_PARAMS;
465
545
  exports._resetAnalyticsForTests = _resetAnalyticsForTests;
546
+ exports.adValuePersonal = adValuePersonal;
466
547
  exports.identify = identify;
467
548
  exports.initAnalytics = initAnalytics;
468
549
  exports.page = page;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/resources/attribution.ts","../src/analytics.ts"],"names":["clean"],"mappings":";;;AAwPA,IAAM,OAAA,GAAU,sBAAA;AAEhB,SAAS,OAAA,GAA+B;AACtC,EAAA,IAAI;AACF,IAAA,OAAQ,UAAA,CAA0C,YAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAEA,SAAS,MAAA,GAAuB;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,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ACjC,CAAC,CAAA;AACD,EAAA,MAAM,KAAK,MAAM,OAAA,CAAQ,KAAK,CAAC,KAAA,EAAO,OAAO,CAAC,CAAA;AAC9C,EAAA,YAAA,CAAa,KAAK,CAAA;AAClB,EAAA,IAAI;AACF,IAAA,OAAO,EAAA,EAAI,iBAAgB,IAAK,KAAA,CAAA;AAAA,EAClC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAGO,SAAS,uBAAA,GAAgC;AAC9C,EAAA,MAAA,CAAO,GAAG,CAAA,GAAI,MAAA;AAChB","file":"analytics.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","/**\n * `@takeal/cusfront-sdk/analytics` — one event layer for product analytics.\n *\n * The app calls {@link track} once per event; the layer hands it to every\n * configured system: PostHog everywhere, Yandex Metrica only on public pages\n * and only for the sign-up goals (what happens behind the login reaches\n * Metrica from the server, not from the browser). Every event passes\n * {@link sanitizeProperties} on the way out, PostHog's own autocapture\n * included.\n *\n * Nothing is bundled: PostHog comes from the app's own `posthog-js` (pass\n * `posthog.load`) or from its script on the configured host, Metrica from\n * its tag script. Both load only when `initAnalytics` asks for them.\n *\n * ```ts\n * initAnalytics({ zone: \"public\", posthog: { key, host: \"https://example.com/ingest\" }, metrika: { counterId: 12345678 } });\n * track(\"signup_started\");\n * ```\n */\n\nimport { rememberAnalyticsIds } from \"./resources/attribution.js\";\n\n/** Where the page lives. Decides what is captured and what is masked. */\nexport type AnalyticsZone = \"public\" | \"cabinet\" | \"miniapp\";\n\n/** Every event name the layer accepts. The first two come from the browser\n * on public pages; the rest match the event types of the platform's\n * `analytics_events` view, so a report reads the same names on both sides. */\nexport const ANALYTICS_EVENTS = [\n \"signup_started\",\n \"signup_completed\",\n \"signup\",\n \"login\",\n \"deposit_started\",\n \"deposit_confirmed\",\n \"deposit_failed\",\n \"card_issued\",\n \"card_issue_failed\",\n \"card_activated\",\n \"card_topped_up\",\n \"card_transferred\",\n \"card_frozen\",\n \"card_unfrozen\",\n \"card_terminated\",\n \"txn_cleared\",\n \"txn_declined\",\n \"subscription_started\",\n \"subscription_renewed\",\n \"subscription_cancelled\",\n \"fee_charged\",\n \"refund_issued\",\n] as const;\n\nexport type AnalyticsEvent = (typeof ANALYTICS_EVENTS)[number];\n\n/** Events that also go to Metrica as goals, from public pages only. Deposits,\n * cards and subscriptions reach Metrica from the server with their value. */\nexport const METRIKA_GOALS: readonly AnalyticsEvent[] = [\"signup_started\", \"signup_completed\"];\n\ntype Primitive = string | number | boolean | null | undefined;\nexport type AnalyticsProperties = Record<string, Primitive | Primitive[]>;\n\n/**\n * Mark a block that must never be recorded or autocaptured: card details,\n * balances, the operations history. PostHog honours this class in\n * autocapture and in session recordings.\n */\nexport const NO_CAPTURE_CLASS = \"ph-no-capture\";\n\n/** The subset of the `posthog-js` instance the layer uses. */\nexport interface PostHogLike {\n init(key: string, config: Record<string, unknown>): unknown;\n capture(event: string, properties?: Record<string, unknown>): unknown;\n identify(distinctId: string): unknown;\n reset(): unknown;\n get_distinct_id(): string;\n register(properties: Record<string, unknown>): unknown;\n set_config(config: Record<string, unknown>): unknown;\n startSessionRecording?(): unknown;\n stopSessionRecording?(): unknown;\n}\n\nexport interface PostHogOptions {\n /** Project key (`phc_…`). Write-only, safe in the browser. */\n key: string;\n /** Where events go. Point it at the proxy path on your own domain, e.g.\n * `https://example.com/ingest`. Default `https://eu.i.posthog.com`. */\n host?: string;\n /** PostHog's own app, for links from the toolbar. Default `https://eu.posthog.com`. */\n uiHost?: string;\n /** Where the script comes from when `load` is not given. Default: the\n * `-assets` twin of a PostHog host, or `host` itself for a proxy. */\n assetsHost?: string;\n /** Return the app's own `posthog-js` instance, usually\n * `() => import(\"posthog-js\").then((m) => m.default)` (1.187 or later).\n * Without it the script is loaded from `assetsHost`. */\n load?: () => Promise<PostHogLike>;\n /** Record sessions in the cabinet and the Mini App, masked. Off by\n * default; turn it on only after checking a recording shows no values.\n * Never recorded on public pages. */\n sessionRecording?: boolean;\n}\n\nexport interface MetrikaOptions {\n counterId: number | string;\n /** Tag script address. Default `https://mc.yandex.ru/metrika/tag.js`. */\n scriptUrl?: string;\n}\n\nexport interface AnalyticsOptions {\n zone: AnalyticsZone;\n posthog?: PostHogOptions;\n /** Used on public pages only; ignored in the cabinet and the Mini App. */\n metrika?: MetrikaOptions;\n /** Send the first page view right away. Default `true`; after that call\n * {@link page} on every route change. */\n initialPageview?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// The filter on the way out\n// ---------------------------------------------------------------------------\n\nconst UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;\nconst EMAIL = /[^\\s@\"'<>(),;:]+@[^\\s@\"'<>(),;:]+\\.[a-z]{2,}/gi;\n/** A run of digits with phone or card separators: 9 to 19 digits is a phone\n * or a card number, never something to send. */\nconst DIGIT_RUN = /\\+?\\d[\\d\\s().-]{7,}\\d/g;\nconst UUID_ONLY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n/** A path segment or a query value that is an id: a number, a UUID, a hex\n * string, or a long token of letters and digits. Slugs have dashes and\n * stay, even with a year in them. */\nfunction isId(v: string): boolean {\n return (\n /^\\d+$/.test(v) ||\n UUID_ONLY.test(v) ||\n /^[0-9a-f]{16,}$/i.test(v) ||\n (/^[A-Za-z0-9_]{20,}$/.test(v) && /\\d.*\\d/.test(v) && /[A-Za-z].*[A-Za-z]/.test(v))\n );\n}\nconst PLACEHOLDER = \":id\";\n\n/** Keys whose value is personal whatever it looks like: any key with one of\n * these words... */\nconst PERSONAL_WORDS = new Set([\n \"email\",\n \"mail\",\n \"phone\",\n \"tel\",\n \"telephone\",\n \"mobile\",\n \"msisdn\",\n \"surname\",\n \"patronymic\",\n \"firstname\",\n \"lastname\",\n \"fullname\",\n \"username\",\n \"nickname\",\n]);\n/** ...and `name` alone or after one of these (`first_name`, `holder_name`).\n * `merchant_name` names a company and stays. */\nconst PERSON_NAME_QUALIFIERS = new Set([\n \"first\",\n \"last\",\n \"full\",\n \"user\",\n \"display\",\n \"given\",\n \"family\",\n \"middle\",\n \"nick\",\n \"real\",\n \"holder\",\n \"cardholder\",\n \"customer\",\n \"contact\",\n \"person\",\n \"owner\",\n \"account\",\n \"legal\",\n]);\n/** Query keys that carry secrets or personal data. */\nconst SECRET_QUERY_WORDS = new Set([\n \"token\",\n \"code\",\n \"key\",\n \"secret\",\n \"password\",\n \"pass\",\n \"pwd\",\n \"otp\",\n \"sig\",\n \"signature\",\n \"session\",\n \"sid\",\n \"auth\",\n \"jwt\",\n \"pan\",\n \"cvv\",\n \"cvc\",\n \"iban\",\n]);\n/** Money is not personal: kept as it is. */\nconst MONEY_KEYS = new Set([\n \"amount\",\n \"amount_minor\",\n \"currency\",\n \"value\",\n \"price\",\n \"revenue\",\n \"sum\",\n]);\n\nfunction words(key: string): string[] {\n return key\n .replace(/^\\$+/, \"\")\n .replace(/([a-z])([A-Z])/g, \"$1_$2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean);\n}\n\nfunction personalKey(key: string): boolean {\n const w = words(key);\n const joined = w.join(\"\");\n if (joined.includes(\"email\") || joined.includes(\"phone\")) return true;\n if (w.some((x) => PERSONAL_WORDS.has(x)) || PERSONAL_WORDS.has(joined)) return true;\n // PostHog's own `$…` keys are never names of people.\n if (key.startsWith(\"$\")) return false;\n return w.some(\n (x, i) => x === \"name\" && (w.length === 1 || PERSON_NAME_QUALIFIERS.has(w[i - 1] ?? \"\")),\n );\n}\n\nfunction urlKey(key: string): boolean {\n const k = key.replace(/^\\$+/, \"\").toLowerCase();\n return (\n /(^|_)(url|href|pathname|path|referrer|referer)$/.test(k) ||\n k === \"page\" ||\n k.startsWith(\"attr__href\")\n );\n}\n\nfunction digitCount(s: string): number {\n return s.replace(/\\D/g, \"\").length;\n}\n\n/** Text with e-mail addresses, phone and card numbers cut out. */\nfunction redactText(v: string): string {\n return v\n .replace(EMAIL, \"[email]\")\n .replace(DIGIT_RUN, (m) => (digitCount(m) >= 9 && digitCount(m) <= 19 ? \"[number]\" : m));\n}\n\nfunction idSegment(seg: string): string {\n let s = seg;\n try {\n s = decodeURIComponent(seg);\n } catch {\n // Leave a broken escape as it is.\n }\n if (isId(s)) return PLACEHOLDER;\n const replaced = s.replace(UUID, PLACEHOLDER);\n if (replaced !== s) return replaced;\n return redactText(s) === s ? seg : PLACEHOLDER;\n}\n\n/**\n * A page address fit to send: UUIDs, numeric ids and long tokens in the\n * path become `:id`; query parameters that carry secrets or personal data\n * are dropped, ids among their values become `:id`; the fragment is dropped.\n * Campaign tags stay.\n */\nexport function sanitizeUrl(raw: string): string {\n const absolute = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(raw);\n let u: URL;\n try {\n u = new URL(raw, \"http://relative.invalid\");\n } catch {\n return redactText(raw.split(/[?#]/)[0] ?? \"\").replace(UUID, PLACEHOLDER);\n }\n const path = u.pathname\n .split(\"/\")\n .map((seg) => (seg ? idSegment(seg) : seg))\n .join(\"/\");\n const query: string[] = [];\n u.searchParams.forEach((value, key) => {\n const k = words(key);\n if (k.some((w) => SECRET_QUERY_WORDS.has(w)) || personalKey(key)) return;\n if (redactText(value) !== value) return;\n query.push(\n `${encodeURIComponent(key)}=${isId(value) ? PLACEHOLDER : encodeURIComponent(value)}`,\n );\n });\n const search = query.length ? `?${query.join(\"&\")}` : \"\";\n return (absolute ? `${u.protocol}//${u.host}` : \"\") + path + search;\n}\n\nfunction cleanValue(key: string, v: unknown, depth: number): unknown {\n if (v === null || v === undefined || typeof v === \"number\" || typeof v === \"boolean\") return v;\n if (typeof v === \"string\") {\n // Money, and whole ids such as PostHog's session and device ids.\n if (MONEY_KEYS.has(key.toLowerCase()) || UUID_ONLY.test(v)) return v;\n if (urlKey(key) || /^https?:\\/\\//i.test(v)) return sanitizeUrl(v);\n if (key === \"$elements_chain\") {\n return redactText(v).replace(\n /attr__href=\"([^\"]*)\"/g,\n (_, h: string) => `attr__href=\"${sanitizeUrl(h)}\"`,\n );\n }\n const r = redactText(v);\n // A value that was nothing but an address or a number goes entirely.\n return r.replace(/\\[(email|number)\\]/g, \"\").trim() === \"\" && r !== v ? undefined : r;\n }\n if (depth > 5) return undefined;\n if (Array.isArray(v))\n return v.map((x) => cleanValue(key, x, depth + 1)).filter((x) => x !== undefined);\n if (typeof v === \"object\") return sanitizeProperties(v as Record<string, unknown>, depth + 1);\n return undefined;\n}\n\n/**\n * The filter every event passes before it leaves the browser. Drops keys\n * that name personal data (`email`, `phone`, `name`, `first_name`, …) and\n * values that look like an e-mail address, a phone or a card number; page\n * addresses go through {@link sanitizeUrl}. Amounts and currencies pass.\n */\nexport function sanitizeProperties<T extends Record<string, unknown>>(\n props: T,\n depth = 0,\n): Partial<T> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(props)) {\n if (personalKey(k)) continue;\n const c = cleanValue(k, v, depth);\n if (c !== undefined) out[k] = c;\n }\n return out as Partial<T>;\n}\n\n/** PostHog's `before_send`: the same filter for what PostHog captures by itself. */\nfunction beforeSend<\n E extends {\n properties?: Record<string, unknown>;\n $set?: Record<string, unknown>;\n $set_once?: Record<string, unknown>;\n },\n>(event: E | null): E | null {\n if (!event) return event;\n const out = { ...event };\n if (event.properties) out.properties = sanitizeProperties(event.properties);\n if (event.$set) out.$set = sanitizeProperties(event.$set);\n if (event.$set_once) out.$set_once = sanitizeProperties(event.$set_once);\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Systems. A new one is a Sink plus a line in `sinksFor`.\n// ---------------------------------------------------------------------------\n\ninterface Sink {\n capture(event: AnalyticsEvent, props: AnalyticsProperties): void;\n page(url: string, referrer: string | undefined): void;\n identify(userId: string): void;\n reset(): void;\n setZone(zone: AnalyticsZone): void;\n}\n\ninterface Win {\n document?: Document;\n location?: Location;\n posthog?: unknown;\n ym?: ((...args: unknown[]) => void) & { a?: unknown[]; l?: number };\n}\n\nconst win = () => globalThis as unknown as Win;\n\nfunction injectScript(src: string, onLoad?: () => void, onError?: () => void): void {\n const doc = win().document;\n if (!doc) return;\n const s = doc.createElement(\"script\");\n s.async = true;\n s.src = src;\n s.crossOrigin = \"anonymous\";\n if (onLoad) s.addEventListener(\"load\", onLoad);\n if (onError) s.addEventListener(\"error\", onError);\n (doc.head ?? doc.documentElement).appendChild(s);\n}\n\nfunction posthogConfig(zone: AnalyticsZone, o: PostHogOptions): Record<string, unknown> {\n const host = (o.host ?? \"https://eu.i.posthog.com\").replace(/\\/+$/, \"\");\n const base: Record<string, unknown> = {\n api_host: host,\n ui_host: o.uiHost ?? \"https://eu.posthog.com\",\n // Profiles for signed-in users only.\n person_profiles: \"identified_only\",\n // Page views go through `page()`, with a cleaned address.\n capture_pageview: false,\n capture_pageleave: true,\n before_send: beforeSend,\n };\n return { ...base, ...zoneConfig(zone, o) };\n}\n\n/** What changes with the zone. Applied at init and on `setAnalyticsZone`. */\nfunction zoneConfig(zone: AnalyticsZone, o: PostHogOptions): Record<string, unknown> {\n if (zone === \"public\") {\n return {\n autocapture: true,\n mask_all_text: false,\n mask_all_element_attributes: false,\n enable_heatmaps: true,\n disable_session_recording: true,\n };\n }\n return {\n // A click is \"the third button in the cards block\", never its label.\n autocapture: { capture_copied_text: false },\n mask_all_text: true,\n mask_all_element_attributes: true,\n enable_heatmaps: false,\n disable_session_recording: !o.sessionRecording,\n session_recording: {\n maskAllInputs: true,\n maskTextSelector: \"*\",\n blockClass: NO_CAPTURE_CLASS,\n },\n };\n}\n\nfunction assetsHost(o: PostHogOptions): string {\n if (o.assetsHost) return o.assetsHost.replace(/\\/+$/, \"\");\n const host = (o.host ?? \"https://eu.i.posthog.com\").replace(/\\/+$/, \"\");\n return host.replace(\".i.posthog.com\", \"-assets.i.posthog.com\");\n}\n\n/** Load posthog-js the way its own snippet does: a placeholder that the\n * script replaces with the instance once it runs. */\nfunction loadPostHogScript(\n o: PostHogOptions,\n config: Record<string, unknown>,\n): Promise<PostHogLike | undefined> {\n return new Promise((resolve) => {\n const w = win();\n if (!w.document) return resolve(undefined);\n const placeholder = Object.assign([] as unknown[], {\n __SV: 1,\n _i: [[o.key, config, \"posthog\"]],\n });\n w.posthog = placeholder;\n injectScript(\n `${assetsHost(o)}/static/array.js`,\n () => {\n const ph = w.posthog;\n const live =\n ph !== placeholder && typeof (ph as PostHogLike | undefined)?.capture === \"function\";\n resolve(live ? (ph as PostHogLike) : undefined);\n },\n () => resolve(undefined),\n );\n });\n}\n\nclass PostHogSink implements Sink {\n readonly ready: Promise<PostHogLike | undefined>;\n\n constructor(\n private readonly o: PostHogOptions,\n zone: AnalyticsZone,\n ) {\n const config = posthogConfig(zone, o);\n this.ready = (\n o.load\n ? o.load().then((ph) => {\n ph.init(o.key, config);\n return ph;\n })\n : loadPostHogScript(o, config)\n )\n .then((ph) => {\n ph?.register({ zone });\n return ph;\n })\n .catch(() => undefined);\n }\n\n private with(fn: (ph: PostHogLike) => void): void {\n void this.ready.then((ph) => ph && fn(ph));\n }\n\n capture(event: AnalyticsEvent, props: AnalyticsProperties): void {\n this.with((ph) => ph.capture(event, props));\n }\n page(url: string, referrer: string | undefined): void {\n const props: Record<string, unknown> = { $current_url: url };\n if (referrer) props.$referrer = referrer;\n this.with((ph) => ph.capture(\"$pageview\", props));\n }\n identify(userId: string): void {\n this.with((ph) => ph.identify(userId));\n }\n reset(): void {\n this.with((ph) => ph.reset());\n }\n setZone(zone: AnalyticsZone): void {\n this.with((ph) => {\n ph.set_config(zoneConfig(zone, this.o));\n ph.register({ zone });\n if (zone === \"public\" || !this.o.sessionRecording) ph.stopSessionRecording?.();\n else ph.startSessionRecording?.();\n });\n }\n}\n\n/** Metrica, public pages only. It never records on its own: no Webvisor, no\n * click map, no automatic page views. It sees exactly what this layer\n * sends, and falls silent when the zone leaves `public`. */\nclass MetrikaSink implements Sink {\n private live = true;\n private readonly id: number;\n\n constructor(o: MetrikaOptions) {\n this.id = Number(o.counterId);\n const w = win();\n if (!w.ym) {\n const ym = ((...args: unknown[]) => {\n (ym.a = ym.a ?? []).push(args);\n }) as NonNullable<Win[\"ym\"]>;\n ym.l = Date.now();\n w.ym = ym;\n injectScript(o.scriptUrl ?? \"https://mc.yandex.ru/metrika/tag.js\");\n }\n this.ym(\"init\", {\n defer: true,\n webvisor: false,\n clickmap: false,\n trackLinks: false,\n accurateTrackBounce: true,\n });\n // The sink exists only once the visitor agreed to analytics: keep the\n // ClientID for the server's conversions (TKL-329).\n this.ym(\"getClientID\", (id: unknown) => {\n if (id !== undefined && id !== null) rememberAnalyticsIds({ metrika_client_id: String(id) });\n });\n }\n\n private ym(...args: unknown[]): void {\n if (this.live) win().ym?.(this.id, ...args);\n }\n\n capture(event: AnalyticsEvent, props: AnalyticsProperties): void {\n if (METRIKA_GOALS.includes(event)) this.ym(\"reachGoal\", event, props);\n }\n page(url: string, referrer: string | undefined): void {\n this.ym(\"hit\", url, referrer ? { referer: referrer } : {});\n }\n identify(userId: string): void {\n // The same id the server sends with its conversions.\n this.ym(\"setUserID\", userId);\n }\n reset(): void {}\n setZone(zone: AnalyticsZone): void {\n this.live = zone === \"public\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// State, kept on globalThis: every sub-export bundles its own copy of this\n// file, and they must all talk to one set of systems.\n// ---------------------------------------------------------------------------\n\ninterface State {\n options: AnalyticsOptions;\n zone: AnalyticsZone;\n posthog?: PostHogSink;\n metrika?: MetrikaSink;\n lastPage?: string;\n userId?: string;\n}\n\nconst KEY = Symbol.for(\"takeal.cusfront-sdk.analytics\");\nconst holder = globalThis as unknown as Record<symbol, State | undefined>;\nconst state = (): State | undefined => holder[KEY];\n\nfunction sinks(s: State): Sink[] {\n // Metrica loads the first time the page is public, and never before.\n if (s.zone === \"public\" && s.options.metrika && !s.metrika) {\n s.metrika = new MetrikaSink(s.options.metrika);\n if (s.userId) s.metrika.identify(s.userId);\n }\n return [s.posthog, s.metrika].filter((x): x is PostHogSink | MetrikaSink => !!x);\n}\n\n/**\n * Start analytics for this page. Call once, as early as possible. A second\n * call does nothing; to move between the site and the cabinet in one app,\n * use {@link setAnalyticsZone}.\n */\nexport function initAnalytics(options: AnalyticsOptions): void {\n if (state() || !win().document) return;\n if (options.zone !== \"public\" && win().ym) {\n console.warn(\n \"[analytics] Yandex Metrica is on a page outside the public zone; it must not be.\",\n );\n }\n const s: State = { options, zone: options.zone };\n holder[KEY] = s;\n if (options.posthog?.key) s.posthog = new PostHogSink(options.posthog, options.zone);\n sinks(s);\n if (options.initialPageview !== false) page();\n}\n\n/**\n * The page moved to another zone without a reload (the site and the cabinet\n * in one app). PostHog switches its masking; Metrica falls silent outside\n * public pages. A full page load into the cabinet is safer still: Metrica is\n * then never on the page at all.\n */\nexport function setAnalyticsZone(zone: AnalyticsZone): void {\n const s = state();\n if (!s || s.zone === zone) return;\n s.zone = zone;\n for (const sink of sinks(s)) sink.setZone(zone);\n}\n\n/** Record an event. The name must be one of {@link ANALYTICS_EVENTS}. */\nexport function track(event: AnalyticsEvent, props: AnalyticsProperties = {}): void {\n const s = state();\n if (!s || !(ANALYTICS_EVENTS as readonly string[]).includes(event)) return;\n const clean = sanitizeProperties(props) as AnalyticsProperties;\n for (const sink of sinks(s)) sink.capture(event, clean);\n}\n\n/** A page view. Call it on every route change; the same address twice in a\n * row counts once. Takes the current address when none is given. */\nexport function page(url?: string): void {\n const s = state();\n const w = win();\n const raw = url ?? w.location?.href;\n if (!s || !raw) return;\n const clean = sanitizeUrl(raw);\n if (clean === s.lastPage) return;\n const referrer =\n s.lastPage ?? (w.document?.referrer ? sanitizeUrl(w.document.referrer) : undefined);\n s.lastPage = clean;\n for (const sink of sinks(s)) sink.page(clean, referrer);\n}\n\n/** After sign-in: tie this browser to the user by the platform's user id\n * (`session.user.id`), never by e-mail. Only signed-in users get profiles. */\nexport function identify(userId: string): void {\n const s = state();\n if (!s || !userId) return;\n s.userId = userId;\n for (const sink of sinks(s)) sink.identify(userId);\n}\n\n/** On sign-out: forget the user, so the next person on this device starts\n * as a new visitor. */\nexport function resetAnalytics(): void {\n const s = state();\n if (!s) return;\n s.userId = undefined;\n for (const sink of sinks(s)) sink.reset();\n}\n\n/** PostHog's id for this browser, for `auth.register({ attribution: {\n * posthog_distinct_id } })`. Waits for PostHog to load, `timeoutMs` at\n * most; `undefined` without PostHog. */\nexport async function posthogDistinctId(timeoutMs = 3000): Promise<string | undefined> {\n const ready = state()?.posthog?.ready;\n if (!ready) return undefined;\n let timer: Parameters<typeof clearTimeout>[0];\n const timeout = new Promise<undefined>((r) => {\n timer = setTimeout(r, timeoutMs);\n });\n const ph = await Promise.race([ready, timeout]);\n clearTimeout(timer);\n try {\n return ph?.get_distinct_id() || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** For tests: forget everything `initAnalytics` set up. */\nexport function _resetAnalyticsForTests(): void {\n holder[KEY] = undefined;\n}\n"]}
1
+ {"version":3,"sources":["../src/resources/attribution.ts","../src/analytics.ts"],"names":["clean"],"mappings":";;;AAwPA,IAAM,OAAA,GAAU,sBAAA;AAEhB,SAAS,OAAA,GAA+B;AACtC,EAAA,IAAI;AACF,IAAA,OAAQ,UAAA,CAA0C,YAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAEA,SAAS,MAAA,GAAuB;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,OAAA,EAAQ,EAAG,OAAA,CAAQ,OAAO,CAAA;AACtC,IAAA,MAAM,IAAI,GAAA,GAAO,IAAA,CAAK,KAAA,CAAM,GAAG,IAAqB,EAAC;AAC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AAA,GAAI,MAAA;AAChB","file":"analytics.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","/**\n * `@takeal/cusfront-sdk/analytics` — one event layer for product analytics.\n *\n * The app calls {@link track} once per event; the layer hands it to every\n * configured system: PostHog everywhere, Yandex Metrica only on public pages\n * and only for the sign-up goals (what happens behind the login reaches\n * Metrica from the server, not from the browser). Every event passes\n * {@link sanitizeProperties} on the way out, PostHog's own autocapture\n * included.\n *\n * Nothing is bundled: PostHog comes from the app's own `posthog-js` (pass\n * `posthog.load`) or from its script on the configured host, Metrica from\n * its tag script. Both load only when `initAnalytics` asks for them.\n *\n * ```ts\n * initAnalytics({ zone: \"public\", posthog: { key, host: \"https://example.com/ingest\" }, metrika: { counterId: 12345678 } });\n * track(\"signup_started\");\n * ```\n */\n\nimport { rememberAnalyticsIds } from \"./resources/attribution.js\";\n\n/** Where the page lives. Decides what is captured and what is masked. */\nexport type AnalyticsZone = \"public\" | \"cabinet\" | \"miniapp\";\n\n/** Every event name the layer accepts. The first two come from the browser\n * on public pages; the rest match the event types of the platform's\n * `analytics_events` view, so a report reads the same names on both sides. */\nexport const ANALYTICS_EVENTS = [\n \"signup_started\",\n \"signup_completed\",\n \"signup\",\n \"login\",\n \"deposit_started\",\n \"deposit_confirmed\",\n \"deposit_failed\",\n \"card_issued\",\n \"card_issue_failed\",\n \"card_activated\",\n \"card_topped_up\",\n \"card_transferred\",\n \"card_frozen\",\n \"card_unfrozen\",\n \"card_terminated\",\n \"txn_cleared\",\n \"txn_declined\",\n \"subscription_started\",\n \"subscription_renewed\",\n \"subscription_cancelled\",\n \"fee_charged\",\n \"refund_issued\",\n] as const;\n\nexport type AnalyticsEvent = (typeof ANALYTICS_EVENTS)[number];\n\n/** Events that also go to Metrica as goals, from public pages only. Deposits,\n * cards and subscriptions reach Metrica from the server with their value. */\nexport const METRIKA_GOALS: readonly AnalyticsEvent[] = [\"signup_started\", \"signup_completed\"];\n\ntype Primitive = string | number | boolean | null | undefined;\nexport type AnalyticsProperties = Record<string, Primitive | Primitive[]>;\n\n/**\n * Mark a block that must never be recorded or autocaptured: card details,\n * balances, the operations history. PostHog honours this class in\n * autocapture and in session recordings.\n */\nexport const NO_CAPTURE_CLASS = \"ph-no-capture\";\n\n/** The subset of the `posthog-js` instance the layer uses. */\nexport interface PostHogLike {\n init(key: string, config: Record<string, unknown>): unknown;\n capture(event: string, properties?: Record<string, unknown>): unknown;\n identify(distinctId: string): unknown;\n reset(): unknown;\n get_distinct_id(): string;\n register(properties: Record<string, unknown>): unknown;\n set_config(config: Record<string, unknown>): unknown;\n startSessionRecording?(): unknown;\n stopSessionRecording?(): unknown;\n}\n\nexport interface PostHogOptions {\n /** Project key (`phc_…`). Write-only, safe in the browser. */\n key: string;\n /** Where events go. Point it at the proxy path on your own domain, e.g.\n * `https://example.com/ingest`. Default `https://eu.i.posthog.com`. */\n host?: string;\n /** PostHog's own app, for links from the toolbar. Default `https://eu.posthog.com`. */\n uiHost?: string;\n /** Where the script comes from when `load` is not given. Default: the\n * `-assets` twin of a PostHog host, or `host` itself for a proxy. */\n assetsHost?: string;\n /** Return the app's own `posthog-js` instance, usually\n * `() => import(\"posthog-js\").then((m) => m.default)` (1.187 or later).\n * Without it the script is loaded from `assetsHost`. */\n load?: () => Promise<PostHogLike>;\n /** Record sessions in the cabinet and the Mini App, masked. Off by\n * default; turn it on only after checking a recording shows no values.\n * Never recorded on public pages. */\n sessionRecording?: boolean;\n}\n\nexport interface MetrikaOptions {\n counterId: number | string;\n /** Tag script address. Default `https://mc.yandex.ru/metrika/tag.js`. */\n scriptUrl?: string;\n}\n\nexport interface AnalyticsOptions {\n zone: AnalyticsZone;\n posthog?: PostHogOptions;\n /** Used on public pages only; ignored in the cabinet and the Mini App. */\n metrika?: MetrikaOptions;\n /** Send the first page view right away. Default `true`; after that call\n * {@link page} on every route change. */\n initialPageview?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// The filter on the way out\n// ---------------------------------------------------------------------------\n\nconst UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;\nconst EMAIL = /[^\\s@\"'<>(),;:]+@[^\\s@\"'<>(),;:]+\\.[a-z]{2,}/gi;\n/** A run of digits with phone or card separators: 9 to 19 digits is a phone\n * or a card number, never something to send. */\nconst DIGIT_RUN = /\\+?\\d[\\d\\s().-]{7,}\\d/g;\nconst UUID_ONLY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n/** A path segment or a query value that is an id: a number, a UUID, a hex\n * string, or a long token of letters and digits. Slugs have dashes and\n * stay, even with a year in them. */\nfunction isId(v: string): boolean {\n return (\n /^\\d+$/.test(v) ||\n UUID_ONLY.test(v) ||\n /^[0-9a-f]{16,}$/i.test(v) ||\n (/^[A-Za-z0-9_]{20,}$/.test(v) && /\\d.*\\d/.test(v) && /[A-Za-z].*[A-Za-z]/.test(v))\n );\n}\nconst PLACEHOLDER = \":id\";\n\n/** Keys whose value is personal whatever it looks like: any key with one of\n * these words... */\nconst PERSONAL_WORDS = new Set([\n \"email\",\n \"mail\",\n \"phone\",\n \"tel\",\n \"telephone\",\n \"mobile\",\n \"msisdn\",\n \"surname\",\n \"patronymic\",\n \"firstname\",\n \"lastname\",\n \"fullname\",\n \"username\",\n \"nickname\",\n]);\n/** ...and `name` alone or after one of these (`first_name`, `holder_name`).\n * `merchant_name` names a company and stays. */\nconst PERSON_NAME_QUALIFIERS = new Set([\n \"first\",\n \"last\",\n \"full\",\n \"user\",\n \"display\",\n \"given\",\n \"family\",\n \"middle\",\n \"nick\",\n \"real\",\n \"holder\",\n \"cardholder\",\n \"customer\",\n \"contact\",\n \"person\",\n \"owner\",\n \"account\",\n \"legal\",\n]);\n/** Query keys that carry secrets or personal data. */\nconst SECRET_QUERY_WORDS = new Set([\n \"token\",\n \"code\",\n \"key\",\n \"secret\",\n \"password\",\n \"pass\",\n \"pwd\",\n \"otp\",\n \"sig\",\n \"signature\",\n \"session\",\n \"sid\",\n \"auth\",\n \"jwt\",\n \"pan\",\n \"cvv\",\n \"cvc\",\n \"iban\",\n]);\n/** Money is not personal: kept as it is. */\nconst MONEY_KEYS = new Set([\n \"amount\",\n \"amount_minor\",\n \"currency\",\n \"value\",\n \"price\",\n \"revenue\",\n \"sum\",\n]);\n\nfunction words(key: string): string[] {\n return key\n .replace(/^\\$+/, \"\")\n .replace(/([a-z])([A-Z])/g, \"$1_$2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean);\n}\n\nfunction personalKey(key: string): boolean {\n const w = words(key);\n const joined = w.join(\"\");\n if (joined.includes(\"email\") || joined.includes(\"phone\")) return true;\n if (w.some((x) => PERSONAL_WORDS.has(x)) || PERSONAL_WORDS.has(joined)) return true;\n // PostHog's own `$…` keys are never names of people.\n if (key.startsWith(\"$\")) return false;\n return w.some(\n (x, i) => x === \"name\" && (w.length === 1 || PERSON_NAME_QUALIFIERS.has(w[i - 1] ?? \"\")),\n );\n}\n\nfunction urlKey(key: string): boolean {\n const k = key.replace(/^\\$+/, \"\").toLowerCase();\n return (\n /(^|_)(url|href|pathname|path|referrer|referer)$/.test(k) ||\n k === \"page\" ||\n k.startsWith(\"attr__href\")\n );\n}\n\nfunction digitCount(s: string): number {\n return s.replace(/\\D/g, \"\").length;\n}\n\n/** Text with e-mail addresses, phone and card numbers cut out. */\nfunction redactText(v: string): string {\n return v\n .replace(EMAIL, \"[email]\")\n .replace(DIGIT_RUN, (m) => (digitCount(m) >= 9 && digitCount(m) <= 19 ? \"[number]\" : m));\n}\n\n// ---------------------------------------------------------------------------\n// Advertising fields: campaign tags and click ids\n// ---------------------------------------------------------------------------\n\n/** Campaign tags. Their values are ids and names an ad account fills in\n * (`{campaign_name}_{campaign_id}`, `{ad_id}`), and long numbers in them are\n * ids, not phones. */\nexport const UTM_PARAMS = [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_content\",\n \"utm_term\",\n] as const;\n\n/** Click ids of ad networks and search engines: the same list the platform\n * reads from a landing address. Their values go out exactly as they came. */\nexport const CLICK_ID_PARAMS = [\n \"yclid\",\n \"ysclid\",\n \"gclid\",\n \"gbraid\",\n \"wbraid\",\n \"fbclid\",\n \"ttclid\",\n \"msclkid\",\n \"rb_clickid\",\n] as const;\n\nconst UTM_SET = new Set<string>(UTM_PARAMS);\nconst CLICK_ID_SET = new Set<string>(CLICK_ID_PARAMS);\n/** What a click id is made of: letters, digits, `-`, `_`, `.`, `~`, at most\n * 256 of them. A 20-digit `yclid` stays a string, never a number. */\nconst CLICK_ID_VALUE = /^[A-Za-z0-9._~-]{1,256}$/;\n\n/** Which advertising field a key names, if any. PostHog's copies of the tags\n * (`$initial_utm_source`, `$initial_gclid`) count too. */\nfunction adField(key: string): \"utm\" | \"click\" | undefined {\n const k = key\n .replace(/^\\$+/, \"\")\n .toLowerCase()\n .replace(/^initial_/, \"\");\n if (UTM_SET.has(k)) return \"utm\";\n if (CLICK_ID_SET.has(k)) return \"click\";\n return undefined;\n}\n\nfunction luhn(digits: string): boolean {\n let sum = 0;\n for (let i = 0; i < digits.length; i++) {\n let d = digits.charCodeAt(digits.length - 1 - i) - 48;\n if (i % 2 === 1) {\n d *= 2;\n if (d > 9) d -= 9;\n }\n sum += d;\n }\n return sum % 10 === 0;\n}\n\n/** A run of digits, possibly with a leading `+` and phone or card separators\n * between the digits. */\nconst NUMBER_RUN = /(?:\\+\\s*)?\\d(?:[\\d\\s().-]*\\d)?/g;\n\n/**\n * Personal data inside a campaign tag. Ids of any length stay; what goes:\n *\n * - an `@` anywhere (an e-mail address);\n * - a number written as a phone: with a leading `+` (9 to 15 digits), or in\n * groups split by spaces, dashes, dots or brackets with 9 to 19 digits in\n * all, where a bracket is present or no group is longer than 4 digits\n * (`8 (900) 123-45-67`, `4242 4242 4242 4242`);\n * - a bare run of 16 to 19 digits that passes the card checksum;\n * - a token: a piece of 20 or more letters and digits with at least two of\n * each, between `_`, `-`, `.`, `~`, `+` or spaces (a JWT, an API key).\n *\n * A bare run of digits shorter than 16 or longer than 19 (`716512542`, a\n * 20-digit id) is an id and stays; outside the advertising fields the\n * general filter still removes any 9 to 19 digits.\n */\nexport function adValuePersonal(v: string): boolean {\n if (v.includes(\"@\")) return true;\n for (const m of v.match(NUMBER_RUN) ?? []) {\n const groups = m.split(/\\D+/).filter(Boolean);\n const n = groups.join(\"\").length;\n if (m.startsWith(\"+\")) {\n if (n >= 9 && n <= 15) return true;\n continue;\n }\n if (groups.length === 1) {\n if (n >= 16 && n <= 19 && luhn(groups[0]!)) return true;\n continue;\n }\n if (n >= 9 && n <= 19 && (/[()]/.test(m) || groups.every((g) => g.length <= 4))) return true;\n }\n return v\n .split(/[\\s_.~+-]+/)\n .some((seg) => seg.length >= 20 && /\\d.*\\d/.test(seg) && /[A-Za-z].*[A-Za-z]/.test(seg));\n}\n\n/** The value of an advertising field fit to send, or `undefined` to drop it. */\nfunction adValue(kind: \"utm\" | \"click\", v: string): string | undefined {\n if (kind === \"click\") return CLICK_ID_VALUE.test(v) ? v : undefined;\n return adValuePersonal(v) ? undefined : v;\n}\n\nfunction idSegment(seg: string): string {\n let s = seg;\n try {\n s = decodeURIComponent(seg);\n } catch {\n // Leave a broken escape as it is.\n }\n if (isId(s)) return PLACEHOLDER;\n const replaced = s.replace(UUID, PLACEHOLDER);\n if (replaced !== s) return replaced;\n return redactText(s) === s ? seg : PLACEHOLDER;\n}\n\nfunction decodeQueryPart(s: string): string {\n try {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n } catch {\n return s;\n }\n}\n\n/**\n * A page address fit to send: UUIDs, numeric ids and long tokens in the\n * path become `:id`; query parameters that carry secrets or personal data\n * are dropped, ids among their values become `:id`; the fragment is dropped.\n *\n * Campaign tags (`utm_*`) and click ids (`yclid`, `gclid`, …) stay exactly as\n * they were written, ids in them included, unless {@link adValuePersonal}\n * finds an address, a phone, a card number or a token in a tag, or a click\n * id has characters a click id never has; then that one parameter goes.\n */\nexport function sanitizeUrl(raw: string): string {\n const absolute = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(raw);\n let u: URL;\n try {\n u = new URL(raw, \"http://relative.invalid\");\n } catch {\n return redactText(raw.split(/[?#]/)[0] ?? \"\").replace(UUID, PLACEHOLDER);\n }\n const path = u.pathname\n .split(\"/\")\n .map((seg) => (seg ? idSegment(seg) : seg))\n .join(\"/\");\n const query: string[] = [];\n // Pair by pair on the address as written, so a kept parameter goes out\n // byte for byte as it came.\n for (const pair of u.search.replace(/^\\?/, \"\").split(\"&\")) {\n if (!pair) continue;\n const eq = pair.indexOf(\"=\");\n const rawKey = eq < 0 ? pair : pair.slice(0, eq);\n const key = decodeQueryPart(rawKey);\n const value = eq < 0 ? \"\" : decodeQueryPart(pair.slice(eq + 1));\n const ad = adField(key);\n if (ad) {\n if (adValue(ad, value) !== undefined) query.push(pair);\n continue;\n }\n const k = words(key);\n if (k.some((w) => SECRET_QUERY_WORDS.has(w)) || personalKey(key)) continue;\n if (redactText(value) !== value) continue;\n query.push(isId(value) ? `${rawKey}=${PLACEHOLDER}` : pair);\n }\n const search = query.length ? `?${query.join(\"&\")}` : \"\";\n return (absolute ? `${u.protocol}//${u.host}` : \"\") + path + search;\n}\n\nfunction cleanValue(key: string, v: unknown, depth: number): unknown {\n if (v === null || v === undefined || typeof v === \"number\" || typeof v === \"boolean\") return v;\n if (typeof v === \"string\") {\n // Money, and whole ids such as PostHog's session and device ids.\n if (MONEY_KEYS.has(key.toLowerCase()) || UUID_ONLY.test(v)) return v;\n // Campaign tags and click ids, PostHog's own copies of them included.\n const ad = adField(key);\n if (ad) return adValue(ad, v);\n if (urlKey(key) || /^https?:\\/\\//i.test(v)) return sanitizeUrl(v);\n if (key === \"$elements_chain\") {\n return redactText(v).replace(\n /attr__href=\"([^\"]*)\"/g,\n (_, h: string) => `attr__href=\"${sanitizeUrl(h)}\"`,\n );\n }\n const r = redactText(v);\n // A value that was nothing but an address or a number goes entirely.\n return r.replace(/\\[(email|number)\\]/g, \"\").trim() === \"\" && r !== v ? undefined : r;\n }\n if (depth > 5) return undefined;\n if (Array.isArray(v))\n return v.map((x) => cleanValue(key, x, depth + 1)).filter((x) => x !== undefined);\n if (typeof v === \"object\") return sanitizeProperties(v as Record<string, unknown>, depth + 1);\n return undefined;\n}\n\n/**\n * The filter every event passes before it leaves the browser. Drops keys\n * that name personal data (`email`, `phone`, `name`, `first_name`, …) and\n * values that look like an e-mail address, a phone or a card number; page\n * addresses go through {@link sanitizeUrl}. Amounts and currencies pass.\n */\nexport function sanitizeProperties<T extends Record<string, unknown>>(\n props: T,\n depth = 0,\n): Partial<T> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(props)) {\n if (personalKey(k)) continue;\n const c = cleanValue(k, v, depth);\n if (c !== undefined) out[k] = c;\n }\n return out as Partial<T>;\n}\n\n/** PostHog's `before_send`: the same filter for what PostHog captures by itself. */\nfunction beforeSend<\n E extends {\n properties?: Record<string, unknown>;\n $set?: Record<string, unknown>;\n $set_once?: Record<string, unknown>;\n },\n>(event: E | null): E | null {\n if (!event) return event;\n const out = { ...event };\n if (event.properties) out.properties = sanitizeProperties(event.properties);\n if (event.$set) out.$set = sanitizeProperties(event.$set);\n if (event.$set_once) out.$set_once = sanitizeProperties(event.$set_once);\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Systems. A new one is a Sink plus a line in `sinksFor`.\n// ---------------------------------------------------------------------------\n\ninterface Sink {\n capture(event: AnalyticsEvent, props: AnalyticsProperties): void;\n page(url: string, referrer: string | undefined): void;\n identify(userId: string): void;\n reset(): void;\n setZone(zone: AnalyticsZone): void;\n}\n\ninterface Win {\n document?: Document;\n location?: Location;\n posthog?: unknown;\n ym?: ((...args: unknown[]) => void) & { a?: unknown[]; l?: number };\n}\n\nconst win = () => globalThis as unknown as Win;\n\nfunction injectScript(src: string, onLoad?: () => void, onError?: () => void): void {\n const doc = win().document;\n if (!doc) return;\n const s = doc.createElement(\"script\");\n s.async = true;\n s.src = src;\n s.crossOrigin = \"anonymous\";\n if (onLoad) s.addEventListener(\"load\", onLoad);\n if (onError) s.addEventListener(\"error\", onError);\n (doc.head ?? doc.documentElement).appendChild(s);\n}\n\nfunction posthogConfig(zone: AnalyticsZone, o: PostHogOptions): Record<string, unknown> {\n const host = (o.host ?? \"https://eu.i.posthog.com\").replace(/\\/+$/, \"\");\n const base: Record<string, unknown> = {\n api_host: host,\n ui_host: o.uiHost ?? \"https://eu.posthog.com\",\n // Profiles for signed-in users only.\n person_profiles: \"identified_only\",\n // Page views go through `page()`, with a cleaned address.\n capture_pageview: false,\n capture_pageleave: true,\n before_send: beforeSend,\n };\n return { ...base, ...zoneConfig(zone, o) };\n}\n\n/** What changes with the zone. Applied at init and on `setAnalyticsZone`. */\nfunction zoneConfig(zone: AnalyticsZone, o: PostHogOptions): Record<string, unknown> {\n if (zone === \"public\") {\n return {\n autocapture: true,\n mask_all_text: false,\n mask_all_element_attributes: false,\n enable_heatmaps: true,\n disable_session_recording: true,\n };\n }\n return {\n // A click is \"the third button in the cards block\", never its label.\n autocapture: { capture_copied_text: false },\n mask_all_text: true,\n mask_all_element_attributes: true,\n enable_heatmaps: false,\n disable_session_recording: !o.sessionRecording,\n session_recording: {\n maskAllInputs: true,\n maskTextSelector: \"*\",\n blockClass: NO_CAPTURE_CLASS,\n },\n };\n}\n\nfunction assetsHost(o: PostHogOptions): string {\n if (o.assetsHost) return o.assetsHost.replace(/\\/+$/, \"\");\n const host = (o.host ?? \"https://eu.i.posthog.com\").replace(/\\/+$/, \"\");\n return host.replace(\".i.posthog.com\", \"-assets.i.posthog.com\");\n}\n\n/** Load posthog-js the way its own snippet does: a placeholder that the\n * script replaces with the instance once it runs. */\nfunction loadPostHogScript(\n o: PostHogOptions,\n config: Record<string, unknown>,\n): Promise<PostHogLike | undefined> {\n return new Promise((resolve) => {\n const w = win();\n if (!w.document) return resolve(undefined);\n const placeholder = Object.assign([] as unknown[], {\n __SV: 1,\n _i: [[o.key, config, \"posthog\"]],\n });\n w.posthog = placeholder;\n injectScript(\n `${assetsHost(o)}/static/array.js`,\n () => {\n const ph = w.posthog;\n const live =\n ph !== placeholder && typeof (ph as PostHogLike | undefined)?.capture === \"function\";\n resolve(live ? (ph as PostHogLike) : undefined);\n },\n () => resolve(undefined),\n );\n });\n}\n\nclass PostHogSink implements Sink {\n readonly ready: Promise<PostHogLike | undefined>;\n\n constructor(\n private readonly o: PostHogOptions,\n zone: AnalyticsZone,\n ) {\n const config = posthogConfig(zone, o);\n this.ready = (\n o.load\n ? o.load().then((ph) => {\n ph.init(o.key, config);\n return ph;\n })\n : loadPostHogScript(o, config)\n )\n .then((ph) => {\n ph?.register({ zone });\n return ph;\n })\n .catch(() => undefined);\n }\n\n private with(fn: (ph: PostHogLike) => void): void {\n void this.ready.then((ph) => ph && fn(ph));\n }\n\n capture(event: AnalyticsEvent, props: AnalyticsProperties): void {\n this.with((ph) => ph.capture(event, props));\n }\n page(url: string, referrer: string | undefined): void {\n const props: Record<string, unknown> = { $current_url: url };\n if (referrer) props.$referrer = referrer;\n this.with((ph) => ph.capture(\"$pageview\", props));\n }\n identify(userId: string): void {\n this.with((ph) => ph.identify(userId));\n }\n reset(): void {\n this.with((ph) => ph.reset());\n }\n setZone(zone: AnalyticsZone): void {\n this.with((ph) => {\n ph.set_config(zoneConfig(zone, this.o));\n ph.register({ zone });\n if (zone === \"public\" || !this.o.sessionRecording) ph.stopSessionRecording?.();\n else ph.startSessionRecording?.();\n });\n }\n}\n\n/** Metrica, public pages only. It never records on its own: no Webvisor, no\n * click map, no automatic page views. It sees exactly what this layer\n * sends, and falls silent when the zone leaves `public`. */\nclass MetrikaSink implements Sink {\n private live = true;\n private readonly id: number;\n\n constructor(o: MetrikaOptions) {\n this.id = Number(o.counterId);\n const w = win();\n if (!w.ym) {\n const ym = ((...args: unknown[]) => {\n (ym.a = ym.a ?? []).push(args);\n }) as NonNullable<Win[\"ym\"]>;\n ym.l = Date.now();\n w.ym = ym;\n injectScript(o.scriptUrl ?? \"https://mc.yandex.ru/metrika/tag.js\");\n }\n this.ym(\"init\", {\n defer: true,\n webvisor: false,\n clickmap: false,\n trackLinks: false,\n accurateTrackBounce: true,\n });\n // The sink exists only once the visitor agreed to analytics: keep the\n // ClientID for the server's conversions (TKL-329).\n this.ym(\"getClientID\", (id: unknown) => {\n if (id !== undefined && id !== null) rememberAnalyticsIds({ metrika_client_id: String(id) });\n });\n }\n\n private ym(...args: unknown[]): void {\n if (this.live) win().ym?.(this.id, ...args);\n }\n\n capture(event: AnalyticsEvent, props: AnalyticsProperties): void {\n if (METRIKA_GOALS.includes(event)) this.ym(\"reachGoal\", event, props);\n }\n page(url: string, referrer: string | undefined): void {\n this.ym(\"hit\", url, referrer ? { referer: referrer } : {});\n }\n identify(userId: string): void {\n // The same id the server sends with its conversions.\n this.ym(\"setUserID\", userId);\n }\n reset(): void {}\n setZone(zone: AnalyticsZone): void {\n this.live = zone === \"public\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// State, kept on globalThis: every sub-export bundles its own copy of this\n// file, and they must all talk to one set of systems.\n// ---------------------------------------------------------------------------\n\ninterface State {\n options: AnalyticsOptions;\n zone: AnalyticsZone;\n posthog?: PostHogSink;\n metrika?: MetrikaSink;\n lastPage?: string;\n userId?: string;\n}\n\nconst KEY = Symbol.for(\"takeal.cusfront-sdk.analytics\");\nconst holder = globalThis as unknown as Record<symbol, State | undefined>;\nconst state = (): State | undefined => holder[KEY];\n\nfunction sinks(s: State): Sink[] {\n // Metrica loads the first time the page is public, and never before.\n if (s.zone === \"public\" && s.options.metrika && !s.metrika) {\n s.metrika = new MetrikaSink(s.options.metrika);\n if (s.userId) s.metrika.identify(s.userId);\n }\n return [s.posthog, s.metrika].filter((x): x is PostHogSink | MetrikaSink => !!x);\n}\n\n/**\n * Start analytics for this page. Call once, as early as possible. A second\n * call does nothing; to move between the site and the cabinet in one app,\n * use {@link setAnalyticsZone}.\n */\nexport function initAnalytics(options: AnalyticsOptions): void {\n if (state() || !win().document) return;\n if (options.zone !== \"public\" && win().ym) {\n console.warn(\n \"[analytics] Yandex Metrica is on a page outside the public zone; it must not be.\",\n );\n }\n const s: State = { options, zone: options.zone };\n holder[KEY] = s;\n if (options.posthog?.key) s.posthog = new PostHogSink(options.posthog, options.zone);\n sinks(s);\n if (options.initialPageview !== false) page();\n}\n\n/**\n * The page moved to another zone without a reload (the site and the cabinet\n * in one app). PostHog switches its masking; Metrica falls silent outside\n * public pages. A full page load into the cabinet is safer still: Metrica is\n * then never on the page at all.\n */\nexport function setAnalyticsZone(zone: AnalyticsZone): void {\n const s = state();\n if (!s || s.zone === zone) return;\n s.zone = zone;\n for (const sink of sinks(s)) sink.setZone(zone);\n}\n\n/** Record an event. The name must be one of {@link ANALYTICS_EVENTS}. */\nexport function track(event: AnalyticsEvent, props: AnalyticsProperties = {}): void {\n const s = state();\n if (!s || !(ANALYTICS_EVENTS as readonly string[]).includes(event)) return;\n const clean = sanitizeProperties(props) as AnalyticsProperties;\n for (const sink of sinks(s)) sink.capture(event, clean);\n}\n\n/** A page view. Call it on every route change; the same address twice in a\n * row counts once. Takes the current address when none is given. */\nexport function page(url?: string): void {\n const s = state();\n const w = win();\n const raw = url ?? w.location?.href;\n if (!s || !raw) return;\n const clean = sanitizeUrl(raw);\n if (clean === s.lastPage) return;\n const referrer =\n s.lastPage ?? (w.document?.referrer ? sanitizeUrl(w.document.referrer) : undefined);\n s.lastPage = clean;\n for (const sink of sinks(s)) sink.page(clean, referrer);\n}\n\n/** After sign-in: tie this browser to the user by the platform's user id\n * (`session.user.id`), never by e-mail. Only signed-in users get profiles. */\nexport function identify(userId: string): void {\n const s = state();\n if (!s || !userId) return;\n s.userId = userId;\n for (const sink of sinks(s)) sink.identify(userId);\n}\n\n/** On sign-out: forget the user, so the next person on this device starts\n * as a new visitor. */\nexport function resetAnalytics(): void {\n const s = state();\n if (!s) return;\n s.userId = undefined;\n for (const sink of sinks(s)) sink.reset();\n}\n\n/** PostHog's id for this browser, for `auth.register({ attribution: {\n * posthog_distinct_id } })`. Waits for PostHog to load, `timeoutMs` at\n * most; `undefined` without PostHog. */\nexport async function posthogDistinctId(timeoutMs = 3000): Promise<string | undefined> {\n const ready = state()?.posthog?.ready;\n if (!ready) return undefined;\n let timer: Parameters<typeof clearTimeout>[0];\n const timeout = new Promise<undefined>((r) => {\n timer = setTimeout(r, timeoutMs);\n });\n const ph = await Promise.race([ready, timeout]);\n clearTimeout(timer);\n try {\n return ph?.get_distinct_id() || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** For tests: forget everything `initAnalytics` set up. */\nexport function _resetAnalyticsForTests(): void {\n holder[KEY] = undefined;\n}\n"]}
@@ -81,11 +81,39 @@ interface AnalyticsOptions {
81
81
  * {@link page} on every route change. */
82
82
  initialPageview?: boolean;
83
83
  }
84
+ /** Campaign tags. Their values are ids and names an ad account fills in
85
+ * (`{campaign_name}_{campaign_id}`, `{ad_id}`), and long numbers in them are
86
+ * ids, not phones. */
87
+ declare const UTM_PARAMS: readonly ["utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term"];
88
+ /** Click ids of ad networks and search engines: the same list the platform
89
+ * reads from a landing address. Their values go out exactly as they came. */
90
+ declare const CLICK_ID_PARAMS: readonly ["yclid", "ysclid", "gclid", "gbraid", "wbraid", "fbclid", "ttclid", "msclkid", "rb_clickid"];
91
+ /**
92
+ * Personal data inside a campaign tag. Ids of any length stay; what goes:
93
+ *
94
+ * - an `@` anywhere (an e-mail address);
95
+ * - a number written as a phone: with a leading `+` (9 to 15 digits), or in
96
+ * groups split by spaces, dashes, dots or brackets with 9 to 19 digits in
97
+ * all, where a bracket is present or no group is longer than 4 digits
98
+ * (`8 (900) 123-45-67`, `4242 4242 4242 4242`);
99
+ * - a bare run of 16 to 19 digits that passes the card checksum;
100
+ * - a token: a piece of 20 or more letters and digits with at least two of
101
+ * each, between `_`, `-`, `.`, `~`, `+` or spaces (a JWT, an API key).
102
+ *
103
+ * A bare run of digits shorter than 16 or longer than 19 (`716512542`, a
104
+ * 20-digit id) is an id and stays; outside the advertising fields the
105
+ * general filter still removes any 9 to 19 digits.
106
+ */
107
+ declare function adValuePersonal(v: string): boolean;
84
108
  /**
85
109
  * A page address fit to send: UUIDs, numeric ids and long tokens in the
86
110
  * path become `:id`; query parameters that carry secrets or personal data
87
111
  * are dropped, ids among their values become `:id`; the fragment is dropped.
88
- * Campaign tags stay.
112
+ *
113
+ * Campaign tags (`utm_*`) and click ids (`yclid`, `gclid`, …) stay exactly as
114
+ * they were written, ids in them included, unless {@link adValuePersonal}
115
+ * finds an address, a phone, a card number or a token in a tag, or a click
116
+ * id has characters a click id never has; then that one parameter goes.
89
117
  */
90
118
  declare function sanitizeUrl(raw: string): string;
91
119
  /**
@@ -126,4 +154,4 @@ declare function posthogDistinctId(timeoutMs?: number): Promise<string | undefin
126
154
  /** For tests: forget everything `initAnalytics` set up. */
127
155
  declare function _resetAnalyticsForTests(): void;
128
156
 
129
- export { ANALYTICS_EVENTS, type AnalyticsEvent, type AnalyticsOptions, type AnalyticsProperties, type AnalyticsZone, METRIKA_GOALS, type MetrikaOptions, NO_CAPTURE_CLASS, type PostHogLike, type PostHogOptions, _resetAnalyticsForTests, identify, initAnalytics, page, posthogDistinctId, resetAnalytics, sanitizeProperties, sanitizeUrl, setAnalyticsZone, track };
157
+ export { ANALYTICS_EVENTS, type AnalyticsEvent, type AnalyticsOptions, type AnalyticsProperties, type AnalyticsZone, CLICK_ID_PARAMS, METRIKA_GOALS, type MetrikaOptions, NO_CAPTURE_CLASS, type PostHogLike, type PostHogOptions, UTM_PARAMS, _resetAnalyticsForTests, adValuePersonal, identify, initAnalytics, page, posthogDistinctId, resetAnalytics, sanitizeProperties, sanitizeUrl, setAnalyticsZone, track };