@baukit/analytics-core 0.7.2 → 0.7.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baukit/analytics-core",
3
- "version": "0.7.2",
3
+ "version": "0.7.3",
4
4
  "description": "Provider-neutral, privacy-first product analytics port and safety policy.",
5
5
  "license": "MIT",
6
6
  "author": "Patrick Koss",
@@ -30,6 +30,7 @@
30
30
  },
31
31
  "files": [
32
32
  "dist",
33
+ "src",
33
34
  "README.md",
34
35
  "LICENSE"
35
36
  ],
@@ -0,0 +1,324 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ import { AnalyticsClient, followsEventNameConvention } from './client.js';
4
+ import { analyticsStorageKeys, InMemoryAnalyticsStorage } from './storage.js';
5
+ import { InMemoryTransport, NoopTransport } from './transports.js';
6
+ import type {
7
+ AnalyticsClientOptions,
8
+ AnalyticsContext,
9
+ EventAllowlist,
10
+ Transport,
11
+ } from './types.js';
12
+
13
+ type ProductEvent =
14
+ | {
15
+ name: 'onboarding_started';
16
+ properties: { source: 'organic' | 'invite'; contact?: string; api_token?: string };
17
+ }
18
+ | { name: 'onboarding_completed'; properties: { duration_seconds: number } }
19
+ | { name: 'step_viewed'; properties: { step: number } };
20
+
21
+ const ANONYMOUS_ID_1 = '00000000-0000-4000-8000-000000000001';
22
+ const ANONYMOUS_ID_2 = '00000000-0000-4000-8000-000000000002';
23
+ const USER_ID = '10000000-0000-4000-8000-000000000001';
24
+
25
+ const context: AnalyticsContext = {
26
+ schema_version: 2,
27
+ app: 'example-app',
28
+ app_version: '1.4.0',
29
+ platform: 'web',
30
+ environment: 'test',
31
+ locale: 'en-GB',
32
+ };
33
+
34
+ const allowlist = {
35
+ onboarding_started: ['source', 'contact', 'api_token'],
36
+ onboarding_completed: ['duration_seconds'],
37
+ step_viewed: ['step'],
38
+ } as const satisfies EventAllowlist<ProductEvent>;
39
+
40
+ function createClient(
41
+ overrides: Partial<AnalyticsClientOptions<ProductEvent>> = {},
42
+ ): AnalyticsClient<ProductEvent> {
43
+ return new AnalyticsClient<ProductEvent>({
44
+ context,
45
+ allowlist,
46
+ uuidFactory: () => ANONYMOUS_ID_1,
47
+ development: false,
48
+ flushBatchSize: 100,
49
+ flushIntervalMs: 60_000,
50
+ ...overrides,
51
+ });
52
+ }
53
+
54
+ afterEach(() => {
55
+ vi.useRealTimers();
56
+ });
57
+
58
+ describe('AnalyticsClient consent', () => {
59
+ it('defaults to unknown and drops rather than buffers without consent', async () => {
60
+ const transport = new InMemoryTransport<ProductEvent>();
61
+ const client = createClient({ transport });
62
+
63
+ client.capture({ name: 'onboarding_started', properties: { source: 'organic' } });
64
+ expect(client.consent).toBe('unknown');
65
+ expect(client.pendingCount).toBe(0);
66
+
67
+ client.setConsent('granted');
68
+ client.capture({ name: 'onboarding_started', properties: { source: 'invite' } });
69
+ expect(client.pendingCount).toBe(1);
70
+ client.setConsent('denied');
71
+ expect(client.pendingCount).toBe(0);
72
+
73
+ client.setConsent('granted');
74
+ client.capture({ name: 'onboarding_completed', properties: { duration_seconds: 12 } });
75
+ await client.flush();
76
+
77
+ expect(transport.envelopes).toHaveLength(1);
78
+ expect(transport.envelopes[0]).toMatchObject({
79
+ type: 'capture',
80
+ event: { name: 'onboarding_completed' },
81
+ });
82
+ });
83
+
84
+ it('persists and re-evaluates consent and anonymous identity on construction', () => {
85
+ const storage = new InMemoryAnalyticsStorage();
86
+ const first = createClient({ storage });
87
+ first.setConsent('granted');
88
+
89
+ const second = createClient({
90
+ storage,
91
+ uuidFactory: () => {
92
+ throw new Error('a stored anonymous UUID should be reused');
93
+ },
94
+ });
95
+
96
+ expect(second.consent).toBe('granted');
97
+ expect(second.anonymousId).toBe(first.anonymousId);
98
+ });
99
+
100
+ it('clears provider pending data exactly once on a transition to denied', () => {
101
+ const clearPending = vi.fn();
102
+ const transport: Transport<ProductEvent> = {
103
+ send: vi.fn(),
104
+ clearPending,
105
+ };
106
+ const client = createClient({ transport });
107
+
108
+ client.setConsent('granted');
109
+ client.setConsent('denied');
110
+ client.setConsent('denied');
111
+
112
+ expect(clearPending).toHaveBeenCalledOnce();
113
+ });
114
+
115
+ it('keeps transports without the optional clear hook compatible', () => {
116
+ const transport: Transport<ProductEvent> = { send: vi.fn() };
117
+ const client = createClient({ transport });
118
+
119
+ client.setConsent('granted');
120
+ expect(() => {
121
+ client.setConsent('denied');
122
+ }).not.toThrow();
123
+ });
124
+ });
125
+
126
+ describe('AnalyticsClient identity', () => {
127
+ it('identifies UUID users, aliases once, and reset rotates the anonymous ID', async () => {
128
+ const transport = new InMemoryTransport<ProductEvent>();
129
+ const uuidValues = [ANONYMOUS_ID_1, ANONYMOUS_ID_2];
130
+ const client = createClient({
131
+ transport,
132
+ uuidFactory: () => uuidValues.shift() ?? ANONYMOUS_ID_2,
133
+ onWarning: () => undefined,
134
+ });
135
+ client.setConsent('granted');
136
+ const originalAnonymousId = client.anonymousId;
137
+
138
+ client.identify(USER_ID, { plan: 'free', emailAddress: 'person@example.com' });
139
+ client.alias(originalAnonymousId, USER_ID);
140
+ client.alias(originalAnonymousId, USER_ID);
141
+ client.reset();
142
+ await client.flush();
143
+
144
+ expect(client.userId).toBeUndefined();
145
+ expect(client.anonymousId).toBe(ANONYMOUS_ID_2);
146
+ expect(client.anonymousId).not.toBe(originalAnonymousId);
147
+ expect(transport.envelopes.map((envelope) => envelope.type)).toEqual([
148
+ 'identify',
149
+ 'alias',
150
+ 'reset',
151
+ ]);
152
+ expect(transport.envelopes[0]).toMatchObject({
153
+ type: 'identify',
154
+ user_id: USER_ID,
155
+ traits: { plan: 'free', emailAddress: '[redacted]' },
156
+ });
157
+ });
158
+
159
+ it('drops identity commands before consent and rejects non-UUID user IDs', async () => {
160
+ const transport = new InMemoryTransport<ProductEvent>();
161
+ const warnings: string[] = [];
162
+ const client = createClient({ transport, onWarning: (warning) => warnings.push(warning) });
163
+
164
+ client.identify(USER_ID);
165
+ client.setConsent('granted');
166
+ client.identify('provider-subject-123');
167
+ await client.flush();
168
+
169
+ expect(client.userId).toBeUndefined();
170
+ expect(transport.envelopes).toEqual([]);
171
+ expect(warnings).toContain('Dropped analytics identify call because userId is not a UUID.');
172
+ });
173
+ });
174
+
175
+ describe('AnalyticsClient capture pipeline', () => {
176
+ it('drops unknown properties before scrubbing and stamps required context', async () => {
177
+ const transport = new InMemoryTransport<ProductEvent>();
178
+ const client = createClient({ transport });
179
+ client.setConsent('granted');
180
+
181
+ client.capture({
182
+ name: 'onboarding_started',
183
+ properties: {
184
+ source: 'organic',
185
+ contact: 'person@example.com',
186
+ api_token: 'short-secret',
187
+ unknown_email: 'leaked@example.com',
188
+ },
189
+ } as ProductEvent);
190
+ await client.flush();
191
+
192
+ expect(transport.envelopes[0]).toMatchObject({
193
+ type: 'capture',
194
+ anonymous_id: ANONYMOUS_ID_1,
195
+ event: {
196
+ ...context,
197
+ name: 'onboarding_started',
198
+ properties: {
199
+ source: 'organic',
200
+ contact: '[redacted]',
201
+ api_token: '[redacted]',
202
+ },
203
+ },
204
+ });
205
+ const envelope = transport.envelopes[0];
206
+ expect(envelope?.type === 'capture' && envelope.event.properties).not.toHaveProperty(
207
+ 'unknown_email',
208
+ );
209
+ });
210
+
211
+ it('passes exact blocked keys to the scrubber', async () => {
212
+ const transport = new InMemoryTransport<ProductEvent>();
213
+ const client = createClient({ transport, exactBlockedKeys: ['contact'] });
214
+ client.setConsent('granted');
215
+
216
+ client.capture({
217
+ name: 'onboarding_started',
218
+ properties: { source: 'invite', contact: 'front desk' },
219
+ });
220
+ await client.flush();
221
+
222
+ expect(transport.envelopes[0]).toMatchObject({
223
+ event: { properties: { source: 'invite', contact: '[redacted]' } },
224
+ });
225
+ });
226
+
227
+ it('drops the oldest waiting command when the bounded queue overflows', async () => {
228
+ const transport = new InMemoryTransport<ProductEvent>();
229
+ const client = createClient({ transport, maxQueueSize: 2, flushBatchSize: 10 });
230
+ client.setConsent('granted');
231
+
232
+ client.capture({ name: 'step_viewed', properties: { step: 1 } });
233
+ client.capture({ name: 'step_viewed', properties: { step: 2 } });
234
+ client.capture({ name: 'step_viewed', properties: { step: 3 } });
235
+ expect(client.pendingCount).toBe(2);
236
+ await client.flush();
237
+
238
+ expect(
239
+ transport.envelopes.map((envelope) =>
240
+ envelope.type === 'capture' ? envelope.event.properties['step'] : undefined,
241
+ ),
242
+ ).toEqual([2, 3]);
243
+ });
244
+
245
+ it('flushes asynchronously at the size threshold and interval', async () => {
246
+ const sizeTransport = new InMemoryTransport<ProductEvent>();
247
+ const sizeClient = createClient({ transport: sizeTransport, flushBatchSize: 2 });
248
+ sizeClient.setConsent('granted');
249
+ sizeClient.capture({ name: 'step_viewed', properties: { step: 1 } });
250
+ sizeClient.capture({ name: 'step_viewed', properties: { step: 2 } });
251
+ await vi.waitFor(() => {
252
+ expect(sizeTransport.envelopes).toHaveLength(2);
253
+ });
254
+
255
+ vi.useFakeTimers();
256
+ const intervalTransport = new InMemoryTransport<ProductEvent>();
257
+ const intervalClient = createClient({ transport: intervalTransport, flushIntervalMs: 25 });
258
+ intervalClient.setConsent('granted');
259
+ intervalClient.capture({ name: 'step_viewed', properties: { step: 3 } });
260
+ await vi.advanceTimersByTimeAsync(25);
261
+ expect(intervalTransport.envelopes).toHaveLength(1);
262
+ });
263
+ });
264
+
265
+ describe('AnalyticsClient failure semantics', () => {
266
+ it('caps retries and never exposes transport failures to callers', async () => {
267
+ let calls = 0;
268
+ const failures: number[] = [];
269
+ const failingTransport: Transport<ProductEvent> = {
270
+ send: () => {
271
+ calls += 1;
272
+ throw new Error('provider unavailable');
273
+ },
274
+ };
275
+ const client = createClient({
276
+ transport: failingTransport,
277
+ maxRetries: 2,
278
+ retryDelayMs: 0,
279
+ onTransportFailure: (failure) => {
280
+ failures.push(failure.attempts);
281
+ },
282
+ });
283
+ client.setConsent('granted');
284
+
285
+ expect(() => {
286
+ client.capture({ name: 'onboarding_completed', properties: { duration_seconds: 8 } });
287
+ }).not.toThrow();
288
+ await expect(client.flush()).resolves.toBeUndefined();
289
+
290
+ expect(calls).toBe(3);
291
+ expect(failures).toEqual([3]);
292
+ expect(client.pendingCount).toBe(0);
293
+ });
294
+
295
+ it('provides a no-op transport and advisory event-name convention check', async () => {
296
+ const client = createClient({ transport: new NoopTransport<ProductEvent>() });
297
+ client.setConsent('granted');
298
+ client.capture({ name: 'onboarding_started', properties: { source: 'organic' } });
299
+
300
+ await expect(client.flush()).resolves.toBeUndefined();
301
+ expect(followsEventNameConvention('checkout_started')).toBe(true);
302
+ expect(followsEventNameConvention('CheckoutStarted')).toBe(false);
303
+ expect(followsEventNameConvention('checkout_start')).toBe(false);
304
+ });
305
+ });
306
+
307
+ describe('analyticsStorageKeys', () => {
308
+ it('names every key the client persists under its prefix', () => {
309
+ const storage = new InMemoryAnalyticsStorage();
310
+ const client = createClient({ storage, storageKeyPrefix: 'app' });
311
+ client.setConsent('granted');
312
+ client.identify(USER_ID);
313
+ client.alias(ANONYMOUS_ID_1, USER_ID);
314
+
315
+ const keys = analyticsStorageKeys('app');
316
+ expect(Object.keys(storage.snapshot()).sort()).toEqual(Object.values(keys).sort());
317
+ expect(keys).toEqual({
318
+ consent: 'app:consent',
319
+ anonymousId: 'app:anonymous-id',
320
+ userId: 'app:user-id',
321
+ aliasedUserId: 'app:aliased-user-id',
322
+ });
323
+ });
324
+ });