@qoretechnologies/reqraft 0.10.56 → 0.10.57-pr.127.g0edd18d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/.claude/CLAUDE.md +1 -0
  2. package/README.md +20 -0
  3. package/design/TRACKING.md +278 -0
  4. package/dist/index.d.ts +2 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +5 -0
  7. package/dist/index.js.map +1 -1
  8. package/dist/tracking/browser/attach.d.ts +8 -0
  9. package/dist/tracking/browser/attach.d.ts.map +1 -0
  10. package/dist/tracking/browser/attach.js +182 -0
  11. package/dist/tracking/browser/attach.js.map +1 -0
  12. package/dist/tracking/browser/env.d.ts +14 -0
  13. package/dist/tracking/browser/env.d.ts.map +1 -0
  14. package/dist/tracking/browser/env.js +150 -0
  15. package/dist/tracking/browser/env.js.map +1 -0
  16. package/dist/tracking/core/consent.d.ts +21 -0
  17. package/dist/tracking/core/consent.d.ts.map +1 -0
  18. package/dist/tracking/core/consent.js +39 -0
  19. package/dist/tracking/core/consent.js.map +1 -0
  20. package/dist/tracking/core/engagement.d.ts +20 -0
  21. package/dist/tracking/core/engagement.d.ts.map +1 -0
  22. package/dist/tracking/core/engagement.js +52 -0
  23. package/dist/tracking/core/engagement.js.map +1 -0
  24. package/dist/tracking/core/experiments.d.ts +109 -0
  25. package/dist/tracking/core/experiments.d.ts.map +1 -0
  26. package/dist/tracking/core/experiments.js +294 -0
  27. package/dist/tracking/core/experiments.js.map +1 -0
  28. package/dist/tracking/core/hash.d.ts +16 -0
  29. package/dist/tracking/core/hash.d.ts.map +1 -0
  30. package/dist/tracking/core/hash.js +31 -0
  31. package/dist/tracking/core/hash.js.map +1 -0
  32. package/dist/tracking/core/ids.d.ts +6 -0
  33. package/dist/tracking/core/ids.d.ts.map +1 -0
  34. package/dist/tracking/core/ids.js +31 -0
  35. package/dist/tracking/core/ids.js.map +1 -0
  36. package/dist/tracking/core/observable.d.ts +12 -0
  37. package/dist/tracking/core/observable.d.ts.map +1 -0
  38. package/dist/tracking/core/observable.js +32 -0
  39. package/dist/tracking/core/observable.js.map +1 -0
  40. package/dist/tracking/core/queue.d.ts +47 -0
  41. package/dist/tracking/core/queue.d.ts.map +1 -0
  42. package/dist/tracking/core/queue.js +205 -0
  43. package/dist/tracking/core/queue.js.map +1 -0
  44. package/dist/tracking/core/sections.d.ts +54 -0
  45. package/dist/tracking/core/sections.d.ts.map +1 -0
  46. package/dist/tracking/core/sections.js +156 -0
  47. package/dist/tracking/core/sections.js.map +1 -0
  48. package/dist/tracking/core/storage.d.ts +15 -0
  49. package/dist/tracking/core/storage.d.ts.map +1 -0
  50. package/dist/tracking/core/storage.js +72 -0
  51. package/dist/tracking/core/storage.js.map +1 -0
  52. package/dist/tracking/core/tracker.d.ts +122 -0
  53. package/dist/tracking/core/tracker.d.ts.map +1 -0
  54. package/dist/tracking/core/tracker.js +390 -0
  55. package/dist/tracking/core/tracker.js.map +1 -0
  56. package/dist/tracking/core/types.d.ts +130 -0
  57. package/dist/tracking/core/types.d.ts.map +1 -0
  58. package/dist/tracking/core/types.js +69 -0
  59. package/dist/tracking/core/types.js.map +1 -0
  60. package/dist/tracking/core/utm.d.ts +6 -0
  61. package/dist/tracking/core/utm.d.ts.map +1 -0
  62. package/dist/tracking/core/utm.js +30 -0
  63. package/dist/tracking/core/utm.js.map +1 -0
  64. package/dist/tracking/index.d.ts +46 -0
  65. package/dist/tracking/index.d.ts.map +1 -0
  66. package/dist/tracking/index.js +91 -0
  67. package/dist/tracking/index.js.map +1 -0
  68. package/dist/tracking/markup.d.ts +12 -0
  69. package/dist/tracking/markup.d.ts.map +1 -0
  70. package/dist/tracking/markup.js +19 -0
  71. package/dist/tracking/markup.js.map +1 -0
  72. package/dist/tracking/react/Experiment.d.ts +23 -0
  73. package/dist/tracking/react/Experiment.d.ts.map +1 -0
  74. package/dist/tracking/react/Experiment.js +28 -0
  75. package/dist/tracking/react/Experiment.js.map +1 -0
  76. package/dist/tracking/react/TrackingProvider.d.ts +26 -0
  77. package/dist/tracking/react/TrackingProvider.d.ts.map +1 -0
  78. package/dist/tracking/react/TrackingProvider.js +45 -0
  79. package/dist/tracking/react/TrackingProvider.js.map +1 -0
  80. package/dist/tracking/react/hooks.d.ts +39 -0
  81. package/dist/tracking/react/hooks.d.ts.map +1 -0
  82. package/dist/tracking/react/hooks.js +96 -0
  83. package/dist/tracking/react/hooks.js.map +1 -0
  84. package/dist/tracking/react/index.d.ts +7 -0
  85. package/dist/tracking/react/index.d.ts.map +1 -0
  86. package/dist/tracking/react/index.js +17 -0
  87. package/dist/tracking/react/index.js.map +1 -0
  88. package/dist/tracking/testing.d.ts +40 -0
  89. package/dist/tracking/testing.d.ts.map +1 -0
  90. package/dist/tracking/testing.js +140 -0
  91. package/dist/tracking/testing.js.map +1 -0
  92. package/dist/tracking/ui/ExperimentCard.d.ts +47 -0
  93. package/dist/tracking/ui/ExperimentCard.d.ts.map +1 -0
  94. package/dist/tracking/ui/ExperimentCard.js +305 -0
  95. package/dist/tracking/ui/ExperimentCard.js.map +1 -0
  96. package/dist/tracking/ui/ExperimentsOverlay.d.ts +53 -0
  97. package/dist/tracking/ui/ExperimentsOverlay.d.ts.map +1 -0
  98. package/dist/tracking/ui/ExperimentsOverlay.js +359 -0
  99. package/dist/tracking/ui/ExperimentsOverlay.js.map +1 -0
  100. package/dist/tracking/ui/anchor.d.ts +107 -0
  101. package/dist/tracking/ui/anchor.d.ts.map +1 -0
  102. package/dist/tracking/ui/anchor.js +108 -0
  103. package/dist/tracking/ui/anchor.js.map +1 -0
  104. package/dist/tracking/ui/card.d.ts +87 -0
  105. package/dist/tracking/ui/card.d.ts.map +1 -0
  106. package/dist/tracking/ui/card.js +287 -0
  107. package/dist/tracking/ui/card.js.map +1 -0
  108. package/dist/tracking/ui/client.d.ts +42 -0
  109. package/dist/tracking/ui/client.d.ts.map +1 -0
  110. package/dist/tracking/ui/client.js +123 -0
  111. package/dist/tracking/ui/client.js.map +1 -0
  112. package/dist/tracking/ui/index.d.ts +20 -0
  113. package/dist/tracking/ui/index.d.ts.map +1 -0
  114. package/dist/tracking/ui/index.js +54 -0
  115. package/dist/tracking/ui/index.js.map +1 -0
  116. package/dist/tracking/ui/types.d.ts +111 -0
  117. package/dist/tracking/ui/types.d.ts.map +1 -0
  118. package/dist/tracking/ui/types.js +8 -0
  119. package/dist/tracking/ui/types.js.map +1 -0
  120. package/dist/tracking/ui/useExperimentsAdmin.d.ts +31 -0
  121. package/dist/tracking/ui/useExperimentsAdmin.d.ts.map +1 -0
  122. package/dist/tracking/ui/useExperimentsAdmin.js +136 -0
  123. package/dist/tracking/ui/useExperimentsAdmin.js.map +1 -0
  124. package/package.json +1 -1
  125. package/src/index.tsx +5 -0
  126. package/src/stories/tracking.tsx +197 -0
  127. package/src/tracking/browser/attach.ts +186 -0
  128. package/src/tracking/browser/env.ts +78 -0
  129. package/src/tracking/core/consent.ts +37 -0
  130. package/src/tracking/core/engagement.ts +47 -0
  131. package/src/tracking/core/experiments.ts +258 -0
  132. package/src/tracking/core/hash.ts +26 -0
  133. package/src/tracking/core/ids.ts +25 -0
  134. package/src/tracking/core/observable.ts +23 -0
  135. package/src/tracking/core/queue.ts +131 -0
  136. package/src/tracking/core/sections.ts +166 -0
  137. package/src/tracking/core/storage.ts +69 -0
  138. package/src/tracking/core/tracker.ts +417 -0
  139. package/src/tracking/core/types.ts +162 -0
  140. package/src/tracking/core/utm.ts +23 -0
  141. package/src/tracking/index.ts +72 -0
  142. package/src/tracking/markup.ts +17 -0
  143. package/src/tracking/react/Experiment.stories.tsx +174 -0
  144. package/src/tracking/react/Experiment.tsx +44 -0
  145. package/src/tracking/react/TrackingProvider.tsx +56 -0
  146. package/src/tracking/react/hooks.ts +106 -0
  147. package/src/tracking/react/index.ts +13 -0
  148. package/src/tracking/testing.ts +108 -0
  149. package/src/tracking/ui/ExperimentCard.stories.tsx +236 -0
  150. package/src/tracking/ui/ExperimentCard.tsx +491 -0
  151. package/src/tracking/ui/ExperimentsOverlay.stories.tsx +148 -0
  152. package/src/tracking/ui/ExperimentsOverlay.tsx +423 -0
  153. package/src/tracking/ui/anchor.ts +180 -0
  154. package/src/tracking/ui/card.ts +323 -0
  155. package/src/tracking/ui/client.ts +117 -0
  156. package/src/tracking/ui/index.ts +71 -0
  157. package/src/tracking/ui/types.ts +104 -0
  158. package/src/tracking/ui/useExperimentsAdmin.ts +103 -0
