-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbreadcrumbs.ts
More file actions
646 lines (547 loc) · 15.7 KB
/
breadcrumbs.ts
File metadata and controls
646 lines (547 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
/**
* @file Breadcrumbs module - captures chronological trail of events before an error
*/
import type { Breadcrumb, BreadcrumbLevel, BreadcrumbType, Json, JsonNode } from '@hawk.so/types';
import { buildElementSelector, isValidBreadcrumb, log, Sanitizer } from '@hawk.so/core';
/**
* Default maximum number of breadcrumbs to store
*/
const DEFAULT_MAX_BREADCRUMBS = 15;
/**
* Hint object passed to beforeBreadcrumb callback
*/
export interface BreadcrumbHint {
/**
* Original event that triggered the breadcrumb (if any)
*/
event?: Event | Response | XMLHttpRequest;
/**
* Request info for fetch/xhr breadcrumbs
*/
input?: RequestInfo | URL;
/**
* Response data for fetch/xhr breadcrumbs
*/
response?: Response;
/**
* XHR instance for xhr breadcrumbs
*/
xhr?: XMLHttpRequest;
}
/**
* Configuration options for breadcrumbs
*/
export interface BreadcrumbsOptions {
/**
* Maximum number of breadcrumbs to store (FIFO)
*
* @default 15
*/
maxBreadcrumbs?: number;
/**
* Hook called before each breadcrumb is stored.
* - Return modified breadcrumb — it will be stored instead of the original.
* - Return `false` — the breadcrumb will be discarded.
* - Any other value is invalid — the original breadcrumb is stored as-is (a warning is logged).
*/
beforeBreadcrumb?: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => Breadcrumb | false | void;
/**
* Enable automatic fetch/XHR breadcrumbs
*
* @default true
*/
trackFetch?: boolean;
/**
* Enable automatic navigation breadcrumbs (history API)
*
* @default true
*/
trackNavigation?: boolean;
/**
* Enable automatic UI click breadcrumbs
*
* @default true
*/
trackClicks?: boolean;
}
/**
* Breadcrumb input type - breadcrumb data with optional timestamp
* (timestamp will be auto-generated if not provided)
*/
export type BreadcrumbInput = Omit<Breadcrumb, 'timestamp'> & { timestamp?: Breadcrumb['timestamp'] };
/**
* Internal breadcrumbs options - all fields except 'beforeBreadcrumb' are required
* (they have default values and are always set during init)
*/
interface InternalBreadcrumbsOptions {
maxBreadcrumbs: number;
trackFetch: boolean;
trackNavigation: boolean;
trackClicks: boolean;
beforeBreadcrumb?: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => Breadcrumb | false | void;
}
/**
* BreadcrumbManager - singleton that manages breadcrumb collection and storage
*/
export class BreadcrumbManager {
/**
* Singleton instance
*/
private static instance: BreadcrumbManager | null = null;
/**
* Breadcrumbs buffer (FIFO)
*/
private readonly breadcrumbs: Breadcrumb[] = [];
/**
* Configuration options - all fields are guaranteed to be set (except optional beforeBreadcrumb)
*/
private options: InternalBreadcrumbsOptions;
/**
* Initialization flag
*/
private isInitialized = false;
/**
* Original fetch function (for restoration)
*/
private originalFetch: typeof fetch | null = null;
/**
* Original XMLHttpRequest.open (for restoration)
*/
private originalXHROpen: typeof XMLHttpRequest.prototype.open | null = null;
/**
* Original XMLHttpRequest.send (for restoration)
*/
private originalXHRSend: typeof XMLHttpRequest.prototype.send | null = null;
/**
* Original history.pushState (for restoration)
*/
private originalPushState: typeof history.pushState | null = null;
/**
* Original history.replaceState (for restoration)
*/
private originalReplaceState: typeof history.replaceState | null = null;
/**
* Click event handler reference (for removal)
*/
private clickHandler: ((event: MouseEvent) => void) | null = null;
/**
* Popstate event handler reference (for removal)
*/
private popstateHandler: (() => void) | null = null;
/**
* Private constructor to enforce singleton pattern
*/
private constructor() {
this.options = {
maxBreadcrumbs: DEFAULT_MAX_BREADCRUMBS,
trackFetch: true,
trackNavigation: true,
trackClicks: true,
};
}
/**
* Get singleton instance
*/
public static getInstance(): BreadcrumbManager {
BreadcrumbManager.instance ??= new BreadcrumbManager();
return BreadcrumbManager.instance;
}
/**
* Initialize breadcrumbs with options and start auto-capture
*
* @param options - Configuration options for breadcrumbs
*/
public init(options: BreadcrumbsOptions = {}): void {
if (this.isInitialized) {
log('[BreadcrumbManager] init has already been called; breadcrumb configuration is global and subsequent init options are ignored.', 'warn');
return;
}
this.options = {
maxBreadcrumbs: options.maxBreadcrumbs ?? DEFAULT_MAX_BREADCRUMBS,
beforeBreadcrumb: options.beforeBreadcrumb,
trackFetch: options.trackFetch ?? true,
trackNavigation: options.trackNavigation ?? true,
trackClicks: options.trackClicks ?? true,
};
this.isInitialized = true;
/**
* Setup auto-capture handlers
*/
if (this.options.trackFetch) {
this.monkeypatchFetch();
this.wrapXHR();
}
if (this.options.trackNavigation) {
this.wrapHistory();
}
if (this.options.trackClicks) {
this.setupClickTracking();
}
}
/**
* Add a breadcrumb to the buffer
*
* @param breadcrumb - The breadcrumb data to add
* @param hint - Optional hint object with original event data (Event, Response, XMLHttpRequest, etc.)
* Used by beforeBreadcrumb callback to access original event context
*/
public addBreadcrumb(breadcrumb: BreadcrumbInput, hint?: BreadcrumbHint): void {
/**
* Ensure timestamp
*/
const bc: Breadcrumb = {
...breadcrumb,
timestamp: breadcrumb.timestamp ?? Date.now(),
};
/**
* Apply beforeBreadcrumb hook
*/
if (this.options.beforeBreadcrumb) {
let breadcrumbClone: Breadcrumb;
try {
breadcrumbClone = structuredClone(bc);
} catch {
/**
* structuredClone may fail on non-cloneable values in breadcrumb.data
* Fall back to passing the original — hook may mutate it, but breadcrumb storage won't crash
*/
breadcrumbClone = bc;
}
const result = this.options.beforeBreadcrumb(breadcrumbClone, hint);
/**
* false means discard
*/
if (result === false) {
return;
}
/**
* Valid breadcrumb → apply changes from hook
*/
if (isValidBreadcrumb(result)) {
Object.assign(bc, result);
} else {
/**
* Anything else is invalid — warn, bc stays untouched (hook only received a clone)
*/
log(
'Invalid beforeBreadcrumb value. It should return breadcrumb or false. Breadcrumb is stored without changes.',
'warn'
);
}
}
/**
* Sanitize data and message
*/
if (bc.data) {
bc.data = Sanitizer.sanitize(bc.data) as Record<string, JsonNode>;
}
if (bc.message) {
bc.message = Sanitizer.sanitize(bc.message) as string;
}
/**
* Add to buffer (FIFO)
*/
this.breadcrumbs.push(bc);
if (this.breadcrumbs.length > this.options.maxBreadcrumbs) {
this.breadcrumbs.shift();
}
}
/**
* Get current breadcrumbs snapshot (oldest to newest)
*/
public getBreadcrumbs(): Breadcrumb[] {
return [ ...this.breadcrumbs ];
}
/**
* Clear all breadcrumbs
*/
public clearBreadcrumbs(): void {
this.breadcrumbs.length = 0;
}
/**
* Destroy the manager and restore original functions
*/
public destroy(): void {
/**
* Restore fetch
*/
if (this.originalFetch) {
window.fetch = this.originalFetch;
this.originalFetch = null;
}
/**
* Restore XHR
*/
if (this.originalXHROpen) {
XMLHttpRequest.prototype.open = this.originalXHROpen;
this.originalXHROpen = null;
}
if (this.originalXHRSend) {
XMLHttpRequest.prototype.send = this.originalXHRSend;
this.originalXHRSend = null;
}
/**
* Restore history
*/
if (this.originalPushState) {
history.pushState = this.originalPushState;
this.originalPushState = null;
}
if (this.originalReplaceState) {
history.replaceState = this.originalReplaceState;
this.originalReplaceState = null;
}
/**
* Remove click handler
*/
if (this.clickHandler) {
document.removeEventListener('click', this.clickHandler, { capture: true });
this.clickHandler = null;
}
/**
* Remove popstate handler
*/
if (this.popstateHandler) {
window.removeEventListener('popstate', this.popstateHandler);
this.popstateHandler = null;
}
this.clearBreadcrumbs();
this.isInitialized = false;
BreadcrumbManager.instance = null;
}
/**
* Monkeypatch fetch API to capture HTTP breadcrumbs
*/
private monkeypatchFetch(): void {
if (typeof fetch === 'undefined') {
return;
}
const originalFetch = window.fetch.bind(window);
this.originalFetch = originalFetch;
// eslint-disable-next-line @typescript-eslint/no-this-alias
const manager = this;
window.fetch = async function (input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const startTime = Date.now();
const method = init?.method || 'GET';
let url: string;
if (typeof input === 'string') {
url = input;
} else if (input instanceof URL) {
url = input.href;
} else {
url = input.url;
}
let response: Response;
try {
response = await originalFetch(input, init);
const duration = Date.now() - startTime;
manager.addBreadcrumb({
type: 'request',
category: 'fetch',
message: `${response.status} ${method} ${url}`,
level: response.ok ? 'info' : 'error',
data: {
url,
method,
statusCode: response.status,
durationMs: duration,
},
}, {
input,
response,
});
return response;
} catch (error) {
const duration = Date.now() - startTime;
manager.addBreadcrumb({
type: 'request',
category: 'fetch',
message: `[FAIL] ${method} ${url}`,
level: 'error',
data: {
url,
method,
statusCode: 0,
durationMs: duration,
error: error instanceof Error ? error.message : String(error),
},
}, {
input,
});
throw error;
}
};
}
/**
* Wrap XMLHttpRequest to capture XHR breadcrumbs
*/
private wrapXHR(): void {
if (typeof XMLHttpRequest === 'undefined') {
return;
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
const manager = this;
const originalOpen = XMLHttpRequest.prototype.open;
const originalSend = XMLHttpRequest.prototype.send;
this.originalXHROpen = originalOpen;
this.originalXHRSend = originalSend;
/**
* Store request info on the XHR instance
*/
interface XHRWithBreadcrumb extends XMLHttpRequest {
hawkMethod?: string;
hawkUrl?: string;
hawkStart?: number;
hawkListenerAdded?: boolean;
}
XMLHttpRequest.prototype.open = function (this: XHRWithBreadcrumb, method: string, url: string | URL, ...args: unknown[]) {
this.hawkMethod = method;
this.hawkUrl = typeof url === 'string' ? url : url.href;
return originalOpen.apply(this, [method, url, ...args] as Parameters<typeof originalOpen>);
};
XMLHttpRequest.prototype.send = function (this: XHRWithBreadcrumb, body?: Document | XMLHttpRequestBodyInit | null) {
this.hawkStart = Date.now();
const onReadyStateChange = (): void => {
if (this.readyState === XMLHttpRequest.DONE) {
const duration = Date.now() - (this.hawkStart || Date.now());
const method = this.hawkMethod || 'GET';
const url = this.hawkUrl || '';
const status = this.status;
manager.addBreadcrumb({
type: 'request',
category: 'xhr',
message: `${status} ${method} ${url}`,
level: status >= 200 && status < 400 ? 'info' : 'error',
data: {
url,
method,
statusCode: status,
durationMs: duration,
},
}, {
xhr: this,
});
}
};
/**
* Add listener only once per XHR instance to prevent duplicates
*/
if (!this.hawkListenerAdded) {
this.addEventListener('readystatechange', onReadyStateChange);
this.hawkListenerAdded = true;
}
return originalSend.call(this, body);
};
}
/**
* Wrap History API to capture navigation breadcrumbs
*/
private wrapHistory(): void {
if (typeof history === 'undefined') {
return;
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
const manager = this;
let lastUrl = window.location.href;
const createNavigationBreadcrumb = (to: string): void => {
const from = lastUrl;
lastUrl = to;
manager.addBreadcrumb({
type: 'navigation',
category: 'navigation',
message: `Navigated to ${to}`,
level: 'info',
data: {
from,
to,
},
});
};
/**
* Wrap pushState
*/
this.originalPushState = history.pushState;
history.pushState = function (...args) {
const result = manager.originalPushState!.apply(this, args);
createNavigationBreadcrumb(window.location.href);
return result;
};
/**
* Wrap replaceState
*/
this.originalReplaceState = history.replaceState;
history.replaceState = function (...args) {
const result = manager.originalReplaceState!.apply(this, args);
createNavigationBreadcrumb(window.location.href);
return result;
};
/**
* Listen for popstate (back/forward)
*/
this.popstateHandler = (): void => {
createNavigationBreadcrumb(window.location.href);
};
window.addEventListener('popstate', this.popstateHandler);
}
/**
* Setup click event tracking for UI breadcrumbs
*/
private setupClickTracking(): void {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const manager = this;
this.clickHandler = (event: MouseEvent): void => {
const target = event.target as HTMLElement;
if (!target) {
return;
}
/**
* Build a simple selector
*/
const selector = buildElementSelector(target);
/**
* Get text content (limited)
*/
const text = (target.textContent || target.innerText || '').trim().substring(0, 50);
manager.addBreadcrumb({
type: 'ui',
category: 'ui.click',
message: `Click on ${selector}`,
level: 'info',
data: {
selector,
text,
tagName: target.tagName,
},
}, {
event,
});
};
document.addEventListener('click', this.clickHandler, {
capture: true,
passive: true });
}
}
/**
* Helper function to create a breadcrumb object
*
* @param message - The breadcrumb message
* @param options - Optional breadcrumb configuration
*/
export function createBreadcrumb(
message: string,
options?: {
type?: BreadcrumbType;
category?: string;
level?: BreadcrumbLevel;
data?: Record<string, Json>;
}
): Breadcrumb {
return {
timestamp: Date.now(),
message,
type: options?.type ?? 'default',
category: options?.category,
level: options?.level ?? 'info',
data: options?.data,
};
}