Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
stacktracey
Advanced tools
Parses call stacks. Reads sources. Clean & filtered output. Sourcemaps. Node & browsers.
Stacktracey is an npm package that provides a powerful and flexible way to parse, manipulate, and analyze JavaScript stack traces. It helps developers to better understand and debug errors by offering a more readable and structured representation of stack traces.
Parsing Stack Traces
This feature allows you to parse a stack trace from an error object. The parsed stack trace is more readable and structured, making it easier to understand the flow of the error.
const Stacktracey = require('stacktracey');
const error = new Error('Something went wrong');
const stack = new Stacktracey(error);
console.log(stack);
Filtering Stack Frames
This feature allows you to filter stack frames based on certain criteria, such as file names or line numbers. This can be useful for focusing on relevant parts of the stack trace.
const Stacktracey = require('stacktracey');
const error = new Error('Something went wrong');
const stack = new Stacktracey(error);
const filteredStack = stack.withSources.filter(frame => frame.file.includes('myProject'));
console.log(filteredStack);
Converting Stack Traces to String
This feature allows you to convert a parsed stack trace back into a string format, but in a more readable table format. This can be useful for logging or displaying the stack trace in a user-friendly manner.
const Stacktracey = require('stacktracey');
const error = new Error('Something went wrong');
const stack = new Stacktracey(error);
console.log(stack.asTable());
Error-stack-parser is a library that extracts and parses error stack traces. It provides a simple API to parse stack traces into a more readable format. Compared to Stacktracey, it is more focused on just parsing and does not offer as many features for manipulating or filtering stack traces.
Stacktrace-parser is a simple library for parsing JavaScript stack traces. It provides a basic API to convert stack trace strings into structured objects. While it is similar to Stacktracey in terms of parsing capabilities, it lacks the advanced features for filtering and converting stack traces into different formats.
Tracey is a lightweight library for parsing and formatting stack traces. It offers basic functionality for parsing stack traces and converting them into a more readable format. Compared to Stacktracey, it is less feature-rich but can be a good choice for simpler use cases.
Parses call stacks. Reads sources. Clean & filtered output. Sourcemaps. Node & browsers.
// @hide
marker)SyntaxError
instancesnpm install stacktracey
import StackTracey from 'stacktracey'
Captures the current call stack:
stack = new StackTracey () // captures the current call stack
Parses stacks from an Error
object:
stack = new StackTracey (error)
stack = new StackTracey (error.stack) // ...or from raw string
Stores parsed data in .items
:
stack.items.length // num entries
stack.items[0] // top
...where each item exposes:
{
beforeParse: <original text>,
callee: <function name>,
calleeShort: <shortened function name>,
file: <full path to file>, // e.g. /Users/john/my_project/node_modules/foobar/main.js
fileRelative: <relative path to file>, // e.g. node_modules/foobar/main.js
fileShort: <short path to file>, // e.g. foobar/main.js
fileName: <file name>, // e.g. main.js
line: <line number>, // starts from 1
column: <column number>, // starts from 1
index: /* true if occured in HTML file at index page */,
native: /* true if occured in native browser code */,
thirdParty: /* true if occured in library code */,
hide: /* true if marked as hidden by "// @hide" tag */,
syntaxError: /* true if generated from a SyntaxError instance */
}
Accessing sources (synchronously, use with caution in browsers):
stack = stack.withSources () // returns a copy of stack with all items supplied with sources
top = stack.items[0] // top item
Accessing sources (asynchronously, preferred method in browsers):
stack = await stack.withSourcesAsync () // returns a copy of stack with all items supplied with sources
top = stack.items[0] // top item
...or:
top = stack.withSourceAt (0) // supplies source for an individiual item (by index)
top = await stack.withSourceAsyncAt (0) // supplies source for an individiual item (by index)
...or:
top = stack.withSource (stack.items[0]) // supplies source for an individiual item
top = await stack.withSourceAsync (stack.items[0]) // supplies source for an individiual item
The returned items contain the following additional fields (already mapped through sourcemaps):
{
... // all the previously described fields
line: <original line number>,
column: <original column number>,
sourceFile: <original source file object>,
sourceLine: <original source line text>
}
To learn about the sourceFile
object, read the get-source docs.
Synchronously (use with caution in browsers):
stack = stack.clean ()
...or (asynchronously):
stack = await stack.cleanAsync ()
It does the following:
isThirdParty
flag (library calls)// @hide
comment (user defined exclusion).mergeRepeatedLines
)You can customize its behavior by overriding the isClean (entry, index)
predicate.
isThirdParty
PredicateYou can override the isThirdParty
behavior by subclassing StackTracey
:
class MyStackTracey extends StackTracey {
isThirdParty (path) {
return (super.isThirdParty (path) // include default behavior
|| path.includes ('my-lib')) // paths including 'my-lib' will be marked as thirdParty
&& !path.includes ('jquery') // jquery paths won't be marked as thirdParty
}
}
...
const stack = new MyStackTracey (error).withSources ()
const prettyPrintedString = new StackTracey (error).asTable ()
...or (for pretty printing cleaned output):
const prettyPrintedString = new StackTracey (error).clean ().asTable () // NB: synchronously reads sources, use .cleanAsync for doing it async
const prettyPrintedString = (await new StackTracey (error).cleanAsync ()).asTable () // asynchronous version
It produces a nice compact table layout (thanks to as-table
), supplied with source lines (if available):
at shouldBeVisibleInStackTrace test.js:25 const shouldBeVisibleInStackTrace = () => new StackTracey ()
at it test.js:100 const stack = shouldBeVisibleInStackTrace ()
at callFn mocha/lib/runnable.js:326 var result = fn.call(ctx);
at run mocha/lib/runnable.js:319 callFn(this.fn);
at runTest mocha/lib/runner.js:422 test.run(fn);
at mocha/lib/runner.js:528 self.runTest(function(err) {
at next mocha/lib/runner.js:342 return fn();
at mocha/lib/runner.js:352 next(suites.pop());
at next mocha/lib/runner.js:284 return fn();
at <anonymous> mocha/lib/runner.js:320 next(0);
If you find your pretty printed tables undesirably trimmed (or maybe too long to fit in the line), you can provide custom column widths when calling asTable
(...or, alternatively, by overriding maxColumnWidths ()
method):
stack.asTable ({
callee: 30,
file: 60,
sourceLine: 80
})
You can even replace the default NodeJS exception printer with this! This is how you can do it:
process.on ('uncaughtException', e => { /* print the stack here */ })
process.on ('unhandledRejection', e => { /* print the stack here */ })
But the most simple way to achieve that is to use the ololog
library (that is built upon StackTracey and several other handy libraries coded by me). Check it out, it's pretty awesome and will blow your brains out :)
const log = require ('ololog').handleNodeErrors ()
// you can also print Errors by simply passing them to the log() function
SyntaxError
instancesFor example, when trying to require
a file named test_files/syntax_error.js
:
// next line contains a syntax error (not a valid JavaScript)
foo->bar ()
...the pretty printed call stack for the error thrown would be something like:
at (syntax error) test_files/syntax_error.js:2 foo->bar ()
at it test.js:184 try { require ('./test_files/syntax_error.js') }
at runCallback timers.js:781
at tryOnImmediate timers.js:743
at processImmediate [as _immediat timers.js:714
...where the first line is generated from parsing the raw output from the util.inspect
call in Node. Unfortunately, this won't work in older versions of Node (v4 and below) as these versions can't provide any meaningful information for a SyntaxError
instance.
All StackTracey instances expose map
, filter
, concat
and slice
methods. These methods will return mapped, filtered, joined, reversed and sliced StackTracey
instances, respectively:
s = new StackTracey ().slice (1).filter (x => !x.thirdParty) // current stack shifted by 1 and cleaned from library calls
s instanceof StackTracey // true
You can compare two locations via this predicate (tests file
, line
and column
for equality):
StackTracey.locationsEqual (a, b)
To force-reload the sources, you can invalidate the global source cache:
StackTracey.resetCache ()
console.log
for the log-driven debugging junkies!react-error-overlay
FAQs
Parses call stacks. Reads sources. Clean & filtered output. Sourcemaps. Node & browsers.
We found that stacktracey demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.