@ft-engage/sdk 0.0.0-stage → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @ft-engage/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ FT.Engage for the web, and the core of `@ft-engage/react-native`. It follows the shared [SDK protocol](../../docs/PROTOCOL.md).
4
+
5
+ ```ts
6
+ import { FtEngage, browserStorage } from '@ft-engage/sdk';
7
+ import { autoTrack } from '@ft-engage/sdk/web';
8
+
9
+ const engage = await FtEngage.init({
10
+ publicKey: 'pk_test_...',
11
+ endpoint: 'https://your-api.example.com',
12
+ platform: 'web',
13
+ appVersion: '1.0.0',
14
+ storage: browserStorage(),
15
+ });
16
+ autoTrack(engage);
17
+
18
+ await engage.identify('user_1001', { email: 'ada@example.com' });
19
+ engage.track('transfer.sent', { method: 'bank' });
20
+ ```
21
+
22
+ `autoTrack` records route changes as screens, clicks with their button or link text (and clicks that hit nothing), uncaught errors and promise rejections, the link that opened the page (UTM tags and Meta, TikTok, Snapchat, Google, X and LinkedIn click ids), and what is on the page in words: the heading, text, buttons, form fields (filled or not, never their values), alerts and dialogs. Everything is masked before it leaves the browser: emails, amounts of money and runs of four or more digits. Add `data-engage-sensitive` to any element to keep it out entirely. Turn parts off with `autoTrack(engage, { content: false, taps: false })`.
@@ -0,0 +1,102 @@
1
+ import type { ScreenContent } from './digest.ts';
2
+ import { Trail } from './errors.ts';
3
+ import type { KeyValueStorage } from './storage.ts';
4
+ export declare const SDK_VERSION = "0.14.0";
5
+ type Value = string | number | boolean | null;
6
+ type Props = Record<string, Value>;
7
+ type Fetch = (url: string, init: {
8
+ method: string;
9
+ headers: Record<string, string>;
10
+ body?: string;
11
+ }) => Promise<{
12
+ status: number;
13
+ }>;
14
+ export interface EngageConfig {
15
+ publicKey: string;
16
+ endpoint: string;
17
+ platform: 'ios' | 'android' | 'web';
18
+ appVersion?: string;
19
+ appId?: string;
20
+ storage?: KeyValueStorage;
21
+ fetch?: Fetch;
22
+ now?: () => Date;
23
+ batchSize?: number;
24
+ flushIntervalMs?: number | null;
25
+ maxQueue?: number;
26
+ requireConsent?: boolean;
27
+ timezone?: string;
28
+ locale?: string;
29
+ sessionTimeoutMs?: number;
30
+ }
31
+ export declare const cleanProps: (props?: Record<string, unknown>) => Props;
32
+ export declare class FtEngage {
33
+ private installId;
34
+ private queue;
35
+ private pendingRegister;
36
+ private pendingIdentify;
37
+ private pendingLogout;
38
+ private userId;
39
+ private consent;
40
+ private failures;
41
+ private retryAt;
42
+ private flushing;
43
+ private timer;
44
+ private sid;
45
+ private lastActivity;
46
+ private screenName;
47
+ private fingerprint;
48
+ private contentOnScreen;
49
+ private shownErrors;
50
+ private reported;
51
+ private reportedInSession;
52
+ private taps;
53
+ readonly trail: Trail;
54
+ private readonly storage;
55
+ private readonly send;
56
+ private readonly now;
57
+ readonly config: EngageConfig;
58
+ private constructor();
59
+ static init(config: EngageConfig): Promise<FtEngage>;
60
+ private load;
61
+ get id(): string;
62
+ get pending(): number;
63
+ get sessionId(): string | null;
64
+ setConsent(granted: boolean): Promise<void>;
65
+ setPush(status: 'granted' | 'denied' | 'unknown', token?: string): Promise<void>;
66
+ identify(userId: string, extra?: {
67
+ email?: string;
68
+ phone?: string;
69
+ traits?: Record<string, unknown>;
70
+ consent?: Record<string, boolean>;
71
+ userHash?: string;
72
+ userHashExpiresAt?: number;
73
+ }): Promise<void>;
74
+ logout(): Promise<void>;
75
+ forget(): Promise<void>;
76
+ private active;
77
+ private enqueue;
78
+ track(name: string, props?: Record<string, unknown>, options?: {
79
+ screen?: string;
80
+ }): void;
81
+ screen(name: string): void;
82
+ content(content: ScreenContent): void;
83
+ tap(tap: {
84
+ x: number;
85
+ y: number;
86
+ label?: string | null;
87
+ dead?: boolean;
88
+ }): void;
89
+ error(error: unknown, options?: {
90
+ fatal?: boolean;
91
+ source?: string;
92
+ }): void;
93
+ openedFrom(link: string): Promise<void>;
94
+ private clearQueue;
95
+ private post;
96
+ private fail;
97
+ flush(force?: boolean): Promise<void>;
98
+ private step;
99
+ private run;
100
+ close(): void;
101
+ }
102
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,311 @@
1
+ import { normaliseContent } from "./digest.js";
2
+ import { Trail, errorReport } from "./errors.js";
3
+ import { newEventId, newInstallId, newSessionId } from "./ids.js";
4
+ import { readLink } from "./links.js";
5
+ import { redactText } from "./redact.js";
6
+ import { MemoryStorage } from "./storage.js";
7
+ export const SDK_VERSION = '0.14.0';
8
+ const NAME = /^[a-z][a-z0-9_.]{0,63}$/;
9
+ const KEY = /^[a-z][a-z0-9_]{0,39}$/;
10
+ const MONEY_KEY = /(^|_)(amount|amounts|fee|fees|rate|rates|price|prices|balance|balances|revenue|volume|usd|total|cost|salary)($|_)/;
11
+ export const cleanProps = (props = {}) => {
12
+ const out = {};
13
+ for (const [k, v] of Object.entries(props)) {
14
+ if (Object.keys(out).length >= 40 || !KEY.test(k) || MONEY_KEY.test(k))
15
+ continue;
16
+ if (typeof v === 'string')
17
+ out[k] = v.slice(0, 256);
18
+ else if (typeof v === 'number' && Number.isFinite(v))
19
+ out[k] = v;
20
+ else if (typeof v === 'boolean' || v === null)
21
+ out[k] = v;
22
+ }
23
+ return out;
24
+ };
25
+ export class FtEngage {
26
+ installId = '';
27
+ queue = [];
28
+ pendingRegister = null;
29
+ pendingIdentify = null;
30
+ pendingLogout = false;
31
+ userId = null;
32
+ consent;
33
+ failures = 0;
34
+ retryAt = 0;
35
+ flushing = null;
36
+ timer = null;
37
+ sid = null;
38
+ lastActivity = 0;
39
+ screenName = null;
40
+ fingerprint = null;
41
+ contentOnScreen = 0;
42
+ shownErrors = new Set();
43
+ reported = new Map();
44
+ reportedInSession = 0;
45
+ taps = [];
46
+ trail = new Trail();
47
+ storage;
48
+ send;
49
+ now;
50
+ config;
51
+ constructor(config) {
52
+ this.config = config;
53
+ this.storage = config.storage ?? new MemoryStorage();
54
+ this.send = config.fetch ?? ((url, init) => globalThis.fetch(url, init));
55
+ this.now = config.now ?? (() => new Date());
56
+ this.consent = !config.requireConsent;
57
+ }
58
+ static async init(config) {
59
+ if (!/^pk_(test|live)_/.test(config.publicKey)) {
60
+ throw new Error('FT.Engage needs a public key (pk_test_ or pk_live_). Never put a secret key in an app.');
61
+ }
62
+ const engage = new FtEngage(config);
63
+ await engage.load();
64
+ const interval = config.flushIntervalMs === undefined ? 10_000 : config.flushIntervalMs;
65
+ if (interval !== null)
66
+ engage.timer = setInterval(() => void engage.flush(), interval);
67
+ return engage;
68
+ }
69
+ async load() {
70
+ const s = this.storage;
71
+ this.installId = (await s.get('install')) ?? newInstallId();
72
+ await s.set('install', this.installId);
73
+ this.queue = JSON.parse((await s.get('queue')) ?? '[]');
74
+ this.userId = await s.get('user');
75
+ if (this.config.requireConsent)
76
+ this.consent = (await s.get('consent')) === 'granted';
77
+ const registration = {
78
+ installId: this.installId,
79
+ platform: this.config.platform,
80
+ sdkVersion: SDK_VERSION,
81
+ ...(this.config.appVersion ? { appVersion: this.config.appVersion } : {}),
82
+ timezone: this.config.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone,
83
+ ...(this.config.locale ? { locale: this.config.locale } : {}),
84
+ };
85
+ if ((await s.get('registered')) !== JSON.stringify(registration))
86
+ this.pendingRegister = registration;
87
+ }
88
+ get id() {
89
+ return this.installId;
90
+ }
91
+ get pending() {
92
+ return this.queue.length;
93
+ }
94
+ get sessionId() {
95
+ return this.sid;
96
+ }
97
+ async setConsent(granted) {
98
+ this.consent = granted;
99
+ await this.storage.set('consent', granted ? 'granted' : 'denied');
100
+ if (!granted)
101
+ await this.clearQueue();
102
+ }
103
+ async setPush(status, token) {
104
+ this.pendingRegister = { ...(this.pendingRegister ?? { installId: this.installId, platform: this.config.platform, sdkVersion: SDK_VERSION }), pushStatus: status, ...(token ? { pushToken: token } : {}) };
105
+ await this.flush();
106
+ }
107
+ async identify(userId, extra = {}) {
108
+ this.userId = userId;
109
+ await this.storage.set('user', userId);
110
+ this.pendingLogout = false;
111
+ this.pendingIdentify = { installId: this.installId, userId, ...extra, ...(extra.traits ? { traits: cleanProps(extra.traits) } : {}) };
112
+ await this.flush();
113
+ }
114
+ async logout() {
115
+ this.userId = null;
116
+ this.pendingIdentify = null;
117
+ this.pendingLogout = true;
118
+ await this.storage.remove('user');
119
+ this.trail.clear();
120
+ await this.flush();
121
+ }
122
+ async forget() {
123
+ await this.clearQueue();
124
+ for (const k of ['install', 'user', 'registered', 'consent', 'referrer'])
125
+ await this.storage.remove(k);
126
+ this.userId = null;
127
+ this.installId = newInstallId();
128
+ await this.storage.set('install', this.installId);
129
+ this.pendingRegister = { installId: this.installId, platform: this.config.platform, sdkVersion: SDK_VERSION };
130
+ this.trail.clear();
131
+ }
132
+ active() {
133
+ const now = this.now().getTime();
134
+ const gap = this.config.sessionTimeoutMs ?? 30 * 60_000;
135
+ if (!this.sid || now - this.lastActivity > gap) {
136
+ if (this.sid)
137
+ this.enqueue('session.ended', { sid: this.sid }, undefined, new Date(this.lastActivity));
138
+ this.sid = newSessionId();
139
+ this.reportedInSession = 0;
140
+ this.reported.clear();
141
+ this.lastActivity = now;
142
+ this.enqueue('session.started', { sid: this.sid });
143
+ }
144
+ this.lastActivity = now;
145
+ return this.sid;
146
+ }
147
+ enqueue(name, props, screen = this.screenName ?? undefined, at = this.now()) {
148
+ if (!this.consent || !NAME.test(name))
149
+ return;
150
+ this.queue.push({
151
+ eventId: newEventId(),
152
+ name,
153
+ installId: this.installId,
154
+ ...(this.userId ? { userId: this.userId } : {}),
155
+ ...(screen ? { screen: screen.slice(0, 128) } : {}),
156
+ at: at.toISOString(),
157
+ props,
158
+ });
159
+ const max = this.config.maxQueue ?? 1000;
160
+ if (this.queue.length > max)
161
+ this.queue.splice(0, this.queue.length - max);
162
+ void this.storage.set('queue', JSON.stringify(this.queue));
163
+ if (this.queue.length >= (this.config.batchSize ?? 20))
164
+ void this.flush();
165
+ }
166
+ track(name, props = {}, options = {}) {
167
+ this.active();
168
+ this.enqueue(name, cleanProps(props), options.screen ?? this.screenName ?? undefined);
169
+ }
170
+ screen(name) {
171
+ const clean = name.trim().slice(0, 128);
172
+ if (!clean || clean === this.screenName)
173
+ return;
174
+ const sid = this.active();
175
+ const from = this.screenName;
176
+ this.screenName = clean;
177
+ this.fingerprint = null;
178
+ this.contentOnScreen = 0;
179
+ this.shownErrors.clear();
180
+ this.taps = [];
181
+ this.trail.add(clean);
182
+ this.enqueue('screen.viewed', { sid, ...(from ? { from } : {}) });
183
+ }
184
+ content(content) {
185
+ if (!this.screenName)
186
+ return;
187
+ const n = normaliseContent(content);
188
+ if (n.empty || n.fingerprint === this.fingerprint || this.contentOnScreen >= 30)
189
+ return;
190
+ this.fingerprint = n.fingerprint;
191
+ this.contentOnScreen += 1;
192
+ const sid = this.active();
193
+ this.enqueue('screen.changed', { sid, ...n.props });
194
+ for (const e of n.errors) {
195
+ const key = `${e.where}|${e.field ?? ''}|${e.message}`;
196
+ if (this.shownErrors.has(key))
197
+ continue;
198
+ this.shownErrors.add(key);
199
+ this.trail.add(`saw ${e.message}`);
200
+ this.enqueue('ui.error_shown', { sid, where: e.where, message: e.message, ...(e.field ? { field: e.field } : {}) });
201
+ }
202
+ }
203
+ tap(tap) {
204
+ if (!this.screenName)
205
+ return;
206
+ const sid = this.active();
207
+ const x = Math.round(Math.min(1, Math.max(0, tap.x)) * 1000) / 1000;
208
+ const y = Math.round(Math.min(1, Math.max(0, tap.y)) * 1000) / 1000;
209
+ const label = tap.label ? redactText(tap.label, 32) : null;
210
+ this.trail.add(label ? `tap ${label}` : 'tap');
211
+ this.enqueue('ui.tap', { sid, x, y, ...(label ? { label } : {}), ...(tap.dead ? { dead: true } : {}) });
212
+ const now = this.now().getTime();
213
+ this.taps = [...this.taps.filter((t) => now - t.at <= 1000 && Math.hypot(t.x - x, t.y - y) <= 0.06), { x, y, at: now }];
214
+ if (this.taps.length === 3)
215
+ this.enqueue('ui.rage_tap', { sid, x, y, taps: 3, ...(label ? { label } : {}) });
216
+ }
217
+ error(error, options = {}) {
218
+ const props = errorReport(error, options.fatal ?? false, this.trail.describe(), options.source ?? 'app');
219
+ const now = this.now().getTime();
220
+ const last = this.reported.get(props.signature);
221
+ if ((last !== undefined && now - last < 60_000) || this.reportedInSession >= 25)
222
+ return;
223
+ this.reported.set(props.signature, now);
224
+ this.reportedInSession += 1;
225
+ const sid = this.active();
226
+ this.enqueue('app.error', { sid, ...props });
227
+ }
228
+ async openedFrom(link) {
229
+ const found = readLink(link);
230
+ if (!found)
231
+ return;
232
+ this.track('link.opened', {
233
+ url_host: found.host,
234
+ source: found.source,
235
+ medium: found.medium,
236
+ campaign: found.campaign,
237
+ click_id_type: found.clickIdType,
238
+ });
239
+ if (found.referrer && !(await this.storage.get('referrer'))) {
240
+ await this.storage.set('referrer', found.referrer);
241
+ await this.post('/v1/attribution/install', { installId: this.installId, referrer: found.referrer }).catch(() => undefined);
242
+ }
243
+ }
244
+ async clearQueue() {
245
+ this.queue = [];
246
+ await this.storage.set('queue', '[]');
247
+ }
248
+ async post(path, body) {
249
+ const url = `${this.config.endpoint.replace(/\/+$/, '')}${path}`;
250
+ const headers = { 'content-type': 'application/json', authorization: `Bearer ${this.config.publicKey}` };
251
+ if (this.config.appId)
252
+ headers['x-engage-app'] = this.config.appId;
253
+ return (await this.send(url, { method: 'POST', headers, body: JSON.stringify(body) })).status;
254
+ }
255
+ fail() {
256
+ this.failures += 1;
257
+ this.retryAt = this.now().getTime() + Math.min(300, 2 ** this.failures) * 1000;
258
+ }
259
+ flush(force = false) {
260
+ if (!this.flushing)
261
+ this.flushing = this.run(force).finally(() => (this.flushing = null));
262
+ return this.flushing;
263
+ }
264
+ async step(path, body, ok) {
265
+ try {
266
+ const status = await this.post(path, body);
267
+ if (ok.includes(status))
268
+ return true;
269
+ }
270
+ catch {
271
+ this.fail();
272
+ return false;
273
+ }
274
+ this.fail();
275
+ return false;
276
+ }
277
+ async run(force) {
278
+ if (!this.consent || (!force && this.now().getTime() < this.retryAt))
279
+ return;
280
+ if (this.pendingRegister) {
281
+ if (!(await this.step('/v1/register', this.pendingRegister, [200, 400])))
282
+ return;
283
+ await this.storage.set('registered', JSON.stringify(this.pendingRegister));
284
+ this.pendingRegister = null;
285
+ }
286
+ if (this.pendingLogout) {
287
+ if (!(await this.step('/v1/logout', { installId: this.installId }, [200, 400, 404])))
288
+ return;
289
+ this.pendingLogout = false;
290
+ }
291
+ if (this.pendingIdentify) {
292
+ if (!(await this.step('/v1/identify', this.pendingIdentify, [200, 400])))
293
+ return;
294
+ this.pendingIdentify = null;
295
+ }
296
+ while (this.queue.length > 0) {
297
+ const batch = this.queue.slice(0, 50);
298
+ if (!(await this.step('/v1/events', { sentAt: this.now().toISOString(), events: batch }, [200, 400, 422])))
299
+ return;
300
+ this.queue.splice(0, batch.length);
301
+ await this.storage.set('queue', JSON.stringify(this.queue));
302
+ }
303
+ this.failures = 0;
304
+ this.retryAt = 0;
305
+ }
306
+ close() {
307
+ if (this.timer)
308
+ clearInterval(this.timer);
309
+ this.timer = null;
310
+ }
311
+ }
@@ -0,0 +1,30 @@
1
+ export interface ScreenField {
2
+ label: string;
3
+ filled: boolean;
4
+ error?: string | null;
5
+ }
6
+ export interface ScreenError {
7
+ where: 'field' | 'dialog' | 'snackbar' | 'banner' | 'inline' | 'toast';
8
+ message: string;
9
+ field?: string | null;
10
+ }
11
+ export interface ScreenContent {
12
+ title?: string | null;
13
+ texts?: string[];
14
+ buttons?: string[];
15
+ fields?: ScreenField[];
16
+ errors?: ScreenError[];
17
+ images?: number;
18
+ listItems?: number;
19
+ dialog?: string | null;
20
+ }
21
+ export declare const normaliseContent: (c: ScreenContent) => {
22
+ props: Record<string, string | number>;
23
+ errors: {
24
+ where: "field" | "dialog" | "snackbar" | "banner" | "inline" | "toast";
25
+ message: string;
26
+ field: string | null;
27
+ }[];
28
+ fingerprint: string;
29
+ empty: boolean;
30
+ };
package/dist/digest.js ADDED
@@ -0,0 +1,59 @@
1
+ import { redactText } from "./redact.js";
2
+ const clean = (items, cap) => {
3
+ const out = [];
4
+ for (const raw of items ?? []) {
5
+ const t = redactText(raw, 60);
6
+ if (t && !out.includes(t))
7
+ out.push(t);
8
+ if (out.length >= cap)
9
+ break;
10
+ }
11
+ return out;
12
+ };
13
+ const join = (parts) => {
14
+ let out = '';
15
+ for (const p of parts) {
16
+ const next = out === '' ? p : `${out} | ${p}`;
17
+ if (next.length > 256)
18
+ break;
19
+ out = next;
20
+ }
21
+ return out === '' ? undefined : out;
22
+ };
23
+ export const normaliseContent = (c) => {
24
+ const fields = (c.fields ?? []).slice(0, 16).map((f) => ({
25
+ label: redactText(f.label, 60) ?? 'Field',
26
+ filled: f.filled,
27
+ error: f.error ? redactText(f.error) : null,
28
+ }));
29
+ const errors = (c.errors ?? []).slice(0, 8).flatMap((e) => {
30
+ const message = redactText(e.message);
31
+ return message ? [{ where: e.where, message, field: e.field ? redactText(e.field, 60) : null }] : [];
32
+ });
33
+ const texts = clean(c.texts, 24);
34
+ const buttons = clean(c.buttons, 16);
35
+ const title = c.title ? redactText(c.title) : null;
36
+ const dialog = c.dialog ? redactText(c.dialog) : null;
37
+ const fieldText = fields.map((f) => `${f.label} (${f.filled ? 'filled' : 'empty'}${f.error ? ', error' : ''})`);
38
+ const props = {
39
+ text_count: texts.length,
40
+ button_count: buttons.length,
41
+ field_count: fields.length,
42
+ error_count: errors.length,
43
+ image_count: c.images ?? 0,
44
+ list_items: c.listItems ?? 0,
45
+ };
46
+ const add = (k, v) => {
47
+ if (v)
48
+ props[k] = v;
49
+ };
50
+ add('title', title);
51
+ add('texts', join(texts));
52
+ add('buttons', join(buttons));
53
+ add('fields', join(fieldText));
54
+ add('errors', join(errors.map((e) => e.message)));
55
+ add('dialog', dialog);
56
+ const fingerprint = [title ?? '', buttons.join(','), fieldText.join(','), errors.map((e) => `${e.where}|${e.field ?? ''}|${e.message}`).join(','), dialog ?? '', texts.slice(0, 4).join(',')].join('#');
57
+ const empty = !title && texts.length === 0 && buttons.length === 0 && fields.length === 0;
58
+ return { props, errors, fingerprint, empty };
59
+ };
@@ -0,0 +1,16 @@
1
+ export declare class Trail {
2
+ private readonly steps;
3
+ private readonly size;
4
+ constructor(size?: number);
5
+ add(step: string): void;
6
+ describe(): string | null;
7
+ clear(): void;
8
+ }
9
+ export interface ErrorProps extends Record<string, string | boolean> {
10
+ type: string;
11
+ message: string;
12
+ signature: string;
13
+ fatal: boolean;
14
+ source: string;
15
+ }
16
+ export declare const errorReport: (error: unknown, fatal: boolean, trail: string | null, source: string) => ErrorProps;
package/dist/errors.js ADDED
@@ -0,0 +1,62 @@
1
+ import { fnv } from "./ids.js";
2
+ import { redactText } from "./redact.js";
3
+ export class Trail {
4
+ steps = [];
5
+ size;
6
+ constructor(size = 12) {
7
+ this.size = size;
8
+ }
9
+ add(step) {
10
+ const clean = redactText(step, 60);
11
+ if (!clean || this.steps[this.steps.length - 1] === clean)
12
+ return;
13
+ this.steps.push(clean);
14
+ if (this.steps.length > this.size)
15
+ this.steps.shift();
16
+ }
17
+ describe() {
18
+ let out = '';
19
+ for (let i = this.steps.length - 1; i >= 0; i--) {
20
+ const next = out === '' ? this.steps[i] : `${this.steps[i]} > ${out}`;
21
+ if (next.length > 256)
22
+ break;
23
+ out = next;
24
+ }
25
+ return out === '' ? null : out;
26
+ }
27
+ clear() {
28
+ this.steps.length = 0;
29
+ }
30
+ }
31
+ const FRAME = /^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?$|^\s*(.*?)@(.+?):(\d+):\d+$/;
32
+ const SKIP = /(node_modules|@ft-engage|webpack|<anonymous>|native|internal\/)/;
33
+ const short = (path) => path.split(/[\\/]/).pop()?.split('?')[0] ?? path;
34
+ export const errorReport = (error, fatal, trail, source) => {
35
+ const err = error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Non-error thrown');
36
+ const type = (err.name || 'Error').slice(0, 120);
37
+ const message = redactText(err.message || type, 200) ?? type;
38
+ const frames = [];
39
+ for (const line of (err.stack ?? '').split('\n')) {
40
+ const m = FRAME.exec(line);
41
+ if (!m)
42
+ continue;
43
+ const fn = m[1] ?? m[4] ?? '';
44
+ const file = m[2] ?? m[5] ?? '';
45
+ const lineNo = m[3] ?? m[6] ?? '';
46
+ if (SKIP.test(file))
47
+ continue;
48
+ frames.push(`${fn || 'anonymous'} (${short(file)}:${lineNo})`);
49
+ if (frames.length === 5)
50
+ break;
51
+ }
52
+ const joined = frames.join(' < ').slice(0, 256);
53
+ return {
54
+ type,
55
+ message,
56
+ signature: fnv(`${type}@${frames[0] ?? message}`),
57
+ fatal,
58
+ source,
59
+ ...(joined ? { frames: joined } : {}),
60
+ ...(trail ? { trail } : {}),
61
+ };
62
+ };
package/dist/ids.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export declare const newInstallId: () => string;
2
+ export declare const newEventId: () => string;
3
+ export declare const newSessionId: () => string;
4
+ export declare const fnv: (text: string) => string;
package/dist/ids.js ADDED
@@ -0,0 +1,17 @@
1
+ const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
2
+ const random = (length) => {
3
+ const bytes = new Uint8Array(length);
4
+ globalThis.crypto.getRandomValues(bytes);
5
+ return Array.from(bytes, (b) => ALPHABET[b % 36]).join('');
6
+ };
7
+ export const newInstallId = () => `inst_${random(24)}`;
8
+ export const newEventId = () => `evt_${random(24)}`;
9
+ export const newSessionId = () => `s${random(8)}`;
10
+ export const fnv = (text) => {
11
+ let hash = 0x811c9dc5;
12
+ for (let i = 0; i < text.length; i++) {
13
+ hash ^= text.charCodeAt(i);
14
+ hash = Math.imul(hash, 0x01000193) >>> 0;
15
+ }
16
+ return hash.toString(16).padStart(8, '0');
17
+ };
@@ -0,0 +1,9 @@
1
+ export { FtEngage, SDK_VERSION, cleanProps } from './client.ts';
2
+ export type { EngageConfig } from './client.ts';
3
+ export type { ScreenContent, ScreenError, ScreenField } from './digest.ts';
4
+ export { Trail, errorReport } from './errors.ts';
5
+ export { readLink, CLICK_IDS } from './links.ts';
6
+ export type { LinkSource } from './links.ts';
7
+ export { redactText } from './redact.ts';
8
+ export { MemoryStorage, browserStorage } from './storage.ts';
9
+ export type { KeyValueStorage } from './storage.ts';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { FtEngage, SDK_VERSION, cleanProps } from "./client.js";
2
+ export { Trail, errorReport } from "./errors.js";
3
+ export { readLink, CLICK_IDS } from "./links.js";
4
+ export { redactText } from "./redact.js";
5
+ export { MemoryStorage, browserStorage } from "./storage.js";
@@ -0,0 +1,11 @@
1
+ export declare const CLICK_IDS: Record<string, string>;
2
+ export interface LinkSource {
3
+ host: string | null;
4
+ source: string | null;
5
+ medium: string | null;
6
+ campaign: string | null;
7
+ clickIdType: string | null;
8
+ referrer: string | null;
9
+ }
10
+ /** Reads where a person came from out of the link that opened the app. */
11
+ export declare const readLink: (link: string) => LinkSource | null;
package/dist/links.js ADDED
@@ -0,0 +1,48 @@
1
+ export const CLICK_IDS = {
2
+ fbclid: 'meta',
3
+ ttclid: 'tiktok',
4
+ ScCid: 'snapchat',
5
+ sccid: 'snapchat',
6
+ gclid: 'google',
7
+ gbraid: 'google',
8
+ wbraid: 'google',
9
+ twclid: 'x',
10
+ li_fat_id: 'linkedin',
11
+ };
12
+ const clean = (v) => (v && /^[A-Za-z0-9_.-]{1,64}$/.test(v) ? v : null);
13
+ /** Reads where a person came from out of the link that opened the app. */
14
+ export const readLink = (link) => {
15
+ let url;
16
+ try {
17
+ url = new URL(link);
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ const q = url.searchParams;
23
+ let clickIdType = null;
24
+ const keep = new URLSearchParams();
25
+ for (const key of ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term']) {
26
+ const v = q.get(key);
27
+ if (v)
28
+ keep.set(key, v.slice(0, 100));
29
+ }
30
+ for (const [key, network] of Object.entries(CLICK_IDS)) {
31
+ const v = q.get(key);
32
+ if (v && !clickIdType) {
33
+ clickIdType = network;
34
+ keep.set(key, v.slice(0, 500));
35
+ }
36
+ }
37
+ const source = clean(q.get('utm_source')) ?? (clickIdType ? clean(clickIdType) : null);
38
+ if (!source && !clickIdType)
39
+ return null;
40
+ return {
41
+ host: url.host || null,
42
+ source,
43
+ medium: clean(q.get('utm_medium')) ?? (clickIdType ? 'paid' : null),
44
+ campaign: clean(q.get('utm_campaign')),
45
+ clickIdType,
46
+ referrer: keep.toString().slice(0, 1000) || null,
47
+ };
48
+ };
@@ -0,0 +1 @@
1
+ export declare const redactText: (value: string, max?: number) => string | null;
package/dist/redact.js ADDED
@@ -0,0 +1,13 @@
1
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
2
+ const MONEY = /(?:[₦$€£¥₵]|\b(?:NGN|USD|EUR|GBP|GHS|KES|ZAR)\b)\s?\d[\d,.]*(?:\s\d[\d,.]*)*/gi;
3
+ const DIGITS = /\d(?:[\d\s,.\-/]*\d)?/g;
4
+ export const redactText = (value, max = 120) => {
5
+ const trimmed = value.replace(/\s+/g, ' ').trim();
6
+ if (trimmed === '')
7
+ return null;
8
+ const masked = trimmed
9
+ .replace(EMAIL, '•••@•••')
10
+ .replace(MONEY, (m) => m.replace(/\d[\d,.\s]*/, '•••'))
11
+ .replace(DIGITS, (run) => ((run.match(/\d/g) ?? []).length >= 4 ? run.replace(/\d/g, '•') : run));
12
+ return Array.from(masked).slice(0, max).join('');
13
+ };
@@ -0,0 +1,12 @@
1
+ export interface KeyValueStorage {
2
+ get(key: string): Promise<string | null>;
3
+ set(key: string, value: string): Promise<void>;
4
+ remove(key: string): Promise<void>;
5
+ }
6
+ export declare class MemoryStorage implements KeyValueStorage {
7
+ private readonly values;
8
+ get(key: string): Promise<string | null>;
9
+ set(key: string, value: string): Promise<void>;
10
+ remove(key: string): Promise<void>;
11
+ }
12
+ export declare const browserStorage: (prefix?: string) => KeyValueStorage;
@@ -0,0 +1,23 @@
1
+ export class MemoryStorage {
2
+ values = new Map();
3
+ async get(key) {
4
+ return this.values.get(key) ?? null;
5
+ }
6
+ async set(key, value) {
7
+ this.values.set(key, value);
8
+ }
9
+ async remove(key) {
10
+ this.values.delete(key);
11
+ }
12
+ }
13
+ export const browserStorage = (prefix = 'ft_engage.') => ({
14
+ async get(key) {
15
+ return globalThis.localStorage?.getItem(prefix + key) ?? null;
16
+ },
17
+ async set(key, value) {
18
+ globalThis.localStorage?.setItem(prefix + key, value);
19
+ },
20
+ async remove(key) {
21
+ globalThis.localStorage?.removeItem(prefix + key);
22
+ },
23
+ });
package/dist/web.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { FtEngage } from './client.ts';
2
+ import type { ScreenContent } from './digest.ts';
3
+ export interface AutoTrackOptions {
4
+ screens?: boolean;
5
+ taps?: boolean;
6
+ errors?: boolean;
7
+ content?: boolean;
8
+ contentIntervalMs?: number;
9
+ screenName?: (location: Location) => string;
10
+ }
11
+ export declare const readPage: (doc?: Document) => ScreenContent;
12
+ export declare const autoTrack: (engage: FtEngage, options?: AutoTrackOptions) => (() => void);
package/dist/web.js ADDED
@@ -0,0 +1,110 @@
1
+ const SENSITIVE = '[data-engage-sensitive]';
2
+ const INTERACTIVE = 'a,button,input,select,textarea,label,summary,[role=button],[role=link],[role=tab],[role=menuitem],[onclick],[tabindex]';
3
+ const visible = (el) => {
4
+ if (el.closest(SENSITIVE))
5
+ return false;
6
+ const html = el;
7
+ if (html.hidden || html.closest('[hidden],[aria-hidden=true]'))
8
+ return false;
9
+ const rect = html.getBoundingClientRect?.();
10
+ return !rect || (rect.width > 0 && rect.height > 0);
11
+ };
12
+ const text = (el) => (el?.textContent ?? '').replace(/\s+/g, ' ').trim();
13
+ const labelOf = (el) => el.getAttribute('aria-label') ?? el.placeholder ?? text(el.closest('label')) ?? '';
14
+ const fieldLabel = (el) => {
15
+ const id = el.id;
16
+ const linked = id ? el.ownerDocument.querySelector(`label[for="${CSS.escape(id)}"]`) : null;
17
+ return el.getAttribute('aria-label') || text(linked) || text(el.closest('label')) || el.placeholder || el.name || 'Field';
18
+ };
19
+ export const readPage = (doc = document) => {
20
+ const all = (selector) => Array.from(doc.querySelectorAll(selector)).filter(visible);
21
+ const fields = [];
22
+ const errors = [];
23
+ for (const el of all('input:not([type=hidden]):not([type=submit]):not([type=button]),select,textarea')) {
24
+ const label = fieldLabel(el);
25
+ const described = el.getAttribute('aria-describedby');
26
+ const hint = described ? text(doc.getElementById(described)) : '';
27
+ const invalid = el.getAttribute('aria-invalid') === 'true';
28
+ const error = invalid ? hint || el.validationMessage || 'Invalid' : null;
29
+ const filled = el.type === 'checkbox' || el.type === 'radio' ? el.checked : el.value !== '';
30
+ fields.push({ label, filled, error });
31
+ if (error)
32
+ errors.push({ where: 'field', message: error, field: label });
33
+ }
34
+ for (const el of all('[role=alert],[aria-live=assertive],.error,.error-message,.alert-danger,.toast-error')) {
35
+ const message = text(el);
36
+ if (message)
37
+ errors.push({ where: el.closest('[role=dialog]') ? 'dialog' : 'banner', message });
38
+ }
39
+ const dialog = all('[role=dialog],dialog[open]')[0];
40
+ return {
41
+ title: text(all('h1')[0]) || doc.title || null,
42
+ texts: all('h2,h3,p,li,td,dt,dd,figcaption,blockquote').map(text).filter(Boolean),
43
+ buttons: all('button,[role=button],a[href],input[type=submit],input[type=button]').map((b) => text(b) || labelOf(b)).filter(Boolean),
44
+ fields,
45
+ errors,
46
+ images: all('img,svg[role=img]').length,
47
+ listItems: all('li,[role=listitem],[role=row]').length,
48
+ dialog: dialog ? text(dialog.querySelector('h1,h2,h3,[role=heading]')) || null : null,
49
+ };
50
+ };
51
+ export const autoTrack = (engage, options = {}) => {
52
+ const w = globalThis.window;
53
+ if (!w)
54
+ return () => undefined;
55
+ const stops = [];
56
+ const name = options.screenName ?? ((l) => l.pathname || '/');
57
+ const onRoute = () => engage.screen(name(w.location));
58
+ if (options.screens !== false) {
59
+ onRoute();
60
+ for (const method of ['pushState', 'replaceState']) {
61
+ const original = w.history[method].bind(w.history);
62
+ w.history[method] = (...args) => {
63
+ original(...args);
64
+ onRoute();
65
+ };
66
+ stops.push(() => (w.history[method] = original));
67
+ }
68
+ w.addEventListener('popstate', onRoute);
69
+ w.addEventListener('hashchange', onRoute);
70
+ stops.push(() => w.removeEventListener('popstate', onRoute), () => w.removeEventListener('hashchange', onRoute));
71
+ }
72
+ if (options.taps !== false) {
73
+ const onClick = (e) => {
74
+ const target = e.target instanceof Element ? e.target : null;
75
+ if (!target || target.closest(SENSITIVE))
76
+ return;
77
+ const hit = target.closest(INTERACTIVE);
78
+ const label = hit ? text(hit).slice(0, 40) || labelOf(hit) : null;
79
+ engage.tap({ x: e.clientX / Math.max(1, w.innerWidth), y: e.clientY / Math.max(1, w.innerHeight), label, dead: !hit });
80
+ };
81
+ w.document.addEventListener('click', onClick, true);
82
+ stops.push(() => w.document.removeEventListener('click', onClick, true));
83
+ }
84
+ if (options.errors !== false) {
85
+ const onError = (e) => engage.error(e.error ?? e.message, { source: 'window' });
86
+ const onRejection = (e) => engage.error(e.reason, { source: 'promise' });
87
+ w.addEventListener('error', onError);
88
+ w.addEventListener('unhandledrejection', onRejection);
89
+ stops.push(() => w.removeEventListener('error', onError), () => w.removeEventListener('unhandledrejection', onRejection));
90
+ }
91
+ if (options.content !== false) {
92
+ const timer = setInterval(() => {
93
+ try {
94
+ engage.content(readPage(w.document));
95
+ }
96
+ catch {
97
+ return;
98
+ }
99
+ }, options.contentIntervalMs ?? 1500);
100
+ stops.push(() => clearInterval(timer));
101
+ }
102
+ const onHide = () => {
103
+ if (w.document.visibilityState === 'hidden')
104
+ void engage.flush(true);
105
+ };
106
+ w.document.addEventListener('visibilitychange', onHide);
107
+ stops.push(() => w.document.removeEventListener('visibilitychange', onHide));
108
+ void engage.openedFrom(w.location.href);
109
+ return () => stops.forEach((stop) => stop());
110
+ };
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@ft-engage/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.14.0",
4
+ "description": "FT.Engage SDK core for the web and React Native: events, identity, sessions, screen content, errors and attribution.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
11
+ "./web": { "types": "./dist/web.d.ts", "default": "./dist/web.js" }
12
+ },
13
+ "files": ["dist", "README.md"],
14
+ "sideEffects": false,
15
+ "scripts": {
16
+ "build": "tsc -p tsconfig.build.json",
17
+ "typecheck": "tsc --noEmit",
18
+ "test": "node --test \"test/**/*.test.ts\""
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^24.0.0",
22
+ "typescript": "^5.9.3"
23
+ }
24
+ }