execution-engine
- Version 4.0.0
- Published
- 218 kB
- No dependencies
- MIT license
Install
npm i execution-engine
yarn add execution-engine
pnpm add execution-engine
Overview
A TypeScript library for tracing and visualizing code execution workflows.
Index
Variables
Functions
Classes
Interfaces
Type Aliases
Variables
variable cacheStoreKey
const cacheStoreKey: Symbol;
variable DEFAULT_TRACE_CONFIG
const DEFAULT_TRACE_CONFIG: { traceExecution?: | boolean | (keyof ExecutionTrace<I, O>)[] | ExecutionTraceExtractor<unknown[], unknown>; parallel?: string | boolean; errors?: 'catch' | 'throw';};
variable isNodeExecutionTrace
const isNodeExecutionTrace: <I, O>( config: ExecutionTraceExtractor<I, O>) => config is ExecutionTraceExtractor<I, O>;
Deprecated
Use
isExecutionTrace
instead.⚠️
isNodeExecutionTrace
is deprecated and will be removed in a future release. Migrate toisExecutionTrace
to ensure compatibility with future updates.
variable isNodeTrace
const isNodeTrace: (config: unknown) => config is Partial<EngineNodeTrace>;
Deprecated
Use
isEngineNodeTrace
instead.⚠️
isNodeTrace
is deprecated and will be removed in a future release. Migrate toisEngineNodeTrace
to ensure compatibility with future updates.
variable memoizationDefaultTTL
const memoizationDefaultTTL: number;
Default expiration in milliseconds that ensures multiple rapid calls can reuse the stored result
variable memoizationKey
const memoizationKey: Symbol;
variable memoizationMaxTTL
const memoizationMaxTTL: number;
Maximum allowable expiration time in milliseconds to prevent excessive retention
Functions
function cache
cache: (options: CacheOptions) => MethodDecorator;
Caches function results to avoid redundant expensive computations If the result is already cached, it returns the cached value; otherwise, it executes the function and stores the result.
Parameter options
Caching configuration specifying TTL, cache key generation, cache management, and optional logging.
Returns
A method decorator that applies caching logic.
Remarks
- Cache behavior can be customized via
cacheKey
,ttl
, andcacheHandler
. - Errors are thrown immediately and **not cached** to allow retries.
function engine
engine: (options?: { id: string }) => ClassDecorator;
A class decorator that enhances a class with execution engine capabilities.
Parameter options
Configuration options for the execution engine.
function execute
execute: { <INPUT extends unknown[], OUTPUT, RESPONSE = OUTPUT, ERROR = RESPONSE>( blockFunction: (...params: INPUT) => OUTPUT, inputs: INPUT, extraInputs?: Record<string, unknown>[], successCallback?: (output: OUTPUT, isPromise: boolean) => RESPONSE, errorCallback?: (error: unknown, isPromise: boolean) => ERROR ): RESPONSE; <INPUT extends unknown[], OUTPUT, RESPONSE = OUTPUT, ERROR = RESPONSE>( blockFunction: (...params: INPUT) => Promise<OUTPUT>, inputs?: INPUT, extraInputs?: Record<string, unknown>[], successCallback?: (output: OUTPUT, isPromise: boolean) => RESPONSE, errorCallback?: (error: unknown, isPromise: boolean) => ERROR ): Promise<RESPONSE>;};
function executeCache
executeCache: <O>( blockFunction: (...params: unknown[]) => O | Promise<O>, inputs: Array<unknown>, options: CacheOptions & { functionId: string }) => Promise<Promise<O> | O>;
Caches function results to avoid redundant expensive computations If the result is already cached, it returns the cached value; otherwise, it executes the function and stores the result.
This is useful for optimizing expensive computations or API calls by reducing duplicate executions.
Remarks
- Errors are thrown immediately and **not cached** to allow retries.
function executeMemoize
executeMemoize: { <O>( blockFunction: (...params: unknown[]) => Promise<O>, inputs?: Array<unknown>, options?: MemoizeOptions<O> ): Promise<Awaited<O>>; <O>( blockFunction: (...params: unknown[]) => O, inputs?: unknown[], options?: MemoizeOptions<O> ): O;};
function executionTrace
executionTrace: { <O>( blockFunction: (...params: unknown[]) => Promise<O>, inputs?: Array<unknown>, onTraceEvent?: (traceContext: TraceContext<O>) => void, options?: { contextKey?: string; errorStrategy?: 'catch' | 'throw'; injectContextInArgs?: boolean; } ): Promise<ExecutionTrace<Array<unknown>, Awaited<O>>>; <O>( blockFunction: (...params: unknown[]) => O, inputs?: unknown[], onTraceEvent?: (traceContext: TraceContext<O>) => void, options?: { contextKey?: string; errorStrategy?: 'catch' | 'throw'; injectContextInArgs?: boolean; } ): ExecutionTrace<unknown[], O>;};
function isEngineNodeTrace
isEngineNodeTrace: ( config: EngineNodeTrace | EngineNodeData | unknown) => config is Partial<EngineNodeTrace>;
function isExecutionTrace
isExecutionTrace: <I, O>( config: ExecutionTraceExtractor<I, O>) => config is ExecutionTraceExtractor<I, O>;
function memoize
memoize: <O>( onMemoizeEvent?: MemoizeOptions<O>['onMemoizeEvent'], ttl?: number) => MethodDecorator;
Decorator to memoize method executions and prevent redundant calls.
Parameter onMemoizeEvent
Optional callback triggered after checking memory
Parameter ttl
Small duration (in milliseconds) before clearing the stored result, capped at 1000ms to prevent excessive retention.
Returns
A method decorator for applying memoization.
Remarks
Uses
executeMemoize
internally to store and reuse results. A short delay (e.g., 100ms) ensures that multiple rapid calls can reuse the stored result.
function run
run: <O>( options?: TraceOptions<Array<any>, O> | TraceOptions<Array<any>, O>['trace']) => ( target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
A method decorator that enables tracing for the decorated method.
Parameter options
Optional tracing options.
Returns
{Function} - A decorator function.
function trace
trace: <O>( onTraceEvent: (traceContext: TraceContext<O>) => void, additionalContext?: Record<string, any>, options?: { contextKey?: string; errorStrategy?: 'catch' | 'throw'; injectContextInArgs?: boolean; }) => MethodDecorator;
Method decorator to trace function execution, capturing metadata, inputs, outputs, and errors.
Parameter onTraceEvent
handle function of the trace context.
Parameter additionalContext
Additional metadata to attach to the trace context.
Parameter options
Configuration options: -
contextKey
: Key to store trace context on the instance. -errorStrategy
: Determines whether errors should be caught ('catch'
) or thrown ('throw'
). -injectContextInArgs
(boolean): Whether to inject the context (fromcontextKey
) into the function arguments. Defaults tofalse
.Returns
A method decorator that wraps the original function with execution tracing.
Classes
class EngineTask
abstract class EngineTask {}
Represents an abstract EngineTask with a reference to the ExecutionEngine.
property engine
engine: ExecutionEngine<{ [key: string]: unknown }>;
class ExecutionEngine
class ExecutionEngine< CXT extends { [key: string]: unknown; } = { [key: string]: unknown; }> extends TraceableEngine {}
Represents a Contextual Execution with traceability features.
CXT - Type of the context object.
constructor
constructor(options?: { executionDate?: Date; executionId?: string; initialTrace?: EngineTrace;});
Creates an instance of ContextualExecution.
Parameter options
Options for initializing the execution.
Parameter
{Date} [options.executionDate] - Date of the execution.
Parameter
{string} [options.executionId] - Unique identifier for the execution.
Parameter
{string} [options.initialTrace] - The initial trace for the execution.
property context
protected context: { [key: string]: unknown };
property executionDate
protected executionDate: Date;
property executionId
protected executionId: string;
method getContext
getContext: () => CXT;
method getOptions
getOptions: () => { executionDate: Date; executionId: string };
Get the current options of the Execution Engine.
Returns
{Object} An object containing the execution date and ID.
Modifiers
@public
method setContext
setContext: (value: CXT) => ExecutionEngine<CXT>;
method updateContext
updateContext: (partialContext: Partial<CXT>) => ExecutionEngine;
Update the context of the execution with partial information.
Parameter partialContext
Partial context information to update.
Returns
{ExecutionEngine} - The updated ContextualExecution instance.
method updateContextAttribute
updateContextAttribute: <K extends keyof CXT>( key: K, partialContextAttribute: CXT[K]) => ExecutionEngine;
Update a specific attribute of the context object.
Parameter key
The key of the attribute to update.
Parameter partialContextAttribute
Partial information to update for the attribute.
Returns
{ExecutionEngine} - The updated ContextualExecution instance.
class ExecutionTimer
class ExecutionTimer {}
A class for measuring the execution time of code blocks.
constructor
constructor(executionId?: string);
Creates an instance of ExecutionTimer.
Parameter executionId
An optional identifier for the execution timer. Defaults to 'default'.
method getDuration
getDuration: (executionId?: string, fractionDigits?: number) => number;
Gets the duration of the execution timer in milliseconds.
Parameter executionId
An optional identifier for the execution timer. Defaults to 'default'.
Parameter fractionDigits
– The number of digits to appear after the decimal point; should be a value between 0 and 100, inclusive.
Returns
The duration of the execution timer in milliseconds.
method getElapsedTime
getElapsedTime: ( executionId?: string, fractionDigits?: number) => string | undefined;
Gets the human-readable elapsed time of the execution timer.
Parameter executionId
An optional identifier for the execution timer. Defaults to 'default'.
Parameter fractionDigits
– The number of digits to appear after the decimal point; should be a value between 0 and 100, inclusive.
Returns
A string representing the human-readable elapsed time.
method getEndDate
getEndDate: (executionId?: string) => Date | undefined;
Gets the end date of the execution timer.
Parameter executionId
An optional identifier for the execution timer. Defaults to 'default'.
Returns
The end date of the execution timer.
method getInfo
getInfo: ( executionId?: string, durationFractionDigits?: number, elapsedTimeFractionDigits?: number) => TimerDetailsModel;
Gets details of a specific execution timer.
Parameter executionId
The timer ID. Defaults to 'default'.
Parameter durationFractionDigits
Decimal places for milliseconds.
Parameter elapsedTimeFractionDigits
Decimal places for milliseconds.
Returns
An object containing timer details.
method getStartDate
getStartDate: (executionId?: string) => Date | undefined;
Gets the start date of the execution timer.
Parameter executionId
An optional identifier for the execution timer. Defaults to 'default'.
Returns
The start date of the execution timer.
method start
start: (executionId?: string) => void;
Starts the execution timer.
Parameter executionId
An optional identifier for the execution timer. Defaults to 'default'.
method stop
stop: (executionId?: string) => void;
Stops the execution timer.
Parameter executionId
An optional identifier for the execution timer. Defaults to 'default'.
class TraceableEngine
class TraceableEngine {}
Represents a class for traceable execution of functions.
constructor
constructor(initialTrace?: EngineTrace);
Initializes a new instance of the TraceableExecution class.
Parameter initialTrace
The initial trace to be used.
method getNarratives
getNarratives: () => Array<string>;
Retrieves an ordered array of narratives.
Returns
{Array} An array that contains the ordered narratives. If no narratives are found, an empty array is returned.
method getTrace
getTrace: () => EngineTrace;
Gets the execution trace.
Returns
An array containing nodes and edges of the execution trace.
method getTraceNodes
getTraceNodes: () => EngineNode[];
Gets the nodes of the execution trace.
Returns
An array containing nodes of the execution trace.
method initTrace
initTrace: (initialTrace: EngineTrace) => TraceableEngine;
Initializes the trace with given initialTrace.
Parameter initialTrace
The initial trace to initialize: the nodes and edges. {TraceableExecution} - The traceable execution object after initialization.
method pushNarratives
pushNarratives: ( nodeId: EngineNodeTrace['id'], narratives: string | string[]) => this;
Pushes or appends narratives to a trace node.
Parameter nodeId
The ID of the node.
Parameter narratives
The narrative or array of narratives to be processed.
Returns
The updated instance of TraceableExecution.
method run
run: { <O>( blockFunction: (...params: any[]) => Promise<O>, inputs: Array<unknown>, options?: TraceOptions<Array<any>, O> ): Promise<ExecutionTrace<Array<unknown>, Awaited<O>>>; <O>( blockFunction: (...params: any[]) => Promise<O>, inputs: unknown[], options?: Partial<EngineNodeData<unknown, unknown>> ): Promise<ExecutionTrace<unknown[], Awaited<O>>>; <O>( blockFunction: (...params: any[]) => O, inputs: unknown[], options?: TraceOptions<any[], O> ): ExecutionTrace<unknown[], O>; <O>( blockFunction: (...params: any[]) => O, inputs: unknown[], options?: Partial<EngineNodeData<unknown, unknown>> ): ExecutionTrace<unknown[], O>;};
ATTENTION: TS chooses the first fitting overload in top-down order, so overloads are sorted from most specific to most broad. ATTENTION: arrow function as blockFunction could be caught by this one, even if it doesn't return a promise prefer using real functions with function keyword!! ATTENTION: functions that return a promise will fit here BUT should be mentioned with ASYNC keyword to work correctly! prefer to use functions with the ASYNC keyword even if rechecking is available so that functions with returned promises are executed safely
ATTENTION: arrow function as blockFunction ARE NOT RECOMMENDED it will work correctly at the overload inferring level to get this signature. It will be caught as a Promise in the signature before!! Especially if you do:
() => { throw new Error("error example");}prefer using real functions with function keyword!!
class TraceableExecution
class TraceableExecution extends TraceableEngine {}
Deprecated
Use
TraceableEngine
instead.⚠️
TraceableExecution
is deprecated and will be removed in a future release. Migrate toTraceableEngine
to ensure compatibility with future updates.
Interfaces
interface CacheContext
interface CacheContext<O = unknown> {}
Represents the context of a cache function execution, providing details such as metadata, inputs, cache status, and value.
property cacheKey
cacheKey: string;
Unique key identifying the cache entry.
property inputs
inputs: Array<unknown>;
The inputs passed to the function.
property isBypassed
isBypassed: boolean;
Flag indicating whether the cached value is bypassed and a fresh computation is triggered.
property isCached
isCached: boolean;
Flag indicating whether the value is found in the cache. @remarks: To confirm it was retrieved from cache, ensure
isBypassed
isfalse
.
property metadata
metadata: FunctionMetadata;
Metadata associated with the function being executed.
property ttl
ttl: number;
The time-to-live (TTL) for the cache entry.
property value
value?: O;
The cached value, if any.
interface CacheOptions
interface CacheOptions<O = unknown> {}
Configuration options for caching behavior.
property bypass
bypass?: (params: { metadata: FunctionMetadata; inputs: unknown[] }) => boolean;
A function that returns
true
to ignore existing cache and force a fresh computation. Defaults tofalse
.
property cacheKey
cacheKey?: (params: { metadata: FunctionMetadata; inputs: unknown[] }) => string;
Function to generate a custom cache key based on method metadata and arguments.
property cacheManager
cacheManager?: CacheStore | ((...args: unknown[]) => CacheStore);
The cache provider or manager used for storing the cache (e.g., in-memory or Redis).
property onCacheEvent
onCacheEvent?: (info: CacheContext<O>) => void;
Callback for handling cache events, providing full access to cache details via
CacheContext
. allowing additional actions based on caching behavior.
property ttl
ttl: | number | ((params: { metadata: FunctionMetadata; inputs: unknown[] }) => number);
Time-to-live (TTL) for cache items. Can be static (number) or dynamic (function that returns a number).
interface CacheStore
interface CacheStore {}
Interface for a cache store that provides methods to interact with cached data.
interface Edge
interface Edge extends EngineEdge {}
Deprecated
Use
EngineEdge
instead.⚠️
Edge
is deprecated and will be removed in a future release. Migrate toEngineEdge
to ensure compatibility with future updates.
interface EdgeData
interface EdgeData extends EngineEdgeData {}
Deprecated
Use
EngineEdgeData
instead.⚠️
EdgeData
is deprecated and will be removed in a future release. Migrate toEngineEdgeData
to ensure compatibility with future updates.
interface EngineEdge
interface EngineEdge {}
Represents an edge in the engine, which defines a relationship or connection between nodes.
interface EngineEdgeData
interface EngineEdgeData {}
interface EngineNode
interface EngineNode {}
Represents a node in the engine, which is an individual component or entity.
interface EngineNodeData
interface EngineNodeData<I = unknown, O = unknown> extends EngineNodeTrace, ExecutionTrace<I, O> {}
interface EngineNodeTrace
interface EngineNodeTrace {}
property abstract
abstract?: boolean;
property createTime
createTime?: Date;
property id
id: string;
property label
label: string;
property parallel
parallel?: boolean | string;
property parent
parent?: string;
property updateTime
updateTime?: Date;
interface ExecutionTrace
interface ExecutionTrace<I, O> {}
Represents an execution trace with information about inputs, outputs, errors, and timing.
property duration
duration?: number;
property elapsedTime
elapsedTime?: string;
property endTime
endTime?: Date;
property errors
errors?: unknown;
property id
id: string;
property inputs
inputs?: I;
property isPromise
isPromise?: boolean;
property narratives
narratives?: Array<string>;
property outputs
outputs?: O;
property startTime
startTime?: Date;
interface ExecutionTraceExtractor
interface ExecutionTraceExtractor<I, O> {}
Defines how to extract specific data from an
ExecutionTrace
.Each property can either be a: -
boolean
: Iftrue
, include all data for the property. -Array<string>
: A list of specific keys to extract from the property. -Function
: A function that processes the data of the property and returns a value.
property endTime
endTime?: boolean;
property errors
errors?: boolean | Array<string> | ((e: Array<unknown>) => unknown);
property inputs
inputs?: boolean | Array<string> | ((i: I) => unknown);
property narratives
narratives?: | boolean | Array<string> | ((execTrace: Partial<ExecutionTrace<I, O>>) => Array<string>);
property outputs
outputs?: boolean | Array<string> | ((o: O) => unknown);
property startTime
startTime?: boolean;
interface FunctionMetadata
interface FunctionMetadata {}
Metadata extracted from a function or a method.
- If the function is a method of a class,
class
represents the class name, andmethod
represents the method name. - Otherwise, these properties are undefined.
property class
class?: string;
If the function is a class method, this represents the class name.
property isAsync
isAsync: boolean;
Indicates if the function is asynchronous.
property isBound
isBound: boolean;
Whether the function is bound to a specific context.
property method
method?: string | symbol;
If the function is a class method, this represents the method name.
property methodSignature
methodSignature?: string;
The full method signature, including parameters, if available.
property name
name: string;
The function name, or "anonymous" if unnamed.
property parameters
parameters: string[];
List of parameter names extracted from the function definition.
interface MemoizationContext
interface MemoizationContext<O> {}
Represents the context of a memoized function execution.
property inputsHash
inputsHash: string;
property isMemoized
isMemoized: boolean;
property metadata
metadata: FunctionMetadata;
property value
value?: Promise<O> | O;
interface MemoizeOptions
interface MemoizeOptions<O> {}
property functionId
functionId: string;
Unique identifier for the function being memoized
property onMemoizeEvent
onMemoizeEvent?: (info: MemoizationContext<O>) => void;
Custom handler for memoization logic
property ttl
ttl?: number;
Optional small expiration time in milliseconds for the memoized result. @remarks: Default is 100ms, capped at 1000ms to prevent excessive retention.
interface Node
interface Node extends EngineNode {}
Deprecated
Use
EngineNode
instead.⚠️
Node
is deprecated and will be removed in a future release. Migrate toEngineNode
to ensure compatibility with future updates.
interface NodeData
interface NodeData extends EngineNodeData {}
Deprecated
Use
EngineNodeData
instead.⚠️
NodeData
is deprecated and will be removed in a future release. Migrate toEngineNodeData
to ensure compatibility with future updates.
interface NodeExecutionTrace
interface NodeExecutionTrace<I, O> extends ExecutionTrace<I, O> {}
Deprecated
Use
ExecutionTrace
instead.⚠️
NodeExecutionTrace
is deprecated and will be removed in a future release. Migrate toExecutionTrace
to ensure compatibility with future updates.
interface NodeExecutionTraceExtractor
interface NodeExecutionTraceExtractor<I, O> extends ExecutionTraceExtractor<I, O> {}
Deprecated
Use
ExecutionTraceExtractor
instead.⚠️
NodeExecutionTraceExtractor
is deprecated and will be removed in a future release. Migrate toExecutionTraceExtractor
to ensure compatibility with future updates.
interface NodeTrace
interface NodeTrace extends EngineNodeTrace {}
Deprecated
Use
EngineNodeTrace
instead.⚠️
NodeTrace
is deprecated and will be removed in a future release. Migrate toEngineNodeTrace
to ensure compatibility with future updates.
interface TimerDetailsModel
interface TimerDetailsModel {}
Represents details of a timed execution.
property duration
duration: number | undefined;
Total execution time in milliseconds.
property elapsedTime
elapsedTime: string | undefined;
Human-readable duration of the execution.
property endTime
endTime: Date | undefined;
The timestamp when execution ended.
property executionId
executionId: string;
Unique identifier for the execution.
property startTime
startTime: Date | undefined;
The timestamp when execution started.
interface TraceContext
interface TraceContext<O> extends ExecutionTrace<Array<unknown>, O> {}
property metadata
metadata: FunctionMetadata;
index signature
[key: string]: unknown;
interface TraceOptions
interface TraceOptions<I, O> {}
Type Aliases
type EngineTrace
type EngineTrace = Array<EngineNode | EngineEdge>;
Represents a **graph structure** as an array of **nodes** and **edges** in the engine.
This structure includes: -
EngineNode
: Represents the nodes in the graph, which are individual components or entities with their own properties and characteristics. -EngineEdge
: Represents the edges in the graph, which define the relationships or dependencies between nodes, showing how entities are connected.The array allows for a complete representation of the system as a graph, where nodes are linked by edges, enabling the modeling of workflows, processes, or complex relationships.
type Trace
type Trace = EngineTrace;
Deprecated
Use
EngineTrace
instead.⚠️
Trace
is deprecated and will be removed in a future release. Migrate toEngineTrace
to ensure compatibility with future updates.
Package Files (22)
- dist/common/models/engineEdgeData.model.d.ts
- dist/common/models/engineNodeData.model.d.ts
- dist/common/models/engineTrace.model.d.ts
- dist/common/models/engineTraceOptions.model.d.ts
- dist/common/models/executionCache.model.d.ts
- dist/common/models/executionFunction.model.d.ts
- dist/common/models/executionMemoization.model.d.ts
- dist/common/models/executionTrace.model.d.ts
- dist/common/models/timer.model.d.ts
- dist/engine/executionEngine.d.ts
- dist/engine/executionEngineDecorators.d.ts
- dist/engine/traceableEngine.d.ts
- dist/execution/cache.d.ts
- dist/execution/cache.decorator.d.ts
- dist/execution/execute.d.ts
- dist/execution/memoize.d.ts
- dist/execution/memoize.decorator.d.ts
- dist/execution/trace.d.ts
- dist/execution/trace.decorator.d.ts
- dist/index.d.ts
- dist/timer/executionTimer.d.ts
- dist/trace/traceableExecution.d.ts
Dependencies (0)
No dependencies.
Dev Dependencies (21)
- @commitlint/cli
- @commitlint/config-conventional
- @stylistic/eslint-plugin
- @types/jest
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- barrelsby
- conventional-changelog-cli
- conventional-changelog-conventionalcommits
- eslint
- eslint-config-prettier
- eslint-plugin-check-file
- eslint-plugin-import
- eslint-plugin-prettier
- eslint-plugin-unused-imports
- husky
- jest
- prettier
- ts-jest
- typescript
- typescript-eslint
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/execution-engine
.
- Markdown[](https://www.jsdocs.io/package/execution-engine)
- HTML<a href="https://www.jsdocs.io/package/execution-engine"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5671 ms. - Missing or incorrect documentation? Open an issue for this package.