@buoy-gg/events 7.0.41 → 7.0.42

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