@buoy-gg/events 7.0.28 → 7.0.30

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.
@@ -1,2066 +0,0 @@
1
- /**
2
- * Event Export Formatter
3
- *
4
- * Utilities for generating formatted exports of unified events.
5
- * Optimized for LLM consumption with smart JSON parsing and diff support.
6
- */
7
-
8
- import type { UnifiedEvent, EventSource } from "../types";
9
- import type { EventsCopySettings } from "../types/copySettings";
10
-
11
- /**
12
- * Export summary statistics
13
- */
14
- export interface ExportSummary {
15
- totalEvents: number;
16
- success: number;
17
- pending: number;
18
- error: number;
19
- neutral: number;
20
- durationMs: number;
21
- sources: Set<EventSource>;
22
- }
23
-
24
- /**
25
- * Status icons for display
26
- */
27
- const STATUS_ICONS = {
28
- success: "\u2705", // ✅
29
- pending: "\u23F3", // ⏳
30
- error: "\u274C", // ❌
31
- neutral: "\u2796", // ➖
32
- } as const;
33
-
34
- /**
35
- * Status icons for plaintext (ASCII-safe)
36
- */
37
- const STATUS_ICONS_ASCII = {
38
- success: "[OK]",
39
- pending: "[...]",
40
- error: "[ERR]",
41
- neutral: "[-]",
42
- } as const;
43
-
44
- /**
45
- * Source labels for display
46
- */
47
- const SOURCE_LABELS: Record<EventSource, string> = {
48
- "storage-async": "Storage",
49
- "storage-mmkv": "MMKV",
50
- redux: "Redux",
51
- network: "Network",
52
- "react-query": "Query",
53
- "react-query-query": "Query",
54
- "react-query-mutation": "Mutation",
55
- route: "Route",
56
- zustand: "Zustand",
57
- jotai: "Jotai",
58
- render: "Render",
59
- };
60
-
61
- // ============================================================================
62
- // SMART JSON PARSING UTILITIES
63
- // ============================================================================
64
-
65
- /**
66
- * Try to parse a string as JSON, return original if not valid JSON
67
- */
68
- function tryParseJson(value: unknown): unknown {
69
- if (typeof value !== "string") return value;
70
-
71
- // Check if it looks like JSON (starts with { or [)
72
- const trimmed = value.trim();
73
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return value;
74
-
75
- try {
76
- return JSON.parse(value);
77
- } catch {
78
- return value;
79
- }
80
- }
81
-
82
- /**
83
- * Recursively parse JSON strings within an object
84
- */
85
- function deepParseJsonStrings(obj: unknown): unknown {
86
- if (obj === null || obj === undefined) return obj;
87
-
88
- if (typeof obj === "string") {
89
- return tryParseJson(obj);
90
- }
91
-
92
- if (Array.isArray(obj)) {
93
- return obj.map(deepParseJsonStrings);
94
- }
95
-
96
- if (typeof obj === "object") {
97
- const result: Record<string, unknown> = {};
98
- for (const [key, value] of Object.entries(obj)) {
99
- result[key] = deepParseJsonStrings(value);
100
- }
101
- return result;
102
- }
103
-
104
- return obj;
105
- }
106
-
107
- /**
108
- * Fields to strip when stripVerboseFields is enabled
109
- * These add noise to LLM analysis without providing actionable info
110
- */
111
- const VERBOSE_FIELDS = new Set([
112
- "image",
113
- "imageUrl",
114
- "imageURL",
115
- "image_url",
116
- "thumbnail",
117
- "thumbnailUrl",
118
- "thumbnail_url",
119
- "icon",
120
- "iconUrl",
121
- "avatar",
122
- "avatarUrl",
123
- "photo",
124
- "photoUrl",
125
- "picture",
126
- "pictureUrl",
127
- "description",
128
- "desc",
129
- "longDescription",
130
- "shortDescription",
131
- "meta_description",
132
- ]);
133
-
134
- /**
135
- * Recursively strip verbose fields from an object
136
- */
137
- function stripVerboseFieldsFromObject(obj: unknown): unknown {
138
- if (obj === null || obj === undefined) return obj;
139
-
140
- if (Array.isArray(obj)) {
141
- return obj.map(stripVerboseFieldsFromObject);
142
- }
143
-
144
- if (typeof obj === "object") {
145
- const result: Record<string, unknown> = {};
146
- for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {
147
- // Skip verbose fields
148
- if (VERBOSE_FIELDS.has(key)) continue;
149
-
150
- // Skip fields that look like image URLs
151
- if (typeof value === "string" && isImageUrl(value)) continue;
152
-
153
- result[key] = stripVerboseFieldsFromObject(value);
154
- }
155
- return result;
156
- }
157
-
158
- return obj;
159
- }
160
-
161
- /**
162
- * Check if a string looks like an image URL
163
- */
164
- function isImageUrl(value: string): boolean {
165
- if (!value.startsWith("http")) return false;
166
- const lower = value.toLowerCase();
167
- return (
168
- lower.includes("/photo") ||
169
- lower.includes("/image") ||
170
- lower.includes("unsplash.com") ||
171
- lower.includes("cloudinary.com") ||
172
- lower.includes("imgur.com") ||
173
- /\.(jpg|jpeg|png|gif|webp|svg|bmp)(\?|$)/i.test(value)
174
- );
175
- }
176
-
177
- /**
178
- * Format timestamp - convert Date objects to ISO strings
179
- */
180
- function formatTimestampValue(value: unknown): unknown {
181
- if (value instanceof Date) {
182
- return value.toISOString();
183
- }
184
- // Check if it's a date-like object that serializes to {}
185
- if (value && typeof value === "object" && Object.keys(value).length === 0) {
186
- return undefined; // Remove empty objects (failed Date serialization)
187
- }
188
- return value;
189
- }
190
-
191
- /**
192
- * Compute array diff - return only added/removed items for cleaner output
193
- */
194
- function computeArrayDiff(
195
- prevArray: unknown[],
196
- newArray: unknown[]
197
- ): { added: unknown[]; removed: unknown[]; unchanged: number } | null {
198
- // Get identifiers for comparison
199
- const getId = (item: unknown): string | null => {
200
- if (typeof item !== "object" || item === null) return null;
201
- const obj = item as Record<string, unknown>;
202
- if (typeof obj.id === "string") return obj.id;
203
- if (typeof obj.orderId === "string") return obj.orderId;
204
- if (typeof obj.key === "string") return obj.key;
205
- return null;
206
- };
207
-
208
- const prevIds = new Set(prevArray.map(getId).filter(Boolean));
209
- const newIds = new Set(newArray.map(getId).filter(Boolean));
210
-
211
- // Can't diff without IDs
212
- if (prevIds.size === 0 && newIds.size === 0) return null;
213
-
214
- const added = newArray.filter(item => {
215
- const id = getId(item);
216
- return id && !prevIds.has(id);
217
- });
218
-
219
- const removed = prevArray.filter(item => {
220
- const id = getId(item);
221
- return id && !newIds.has(id);
222
- });
223
-
224
- const unchanged = newArray.length - added.length;
225
-
226
- // Only return diff if it's simpler than showing full arrays
227
- if (added.length + removed.length < prevArray.length && added.length + removed.length < newArray.length) {
228
- return { added, removed, unchanged };
229
- }
230
-
231
- return null;
232
- }
233
-
234
- /**
235
- * Format Storage event data with smart parsing
236
- */
237
- function formatStorageData(
238
- data: Record<string, unknown>,
239
- settings: EventsCopySettings
240
- ): Record<string, unknown> {
241
- const result: Record<string, unknown> = {};
242
-
243
- // Copy fields, fixing timestamps
244
- if (data.action) result.action = data.action;
245
- if (data.storageType) result.storageType = data.storageType;
246
-
247
- // Fix timestamp serialization
248
- if (data.timestamp !== undefined) {
249
- const formattedTs = formatTimestampValue(data.timestamp);
250
- if (formattedTs !== undefined) {
251
- result.timestamp = formattedTs;
252
- }
253
- }
254
-
255
- if (data.data) {
256
- const innerData = { ...(data.data as Record<string, unknown>) };
257
-
258
- // Parse value and prevValue if they're JSON strings
259
- if (settings.smartJsonParsing) {
260
- if (innerData.value !== undefined) {
261
- innerData.value = tryParseJson(innerData.value);
262
- }
263
- if (innerData.prevValue !== undefined) {
264
- innerData.prevValue = tryParseJson(innerData.prevValue);
265
- }
266
- }
267
-
268
- // For array values, try to show just the diff
269
- if (settings.showStorageDiff && Array.isArray(innerData.value) && Array.isArray(innerData.prevValue)) {
270
- const diff = computeArrayDiff(innerData.prevValue as unknown[], innerData.value as unknown[]);
271
- if (diff) {
272
- // Replace full arrays with diff
273
- const diffData: Record<string, unknown> = { key: innerData.key };
274
-
275
- if (diff.added.length > 0) {
276
- diffData.added = diff.added;
277
- }
278
- if (diff.removed.length > 0) {
279
- diffData.removed = diff.removed;
280
- }
281
- if (diff.unchanged > 0) {
282
- diffData.unchangedCount = diff.unchanged;
283
- }
284
-
285
- result.data = diffData;
286
- return result;
287
- }
288
- }
289
-
290
- result.data = innerData;
291
- }
292
-
293
- return result;
294
- }
295
-
296
- /**
297
- * Format Redux event data - filter to only changed slices
298
- */
299
- function formatReduxData(
300
- data: Record<string, unknown>,
301
- settings: EventsCopySettings
302
- ): Record<string, unknown> {
303
- if (!settings.reduxChangedOnly) {
304
- return settings.smartJsonParsing ? deepParseJsonStrings(data) as Record<string, unknown> : data;
305
- }
306
-
307
- const result: Record<string, unknown> = {};
308
-
309
- // Always include action info
310
- if (data.type) result.type = data.type;
311
- if (data.payload) result.payload = settings.smartJsonParsing ? deepParseJsonStrings(data.payload) : data.payload;
312
- if (data.sliceName) result.sliceName = data.sliceName;
313
- if (data.actionName) result.actionName = data.actionName;
314
- if (data.duration) result.duration = data.duration;
315
-
316
- // Include state change info
317
- if (data.hasStateChange !== undefined) result.hasStateChange = data.hasStateChange;
318
- if (data.diffSummary) result.diffSummary = data.diffSummary;
319
- if (data.changedKeysCount !== undefined) result.changedKeysCount = data.changedKeysCount;
320
-
321
- // Only include state if there were changes
322
- if (data.hasStateChange === true) {
323
- // Try to extract only the changed slice
324
- const sliceName = data.sliceName as string | undefined;
325
- if (sliceName && data.prevState && data.nextState) {
326
- const prevState = data.prevState as Record<string, unknown>;
327
- const nextState = data.nextState as Record<string, unknown>;
328
-
329
- if (prevState[sliceName] !== undefined || nextState[sliceName] !== undefined) {
330
- result.stateChange = {
331
- slice: sliceName,
332
- before: prevState[sliceName],
333
- after: nextState[sliceName],
334
- };
335
- }
336
- }
337
- }
338
-
339
- return result;
340
- }
341
-
342
- /**
343
- * Get item identifier (name, id, or key) from an object
344
- */
345
- function getItemIdentifier(item: unknown): string | null {
346
- if (typeof item !== "object" || item === null) return null;
347
- const obj = item as Record<string, unknown>;
348
- if (typeof obj.name === "string") return obj.name;
349
- if (typeof obj.id === "string") return obj.id;
350
- if (typeof obj.key === "string") return obj.key;
351
- return null;
352
- }
353
-
354
- /**
355
- * Generate a simple diff summary for storage values
356
- */
357
- function generateStorageDiffSummary(
358
- prevValue: unknown,
359
- newValue: unknown
360
- ): string | null {
361
- // Parse if strings
362
- const prev = typeof prevValue === "string" ? tryParseJson(prevValue) : prevValue;
363
- const next = typeof newValue === "string" ? tryParseJson(newValue) : newValue;
364
-
365
- // Handle null/undefined cases
366
- if ((prev === null || prev === undefined) && next !== null && next !== undefined) return "Created";
367
- if (prev !== null && prev !== undefined && (next === null || next === undefined)) return "Deleted";
368
-
369
- // Handle arrays (common for cart-like data)
370
- if (Array.isArray(prev) && Array.isArray(next)) {
371
- const prevLen = prev.length;
372
- const nextLen = next.length;
373
-
374
- // Get identifiers for comparison
375
- const prevIds = prev.map(getItemIdentifier).filter(Boolean) as string[];
376
- const nextIds = next.map(getItemIdentifier).filter(Boolean) as string[];
377
-
378
- // Check if items were replaced (same count but different items)
379
- if (prevLen === nextLen && prevLen > 0) {
380
- const prevSet = new Set(prevIds);
381
- const nextSet = new Set(nextIds);
382
- const kept = prevIds.filter(id => nextSet.has(id));
383
-
384
- if (kept.length === 0 && prevIds.length > 0 && nextIds.length > 0) {
385
- // Complete replacement!
386
- return `⚠️ Replaced: [${prevIds.join(", ")}] → [${nextIds.join(", ")}]`;
387
- }
388
-
389
- if (kept.length < prevLen) {
390
- const removed = prevIds.filter(id => !nextSet.has(id));
391
- const added = nextIds.filter(id => !prevSet.has(id));
392
- return `Changed: -${removed.join(", ")} +${added.join(", ")}`;
393
- }
394
- }
395
-
396
- if (prevLen === 0 && nextLen > 0) {
397
- if (nextIds.length > 0) {
398
- return `Added: [${nextIds.join(", ")}]`;
399
- }
400
- return `Added ${nextLen} item${nextLen > 1 ? "s" : ""}`;
401
- }
402
-
403
- if (prevLen > 0 && nextLen === 0) {
404
- if (prevIds.length > 0) {
405
- return `Removed all: [${prevIds.join(", ")}]`;
406
- }
407
- return `Removed all ${prevLen} item${prevLen > 1 ? "s" : ""}`;
408
- }
409
-
410
- if (nextLen > prevLen) {
411
- const prevSet = new Set(prevIds);
412
- const added = nextIds.filter(id => !prevSet.has(id));
413
- if (added.length > 0) {
414
- return `Added: [${added.join(", ")}] (${prevLen} → ${nextLen})`;
415
- }
416
- return `Added ${nextLen - prevLen} item${nextLen - prevLen > 1 ? "s" : ""} (${prevLen} → ${nextLen})`;
417
- }
418
-
419
- if (nextLen < prevLen) {
420
- const nextSet = new Set(nextIds);
421
- const removed = prevIds.filter(id => !nextSet.has(id));
422
- if (removed.length > 0) {
423
- return `Removed: [${removed.join(", ")}] (${prevLen} → ${nextLen})`;
424
- }
425
- return `Removed ${prevLen - nextLen} item${prevLen - nextLen > 1 ? "s" : ""} (${prevLen} → ${nextLen})`;
426
- }
427
-
428
- return `Updated (${nextLen} item${nextLen > 1 ? "s" : ""})`;
429
- }
430
-
431
- // Handle objects
432
- if (typeof prev === "object" && typeof next === "object" && prev && next) {
433
- const prevKeys = Object.keys(prev);
434
- const nextKeys = Object.keys(next);
435
- const addedKeys = nextKeys.filter(k => !prevKeys.includes(k));
436
- const removedKeys = prevKeys.filter(k => !nextKeys.includes(k));
437
-
438
- if (addedKeys.length > 0 && removedKeys.length > 0) {
439
- return `+${addedKeys.length} -${removedKeys.length} keys`;
440
- }
441
- if (addedKeys.length > 0) return `Added: ${addedKeys.join(", ")}`;
442
- if (removedKeys.length > 0) return `Removed: ${removedKeys.join(", ")}`;
443
- return "Updated";
444
- }
445
-
446
- return null;
447
- }
448
-
449
- /**
450
- * Format React Query event data - remove verbose internal state
451
- */
452
- function formatReactQueryData(
453
- data: Record<string, unknown>,
454
- settings: EventsCopySettings
455
- ): Record<string, unknown> {
456
- const result: Record<string, unknown> = {};
457
-
458
- // Core identifiers
459
- if (data.id) result.id = data.id;
460
- if (data.type) result.type = data.type;
461
- if (data.timestamp) result.timestamp = data.timestamp;
462
-
463
- // Query-specific fields
464
- if (data.queryKey) result.queryKey = data.queryKey;
465
- if (data.mutationKey) result.mutationKey = data.mutationKey;
466
- if (data.mutationId) result.mutationId = data.mutationId;
467
- if (data.duration) result.duration = data.duration;
468
-
469
- // For success events, include the data (not duplicated)
470
- if (data.queryData !== undefined) {
471
- result.data = settings.smartJsonParsing ? deepParseJsonStrings(data.queryData) : data.queryData;
472
- }
473
-
474
- // For mutation events, include variables
475
- if (data.variables !== undefined) {
476
- result.variables = settings.smartJsonParsing ? deepParseJsonStrings(data.variables) : data.variables;
477
- }
478
-
479
- // For errors, include error info (try to extract message)
480
- if (data.queryError !== undefined) {
481
- const error = data.queryError as Record<string, unknown>;
482
- if (error && typeof error === "object") {
483
- result.error = error.message || error.name || error;
484
- } else {
485
- result.error = data.queryError;
486
- }
487
- }
488
-
489
- if (data.mutationError !== undefined) {
490
- const error = data.mutationError as Record<string, unknown>;
491
- if (error && typeof error === "object") {
492
- result.error = error.message || error.name || error;
493
- } else {
494
- result.error = data.mutationError;
495
- }
496
- }
497
-
498
- // Include status from query/mutation state if available
499
- if (data.query && typeof data.query === "object") {
500
- const query = data.query as Record<string, unknown>;
501
- if (query.state && typeof query.state === "object") {
502
- const state = query.state as Record<string, unknown>;
503
- if (state.status) result.status = state.status;
504
- if (state.fetchStatus) result.fetchStatus = state.fetchStatus;
505
- if (state.error) {
506
- const stateError = state.error as Record<string, unknown>;
507
- if (stateError && typeof stateError === "object") {
508
- result.error = stateError.message || stateError.name || stateError;
509
- }
510
- }
511
- }
512
- }
513
-
514
- if (data.mutation && typeof data.mutation === "object") {
515
- const mutation = data.mutation as Record<string, unknown>;
516
- if (mutation.state && typeof mutation.state === "object") {
517
- const state = mutation.state as Record<string, unknown>;
518
- if (state.status) result.status = state.status;
519
- if (state.failureCount) result.failureCount = state.failureCount;
520
- if (state.error) {
521
- const stateError = state.error as Record<string, unknown>;
522
- if (stateError && typeof stateError === "object") {
523
- result.error = stateError.message || stateError.name || stateError;
524
- }
525
- }
526
- if (state.failureReason) {
527
- const reason = state.failureReason as Record<string, unknown>;
528
- if (reason && typeof reason === "object") {
529
- result.failureReason = reason.message || reason.name || reason;
530
- }
531
- }
532
- }
533
- }
534
-
535
- return result;
536
- }
537
-
538
- /**
539
- * Format event data based on source type and settings
540
- */
541
- function formatEventData(
542
- event: UnifiedEvent,
543
- settings: EventsCopySettings
544
- ): unknown {
545
- const data = event.originalEvent as Record<string, unknown>;
546
- if (!data) return null;
547
-
548
- let result: unknown;
549
-
550
- // Storage events
551
- if (event.source === "storage-async" || event.source === "storage-mmkv") {
552
- result = formatStorageData(data, settings);
553
- }
554
- // Redux events
555
- else if (event.source === "redux") {
556
- result = formatReduxData(data, settings);
557
- }
558
- // React Query events
559
- else if (event.source === "react-query" || event.source === "react-query-query" || event.source === "react-query-mutation") {
560
- result = formatReactQueryData(data, settings);
561
- }
562
- // Other events - just apply smart parsing
563
- else if (settings.smartJsonParsing) {
564
- result = deepParseJsonStrings(data);
565
- } else {
566
- result = data;
567
- }
568
-
569
- // Strip verbose fields if enabled
570
- if (settings.stripVerboseFields && result) {
571
- result = stripVerboseFieldsFromObject(result);
572
- }
573
-
574
- return result;
575
- }
576
-
577
- /**
578
- * Get summary statistics for events
579
- */
580
- export function getExportSummary(events: UnifiedEvent[]): ExportSummary {
581
- const summary: ExportSummary = {
582
- totalEvents: events.length,
583
- success: 0,
584
- pending: 0,
585
- error: 0,
586
- neutral: 0,
587
- durationMs: 0,
588
- sources: new Set(),
589
- };
590
-
591
- if (events.length === 0) return summary;
592
-
593
- let minTimestamp = Infinity;
594
- let maxTimestamp = -Infinity;
595
-
596
- for (const event of events) {
597
- // Count by status
598
- summary[event.status]++;
599
-
600
- // Track sources
601
- summary.sources.add(event.source);
602
-
603
- // Track time range
604
- if (event.timestamp < minTimestamp) minTimestamp = event.timestamp;
605
- if (event.timestamp > maxTimestamp) maxTimestamp = event.timestamp;
606
- }
607
-
608
- summary.durationMs = maxTimestamp - minTimestamp;
609
-
610
- return summary;
611
- }
612
-
613
- /**
614
- * Filter events based on settings
615
- */
616
- export function filterEvents(
617
- events: UnifiedEvent[],
618
- settings: EventsCopySettings
619
- ): UnifiedEvent[] {
620
- let filtered = [...events];
621
-
622
- // Filter by status
623
- if (settings.filterMode !== "all") {
624
- filtered = filtered.filter((event) => {
625
- switch (settings.filterMode) {
626
- case "errors":
627
- return event.status === "error";
628
- case "success":
629
- return event.status === "success";
630
- case "pending":
631
- return event.status === "pending";
632
- default:
633
- return true;
634
- }
635
- });
636
- }
637
-
638
- // Filter by sources
639
- if (settings.filterSources.length > 0) {
640
- const sourceSet = new Set(settings.filterSources);
641
- filtered = filtered.filter((event) => sourceSet.has(event.source));
642
- }
643
-
644
- return filtered;
645
- }
646
-
647
- /**
648
- * Format relative timestamp
649
- */
650
- function formatRelativeTime(ms: number): string {
651
- if (ms < 1000) return `+${ms}ms`;
652
- if (ms < 60000) return `+${(ms / 1000).toFixed(1)}s`;
653
- return `+${(ms / 60000).toFixed(1)}m`;
654
- }
655
-
656
- /**
657
- * Format absolute timestamp
658
- */
659
- function formatAbsoluteTime(timestamp: number): string {
660
- const date = new Date(timestamp);
661
- return date.toISOString();
662
- }
663
-
664
- /**
665
- * Format timestamp based on settings
666
- */
667
- function formatTimestamp(
668
- timestamp: number,
669
- baseTimestamp: number,
670
- format: EventsCopySettings["timestampFormat"]
671
- ): string {
672
- const relative = formatRelativeTime(timestamp - baseTimestamp);
673
- const absolute = formatAbsoluteTime(timestamp);
674
-
675
- switch (format) {
676
- case "relative":
677
- return relative;
678
- case "absolute":
679
- return absolute;
680
- case "both":
681
- return `${relative} (${absolute})`;
682
- }
683
- }
684
-
685
- /**
686
- * Early-aborting JSON-size probe: approximate byte count, bailing as soon as
687
- * `limit` is exceeded — O(limit), never O(payload). Measuring with
688
- * JSON.stringify(data).length meant enforcing a 5KB cap could serialize a
689
- * 190MB state tree first, blocking the JS thread for seconds per event.
690
- */
691
- function approxJsonBytesOver(
692
- value: unknown,
693
- limit: number
694
- ): { over: boolean; approxBytes: number } {
695
- let bytes = 0;
696
- const stack: unknown[] = [value];
697
- const seen = new Set<object>();
698
- while (stack.length > 0) {
699
- if (bytes > limit) return { over: true, approxBytes: bytes };
700
- const v = stack.pop();
701
- if (v === null || v === undefined) bytes += 4;
702
- else if (typeof v === "string") bytes += v.length + 2;
703
- else if (typeof v === "number") bytes += 8;
704
- else if (typeof v === "boolean") bytes += 5;
705
- else if (typeof v === "object") {
706
- if (seen.has(v as object)) continue;
707
- seen.add(v as object);
708
- if (Array.isArray(v)) {
709
- bytes += 2 + v.length;
710
- for (let i = 0; i < v.length; i++) stack.push(v[i]);
711
- } else {
712
- bytes += 2;
713
- for (const k in v as Record<string, unknown>) {
714
- bytes += k.length + 4;
715
- stack.push((v as Record<string, unknown>)[k]);
716
- }
717
- }
718
- } else bytes += 4;
719
- }
720
- return { over: bytes > limit, approxBytes: bytes };
721
- }
722
-
723
- /**
724
- * Truncate data based on size threshold
725
- */
726
- function truncateData(
727
- data: unknown,
728
- thresholdKB: number
729
- ): { data: unknown; truncated: boolean } {
730
- if (thresholdKB === -1) {
731
- return { data, truncated: false };
732
- }
733
-
734
- // Cheap probe first — never serialize a payload just to learn it's huge.
735
- const { over, approxBytes } = approxJsonBytesOver(data, thresholdKB * 1024);
736
- if (over) {
737
- return {
738
- data: `[Data truncated - ≥${(approxBytes / 1024).toFixed(1)}KB exceeds ${thresholdKB}KB limit]`,
739
- truncated: true,
740
- };
741
- }
742
-
743
- try {
744
- // Under the cap: a real stringify is bounded by the threshold and also
745
- // validates serializability (cycles etc.).
746
- JSON.stringify(data);
747
- return { data, truncated: false };
748
- } catch {
749
- return { data: "[Unable to serialize data]", truncated: true };
750
- }
751
- }
752
-
753
- /**
754
- * Estimate export size in bytes
755
- */
756
- export function estimateExportSize(
757
- events: UnifiedEvent[],
758
- settings: EventsCopySettings
759
- ): number {
760
- let size = 0;
761
-
762
- for (const event of events) {
763
- // Basic event info
764
- if (settings.includeSource) size += 20;
765
- if (settings.includeStatus) size += 10;
766
- if (settings.includeTitle) size += (event.title?.length || 0) + 10;
767
- if (settings.includeSubtitle) size += (event.subtitle?.length || 0) + 10;
768
- if (settings.includeCorrelation) size += 20;
769
- if (settings.includeDuration) size += 15;
770
- size += 30; // Timestamp
771
-
772
- // Event data — probe with an early-abort cap instead of fully
773
- // serializing (an estimate never justifies an O(payload) stringify).
774
- if (settings.includeEventData && event.originalEvent) {
775
- const cap =
776
- settings.dataSizeThreshold === -1
777
- ? 1024 * 1024 // no threshold: cap the ESTIMATE at 1MB per event
778
- : settings.dataSizeThreshold * 1024;
779
- const { approxBytes } = approxJsonBytesOver(event.originalEvent, cap);
780
- size += Math.min(approxBytes, cap);
781
- }
782
- }
783
-
784
- // Summary header
785
- if (settings.includeSummaryHeader) size += 100;
786
- if (settings.includeTotalDuration) size += 50;
787
-
788
- // Format overhead
789
- if (settings.format === "markdown") size *= 1.2;
790
- if (settings.format === "json") size *= 1.3;
791
-
792
- return Math.round(size);
793
- }
794
-
795
- /**
796
- * Generate a compact one-liner for an event
797
- */
798
- function formatCompactEvent(
799
- event: UnifiedEvent,
800
- baseTimestamp: number,
801
- settings: EventsCopySettings
802
- ): string {
803
- const parts: string[] = [];
804
-
805
- // Timestamp
806
- const timestamp = formatTimestamp(event.timestamp, baseTimestamp, settings.timestampFormat);
807
- parts.push(`\`${timestamp}\``);
808
-
809
- // Status icon
810
- if (settings.includeStatus) {
811
- parts.push(STATUS_ICONS[event.status]);
812
- }
813
-
814
- // Source
815
- if (settings.includeSource) {
816
- parts.push(`**${SOURCE_LABELS[event.source]}**`);
817
- }
818
-
819
- // Title
820
- if (settings.includeTitle) {
821
- parts.push(event.title);
822
- }
823
-
824
- // For storage events, add a brief summary
825
- if (settings.showStorageDiff && (event.source === "storage-async" || event.source === "storage-mmkv")) {
826
- const data = event.originalEvent as Record<string, unknown>;
827
- if (data?.data) {
828
- const innerData = data.data as Record<string, unknown>;
829
- const diff = generateStorageDiffSummary(innerData.prevValue, innerData.value);
830
- if (diff) {
831
- parts.push(`→ ${diff}`);
832
- }
833
- }
834
- }
835
-
836
- // For Redux, show if there was a state change
837
- if (event.source === "redux") {
838
- const data = event.originalEvent as Record<string, unknown>;
839
- if (data?.hasStateChange === false) {
840
- parts.push("(no state change)");
841
- }
842
- }
843
-
844
- // Subtitle as brief context
845
- if (settings.includeSubtitle && event.subtitle) {
846
- parts.push(`- ${event.subtitle}`);
847
- }
848
-
849
- return parts.join(" ");
850
- }
851
-
852
- /**
853
- * Generate storage diff block for markdown
854
- */
855
- function generateStorageDiffBlock(
856
- event: UnifiedEvent,
857
- settings: EventsCopySettings
858
- ): string[] {
859
- const lines: string[] = [];
860
- const data = event.originalEvent as Record<string, unknown>;
861
-
862
- if (!data?.data) return lines;
863
-
864
- const innerData = data.data as Record<string, unknown>;
865
- const prevValue = settings.smartJsonParsing ? tryParseJson(innerData.prevValue) : innerData.prevValue;
866
- const newValue = settings.smartJsonParsing ? tryParseJson(innerData.value) : innerData.value;
867
-
868
- // Generate diff summary
869
- const diffSummary = generateStorageDiffSummary(innerData.prevValue, innerData.value);
870
- if (diffSummary) {
871
- lines.push(` **Change:** ${diffSummary}`);
872
- }
873
-
874
- // Show before/after for arrays
875
- if (Array.isArray(prevValue) && Array.isArray(newValue)) {
876
- // Show item names if available
877
- const prevNames = prevValue.map((item: unknown) => {
878
- if (typeof item === "object" && item && "name" in item) return (item as { name: string }).name;
879
- return null;
880
- }).filter(Boolean);
881
-
882
- const newNames = newValue.map((item: unknown) => {
883
- if (typeof item === "object" && item && "name" in item) return (item as { name: string }).name;
884
- return null;
885
- }).filter(Boolean);
886
-
887
- if (prevNames.length > 0 || newNames.length > 0) {
888
- if (prevNames.length > 0) {
889
- lines.push(` Before: [${prevNames.join(", ")}]`);
890
- }
891
- lines.push(` After: [${newNames.join(", ")}]`);
892
- }
893
- }
894
-
895
- return lines;
896
- }
897
-
898
- /**
899
- * Generate Markdown export
900
- */
901
- export function generateMarkdownExport(
902
- events: UnifiedEvent[],
903
- settings: EventsCopySettings
904
- ): string {
905
- const filtered = filterEvents(events, settings);
906
- if (filtered.length === 0) return "No events to export.";
907
-
908
- // Sort by timestamp (oldest first for timeline)
909
- const sorted = [...filtered].sort((a, b) => a.timestamp - b.timestamp);
910
- const baseTimestamp = sorted[0].timestamp;
911
- const summary = getExportSummary(sorted);
912
-
913
- const lines: string[] = [];
914
-
915
- // Header
916
- lines.push("## Event Flow");
917
-
918
- // Summary line
919
- if (settings.includeSummaryHeader || settings.includeTotalDuration) {
920
- const parts: string[] = [];
921
-
922
- if (settings.includeTotalDuration) {
923
- parts.push(`**Duration:** ${formatRelativeTime(summary.durationMs).replace("+", "")}`);
924
- }
925
-
926
- parts.push(`**Events:** ${summary.totalEvents}`);
927
-
928
- if (settings.includeSummaryHeader) {
929
- const statusParts: string[] = [];
930
- if (summary.success > 0) statusParts.push(`${summary.success} ${STATUS_ICONS.success}`);
931
- if (summary.pending > 0) statusParts.push(`${summary.pending} ${STATUS_ICONS.pending}`);
932
- if (summary.error > 0) statusParts.push(`${summary.error} ${STATUS_ICONS.error}`);
933
- if (summary.neutral > 0) statusParts.push(`${summary.neutral} ${STATUS_ICONS.neutral}`);
934
- if (statusParts.length > 0) {
935
- parts.push(`**Status:** ${statusParts.join(" ")}`);
936
- }
937
- }
938
-
939
- lines.push(parts.join(" | "));
940
- }
941
-
942
- lines.push("");
943
- lines.push("### Timeline");
944
- lines.push("");
945
-
946
- // Compact mode: one line per event
947
- if (settings.compactMode) {
948
- sorted.forEach((event, index) => {
949
- lines.push(`${index + 1}. ${formatCompactEvent(event, baseTimestamp, settings)}`);
950
- });
951
- return lines.join("\n");
952
- }
953
-
954
- // Full mode: detailed events
955
- sorted.forEach((event, index) => {
956
- const parts: string[] = [];
957
-
958
- // Line number and timestamp
959
- const timestamp = formatTimestamp(event.timestamp, baseTimestamp, settings.timestampFormat);
960
- parts.push(`${index + 1}. \`${timestamp}\``);
961
-
962
- // Status icon
963
- if (settings.includeStatus) {
964
- parts.push(STATUS_ICONS[event.status]);
965
- }
966
-
967
- // Source
968
- if (settings.includeSource) {
969
- parts.push(`**${SOURCE_LABELS[event.source]}**`);
970
- }
971
-
972
- // Title
973
- if (settings.includeTitle) {
974
- parts.push(event.title);
975
- }
976
-
977
- // Correlation
978
- if (settings.includeCorrelation && event.correlationId && event.sequenceInGroup) {
979
- parts.push(`(${event.sequenceInGroup})`);
980
- }
981
-
982
- lines.push(parts.join(" "));
983
-
984
- // Subtitle on next line
985
- if (settings.includeSubtitle && event.subtitle) {
986
- lines.push(` \u2514\u2500 ${event.subtitle}`);
987
- }
988
-
989
- // Storage diff summary (if enabled and no full data)
990
- if (settings.showStorageDiff && !settings.includeEventData) {
991
- if (event.source === "storage-async" || event.source === "storage-mmkv") {
992
- const diffLines = generateStorageDiffBlock(event, settings);
993
- lines.push(...diffLines);
994
- }
995
- }
996
-
997
- // Event data (formatted with smart parsing)
998
- if (settings.includeEventData && event.originalEvent) {
999
- // Use smart formatting
1000
- const formattedData = formatEventData(event, settings);
1001
-
1002
- const { data, truncated } = truncateData(
1003
- formattedData,
1004
- settings.dataSizeThreshold
1005
- );
1006
-
1007
- if (truncated) {
1008
- lines.push(` \u2514\u2500 ${data}`);
1009
- } else {
1010
- // Add storage diff annotation before the JSON block
1011
- if (settings.showStorageDiff && (event.source === "storage-async" || event.source === "storage-mmkv")) {
1012
- const originalData = event.originalEvent as Record<string, unknown>;
1013
- if (originalData?.data) {
1014
- const innerData = originalData.data as Record<string, unknown>;
1015
- const diffSummary = generateStorageDiffSummary(innerData.prevValue, innerData.value);
1016
- if (diffSummary) {
1017
- lines.push(` **Change:** ${diffSummary}`);
1018
- }
1019
- }
1020
- }
1021
-
1022
- lines.push(" ```json");
1023
- lines.push(` ${JSON.stringify(data, null, 2).split("\n").join("\n ")}`);
1024
- lines.push(" ```");
1025
- }
1026
- }
1027
-
1028
- lines.push("");
1029
- });
1030
-
1031
- // Error details section
1032
- const errors = sorted.filter((e) => e.status === "error");
1033
- if (errors.length > 0 && settings.includeEventData) {
1034
- lines.push("---");
1035
- lines.push("");
1036
- lines.push("### Errors");
1037
- lines.push("");
1038
-
1039
- for (const error of errors) {
1040
- const timestamp = formatTimestamp(error.timestamp, baseTimestamp, settings.timestampFormat);
1041
- lines.push(`**${error.title}** (${timestamp})`);
1042
-
1043
- if (error.originalEvent) {
1044
- const formattedData = formatEventData(error, settings);
1045
- const { data, truncated } = truncateData(
1046
- formattedData,
1047
- settings.dataSizeThreshold
1048
- );
1049
-
1050
- if (!truncated) {
1051
- lines.push("```json");
1052
- lines.push(JSON.stringify(data, null, 2));
1053
- lines.push("```");
1054
- }
1055
- }
1056
-
1057
- lines.push("");
1058
- }
1059
- }
1060
-
1061
- return lines.join("\n");
1062
- }
1063
-
1064
- /**
1065
- * Generate JSON export
1066
- */
1067
- export function generateJsonExport(
1068
- events: UnifiedEvent[],
1069
- settings: EventsCopySettings
1070
- ): string {
1071
- const filtered = filterEvents(events, settings);
1072
- if (filtered.length === 0) return "[]";
1073
-
1074
- // Sort by timestamp (oldest first)
1075
- const sorted = [...filtered].sort((a, b) => a.timestamp - b.timestamp);
1076
- const baseTimestamp = sorted[0].timestamp;
1077
- const summary = getExportSummary(sorted);
1078
-
1079
- const exportData: Record<string, unknown> = {
1080
- exportedAt: new Date().toISOString(),
1081
- };
1082
-
1083
- // Summary
1084
- if (settings.includeSummaryHeader) {
1085
- exportData.summary = {
1086
- totalEvents: summary.totalEvents,
1087
- success: summary.success,
1088
- pending: summary.pending,
1089
- error: summary.error,
1090
- neutral: summary.neutral,
1091
- durationMs: summary.durationMs,
1092
- sources: Array.from(summary.sources),
1093
- };
1094
- }
1095
-
1096
- // Events
1097
- exportData.events = sorted.map((event) => {
1098
- const eventData: Record<string, unknown> = {};
1099
-
1100
- // Timestamp
1101
- eventData.timestamp = formatAbsoluteTime(event.timestamp);
1102
- if (settings.timestampFormat === "relative" || settings.timestampFormat === "both") {
1103
- eventData.relativeMs = event.timestamp - baseTimestamp;
1104
- }
1105
-
1106
- // Event info
1107
- if (settings.includeSource) eventData.source = event.source;
1108
- if (settings.includeStatus) eventData.status = event.status;
1109
- if (settings.includeTitle) eventData.title = event.title;
1110
- if (settings.includeSubtitle) eventData.subtitle = event.subtitle;
1111
- if (settings.includeCorrelation && event.correlationId) {
1112
- eventData.correlationId = event.correlationId;
1113
- eventData.sequenceInGroup = event.sequenceInGroup;
1114
- }
1115
-
1116
- // Event data (with smart formatting)
1117
- if (settings.includeEventData && event.originalEvent) {
1118
- const formattedData = formatEventData(event, settings);
1119
- const { data, truncated } = truncateData(
1120
- formattedData,
1121
- settings.dataSizeThreshold
1122
- );
1123
- eventData.data = data;
1124
- if (truncated) eventData.dataTruncated = true;
1125
-
1126
- // Add diff summary for storage events
1127
- if (settings.showStorageDiff && (event.source === "storage-async" || event.source === "storage-mmkv")) {
1128
- const originalData = event.originalEvent as Record<string, unknown>;
1129
- if (originalData?.data) {
1130
- const innerData = originalData.data as Record<string, unknown>;
1131
- const diffSummary = generateStorageDiffSummary(innerData.prevValue, innerData.value);
1132
- if (diffSummary) {
1133
- eventData.changeSummary = diffSummary;
1134
- }
1135
- }
1136
- }
1137
- }
1138
-
1139
- return eventData;
1140
- });
1141
-
1142
- return JSON.stringify(exportData, null, 2);
1143
- }
1144
-
1145
- /**
1146
- * Generate plaintext export
1147
- */
1148
- export function generatePlaintextExport(
1149
- events: UnifiedEvent[],
1150
- settings: EventsCopySettings
1151
- ): string {
1152
- const filtered = filterEvents(events, settings);
1153
- if (filtered.length === 0) return "No events to export.";
1154
-
1155
- // Sort by timestamp (oldest first)
1156
- const sorted = [...filtered].sort((a, b) => a.timestamp - b.timestamp);
1157
- const baseTimestamp = sorted[0].timestamp;
1158
- const summary = getExportSummary(sorted);
1159
-
1160
- const lines: string[] = [];
1161
-
1162
- // Header
1163
- if (settings.includeSummaryHeader || settings.includeTotalDuration) {
1164
- const parts: string[] = [`Event Flow (${summary.totalEvents} events`];
1165
-
1166
- if (settings.includeTotalDuration) {
1167
- parts[0] += `, ${formatRelativeTime(summary.durationMs).replace("+", "")}`;
1168
- }
1169
-
1170
- parts[0] += ")";
1171
- lines.push(parts[0]);
1172
-
1173
- if (settings.includeSummaryHeader) {
1174
- const statusParts: string[] = [];
1175
- if (summary.success > 0) statusParts.push(`${summary.success} success`);
1176
- if (summary.pending > 0) statusParts.push(`${summary.pending} pending`);
1177
- if (summary.error > 0) statusParts.push(`${summary.error} error`);
1178
- if (summary.neutral > 0) statusParts.push(`${summary.neutral} neutral`);
1179
- if (statusParts.length > 0) {
1180
- lines.push(statusParts.join(", "));
1181
- }
1182
- }
1183
-
1184
- lines.push("");
1185
- }
1186
-
1187
- // Events
1188
- for (const event of sorted) {
1189
- const parts: string[] = [];
1190
-
1191
- // Timestamp
1192
- const timestamp = formatTimestamp(event.timestamp, baseTimestamp, settings.timestampFormat);
1193
- parts.push(timestamp.padEnd(12));
1194
-
1195
- // Status
1196
- if (settings.includeStatus) {
1197
- parts.push(STATUS_ICONS_ASCII[event.status]);
1198
- }
1199
-
1200
- // Source
1201
- if (settings.includeSource) {
1202
- parts.push(`${SOURCE_LABELS[event.source]}:`);
1203
- }
1204
-
1205
- // Title
1206
- if (settings.includeTitle) {
1207
- parts.push(event.title);
1208
- }
1209
-
1210
- // For storage events, add diff summary
1211
- if (settings.showStorageDiff && (event.source === "storage-async" || event.source === "storage-mmkv")) {
1212
- const data = event.originalEvent as Record<string, unknown>;
1213
- if (data?.data) {
1214
- const innerData = data.data as Record<string, unknown>;
1215
- const diff = generateStorageDiffSummary(innerData.prevValue, innerData.value);
1216
- if (diff) {
1217
- parts.push(`-> ${diff}`);
1218
- }
1219
- }
1220
- }
1221
-
1222
- // For Redux, note if no state change
1223
- if (event.source === "redux") {
1224
- const data = event.originalEvent as Record<string, unknown>;
1225
- if (data?.hasStateChange === false) {
1226
- parts.push("(no change)");
1227
- }
1228
- }
1229
-
1230
- // Subtitle
1231
- if (settings.includeSubtitle && event.subtitle) {
1232
- parts.push(`- ${event.subtitle}`);
1233
- }
1234
-
1235
- lines.push(parts.join(" "));
1236
-
1237
- // Event data (with smart formatting)
1238
- if (settings.includeEventData && event.originalEvent) {
1239
- const formattedData = formatEventData(event, settings);
1240
- const { data, truncated } = truncateData(
1241
- formattedData,
1242
- settings.dataSizeThreshold
1243
- );
1244
-
1245
- if (truncated) {
1246
- lines.push(` ${data}`);
1247
- } else {
1248
- lines.push(` Data: ${JSON.stringify(data)}`);
1249
- }
1250
- }
1251
- }
1252
-
1253
- return lines.join("\n");
1254
- }
1255
-
1256
- // ============================================================================
1257
- // MERMAID SEQUENCE DIAGRAM EXPORT
1258
- // ============================================================================
1259
-
1260
- /**
1261
- * Participant configuration for Mermaid sequence diagrams
1262
- */
1263
- interface MermaidParticipant {
1264
- id: string;
1265
- icon: string;
1266
- label: string;
1267
- sources: EventSource[];
1268
- group?: "client" | "server";
1269
- }
1270
-
1271
- /**
1272
- * Participant definitions - map event sources to diagram actors
1273
- * Organized by client vs server for grouping
1274
- * Note: Storage types are split for clarity
1275
- */
1276
- const MERMAID_PARTICIPANTS: MermaidParticipant[] = [
1277
- // Client-side
1278
- { id: "U", icon: "👤", label: "User", sources: [], group: "client" },
1279
- { id: "App", icon: "📱", label: "App", sources: ["route", "render"], group: "client" },
1280
- { id: "Async", icon: "💾", label: "AsyncStorage", sources: ["storage-async"], group: "client" },
1281
- { id: "MMKV", icon: "⚡", label: "MMKV", sources: ["storage-mmkv"], group: "client" },
1282
- { id: "Redux", icon: "🔄", label: "Redux", sources: ["redux"], group: "client" },
1283
- // Server-side / External
1284
- { id: "API", icon: "🌐", label: "API", sources: ["network"], group: "server" },
1285
- { id: "Cache", icon: "📦", label: "QueryCache", sources: ["react-query", "react-query-query", "react-query-mutation"], group: "server" },
1286
- ];
1287
-
1288
- /**
1289
- * Get the Mermaid participant ID for an event source
1290
- */
1291
- function getParticipantId(source: EventSource): string {
1292
- const participant = MERMAID_PARTICIPANTS.find((p) => p.sources.includes(source));
1293
- return participant?.id || "App";
1294
- }
1295
-
1296
- /**
1297
- * Detect which participants are needed based on events
1298
- */
1299
- function detectParticipants(events: UnifiedEvent[]): MermaidParticipant[] {
1300
- const sourcesInUse = new Set<EventSource>();
1301
- for (const event of events) {
1302
- sourcesInUse.add(event.source);
1303
- }
1304
-
1305
- const participants: MermaidParticipant[] = [];
1306
-
1307
- // Always include User and App
1308
- participants.push(MERMAID_PARTICIPANTS[0]); // User
1309
- participants.push(MERMAID_PARTICIPANTS[1]); // App
1310
-
1311
- // Add other participants based on event sources present
1312
- for (const participant of MERMAID_PARTICIPANTS.slice(2)) {
1313
- if (participant.sources.some((s) => sourcesInUse.has(s))) {
1314
- participants.push(participant);
1315
- }
1316
- }
1317
-
1318
- return participants;
1319
- }
1320
-
1321
- /**
1322
- * Check if we should use participant grouping (boxes)
1323
- */
1324
- function shouldUseGroups(participants: MermaidParticipant[]): boolean {
1325
- const hasClient = participants.some((p) => p.group === "client");
1326
- const hasServer = participants.some((p) => p.group === "server");
1327
- return hasClient && hasServer && participants.length >= 3;
1328
- }
1329
-
1330
- /**
1331
- * Format duration for Mermaid notes
1332
- */
1333
- function formatMermaidDuration(ms: number): string {
1334
- if (ms < 1000) return `${ms}ms`;
1335
- if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
1336
- return `${(ms / 60000).toFixed(1)}m`;
1337
- }
1338
-
1339
- /**
1340
- * Escape text for Mermaid (handle special characters)
1341
- */
1342
- function escapeMermaidText(text: string): string {
1343
- return text
1344
- .replace(/[#;:]/g, " ") // Remove characters with special meaning
1345
- .replace(/[\n\r]/g, " ") // Replace newlines with spaces
1346
- .replace(/"/g, "'") // Replace double quotes with single
1347
- .replace(/\s+/g, " ") // Collapse multiple spaces
1348
- .trim();
1349
- }
1350
-
1351
- /**
1352
- * Check if a storage key is internal/devtools tracking
1353
- * Be conservative - only filter obvious internal keys
1354
- */
1355
- function isInternalStorageKey(key: string): boolean {
1356
- const internalPatterns = [
1357
- "last-route",
1358
- "@dev/last",
1359
- "__debug",
1360
- "_persist",
1361
- "devtools/internal",
1362
- ];
1363
- const lowerKey = key.toLowerCase();
1364
- return internalPatterns.some((p) => lowerKey.includes(p));
1365
- }
1366
-
1367
- /**
1368
- * Format bytes to human readable size
1369
- */
1370
- function formatBytes(bytes: number): string {
1371
- if (bytes < 1024) return `${bytes}B`;
1372
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
1373
- return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
1374
- }
1375
-
1376
- /**
1377
- * Estimate size of data in bytes (early-abort probe, capped at 1MB — a size
1378
- * label never justifies an O(payload) stringify).
1379
- */
1380
- function estimateDataSize(data: unknown): number {
1381
- return approxJsonBytesOver(data, 1024 * 1024).approxBytes;
1382
- }
1383
-
1384
- /**
1385
- * Get canonical URL for duplicate detection (strip timestamps, debug params)
1386
- */
1387
- function getCanonicalUrl(url: string): string {
1388
- try {
1389
- const urlObj = new URL(url, "http://localhost");
1390
- // Remove common cache-busting/debug params
1391
- const paramsToRemove = ["timestamp", "t", "_t", "debug", "client", "version", "cache", "_"];
1392
- paramsToRemove.forEach((p) => urlObj.searchParams.delete(p));
1393
- return urlObj.pathname + (urlObj.searchParams.toString() ? "?" + urlObj.searchParams.toString() : "");
1394
- } catch {
1395
- return url;
1396
- }
1397
- }
1398
-
1399
- /**
1400
- * Get a readable short name from a storage key
1401
- */
1402
- function getStorageKeyName(key: string): string {
1403
- // Remove common prefixes
1404
- let name = key
1405
- .replace(/^@[\w-]+\//, "") // Remove @prefix/
1406
- .replace(/^devtools\//, "")
1407
- .replace(/^dev\//, "")
1408
- .replace(/^buoy\//, "")
1409
- .replace(/^pokemon\//, ""); // Remove pokemon/ prefix for this app
1410
-
1411
- // Get last meaningful segment
1412
- const segments = name.split("/").filter(Boolean);
1413
- if (segments.length > 1) {
1414
- name = segments.slice(-1).join("/"); // Just the last segment
1415
- }
1416
-
1417
- // Humanize common patterns
1418
- name = name
1419
- .replace(/-/g, " ")
1420
- .replace(/_/g, " ");
1421
-
1422
- // Title case
1423
- name = name.split(" ").map(word =>
1424
- word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
1425
- ).join(" ");
1426
-
1427
- // Common renames for clarity
1428
- if (name.toLowerCase() === "saved") name = "Favorites";
1429
-
1430
- return name.substring(0, 20);
1431
- }
1432
-
1433
- /**
1434
- * Extract entity name from URL path (e.g., /pokemon/charizard -> Charizard)
1435
- */
1436
- function extractEntityFromPath(url: string): string | null {
1437
- // Strip query params first
1438
- let path = url;
1439
- try {
1440
- const urlObj = new URL(url, "http://localhost");
1441
- path = urlObj.pathname;
1442
- } catch {
1443
- // If URL parsing fails, try to strip query params manually
1444
- const queryIndex = path.indexOf("?");
1445
- if (queryIndex > 0) {
1446
- path = path.substring(0, queryIndex);
1447
- }
1448
- }
1449
-
1450
- // Common patterns: /resource/:id, /resource/:name
1451
- const segments = path.split("/").filter(Boolean);
1452
-
1453
- if (segments.length >= 2) {
1454
- const lastSegment = segments[segments.length - 1];
1455
- // If it looks like an ID (number or uuid), use the resource name
1456
- if (/^\d+$/.test(lastSegment) || /^[a-f0-9-]{36}$/i.test(lastSegment)) {
1457
- return null;
1458
- }
1459
- // Humanize the last segment (e.g., charizard -> Charizard)
1460
- return lastSegment.charAt(0).toUpperCase() + lastSegment.slice(1);
1461
- }
1462
-
1463
- if (segments.length === 1) {
1464
- return segments[0].charAt(0).toUpperCase() + segments[0].slice(1);
1465
- }
1466
-
1467
- return null;
1468
- }
1469
-
1470
- /**
1471
- * Get human-readable action from HTTP method + path
1472
- */
1473
- function getHumanReadableApiAction(method: string, url: string): string {
1474
- try {
1475
- const urlObj = new URL(url, "http://localhost");
1476
- let path = urlObj.pathname;
1477
-
1478
- // Handle GraphQL specially
1479
- if (path.includes("graphql")) {
1480
- return "GraphQL Request";
1481
- }
1482
-
1483
- // Remove API prefixes
1484
- path = path.replace(/^\/api\/v\d+/, "").replace(/^\/api/, "");
1485
-
1486
- const entity = extractEntityFromPath(path);
1487
- const segments = path.split("/").filter(Boolean);
1488
- const resource = segments[0]
1489
- ? segments[0].charAt(0).toUpperCase() + segments[0].slice(1)
1490
- : "Data";
1491
-
1492
- // Check for search/query patterns
1493
- const hasSearchQuery = urlObj.searchParams.has("q") ||
1494
- urlObj.searchParams.has("query") ||
1495
- urlObj.searchParams.has("search");
1496
-
1497
- // Generate human-readable action based on method
1498
- switch (method.toUpperCase()) {
1499
- case "GET":
1500
- if (hasSearchQuery) {
1501
- const query = urlObj.searchParams.get("q") ||
1502
- urlObj.searchParams.get("query") ||
1503
- urlObj.searchParams.get("search");
1504
- if (query) return `Search "${query}"`;
1505
- return `Search ${resource}`;
1506
- }
1507
- if (entity) return `Fetch ${entity}`;
1508
- return `Fetch ${resource}`;
1509
- case "POST":
1510
- if (path.includes("search")) return `Search ${resource}`;
1511
- if (entity) return `Create ${entity}`;
1512
- return `Create ${resource}`;
1513
- case "PUT":
1514
- case "PATCH":
1515
- if (entity) return `Update ${entity}`;
1516
- return `Update ${resource}`;
1517
- case "DELETE":
1518
- if (entity) return `Delete ${entity}`;
1519
- return `Delete ${resource}`;
1520
- default:
1521
- return `${method} ${resource}`;
1522
- }
1523
- } catch {
1524
- return `${method} request`;
1525
- }
1526
- }
1527
-
1528
- /**
1529
- * Get human-readable route label
1530
- */
1531
- function getHumanReadableRoute(pathname: string): string {
1532
- if (pathname === "/" || pathname === "") return "Home";
1533
-
1534
- const segments = pathname.split("/").filter(Boolean);
1535
-
1536
- if (segments.length === 0) return "Home";
1537
-
1538
- // Handle common patterns
1539
- if (segments.length === 1) {
1540
- // /pokemon -> Pokemon List
1541
- const name = segments[0].charAt(0).toUpperCase() + segments[0].slice(1);
1542
- return `${name} List`;
1543
- }
1544
-
1545
- if (segments.length >= 2) {
1546
- // /pokemon/charizard -> Charizard Details
1547
- const entity = segments[segments.length - 1];
1548
- // Check if it's a numeric ID
1549
- if (/^\d+$/.test(entity)) {
1550
- const resource = segments[0].charAt(0).toUpperCase() + segments[0].slice(1);
1551
- return `${resource} #${entity}`;
1552
- }
1553
- const entityName = entity.charAt(0).toUpperCase() + entity.slice(1);
1554
- return `${entityName} Details`;
1555
- }
1556
-
1557
- return pathname;
1558
- }
1559
-
1560
- /**
1561
- * Format a single event as Mermaid sequence messages
1562
- * Returns both the messages and any notes to add
1563
- * Returns null if the event should be skipped (internal/devtools)
1564
- */
1565
- function formatMermaidEvent(
1566
- event: UnifiedEvent,
1567
- _settings: EventsCopySettings,
1568
- baseTimestamp: number
1569
- ): { messages: string[]; notes: string[]; skip?: boolean } {
1570
- const messages: string[] = [];
1571
- const notes: string[] = [];
1572
- const relativeTime = formatMermaidDuration(event.timestamp - baseTimestamp);
1573
-
1574
- switch (event.source) {
1575
- case "route": {
1576
- const data = event.originalEvent as Record<string, unknown>;
1577
- const pathname = String(data?.pathname || event.title);
1578
- const previousPathname = data?.previousPathname as string | undefined;
1579
- const timeSincePrevious = data?.timeSincePrevious as number | undefined;
1580
-
1581
- const routeLabel = getHumanReadableRoute(pathname);
1582
- const fromLabel = previousPathname ? getHumanReadableRoute(previousPathname) : null;
1583
-
1584
- // Show navigation with clear from → to pattern
1585
- if (fromLabel) {
1586
- messages.push(`U->>App: ${fromLabel} → ${routeLabel}`);
1587
- // Show how long user spent on previous screen
1588
- if (timeSincePrevious && timeSincePrevious > 0) {
1589
- notes.push(`Note right of App: ${formatMermaidDuration(timeSincePrevious)} on ${fromLabel}`);
1590
- }
1591
- } else {
1592
- messages.push(`U->>App: Open ${routeLabel}`);
1593
- }
1594
- break;
1595
- }
1596
-
1597
- case "network": {
1598
- const data = event.originalEvent as Record<string, unknown>;
1599
- const method = (data?.method as string) || "GET";
1600
- const url = (data?.url as string) || "";
1601
- const status = data?.status as number | undefined;
1602
- const duration = data?.duration as number | undefined;
1603
- const responseData = data?.response || data?.data || data?.body;
1604
- // Try to get size from various possible fields
1605
- const responseSize = data?.responseSize as number | undefined ||
1606
- data?.size as number | undefined ||
1607
- data?.contentLength as number | undefined;
1608
-
1609
- // Get human-readable action
1610
- const action = getHumanReadableApiAction(method, url);
1611
- const entity = extractEntityFromPath(url);
1612
-
1613
- // Request with activation
1614
- messages.push(`App->>+API: ${action}`);
1615
-
1616
- // Response with entity context if available
1617
- if (event.status === "error") {
1618
- const statusText = status ? `${status} Error` : "Failed";
1619
- messages.push(`API--x-App: ${statusText}`);
1620
- } else {
1621
- let response = entity ? `✓ ${entity}` : "✓ Success";
1622
- messages.push(`API-->>-App: ${response}`);
1623
- }
1624
-
1625
- // Build note with duration and size
1626
- const noteParts: string[] = [];
1627
- if (duration) {
1628
- noteParts.push(formatMermaidDuration(duration));
1629
- }
1630
- // Add response size - try explicit size first, then estimate
1631
- if (responseSize && responseSize > 0) {
1632
- noteParts.push(formatBytes(responseSize));
1633
- } else if (responseData) {
1634
- const size = estimateDataSize(responseData);
1635
- if (size > 1024) { // Only show if > 1KB
1636
- noteParts.push(formatBytes(size));
1637
- }
1638
- }
1639
- if (noteParts.length > 0) {
1640
- notes.push(`Note right of API: ${noteParts.join(" · ")}`);
1641
- }
1642
- break;
1643
- }
1644
-
1645
- case "storage-async":
1646
- case "storage-mmkv": {
1647
- const data = event.originalEvent as Record<string, unknown>;
1648
- const innerData = data?.data as Record<string, unknown>;
1649
- const action = (data?.action as string) || "access";
1650
- const key = (innerData?.key as string) || "data";
1651
-
1652
- // Skip internal devtools storage
1653
- if (isInternalStorageKey(key)) {
1654
- return { messages: [], notes: [], skip: true };
1655
- }
1656
-
1657
- const keyName = getStorageKeyName(key);
1658
- const storeId = event.source === "storage-mmkv" ? "MMKV" : "Async";
1659
-
1660
- // Helper to get item identifier (handles both objects and strings)
1661
- const getItemId = (item: unknown): string | null => {
1662
- if (typeof item === "string") return item;
1663
- if (typeof item === "number") return String(item);
1664
- if (typeof item === "object" && item) {
1665
- if ("name" in item) return String((item as { name: unknown }).name);
1666
- if ("id" in item) return String((item as { id: unknown }).id);
1667
- }
1668
- return null;
1669
- };
1670
-
1671
- // Helper to capitalize first letter
1672
- const capitalize = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1);
1673
-
1674
- // Analyze the change to determine action and entity
1675
- let actionIcon = "";
1676
- let actionVerb = "";
1677
- let entityName = "";
1678
- let countInfo = "";
1679
-
1680
- const prevValue = innerData?.prevValue;
1681
- const newValue = innerData?.value;
1682
-
1683
- // Handle array comparisons (most common for collections)
1684
- if (Array.isArray(prevValue) && Array.isArray(newValue)) {
1685
- const prevLen = prevValue.length;
1686
- const newLen = newValue.length;
1687
- countInfo = `${prevLen} → ${newLen} items`;
1688
-
1689
- if (newLen > prevLen) {
1690
- // Items were added
1691
- actionIcon = "➕";
1692
- actionVerb = "Add";
1693
- // Find what was added
1694
- const prevSet = new Set(prevValue.map(getItemId).filter(Boolean));
1695
- for (const item of newValue) {
1696
- const id = getItemId(item);
1697
- if (id && !prevSet.has(id)) {
1698
- entityName = capitalize(id);
1699
- break;
1700
- }
1701
- }
1702
- } else if (newLen < prevLen) {
1703
- // Items were removed
1704
- actionIcon = "➖";
1705
- actionVerb = "Remove";
1706
- // Find what was removed
1707
- const newSet = new Set(newValue.map(getItemId).filter(Boolean));
1708
- for (const item of prevValue) {
1709
- const id = getItemId(item);
1710
- if (id && !newSet.has(id)) {
1711
- entityName = capitalize(id);
1712
- break;
1713
- }
1714
- }
1715
- } else {
1716
- // Same length - update
1717
- actionIcon = "📝";
1718
- actionVerb = "Update";
1719
- }
1720
- } else if (Array.isArray(newValue) && (!prevValue || (Array.isArray(prevValue) && prevValue.length === 0))) {
1721
- // Adding first item(s) - prevValue is null/undefined or empty array
1722
- actionIcon = "➕";
1723
- actionVerb = "Add";
1724
- countInfo = `→ ${newValue.length} items`;
1725
- if (newValue.length > 0) {
1726
- const id = getItemId(newValue[0]);
1727
- if (id) entityName = capitalize(id);
1728
- }
1729
- } else if (Array.isArray(prevValue) && (!newValue || (Array.isArray(newValue) && newValue.length === 0))) {
1730
- // Removing all items
1731
- actionIcon = "➖";
1732
- actionVerb = "Clear";
1733
- countInfo = `${prevValue.length} → 0 items`;
1734
- } else if (action === "getItem") {
1735
- actionIcon = "📖";
1736
- actionVerb = "Load";
1737
- } else if (action === "removeItem") {
1738
- actionIcon = "➖";
1739
- actionVerb = "Remove";
1740
- } else if (action === "clear") {
1741
- actionIcon = "🗑️";
1742
- actionVerb = "Clear";
1743
- } else {
1744
- // Default for setItem without prev/new comparison
1745
- actionIcon = "💾";
1746
- actionVerb = "Save";
1747
- }
1748
-
1749
- // Build the message
1750
- let message: string;
1751
- if (entityName) {
1752
- message = `App->>${storeId}: ${actionIcon} ${actionVerb} ${entityName} → ${keyName}`;
1753
- } else {
1754
- message = `App->>${storeId}: ${actionIcon} ${actionVerb} ${keyName}`;
1755
- }
1756
- messages.push(message);
1757
-
1758
- // Add note with count info
1759
- if (countInfo) {
1760
- notes.push(`Note right of ${storeId}: ${countInfo}`);
1761
- }
1762
- break;
1763
- }
1764
-
1765
- case "react-query":
1766
- case "react-query-query": {
1767
- const data = event.originalEvent as Record<string, unknown>;
1768
- const type = (data?.type as string) || "";
1769
- const queryKey = data?.queryKey;
1770
- const duration = data?.duration as number | undefined;
1771
-
1772
- // Format query key as human-readable
1773
- let keyLabel = "data";
1774
- if (Array.isArray(queryKey) && queryKey.length > 0) {
1775
- // Try to make it readable: ["pokemon", "charizard"] -> "Charizard"
1776
- const lastKey = queryKey[queryKey.length - 1];
1777
- if (typeof lastKey === "string" && !/^\d+$/.test(lastKey)) {
1778
- keyLabel = lastKey.charAt(0).toUpperCase() + lastKey.slice(1);
1779
- } else if (queryKey.length > 1 && typeof queryKey[0] === "string") {
1780
- keyLabel = queryKey[0].charAt(0).toUpperCase() + queryKey[0].slice(1);
1781
- }
1782
- }
1783
-
1784
- if (type.includes("start") || type.includes("fetch") || event.status === "pending") {
1785
- messages.push(`App->>+Cache: Fetch ${keyLabel}`);
1786
- } else if (event.status === "error") {
1787
- messages.push(`Cache--x-App: Failed to load`);
1788
- } else if (event.status === "success") {
1789
- let response = `✓ ${keyLabel} ready`;
1790
- if (duration) {
1791
- response += ` (${formatMermaidDuration(duration)})`;
1792
- }
1793
- messages.push(`Cache-->>-App: ${response}`);
1794
- } else if (type.includes("invalidate")) {
1795
- messages.push(`App->>Cache: Refresh ${keyLabel}`);
1796
- } else {
1797
- messages.push(`Cache-->>App: ${escapeMermaidText(type)}`);
1798
- }
1799
- break;
1800
- }
1801
-
1802
- case "react-query-mutation": {
1803
- const data = event.originalEvent as Record<string, unknown>;
1804
- const type = (data?.type as string) || "";
1805
- const mutationKey = data?.mutationKey;
1806
- const duration = data?.duration as number | undefined;
1807
-
1808
- let actionLabel = "Update";
1809
- if (Array.isArray(mutationKey) && mutationKey.length > 0) {
1810
- const key = String(mutationKey[0]);
1811
- // Common mutation patterns
1812
- if (key.includes("add") || key.includes("create")) actionLabel = "Add";
1813
- else if (key.includes("delete") || key.includes("remove")) actionLabel = "Delete";
1814
- else if (key.includes("update") || key.includes("edit")) actionLabel = "Update";
1815
- else actionLabel = key.charAt(0).toUpperCase() + key.slice(1);
1816
- }
1817
-
1818
- if (type.includes("start") || type.includes("loading") || event.status === "pending") {
1819
- messages.push(`App->>+Cache: ${actionLabel}`);
1820
- } else if (event.status === "error") {
1821
- messages.push(`Cache--x-App: ${actionLabel} failed`);
1822
- } else if (event.status === "success") {
1823
- let response = `✓ ${actionLabel} complete`;
1824
- if (duration) {
1825
- response += ` (${formatMermaidDuration(duration)})`;
1826
- }
1827
- messages.push(`Cache-->>-App: ${response}`);
1828
- }
1829
- break;
1830
- }
1831
-
1832
- case "redux": {
1833
- const data = event.originalEvent as Record<string, unknown>;
1834
- const actionType = (data?.type as string) || event.title;
1835
- const hasChange = data?.hasStateChange as boolean;
1836
- const diffSummary = data?.diffSummary as string | undefined;
1837
-
1838
- // Parse action type into human-readable form
1839
- // e.g., "cart/addItem" -> "Add Item to Cart"
1840
- const parts = actionType.split("/");
1841
- let actionLabel: string;
1842
- if (parts.length >= 2) {
1843
- const slice = parts[0].charAt(0).toUpperCase() + parts[0].slice(1);
1844
- let action = parts[1]
1845
- .replace(/([A-Z])/g, " $1") // camelCase to spaces
1846
- .replace(/(pending|fulfilled|rejected)$/i, "")
1847
- .trim();
1848
- action = action.charAt(0).toUpperCase() + action.slice(1);
1849
- actionLabel = `${action} (${slice})`;
1850
- } else {
1851
- actionLabel = escapeMermaidText(actionType).substring(0, 25);
1852
- }
1853
-
1854
- messages.push(`App->>Redux: ${actionLabel}`);
1855
-
1856
- if (hasChange === false) {
1857
- notes.push(`Note right of Redux: No change`);
1858
- } else if (diffSummary) {
1859
- notes.push(`Note right of Redux: ${escapeMermaidText(diffSummary).substring(0, 35)}`);
1860
- }
1861
- break;
1862
- }
1863
-
1864
- case "render": {
1865
- const data = event.originalEvent as Record<string, unknown>;
1866
- const renderData = data?.renderData as Record<string, unknown>;
1867
- const componentName = escapeMermaidText(event.title).substring(0, 20);
1868
- const cause = (renderData?.cause as string) || "update";
1869
-
1870
- // Make cause more human-readable
1871
- const causeLabel =
1872
- cause === "mount" ? "mounted" :
1873
- cause === "props" ? "props changed" :
1874
- cause === "state" ? "state changed" :
1875
- cause === "context" ? "context changed" :
1876
- cause === "parent" ? "parent re-rendered" :
1877
- cause === "hooks" ? "hook changed" : cause;
1878
-
1879
- messages.push(`App->>App: Render ${componentName}`);
1880
- notes.push(`Note right of App: ${causeLabel}`);
1881
- break;
1882
- }
1883
-
1884
- default: {
1885
- messages.push(`App->>App: ${escapeMermaidText(event.title).substring(0, 30)}`);
1886
- }
1887
- }
1888
-
1889
- return { messages, notes };
1890
- }
1891
-
1892
- /**
1893
- * Generate Mermaid sequence diagram export
1894
- */
1895
- export function generateMermaidExport(
1896
- events: UnifiedEvent[],
1897
- settings: EventsCopySettings
1898
- ): string {
1899
- const filtered = filterEvents(events, settings);
1900
- if (filtered.length === 0) {
1901
- return "sequenceDiagram\n participant U as 👤 User\n participant App as 📱 App\n Note over U,App: No events captured";
1902
- }
1903
-
1904
- // Sort by timestamp (oldest first for timeline)
1905
- const sorted = [...filtered].sort((a, b) => a.timestamp - b.timestamp);
1906
- const baseTimestamp = sorted[0].timestamp;
1907
-
1908
- // Detect participants
1909
- const participants = detectParticipants(sorted);
1910
- const useGroups = shouldUseGroups(participants);
1911
-
1912
- const lines: string[] = ["sequenceDiagram"];
1913
- lines.push(" autonumber");
1914
- lines.push("");
1915
-
1916
- // Add participants with optional grouping
1917
- if (useGroups) {
1918
- const clientParticipants = participants.filter((p) => p.group === "client");
1919
- const serverParticipants = participants.filter((p) => p.group === "server");
1920
-
1921
- if (clientParticipants.length > 0) {
1922
- lines.push(" box rgb(240, 248, 255) Client");
1923
- for (const p of clientParticipants) {
1924
- lines.push(` participant ${p.id} as ${p.icon} ${p.label}`);
1925
- }
1926
- lines.push(" end");
1927
- }
1928
-
1929
- if (serverParticipants.length > 0) {
1930
- lines.push(" box rgb(255, 248, 240) External");
1931
- for (const p of serverParticipants) {
1932
- lines.push(` participant ${p.id} as ${p.icon} ${p.label}`);
1933
- }
1934
- lines.push(" end");
1935
- }
1936
- } else {
1937
- for (const p of participants) {
1938
- lines.push(` participant ${p.id} as ${p.icon} ${p.label}`);
1939
- }
1940
- }
1941
- lines.push("");
1942
-
1943
- // Calculate session summary stats
1944
- const sessionDuration = sorted[sorted.length - 1].timestamp - baseTimestamp;
1945
- const networkEvents = sorted.filter((e) => e.source === "network");
1946
- const totalBytes = networkEvents.reduce((sum, e) => {
1947
- const data = e.originalEvent as Record<string, unknown>;
1948
- const size = (data?.responseSize as number) || (data?.size as number) || 0;
1949
- return sum + size;
1950
- }, 0);
1951
- const errorCount = sorted.filter((e) => e.status === "error").length;
1952
-
1953
- // Build summary parts
1954
- const summaryParts: string[] = [];
1955
- summaryParts.push(`⏱️ ${formatMermaidDuration(sessionDuration)}`);
1956
- summaryParts.push(`📊 ${sorted.length} events`);
1957
- if (networkEvents.length > 0) {
1958
- summaryParts.push(`🌐 ${networkEvents.length} API calls`);
1959
- }
1960
- if (totalBytes > 0) {
1961
- summaryParts.push(`📦 ${formatBytes(totalBytes)}`);
1962
- }
1963
- if (errorCount > 0) {
1964
- summaryParts.push(`❌ ${errorCount} errors`);
1965
- }
1966
-
1967
- // Add session summary header
1968
- lines.push(` Note over U,API: ${summaryParts.join(" · ")}`);
1969
- lines.push("");
1970
-
1971
- // Track for duplicate detection - use canonical URLs (without cache-busting params)
1972
- const recentNetworkUrls = new Map<string, { timestamp: number; count: number }>();
1973
-
1974
- // Process events
1975
- let skippedCount = 0;
1976
- for (const event of sorted) {
1977
- const result = formatMermaidEvent(event, settings, baseTimestamp);
1978
-
1979
- // Skip internal/devtools events
1980
- if (result.skip) {
1981
- skippedCount++;
1982
- continue;
1983
- }
1984
-
1985
- const { messages, notes } = result;
1986
-
1987
- // Check for duplicate network requests using canonical URL
1988
- let isDuplicate = false;
1989
- let duplicateInfo = "";
1990
- if (event.source === "network") {
1991
- const data = event.originalEvent as Record<string, unknown>;
1992
- const url = data?.url as string;
1993
- if (url) {
1994
- const canonicalUrl = getCanonicalUrl(url);
1995
- const existing = recentNetworkUrls.get(canonicalUrl);
1996
- if (existing && event.timestamp - existing.timestamp < 30000) { // 30 second window
1997
- isDuplicate = true;
1998
- const timeSince = event.timestamp - existing.timestamp;
1999
- const timeLabel = formatMermaidDuration(timeSince);
2000
- duplicateInfo = `⚠️ Already fetched ${timeLabel} ago`;
2001
- recentNetworkUrls.set(canonicalUrl, { timestamp: event.timestamp, count: existing.count + 1 });
2002
- } else {
2003
- recentNetworkUrls.set(canonicalUrl, { timestamp: event.timestamp, count: 1 });
2004
- }
2005
- }
2006
- }
2007
-
2008
- // Wrap duplicates or errors in highlighted rect
2009
- if (isDuplicate) {
2010
- lines.push(" rect rgb(255, 245, 230)");
2011
- lines.push(` Note over App,API: ${duplicateInfo}`);
2012
- for (const msg of messages) {
2013
- lines.push(` ${msg}`);
2014
- }
2015
- for (const note of notes) {
2016
- lines.push(` ${note}`);
2017
- }
2018
- lines.push(" end");
2019
- } else if (event.status === "error") {
2020
- lines.push(" rect rgb(255, 235, 235)");
2021
- for (const msg of messages) {
2022
- lines.push(` ${msg}`);
2023
- }
2024
- for (const note of notes) {
2025
- lines.push(` ${note}`);
2026
- }
2027
- lines.push(" end");
2028
- } else {
2029
- for (const msg of messages) {
2030
- lines.push(` ${msg}`);
2031
- }
2032
- for (const note of notes) {
2033
- lines.push(` ${note}`);
2034
- }
2035
- }
2036
- }
2037
-
2038
- // Add note about skipped internal events if any
2039
- if (skippedCount > 0) {
2040
- lines.push("");
2041
- lines.push(` Note over App: ${skippedCount} internal events hidden`);
2042
- }
2043
-
2044
- return lines.join("\n");
2045
- }
2046
-
2047
- /**
2048
- * Generate export based on settings format
2049
- */
2050
- export function generateExport(
2051
- events: UnifiedEvent[],
2052
- settings: EventsCopySettings
2053
- ): string {
2054
- switch (settings.format) {
2055
- case "markdown":
2056
- return generateMarkdownExport(events, settings);
2057
- case "json":
2058
- return generateJsonExport(events, settings);
2059
- case "plaintext":
2060
- return generatePlaintextExport(events, settings);
2061
- case "mermaid":
2062
- return generateMermaidExport(events, settings);
2063
- default:
2064
- return generateMarkdownExport(events, settings);
2065
- }
2066
- }