@takeal/cusfront-sdk 0.6.14 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -0
- package/README.md +53 -1
- package/dist/analytics.cjs +88 -7
- package/dist/analytics.cjs.map +1 -1
- package/dist/analytics.d.cts +30 -2
- package/dist/analytics.d.ts +30 -2
- package/dist/analytics.js +86 -8
- package/dist/analytics.js.map +1 -1
- package/dist/{cards-D_krTWzr.d.cts → cards-BPu8Ill7.d.cts} +122 -2
- package/dist/{cards-DPlgx76p.d.ts → cards-DP1fJc_c.d.ts} +122 -2
- package/dist/index.cjs +147 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +147 -15
- 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 +8 -4
- package/dist/resources/auth.cjs.map +1 -1
- package/dist/resources/auth.d.cts +17 -6
- package/dist/resources/auth.d.ts +17 -6
- package/dist/resources/auth.js +8 -4
- package/dist/resources/auth.js.map +1 -1
- package/dist/resources/cards.cjs +60 -1
- package/dist/resources/cards.cjs.map +1 -1
- package/dist/resources/cards.d.cts +2 -1
- package/dist/resources/cards.d.ts +2 -1
- package/dist/resources/cards.js +59 -2
- package/dist/resources/cards.js.map +1 -1
- package/dist/resources/deposits.cjs.map +1 -1
- package/dist/resources/deposits.d.cts +2 -1
- package/dist/resources/deposits.d.ts +2 -1
- package/dist/resources/deposits.js.map +1 -1
- package/dist/resources/funding-options.d.cts +2 -1
- package/dist/resources/funding-options.d.ts +2 -1
- package/dist/resources/me.d.cts +1 -1
- package/dist/resources/me.d.ts +1 -1
- package/dist/telegram.cjs +54 -7
- package/dist/telegram.cjs.map +1 -1
- package/dist/telegram.d.cts +2 -2
- package/dist/telegram.d.ts +2 -2
- package/dist/telegram.js +54 -7
- package/dist/telegram.js.map +1 -1
- package/package.json +1 -1
package/dist/analytics.d.ts
CHANGED
|
@@ -81,11 +81,39 @@ interface AnalyticsOptions {
|
|
|
81
81
|
* {@link page} on every route change. */
|
|
82
82
|
initialPageview?: boolean;
|
|
83
83
|
}
|
|
84
|
+
/** Campaign tags. Their values are ids and names an ad account fills in
|
|
85
|
+
* (`{campaign_name}_{campaign_id}`, `{ad_id}`), and long numbers in them are
|
|
86
|
+
* ids, not phones. */
|
|
87
|
+
declare const UTM_PARAMS: readonly ["utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term"];
|
|
88
|
+
/** Click ids of ad networks and search engines: the same list the platform
|
|
89
|
+
* reads from a landing address. Their values go out exactly as they came. */
|
|
90
|
+
declare const CLICK_ID_PARAMS: readonly ["yclid", "ysclid", "gclid", "gbraid", "wbraid", "fbclid", "ttclid", "msclkid", "rb_clickid"];
|
|
91
|
+
/**
|
|
92
|
+
* Personal data inside a campaign tag. Ids of any length stay; what goes:
|
|
93
|
+
*
|
|
94
|
+
* - an `@` anywhere (an e-mail address);
|
|
95
|
+
* - a number written as a phone: with a leading `+` (9 to 15 digits), or in
|
|
96
|
+
* groups split by spaces, dashes, dots or brackets with 9 to 19 digits in
|
|
97
|
+
* all, where a bracket is present or no group is longer than 4 digits
|
|
98
|
+
* (`8 (900) 123-45-67`, `4242 4242 4242 4242`);
|
|
99
|
+
* - a bare run of 16 to 19 digits that passes the card checksum;
|
|
100
|
+
* - a token: a piece of 20 or more letters and digits with at least two of
|
|
101
|
+
* each, between `_`, `-`, `.`, `~`, `+` or spaces (a JWT, an API key).
|
|
102
|
+
*
|
|
103
|
+
* A bare run of digits shorter than 16 or longer than 19 (`716512542`, a
|
|
104
|
+
* 20-digit id) is an id and stays; outside the advertising fields the
|
|
105
|
+
* general filter still removes any 9 to 19 digits.
|
|
106
|
+
*/
|
|
107
|
+
declare function adValuePersonal(v: string): boolean;
|
|
84
108
|
/**
|
|
85
109
|
* A page address fit to send: UUIDs, numeric ids and long tokens in the
|
|
86
110
|
* path become `:id`; query parameters that carry secrets or personal data
|
|
87
111
|
* are dropped, ids among their values become `:id`; the fragment is dropped.
|
|
88
|
-
*
|
|
112
|
+
*
|
|
113
|
+
* Campaign tags (`utm_*`) and click ids (`yclid`, `gclid`, …) stay exactly as
|
|
114
|
+
* they were written, ids in them included, unless {@link adValuePersonal}
|
|
115
|
+
* finds an address, a phone, a card number or a token in a tag, or a click
|
|
116
|
+
* id has characters a click id never has; then that one parameter goes.
|
|
89
117
|
*/
|
|
90
118
|
declare function sanitizeUrl(raw: string): string;
|
|
91
119
|
/**
|
|
@@ -126,4 +154,4 @@ declare function posthogDistinctId(timeoutMs?: number): Promise<string | undefin
|
|
|
126
154
|
/** For tests: forget everything `initAnalytics` set up. */
|
|
127
155
|
declare function _resetAnalyticsForTests(): void;
|
|
128
156
|
|
|
129
|
-
export { ANALYTICS_EVENTS, type AnalyticsEvent, type AnalyticsOptions, type AnalyticsProperties, type AnalyticsZone, METRIKA_GOALS, type MetrikaOptions, NO_CAPTURE_CLASS, type PostHogLike, type PostHogOptions, _resetAnalyticsForTests, identify, initAnalytics, page, posthogDistinctId, resetAnalytics, sanitizeProperties, sanitizeUrl, setAnalyticsZone, track };
|
|
157
|
+
export { ANALYTICS_EVENTS, type AnalyticsEvent, type AnalyticsOptions, type AnalyticsProperties, type AnalyticsZone, CLICK_ID_PARAMS, METRIKA_GOALS, type MetrikaOptions, NO_CAPTURE_CLASS, type PostHogLike, type PostHogOptions, UTM_PARAMS, _resetAnalyticsForTests, adValuePersonal, identify, initAnalytics, page, posthogDistinctId, resetAnalytics, sanitizeProperties, sanitizeUrl, setAnalyticsZone, track };
|
package/dist/analytics.js
CHANGED
|
@@ -156,6 +156,67 @@ function digitCount(s) {
|
|
|
156
156
|
function redactText(v) {
|
|
157
157
|
return v.replace(EMAIL, "[email]").replace(DIGIT_RUN, (m) => digitCount(m) >= 9 && digitCount(m) <= 19 ? "[number]" : m);
|
|
158
158
|
}
|
|
159
|
+
var UTM_PARAMS = [
|
|
160
|
+
"utm_source",
|
|
161
|
+
"utm_medium",
|
|
162
|
+
"utm_campaign",
|
|
163
|
+
"utm_content",
|
|
164
|
+
"utm_term"
|
|
165
|
+
];
|
|
166
|
+
var CLICK_ID_PARAMS = [
|
|
167
|
+
"yclid",
|
|
168
|
+
"ysclid",
|
|
169
|
+
"gclid",
|
|
170
|
+
"gbraid",
|
|
171
|
+
"wbraid",
|
|
172
|
+
"fbclid",
|
|
173
|
+
"ttclid",
|
|
174
|
+
"msclkid",
|
|
175
|
+
"rb_clickid"
|
|
176
|
+
];
|
|
177
|
+
var UTM_SET = new Set(UTM_PARAMS);
|
|
178
|
+
var CLICK_ID_SET = new Set(CLICK_ID_PARAMS);
|
|
179
|
+
var CLICK_ID_VALUE = /^[A-Za-z0-9._~-]{1,256}$/;
|
|
180
|
+
function adField(key) {
|
|
181
|
+
const k = key.replace(/^\$+/, "").toLowerCase().replace(/^initial_/, "");
|
|
182
|
+
if (UTM_SET.has(k)) return "utm";
|
|
183
|
+
if (CLICK_ID_SET.has(k)) return "click";
|
|
184
|
+
return void 0;
|
|
185
|
+
}
|
|
186
|
+
function luhn(digits) {
|
|
187
|
+
let sum = 0;
|
|
188
|
+
for (let i = 0; i < digits.length; i++) {
|
|
189
|
+
let d = digits.charCodeAt(digits.length - 1 - i) - 48;
|
|
190
|
+
if (i % 2 === 1) {
|
|
191
|
+
d *= 2;
|
|
192
|
+
if (d > 9) d -= 9;
|
|
193
|
+
}
|
|
194
|
+
sum += d;
|
|
195
|
+
}
|
|
196
|
+
return sum % 10 === 0;
|
|
197
|
+
}
|
|
198
|
+
var NUMBER_RUN = /(?:\+\s*)?\d(?:[\d\s().-]*\d)?/g;
|
|
199
|
+
function adValuePersonal(v) {
|
|
200
|
+
if (v.includes("@")) return true;
|
|
201
|
+
for (const m of v.match(NUMBER_RUN) ?? []) {
|
|
202
|
+
const groups = m.split(/\D+/).filter(Boolean);
|
|
203
|
+
const n = groups.join("").length;
|
|
204
|
+
if (m.startsWith("+")) {
|
|
205
|
+
if (n >= 9 && n <= 15) return true;
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (groups.length === 1) {
|
|
209
|
+
if (n >= 16 && n <= 19 && luhn(groups[0])) return true;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (n >= 9 && n <= 19 && (/[()]/.test(m) || groups.every((g) => g.length <= 4))) return true;
|
|
213
|
+
}
|
|
214
|
+
return v.split(/[\s_.~+-]+/).some((seg) => seg.length >= 20 && /\d.*\d/.test(seg) && /[A-Za-z].*[A-Za-z]/.test(seg));
|
|
215
|
+
}
|
|
216
|
+
function adValue(kind, v) {
|
|
217
|
+
if (kind === "click") return CLICK_ID_VALUE.test(v) ? v : void 0;
|
|
218
|
+
return adValuePersonal(v) ? void 0 : v;
|
|
219
|
+
}
|
|
159
220
|
function idSegment(seg) {
|
|
160
221
|
let s = seg;
|
|
161
222
|
try {
|
|
@@ -167,6 +228,13 @@ function idSegment(seg) {
|
|
|
167
228
|
if (replaced !== s) return replaced;
|
|
168
229
|
return redactText(s) === s ? seg : PLACEHOLDER;
|
|
169
230
|
}
|
|
231
|
+
function decodeQueryPart(s) {
|
|
232
|
+
try {
|
|
233
|
+
return decodeURIComponent(s.replace(/\+/g, " "));
|
|
234
|
+
} catch {
|
|
235
|
+
return s;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
170
238
|
function sanitizeUrl(raw) {
|
|
171
239
|
const absolute = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw);
|
|
172
240
|
let u;
|
|
@@ -177,14 +245,22 @@ function sanitizeUrl(raw) {
|
|
|
177
245
|
}
|
|
178
246
|
const path = u.pathname.split("/").map((seg) => seg ? idSegment(seg) : seg).join("/");
|
|
179
247
|
const query = [];
|
|
180
|
-
u.
|
|
248
|
+
for (const pair of u.search.replace(/^\?/, "").split("&")) {
|
|
249
|
+
if (!pair) continue;
|
|
250
|
+
const eq = pair.indexOf("=");
|
|
251
|
+
const rawKey = eq < 0 ? pair : pair.slice(0, eq);
|
|
252
|
+
const key = decodeQueryPart(rawKey);
|
|
253
|
+
const value = eq < 0 ? "" : decodeQueryPart(pair.slice(eq + 1));
|
|
254
|
+
const ad = adField(key);
|
|
255
|
+
if (ad) {
|
|
256
|
+
if (adValue(ad, value) !== void 0) query.push(pair);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
181
259
|
const k = words(key);
|
|
182
|
-
if (k.some((w) => SECRET_QUERY_WORDS.has(w)) || personalKey(key))
|
|
183
|
-
if (redactText(value) !== value)
|
|
184
|
-
query.push(
|
|
185
|
-
|
|
186
|
-
);
|
|
187
|
-
});
|
|
260
|
+
if (k.some((w) => SECRET_QUERY_WORDS.has(w)) || personalKey(key)) continue;
|
|
261
|
+
if (redactText(value) !== value) continue;
|
|
262
|
+
query.push(isId(value) ? `${rawKey}=${PLACEHOLDER}` : pair);
|
|
263
|
+
}
|
|
188
264
|
const search = query.length ? `?${query.join("&")}` : "";
|
|
189
265
|
return (absolute ? `${u.protocol}//${u.host}` : "") + path + search;
|
|
190
266
|
}
|
|
@@ -192,6 +268,8 @@ function cleanValue(key, v, depth) {
|
|
|
192
268
|
if (v === null || v === void 0 || typeof v === "number" || typeof v === "boolean") return v;
|
|
193
269
|
if (typeof v === "string") {
|
|
194
270
|
if (MONEY_KEYS.has(key.toLowerCase()) || UUID_ONLY.test(v)) return v;
|
|
271
|
+
const ad = adField(key);
|
|
272
|
+
if (ad) return adValue(ad, v);
|
|
195
273
|
if (urlKey(key) || /^https?:\/\//i.test(v)) return sanitizeUrl(v);
|
|
196
274
|
if (key === "$elements_chain") {
|
|
197
275
|
return redactText(v).replace(
|
|
@@ -457,6 +535,6 @@ function _resetAnalyticsForTests() {
|
|
|
457
535
|
holder[KEY] = void 0;
|
|
458
536
|
}
|
|
459
537
|
|
|
460
|
-
export { ANALYTICS_EVENTS, METRIKA_GOALS, NO_CAPTURE_CLASS, _resetAnalyticsForTests, identify, initAnalytics, page, posthogDistinctId, resetAnalytics, sanitizeProperties, sanitizeUrl, setAnalyticsZone, track };
|
|
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 };
|
|
461
539
|
//# sourceMappingURL=analytics.js.map
|
|
462
540
|
//# 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,OAAO,MAAA;AAAA,EACT;AACF;AAEA,SAAS,MAAA,GAAuB;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,OAAA,EAAQ,EAAG,OAAA,CAAQ,OAAO,CAAA;AACtC,IAAA,MAAM,IAAI,GAAA,GAAO,IAAA,CAAK,KAAA,CAAM,GAAG,IAAqB,EAAC;AACrD,IAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,GAAO,IAAI,EAAC;AAAA,EACpD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAEA,SAAS,MAAM,GAAA,EAA6C;AAC1D,EAAA,MAAM,MAAoB,EAAC;AAC3B,EAAA,MAAM,EAAA,GAAK,GAAA,CAAI,iBAAA,EAAmB,IAAA,EAAK;AACvC,EAAA,IAAI,MAAM,YAAA,CAAa,IAAA,CAAK,EAAE,CAAA,MAAO,iBAAA,GAAoB,EAAA;AACzD,EAAA,MAAM,EAAA,GAAK,GAAA,CAAI,YA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;AACnB,EAAA,CAAA,CAAE,MAAA,GAAS,MAAA;AACX,EAAA,KAAA,MAAW,QAAQ,KAAA,CAAM,CAAC,CAAA,EAAG,IAAA,CAAK,SAAS,MAAM,CAAA;AACnD;AAIO,SAAS,cAAA,GAAuB;AACrC,EAAA,MAAM,IAAI,KAAA,EAAM;AAChB,EAAA,IAAI,CAAC,CAAA,EAAG;AACR,EAAA,CAAA,CAAE,MAAA,GAAS,MAAA;AACX,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,CAAM,CAAC,CAAA,OAAQ,KAAA,EAAM;AAC1C;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/** The subset of the `posthog-js` instance the layer uses. */\nexport interface PostHogLike {\n init(key: string, config: Record<string, unknown>): unknown;\n capture(event: string, properties?: Record<string, unknown>): unknown;\n identify(distinctId: string): unknown;\n reset(): unknown;\n get_distinct_id(): string;\n register(properties: Record<string, unknown>): unknown;\n set_config(config: Record<string, unknown>): unknown;\n startSessionRecording?(): unknown;\n stopSessionRecording?(): unknown;\n}\n\nexport interface PostHogOptions {\n /** Project key (`phc_…`). Write-only, safe in the browser. */\n key: string;\n /** Where events go. Point it at the proxy path on your own domain, e.g.\n * `https://example.com/ingest`. Default `https://eu.i.posthog.com`. */\n host?: string;\n /** PostHog's own app, for links from the toolbar. Default `https://eu.posthog.com`. */\n uiHost?: string;\n /** Where the script comes from when `load` is not given. Default: the\n * `-assets` twin of a PostHog host, or `host` itself for a proxy. */\n assetsHost?: string;\n /** Return the app's own `posthog-js` instance, usually\n * `() => import(\"posthog-js\").then((m) => m.default)` (1.187 or later).\n * Without it the script is loaded from `assetsHost`. */\n load?: () => Promise<PostHogLike>;\n /** Record sessions in the cabinet and the Mini App, masked. Off by\n * default; turn it on only after checking a recording shows no values.\n * Never recorded on public pages. */\n sessionRecording?: boolean;\n}\n\nexport interface MetrikaOptions {\n counterId: number | string;\n /** Tag script address. Default `https://mc.yandex.ru/metrika/tag.js`. */\n scriptUrl?: string;\n}\n\nexport interface AnalyticsOptions {\n zone: AnalyticsZone;\n posthog?: PostHogOptions;\n /** Used on public pages only; ignored in the cabinet and the Mini App. */\n metrika?: MetrikaOptions;\n /** Send the first page view right away. Default `true`; after that call\n * {@link page} on every route change. */\n initialPageview?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// The filter on the way out\n// ---------------------------------------------------------------------------\n\nconst UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;\nconst EMAIL = /[^\\s@\"'<>(),;:]+@[^\\s@\"'<>(),;:]+\\.[a-z]{2,}/gi;\n/** A run of digits with phone or card separators: 9 to 19 digits is a phone\n * or a card number, never something to send. */\nconst DIGIT_RUN = /\\+?\\d[\\d\\s().-]{7,}\\d/g;\nconst UUID_ONLY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n/** A path segment or a query value that is an id: a number, a UUID, a hex\n * string, or a long token of letters and digits. Slugs have dashes and\n * stay, even with a year in them. */\nfunction isId(v: string): boolean {\n return (\n /^\\d+$/.test(v) ||\n UUID_ONLY.test(v) ||\n /^[0-9a-f]{16,}$/i.test(v) ||\n (/^[A-Za-z0-9_]{20,}$/.test(v) && /\\d.*\\d/.test(v) && /[A-Za-z].*[A-Za-z]/.test(v))\n );\n}\nconst PLACEHOLDER = \":id\";\n\n/** Keys whose value is personal whatever it looks like: any key with one of\n * these words... */\nconst PERSONAL_WORDS = new Set([\n \"email\",\n \"mail\",\n \"phone\",\n \"tel\",\n \"telephone\",\n \"mobile\",\n \"msisdn\",\n \"surname\",\n \"patronymic\",\n \"firstname\",\n \"lastname\",\n \"fullname\",\n \"username\",\n \"nickname\",\n]);\n/** ...and `name` alone or after one of these (`first_name`, `holder_name`).\n * `merchant_name` names a company and stays. */\nconst PERSON_NAME_QUALIFIERS = new Set([\n \"first\",\n \"last\",\n \"full\",\n \"user\",\n \"display\",\n \"given\",\n \"family\",\n \"middle\",\n \"nick\",\n \"real\",\n \"holder\",\n \"cardholder\",\n \"customer\",\n \"contact\",\n \"person\",\n \"owner\",\n \"account\",\n \"legal\",\n]);\n/** Query keys that carry secrets or personal data. */\nconst SECRET_QUERY_WORDS = new Set([\n \"token\",\n \"code\",\n \"key\",\n \"secret\",\n \"password\",\n \"pass\",\n \"pwd\",\n \"otp\",\n \"sig\",\n \"signature\",\n \"session\",\n \"sid\",\n \"auth\",\n \"jwt\",\n \"pan\",\n \"cvv\",\n \"cvc\",\n \"iban\",\n]);\n/** Money is not personal: kept as it is. */\nconst MONEY_KEYS = new Set([\n \"amount\",\n \"amount_minor\",\n \"currency\",\n \"value\",\n \"price\",\n \"revenue\",\n \"sum\",\n]);\n\nfunction words(key: string): string[] {\n return key\n .replace(/^\\$+/, \"\")\n .replace(/([a-z])([A-Z])/g, \"$1_$2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean);\n}\n\nfunction personalKey(key: string): boolean {\n const w = words(key);\n const joined = w.join(\"\");\n if (joined.includes(\"email\") || joined.includes(\"phone\")) return true;\n if (w.some((x) => PERSONAL_WORDS.has(x)) || PERSONAL_WORDS.has(joined)) return true;\n // PostHog's own `$…` keys are never names of people.\n if (key.startsWith(\"$\")) return false;\n return w.some(\n (x, i) => x === \"name\" && (w.length === 1 || PERSON_NAME_QUALIFIERS.has(w[i - 1] ?? \"\")),\n );\n}\n\nfunction urlKey(key: string): boolean {\n const k = key.replace(/^\\$+/, \"\").toLowerCase();\n return (\n /(^|_)(url|href|pathname|path|referrer|referer)$/.test(k) ||\n k === \"page\" ||\n k.startsWith(\"attr__href\")\n );\n}\n\nfunction digitCount(s: string): number {\n return s.replace(/\\D/g, \"\").length;\n}\n\n/** Text with e-mail addresses, phone and card numbers cut out. */\nfunction redactText(v: string): string {\n return v\n .replace(EMAIL, \"[email]\")\n .replace(DIGIT_RUN, (m) => (digitCount(m) >= 9 && digitCount(m) <= 19 ? \"[number]\" : m));\n}\n\nfunction idSegment(seg: string): string {\n let s = seg;\n try {\n s = decodeURIComponent(seg);\n } catch {\n // Leave a broken escape as it is.\n }\n if (isId(s)) return PLACEHOLDER;\n const replaced = s.replace(UUID, PLACEHOLDER);\n if (replaced !== s) return replaced;\n return redactText(s) === s ? seg : PLACEHOLDER;\n}\n\n/**\n * A page address fit to send: UUIDs, numeric ids and long tokens in the\n * path become `:id`; query parameters that carry secrets or personal data\n * are dropped, ids among their values become `:id`; the fragment is dropped.\n * Campaign tags stay.\n */\nexport function sanitizeUrl(raw: string): string {\n const absolute = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(raw);\n let u: URL;\n try {\n u = new URL(raw, \"http://relative.invalid\");\n } catch {\n return redactText(raw.split(/[?#]/)[0] ?? \"\").replace(UUID, PLACEHOLDER);\n }\n const path = u.pathname\n .split(\"/\")\n .map((seg) => (seg ? idSegment(seg) : seg))\n .join(\"/\");\n const query: string[] = [];\n u.searchParams.forEach((value, key) => {\n const k = words(key);\n if (k.some((w) => SECRET_QUERY_WORDS.has(w)) || personalKey(key)) return;\n if (redactText(value) !== value) return;\n query.push(\n `${encodeURIComponent(key)}=${isId(value) ? PLACEHOLDER : encodeURIComponent(value)}`,\n );\n });\n const search = query.length ? `?${query.join(\"&\")}` : \"\";\n return (absolute ? `${u.protocol}//${u.host}` : \"\") + path + search;\n}\n\nfunction cleanValue(key: string, v: unknown, depth: number): unknown {\n if (v === null || v === undefined || typeof v === \"number\" || typeof v === \"boolean\") return v;\n if (typeof v === \"string\") {\n // Money, and whole ids such as PostHog's session and device ids.\n if (MONEY_KEYS.has(key.toLowerCase()) || UUID_ONLY.test(v)) return v;\n if (urlKey(key) || /^https?:\\/\\//i.test(v)) return sanitizeUrl(v);\n if (key === \"$elements_chain\") {\n return redactText(v).replace(\n /attr__href=\"([^\"]*)\"/g,\n (_, h: string) => `attr__href=\"${sanitizeUrl(h)}\"`,\n );\n }\n const r = redactText(v);\n // A value that was nothing but an address or a number goes entirely.\n return r.replace(/\\[(email|number)\\]/g, \"\").trim() === \"\" && r !== v ? undefined : r;\n }\n if (depth > 5) return undefined;\n if (Array.isArray(v))\n return v.map((x) => cleanValue(key, x, depth + 1)).filter((x) => x !== undefined);\n if (typeof v === \"object\") return sanitizeProperties(v as Record<string, unknown>, depth + 1);\n return undefined;\n}\n\n/**\n * The filter every event passes before it leaves the browser. Drops keys\n * that name personal data (`email`, `phone`, `name`, `first_name`, …) and\n * values that look like an e-mail address, a phone or a card number; page\n * addresses go through {@link sanitizeUrl}. Amounts and currencies pass.\n */\nexport function sanitizeProperties<T extends Record<string, unknown>>(\n props: T,\n depth = 0,\n): Partial<T> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(props)) {\n if (personalKey(k)) continue;\n const c = cleanValue(k, v, depth);\n if (c !== undefined) out[k] = c;\n }\n return out as Partial<T>;\n}\n\n/** PostHog's `before_send`: the same filter for what PostHog captures by itself. */\nfunction beforeSend<\n E extends {\n properties?: Record<string, unknown>;\n $set?: Record<string, unknown>;\n $set_once?: Record<string, unknown>;\n },\n>(event: E | null): E | null {\n if (!event) return event;\n const out = { ...event };\n if (event.properties) out.properties = sanitizeProperties(event.properties);\n if (event.$set) out.$set = sanitizeProperties(event.$set);\n if (event.$set_once) out.$set_once = sanitizeProperties(event.$set_once);\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Systems. A new one is a Sink plus a line in `sinksFor`.\n// ---------------------------------------------------------------------------\n\ninterface Sink {\n capture(event: AnalyticsEvent, props: AnalyticsProperties): void;\n page(url: string, referrer: string | undefined): void;\n identify(userId: string): void;\n reset(): void;\n setZone(zone: AnalyticsZone): void;\n}\n\ninterface Win {\n document?: Document;\n location?: Location;\n posthog?: unknown;\n ym?: ((...args: unknown[]) => void) & { a?: unknown[]; l?: number };\n}\n\nconst win = () => globalThis as unknown as Win;\n\nfunction injectScript(src: string, onLoad?: () => void, onError?: () => void): void {\n const doc = win().document;\n if (!doc) return;\n const s = doc.createElement(\"script\");\n s.async = true;\n s.src = src;\n s.crossOrigin = \"anonymous\";\n if (onLoad) s.addEventListener(\"load\", onLoad);\n if (onError) s.addEventListener(\"error\", onError);\n (doc.head ?? doc.documentElement).appendChild(s);\n}\n\nfunction posthogConfig(zone: AnalyticsZone, o: PostHogOptions): Record<string, unknown> {\n const host = (o.host ?? \"https://eu.i.posthog.com\").replace(/\\/+$/, \"\");\n const base: Record<string, unknown> = {\n api_host: host,\n ui_host: o.uiHost ?? \"https://eu.posthog.com\",\n // Profiles for signed-in users only.\n person_profiles: \"identified_only\",\n // Page views go through `page()`, with a cleaned address.\n capture_pageview: false,\n capture_pageleave: true,\n before_send: beforeSend,\n };\n return { ...base, ...zoneConfig(zone, o) };\n}\n\n/** What changes with the zone. Applied at init and on `setAnalyticsZone`. */\nfunction zoneConfig(zone: AnalyticsZone, o: PostHogOptions): Record<string, unknown> {\n if (zone === \"public\") {\n return {\n autocapture: true,\n mask_all_text: false,\n mask_all_element_attributes: false,\n enable_heatmaps: true,\n disable_session_recording: true,\n };\n }\n return {\n // A click is \"the third button in the cards block\", never its label.\n autocapture: { capture_copied_text: false },\n mask_all_text: true,\n mask_all_element_attributes: true,\n enable_heatmaps: false,\n disable_session_recording: !o.sessionRecording,\n session_recording: {\n maskAllInputs: true,\n maskTextSelector: \"*\",\n blockClass: NO_CAPTURE_CLASS,\n },\n };\n}\n\nfunction assetsHost(o: PostHogOptions): string {\n if (o.assetsHost) return o.assetsHost.replace(/\\/+$/, \"\");\n const host = (o.host ?? \"https://eu.i.posthog.com\").replace(/\\/+$/, \"\");\n return host.replace(\".i.posthog.com\", \"-assets.i.posthog.com\");\n}\n\n/** Load posthog-js the way its own snippet does: a placeholder that the\n * script replaces with the instance once it runs. */\nfunction loadPostHogScript(\n o: PostHogOptions,\n config: Record<string, unknown>,\n): Promise<PostHogLike | undefined> {\n return new Promise((resolve) => {\n const w = win();\n if (!w.document) return resolve(undefined);\n const placeholder = Object.assign([] as unknown[], {\n __SV: 1,\n _i: [[o.key, config, \"posthog\"]],\n });\n w.posthog = placeholder;\n injectScript(\n `${assetsHost(o)}/static/array.js`,\n () => {\n const ph = w.posthog;\n const live =\n ph !== placeholder && typeof (ph as PostHogLike | undefined)?.capture === \"function\";\n resolve(live ? (ph as PostHogLike) : undefined);\n },\n () => resolve(undefined),\n );\n });\n}\n\nclass PostHogSink implements Sink {\n readonly ready: Promise<PostHogLike | undefined>;\n\n constructor(\n private readonly o: PostHogOptions,\n zone: AnalyticsZone,\n ) {\n const config = posthogConfig(zone, o);\n this.ready = (\n o.load\n ? o.load().then((ph) => {\n ph.init(o.key, config);\n return ph;\n })\n : loadPostHogScript(o, config)\n )\n .then((ph) => {\n ph?.register({ zone });\n return ph;\n })\n .catch(() => undefined);\n }\n\n private with(fn: (ph: PostHogLike) => void): void {\n void this.ready.then((ph) => ph && fn(ph));\n }\n\n capture(event: AnalyticsEvent, props: AnalyticsProperties): void {\n this.with((ph) => ph.capture(event, props));\n }\n page(url: string, referrer: string | undefined): void {\n const props: Record<string, unknown> = { $current_url: url };\n if (referrer) props.$referrer = referrer;\n this.with((ph) => ph.capture(\"$pageview\", props));\n }\n identify(userId: string): void {\n this.with((ph) => ph.identify(userId));\n }\n reset(): void {\n this.with((ph) => ph.reset());\n }\n setZone(zone: AnalyticsZone): void {\n this.with((ph) => {\n ph.set_config(zoneConfig(zone, this.o));\n ph.register({ zone });\n if (zone === \"public\" || !this.o.sessionRecording) ph.stopSessionRecording?.();\n else ph.startSessionRecording?.();\n });\n }\n}\n\n/** Metrica, public pages only. It never records on its own: no Webvisor, no\n * click map, no automatic page views. It sees exactly what this layer\n * sends, and falls silent when the zone leaves `public`. */\nclass MetrikaSink implements Sink {\n private live = true;\n private readonly id: number;\n\n constructor(o: MetrikaOptions) {\n this.id = Number(o.counterId);\n const w = win();\n if (!w.ym) {\n const ym = ((...args: unknown[]) => {\n (ym.a = ym.a ?? []).push(args);\n }) as NonNullable<Win[\"ym\"]>;\n ym.l = Date.now();\n w.ym = ym;\n injectScript(o.scriptUrl ?? \"https://mc.yandex.ru/metrika/tag.js\");\n }\n this.ym(\"init\", {\n defer: true,\n webvisor: false,\n clickmap: false,\n trackLinks: false,\n accurateTrackBounce: true,\n });\n // The sink exists only once the visitor agreed to analytics: keep the\n // ClientID for the server's conversions (TKL-329).\n this.ym(\"getClientID\", (id: unknown) => {\n if (id !== undefined && id !== null) rememberAnalyticsIds({ metrika_client_id: String(id) });\n });\n }\n\n private ym(...args: unknown[]): void {\n if (this.live) win().ym?.(this.id, ...args);\n }\n\n capture(event: AnalyticsEvent, props: AnalyticsProperties): void {\n if (METRIKA_GOALS.includes(event)) this.ym(\"reachGoal\", event, props);\n }\n page(url: string, referrer: string | undefined): void {\n this.ym(\"hit\", url, referrer ? { referer: referrer } : {});\n }\n identify(userId: string): void {\n // The same id the server sends with its conversions.\n this.ym(\"setUserID\", userId);\n }\n reset(): void {}\n setZone(zone: AnalyticsZone): void {\n this.live = zone === \"public\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// State, kept on globalThis: every sub-export bundles its own copy of this\n// file, and they must all talk to one set of systems.\n// ---------------------------------------------------------------------------\n\ninterface State {\n options: AnalyticsOptions;\n zone: AnalyticsZone;\n posthog?: PostHogSink;\n metrika?: MetrikaSink;\n lastPage?: string;\n userId?: string;\n}\n\nconst KEY = Symbol.for(\"takeal.cusfront-sdk.analytics\");\nconst holder = globalThis as unknown as Record<symbol, State | undefined>;\nconst state = (): State | undefined => holder[KEY];\n\nfunction sinks(s: State): Sink[] {\n // Metrica loads the first time the page is public, and never before.\n if (s.zone === \"public\" && s.options.metrika && !s.metrika) {\n s.metrika = new MetrikaSink(s.options.metrika);\n if (s.userId) s.metrika.identify(s.userId);\n }\n return [s.posthog, s.metrika].filter((x): x is PostHogSink | MetrikaSink => !!x);\n}\n\n/**\n * Start analytics for this page. Call once, as early as possible. A second\n * call does nothing; to move between the site and the cabinet in one app,\n * use {@link setAnalyticsZone}.\n */\nexport function initAnalytics(options: AnalyticsOptions): void {\n if (state() || !win().document) return;\n if (options.zone !== \"public\" && win().ym) {\n console.warn(\n \"[analytics] Yandex Metrica is on a page outside the public zone; it must not be.\",\n );\n }\n const s: State = { options, zone: options.zone };\n holder[KEY] = s;\n if (options.posthog?.key) s.posthog = new PostHogSink(options.posthog, options.zone);\n sinks(s);\n if (options.initialPageview !== false) page();\n}\n\n/**\n * The page moved to another zone without a reload (the site and the cabinet\n * in one app). PostHog switches its masking; Metrica falls silent outside\n * public pages. A full page load into the cabinet is safer still: Metrica is\n * then never on the page at all.\n */\nexport function setAnalyticsZone(zone: AnalyticsZone): void {\n const s = state();\n if (!s || s.zone === zone) return;\n s.zone = zone;\n for (const sink of sinks(s)) sink.setZone(zone);\n}\n\n/** Record an event. The name must be one of {@link ANALYTICS_EVENTS}. */\nexport function track(event: AnalyticsEvent, props: AnalyticsProperties = {}): void {\n const s = state();\n if (!s || !(ANALYTICS_EVENTS as readonly string[]).includes(event)) return;\n const clean = sanitizeProperties(props) as AnalyticsProperties;\n for (const sink of sinks(s)) sink.capture(event, clean);\n}\n\n/** A page view. Call it on every route change; the same address twice in a\n * row counts once. Takes the current address when none is given. */\nexport function page(url?: string): void {\n const s = state();\n const w = win();\n const raw = url ?? w.location?.href;\n if (!s || !raw) return;\n const clean = sanitizeUrl(raw);\n if (clean === s.lastPage) return;\n const referrer =\n s.lastPage ?? (w.document?.referrer ? sanitizeUrl(w.document.referrer) : undefined);\n s.lastPage = clean;\n for (const sink of sinks(s)) sink.page(clean, referrer);\n}\n\n/** After sign-in: tie this browser to the user by the platform's user id\n * (`session.user.id`), never by e-mail. Only signed-in users get profiles. */\nexport function identify(userId: string): void {\n const s = state();\n if (!s || !userId) return;\n s.userId = userId;\n for (const sink of sinks(s)) sink.identify(userId);\n}\n\n/** On sign-out: forget the user, so the next person on this device starts\n * as a new visitor. */\nexport function resetAnalytics(): void {\n const s = state();\n if (!s) return;\n s.userId = undefined;\n for (const sink of sinks(s)) sink.reset();\n}\n\n/** PostHog's id for this browser, for `auth.register({ attribution: {\n * posthog_distinct_id } })`. Waits for PostHog to load, `timeoutMs` at\n * most; `undefined` without PostHog. */\nexport async function posthogDistinctId(timeoutMs = 3000): Promise<string | undefined> {\n const ready = state()?.posthog?.ready;\n if (!ready) return undefined;\n let timer: Parameters<typeof clearTimeout>[0];\n const timeout = new Promise<undefined>((r) => {\n timer = setTimeout(r, timeoutMs);\n });\n const ph = await Promise.race([ready, timeout]);\n clearTimeout(timer);\n try {\n return ph?.get_distinct_id() || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** For tests: forget everything `initAnalytics` set up. */\nexport function _resetAnalyticsForTests(): void {\n holder[KEY] = undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/resources/attribution.ts","../src/analytics.ts"],"names":["clean"],"mappings":";AAwPA,IAAM,OAAA,GAAU,sBAAA;AAEhB,SAAS,OAAA,GAA+B;AACtC,EAAA,IAAI;AACF,IAAA,OAAQ,UAAA,CAA0C,YAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAEA,SAAS,MAAA,GAAuB;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,OAAA,EAAQ,EAAG,OAAA,CAAQ,OAAO,CAAA;AACtC,IAAA,MAAM,IAAI,GAAA,GAAO,IAAA,CAAK,KAAA,CAAM,GAAG,IAAqB,EAAC;AACrD,IAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,GAAO,IAAI,EAAC;AAAA,EACpD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAEA,SAAS,MAAM,GAAA,EAA6C;AAC1D,EAAA,MAAM,MAAoB,EAAC;AAC3B,EAAA,MAAM,EAAA,GAAK,GAAA,CAAI,iBAAA,EAAmB,IAAA,EAAK;AACvC,EAAA,IAAI,MAAM,YAAA,CAAa,IAAA,CAAK,EAAE,CAAA,MAAO,iBAAA,GAAoB,EAAA;AACzD,EAAA,MAAM,EAAA,GAAK,GAAA,CAAI,YAAA,EAAc,IAAA,EAAK;AAClC,EAAA,IAAI,EAAA,IAAM,aAAa,IAAA,CAAK,EAAE,KAAK,EAAA,CAAG,MAAA,IAAU,EAAA,EAAI,GAAA,CAAI,YAAA,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,OAAQ,KAAA,EAAM;AAC1C;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/** 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,4 +1,5 @@
|
|
|
1
1
|
import { Claim } from './resources/claims.cjs';
|
|
2
|
+
import { CodeRejection, CodeDiscount, CodeEffect } from './resources/codes.cjs';
|
|
2
3
|
import { ConsentKind, ConsentChannel } from './resources/consents.cjs';
|
|
3
4
|
import { H as HttpClient } from './http-CL97TjMO.cjs';
|
|
4
5
|
import { AnalyticsIds } from './resources/attribution.cjs';
|
|
@@ -847,6 +848,92 @@ interface CardOrderInput {
|
|
|
847
848
|
/** The visitor's analytics ids for the order's server-side conversions.
|
|
848
849
|
* Leave out to send the ones this browser holds (see `analyticsIds`). */
|
|
849
850
|
analyticsIds?: AnalyticsIds;
|
|
851
|
+
/**
|
|
852
|
+
* The amount the user was shown and agreed to pay: `amount` of the
|
|
853
|
+
* quote. If the order comes to anything else, no payment is opened and
|
|
854
|
+
* the API answers 409 `price_changed` with the new quote (see
|
|
855
|
+
* {@link priceChangedQuote}). Leave it out and the payment opens for
|
|
856
|
+
* whatever the order comes to. Sent as `expected_amount`.
|
|
857
|
+
*/
|
|
858
|
+
expectedAmount?: string;
|
|
859
|
+
/** `currency` of the same quote. Sent as `expected_currency`. */
|
|
860
|
+
expectedCurrency?: string;
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* A card order to price with {@link CardsResource.quote} or
|
|
864
|
+
* {@link CardsResource.quotePublic}: the same fields as the order.
|
|
865
|
+
*/
|
|
866
|
+
interface CardOrderQuoteInput {
|
|
867
|
+
/** Sent as `product_id`. */
|
|
868
|
+
productId: string;
|
|
869
|
+
/** Sent as `design_id`. */
|
|
870
|
+
designId?: string;
|
|
871
|
+
method: DepositMethod;
|
|
872
|
+
/** Sent as `funder_slug`. */
|
|
873
|
+
funderSlug?: string;
|
|
874
|
+
currency?: string;
|
|
875
|
+
/** Sent as `extra_load`. */
|
|
876
|
+
extraLoad?: string;
|
|
877
|
+
/** The code the user typed. Sent as `promo_code`. */
|
|
878
|
+
promoCode?: string;
|
|
879
|
+
/** Signed in only: pay part of the price with bonuses, on by default. Sent as `use_bonus`. */
|
|
880
|
+
useBonus?: boolean;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Where a promo code stands in a quote. `applied`: its discount is in the
|
|
884
|
+
* amount. `conditional` (before sign-in only): it works for someone who
|
|
885
|
+
* meets `conditions`, which are checked after sign-in, and the amount is
|
|
886
|
+
* provisional. `rejected`: it can't be used, for `reason`; an order that
|
|
887
|
+
* keeps the code is refused, so drop it from the order. `unavailable`: it
|
|
888
|
+
* couldn't be checked right now; the amount is without it.
|
|
889
|
+
*/
|
|
890
|
+
type PromoCodeStatus = "applied" | "conditional" | "rejected" | "unavailable";
|
|
891
|
+
/** What a promo code does to a card order. */
|
|
892
|
+
interface PromoCodeQuote {
|
|
893
|
+
/** The code as stored, or as typed when it wasn't found. */
|
|
894
|
+
code: string;
|
|
895
|
+
status: PromoCodeStatus;
|
|
896
|
+
/** For `rejected`. */
|
|
897
|
+
reason: CodeRejection | null;
|
|
898
|
+
/**
|
|
899
|
+
* For `conditional`: `not_first_operation` (first card only) or
|
|
900
|
+
* `own_code` (not for the person it belongs to).
|
|
901
|
+
*/
|
|
902
|
+
conditions: CodeRejection[];
|
|
903
|
+
/** A sentence to show next to the code, in English. Null when the discount says it all. */
|
|
904
|
+
message: string | null;
|
|
905
|
+
/**
|
|
906
|
+
* The discount and what it comes off: `card_issuance` (the card's price,
|
|
907
|
+
* in `discount` of the quote) or `funding_commission` (the payment's
|
|
908
|
+
* commission: the amount stays the same and more goes onto the card).
|
|
909
|
+
*/
|
|
910
|
+
discount: CodeDiscount | null;
|
|
911
|
+
/** What else the code gives, once the card is issued. */
|
|
912
|
+
effects: CodeEffect[];
|
|
913
|
+
/** The code the user signed up with, applied without being typed. */
|
|
914
|
+
from_sign_up: boolean;
|
|
915
|
+
}
|
|
916
|
+
/** What a card order would cost now, from {@link CardsResource.quote} or {@link CardsResource.quotePublic}. */
|
|
917
|
+
interface CardOrderQuote {
|
|
918
|
+
/** What the user pays, decimal string, in `currency`. Pass it to the order as `expectedAmount`. */
|
|
919
|
+
amount: string;
|
|
920
|
+
/** Pass it to the order as `expectedCurrency`. */
|
|
921
|
+
currency: string;
|
|
922
|
+
/** The same order without the promo code, decimal string, in `currency`. */
|
|
923
|
+
price: string;
|
|
924
|
+
/** `price` less `amount`: what the code takes off. `"0"` without one. */
|
|
925
|
+
discount: string;
|
|
926
|
+
/** What the payment brings, in `card_currency`, as in {@link CardOrder}. */
|
|
927
|
+
card_amount: string;
|
|
928
|
+
card_currency: string;
|
|
929
|
+
/** Card fees owed, in `card_currency`, included in `card_amount`. Always `"0"` before sign-in. */
|
|
930
|
+
debt_withheld: string;
|
|
931
|
+
/** Bonuses that pay part of the price; null before sign-in. */
|
|
932
|
+
bonus_units: string | null;
|
|
933
|
+
/** The amount may still change after sign-in: show it as provisional. */
|
|
934
|
+
preliminary: boolean;
|
|
935
|
+
/** Null when no code was typed and none applies by itself. */
|
|
936
|
+
promo_code: PromoCodeQuote | null;
|
|
850
937
|
}
|
|
851
938
|
/** What {@link CardsResource.order} returns: the top-up to pay and its price. */
|
|
852
939
|
interface CardOrder {
|
|
@@ -869,7 +956,19 @@ interface CardOrder {
|
|
|
869
956
|
interface CardOrderError {
|
|
870
957
|
code: string;
|
|
871
958
|
message: string;
|
|
959
|
+
/** With `code: "price_changed"`: what the card costs now. */
|
|
960
|
+
quote?: CardOrderQuote;
|
|
872
961
|
}
|
|
962
|
+
/**
|
|
963
|
+
* The new quote of an order that opened no payment because its price
|
|
964
|
+
* changed (`price_changed`), from either a thrown {@link ApiError} of
|
|
965
|
+
* {@link CardsResource.order} or the `card_order_error` of a sign-in.
|
|
966
|
+
* Show its amount; once the user agrees, send the order again with
|
|
967
|
+
* `expectedAmount` set to it. `undefined` for any other error.
|
|
968
|
+
*/
|
|
969
|
+
declare function priceChangedQuote(error: unknown): CardOrderQuote | undefined;
|
|
970
|
+
/** Build the API body of a card order quote. */
|
|
971
|
+
declare function cardOrderQuoteBody(input: CardOrderQuoteInput): Record<string, unknown>;
|
|
873
972
|
/** Build the API body of a card order. */
|
|
874
973
|
declare function cardOrderBody(input: CardOrderInput): Record<string, unknown>;
|
|
875
974
|
/** Remaining balance of a prepaid card. */
|
|
@@ -1133,11 +1232,32 @@ declare class CardsResource {
|
|
|
1133
1232
|
* `holder_data_required` and the user has not agreed to it), 409
|
|
1134
1233
|
* `payments_on_hold` (a payment on this account was not accepted and new
|
|
1135
1234
|
* ones wait until support sorts it out: show the message and point the
|
|
1136
|
-
* user to support),
|
|
1235
|
+
* user to support), 409 `price_changed` (the order came to another amount
|
|
1236
|
+
* than `expectedAmount`; no payment was opened, and
|
|
1237
|
+
* {@link priceChangedQuote} gives the new quote), 503 no funding connector
|
|
1238
|
+
* or no exchange rate.
|
|
1137
1239
|
*/
|
|
1138
1240
|
order(input: CardOrderInput & {
|
|
1139
1241
|
idempotencyKey: string;
|
|
1140
1242
|
}): Promise<CardOrder>;
|
|
1243
|
+
/**
|
|
1244
|
+
* What an order of this card would cost the signed-in user now, with the
|
|
1245
|
+
* promo code: the same calculation {@link order} makes, with every
|
|
1246
|
+
* condition of the code checked. Nothing is reserved or used up. Pass
|
|
1247
|
+
* `amount` and `currency` to the order as `expectedAmount` and
|
|
1248
|
+
* `expectedCurrency`.
|
|
1249
|
+
*/
|
|
1250
|
+
quote(input: CardOrderQuoteInput): Promise<CardOrderQuote>;
|
|
1251
|
+
/**
|
|
1252
|
+
* The same quote before sign-in, for a landing page or the purchase form
|
|
1253
|
+
* before the e-mail code. Prices are list prices, and a code whose
|
|
1254
|
+
* conditions depend on the person (first card only, say) comes back
|
|
1255
|
+
* `conditional`, with `preliminary` set. Send `expectedAmount` with the
|
|
1256
|
+
* order placed at sign-in: if the price turns out different, no payment
|
|
1257
|
+
* is opened and `card_order_error` carries the new quote. The API limits
|
|
1258
|
+
* how often one address can ask (429 `too_many_requests`).
|
|
1259
|
+
*/
|
|
1260
|
+
quotePublic(input: Omit<CardOrderQuoteInput, "useBonus">): Promise<CardOrderQuote>;
|
|
1141
1261
|
/**
|
|
1142
1262
|
* The cards the caller can order, in the order the storefront shows them
|
|
1143
1263
|
* (`is_default` marks the one issued when none is chosen). Each item
|
|
@@ -1276,4 +1396,4 @@ declare class CardsResource {
|
|
|
1276
1396
|
terminate(id: string, reason?: string): Promise<Card>;
|
|
1277
1397
|
}
|
|
1278
1398
|
|
|
1279
|
-
export {
|
|
1399
|
+
export { type TransferInput as $, type Address as A, type BillingAddress as B, type CardProduct as C, type Deposit as D, type CustomerInfo as E, FundingOptionsResource as F, type DepositMethod as G, type DepositStatus as H, type DepositTarget as I, type FeeKind as J, type FunderMode as K, type FundingOption as L, type FundingQuote as M, type InitiateDepositInput as N, type IssuanceBonus as O, type IssueCardInput as P, type MethodTerms as Q, type PromoCodeQuote as R, type PromoCodeStatus as S, type Refund as T, type RevealCardInput as U, type RevealState as V, type RevealedCard as W, type SetPinInput as X, type TopUpInput as Y, type TopUpResult as Z, type TopUpTerms as _, type Card as a, type TransferResult as a0, type UpdateCardInput as a1, priceChangedQuote as a2, revealState as a3, cardOrderBody as a4, cardOrderQuoteBody as a5, cardRequestBody as a6, 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 CardProductPrice as n, type CardStatus as o, type CardStatusSource as p, type CardTariff as q, type CardTopUp as r, type CardTopUpStatus as s, type CardTransfer as t, type CardType as u, type Cardholder as v, type CloseBlockedReason as w, type CreateCardInput as x, type CreateDepositRefundInput as y, type CreateQuoteInput as z };
|