-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathconsoleCatcher.ts
More file actions
218 lines (189 loc) · 5.84 KB
/
consoleCatcher.ts
File metadata and controls
218 lines (189 loc) · 5.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/**
* @file Module for intercepting console logs with stack trace capture
*/
import type { ConsoleLogEvent } from '@hawk.so/types';
import Sanitizer from '../modules/sanitizer';
/**
* Creates a console interceptor that captures and formats console output
*/
function createConsoleCatcher(): {
initConsoleCatcher: () => void;
addErrorEvent: (event: ErrorEvent | PromiseRejectionEvent) => void;
getConsoleLogStack: () => ConsoleLogEvent[];
} {
const MAX_LOGS = 20;
const consoleOutput: ConsoleLogEvent[] = [];
let isInitialized = false;
/**
* Converts any argument to its string representation
*
* @param arg - Value to convert to string
* @throws Error if the argument can not be stringified, for example by such reason:
* SecurityError: Failed to read a named property 'toJSON' from 'Window': Blocked a frame with origin "https://codex.so" from accessing a cross-origin frame.
*/
function stringifyArg(arg: unknown): string {
if (typeof arg === 'string') {
return arg;
}
if (typeof arg === 'number' || typeof arg === 'boolean') {
return String(arg);
}
/**
* Sanitize the argument before stringifying to handle circular references, deep objects, etc
* And then it can be stringified safely
*/
const sanitized = Sanitizer.sanitize(arg);
return JSON.stringify(sanitized);
}
/**
* Formats console arguments handling %c directives
*
* @param args - Console arguments that may include style directives
*/
function formatConsoleArgs(args: unknown[]): {
message: string;
styles: string[];
} {
if (args.length === 0) {
return {
message: '',
styles: [],
};
}
const firstArg = args[0];
if (typeof firstArg !== 'string' || !firstArg.includes('%c')) {
return {
message: args.map(arg => {
try {
return stringifyArg(arg);
} catch (error) {
return '[Error stringifying argument: ' + (error instanceof Error ? error.message : String(error)) + ']';
}
}).join(' '),
styles: [],
};
}
// Handle %c formatting
const message = args[0] as string;
const styles: string[] = [];
// Extract styles from arguments
let styleIndex = 0;
for (let i = 1; i < args.length; i++) {
const arg = args[i];
if (typeof arg === 'string' && message.indexOf('%c', styleIndex) !== -1) {
styles.push(arg);
styleIndex = message.indexOf('%c', styleIndex) + 2;
}
}
// Add remaining arguments that aren't styles
const remainingArgs = args
.slice(styles.length + 1)
.map(arg => {
try {
return stringifyArg(arg);
} catch (error) {
return '[Error stringifying argument: ' + (error instanceof Error ? error.message : String(error)) + ']';
}
})
.join(' ');
return {
message: message + (remainingArgs ? ' ' + remainingArgs : ''),
styles,
};
}
/**
* Adds a console log event to the output buffer
*
* @param logEvent - The console log event to be added to the output buffer
*/
function addToConsoleOutput(logEvent: ConsoleLogEvent): void {
if (consoleOutput.length >= MAX_LOGS) {
consoleOutput.shift();
}
consoleOutput.push(logEvent);
}
/**
* Creates a console log event from an error or promise rejection
*
* @param event - The error event or promise rejection event to convert
*/
function createConsoleEventFromError(
event: ErrorEvent | PromiseRejectionEvent
): ConsoleLogEvent {
if (event instanceof ErrorEvent) {
return {
method: 'error',
timestamp: new Date(),
type: event.error?.name || 'Error',
message: event.error?.message || event.message,
stack: event.error?.stack || '',
fileLine: event.filename
? `${event.filename}:${event.lineno}:${event.colno}`
: '',
};
}
return {
method: 'error',
timestamp: new Date(),
type: 'UnhandledRejection',
message: event.reason?.message || String(event.reason),
stack: event.reason?.stack || '',
fileLine: '',
};
}
/**
* Initializes the console interceptor by overriding default console methods
*/
function initConsoleCatcher(): void {
if (isInitialized) {
return;
}
isInitialized = true;
const consoleMethods: string[] = ['log', 'warn', 'error', 'info', 'debug'];
consoleMethods.forEach(function overrideConsoleMethod(method) {
if (typeof window.console[method] !== 'function') {
return;
}
const oldFunction = window.console[method].bind(window.console);
window.console[method] = function (...args: unknown[]): void {
const stack = new Error().stack?.split('\n').slice(2)
.join('\n') || '';
const { message, styles } = formatConsoleArgs(args);
const logEvent: ConsoleLogEvent = {
method,
timestamp: new Date(),
type: method,
message,
stack,
fileLine: stack.split('\n')[0]?.trim(),
styles,
};
addToConsoleOutput(logEvent);
oldFunction(...args);
};
});
}
/**
* Handles error events by converting them to console log events
*
* @param event - The error or promise rejection event to handle
*/
function addErrorEvent(event: ErrorEvent | PromiseRejectionEvent): void {
const logEvent = createConsoleEventFromError(event);
addToConsoleOutput(logEvent);
}
/**
* Returns the current console output buffer
*/
function getConsoleLogStack(): ConsoleLogEvent[] {
return [ ...consoleOutput ];
}
return {
initConsoleCatcher,
addErrorEvent,
getConsoleLogStack,
};
}
const consoleCatcher = createConsoleCatcher();
export const { initConsoleCatcher, getConsoleLogStack, addErrorEvent } =
consoleCatcher;