Skip to content

Analyzes stackframes and source maps to get a function's call site as AST node *at runtime*.

License

Notifications You must be signed in to change notification settings

HoldYourWaffle/ts-call-site

Repository files navigation

ts-call-site

npm

Analyzes stackframes, source maps and source code to get a function's call site as AST node at runtime. This can be used to analyze how the function was called, with full type information.

⚠️ Enable source maps

This modules needs source maps to connect JavaScript stackframes to the orignal TypeScript AST. Please make sure that source map support is enabled before using this module. Instructions and more information can be found at the source-map-support package.

❗ THIS MODULE RELIES ON SOURCE MAPS AND THE ORIGINAL SOURCE TO WORK ❗

Because of these constraints the use-cases for this module are limited. This module was originally intended for code-generation purposes, where the original source-code (and sourcemaps) is of course available.

An alternative (compile-time) method that might ease some of these constraints is discussed in #5.

Usage

// Enable source maps, see source-map-support's documentation for alternatives
import 'source-map-support/register'
import { getCallSite } from 'ts-call-site'

function myAmazingCaller() {
	myAmazingFunction();
}

function myAmazingFunction() {
    const caller = getCallSite();
    // Now you can do whatever you want with your CallExpression
    console.log(caller.getText()); // 'myAmazingFunction()'
}

The getCallSite method also supports an options object:

stackAtCalled

An Error object containing the stack representing the call to be analyzed. This stack will generally look like this:

[0] at myAmazingFunction (a:b)
[1] at myAmazingCaller (x:y)

The second element down this stack (index 1) is treated as 'the caller', and the CallExpression at that position is returned.

If none is provided, a new Error object is created for you. The extra getCallSite stackframe is taken into account.

project

A Project instance or ProjectOptions from ts-morph. Used to setup source analysis. Re-using a Project instance among multiple getCallSite calls will almost certainly result in a big performance boost.

If none is provided, a new Project is created based on the tsconfig file nearest to the calling file.

Contributing

I love all contributions! See the contribution guide for more information.

About

Analyzes stackframes and source maps to get a function's call site as AST node *at runtime*.

Topics

Resources

License

Stars

Watchers

Forks