tracenest-node 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,167 @@
1
+ 'use strict';
2
+
3
+ const { createStyler, shouldEnableColor, formatDuration, formatTime } = require('../utils/formatting');
4
+
5
+ class ConsoleReporter {
6
+ /**
7
+ * Renders the trace report as a string.
8
+ *
9
+ * @param {object} reportData
10
+ * @param {object} [options]
11
+ * @param {boolean} [options.color] Enable or disable colors
12
+ * @param {boolean} [options.showTimeline=true]
13
+ * @param {boolean} [options.showTree=true]
14
+ * @param {boolean} [options.showSlow=true]
15
+ * @param {boolean} [options.showFailures=true]
16
+ * @returns {string}
17
+ */
18
+ render(reportData, options = {}) {
19
+ const useColor = shouldEnableColor(options);
20
+ const s = createStyler(useColor);
21
+ const lines = [];
22
+
23
+ const summary = reportData.summary || {};
24
+ const slowOps = reportData.slowOperations || [];
25
+ const tree = reportData.tree || [];
26
+ const events = reportData.events || [];
27
+ const errors = reportData.errors || [];
28
+
29
+ // Header
30
+ lines.push('');
31
+ lines.push(s.bold(s.cyan('========================================================')));
32
+ lines.push(s.bold(s.cyan(` TRACENEST EXECUTION REPORT `)));
33
+ lines.push(s.bold(s.cyan('========================================================')));
34
+ lines.push('');
35
+
36
+ // Summary Section
37
+ lines.push(s.bold(s.white('--- Summary ---')));
38
+ lines.push(` Trace ID: ${s.dim(reportData.traceId || 'N/A')}`);
39
+ lines.push(` Total Operations: ${s.bold(String(summary.totalOperations || 0))}`);
40
+ lines.push(` Successful Operations: ${s.green(String(summary.successfulOperations || 0))}`);
41
+ const failedStr = (summary.failedOperations || 0) > 0
42
+ ? s.red(String(summary.failedOperations))
43
+ : '0';
44
+ lines.push(` Failed Operations: ${failedStr}`);
45
+ lines.push(` Success Rate: ${summary.successRate !== undefined ? summary.successRate + '%' : '100%'}`);
46
+ lines.push(` Wall-Clock Time: ${s.bold(formatDuration(summary.wallClockTimeMs || summary.totalExecutionTimeMs || 0))}`);
47
+ if (typeof summary.sumOperationDurationMs === 'number') {
48
+ lines.push(` Cumulative Op Time: ${formatDuration(summary.sumOperationDurationMs)}`);
49
+ }
50
+ lines.push(` Average Duration: ${formatDuration(summary.averageDurationMs || 0)}`);
51
+ lines.push(` Min / Max Duration: ${formatDuration(summary.minDurationMs || 0)} / ${formatDuration(summary.maxDurationMs || 0)}`);
52
+ if (summary.percentiles) {
53
+ lines.push(` P50 / P95 Duration: ${formatDuration(summary.percentiles.p50 || 0)} / ${formatDuration(summary.percentiles.p95 || 0)}`);
54
+ }
55
+ lines.push('');
56
+
57
+ // Failed Operations Section
58
+ if (options.showFailures !== false && errors.length > 0) {
59
+ lines.push(s.bold(s.red('--- Failed Operations ---')));
60
+ for (const errItem of errors) {
61
+ const opDuration = typeof errItem.durationMs === 'number' ? ` (${formatDuration(errItem.durationMs)})` : '';
62
+ const errMsg = errItem.error && errItem.error.message ? errItem.error.message : 'Unknown error';
63
+ lines.push(` ${s.red('[FAILED]')} ${s.bold(errItem.name)}${opDuration} - ${s.red(errMsg)}`);
64
+ }
65
+ lines.push('');
66
+ }
67
+
68
+ // Slow Operations Section
69
+ if (options.showSlow !== false && slowOps.length > 0) {
70
+ lines.push(s.bold(s.yellow(`--- Slow Operations (Threshold: >= ${slowOps[0].thresholdMs}ms) ---`)));
71
+ for (const op of slowOps) {
72
+ const badge = op.status === 'ERROR' ? s.red('[FAILED]') : s.yellow('[SLOW]');
73
+ lines.push(` ${badge} ${s.bold(op.name)} - ${s.yellow(formatDuration(op.durationMs))} (threshold: ${op.thresholdMs}ms)`);
74
+ }
75
+ lines.push('');
76
+ }
77
+
78
+ // Hierarchical Operation Tree Section
79
+ if (options.showTree !== false && tree.length > 0) {
80
+ lines.push(s.bold(s.white('--- Operation Hierarchy Tree ---')));
81
+ for (const root of tree) {
82
+ this._renderTreeNode(root, '', true, lines, s);
83
+ }
84
+ lines.push('');
85
+ }
86
+
87
+ // Execution Timeline Section
88
+ if (options.showTimeline !== false && events.length > 0) {
89
+ lines.push(s.bold(s.white('--- Execution Timeline ---')));
90
+ for (const evt of events) {
91
+ const timeStr = formatTime(evt.timestamp);
92
+ const typeBadge = this._formatTypeBadge(evt.type, s);
93
+ const indent = ' '.repeat(evt.depth || 0);
94
+ let durationStr = '';
95
+ if (typeof evt.durationMs === 'number') {
96
+ durationStr = ` ${s.dim(`(${formatDuration(evt.durationMs)})`)}`;
97
+ }
98
+ let errorSnippet = '';
99
+ if (evt.error && evt.error.message) {
100
+ errorSnippet = ` ${s.red(`- Error: ${evt.error.message}`)}`;
101
+ }
102
+ lines.push(` ${s.gray(timeStr)} ${typeBadge} ${indent}${evt.name}${durationStr}${errorSnippet}`);
103
+ }
104
+ lines.push('');
105
+ }
106
+
107
+ lines.push(s.bold(s.cyan('========================================================')));
108
+ lines.push('');
109
+
110
+ return lines.join('\n');
111
+ }
112
+
113
+ /**
114
+ * Prints the rendered report to console.
115
+ * @param {object} reportData
116
+ * @param {object} [options]
117
+ */
118
+ print(reportData, options = {}) {
119
+ const output = this.render(reportData, options);
120
+ console.log(output);
121
+ }
122
+
123
+ _formatTypeBadge(type, s) {
124
+ switch (type) {
125
+ case 'START':
126
+ return s.blue('START ');
127
+ case 'CALL':
128
+ return s.cyan('CALL ');
129
+ case 'SUCCESS':
130
+ return s.green('SUCCESS');
131
+ case 'ERROR':
132
+ return s.red('ERROR ');
133
+ case 'WARNING':
134
+ return s.yellow('WARNING');
135
+ case 'TRACK':
136
+ return s.magenta('TRACK ');
137
+ case 'END':
138
+ return s.blue('END ');
139
+ default:
140
+ return (type || 'UNKNOWN').padEnd(7, ' ');
141
+ }
142
+ }
143
+
144
+ _renderTreeNode(node, prefix, isLast, lines, s) {
145
+ const connector = isLast ? '└── ' : '├── ';
146
+ const statusColor = node.status === 'ERROR' ? s.red : (node.status === 'SUCCESS' ? s.green : s.yellow);
147
+ const duration = typeof node.durationMs === 'number' ? ` [${formatDuration(node.durationMs)}]` : '';
148
+ const status = ` (${statusColor(node.status)})`;
149
+ let errorDetail = '';
150
+ if (node.status === 'ERROR' && node.error && node.error.message) {
151
+ errorDetail = ` ${s.red(`- Error: ${node.error.message}`)}`;
152
+ }
153
+ const line = ` ${prefix}${connector}${s.bold(node.name)}${status}${duration}${errorDetail}`;
154
+ lines.push(line);
155
+
156
+ const childPrefix = prefix + (isLast ? ' ' : '│ ');
157
+ const children = node.children || [];
158
+ for (let i = 0; i < children.length; i++) {
159
+ const isLastChild = i === children.length - 1;
160
+ this._renderTreeNode(children[i], childPrefix, isLastChild, lines, s);
161
+ }
162
+ }
163
+ }
164
+
165
+ module.exports = {
166
+ ConsoleReporter
167
+ };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ class JsonReporter {
7
+ /**
8
+ * Generates a serialized JSON string representing the full trace data.
9
+ *
10
+ * @param {object} reportData
11
+ * @param {object} [options]
12
+ * @param {number|string} [options.indent=2]
13
+ * @returns {string}
14
+ */
15
+ render(reportData, options = {}) {
16
+ const indent = options.indent !== undefined ? options.indent : 2;
17
+ return JSON.stringify(reportData, null, indent);
18
+ }
19
+
20
+ /**
21
+ * Exports the trace report data to a JSON file.
22
+ *
23
+ * @param {string} filePath File path to write to
24
+ * @param {object} reportData Trace report payload
25
+ * @param {object} [options]
26
+ * @returns {string} Resolved file path
27
+ */
28
+ export(filePath, reportData, options = {}) {
29
+ if (!filePath || typeof filePath !== 'string') {
30
+ throw new TypeError('TraceNest.exportJSON requires a valid file path string.');
31
+ }
32
+
33
+ const resolvedPath = path.resolve(process.cwd(), filePath);
34
+ const dir = path.dirname(resolvedPath);
35
+
36
+ if (!fs.existsSync(dir)) {
37
+ fs.mkdirSync(dir, { recursive: true });
38
+ }
39
+
40
+ const jsonString = this.render(reportData, options);
41
+ fs.writeFileSync(resolvedPath, jsonString, 'utf8');
42
+
43
+ return resolvedPath;
44
+ }
45
+ }
46
+
47
+ module.exports = {
48
+ JsonReporter
49
+ };
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ const { formatDuration, formatTime } = require('./time');
4
+
5
+ // ANSI Color escapes
6
+ const ESC = '\x1b[';
7
+ const colors = {
8
+ reset: `${ESC}0m`,
9
+ bold: `${ESC}1m`,
10
+ dim: `${ESC}2m`,
11
+ italic: `${ESC}3m`,
12
+ underline: `${ESC}4m`,
13
+ red: `${ESC}31m`,
14
+ green: `${ESC}32m`,
15
+ yellow: `${ESC}33m`,
16
+ blue: `${ESC}34m`,
17
+ magenta: `${ESC}35m`,
18
+ cyan: `${ESC}36m`,
19
+ white: `${ESC}37m`,
20
+ gray: `${ESC}90m`,
21
+ bgRed: `${ESC}41m`,
22
+ bgGreen: `${ESC}42m`,
23
+ bgYellow: `${ESC}43m`,
24
+ bgBlue: `${ESC}44m`
25
+ };
26
+
27
+ /**
28
+ * Colorizer function factory that respects color enable/disable flag.
29
+ * @param {boolean} enabled
30
+ */
31
+ function createStyler(enabled = true) {
32
+ const style = (colorCode, text) => (enabled ? `${colorCode}${text}${colors.reset}` : String(text));
33
+
34
+ return {
35
+ bold: (t) => style(colors.bold, t),
36
+ dim: (t) => style(colors.dim, t),
37
+ red: (t) => style(colors.red, t),
38
+ green: (t) => style(colors.green, t),
39
+ yellow: (t) => style(colors.yellow, t),
40
+ blue: (t) => style(colors.blue, t),
41
+ magenta: (t) => style(colors.magenta, t),
42
+ cyan: (t) => style(colors.cyan, t),
43
+ gray: (t) => style(colors.gray, t),
44
+ white: (t) => style(colors.white, t)
45
+ };
46
+ }
47
+
48
+ /**
49
+ * Checks whether colors should be enabled based on options and environment.
50
+ * @param {object} [options]
51
+ * @returns {boolean}
52
+ */
53
+ function shouldEnableColor(options = {}) {
54
+ if (options.color === false || options.noColor) return false;
55
+ if (process.env.NO_COLOR && process.env.NO_COLOR !== '0') return false;
56
+ if (options.color === true) return true;
57
+ return Boolean(process.stdout && process.stdout.isTTY);
58
+ }
59
+
60
+ module.exports = {
61
+ colors,
62
+ createStyler,
63
+ shouldEnableColor,
64
+ formatDuration,
65
+ formatTime
66
+ };
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('node:crypto');
4
+
5
+ let counter = 0;
6
+
7
+ /**
8
+ * Generate a unique ID with an optional prefix.
9
+ * Combines crypto random bytes and an incrementing counter for absolute uniqueness.
10
+ * @param {string} prefix
11
+ * @returns {string}
12
+ */
13
+ function generateId(prefix = 'id') {
14
+ counter = (counter + 1) & 0xffffff;
15
+ const counterHex = counter.toString(16).padStart(6, '0');
16
+ if (typeof crypto.randomUUID === 'function') {
17
+ const raw = crypto.randomUUID().replace(/-/g, '').slice(0, 16);
18
+ return `${prefix}_${raw}_${counterHex}`;
19
+ }
20
+ const randomHex = crypto.randomBytes(8).toString('hex');
21
+ return `${prefix}_${randomHex}_${counterHex}`;
22
+ }
23
+
24
+ module.exports = {
25
+ generateId,
26
+ createTraceId: () => generateId('trc'),
27
+ createOperationId: () => generateId('op'),
28
+ createEventId: () => generateId('evt'),
29
+ createRequestId: () => generateId('req')
30
+ };
@@ -0,0 +1,61 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Returns high-resolution time in milliseconds.
5
+ * Uses process.hrtime.bigint() for microsecond-level accuracy.
6
+ * @returns {bigint}
7
+ */
8
+ function getHrTime() {
9
+ return process.hrtime.bigint();
10
+ }
11
+
12
+ /**
13
+ * Calculates elapsed milliseconds between a start bigint and now (or end bigint).
14
+ * @param {bigint} startHrTime
15
+ * @param {bigint} [endHrTime]
16
+ * @returns {number} duration in milliseconds rounded to 3 decimal places
17
+ */
18
+ function calcElapsedMs(startHrTime, endHrTime = process.hrtime.bigint()) {
19
+ const diffNs = endHrTime - startHrTime;
20
+ const ms = Number(diffNs) / 1e6;
21
+ return Math.round(ms * 1000) / 1000;
22
+ }
23
+
24
+ /**
25
+ * Formats a Date or timestamp as HH:mm:ss.SSS
26
+ * @param {number|Date} [date]
27
+ * @returns {string}
28
+ */
29
+ function formatTime(date = Date.now()) {
30
+ const d = date instanceof Date ? date : new Date(date);
31
+ const hours = String(d.getHours()).padStart(2, '0');
32
+ const minutes = String(d.getMinutes()).padStart(2, '0');
33
+ const seconds = String(d.getSeconds()).padStart(2, '0');
34
+ const millis = String(d.getMilliseconds()).padStart(3, '0');
35
+ return `${hours}:${minutes}:${seconds}.${millis}`;
36
+ }
37
+
38
+ /**
39
+ * Formats duration into human-readable string (e.g. 1.25ms, 450.00ms, 2.34s)
40
+ * @param {number} ms
41
+ * @returns {string}
42
+ */
43
+ function formatDuration(ms) {
44
+ if (ms === null || ms === undefined || Number.isNaN(ms)) {
45
+ return '0.00ms';
46
+ }
47
+ if (ms < 0.001) {
48
+ return '<0.01ms';
49
+ }
50
+ if (ms < 1000) {
51
+ return `${ms.toFixed(2)}ms`;
52
+ }
53
+ return `${(ms / 1000).toFixed(2)}s`;
54
+ }
55
+
56
+ module.exports = {
57
+ getHrTime,
58
+ calcElapsedMs,
59
+ formatTime,
60
+ formatDuration
61
+ };