Get the stack trace of the creation of objects.
// foo.ts
import { record } from 'trace-record'
export const obj = record({ some: 'obj' })
// bar.ts
import { getTrace } from 'trace-record'
import { obj } from './foo'
console.log(getTrace(obj)) // [{ file: 'foo.ts', line: 3, column: 0 }, ...]
record()
is a bypass function that returns the object passed in. But also records the current stack trace and binds it to the object with an internal WeakMap. To retrieve the stack trace, use getTrace()
and pass the object instance to it.
import { record } from 'trace-record'
const obj = record({ some: 'obj' })
const arr = record([1, 2, 3])
const fn = record(() => {})
Since it uses WeakMap under the hood, it requires the object to be a reference type (object-like). Primitive types like string
, number
, boolean
, null
, undefined
will not work.
getTrace()
retrieves the stack trace of the object created by record()
. It returns an array of StackFrame
array. Returns undefined
if the object is not recorded. Stacktrace parsing is powered by error-stack-parser-es
Same as getTrace()
but returns a raw, unparsed, stacktrace string provided by the the JavaScript engine. The format may vary between engines and runtimes.
To make it easier to bail out the tracing in production, you can alias the package to the noop export in your build tool.
defineConfig({
alias: {
'trace-record': 'trace-record/noop'
}
})
I have a plan to rewrite a transpiler to automatically insert the record()
for specific types of objects. For now, you might need to manually add record()
to the objects you want to trace.
MIT License © 2023-PRESENT Anthony Fu