@takeal/cusfront-sdk 0.8.4 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -0
- package/README.md +46 -5
- package/dist/analytics.cjs +74 -22
- package/dist/analytics.cjs.map +1 -1
- package/dist/analytics.d.cts +43 -4
- package/dist/analytics.d.ts +43 -4
- package/dist/analytics.js +71 -23
- package/dist/analytics.js.map +1 -1
- package/dist/{cards-DwxkVJUB.d.cts → cards-C5rk0XkI.d.cts} +47 -5
- package/dist/{cards-VkS_2lPe.d.ts → cards-CS-oxqLS.d.ts} +47 -5
- package/dist/index.cjs +94 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -5
- package/dist/index.d.ts +13 -5
- package/dist/index.js +91 -27
- package/dist/index.js.map +1 -1
- package/dist/react/index.d.cts +1 -1
- package/dist/react/index.d.ts +1 -1
- package/dist/resources/auth.cjs.map +1 -1
- package/dist/resources/auth.d.cts +1 -1
- package/dist/resources/auth.d.ts +1 -1
- package/dist/resources/auth.js.map +1 -1
- package/dist/resources/branding.cjs.map +1 -1
- package/dist/resources/branding.d.cts +6 -0
- package/dist/resources/branding.d.ts +6 -0
- package/dist/resources/branding.js.map +1 -1
- package/dist/resources/cards.cjs.map +1 -1
- package/dist/resources/cards.d.cts +1 -1
- package/dist/resources/cards.d.ts +1 -1
- package/dist/resources/cards.js.map +1 -1
- package/dist/resources/deposits.cjs.map +1 -1
- package/dist/resources/deposits.d.cts +1 -1
- package/dist/resources/deposits.d.ts +1 -1
- package/dist/resources/deposits.js.map +1 -1
- package/dist/resources/funding-options.d.cts +1 -1
- package/dist/resources/funding-options.d.ts +1 -1
- package/dist/resources/me.d.cts +1 -1
- package/dist/resources/me.d.ts +1 -1
- package/dist/telegram.cjs +20 -4
- package/dist/telegram.cjs.map +1 -1
- package/dist/telegram.d.cts +1 -1
- package/dist/telegram.d.ts +1 -1
- package/dist/telegram.js +20 -4
- package/dist/telegram.js.map +1 -1
- package/package.json +1 -1
package/dist/analytics.js
CHANGED
|
@@ -60,6 +60,8 @@ var ANALYTICS_EVENTS = [
|
|
|
60
60
|
];
|
|
61
61
|
var METRIKA_GOALS = ["signup_started", "signup_completed"];
|
|
62
62
|
var NO_CAPTURE_CLASS = "ph-no-capture";
|
|
63
|
+
var MASK_TEXT_CLASS = "ph-mask";
|
|
64
|
+
var ZONE_ATTRIBUTE = "data-analytics-zone";
|
|
63
65
|
var UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
|
|
64
66
|
var EMAIL = /[^\s@"'<>(),;:]+@[^\s@"'<>(),;:]+\.[a-z]{2,}/gi;
|
|
65
67
|
var DIGIT_RUN = /\+?\d[\d\s().-]{7,}\d/g;
|
|
@@ -325,18 +327,38 @@ function posthogConfig(zone, o) {
|
|
|
325
327
|
// Page views go through `page()`, with a cleaned address.
|
|
326
328
|
capture_pageview: false,
|
|
327
329
|
capture_pageleave: true,
|
|
328
|
-
before_send: beforeSend
|
|
330
|
+
before_send: beforeSend,
|
|
331
|
+
// Set once. A zone change never touches these: posthog-js hands the
|
|
332
|
+
// recording options to rrweb when the recorder starts, and changing
|
|
333
|
+
// `disable_session_recording` stops or restarts it.
|
|
334
|
+
disable_session_recording: !o.sessionRecording,
|
|
335
|
+
session_recording: recordingOptions()
|
|
336
|
+
};
|
|
337
|
+
return { ...base, ...zoneConfig(zone) };
|
|
338
|
+
}
|
|
339
|
+
function recordingOptions() {
|
|
340
|
+
return {
|
|
341
|
+
maskAllInputs: true,
|
|
342
|
+
maskTextSelector: "*",
|
|
343
|
+
maskTextFn: maskRecordedText,
|
|
344
|
+
blockClass: NO_CAPTURE_CLASS
|
|
329
345
|
};
|
|
330
|
-
return { ...base, ...zoneConfig(zone, o) };
|
|
331
346
|
}
|
|
332
|
-
|
|
347
|
+
var PRIVATE_BLOCK = `.${MASK_TEXT_CLASS}, [${ZONE_ATTRIBUTE}]:not([${ZONE_ATTRIBUTE}="public"])`;
|
|
348
|
+
function maskRecordedText(text, element) {
|
|
349
|
+
try {
|
|
350
|
+
if (state()?.zone === "public" && !element?.closest(PRIVATE_BLOCK)) return text;
|
|
351
|
+
} catch {
|
|
352
|
+
}
|
|
353
|
+
return text.replace(/\S/g, "*");
|
|
354
|
+
}
|
|
355
|
+
function zoneConfig(zone) {
|
|
333
356
|
if (zone === "public") {
|
|
334
357
|
return {
|
|
335
358
|
autocapture: true,
|
|
336
359
|
mask_all_text: false,
|
|
337
360
|
mask_all_element_attributes: false,
|
|
338
|
-
enable_heatmaps: true
|
|
339
|
-
disable_session_recording: true
|
|
361
|
+
enable_heatmaps: true
|
|
340
362
|
};
|
|
341
363
|
}
|
|
342
364
|
return {
|
|
@@ -344,13 +366,7 @@ function zoneConfig(zone, o) {
|
|
|
344
366
|
autocapture: { capture_copied_text: false },
|
|
345
367
|
mask_all_text: true,
|
|
346
368
|
mask_all_element_attributes: true,
|
|
347
|
-
enable_heatmaps: false
|
|
348
|
-
disable_session_recording: !o.sessionRecording,
|
|
349
|
-
session_recording: {
|
|
350
|
-
maskAllInputs: true,
|
|
351
|
-
maskTextSelector: "*",
|
|
352
|
-
blockClass: NO_CAPTURE_CLASS
|
|
353
|
-
}
|
|
369
|
+
enable_heatmaps: false
|
|
354
370
|
};
|
|
355
371
|
}
|
|
356
372
|
function assetsHost(o) {
|
|
@@ -409,16 +425,26 @@ var PostHogSink = class {
|
|
|
409
425
|
}
|
|
410
426
|
setZone(zone) {
|
|
411
427
|
this.with((ph) => {
|
|
412
|
-
ph.set_config(zoneConfig(zone
|
|
428
|
+
ph.set_config(zoneConfig(zone));
|
|
413
429
|
ph.register({ zone });
|
|
414
|
-
|
|
415
|
-
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
setConsent(granted) {
|
|
433
|
+
this.with((ph) => {
|
|
434
|
+
if (granted) {
|
|
435
|
+
ph.opt_in_capturing?.();
|
|
436
|
+
if (this.o.sessionRecording) ph.startSessionRecording?.();
|
|
437
|
+
} else {
|
|
438
|
+
ph.stopSessionRecording?.();
|
|
439
|
+
ph.opt_out_capturing?.();
|
|
440
|
+
}
|
|
416
441
|
});
|
|
417
442
|
}
|
|
418
443
|
};
|
|
419
444
|
var MetrikaSink = class {
|
|
420
445
|
constructor(o) {
|
|
421
446
|
this.live = true;
|
|
447
|
+
this.consented = true;
|
|
422
448
|
this.id = Number(o.counterId);
|
|
423
449
|
const w = win();
|
|
424
450
|
if (!w.ym) {
|
|
@@ -441,7 +467,7 @@ var MetrikaSink = class {
|
|
|
441
467
|
});
|
|
442
468
|
}
|
|
443
469
|
ym(...args) {
|
|
444
|
-
if (this.live) win().ym?.(this.id, ...args);
|
|
470
|
+
if (this.live && this.consented) win().ym?.(this.id, ...args);
|
|
445
471
|
}
|
|
446
472
|
capture(event, props) {
|
|
447
473
|
if (METRIKA_GOALS.includes(event)) this.ym("reachGoal", event, props);
|
|
@@ -457,16 +483,27 @@ var MetrikaSink = class {
|
|
|
457
483
|
setZone(zone) {
|
|
458
484
|
this.live = zone === "public";
|
|
459
485
|
}
|
|
486
|
+
setConsent(granted) {
|
|
487
|
+
this.consented = granted;
|
|
488
|
+
}
|
|
460
489
|
};
|
|
461
490
|
var KEY = /* @__PURE__ */ Symbol.for("takeal.cusfront-sdk.analytics");
|
|
462
491
|
var holder = globalThis;
|
|
463
492
|
var state = () => holder[KEY];
|
|
493
|
+
function loaded(s) {
|
|
494
|
+
return [s.posthog, s.metrika].filter((x) => !!x);
|
|
495
|
+
}
|
|
464
496
|
function sinks(s) {
|
|
497
|
+
if (!s.consent) return [];
|
|
498
|
+
if (s.options.posthog?.key && !s.posthog) {
|
|
499
|
+
s.posthog = new PostHogSink(s.options.posthog, s.zone);
|
|
500
|
+
if (s.userId) s.posthog.identify(s.userId);
|
|
501
|
+
}
|
|
465
502
|
if (s.zone === "public" && s.options.metrika && !s.metrika) {
|
|
466
503
|
s.metrika = new MetrikaSink(s.options.metrika);
|
|
467
504
|
if (s.userId) s.metrika.identify(s.userId);
|
|
468
505
|
}
|
|
469
|
-
return
|
|
506
|
+
return loaded(s);
|
|
470
507
|
}
|
|
471
508
|
function initAnalytics(options) {
|
|
472
509
|
if (state() || !win().document) return;
|
|
@@ -475,17 +512,28 @@ function initAnalytics(options) {
|
|
|
475
512
|
"[analytics] Yandex Metrica is on a page outside the public zone; it must not be."
|
|
476
513
|
);
|
|
477
514
|
}
|
|
478
|
-
const s = { options, zone: options.zone };
|
|
515
|
+
const s = { options, zone: options.zone, consent: options.consent !== false };
|
|
479
516
|
holder[KEY] = s;
|
|
480
|
-
if (options.posthog?.key) s.posthog = new PostHogSink(options.posthog, options.zone);
|
|
481
517
|
sinks(s);
|
|
482
518
|
if (options.initialPageview !== false) page();
|
|
483
519
|
}
|
|
520
|
+
function setAnalyticsConsent(granted) {
|
|
521
|
+
const s = state();
|
|
522
|
+
if (!s || s.consent === granted) return;
|
|
523
|
+
s.consent = granted;
|
|
524
|
+
const before = loaded(s);
|
|
525
|
+
for (const sink of before) sink.setConsent(granted);
|
|
526
|
+
if (granted) {
|
|
527
|
+
sinks(s);
|
|
528
|
+
if (s.lastPage === void 0 && s.options.initialPageview !== false) page();
|
|
529
|
+
}
|
|
530
|
+
}
|
|
484
531
|
function setAnalyticsZone(zone) {
|
|
485
532
|
const s = state();
|
|
486
533
|
if (!s || s.zone === zone) return;
|
|
487
534
|
s.zone = zone;
|
|
488
|
-
|
|
535
|
+
sinks(s);
|
|
536
|
+
for (const sink of loaded(s)) sink.setZone(zone);
|
|
489
537
|
}
|
|
490
538
|
function track(event, props = {}) {
|
|
491
539
|
const s = state();
|
|
@@ -497,7 +545,7 @@ function page(url) {
|
|
|
497
545
|
const s = state();
|
|
498
546
|
const w = win();
|
|
499
547
|
const raw = url ?? w.location?.href;
|
|
500
|
-
if (!s || !raw) return;
|
|
548
|
+
if (!s || !s.consent || !raw) return;
|
|
501
549
|
const clean2 = sanitizeUrl(raw);
|
|
502
550
|
if (clean2 === s.lastPage) return;
|
|
503
551
|
const referrer = s.lastPage ?? (w.document?.referrer ? sanitizeUrl(w.document.referrer) : void 0);
|
|
@@ -514,7 +562,7 @@ function resetAnalytics() {
|
|
|
514
562
|
const s = state();
|
|
515
563
|
if (!s) return;
|
|
516
564
|
s.userId = void 0;
|
|
517
|
-
for (const sink of
|
|
565
|
+
for (const sink of loaded(s)) sink.reset();
|
|
518
566
|
}
|
|
519
567
|
async function posthogDistinctId(timeoutMs = 3e3) {
|
|
520
568
|
const ready = state()?.posthog?.ready;
|
|
@@ -535,6 +583,6 @@ function _resetAnalyticsForTests() {
|
|
|
535
583
|
holder[KEY] = void 0;
|
|
536
584
|
}
|
|
537
585
|
|
|
538
|
-
export { ANALYTICS_EVENTS, CLICK_ID_PARAMS, METRIKA_GOALS, NO_CAPTURE_CLASS, UTM_PARAMS, _resetAnalyticsForTests, adValuePersonal, identify, initAnalytics, page, posthogDistinctId, resetAnalytics, sanitizeProperties, sanitizeUrl, setAnalyticsZone, track };
|
|
586
|
+
export { ANALYTICS_EVENTS, CLICK_ID_PARAMS, MASK_TEXT_CLASS, METRIKA_GOALS, NO_CAPTURE_CLASS, UTM_PARAMS, ZONE_ATTRIBUTE, _resetAnalyticsForTests, adValuePersonal, identify, initAnalytics, maskRecordedText, page, posthogDistinctId, resetAnalytics, sanitizeProperties, sanitizeUrl, setAnalyticsConsent, setAnalyticsZone, track };
|
|
539
587
|
//# sourceMappingURL=analytics.js.map
|
|
540
588
|
//# sourceMappingURL=analytics.js.map
|
package/dist/analytics.js.map
CHANGED
|
@@ -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,O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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.js","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n \"friend\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"skipped\";\n\n/**\n * The visitor's ids at the analytics platforms (TKL-329). The SDK keeps\n * them from the moment the visitor agreed to analytics cookies and sends\n * them with an order, a top-up and a sign-in, so the server can report the\n * payment and the issued card to the platforms after the person has left\n * for the bank or Telegram. See {@link analyticsIds}.\n */\nexport interface AnalyticsIds {\n /** Yandex Metrica's ClientID, from `getClientID`. A string: it does not fit a number. */\n metrika_client_id?: string;\n /** Google Analytics' client id, from the `_ga` cookie: `1234567890.1700000000`. */\n ga_client_id?: string;\n}\n\nexport interface HandoffToken {\n /** Goes into the Mini App link's `startapp` after two underscores. */\n token: string;\n expires_at: string;\n}\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** A one-day token that carries the visitor's analytics ids into the\n * Telegram Mini App, whose sign-in reads it back. Most callers want\n * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of\n * the ids is valid. */\n async handoff(ids: AnalyticsIds): Promise<HandoffToken> {\n return this.http.post<HandoffToken>(\"/attribution/handoff\", { body: ids, skipAuth: true });\n }\n\n /**\n * The `startapp` value for a link from the site to the Mini App: the code\n * as it is, followed by `__<token>` when the visitor has analytics ids, so\n * a payment made in Telegram is still credited to the visit it came from.\n * Without ids, or when the token can't be had, just the code.\n *\n * ```ts\n * const start = await client.attribution.telegramStartParam(\"SPRING\");\n * location.href = `https://t.me/our_bot/app?startapp=${start}`;\n * ```\n */\n async telegramStartParam(code = \"\"): Promise<string> {\n const ids = analyticsIds();\n if (!ids) return code;\n try {\n const { token } = await this.handoff(ids);\n return `${code}__${token}`;\n } catch {\n return code;\n }\n }\n\n /** Send the visitor's analytics ids for the signed-in account, e.g. right\n * after they agreed to analytics cookies in the cabinet. Without an\n * argument the ids this browser holds are sent; nothing is sent when it\n * holds none. */\n async sendAnalyticsIds(ids: AnalyticsIds | undefined = analyticsIds()): Promise<void> {\n if (!ids) return;\n await this.http.post<void>(\"/me/analytics/ids\", { body: ids });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Analytics ids (TKL-329)\n// ---------------------------------------------------------------------------\n\nconst IDS_KEY = \"takeal_analytics_ids\";\n\nfunction storage(): Storage | undefined {\n try {\n return (globalThis as { localStorage?: Storage }).localStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction stored(): AnalyticsIds {\n try {\n const raw = storage()?.getItem(IDS_KEY);\n const v = raw ? (JSON.parse(raw) as AnalyticsIds) : {};\n return typeof v === \"object\" && v !== null ? v : {};\n } catch {\n return {};\n }\n}\n\nfunction clean(ids: AnalyticsIds): AnalyticsIds | undefined {\n const out: AnalyticsIds = {};\n const ym = ids.metrika_client_id?.trim();\n if (ym && /^\\d{1,32}$/.test(ym)) out.metrika_client_id = ym;\n const ga = ids.ga_client_id?.trim();\n if (ga && /^\\d+\\.\\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;\n return out.metrika_client_id || out.ga_client_id ? out : undefined;\n}\n\n/**\n * Keep analytics ids for this browser, on top of the ones kept before. The\n * Metrica sink of `initAnalytics` calls it with `getClientID`'s answer once\n * the visitor agreed to analytics; call it yourself for another platform.\n */\nexport function rememberAnalyticsIds(ids: AnalyticsIds): void {\n const merged = clean({ ...stored(), ...ids });\n if (!merged) return;\n try {\n storage()?.setItem(IDS_KEY, JSON.stringify(merged));\n } catch {\n // Storage full or blocked: the cookies still hold them.\n }\n}\n\n/** Forget the kept analytics ids: the visitor declined analytics. */\nexport function forgetAnalyticsIds(): void {\n try {\n storage()?.removeItem(IDS_KEY);\n } catch {\n // Nothing kept, or nothing to reach.\n }\n}\n\n/**\n * The visitor's analytics ids: the ones kept by {@link rememberAnalyticsIds},\n * and failing those the platforms' own cookies (`_ym_uid`, `_ga`), which\n * exist only once the visitor agreed to analytics. `undefined` when there\n * are none. The site and the cabinet share them when they share the origin.\n */\nexport function analyticsIds(): AnalyticsIds | undefined {\n const kept = stored();\n return clean({\n metrika_client_id: kept.metrika_client_id ?? readCookie(\"_ym_uid\"),\n ga_client_id: kept.ga_client_id ?? readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\"),\n });\n}\n\n/** `attribution` with the visitor's analytics ids filled in where it has none. */\nexport function withAnalyticsIds(\n attribution: SignupAttribution | undefined,\n): SignupAttribution | undefined {\n const ids = analyticsIds();\n if (!ids) return attribution;\n return {\n ...attribution,\n metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,\n ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id,\n };\n}\n","/**\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"]}
|
|
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,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,CAAA,OAAQ,KAAA,EAAM;AAC3C;AAKA,eAAsB,iBAAA,CAAkB,YAAY,GAAA,EAAmC;AACrF,EAAA,MAAM,KAAA,GAAQ,KAAA,EAAM,EAAG,OAAA,EAAS,KAAA;AAChC,EAAA,IAAI,CAAC,OAAO,OAAO,MAAA;AACnB,EAAA,IAAI,KAAA;AACJ,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAmB,CAAC,CAAA,KAAM;AAC5C,IAAA,KAAA,GAAQ,UAAA,CAAW,GAAG,SAAS,CAAA;AAAA,EACjC,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.js","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n \"friend\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"skipped\";\n\n/**\n * The visitor's ids at the analytics platforms (TKL-329). The SDK keeps\n * them from the moment the visitor agreed to analytics cookies and sends\n * them with an order, a top-up and a sign-in, so the server can report the\n * payment and the issued card to the platforms after the person has left\n * for the bank or Telegram. See {@link analyticsIds}.\n */\nexport interface AnalyticsIds {\n /** Yandex Metrica's ClientID, from `getClientID`. A string: it does not fit a number. */\n metrika_client_id?: string;\n /** Google Analytics' client id, from the `_ga` cookie: `1234567890.1700000000`. */\n ga_client_id?: string;\n}\n\nexport interface HandoffToken {\n /** Goes into the Mini App link's `startapp` after two underscores. */\n token: string;\n expires_at: string;\n}\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** A one-day token that carries the visitor's analytics ids into the\n * Telegram Mini App, whose sign-in reads it back. Most callers want\n * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of\n * the ids is valid. */\n async handoff(ids: AnalyticsIds): Promise<HandoffToken> {\n return this.http.post<HandoffToken>(\"/attribution/handoff\", { body: ids, skipAuth: true });\n }\n\n /**\n * The `startapp` value for a link from the site to the Mini App: the code\n * as it is, followed by `__<token>` when the visitor has analytics ids, so\n * a payment made in Telegram is still credited to the visit it came from.\n * Without ids, or when the token can't be had, just the code.\n *\n * ```ts\n * const start = await client.attribution.telegramStartParam(\"SPRING\");\n * location.href = `https://t.me/our_bot/app?startapp=${start}`;\n * ```\n */\n async telegramStartParam(code = \"\"): Promise<string> {\n const ids = analyticsIds();\n if (!ids) return code;\n try {\n const { token } = await this.handoff(ids);\n return `${code}__${token}`;\n } catch {\n return code;\n }\n }\n\n /** Send the visitor's analytics ids for the signed-in account, e.g. right\n * after they agreed to analytics cookies in the cabinet. Without an\n * argument the ids this browser holds are sent; nothing is sent when it\n * holds none. */\n async sendAnalyticsIds(ids: AnalyticsIds | undefined = analyticsIds()): Promise<void> {\n if (!ids) return;\n await this.http.post<void>(\"/me/analytics/ids\", { body: ids });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Analytics ids (TKL-329)\n// ---------------------------------------------------------------------------\n\nconst IDS_KEY = \"takeal_analytics_ids\";\n\nfunction storage(): Storage | undefined {\n try {\n return (globalThis as { localStorage?: Storage }).localStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction stored(): AnalyticsIds {\n try {\n const raw = storage()?.getItem(IDS_KEY);\n const v = raw ? (JSON.parse(raw) as AnalyticsIds) : {};\n return typeof v === \"object\" && v !== null ? v : {};\n } catch {\n return {};\n }\n}\n\nfunction clean(ids: AnalyticsIds): AnalyticsIds | undefined {\n const out: AnalyticsIds = {};\n const ym = ids.metrika_client_id?.trim();\n if (ym && /^\\d{1,32}$/.test(ym)) out.metrika_client_id = ym;\n const ga = ids.ga_client_id?.trim();\n if (ga && /^\\d+\\.\\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;\n return out.metrika_client_id || out.ga_client_id ? out : undefined;\n}\n\n/**\n * Keep analytics ids for this browser, on top of the ones kept before. The\n * Metrica sink of `initAnalytics` calls it with `getClientID`'s answer once\n * the visitor agreed to analytics; call it yourself for another platform.\n */\nexport function rememberAnalyticsIds(ids: AnalyticsIds): void {\n const merged = clean({ ...stored(), ...ids });\n if (!merged) return;\n try {\n storage()?.setItem(IDS_KEY, JSON.stringify(merged));\n } catch {\n // Storage full or blocked: the cookies still hold them.\n }\n}\n\n/** Forget the kept analytics ids: the visitor declined analytics. */\nexport function forgetAnalyticsIds(): void {\n try {\n storage()?.removeItem(IDS_KEY);\n } catch {\n // Nothing kept, or nothing to reach.\n }\n}\n\n/**\n * The visitor's analytics ids: the ones kept by {@link rememberAnalyticsIds},\n * and failing those the platforms' own cookies (`_ym_uid`, `_ga`), which\n * exist only once the visitor agreed to analytics. `undefined` when there\n * are none. The site and the cabinet share them when they share the origin.\n */\nexport function analyticsIds(): AnalyticsIds | undefined {\n const kept = stored();\n return clean({\n metrika_client_id: kept.metrika_client_id ?? readCookie(\"_ym_uid\"),\n ga_client_id: kept.ga_client_id ?? readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\"),\n });\n}\n\n/** `attribution` with the visitor's analytics ids filled in where it has none. */\nexport function withAnalyticsIds(\n attribution: SignupAttribution | undefined,\n): SignupAttribution | undefined {\n const ids = analyticsIds();\n if (!ids) return attribution;\n return {\n ...attribution,\n metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,\n ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id,\n };\n}\n","/**\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/**\n * Mark an element whose text must be masked in recordings in every zone,\n * public pages included: a header that shows the user's e-mail or balance on\n * every page. The block is still recorded, its text as `*`. PostHog's own\n * name for this class.\n */\nexport const MASK_TEXT_CLASS = \"ph-mask\";\n\n/**\n * Put `data-analytics-zone=\"cabinet\"` (or `\"miniapp\"`) on the root element of\n * the cabinet's layout. Recordings mask every text inside it from the first\n * render, even when {@link setAnalyticsZone} comes a moment late.\n */\nexport const ZONE_ATTRIBUTE = \"data-analytics-zone\";\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 opt_in_capturing?(): unknown;\n opt_out_capturing?(): 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 (PostHog Session Replay). Off by default; without it\n * nothing is recorded in any zone. With it, one recording follows the\n * visitor from the site into the cabinet and back: on public pages every\n * input is masked and the page text is not; in the cabinet and the Mini App\n * every text and every input is masked. Blocks with {@link NO_CAPTURE_CLASS}\n * are never recorded. A zone change switches the masking without\n * restarting the recording. Turn it on only after checking a cabinet\n * recording shows no values. */\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 /** Whether the visitor agreed to analytics cookies. Default `true`:\n * calling `initAnalytics` says they did. With `false` nothing is loaded\n * and nothing is recorded until {@link setAnalyticsConsent} says `true`. */\n consent?: 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 setConsent(granted: boolean): 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 // Set once. A zone change never touches these: posthog-js hands the\n // recording options to rrweb when the recorder starts, and changing\n // `disable_session_recording` stops or restarts it.\n disable_session_recording: !o.sessionRecording,\n session_recording: recordingOptions(),\n };\n return { ...base, ...zoneConfig(zone) };\n}\n\n/**\n * Recording masking that follows the zone without restarting the recorder.\n *\n * posthog-js passes `session_recording` to rrweb once, when the recorder\n * starts; a later `set_config` does not reach it. What rrweb does evaluate\n * on every text it serializes (full snapshots and each text change) is the\n * mask decision: `maskTextSelector: \"*\"` marks every text for masking and\n * rrweb then calls `maskTextFn(text, parentElement)` for it. That callback\n * reads the zone at that moment, so the switch is immediate. If a posthog-js\n * build ignored `maskTextFn`, rrweb would mask every text with `*`: closed.\n */\nfunction recordingOptions(): Record<string, unknown> {\n return {\n maskAllInputs: true,\n maskTextSelector: \"*\",\n maskTextFn: maskRecordedText,\n blockClass: NO_CAPTURE_CLASS,\n };\n}\n\nconst PRIVATE_BLOCK = `.${MASK_TEXT_CLASS}, [${ZONE_ATTRIBUTE}]:not([${ZONE_ATTRIBUTE}=\"public\"])`;\n\n/**\n * The text a recording keeps: as it is on a public page, all `*` anywhere\n * else. Anything short of a known public page masks: no analytics state yet,\n * an unknown zone, an element inside {@link MASK_TEXT_CLASS} or inside a\n * {@link ZONE_ATTRIBUTE} root that is not `public`, or an error here.\n */\nexport function maskRecordedText(text: string, element?: Element | null): string {\n try {\n if (state()?.zone === \"public\" && !element?.closest(PRIVATE_BLOCK)) return text;\n } catch {\n // Mask below.\n }\n return text.replace(/\\S/g, \"*\");\n}\n\n/** What changes with the zone in autocapture and heatmaps. Applied at init\n * and on `setAnalyticsZone`. Recording masking follows the zone by itself\n * ({@link maskRecordedText}). Anything but `public` gets the masked set. */\nfunction zoneConfig(zone: AnalyticsZone): 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 };\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 };\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 // The recording goes on: no stop, no start, and nothing in this config\n // that would make posthog-js restart it.\n this.with((ph) => {\n ph.set_config(zoneConfig(zone));\n ph.register({ zone });\n });\n }\n setConsent(granted: boolean): void {\n this.with((ph) => {\n if (granted) {\n ph.opt_in_capturing?.();\n if (this.o.sessionRecording) ph.startSessionRecording?.();\n } else {\n // posthog-js keeps rrweb running after an opt-out, it only stops\n // sending; stop the recorder itself.\n ph.stopSessionRecording?.();\n ph.opt_out_capturing?.();\n }\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 consented = 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 && this.consented) 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 setConsent(granted: boolean): void {\n this.consented = granted;\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 consent: boolean;\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\n/** The systems already loaded, whatever the consent. */\nfunction loaded(s: State): (PostHogSink | MetrikaSink)[] {\n return [s.posthog, s.metrika].filter((x): x is PostHogSink | MetrikaSink => !!x);\n}\n\n/** The systems that may receive something now. Nothing loads before the\n * visitor agreed. */\nfunction sinks(s: State): Sink[] {\n if (!s.consent) return [];\n if (s.options.posthog?.key && !s.posthog) {\n s.posthog = new PostHogSink(s.options.posthog, s.zone);\n if (s.userId) s.posthog.identify(s.userId);\n }\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 loaded(s);\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, consent: options.consent !== false };\n holder[KEY] = s;\n sinks(s);\n if (options.initialPageview !== false) page();\n}\n\n/**\n * The visitor's answer on analytics cookies changed in an open tab. `false`\n * stops the recording, opts PostHog out and silences Metrica; `true` opts\n * back in and resumes the recording when `sessionRecording` is on, or loads\n * the systems for the first time after `initAnalytics({ consent: false })`.\n * Before `initAnalytics` it does nothing.\n */\nexport function setAnalyticsConsent(granted: boolean): void {\n const s = state();\n if (!s || s.consent === granted) return;\n s.consent = granted;\n const before = loaded(s);\n for (const sink of before) sink.setConsent(granted);\n if (granted) {\n sinks(s);\n if (s.lastPage === undefined && s.options.initialPageview !== false) page();\n }\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 // Synchronous: recording masking reads this before the next render.\n s.zone = zone;\n sinks(s);\n for (const sink of loaded(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 || !s.consent || !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 loaded(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"]}
|
|
@@ -296,7 +296,8 @@ interface Deposit {
|
|
|
296
296
|
/**
|
|
297
297
|
* For a top-up onto a card: `pending` until the card provider has loaded
|
|
298
298
|
* the card, then `succeeded` or `failed`. Show the top-up as done only
|
|
299
|
-
* once it is `succeeded`, or once `returned_to_wallet_at` is set.
|
|
299
|
+
* once it is `succeeded`, or once `returned_to_wallet_at` is set. Empty
|
|
300
|
+
* for a top-up that was never paid: nothing was there to load.
|
|
300
301
|
*/
|
|
301
302
|
card_load_status?: CardLoadStatus | null;
|
|
302
303
|
/** Why the card could not take it, when `card_load_status` is `failed`. */
|
|
@@ -865,7 +866,15 @@ interface CardOrderInput {
|
|
|
865
866
|
currency?: string;
|
|
866
867
|
/** Money to put on the card on top of its price, decimal string in the card's currency. Sent as `extra_load`. */
|
|
867
868
|
extraLoad?: string;
|
|
868
|
-
/**
|
|
869
|
+
/**
|
|
870
|
+
* A promo code for the order. A code for cards lowers the card's price.
|
|
871
|
+
* A code for top-ups lowers the fee on the payment: for a way of paying
|
|
872
|
+
* with its fee in the exchange rate it lowers the rate, and the amount
|
|
873
|
+
* with it (see `rate` of the order and of the quote). A minimum amount of
|
|
874
|
+
* such a code is checked against the money that goes onto the card, not
|
|
875
|
+
* against the card's price; below it the order is refused with
|
|
876
|
+
* `promo_code_below_minimum` and a sentence to show. Sent as `promo_code`.
|
|
877
|
+
*/
|
|
869
878
|
promoCode?: string;
|
|
870
879
|
/** Pay part of the price with bonuses; on by default. Sent as `use_bonus`. */
|
|
871
880
|
useBonus?: boolean;
|
|
@@ -937,8 +946,10 @@ interface PromoCodeQuote {
|
|
|
937
946
|
message: string | null;
|
|
938
947
|
/**
|
|
939
948
|
* The discount and what it comes off: `card_issuance` (the card's price,
|
|
940
|
-
* in `discount` of the quote) or `funding_commission` (the
|
|
941
|
-
*
|
|
949
|
+
* in `discount` of the quote) or `funding_commission` (the fee on the
|
|
950
|
+
* payment). A fee in the exchange rate gets lower and the amount with it,
|
|
951
|
+
* so it is in `discount` of the quote too; a separate commission gets
|
|
952
|
+
* lower while the amount stays the same, and more goes onto the card.
|
|
942
953
|
*/
|
|
943
954
|
discount: CodeDiscount | null;
|
|
944
955
|
/** What else the code gives, once the card is issued. */
|
|
@@ -946,6 +957,26 @@ interface PromoCodeQuote {
|
|
|
946
957
|
/** The code the user signed up with, applied without being typed. */
|
|
947
958
|
from_sign_up: boolean;
|
|
948
959
|
}
|
|
960
|
+
/**
|
|
961
|
+
* The exchange rate a card order was priced at, when the payment is in
|
|
962
|
+
* another currency than the card's.
|
|
963
|
+
*/
|
|
964
|
+
interface CardOrderRate {
|
|
965
|
+
/**
|
|
966
|
+
* The rate the user gets, the fee included: units of `card_currency` per
|
|
967
|
+
* 1 unit of `currency`, decimal string. Show this one; `1 / effective_rate`
|
|
968
|
+
* is the price of one unit of the card's currency.
|
|
969
|
+
*/
|
|
970
|
+
effective_rate: string;
|
|
971
|
+
/** The fee in basis points (1900 = 19 %), as the order was priced. */
|
|
972
|
+
fee_bps: number;
|
|
973
|
+
/** `markup` (the fee is in the rate), `spread` or `commission`. */
|
|
974
|
+
fee_kind: string;
|
|
975
|
+
/** When the user's plan or a promo code lowered the fee in the rate: the fee before that. */
|
|
976
|
+
list_fee_bps?: number | null;
|
|
977
|
+
/** The promo code the rate was priced with. */
|
|
978
|
+
promo_code?: string | null;
|
|
979
|
+
}
|
|
949
980
|
/** What a card order would cost now, from {@link CardsResource.quote} or {@link CardsResource.quotePublic}. */
|
|
950
981
|
interface CardOrderQuote {
|
|
951
982
|
/** What the user pays, decimal string, in `currency`. Pass it to the order as `expectedAmount`. */
|
|
@@ -967,6 +998,12 @@ interface CardOrderQuote {
|
|
|
967
998
|
preliminary: boolean;
|
|
968
999
|
/** Null when no code was typed and none applies by itself. */
|
|
969
1000
|
promo_code: PromoCodeQuote | null;
|
|
1001
|
+
/**
|
|
1002
|
+
* The rate the amount was worked out at, with the promo code's share
|
|
1003
|
+
* taken off the fee. Null when the payment is in the card's currency;
|
|
1004
|
+
* older platforms leave it out.
|
|
1005
|
+
*/
|
|
1006
|
+
rate?: CardOrderRate | null;
|
|
970
1007
|
}
|
|
971
1008
|
/** What {@link CardsResource.order} returns: the top-up to pay and its price. */
|
|
972
1009
|
interface CardOrder {
|
|
@@ -984,6 +1021,11 @@ interface CardOrder {
|
|
|
984
1021
|
* it before the payment. Older platforms leave it out.
|
|
985
1022
|
*/
|
|
986
1023
|
debt_withheld?: string;
|
|
1024
|
+
/**
|
|
1025
|
+
* The rate the order was priced at. Null when the payment is in the
|
|
1026
|
+
* card's currency; older platforms leave it out.
|
|
1027
|
+
*/
|
|
1028
|
+
rate?: CardOrderRate | null;
|
|
987
1029
|
}
|
|
988
1030
|
/** Why a card ordered with the sign-up was not placed. The account exists all the same. */
|
|
989
1031
|
interface CardOrderError {
|
|
@@ -1429,4 +1471,4 @@ declare class CardsResource {
|
|
|
1429
1471
|
terminate(id: string, reason?: string): Promise<Card>;
|
|
1430
1472
|
}
|
|
1431
1473
|
|
|
1432
|
-
export { type
|
|
1474
|
+
export { type TopUpTerms as $, type Address as A, type BillingAddress as B, type CardProduct as C, type Deposit as D, type CreateQuoteInput as E, FundingOptionsResource as F, type CustomerInfo as G, type DepositMethod as H, type DepositStatus as I, type DepositTarget as J, type FeeKind as K, type FunderMode as L, type FundingOption as M, type FundingQuote as N, type InitiateDepositInput as O, type IssuanceBonus as P, type IssueCardInput as Q, type MethodTerms as R, type PromoCodeQuote as S, type PromoCodeStatus as T, type Refund as U, type RevealCardInput as V, type RevealState as W, type RevealedCard as X, type SetPinInput as Y, type TopUpInput as Z, type TopUpResult as _, type Card as a, type TransferInput as a0, type TransferResult as a1, type UpdateCardInput as a2, priceChangedQuote as a3, revealState as a4, cardOrderBody as a5, cardOrderQuoteBody as a6, cardRequestBody as a7, DepositsResource as b, CardsResource as c, type CardBalance as d, type CardDesignRef as e, type CardForm as f, type CardInTransit as g, type CardLoadStatus as h, type CardOrder as i, type CardOrderError as j, type CardOrderInput as k, type CardOrderQuote as l, type CardOrderQuoteInput as m, type CardOrderRate as n, type CardProductPrice as o, type CardStatus as p, type CardStatusSource as q, type CardTariff as r, type CardTopUp as s, type CardTopUpStatus as t, type CardTransfer as u, type CardType as v, type Cardholder as w, type CloseBlockedReason as x, type CreateCardInput as y, type CreateDepositRefundInput as z };
|