|
| 1 | +import { Trace } from "../types/stacktrace"; |
| 2 | + |
| 3 | +const LINE_REGEXP = /\s*at\s*(?:(.+?)\s*\()?(?:(.+):(\d+):(\d+))?\)?/; |
| 4 | +const EXTENSION_REGEXP = /\.(\w+)$/; |
| 5 | +const CLASS_METHOD_REGEXP = /(.+)\.([^.]+)$/; |
| 6 | + |
| 7 | +const EXCLUDED = ["<anonymous>"]; |
| 8 | + |
| 9 | +const parse = (stackTrace: string): Trace[] => { |
| 10 | + const lines = stackTrace.split("\n"); |
| 11 | + const traces: Trace[] = []; |
| 12 | + |
| 13 | + for (const line of lines) { |
| 14 | + const stackTraceLine = parseStackTraceLine(line); |
| 15 | + if (stackTraceLine) { |
| 16 | + traces.push(stackTraceLine); |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + return traces; |
| 21 | +}; |
| 22 | + |
| 23 | +const parseStackTraceLine = (line: string): Trace | null => { |
| 24 | + const match = line.match(LINE_REGEXP); |
| 25 | + if (!match || EXCLUDED.includes(match[1])) { |
| 26 | + return null; |
| 27 | + } |
| 28 | + |
| 29 | + const [, method, file, lineStr, columnStr] = match; |
| 30 | + const lineNo = parseOptionalInt(lineStr); |
| 31 | + const columnNo = parseOptionalInt(columnStr); |
| 32 | + const ext = getFileExtension(file); |
| 33 | + const methodName = getFullMethodName(method); |
| 34 | + |
| 35 | + return { |
| 36 | + filename: file, |
| 37 | + lineNo, |
| 38 | + columnNo, |
| 39 | + function: methodName, |
| 40 | + extension: ext |
| 41 | + }; |
| 42 | +}; |
| 43 | + |
| 44 | +const parseOptionalInt = (str?: string): number | null => { |
| 45 | + return str ? parseInt(str, 10) : null; |
| 46 | +}; |
| 47 | + |
| 48 | +const getFileExtension = (file?: string): string | null => { |
| 49 | + if (!file) { |
| 50 | + return null; |
| 51 | + } |
| 52 | + |
| 53 | + const match = file.match(EXTENSION_REGEXP); |
| 54 | + return match ? match[1] : null; |
| 55 | +}; |
| 56 | + |
| 57 | +const getFullMethodName = (method?: string): string | null => { |
| 58 | + if (!method) { |
| 59 | + return null; |
| 60 | + } |
| 61 | + |
| 62 | + const match = method.match(CLASS_METHOD_REGEXP); |
| 63 | + return match ? `${match[1]}.${match[2]}` : method; |
| 64 | +}; |
| 65 | + |
| 66 | +export const stacktrace = { |
| 67 | + parse |
| 68 | +}; |
0 commit comments