@@ -0,0 +1,417 @@
1
+ import { ConsentStore } from './consent';
2
+ import { EngagementClock } from './engagement';
3
+ import { assign, ExperimentStore, type IAssignContext, type IAssignment } from './experiments';
4
+ import { eventId, randomId } from './ids';
5
+ import { Observable } from './observable';
6
+ import { EventQueue, type ITransport } from './queue';
7
+ import { SectionClock } from './sections';
8
+ import { readJson, writeJson, type IStorage } from './storage';
9
+ import {
10
+ resolveConfig,
11
+ storageKeys,
12
+ type IBatch,
13
+ type ITrackingConfig,
14
+ type IUtm,
15
+ type TEventType,
16
+ type TProps,
17
+ type TStorageKeys,
18
+ type TTrackingOptions,
19
+ } from './types';
20
+ import { parseUtm, utmParams } from './utm';
21
+
22
+ /** What the page looks like right now (the browser layer reads it from `window`). */
23
+ export interface IPageInfo {
24
+ /** `https://example.com` */
25
+ origin: string;
26
+ path: string;
27
+ search: string;
28
+ title: string;
29
+ referrer: string;
30
+ lang: string;
31
+ viewport: [number, number];
32
+ device?: IAssignContext['device'];
33
+ }
34
+
35
+ /** Everything the tracker needs from its host; tests pass fakes. */
36
+ export interface ITrackerEnv {
37
+ local: IStorage;
38
+ session: IStorage;
39
+ transport: ITransport;
40
+ now: () => number;
41
+ setTimer: (fn: () => void, ms: number) => unknown;
42
+ clearTimer: (handle: unknown) => void;
43
+ page: () => IPageInfo;
44
+ fetchJson: (url: string, timeoutMs: number) => Promise<unknown>;
45
+ log?: (...args: unknown[]) => void;
46
+ }
47
+
48
+ interface IPageView {
49
+ id: string;
50
+ path: string;
51
+ start: number;
52
+ maxScrollPct: number;
53
+ summarySeq: number;
54
+ exposed: Set<string>;
55
+ }
56
+
57
+ interface IExposureWatch {
58
+ assignment: IAssignment;
59
+ }
60
+
61
+ /**
62
+ * The tracker: identity, consent, the event queue, page views and their summaries,
63
+ * experiment assignment and exposure. It has no DOM code of its own (see
64
+ * `browser/attach.ts`), so it runs unchanged in tests and in any web property.
65
+ * Everything product-specific (property, endpoints, storage prefix) is in `config`.
66
+ *
67
+ * Never throws into the page: every public method is wrapped.
68
+ */
69
+ export class Tracker {
70
+ readonly consent: ConsentStore;
71
+ readonly experiments: ExperimentStore;
72
+ readonly sections: SectionClock;
73
+ private readonly engagement: EngagementClock;
74
+ private readonly queue: EventQueue;
75
+ private pv: IPageView | null = null;
76
+ private lastUrl: string | null = null;
77
+ private readonly firstTouchUtm: IUtm | null;
78
+ private watches = new Set<IExposureWatch>();
79
+ private started = false;
80
+ /** The current page view id (null without consent): the browser layer re-measures sections on change. */
81
+ readonly pageViewId = new Observable<string | null>(null);
82
+ /** The storage keys under `config.storagePrefix`. */
83
+ readonly keys: TStorageKeys;
84
+ readonly config: ITrackingConfig;
85
+
86
+ constructor(
87
+ options: TTrackingOptions,
88
+ private readonly env: ITrackerEnv,
89
+ ) {
90
+ // A config built by hand (not through `resolveConfig`) still gets the defaults.
91
+ const config = resolveConfig(options);
92
+ this.config = config;
93
+ this.keys = storageKeys(config.storagePrefix);
94
+ this.consent = new ConsentStore(env.local, config.consentVersion, this.keys);
95
+ const first = env.page();
96
+ this.firstTouchUtm = parseUtm(first.search);
97
+ this.experiments = new ExperimentStore({
98
+ property: config.property,
99
+ endpoint: config.experimentsEndpoint,
100
+ local: env.local,
101
+ session: env.session,
102
+ now: env.now,
103
+ fetchJson: env.fetchJson,
104
+ keys: this.keys,
105
+ previewParam: config.previewParam,
106
+ });
107
+ this.experiments.applyPreviewFrom(first.search);
108
+ this.sections = new SectionClock(env.now());
109
+ this.engagement = new EngagementClock(config.engagedWindowMs);
110
+ this.queue = new EventQueue({
111
+ flushIntervalMs: config.flushIntervalMs,
112
+ maxQueued: config.maxQueued,
113
+ transport: env.transport,
114
+ envelope: () => this.envelope(),
115
+ now: env.now,
116
+ setTimer: env.setTimer,
117
+ clearTimer: env.clearTimer,
118
+ debug: config.debug ? (b) => env.log?.('[tracking] batch', b) : undefined,
119
+ });
120
+ this.sections.onSeen((id) => this.safe(() => this.onSectionSeen(id)));
121
+ this.consent.state.subscribe(() => this.safe(() => this.onConsentChange()));
122
+ }
123
+
124
+ /** Runs `fn` and swallows any error: analytics never breaks the page. */
125
+ private safe<T>(fn: () => T): T | undefined {
126
+ try {
127
+ return fn();
128
+ } catch (err) {
129
+ if (this.config.debug) this.env.log?.('[tracking] error', err);
130
+ return undefined;
131
+ }
132
+ }
133
+
134
+ private active = () => this.config.enabled && this.consent.granted();
135
+
136
+ /** The tracker's clock (the browser layer times sections with it). */
137
+ now = (): number => this.env.now();
138
+
139
+ // ── identity ────────────────────────────────────────────────────────────────
140
+
141
+ /** The visitor id: exists only with consent. */
142
+ vid(): string | null {
143
+ if (!this.active()) return null;
144
+ let vid = this.env.local.get(this.keys.vid);
145
+ if (!vid) {
146
+ vid = randomId(16);
147
+ this.env.local.set(this.keys.vid, vid);
148
+ }
149
+ return vid;
150
+ }
151
+
152
+ /** The session id: a new one after `sessionTimeoutMs` without an event. */
153
+ private sid(touch: boolean): string {
154
+ const now = this.env.now();
155
+ const s = readJson<{ id: string; last: number }>(this.env.session, this.keys.sid);
156
+ const id = s && now - s.last < this.config.sessionTimeoutMs ? s.id : randomId(12);
157
+ if (touch || !s || s.id !== id) writeJson(this.env.session, this.keys.sid, { id, last: now });
158
+ return id;
159
+ }
160
+
161
+ private envelope(): Omit<IBatch, 'events' | 'sent_at'> | null {
162
+ const vid = this.vid();
163
+ if (!vid) return null;
164
+ return { v: 1, property: this.config.property, vid, sid: this.sid(false), consent: 'granted' };
165
+ }
166
+
167
+ // ── consent ─────────────────────────────────────────────────────────────────
168
+
169
+ grant() {
170
+ this.safe(() => this.consent.answer('granted'));
171
+ }
172
+
173
+ /** Declines or withdraws: the visitor id and everything tied to it are deleted, nothing more is sent. */
174
+ deny() {
175
+ this.safe(() => this.consent.answer('denied'));
176
+ }
177
+
178
+ private onConsentChange() {
179
+ if (this.consent.granted()) {
180
+ if (!this.config.enabled) return;
181
+ this.vid();
182
+ if (this.firstTouchUtm && !this.env.session.get(this.keys.utm)) writeJson(this.env.session, this.keys.utm, this.firstTouchUtm);
183
+ this.beginPageView();
184
+ void this.experiments.load();
185
+ return;
186
+ }
187
+ this.queue.clear();
188
+ [this.keys.vid, this.keys.exposed].forEach((k) => this.env.local.remove(k));
189
+ [this.keys.sid, this.keys.utm].forEach((k) => this.env.session.remove(k));
190
+ this.pv = null;
191
+ this.pageViewId.set(null);
192
+ }
193
+
194
+ // ── lifecycle ───────────────────────────────────────────────────────────────
195
+
196
+ /** Call once when the page has loaded: starts the first page view if consent was given earlier. */
197
+ start() {
198
+ this.safe(() => {
199
+ // Idempotent: React StrictMode mounts twice in development.
200
+ if (this.started) return;
201
+ this.started = true;
202
+ void this.experiments.load();
203
+ if (!this.active()) return;
204
+ this.vid();
205
+ this.beginPageView();
206
+ });
207
+ }
208
+
209
+ /** A route change in a single-page app: closes the current page view and starts a new one. */
210
+ pageview() {
211
+ this.safe(() => {
212
+ const page = this.env.page();
213
+ if (this.pv && this.lastUrl === page.path + page.search) return;
214
+ this.experiments.applyPreviewFrom(page.search);
215
+ if (!this.active()) return;
216
+ if (this.pv) this.summary(true);
217
+ this.beginPageView();
218
+ });
219
+ }
220
+
221
+ private beginPageView() {
222
+ const page = this.env.page();
223
+ const now = this.env.now();
224
+ const previous = this.lastUrl;
225
+ this.pv = { id: eventId(), path: page.path, start: now, maxScrollPct: 0, summarySeq: 0, exposed: new Set() };
226
+ this.lastUrl = page.path + page.search;
227
+ this.sections.reset(now);
228
+ this.engagement.reset();
229
+ this.pageViewId.set(this.pv.id);
230
+ const firstOfSession = !this.env.session.get(this.keys.sid);
231
+ const utm = parseUtm(page.search) ?? (firstOfSession ? this.firstTouchUtm : null);
232
+ this.record('pageview', {
233
+ // The first page view carries the document referrer; later SPA views the previous page.
234
+ referrer: previous ? `${page.origin}${previous}` : page.referrer || null,
235
+ title: page.title,
236
+ ...(utm ? { utm } : {}),
237
+ viewport: page.viewport,
238
+ lang: page.lang,
239
+ });
240
+ // Watches whose trigger is the render itself fire once per page view.
241
+ this.watches.forEach((w) => w.assignment.trigger == null && this.expose(w.assignment, 'render'));
242
+ this.watches.forEach((w) => w.assignment.trigger != null && this.sections.register(w.assignment.trigger, false));
243
+ }
244
+
245
+ /**
246
+ * A cumulative summary of the page view. Sent when the tab is hidden (`final:
247
+ * false`, the visitor may come back) and when the page is left (`final: true`);
248
+ * the one with the highest `seq` for a `pv_id` is the complete one.
249
+ */
250
+ summary(final: boolean) {
251
+ this.safe(() => {
252
+ if (!this.pv || !this.active()) return;
253
+ const now = this.env.now();
254
+ this.pv.summarySeq += 1;
255
+ this.record('page_summary', {
256
+ duration_ms: Math.max(0, Math.round(now - this.pv.start)),
257
+ engaged_ms: this.engagement.total(now),
258
+ max_scroll_pct: this.pv.maxScrollPct,
259
+ exit_section: this.sections.current(),
260
+ sections: this.sections.summary(now),
261
+ seq: this.pv.summarySeq,
262
+ final,
263
+ });
264
+ });
265
+ }
266
+
267
+ // ── signals from the browser layer ─────────────────────────────────────────
268
+
269
+ activity() {
270
+ this.safe(() => this.engagement.activity(this.env.now()));
271
+ }
272
+
273
+ scrolled(pct: number) {
274
+ this.safe(() => {
275
+ if (this.pv) this.pv.maxScrollPct = Math.max(this.pv.maxScrollPct, Math.min(100, Math.round(pct)));
276
+ });
277
+ }
278
+
279
+ setTabVisible(visible: boolean) {
280
+ this.safe(() => {
281
+ const now = this.env.now();
282
+ this.sections.setTabVisible(visible, now);
283
+ this.engagement.setTabVisible(visible, now);
284
+ if (!visible) {
285
+ this.summary(false);
286
+ void this.flush('beacon');
287
+ }
288
+ });
289
+ }
290
+
291
+ /** The page is going away (`pagehide`). */
292
+ leave() {
293
+ this.safe(() => {
294
+ this.summary(true);
295
+ void this.flush('beacon');
296
+ });
297
+ }
298
+
299
+ flush(mode: 'fetch' | 'beacon' = 'fetch') {
300
+ return this.safe(() => this.queue.flush(mode)) ?? Promise.resolve();
301
+ }
302
+
303
+ // ── events ──────────────────────────────────────────────────────────────────
304
+
305
+ /** Queues an event of any type (nothing happens without consent). */
306
+ record(type: TEventType, props?: TProps) {
307
+ this.safe(() => {
308
+ if (!this.active() || !this.pv) return;
309
+ this.sid(true);
310
+ this.queue.push({
311
+ id: eventId(),
312
+ type,
313
+ ts: new Date(this.env.now()).toISOString(),
314
+ pv_id: this.pv.id,
315
+ path: this.pv.path,
316
+ ...(props && Object.keys(props).length ? { props } : {}),
317
+ });
318
+ });
319
+ }
320
+
321
+ heartbeat() {
322
+ this.record('heartbeat');
323
+ }
324
+
325
+ click(props: { target: string; placement?: string | null; label?: string | null; href?: string | null }) {
326
+ this.record('click', props);
327
+ }
328
+
329
+ /** A conversion the server's goals can match (`signup-started`, …). */
330
+ goal(name: string, value?: number) {
331
+ this.record('goal', value == null ? { goal: name } : { goal: name, value });
332
+ }
333
+
334
+ /** A named event with free-form props (`form-submitted`, `plan-picked`, …). */
335
+ custom(name: string, props: TProps = {}) {
336
+ this.record('custom', { ...props, name });
337
+ }
338
+
339
+ // ── experiments ─────────────────────────────────────────────────────────────
340
+
341
+ /**
342
+ * The variant for this visitor. Preview override first, then the running
343
+ * definition; the control whenever consent, the definitions or targeting say no.
344
+ */
345
+ decide(key: string, fallbackControl = 'a'): IAssignment {
346
+ return (
347
+ this.safe(() => {
348
+ const def = this.experiments.get(key);
349
+ const trigger = def?.trigger?.section ?? null;
350
+ // An ended test shows its winner to everybody (consent or not, previews or not).
351
+ if (def?.status === 'concluded') return assign(def, null, { path: this.env.page().path });
352
+ const preview = this.experiments.previewOf(key);
353
+ if (preview) return { key, variant: preview, enrolled: false, reason: 'preview', trigger } as IAssignment;
354
+ if (!this.active()) return { key, variant: fallbackControl, enrolled: false, reason: 'no-consent', trigger } as IAssignment;
355
+ if (!def) return { key, variant: fallbackControl, enrolled: false, reason: 'not-running', trigger: null } as IAssignment;
356
+ const page = this.env.page();
357
+ return assign(def, this.vid(), { path: page.path, device: page.device, lang: page.lang });
358
+ }) ?? { key, variant: fallbackControl, enrolled: false, reason: 'not-running', trigger: null }
359
+ );
360
+ }
361
+
362
+ /**
363
+ * Logs the exposure once per page view when the trigger section is seen (or at
364
+ * once for `trigger: null`). Returns an unsubscribe for when the variant unmounts.
365
+ */
366
+ watchExposure(assignment: IAssignment): () => void {
367
+ if (!assignment.enrolled) return () => undefined;
368
+ const watch: IExposureWatch = { assignment };
369
+ this.watches.add(watch);
370
+ this.safe(() => {
371
+ if (assignment.trigger == null) this.expose(assignment, 'render');
372
+ else {
373
+ this.sections.register(assignment.trigger, false);
374
+ if (this.sections.isSeen(assignment.trigger)) this.expose(assignment, 'view');
375
+ }
376
+ });
377
+ return () => void this.watches.delete(watch);
378
+ }
379
+
380
+ private onSectionSeen(id: string) {
381
+ this.watches.forEach((w) => w.assignment.trigger === id && this.expose(w.assignment, 'view'));
382
+ }
383
+
384
+ private expose(a: IAssignment, trigger: 'view' | 'render') {
385
+ if (!this.pv || !this.active() || this.pv.exposed.has(a.key)) return;
386
+ this.pv.exposed.add(a.key);
387
+ const exposed = readJson<Record<string, string>>(this.env.local, this.keys.exposed) ?? {};
388
+ if (exposed[a.key] !== a.variant) writeJson(this.env.local, this.keys.exposed, { ...exposed, [a.key]: a.variant });
389
+ this.record('exposure', { experiment: a.key, variant: a.variant, trigger });
390
+ }
391
+
392
+ // ── sign-up attribution ─────────────────────────────────────────────────────
393
+
394
+ /**
395
+ * Adds `qa_exp=key:variant,…` (experiments this visitor was exposed to; the server's
396
+ * sign-up flow reads this parameter, §5.4 of the contract) and the
397
+ * session's first-touch `utm_*` to a sign-up URL — nothing else, never the vid.
398
+ * Without consent the URL is returned unchanged.
399
+ */
400
+ decorateSignupUrl(url: string): string {
401
+ return (
402
+ this.safe(() => {
403
+ if (!this.active()) return url;
404
+ const u = new URL(url);
405
+ const exposed = readJson<Record<string, string>>(this.env.local, this.keys.exposed) ?? {};
406
+ const pairs = Object.entries(exposed)
407
+ .filter(([k, v]) => k && v)
408
+ .sort(([a], [b]) => a.localeCompare(b))
409
+ .map(([k, v]) => `${k}:${v}`);
410
+ if (pairs.length) u.searchParams.set('qa_exp', pairs.join(','));
411
+ const utm = readJson<IUtm>(this.env.session, this.keys.utm) ?? this.firstTouchUtm;
412
+ utmParams(utm).forEach(([k, v]) => u.searchParams.set(k, v));
413
+ return u.toString();
414
+ }) ?? url
415
+ );
416
+ }
417
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Wire types of the first-party tracker. The contract (event shapes, batch envelope,
3
+ * experiment definitions) is owned by qorus-api `design/analytics-and-experiments-design.md`
4
+ * (§4 collector, §5 experiments); change it there first, then here.
5
+ */
6
+
7
+ export type TConsentState = 'unknown' | 'granted' | 'denied';
8
+
9
+ /** Event types the collector knows. New ones are allowed without a schema change (§4). */
10
+ export type TEventType =
11
+ | 'pageview'
12
+ | 'page_summary'
13
+ | 'click'
14
+ | 'heartbeat'
15
+ | 'exposure'
16
+ | 'goal'
17
+ | 'custom'
18
+ | (string & Record<never, never>);
19
+
20
+ export type TProps = Record<string, unknown>;
21
+
22
+ export interface ITrackedEvent {
23
+ /** Random id: makes the write idempotent (retries, beacon + fetch fallback). */
24
+ id: string;
25
+ type: TEventType;
26
+ /** ISO timestamp of when it happened in the browser. */
27
+ ts: string;
28
+ pv_id: string;
29
+ path: string;
30
+ props?: TProps;
31
+ }
32
+
33
+ export interface IBatch {
34
+ v: 1;
35
+ property: string;
36
+ vid: string;
37
+ sid: string;
38
+ sent_at: string;
39
+ consent: 'granted';
40
+ events: ITrackedEvent[];
41
+ }
42
+
43
+ export interface IUtm {
44
+ source?: string;
45
+ medium?: string;
46
+ campaign?: string;
47
+ term?: string;
48
+ content?: string;
49
+ }
50
+
51
+ /** Public fields of a running experiment (the experiments endpoint, `?property=…`). */
52
+ export interface IExperimentVariant {
53
+ key: string;
54
+ weight: number;
55
+ control?: boolean;
56
+ }
57
+
58
+ export interface IExperimentDefinition {
59
+ key: string;
60
+ /**
61
+ * `running` (assign and log), or `concluded`: everybody sees `winner`, nothing is logged. A
62
+ * concluded entry carries only `key`, `status` and `winner`; its `variants` are normalised to [].
63
+ */
64
+ status?: 'running' | 'concluded' | (string & Record<never, never>);
65
+ winner?: string | null;
66
+ /** Counter of the running experiment's phase (a removed version starts a new one). */
67
+ phase?: number;
68
+ variants: IExperimentVariant[];
69
+ /** Share of visitors enrolled, 0..1 (the rest see the control, no exposure). */
70
+ traffic: number;
71
+ targeting?: { paths?: string[] | null; device?: string | null; lang?: string | null } | null;
72
+ /** The element whose being seen counts as exposure; none → exposure on render. */
73
+ trigger?: { section?: string | null } | null;
74
+ }
75
+
76
+ /** Everything the tracker needs from its host. Every product-specific value lives here. */
77
+ export interface ITrackingConfig {
78
+ /**
79
+ * Which product the events belong to (`landing`, `ide`, `admin`, …). The server keeps each
80
+ * property's events, goals and experiments apart, and the experiments list is fetched for it.
81
+ */
82
+ property: string;
83
+ /** Collector URL (`POST`, the batch envelope of §4 of the contract). */
84
+ endpoint: string;
85
+ /** Running-experiments URL (`GET`); `?property=` is appended. */
86
+ experimentsEndpoint: string;
87
+ /** Master switch: false → nothing is ever sent, experiments serve the control. */
88
+ enabled: boolean;
89
+ /** Bump when the consent text changes materially: stored answers of older versions are asked again. */
90
+ consentVersion: number;
91
+ /**
92
+ * Prefix of every localStorage / sessionStorage key the tracker writes (default `qa.`, the
93
+ * contract's). Two products on one origin need different prefixes, or they share one consent
94
+ * answer, one visitor id and one experiments cache.
95
+ */
96
+ storagePrefix: string;
97
+ /** Query parameter of a shareable variant preview (`?qa_variant=key:variant`). */
98
+ previewParam: string;
99
+ /** Log every batch to the console instead of silently sending. */
100
+ debug: boolean;
101
+ flushIntervalMs: number;
102
+ /** Flush as soon as this many events are queued. */
103
+ maxQueued: number;
104
+ heartbeatMs: number;
105
+ sessionTimeoutMs: number;
106
+ /** An interaction within this window counts the time as engaged. */
107
+ engagedWindowMs: number;
108
+ }
109
+
110
+ /** The config fields every product must set: nothing product-specific has a default. */
111
+ export type TRequiredTrackingConfig = 'property' | 'endpoint' | 'experimentsEndpoint';
112
+
113
+ export const DEFAULT_STORAGE_PREFIX = 'qa.';
114
+
115
+ export const DEFAULT_CONFIG: Omit<ITrackingConfig, TRequiredTrackingConfig> = {
116
+ enabled: true,
117
+ consentVersion: 1,
118
+ storagePrefix: DEFAULT_STORAGE_PREFIX,
119
+ previewParam: 'qa_variant',
120
+ debug: false,
121
+ flushIntervalMs: 5000,
122
+ maxQueued: 20,
123
+ heartbeatMs: 15000,
124
+ sessionTimeoutMs: 30 * 60 * 1000,
125
+ engagedWindowMs: 10000,
126
+ };
127
+
128
+ /** What a product passes: the required fields, and any default it wants to change. */
129
+ export type TTrackingOptions = Partial<ITrackingConfig> & Pick<ITrackingConfig, TRequiredTrackingConfig>;
130
+
131
+ /** The full config: `options` over `DEFAULT_CONFIG` (an `undefined` option keeps the default). */
132
+ export const resolveConfig = (options: TTrackingOptions): ITrackingConfig => {
133
+ const set = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== undefined));
134
+ return { ...DEFAULT_CONFIG, ...set } as ITrackingConfig;
135
+ };
136
+
137
+ /** The storage keys for one prefix (first-party, removable in one sweep). */
138
+ export const storageKeys = (prefix: string = DEFAULT_STORAGE_PREFIX) => ({
139
+ /** localStorage: `granted` | `denied` */
140
+ consent: `${prefix}consent`,
141
+ /** localStorage: the consent version that was answered */
142
+ consentVersion: `${prefix}consent.v`,
143
+ /** localStorage: the visitor id (exists only with consent) */
144
+ vid: `${prefix}vid`,
145
+ /** sessionStorage: `{ id, last }` */
146
+ sid: `${prefix}sid`,
147
+ /** sessionStorage: first-touch utm of this session */
148
+ utm: `${prefix}utm`,
149
+ /** localStorage: `{ experimentKey: variant }` the visitor was exposed to (sign-up attribution) */
150
+ exposed: `${prefix}exp`,
151
+ /** sessionStorage: preview overrides from the preview query parameter */
152
+ preview: `${prefix}preview`,
153
+ /** localStorage: last fetched public experiment definitions */
154
+ experimentsCache: `${prefix}experiments`,
155
+ /** localStorage: an in-app version switch per experiment (`{ key: variant }`), never logged */
156
+ editorVariants: `${prefix}editor.variants`,
157
+ });
158
+
159
+ export type TStorageKeys = ReturnType<typeof storageKeys>;
160
+
161
+ /** The keys with the default prefix (`qa.consent`, `qa.vid`, …). */
162
+ export const KEYS: TStorageKeys = storageKeys(DEFAULT_STORAGE_PREFIX);
@@ -0,0 +1,23 @@
1
+ import type { IUtm } from './types';
2
+
3
+ const UTM_FIELDS = ['source', 'medium', 'campaign', 'term', 'content'] as const;
4
+
5
+ /** The `utm_*` parameters of a query string, or null when there are none. */
6
+ export const parseUtm = (search: string): IUtm | null => {
7
+ let params: URLSearchParams;
8
+ try {
9
+ params = new URLSearchParams(search);
10
+ } catch {
11
+ return null;
12
+ }
13
+ const utm: IUtm = {};
14
+ for (const f of UTM_FIELDS) {
15
+ const v = params.get(`utm_${f}`)?.trim();
16
+ if (v) utm[f] = v.slice(0, 200);
17
+ }
18
+ return Object.keys(utm).length ? utm : null;
19
+ };
20
+
21
+ /** `{ source: 'x' }` → `[['utm_source', 'x']]`, in a stable order. */
22
+ export const utmParams = (utm: IUtm | null | undefined): [string, string][] =>
23
+ utm ? UTM_FIELDS.filter((f) => utm[f]).map((f) => [`utm_${f}`, utm[f] as string]) : [];
@@ -0,0 +1,72 @@
1
+ /**
2
+ * First-party tracking, consent and A/B testing for any Qore web app.
3
+ *
4
+ * How to use it: design/TRACKING.md in this repo.
5
+ * The contract (events, experiments, storage): qorus-api design/analytics-and-experiments-design.md.
6
+ *
7
+ * Layers (each only imports the ones above it):
8
+ * core/ plain TypeScript, no DOM: ids, consent, queue, sections, hashing, assignment, Tracker
9
+ * browser/ wiring to window/document: transport, IntersectionObserver, listeners
10
+ * react/ <TrackingProvider>, useConsent, useExperiment, <Experiment>
11
+ * Nothing product-specific lives here: the property, endpoints, consent version and storage
12
+ * prefix come from the config each app passes to `createBrowserTracker`.
13
+ */
14
+ import { attachToPage, type IAttached } from './browser/attach';
15
+ import { browserEnv } from './browser/env';
16
+ import { Tracker } from './core/tracker';
17
+ import { resolveConfig, type TTrackingOptions } from './core/types';
18
+
19
+ export { Tracker } from './core/tracker';
20
+ export type { IPageInfo, ITrackerEnv } from './core/tracker';
21
+ export { ConsentStore } from './core/consent';
22
+ export {
23
+ assign,
24
+ bucketRanges,
25
+ controlOf,
26
+ DEFAULT_PREVIEW_PARAM,
27
+ ExperimentStore,
28
+ normaliseDefinition,
29
+ parsePreview,
30
+ pathMatches,
31
+ } from './core/experiments';
32
+ export type { IAssignContext, IAssignment, TAssignmentReason, TExperimentsStatus } from './core/experiments';
33
+ export { fnv1a32, hashV2 } from './core/hash';
34
+ export { Observable } from './core/observable';
35
+ export { EventQueue } from './core/queue';
36
+ export type { ITransport } from './core/queue';
37
+ export { effectiveRatio, SectionClock } from './core/sections';
38
+ export type { ISectionSummary } from './core/sections';
39
+ export { memoryStorage, readJson, safeStorage, writeJson } from './core/storage';
40
+ export type { IStorage } from './core/storage';
41
+ export { parseUtm, utmParams } from './core/utm';
42
+ export { DEFAULT_CONFIG, DEFAULT_STORAGE_PREFIX, KEYS, resolveConfig, storageKeys } from './core/types';
43
+ export type {
44
+ IBatch,
45
+ IExperimentDefinition,
46
+ IExperimentVariant,
47
+ ITrackedEvent,
48
+ ITrackingConfig,
49
+ IUtm,
50
+ TConsentState,
51
+ TEventType,
52
+ TProps,
53
+ TRequiredTrackingConfig,
54
+ TStorageKeys,
55
+ TTrackingOptions,
56
+ } from './core/types';
57
+ export { attachToPage } from './browser/attach';
58
+ export type { IAttached } from './browser/attach';
59
+ export { browserEnv, browserTransport, deviceOf } from './browser/env';
60
+
61
+ /** A tracker for a real browser page. Call `attach()` once the page is up (`<TrackingProvider>` does). */
62
+ export const createBrowserTracker = (options: TTrackingOptions): { tracker: Tracker; attach: () => IAttached } => {
63
+ const config = resolveConfig(options);
64
+ const tracker = new Tracker(config, browserEnv(config.endpoint));
65
+ return { tracker, attach: () => attachToPage(tracker, config.heartbeatMs) };
66
+ };
67
+
68
+ export { trackClick, trackSection } from './markup';
69
+ export type { TTrackAttributes } from './markup';
70
+ export * from './react';
71
+ export { createMemoryTracker } from './testing';
72
+ export type { IMemoryTracker, IMemoryTrackerOptions } from './testing';
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The markup contract as props, for places where JSX `data-*` attributes cannot be
3
+ * written directly (a Reqore panel action or a tier's `actionButtonProps` are
4
+ * object literals). In JSX, `data-track-click="…"` works just as well.
5
+ *
6
+ * <ReqoreButton {...trackClick('get-started', 'cta')} … />
7
+ * bottomActions={[{ ...primaryCta, ...trackClick('contact', 'pricing-panel'), label: … }]}
8
+ */
9
+ export type TTrackAttributes = Record<`data-track-${string}`, string>;
10
+
11
+ export const trackClick = (target: string, placement?: string, label?: string): TTrackAttributes => ({
12
+ 'data-track-click': target,
13
+ ...(placement ? { 'data-track-placement': placement } : {}),
14
+ ...(label ? { 'data-track-label': label } : {}),
15
+ });
16
+
17
+ export const trackSection = (id: string): TTrackAttributes => ({ 'data-track-section': id });