@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/src/client.ts ADDED
@@ -0,0 +1,585 @@
1
+ import { scrubProperties, type ScrubberOptions } from './scrubber.js';
2
+ import {
3
+ analyticsStorageKeys,
4
+ InMemoryAnalyticsStorage,
5
+ type AnalyticsStorageKeys,
6
+ } from './storage.js';
7
+ import { NoopTransport } from './transports.js';
8
+ import type {
9
+ AliasEnvelope,
10
+ AnalyticsClientOptions,
11
+ AnalyticsContext,
12
+ AnalyticsEnvelope,
13
+ AnalyticsEvent,
14
+ AnalyticsPort,
15
+ AnalyticsStorage,
16
+ ConsentState,
17
+ EventAllowlist,
18
+ IdentifyEnvelope,
19
+ ResetEnvelope,
20
+ SafeTraits,
21
+ Transport,
22
+ TransportFailure,
23
+ } from './types.js';
24
+
25
+ const DEFAULT_MAX_QUEUE_SIZE = 100;
26
+ const DEFAULT_FLUSH_BATCH_SIZE = 20;
27
+ const DEFAULT_FLUSH_INTERVAL_MS = 5_000;
28
+ const DEFAULT_MAX_RETRIES = 2;
29
+ const DEFAULT_RETRY_DELAY_MS = 100;
30
+ const UUID_PATTERN = /^[A-Fa-f0-9]{8}-(?:[A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}$/;
31
+ const IRREGULAR_PAST_TENSE = new Set([
32
+ 'begun',
33
+ 'bought',
34
+ 'built',
35
+ 'caught',
36
+ 'chosen',
37
+ 'done',
38
+ 'found',
39
+ 'given',
40
+ 'gone',
41
+ 'kept',
42
+ 'known',
43
+ 'left',
44
+ 'lost',
45
+ 'made',
46
+ 'paid',
47
+ 'read',
48
+ 'run',
49
+ 'seen',
50
+ 'sent',
51
+ 'shown',
52
+ 'sold',
53
+ 'taken',
54
+ 'won',
55
+ 'written',
56
+ ]);
57
+
58
+ interface TimeoutRuntime {
59
+ setTimeout(callback: () => void, milliseconds: number): unknown;
60
+ clearTimeout(handle: unknown): void;
61
+ }
62
+
63
+ interface NodeStyleTimeout {
64
+ unref(): void;
65
+ }
66
+
67
+ function getTimeoutRuntime(): TimeoutRuntime {
68
+ const runtime = globalThis as unknown as Partial<TimeoutRuntime>;
69
+ if (runtime.setTimeout === undefined || runtime.clearTimeout === undefined) {
70
+ throw new Error('@baukit/analytics-core requires setTimeout and clearTimeout');
71
+ }
72
+ return runtime as TimeoutRuntime;
73
+ }
74
+
75
+ function inferDevelopmentMode(): boolean {
76
+ const runtime = globalThis as unknown as {
77
+ process?: { env?: Readonly<Record<string, string | undefined>> };
78
+ };
79
+ return runtime.process?.env?.['NODE_ENV'] !== 'production';
80
+ }
81
+
82
+ function defaultWarning(message: string): void {
83
+ const runtime = globalThis as unknown as { console?: { warn(value: string): void } };
84
+ runtime.console?.warn(message);
85
+ }
86
+
87
+ function defaultUuidFactory(): string {
88
+ const runtime = globalThis as unknown as { crypto?: { randomUUID?: () => string } };
89
+ if (runtime.crypto?.randomUUID === undefined) {
90
+ throw new Error(
91
+ '@baukit/analytics-core requires crypto.randomUUID; provide uuidFactory on runtimes without it',
92
+ );
93
+ }
94
+ return runtime.crypto.randomUUID();
95
+ }
96
+
97
+ function requireInteger(name: string, value: number, minimum: number): number {
98
+ if (!Number.isInteger(value) || value < minimum) {
99
+ throw new TypeError(`${name} must be an integer greater than or equal to ${String(minimum)}`);
100
+ }
101
+ return value;
102
+ }
103
+
104
+ function requireNonEmpty(name: string, value: string): string {
105
+ if (value.trim().length === 0) {
106
+ throw new TypeError(`${name} must not be empty`);
107
+ }
108
+ return value;
109
+ }
110
+
111
+ function validateContext(context: AnalyticsContext): AnalyticsContext {
112
+ requireInteger('context.schema_version', context.schema_version, 1);
113
+ requireNonEmpty('context.app', context.app);
114
+ requireNonEmpty('context.app_version', context.app_version);
115
+ requireNonEmpty('context.platform', context.platform);
116
+ requireNonEmpty('context.environment', context.environment);
117
+ requireNonEmpty('context.locale', context.locale);
118
+ return { ...context };
119
+ }
120
+
121
+ function isUuid(value: string): boolean {
122
+ return UUID_PATTERN.test(value);
123
+ }
124
+
125
+ /** A deliberately conservative development-time heuristic, not a type-level grammar. */
126
+ export function followsEventNameConvention(name: string): boolean {
127
+ if (!/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/.test(name)) {
128
+ return false;
129
+ }
130
+ return name.split('_').some((part) => part.endsWith('ed') || IRREGULAR_PAST_TENSE.has(part));
131
+ }
132
+
133
+ export class AnalyticsClient<E extends AnalyticsEvent> implements AnalyticsPort<E> {
134
+ readonly #context: AnalyticsContext;
135
+ readonly #allowlist: EventAllowlist<E>;
136
+ readonly #transport: Transport<E>;
137
+ readonly #storage: AnalyticsStorage;
138
+ readonly #storageKeys: AnalyticsStorageKeys;
139
+ readonly #uuidFactory: () => string;
140
+ readonly #scrubberOptions: ScrubberOptions;
141
+ readonly #maxQueueSize: number;
142
+ readonly #flushBatchSize: number;
143
+ readonly #flushIntervalMs: number;
144
+ readonly #maxRetries: number;
145
+ readonly #retryDelayMs: number;
146
+ readonly #development: boolean;
147
+ readonly #now: () => Date;
148
+ readonly #onWarning: (message: string) => void;
149
+ readonly #onTransportFailure: ((failure: TransportFailure<E>) => void) | undefined;
150
+ readonly #queue: AnalyticsEnvelope<E>[] = [];
151
+ readonly #warnedEventNames = new Set<string>();
152
+ #consent: ConsentState;
153
+ #anonymousId: string;
154
+ #userId: string | undefined;
155
+ #aliasedUserId: string | undefined;
156
+ #flushTimer: unknown;
157
+ #immediateFlushScheduled = false;
158
+ #activeFlush: Promise<void> | undefined;
159
+
160
+ public constructor(options: AnalyticsClientOptions<E>) {
161
+ this.#context = validateContext(options.context);
162
+ this.#allowlist = options.allowlist;
163
+ this.#transport = options.transport ?? new NoopTransport<E>();
164
+ this.#storage = options.storage ?? new InMemoryAnalyticsStorage();
165
+ this.#storageKeys = analyticsStorageKeys(
166
+ options.storageKeyPrefix ?? `@baukit/analytics-core:${this.#context.app}`,
167
+ );
168
+ this.#uuidFactory = options.uuidFactory ?? defaultUuidFactory;
169
+ this.#scrubberOptions = {
170
+ blockedKeys: [...(options.blockedKeys ?? [])],
171
+ exactBlockedKeys: [...(options.exactBlockedKeys ?? [])],
172
+ };
173
+ this.#maxQueueSize = requireInteger(
174
+ 'maxQueueSize',
175
+ options.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE,
176
+ 1,
177
+ );
178
+ this.#flushBatchSize = requireInteger(
179
+ 'flushBatchSize',
180
+ options.flushBatchSize ?? Math.min(DEFAULT_FLUSH_BATCH_SIZE, this.#maxQueueSize),
181
+ 1,
182
+ );
183
+ this.#flushIntervalMs = requireInteger(
184
+ 'flushIntervalMs',
185
+ options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
186
+ 1,
187
+ );
188
+ this.#maxRetries = requireInteger('maxRetries', options.maxRetries ?? DEFAULT_MAX_RETRIES, 0);
189
+ this.#retryDelayMs = requireInteger(
190
+ 'retryDelayMs',
191
+ options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS,
192
+ 0,
193
+ );
194
+ this.#development = options.development ?? inferDevelopmentMode();
195
+ this.#now = options.now ?? (() => new Date());
196
+ this.#onWarning = options.onWarning ?? defaultWarning;
197
+ this.#onTransportFailure = options.onTransportFailure;
198
+
199
+ const storedConsent = this.#readStorage(this.#storageKeys.consent);
200
+ this.#consent =
201
+ storedConsent === 'granted' || storedConsent === 'denied' || storedConsent === 'unknown'
202
+ ? storedConsent
203
+ : 'unknown';
204
+
205
+ const storedAnonymousId = this.#readStorage(this.#storageKeys.anonymousId);
206
+ this.#anonymousId =
207
+ storedAnonymousId !== undefined && isUuid(storedAnonymousId)
208
+ ? storedAnonymousId
209
+ : this.#generateAnonymousId();
210
+ this.#writeStorage(this.#storageKeys.anonymousId, this.#anonymousId);
211
+
212
+ const storedUserId = this.#readStorage(this.#storageKeys.userId);
213
+ this.#userId = storedUserId !== undefined && isUuid(storedUserId) ? storedUserId : undefined;
214
+
215
+ const storedAliasedUserId = this.#readStorage(this.#storageKeys.aliasedUserId);
216
+ this.#aliasedUserId =
217
+ storedAliasedUserId !== undefined && isUuid(storedAliasedUserId)
218
+ ? storedAliasedUserId
219
+ : undefined;
220
+ }
221
+
222
+ public get consent(): ConsentState {
223
+ return this.#consent;
224
+ }
225
+
226
+ public get anonymousId(): string {
227
+ return this.#anonymousId;
228
+ }
229
+
230
+ public get userId(): string | undefined {
231
+ return this.#userId;
232
+ }
233
+
234
+ public get pendingCount(): number {
235
+ return this.#queue.length;
236
+ }
237
+
238
+ public capture(event: E): void {
239
+ if (this.#consent !== 'granted') {
240
+ return;
241
+ }
242
+
243
+ this.#warnAboutEventName(event.name);
244
+ const allowedProperties = this.#allowedProperties(event);
245
+ if (allowedProperties === undefined) {
246
+ this.#warn(`Dropped undeclared analytics event "${event.name}".`);
247
+ return;
248
+ }
249
+
250
+ const filtered: Record<string, unknown> = {};
251
+ const source = event.properties as Readonly<Record<string, unknown>>;
252
+ for (const propertyName of allowedProperties) {
253
+ if (Object.prototype.hasOwnProperty.call(source, propertyName)) {
254
+ filtered[propertyName] = source[propertyName];
255
+ }
256
+ }
257
+
258
+ const envelope: AnalyticsEnvelope<E> = {
259
+ type: 'capture',
260
+ captured_at: this.#timestamp(),
261
+ anonymous_id: this.#anonymousId,
262
+ ...(this.#userId === undefined ? {} : { user_id: this.#userId }),
263
+ event: {
264
+ ...this.#context,
265
+ name: event.name,
266
+ properties: scrubProperties(filtered, this.#scrubberOptions),
267
+ },
268
+ };
269
+ this.#enqueue(envelope);
270
+ }
271
+
272
+ public identify(userId: string, traits?: SafeTraits): void {
273
+ if (this.#consent !== 'granted') {
274
+ return;
275
+ }
276
+ if (!isUuid(userId)) {
277
+ this.#warn('Dropped analytics identify call because userId is not a UUID.');
278
+ return;
279
+ }
280
+ if (this.#userId !== undefined && this.#userId !== userId) {
281
+ this.#warn('Dropped analytics identify call for a different user; call reset() first.');
282
+ return;
283
+ }
284
+
285
+ this.#userId = userId;
286
+ this.#writeStorage(this.#storageKeys.userId, userId);
287
+ const scrubbedTraits =
288
+ traits === undefined ? undefined : scrubProperties(traits, this.#scrubberOptions);
289
+ const envelope: IdentifyEnvelope = {
290
+ type: 'identify',
291
+ captured_at: this.#timestamp(),
292
+ anonymous_id: this.#anonymousId,
293
+ user_id: userId,
294
+ ...(scrubbedTraits === undefined ? {} : { traits: scrubbedTraits }),
295
+ };
296
+ this.#enqueue(envelope);
297
+ }
298
+
299
+ public alias(anonymousId: string, userId: string): void {
300
+ if (this.#consent !== 'granted') {
301
+ return;
302
+ }
303
+ if (!isUuid(anonymousId) || anonymousId !== this.#anonymousId) {
304
+ this.#warn('Dropped analytics alias call because anonymousId is not the current UUID.');
305
+ return;
306
+ }
307
+ if (!isUuid(userId) || this.#userId !== userId) {
308
+ this.#warn('Dropped analytics alias call; identify() must first set the same UUID userId.');
309
+ return;
310
+ }
311
+ if (this.#aliasedUserId !== undefined) {
312
+ this.#warn('Dropped repeated analytics alias call for the current anonymous identity.');
313
+ return;
314
+ }
315
+
316
+ this.#aliasedUserId = userId;
317
+ this.#writeStorage(this.#storageKeys.aliasedUserId, userId);
318
+ const envelope: AliasEnvelope = {
319
+ type: 'alias',
320
+ captured_at: this.#timestamp(),
321
+ anonymous_id: anonymousId,
322
+ user_id: userId,
323
+ };
324
+ this.#enqueue(envelope);
325
+ }
326
+
327
+ public reset(): void {
328
+ const previousAnonymousId = this.#anonymousId;
329
+ const previousUserId = this.#userId;
330
+ const nextAnonymousId = this.#generateAnonymousId(previousAnonymousId);
331
+
332
+ if (this.#consent === 'granted') {
333
+ const envelope: ResetEnvelope = {
334
+ type: 'reset',
335
+ captured_at: this.#timestamp(),
336
+ previous_anonymous_id: previousAnonymousId,
337
+ ...(previousUserId === undefined ? {} : { previous_user_id: previousUserId }),
338
+ };
339
+ this.#enqueue(envelope);
340
+ }
341
+
342
+ this.#anonymousId = nextAnonymousId;
343
+ this.#userId = undefined;
344
+ this.#aliasedUserId = undefined;
345
+ this.#writeStorage(this.#storageKeys.anonymousId, nextAnonymousId);
346
+ this.#removeStorage(this.#storageKeys.userId);
347
+ this.#removeStorage(this.#storageKeys.aliasedUserId);
348
+ }
349
+
350
+ public setConsent(value: ConsentState): void {
351
+ const transitionedToDenied = this.#consent !== 'denied' && value === 'denied';
352
+ this.#consent = value;
353
+ this.#writeStorage(this.#storageKeys.consent, value);
354
+ if (value !== 'granted') {
355
+ this.#queue.length = 0;
356
+ this.#clearFlushTimer();
357
+ }
358
+ if (transitionedToDenied) {
359
+ this.#clearTransportPending();
360
+ }
361
+ }
362
+
363
+ /** Flushes accepted commands and always resolves, including on transport failure. */
364
+ public flush(): Promise<void> {
365
+ if (this.#activeFlush !== undefined) {
366
+ return this.#activeFlush;
367
+ }
368
+ this.#clearFlushTimer();
369
+ const operation = this.#drainQueue().finally(() => {
370
+ if (this.#activeFlush === operation) {
371
+ this.#activeFlush = undefined;
372
+ }
373
+ if (this.#queue.length > 0 && this.#consent === 'granted') {
374
+ this.#armFlushTimer();
375
+ }
376
+ });
377
+ this.#activeFlush = operation;
378
+ return operation;
379
+ }
380
+
381
+ /** Stops the interval timer after a best-effort flush. */
382
+ public async dispose(): Promise<void> {
383
+ this.#clearFlushTimer();
384
+ await this.flush();
385
+ this.#clearFlushTimer();
386
+ }
387
+
388
+ #allowedProperties(event: E): readonly string[] | undefined {
389
+ const allowlist = this.#allowlist as Readonly<Record<string, readonly string[] | undefined>>;
390
+ return allowlist[event.name];
391
+ }
392
+
393
+ #enqueue(envelope: AnalyticsEnvelope<E>): void {
394
+ if (this.#consent !== 'granted') {
395
+ return;
396
+ }
397
+ if (this.#queue.length === this.#maxQueueSize) {
398
+ this.#queue.shift();
399
+ }
400
+ this.#queue.push(envelope);
401
+
402
+ if (this.#queue.length >= this.#flushBatchSize) {
403
+ this.#requestImmediateFlush();
404
+ } else {
405
+ this.#armFlushTimer();
406
+ }
407
+ }
408
+
409
+ #requestImmediateFlush(): void {
410
+ if (this.#immediateFlushScheduled) {
411
+ return;
412
+ }
413
+ this.#immediateFlushScheduled = true;
414
+ void Promise.resolve()
415
+ .then(() => {
416
+ this.#immediateFlushScheduled = false;
417
+ return this.flush();
418
+ })
419
+ .catch(() => {
420
+ // flush() is deliberately no-throw; this guard prevents future regressions leaking rejections.
421
+ });
422
+ }
423
+
424
+ #armFlushTimer(): void {
425
+ if (this.#flushTimer !== undefined || this.#queue.length === 0) {
426
+ return;
427
+ }
428
+ const timers = getTimeoutRuntime();
429
+ this.#flushTimer = timers.setTimeout(() => {
430
+ this.#flushTimer = undefined;
431
+ void this.flush();
432
+ }, this.#flushIntervalMs);
433
+ if (this.#isNodeStyleTimeout(this.#flushTimer)) {
434
+ this.#flushTimer.unref();
435
+ }
436
+ }
437
+
438
+ #clearFlushTimer(): void {
439
+ if (this.#flushTimer === undefined) {
440
+ return;
441
+ }
442
+ getTimeoutRuntime().clearTimeout(this.#flushTimer);
443
+ this.#flushTimer = undefined;
444
+ }
445
+
446
+ #clearTransportPending(): void {
447
+ try {
448
+ const operation = this.#transport.clearPending?.();
449
+ if (operation !== undefined) {
450
+ void Promise.resolve(operation).catch((error: unknown) => {
451
+ this.#reportTransportFailure({ error, envelopes: [], attempts: 0 });
452
+ });
453
+ }
454
+ } catch (error: unknown) {
455
+ this.#reportTransportFailure({ error, envelopes: [], attempts: 0 });
456
+ }
457
+ }
458
+
459
+ #isNodeStyleTimeout(value: unknown): value is NodeStyleTimeout {
460
+ return (
461
+ typeof value === 'object' &&
462
+ value !== null &&
463
+ 'unref' in value &&
464
+ typeof (value as Partial<NodeStyleTimeout>).unref === 'function'
465
+ );
466
+ }
467
+
468
+ async #drainQueue(): Promise<void> {
469
+ try {
470
+ while (this.#queue.length > 0 && this.#hasConsent()) {
471
+ const batch = this.#queue.splice(0, this.#flushBatchSize);
472
+ let lastError: unknown;
473
+ let attempts = 0;
474
+
475
+ while (attempts <= this.#maxRetries && this.#hasConsent()) {
476
+ attempts += 1;
477
+ try {
478
+ await this.#transport.send(batch);
479
+ lastError = undefined;
480
+ break;
481
+ } catch (error: unknown) {
482
+ lastError = error;
483
+ if (attempts <= this.#maxRetries && this.#hasConsent()) {
484
+ await this.#retryDelay(attempts);
485
+ }
486
+ }
487
+ }
488
+
489
+ if (lastError !== undefined) {
490
+ this.#reportTransportFailure({ error: lastError, envelopes: batch, attempts });
491
+ }
492
+ }
493
+ } catch (error: unknown) {
494
+ this.#reportTransportFailure({ error, envelopes: [], attempts: 0 });
495
+ }
496
+ }
497
+
498
+ #hasConsent(): boolean {
499
+ return this.#consent === 'granted';
500
+ }
501
+
502
+ async #retryDelay(attempt: number): Promise<void> {
503
+ const delay = this.#retryDelayMs * 2 ** (attempt - 1);
504
+ if (delay === 0) {
505
+ await Promise.resolve();
506
+ return;
507
+ }
508
+ await new Promise<void>((resolve) => {
509
+ getTimeoutRuntime().setTimeout(resolve, delay);
510
+ });
511
+ }
512
+
513
+ #reportTransportFailure(failure: TransportFailure<E>): void {
514
+ try {
515
+ this.#onTransportFailure?.(failure);
516
+ } catch {
517
+ // Diagnostics are never allowed to affect application behavior.
518
+ }
519
+ }
520
+
521
+ #timestamp(): string {
522
+ try {
523
+ return this.#now().toISOString();
524
+ } catch {
525
+ return new Date().toISOString();
526
+ }
527
+ }
528
+
529
+ #generateAnonymousId(previous?: string): string {
530
+ for (let attempt = 0; attempt < 3; attempt += 1) {
531
+ const candidate = this.#uuidFactory();
532
+ if (isUuid(candidate) && candidate !== previous) {
533
+ return candidate;
534
+ }
535
+ }
536
+ throw new Error('uuidFactory must return a fresh UUID');
537
+ }
538
+
539
+ #warnAboutEventName(name: string): void {
540
+ if (
541
+ !this.#development ||
542
+ this.#warnedEventNames.has(name) ||
543
+ followsEventNameConvention(name)
544
+ ) {
545
+ return;
546
+ }
547
+ this.#warnedEventNames.add(name);
548
+ this.#warn(
549
+ `Analytics event "${name}" does not appear to use the past-tense snake_case convention.`,
550
+ );
551
+ }
552
+
553
+ #readStorage(key: string): string | undefined {
554
+ try {
555
+ return this.#storage.getItem(key);
556
+ } catch {
557
+ this.#warn(`Analytics storage read failed for "${key}"; using a privacy-safe default.`);
558
+ return undefined;
559
+ }
560
+ }
561
+
562
+ #writeStorage(key: string, value: string): void {
563
+ try {
564
+ this.#storage.setItem(key, value);
565
+ } catch {
566
+ this.#warn(`Analytics storage write failed for "${key}".`);
567
+ }
568
+ }
569
+
570
+ #removeStorage(key: string): void {
571
+ try {
572
+ this.#storage.removeItem(key);
573
+ } catch {
574
+ this.#warn(`Analytics storage removal failed for "${key}".`);
575
+ }
576
+ }
577
+
578
+ #warn(message: string): void {
579
+ try {
580
+ this.#onWarning(message);
581
+ } catch {
582
+ // Warnings are advisory and never alter analytics behavior.
583
+ }
584
+ }
585
+ }
package/src/index.ts ADDED
@@ -0,0 +1,34 @@
1
+ export { AnalyticsClient, followsEventNameConvention } from './client.js';
2
+ export {
3
+ DEFAULT_BLOCKED_KEYS,
4
+ DEFAULT_EXACT_BLOCKED_KEYS,
5
+ ERROR_EVENT_BLOCKED_KEYS,
6
+ ERROR_EVENT_PRESERVED_KEYS,
7
+ REDACTED_VALUE,
8
+ scrubErrorEvent,
9
+ scrubProperties,
10
+ type ScrubberOptions,
11
+ } from './scrubber.js';
12
+ export {
13
+ analyticsStorageKeys,
14
+ InMemoryAnalyticsStorage,
15
+ type AnalyticsStorageKeys,
16
+ } from './storage.js';
17
+ export { InMemoryTransport, NoopTransport } from './transports.js';
18
+ export type {
19
+ AliasEnvelope,
20
+ AnalyticsClientOptions,
21
+ AnalyticsContext,
22
+ AnalyticsEnvelope,
23
+ AnalyticsEvent,
24
+ AnalyticsPort,
25
+ AnalyticsStorage,
26
+ CaptureEnvelope,
27
+ ConsentState,
28
+ EventAllowlist,
29
+ IdentifyEnvelope,
30
+ ResetEnvelope,
31
+ SafeTraits,
32
+ Transport,
33
+ TransportFailure,
34
+ } from './types.js';