@ark/attest 0.48.2 → 0.49.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.
- package/out/assert/assertions.d.ts +0 -2
- package/out/assert/assertions.js +0 -2
- package/out/assert/chainableAssertions.d.ts +5 -2
- package/out/assert/chainableAssertions.js +4 -8
- package/out/cache/ts.js +5 -15
- package/out/cli/cli.js +1 -1
- package/out/cli/trace.js +282 -315
- package/out/config.d.ts +0 -1
- package/out/config.js +0 -1
- package/out/tsVersioning.js +37 -32
- package/package.json +4 -4
|
@@ -7,8 +7,6 @@ export type ThrowAssertionErrorContext = {
|
|
|
7
7
|
stack: string;
|
|
8
8
|
};
|
|
9
9
|
export declare const throwAssertionError: ({ stack, ...errorArgs }: ThrowAssertionErrorContext) => never;
|
|
10
|
-
export declare class MissingSnapshotError extends Error {
|
|
11
|
-
}
|
|
12
10
|
export type AssertFn = (expected: unknown, actual: unknown, ctx: AssertionContext) => void;
|
|
13
11
|
export type MappedTypeAssertionResult = {
|
|
14
12
|
actual: unknown;
|
package/out/assert/assertions.js
CHANGED
|
@@ -53,9 +53,12 @@ type snapProperty<expected, kind extends AssertionKind> = {
|
|
|
53
53
|
unwrap: Unwrapper<expected>;
|
|
54
54
|
};
|
|
55
55
|
export type Unwrapper<expected = unknown> = (opts?: UnwrapOptions) => expected;
|
|
56
|
-
export declare const nonOverlappingSatisfiesMessage = "
|
|
56
|
+
export declare const nonOverlappingSatisfiesMessage = "The type of your actual value and expected satisfies constraint have no overlap";
|
|
57
57
|
export type nonOverlappingSatisfiesMessage = typeof nonOverlappingSatisfiesMessage;
|
|
58
|
-
type validateExpectedOverlaps<expected, satisfies> = isDisjoint<expected, satisfies> extends true ? ErrorType<nonOverlappingSatisfiesMessage
|
|
58
|
+
type validateExpectedOverlaps<expected, satisfies> = isDisjoint<expected, satisfies> extends true ? ErrorType<nonOverlappingSatisfiesMessage, {
|
|
59
|
+
actual: expected;
|
|
60
|
+
satisfies: satisfies;
|
|
61
|
+
}> : unknown;
|
|
59
62
|
export type comparableValueAssertion<expected, kind extends AssertionKind> = {
|
|
60
63
|
snap: snapProperty<expected, kind>;
|
|
61
64
|
equals: (value: expected) => nextAssertions<kind>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { caller
|
|
1
|
+
import { caller } from "@ark/fs";
|
|
2
2
|
import { printable, snapshot } from "@ark/util";
|
|
3
3
|
import prettier from "@prettier/sync";
|
|
4
4
|
import { type } from "arktype";
|
|
@@ -7,7 +7,7 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
7
7
|
import { getSnapshotByName, queueSnapshotUpdate, updateExternalSnapshot } from "../cache/snapshots.js";
|
|
8
8
|
import { getConfig } from "../config.js";
|
|
9
9
|
import { chainableNoOpProxy } from "../utils.js";
|
|
10
|
-
import {
|
|
10
|
+
import { TypeAssertionMapping, assertEqualOrMatching, assertEquals, assertSatisfies, callAssertedFunction, getThrownMessage, throwAssertionError } from "./assertions.js";
|
|
11
11
|
export class ChainableAssertions {
|
|
12
12
|
ctx;
|
|
13
13
|
constructor(ctx) {
|
|
@@ -68,13 +68,9 @@ export class ChainableAssertions {
|
|
|
68
68
|
const snapName = this.ctx.lastSnapName ?? "snap";
|
|
69
69
|
const expectedSerialized = snapshot(args[0]);
|
|
70
70
|
if (!args.length || this.ctx.cfg.updateSnapshots) {
|
|
71
|
-
const position = caller();
|
|
72
|
-
if (this.ctx.cfg.failOnMissingSnapshots) {
|
|
73
|
-
throw new MissingSnapshotError(`.${snapName}() at ${positionToString(position)} must be populated.`);
|
|
74
|
-
}
|
|
75
71
|
if (this.snapRequiresUpdate(expectedSerialized)) {
|
|
76
72
|
const snapshotArgs = {
|
|
77
|
-
position,
|
|
73
|
+
position: caller(),
|
|
78
74
|
serializedValue: this.serializedActual,
|
|
79
75
|
snapFunctionName: snapName
|
|
80
76
|
};
|
|
@@ -210,4 +206,4 @@ const formatTypeString = (typeString) => prettier
|
|
|
210
206
|
})
|
|
211
207
|
.slice(declarationPrefix.length)
|
|
212
208
|
.trimEnd();
|
|
213
|
-
export const nonOverlappingSatisfiesMessage = "
|
|
209
|
+
export const nonOverlappingSatisfiesMessage = "The type of your actual value and expected satisfies constraint have no overlap";
|
package/out/cache/ts.js
CHANGED
|
@@ -36,22 +36,12 @@ export class TsServer {
|
|
|
36
36
|
}
|
|
37
37
|
getSourceFileOrThrow(path) {
|
|
38
38
|
const tsPath = path.replaceAll("\\", "/");
|
|
39
|
-
const
|
|
40
|
-
if (
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
throwInternalError(`@ark/attest: TypeScript was unable to resolve expected file at ${tsPath}.\n`);
|
|
39
|
+
const file = this.virtualEnv.getSourceFile(tsPath);
|
|
40
|
+
if (!file) {
|
|
41
|
+
throwInternalError(`TypeScript was unable to resolve expected file at ${path}.\n
|
|
42
|
+
Make sure it is included in your tsconfig.json.`);
|
|
44
43
|
}
|
|
45
|
-
|
|
46
|
-
if (!contents) {
|
|
47
|
-
throwInternalError(`@ark/attest: TypeScript says a file exists at ${tsPath}, but was unable to read its contents.\n`);
|
|
48
|
-
}
|
|
49
|
-
this.virtualEnv.createFile(tsPath, contents);
|
|
50
|
-
const createdFile = this.virtualEnv.getSourceFile(tsPath);
|
|
51
|
-
if (!createdFile) {
|
|
52
|
-
throwInternalError(`@ark/attest: TypeScript tried to create a file at ${tsPath} but was unable to access it.`);
|
|
53
|
-
}
|
|
54
|
-
return createdFile;
|
|
44
|
+
return file;
|
|
55
45
|
}
|
|
56
46
|
}
|
|
57
47
|
export const nearestCallExpressionChild = (node, position) => {
|
package/out/cli/cli.js
CHANGED
|
@@ -12,7 +12,7 @@ const subcommands = {
|
|
|
12
12
|
const baseFileName = basename(fileName());
|
|
13
13
|
const thisFileIndex = process.argv.findIndex(
|
|
14
14
|
// if running from build output in npm, will be a file called `attest`
|
|
15
|
-
// if running from build output in pnpm, will be
|
|
15
|
+
// if running from build output in pnpm, will be cli.js in build output
|
|
16
16
|
s => s.endsWith(baseFileName) || s.endsWith("attest"));
|
|
17
17
|
if (thisFileIndex === -1)
|
|
18
18
|
throw new Error(`Expected to find an argument ending with "${baseFileName}"`);
|
package/out/cli/trace.js
CHANGED
|
@@ -16,148 +16,54 @@ const outputCapture = (() => {
|
|
|
16
16
|
buffer.push(text);
|
|
17
17
|
},
|
|
18
18
|
getBuffer: () => buffer.join("\n"),
|
|
19
|
-
getLines: () => [...buffer],
|
|
20
19
|
clear: () => {
|
|
21
20
|
buffer = [];
|
|
22
21
|
}
|
|
23
22
|
};
|
|
24
23
|
})();
|
|
25
|
-
/**
|
|
26
|
-
* Formats microseconds to a string of milliseconds.
|
|
27
|
-
*/
|
|
28
|
-
const formatMillis = (ms, fractionDigits = 2) => (ms / 1000).toFixed(fractionDigits);
|
|
29
|
-
/**
|
|
30
|
-
* Formats microseconds to a padded string of milliseconds.
|
|
31
|
-
*/
|
|
32
|
-
const formatPaddedMillis = (ms, pad, fractionDigits = 2) => formatMillis(ms, fractionDigits).padStart(pad);
|
|
33
|
-
// Helper to format duration in seconds to a human-readable string
|
|
34
|
-
const formatSeconds = (totalSeconds) => {
|
|
35
|
-
if (totalSeconds < 0)
|
|
36
|
-
totalSeconds = 0;
|
|
37
|
-
const hours = Math.floor(totalSeconds / 3600);
|
|
38
|
-
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
39
|
-
const seconds = Math.floor(totalSeconds % 60);
|
|
40
|
-
if (hours > 0)
|
|
41
|
-
return `about ${hours} hour(s)`;
|
|
42
|
-
if (minutes > 0)
|
|
43
|
-
return `about ${minutes} minute(s)`;
|
|
44
|
-
return `${seconds}s`;
|
|
45
|
-
};
|
|
46
|
-
class ProgressDisplay {
|
|
47
|
-
totalItems;
|
|
48
|
-
processedItems = 0;
|
|
49
|
-
startTime = 0;
|
|
50
|
-
timerId;
|
|
51
|
-
barWidth = 30; // Width of the progress bar itself
|
|
52
|
-
constructor(totalItems) {
|
|
53
|
-
this.totalItems = totalItems;
|
|
54
|
-
if (this.totalItems <= 0)
|
|
55
|
-
this.totalItems = 0;
|
|
56
|
-
}
|
|
57
|
-
start() {
|
|
58
|
-
if (this.totalItems === 0)
|
|
59
|
-
return;
|
|
60
|
-
this.startTime = Date.now();
|
|
61
|
-
this.processedItems = 0;
|
|
62
|
-
this.render(); // Initial render
|
|
63
|
-
// Update every second for elapsed time and ETA
|
|
64
|
-
this.timerId = setInterval(() => this.render(), 1000);
|
|
65
|
-
}
|
|
66
|
-
update(processedCount) {
|
|
67
|
-
if (this.totalItems === 0)
|
|
68
|
-
return;
|
|
69
|
-
this.processedItems = Math.min(processedCount, this.totalItems);
|
|
70
|
-
this.render(); // Re-render on each item processed for immediate feedback
|
|
71
|
-
if (this.processedItems >= this.totalItems)
|
|
72
|
-
this.stop(); // Automatically stop if all items are processed
|
|
73
|
-
}
|
|
74
|
-
render() {
|
|
75
|
-
if (this.totalItems === 0 && this.processedItems === 0 && !this.startTime)
|
|
76
|
-
return; // Avoid rendering if not started for 0 items
|
|
77
|
-
const percent = this.totalItems > 0 ?
|
|
78
|
-
Math.min(100, (this.processedItems / this.totalItems) * 100)
|
|
79
|
-
: 100;
|
|
80
|
-
const filledLength = Math.floor((this.barWidth * percent) / 100);
|
|
81
|
-
const emptyLength = this.barWidth - filledLength;
|
|
82
|
-
const bar = `[${"=".repeat(filledLength)}${" ".repeat(emptyLength)}]`;
|
|
83
|
-
const elapsedMs = Date.now() - this.startTime;
|
|
84
|
-
const elapsedSec = elapsedMs / 1000;
|
|
85
|
-
const formattedElapsed = formatSeconds(elapsedSec);
|
|
86
|
-
let etaStr = "";
|
|
87
|
-
if (this.processedItems > 0 && this.processedItems < this.totalItems) {
|
|
88
|
-
const avgTimePerItemMs = elapsedMs / this.processedItems;
|
|
89
|
-
const remainingItems = this.totalItems - this.processedItems;
|
|
90
|
-
const etaMs = remainingItems * avgTimePerItemMs;
|
|
91
|
-
etaStr = ` (ETA: ${formatSeconds(etaMs / 1000)})`;
|
|
92
|
-
}
|
|
93
|
-
else if (this.processedItems >= this.totalItems && this.totalItems > 0)
|
|
94
|
-
etaStr = " (Done)";
|
|
95
|
-
const summary = `${this.processedItems}/${this.totalItems} entries (${percent.toFixed(0)}%)`;
|
|
96
|
-
const timeInfo = `${formattedElapsed} elapsed${etaStr}`;
|
|
97
|
-
process.stdout.clearLine(0); // Clear the current line
|
|
98
|
-
process.stdout.cursorTo(0); // Move cursor to the beginning of the line
|
|
99
|
-
process.stdout.write(`Processing: ${bar} ${summary} | ${timeInfo}`);
|
|
100
|
-
}
|
|
101
|
-
stop() {
|
|
102
|
-
if (this.timerId) {
|
|
103
|
-
clearInterval(this.timerId);
|
|
104
|
-
this.timerId = undefined;
|
|
105
|
-
}
|
|
106
|
-
if (this.totalItems > 0) {
|
|
107
|
-
this.processedItems = this.totalItems; // Ensure final state is 100%
|
|
108
|
-
this.render(); // Final render
|
|
109
|
-
process.stdout.write("\n"); // Move to the next line
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
24
|
export const trace = async (args) => {
|
|
114
25
|
const packageDir = resolve(args[0] ?? process.cwd());
|
|
115
26
|
const config = getConfig();
|
|
116
27
|
if (!config.tsconfig) {
|
|
117
|
-
// This message should go to console.error and also be captured if needed,
|
|
118
|
-
// but since it exits, direct console.error is fine.
|
|
119
28
|
console.error(`attest trace must be run from a directory with a tsconfig.json file`);
|
|
120
29
|
process.exit(1);
|
|
121
30
|
}
|
|
122
31
|
const traceDir = resolve(config.cacheDir, "trace");
|
|
123
32
|
ensureDir(traceDir);
|
|
33
|
+
let tracingOutput = "";
|
|
124
34
|
outputCapture.clear();
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
outputCapture.write(initialMessages[0]); // This goes to console and buffer
|
|
128
|
-
const tracingOutput = generateTraceData(traceDir, config.tsconfig, packageDir);
|
|
35
|
+
outputCapture.write(`⏳ Gathering type trace data for ${packageDir}...`);
|
|
36
|
+
tracingOutput = generateTraceData(traceDir, config.tsconfig, packageDir);
|
|
129
37
|
const traceFile = join(traceDir, "trace.json");
|
|
130
38
|
if (!existsSync(traceFile)) {
|
|
131
|
-
outputCapture.write(`❌ No trace data found (expected a file at ${
|
|
132
|
-
const summaryPath = join(traceDir, "summary.txt");
|
|
133
|
-
writeFile(summaryPath, outputCapture.getBuffer());
|
|
39
|
+
outputCapture.write(`❌ No trace data found (expected a file at ${join(traceDir, "trace.json")})`);
|
|
134
40
|
return;
|
|
135
41
|
}
|
|
136
|
-
// This message will be followed by the progress bar on the next line
|
|
137
42
|
outputCapture.write(`⏳ Analyzing type trace data for ${packageDir}...`);
|
|
138
|
-
analyzeTypeInstantiations(traceDir);
|
|
139
|
-
//
|
|
140
|
-
//
|
|
141
|
-
const analysisMessages = outputCapture
|
|
142
|
-
.getLines()
|
|
143
|
-
.slice(initialMessages.length + 1); // +1 for the "Analyzing..." message
|
|
144
|
-
const summaryContent = [
|
|
145
|
-
...initialMessages,
|
|
146
|
-
tracingOutput,
|
|
147
|
-
outputCapture.getLines()[initialMessages.length], // The "Analyzing..." message
|
|
148
|
-
...analysisMessages
|
|
149
|
-
].join("\n");
|
|
43
|
+
analyzeTypeInstantiations(traceDir);
|
|
44
|
+
// Write summary file containing our messages followed by compiler output
|
|
45
|
+
// This ensures the initial message comes first in the file
|
|
150
46
|
const summaryPath = join(traceDir, "summary.txt");
|
|
47
|
+
const summaryContent = outputCapture.getBuffer().split("\n")[0] +
|
|
48
|
+
"\n" +
|
|
49
|
+
tracingOutput +
|
|
50
|
+
"\n" +
|
|
51
|
+
outputCapture.getBuffer().split("\n").slice(1).join("\n");
|
|
151
52
|
writeFile(summaryPath, summaryContent);
|
|
152
53
|
};
|
|
153
54
|
const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
|
|
154
55
|
try {
|
|
56
|
+
// Capture the output instead of just displaying it
|
|
155
57
|
const output = getShellOutput(`${baseDiagnosticTscCmd} --project ${tsconfigPath} --generateTrace ${traceDir}`, { cwd: packageDir });
|
|
156
|
-
|
|
58
|
+
// Display the output to the console as before
|
|
59
|
+
process.stdout.write(output);
|
|
157
60
|
return output;
|
|
158
61
|
}
|
|
159
|
-
catch (
|
|
160
|
-
|
|
62
|
+
catch (_) {
|
|
63
|
+
// even if tsc returns a non-zero exit code,
|
|
64
|
+
// we can still proceed as long as the trace.json
|
|
65
|
+
// file was generated
|
|
66
|
+
const e = _;
|
|
161
67
|
const output = e.stdout ?? "";
|
|
162
68
|
const errorOutput = e.stderr ?? "";
|
|
163
69
|
process.stdout.write(output);
|
|
@@ -167,10 +73,10 @@ const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
|
|
|
167
73
|
};
|
|
168
74
|
const initializeAnalysisContext = (traceDir) => {
|
|
169
75
|
const tsServer = TsServer.instance;
|
|
76
|
+
// Load trace data
|
|
170
77
|
const tracePath = join(traceDir, "trace.json");
|
|
171
|
-
if (!existsSync(tracePath))
|
|
172
|
-
throw new Error(`
|
|
173
|
-
}
|
|
78
|
+
if (!existsSync(tracePath))
|
|
79
|
+
throw new Error(`Expected a trace file at ${tracePath}`);
|
|
174
80
|
const traceEntries = readJson(tracePath);
|
|
175
81
|
return {
|
|
176
82
|
traceDir,
|
|
@@ -184,111 +90,147 @@ const initializeAnalysisContext = (traceDir) => {
|
|
|
184
90
|
};
|
|
185
91
|
};
|
|
186
92
|
const filterDurationEntries = (ctx) => {
|
|
187
|
-
ctx.durationEntries = ctx.traceEntries.filter(entry =>
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
typeof args.pos === "number" &&
|
|
194
|
-
typeof args.end === "number");
|
|
195
|
-
});
|
|
196
|
-
// This message goes to outputCapture for the summary file
|
|
197
|
-
outputCapture.write(`Found ${ctx.durationEntries.length} complete event traces with duration, path, and position.`);
|
|
93
|
+
ctx.durationEntries = ctx.traceEntries.filter(entry => entry.ph === "X" &&
|
|
94
|
+
entry.dur !== undefined &&
|
|
95
|
+
entry.args.path &&
|
|
96
|
+
entry.args.pos &&
|
|
97
|
+
entry.args.end);
|
|
98
|
+
outputCapture.write(`Found ${ctx.durationEntries.length} traces with duration information`);
|
|
198
99
|
};
|
|
199
100
|
const processDurationEntry = (entry, ctx) => {
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
functionName
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
|
-
else {
|
|
215
|
-
const relevantNode = findMostSpecificNodeInRange(sourceFile, entryPos, entryEnd);
|
|
216
|
-
if (relevantNode) {
|
|
217
|
-
const nodeType = getStringifiableType(relevantNode);
|
|
218
|
-
const nodeKind = ts.SyntaxKind[relevantNode.kind];
|
|
219
|
-
const typeName = `${nodeKind}: ${nodeType.toString().substring(0, 25)}`;
|
|
220
|
-
const typeNodeIdPart = nodeType.id ?? nodeType.toString().substring(0, 20);
|
|
221
|
-
callRangeData = {
|
|
222
|
-
typeId: `node-${relevantNode.kind}-${typeNodeIdPart}`,
|
|
223
|
-
functionName: typeName
|
|
224
|
-
};
|
|
101
|
+
try {
|
|
102
|
+
const sourceFile = ctx.tsServer.getSourceFileOrThrow(entry.args.path);
|
|
103
|
+
const pos = entry.args.pos;
|
|
104
|
+
const end = entry.args.end;
|
|
105
|
+
// First try to find any call expression in the range
|
|
106
|
+
const callExpr = findCallExpressionInRange(sourceFile, pos, end);
|
|
107
|
+
if (callExpr)
|
|
108
|
+
processCallExpression(callExpr, entry, pos, end, ctx);
|
|
109
|
+
else {
|
|
110
|
+
// Try to process as another type of node
|
|
111
|
+
processNonCallNode(sourceFile, entry, pos, end, ctx);
|
|
225
112
|
}
|
|
226
113
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
id: `${entry.ts}-${entryPos}-${entryEnd}`,
|
|
230
|
-
typeId: callRangeData.typeId,
|
|
231
|
-
functionName: callRangeData.functionName,
|
|
232
|
-
callSite: `${entryPath}:${entryPos}-${entryEnd}`,
|
|
233
|
-
startTime: entry.ts,
|
|
234
|
-
endTime: entry.ts + entryDur,
|
|
235
|
-
duration: entryDur,
|
|
236
|
-
children: [],
|
|
237
|
-
selfTime: entryDur
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
else {
|
|
241
|
-
throw new Error(`Failed to identify a processable AST node for duration entry (name: ${entry.name}, path: ${entryPath}, pos: ${entryPos}-${entryEnd}).`);
|
|
114
|
+
catch (e) {
|
|
115
|
+
handleProcessingError(e, entry);
|
|
242
116
|
}
|
|
243
117
|
};
|
|
118
|
+
/**
|
|
119
|
+
* Find any call expression within the given range, with preference for method calls
|
|
120
|
+
*/
|
|
244
121
|
const findCallExpressionInRange = (file, start, end) => {
|
|
122
|
+
// First try the default nearest bounding call expression
|
|
245
123
|
const boundingCall = nearestBoundingCallExpression(file, start);
|
|
246
|
-
if (boundingCall
|
|
124
|
+
if (boundingCall)
|
|
247
125
|
return boundingCall;
|
|
126
|
+
// If that fails, search for any call expressions in the range
|
|
248
127
|
const allNodes = getDescendants(file);
|
|
249
128
|
const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
|
|
129
|
+
// Find all call expressions in the range
|
|
250
130
|
const callExpressions = nodesInRange.filter(node => ts.isCallExpression(node));
|
|
251
131
|
if (callExpressions.length === 0)
|
|
252
132
|
return undefined;
|
|
133
|
+
// Prioritize method calls (e.g. x.and(), x.or())
|
|
253
134
|
const methodCalls = callExpressions.filter(call => ts.isPropertyAccessExpression(call.expression));
|
|
135
|
+
// Return a method call if found, otherwise the first call expression
|
|
254
136
|
return methodCalls.length > 0 ? methodCalls[0] : callExpressions[0];
|
|
255
137
|
};
|
|
138
|
+
/**
|
|
139
|
+
* Extract function or method name from a call expression, normalizing the format
|
|
140
|
+
*/
|
|
256
141
|
const extractFunctionName = (callExpr) => {
|
|
142
|
+
// For method calls like x.and()
|
|
257
143
|
if (ts.isPropertyAccessExpression(callExpr.expression))
|
|
258
144
|
return callExpr.expression.name.getText();
|
|
145
|
+
// For direct function calls like type() or scope()
|
|
259
146
|
if (ts.isIdentifier(callExpr.expression))
|
|
260
147
|
return callExpr.expression.getText();
|
|
261
|
-
|
|
148
|
+
// For other expressions, try to get a reasonable name
|
|
149
|
+
return "anonymous";
|
|
150
|
+
};
|
|
151
|
+
const processCallExpression = (callExpr, entry, pos, end, ctx) => {
|
|
152
|
+
// Simply use the function name for grouping
|
|
153
|
+
const functionName = extractFunctionName(callExpr);
|
|
154
|
+
// Use the function name for both ID and display name
|
|
155
|
+
// This will ensure all calls to the same function are grouped together
|
|
156
|
+
const typeId = `function-${functionName}`;
|
|
157
|
+
const callSite = `${entry.args.path}:${pos}-${end}`;
|
|
158
|
+
ctx.callRanges.push({
|
|
159
|
+
id: `${entry.ts}-${pos}-${end}`,
|
|
160
|
+
typeId,
|
|
161
|
+
functionName,
|
|
162
|
+
callSite,
|
|
163
|
+
startTime: entry.ts,
|
|
164
|
+
endTime: entry.ts + (entry.dur || 0),
|
|
165
|
+
duration: entry.dur || 0,
|
|
166
|
+
children: [],
|
|
167
|
+
selfTime: entry.dur || 0
|
|
168
|
+
});
|
|
169
|
+
};
|
|
170
|
+
const processNonCallNode = (sourceFile, entry, pos, end, ctx) => {
|
|
171
|
+
const relevantNode = findMostSpecificNodeInRange(sourceFile, pos, end);
|
|
172
|
+
if (!relevantNode)
|
|
173
|
+
return;
|
|
174
|
+
const nodeType = getStringifiableType(relevantNode);
|
|
175
|
+
const nodeKind = ts.SyntaxKind[relevantNode.kind];
|
|
176
|
+
const typeName = `${nodeKind}: ${nodeType.toString().substring(0, 25)}`;
|
|
177
|
+
const typeId = `node-${relevantNode.kind}-${nodeType.id || nodeType.toString().substring(0, 20)}`;
|
|
178
|
+
const callSite = `${entry.args.path}:${pos}-${end}`;
|
|
179
|
+
ctx.callRanges.push({
|
|
180
|
+
id: `${entry.ts}-${pos}-${end}`,
|
|
181
|
+
typeId,
|
|
182
|
+
functionName: typeName,
|
|
183
|
+
callSite,
|
|
184
|
+
startTime: entry.ts,
|
|
185
|
+
endTime: entry.ts + (entry.dur || 0),
|
|
186
|
+
duration: entry.dur || 0,
|
|
187
|
+
children: [],
|
|
188
|
+
selfTime: entry.dur || 0
|
|
189
|
+
});
|
|
190
|
+
};
|
|
191
|
+
const handleProcessingError = (e, entry) => {
|
|
192
|
+
if (!(e instanceof Error))
|
|
193
|
+
throw e;
|
|
194
|
+
// Silent failure for common case of not finding a call expression
|
|
195
|
+
if (e.message?.includes("Unable to find bounding call expression"))
|
|
196
|
+
return;
|
|
197
|
+
console.warn(`Error processing entry at ${entry.args.path}:${entry.args.pos}: ${e.message}`);
|
|
262
198
|
};
|
|
263
199
|
const buildCallTree = (ctx) => {
|
|
264
|
-
//
|
|
265
|
-
outputCapture.write(`Building call tree from ${ctx.callRanges.length} ranges...`);
|
|
200
|
+
// Sort by start time for nesting analysis
|
|
266
201
|
ctx.callRanges.sort((a, b) => a.startTime - b.startTime);
|
|
267
202
|
const activeCallStack = [];
|
|
268
203
|
for (const call of ctx.callRanges) {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
activeCallStack.pop();
|
|
272
|
-
if (activeCallStack.length === 0)
|
|
273
|
-
ctx.rootCalls.push(call);
|
|
274
|
-
else {
|
|
275
|
-
const parent = activeCallStack[activeCallStack.length - 1];
|
|
276
|
-
parent.children.push(call);
|
|
277
|
-
}
|
|
204
|
+
popFinishedCalls(call, activeCallStack);
|
|
205
|
+
assignToParentOrRoot(call, activeCallStack, ctx);
|
|
278
206
|
activeCallStack.push(call);
|
|
279
207
|
}
|
|
280
|
-
|
|
208
|
+
};
|
|
209
|
+
const popFinishedCalls = (call, activeCallStack) => {
|
|
210
|
+
while (activeCallStack.length > 0 &&
|
|
211
|
+
activeCallStack[activeCallStack.length - 1].endTime < call.startTime)
|
|
212
|
+
activeCallStack.pop();
|
|
213
|
+
};
|
|
214
|
+
const assignToParentOrRoot = (call, activeCallStack, ctx) => {
|
|
215
|
+
if (activeCallStack.length === 0) {
|
|
216
|
+
// This is a root call
|
|
217
|
+
ctx.rootCalls.push(call);
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
// This call is nested inside the current active call
|
|
221
|
+
const parent = activeCallStack[activeCallStack.length - 1];
|
|
222
|
+
parent.children.push(call);
|
|
223
|
+
}
|
|
281
224
|
};
|
|
282
225
|
const calculateSelfTimes = (call) => {
|
|
283
226
|
let childrenTime = 0;
|
|
284
227
|
for (const child of call.children)
|
|
285
228
|
childrenTime += calculateSelfTimes(child);
|
|
286
229
|
call.selfTime = call.duration - childrenTime;
|
|
287
|
-
if (call.selfTime < 0)
|
|
288
|
-
call.selfTime = 0;
|
|
289
230
|
return call.duration;
|
|
290
231
|
};
|
|
291
232
|
const collectFunctionStats = (call, ctx) => {
|
|
233
|
+
// Initialize stats object if needed
|
|
292
234
|
if (!ctx.functionStats[call.typeId]) {
|
|
293
235
|
ctx.functionStats[call.typeId] = {
|
|
294
236
|
typeId: call.typeId,
|
|
@@ -301,120 +243,103 @@ const collectFunctionStats = (call, ctx) => {
|
|
|
301
243
|
};
|
|
302
244
|
}
|
|
303
245
|
const stats = ctx.functionStats[call.typeId];
|
|
246
|
+
// Track detailed call site information
|
|
247
|
+
addCallSiteToStats(call, stats);
|
|
248
|
+
// Update aggregate metrics
|
|
249
|
+
stats.totalTime += call.duration;
|
|
250
|
+
stats.selfTime += call.selfTime;
|
|
251
|
+
stats.count++;
|
|
252
|
+
// Process children
|
|
253
|
+
for (const child of call.children)
|
|
254
|
+
collectFunctionStats(child, ctx);
|
|
255
|
+
};
|
|
256
|
+
const addCallSiteToStats = (call, stats) => {
|
|
304
257
|
const [filePath, positionRange] = call.callSite.split(":");
|
|
305
|
-
if (!filePath || !positionRange)
|
|
306
|
-
throw new Error(`Invalid callSite format: ${call.callSite}`);
|
|
307
258
|
const [posStr, endStr] = positionRange.split("-");
|
|
308
|
-
const pos = parseInt(posStr, 10);
|
|
309
|
-
const end = parseInt(endStr, 10);
|
|
310
|
-
if (isNaN(pos) || isNaN(end)) {
|
|
311
|
-
throw new Error(`Invalid position in callSite: ${call.callSite}. Pos: ${posStr}, End: ${endStr}`);
|
|
312
|
-
}
|
|
313
259
|
stats.detailedCallSites.push({
|
|
314
260
|
path: filePath,
|
|
315
|
-
pos,
|
|
316
|
-
end,
|
|
261
|
+
pos: parseInt(posStr),
|
|
262
|
+
end: parseInt(endStr),
|
|
317
263
|
selfTime: call.selfTime
|
|
318
264
|
});
|
|
319
|
-
stats.totalTime += call.duration;
|
|
320
|
-
stats.selfTime += call.selfTime;
|
|
321
|
-
stats.count++;
|
|
322
|
-
for (const child of call.children)
|
|
323
|
-
collectFunctionStats(child, ctx);
|
|
324
265
|
};
|
|
325
266
|
const sortAndRankFunctions = (ctx) => {
|
|
326
|
-
|
|
267
|
+
// Sort each function's call sites by self-time
|
|
327
268
|
for (const stats of Object.values(ctx.functionStats))
|
|
328
269
|
stats.detailedCallSites.sort((a, b) => b.selfTime - a.selfTime);
|
|
270
|
+
// Sort functions by self-time
|
|
329
271
|
ctx.allFunctions = Object.values(ctx.functionStats).sort((a, b) => b.selfTime - a.selfTime);
|
|
330
272
|
};
|
|
331
273
|
const analyzeTypeInstantiations = (traceDir) => {
|
|
274
|
+
// Initialize the analysis context
|
|
332
275
|
const ctx = initializeAnalysisContext(traceDir);
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
const progressDisplay = new ProgressDisplay(totalEntries);
|
|
342
|
-
progressDisplay.start();
|
|
343
|
-
for (const [index, entry] of ctx.durationEntries.entries()) {
|
|
344
|
-
try {
|
|
345
|
-
processDurationEntry(entry, ctx);
|
|
346
|
-
}
|
|
347
|
-
catch (e) {
|
|
348
|
-
progressDisplay.stop(); // Stop progress before printing error via outputCapture
|
|
349
|
-
outputCapture.write(`\n❌ Error processing entry ${index + 1}/${totalEntries} (Path: ${entry.args.path ?? "N/A"}, Pos: ${entry.args.pos ?? "N/A"}): ${e.message}`);
|
|
350
|
-
outputCapture.write("Aborting analysis due to error.");
|
|
351
|
-
// Early exit, summary will be written by the main trace function
|
|
352
|
-
return;
|
|
353
|
-
}
|
|
354
|
-
progressDisplay.update(index + 1);
|
|
355
|
-
}
|
|
356
|
-
progressDisplay.stop(); // Ensure it's stopped if loop finished
|
|
357
|
-
// Subsequent messages use outputCapture and will appear after the progress bar
|
|
358
|
-
buildCallTree(ctx); // Uses outputCapture
|
|
359
|
-
outputCapture.write("Calculating self-times for call tree nodes...");
|
|
276
|
+
// Filter entries with duration information
|
|
277
|
+
filterDurationEntries(ctx);
|
|
278
|
+
// Process each duration entry to extract call ranges
|
|
279
|
+
for (const entry of ctx.durationEntries)
|
|
280
|
+
processDurationEntry(entry, ctx);
|
|
281
|
+
// Build call tree from ranges
|
|
282
|
+
buildCallTree(ctx);
|
|
283
|
+
// Calculate self-time for each call
|
|
360
284
|
for (const root of ctx.rootCalls)
|
|
361
285
|
calculateSelfTimes(root);
|
|
362
|
-
|
|
363
|
-
const ungroupedStats = collectUngroupedStats(ctx);
|
|
364
|
-
for (const
|
|
365
|
-
collectFunctionStats(
|
|
366
|
-
|
|
286
|
+
// Collect statistics by view type
|
|
287
|
+
const ungroupedStats = collectUngroupedStats(ctx);
|
|
288
|
+
for (const call of ctx.rootCalls)
|
|
289
|
+
collectFunctionStats(call, ctx);
|
|
290
|
+
// Sort and rank functions
|
|
291
|
+
sortAndRankFunctions(ctx);
|
|
292
|
+
// Display summaries to console
|
|
367
293
|
outputCapture.write("\n📊 Performance Analysis - Top Individual Calls:\n");
|
|
368
|
-
displayIndividualSummary(ungroupedStats);
|
|
294
|
+
displayIndividualSummary(ungroupedStats);
|
|
369
295
|
outputCapture.write("\n📊 Performance Analysis - Functions by Self Time:\n");
|
|
370
|
-
displayGroupedSummary(ctx.allFunctions);
|
|
296
|
+
displayGroupedSummary(ctx.allFunctions);
|
|
297
|
+
// Write CSV reports
|
|
371
298
|
const rangesCsvPath = join(traceDir, "ranges.csv");
|
|
372
299
|
const namesCsvPath = join(traceDir, "names.csv");
|
|
373
|
-
const
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
}
|
|
410
|
-
else {
|
|
411
|
-
outputCapture.write(`\n✅ Analysis complete! No call ranges processed to export to CSV. Summary written to:\n` +
|
|
412
|
-
` - ${summaryFilePath}`);
|
|
413
|
-
}
|
|
300
|
+
const summaryPath = join(traceDir, "summary.txt");
|
|
301
|
+
// Export individual ranges to CSV
|
|
302
|
+
writeToCsv(rangesCsvPath, ["Function Name", "Self (ms)", "Duration (ms)", "Location"], ungroupedStats.map(stat => [
|
|
303
|
+
stat.functionName,
|
|
304
|
+
(stat.selfTime / 1000).toFixed(3),
|
|
305
|
+
(stat.duration / 1000).toFixed(3),
|
|
306
|
+
formatLocation(stat.callSite)
|
|
307
|
+
]));
|
|
308
|
+
// Export grouped functions to CSV
|
|
309
|
+
writeToCsv(namesCsvPath, [
|
|
310
|
+
"Function Name",
|
|
311
|
+
"Total Self (ms)",
|
|
312
|
+
"Avg Self (ms)",
|
|
313
|
+
"Call Count",
|
|
314
|
+
"Top Location",
|
|
315
|
+
"Top Self (ms)"
|
|
316
|
+
], ctx.allFunctions.map(stats => {
|
|
317
|
+
const topUsage = stats.detailedCallSites[0] || {
|
|
318
|
+
path: "unknown",
|
|
319
|
+
pos: 0,
|
|
320
|
+
end: 0,
|
|
321
|
+
selfTime: 0
|
|
322
|
+
};
|
|
323
|
+
return [
|
|
324
|
+
stats.functionName,
|
|
325
|
+
(stats.selfTime / 1000).toFixed(3),
|
|
326
|
+
(stats.selfTime / stats.count / 1000).toFixed(3),
|
|
327
|
+
stats.count.toString(),
|
|
328
|
+
formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`),
|
|
329
|
+
(topUsage.selfTime / 1000).toFixed(3)
|
|
330
|
+
];
|
|
331
|
+
}));
|
|
332
|
+
outputCapture.write(`\n✅ Analysis complete! Results exported to:\n` +
|
|
333
|
+
` - ${rangesCsvPath} (individual calls)\n` +
|
|
334
|
+
` - ${namesCsvPath} (grouped by function name)\n` +
|
|
335
|
+
` - ${summaryPath} (complete analysis report)`);
|
|
414
336
|
};
|
|
337
|
+
/**
|
|
338
|
+
* Collect statistics for individual (ungrouped) calls
|
|
339
|
+
*/
|
|
415
340
|
const collectUngroupedStats = (ctx) => {
|
|
416
|
-
outputCapture.write("Collecting and sorting ungrouped call statistics...");
|
|
417
341
|
const ungroupedStats = [];
|
|
342
|
+
// Flatten the call tree into individual entries
|
|
418
343
|
const flattenCallTree = (call) => {
|
|
419
344
|
ungroupedStats.push({
|
|
420
345
|
typeId: call.typeId,
|
|
@@ -428,35 +353,46 @@ const collectUngroupedStats = (ctx) => {
|
|
|
428
353
|
};
|
|
429
354
|
for (const root of ctx.rootCalls)
|
|
430
355
|
flattenCallTree(root);
|
|
356
|
+
// Sort by self time in descending order
|
|
431
357
|
return ungroupedStats.sort((a, b) => b.selfTime - a.selfTime);
|
|
432
358
|
};
|
|
359
|
+
/**
|
|
360
|
+
* Display a summary of individual calls
|
|
361
|
+
*/
|
|
433
362
|
const displayIndividualSummary = (stats) => {
|
|
434
363
|
displayTableHeader(["Rank", "Function Name", "Self (ms)", "Location"]);
|
|
435
|
-
const
|
|
436
|
-
for (
|
|
437
|
-
const stat = stats[i];
|
|
364
|
+
const top20 = stats.slice(0, 20);
|
|
365
|
+
for (const [index, stat] of top20.entries()) {
|
|
438
366
|
const typeNameFormatted = formatTypeName(stat.functionName, 20);
|
|
439
|
-
const selfTimeMs =
|
|
367
|
+
const selfTimeMs = (stat.selfTime / 1000).toFixed(2).padStart(15);
|
|
440
368
|
const location = formatLocation(stat.callSite);
|
|
441
|
-
outputCapture.write(`${(
|
|
369
|
+
outputCapture.write(`${(index + 1).toString().padStart(4)} | ${typeNameFormatted} | ${selfTimeMs} | ${location}`);
|
|
442
370
|
}
|
|
443
371
|
};
|
|
372
|
+
/**
|
|
373
|
+
* Display a summary table header with aligned columns
|
|
374
|
+
*/
|
|
444
375
|
const displayTableHeader = (columns) => {
|
|
376
|
+
// Create header row with standard column widths
|
|
445
377
|
const headerRow = [
|
|
446
378
|
columns[0].padEnd(4),
|
|
447
379
|
columns[1].padEnd(20),
|
|
448
380
|
columns[2].padEnd(15),
|
|
449
381
|
...columns.slice(3)
|
|
450
382
|
].join(" | ");
|
|
383
|
+
// Create separator line matching the header column widths
|
|
451
384
|
const separatorRow = [
|
|
452
|
-
"
|
|
453
|
-
"
|
|
454
|
-
"
|
|
385
|
+
"----",
|
|
386
|
+
"--------------------",
|
|
387
|
+
"---------------",
|
|
455
388
|
...columns.slice(3).map(col => "-".repeat(col.length))
|
|
456
389
|
].join("-|-");
|
|
457
390
|
outputCapture.write(headerRow);
|
|
458
391
|
outputCapture.write(separatorRow);
|
|
459
392
|
};
|
|
393
|
+
/**
|
|
394
|
+
* Display a combined summary of grouped functions showing both total and average times
|
|
395
|
+
*/
|
|
460
396
|
const displayGroupedSummary = (functions) => {
|
|
461
397
|
displayTableHeader([
|
|
462
398
|
"Rank",
|
|
@@ -466,84 +402,109 @@ const displayGroupedSummary = (functions) => {
|
|
|
466
402
|
"Calls",
|
|
467
403
|
"Top Usage"
|
|
468
404
|
]);
|
|
469
|
-
const
|
|
470
|
-
for (let i = 0; i < topN; i++) {
|
|
471
|
-
const stats = functions[i];
|
|
405
|
+
for (const [index, stats] of functions.slice(0, 20).entries()) {
|
|
472
406
|
const typeNameFormatted = formatTypeName(stats.functionName, 20);
|
|
473
|
-
const totalTimeMs =
|
|
474
|
-
const avgTimeMs =
|
|
407
|
+
const totalTimeMs = (stats.selfTime / 1000).toFixed(2).padStart(15);
|
|
408
|
+
const avgTimeMs = (stats.selfTime / stats.count / 1000)
|
|
409
|
+
.toFixed(2)
|
|
410
|
+
.padStart(13);
|
|
475
411
|
const calls = stats.count.toString().padStart(5);
|
|
476
|
-
|
|
412
|
+
// Get details about top usage site
|
|
413
|
+
const topUsage = stats.detailedCallSites[0] || {
|
|
477
414
|
path: "unknown",
|
|
478
415
|
pos: 0,
|
|
479
416
|
end: 0,
|
|
480
417
|
selfTime: 0
|
|
481
418
|
};
|
|
482
|
-
const topUsageTime =
|
|
419
|
+
const topUsageTime = (topUsage.selfTime / 1000).toFixed(2) + "ms";
|
|
483
420
|
const topUsageLocation = formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`);
|
|
484
|
-
outputCapture.write(`${(
|
|
421
|
+
outputCapture.write(`${(index + 1).toString().padStart(4)} | ${typeNameFormatted} | ${totalTimeMs} | ${avgTimeMs} | ${calls} | ${topUsageLocation} (${topUsageTime})`);
|
|
485
422
|
}
|
|
486
423
|
};
|
|
424
|
+
/**
|
|
425
|
+
* Format a type name for display, ensuring the most identifiable parts are preserved
|
|
426
|
+
*/
|
|
487
427
|
const formatTypeName = (typeName, maxLength) => {
|
|
428
|
+
// Remove any () from the name
|
|
488
429
|
typeName = typeName.replace(/\(\)$/, "");
|
|
489
430
|
if (typeName.length <= maxLength)
|
|
490
431
|
return typeName.padEnd(maxLength);
|
|
491
|
-
|
|
492
|
-
const
|
|
432
|
+
// Default truncation strategy
|
|
433
|
+
const charsToKeep = maxLength - 3; // Account for "..."
|
|
434
|
+
const firstPart = Math.ceil(charsToKeep * 0.7); // Keep more of the start
|
|
493
435
|
const lastPart = charsToKeep - firstPart;
|
|
494
436
|
return (typeName.substring(0, firstPart) +
|
|
495
437
|
"..." +
|
|
496
438
|
(lastPart > 0 ? typeName.substring(typeName.length - lastPart) : "")).padEnd(maxLength);
|
|
497
439
|
};
|
|
440
|
+
/**
|
|
441
|
+
* Format a file location to be more readable with relative path and line:char
|
|
442
|
+
*/
|
|
498
443
|
const formatLocation = (location) => {
|
|
499
|
-
if (!location || location === "unknown"
|
|
500
|
-
return
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
444
|
+
if (!location || location === "unknown")
|
|
445
|
+
return "unknown";
|
|
446
|
+
// Extract file path and position range
|
|
447
|
+
const [filePath, positionRange] = location.split(":");
|
|
448
|
+
try {
|
|
449
|
+
const relativePath = relative(process.cwd(), filePath);
|
|
450
|
+
// Get position values
|
|
451
|
+
const [posStr] = positionRange.split("-");
|
|
452
|
+
const pos = parseInt(posStr);
|
|
453
|
+
// Get the source file to convert position to line:character
|
|
454
|
+
const sourceFile = TsServer.instance.getSourceFileOrThrow(filePath);
|
|
455
|
+
const lineAndChar = sourceFile.getLineAndCharacterOfPosition(pos);
|
|
456
|
+
// Format as relative-path:line:char
|
|
457
|
+
return `${relativePath}:${lineAndChar.line + 1}:${lineAndChar.character + 1}`;
|
|
458
|
+
}
|
|
459
|
+
catch {
|
|
460
|
+
// If any part fails, return the basic filename as fallback
|
|
461
|
+
return basename(filePath) + (positionRange ? `:${positionRange}` : "");
|
|
462
|
+
}
|
|
514
463
|
};
|
|
464
|
+
/**
|
|
465
|
+
* Finds the most specific non-trivial node within the given range
|
|
466
|
+
*/
|
|
515
467
|
const findMostSpecificNodeInRange = (file, start, end) => {
|
|
468
|
+
// Get all descendants in the file
|
|
516
469
|
const allNodes = getDescendants(file);
|
|
470
|
+
// Filter nodes that are completely contained within our range
|
|
517
471
|
const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
|
|
518
|
-
|
|
519
|
-
return undefined;
|
|
472
|
+
// Find most specific nodes (leaf nodes)
|
|
520
473
|
const leafNodes = nodesInRange.filter(node => !nodesInRange.some(other => other !== node && other.pos >= node.pos && other.end <= node.end));
|
|
521
|
-
|
|
474
|
+
// Find nodes in order of preference
|
|
475
|
+
return findNodeByPreference(leafNodes);
|
|
522
476
|
};
|
|
523
477
|
const findNodeByPreference = (nodes) => {
|
|
524
|
-
|
|
525
|
-
return undefined;
|
|
478
|
+
// 1. Type references
|
|
526
479
|
const typeReference = nodes.find(node => ts.isTypeReferenceNode(node) || ts.isTypeQueryNode(node));
|
|
527
480
|
if (typeReference)
|
|
528
481
|
return typeReference;
|
|
482
|
+
// 2. Declarations
|
|
529
483
|
const declaration = nodes.find(node => ts.isVariableDeclaration(node) ||
|
|
530
484
|
ts.isFunctionDeclaration(node) ||
|
|
531
485
|
ts.isClassDeclaration(node) ||
|
|
532
486
|
ts.isInterfaceDeclaration(node));
|
|
533
487
|
if (declaration)
|
|
534
488
|
return declaration;
|
|
489
|
+
// 3. Property accesses
|
|
535
490
|
const propertyAccess = nodes.find(node => ts.isPropertyAccessExpression(node));
|
|
536
491
|
if (propertyAccess)
|
|
537
492
|
return propertyAccess;
|
|
493
|
+
// 4. Assignments
|
|
538
494
|
const assignment = nodes.find(node => ts.isBinaryExpression(node) &&
|
|
539
495
|
node.operatorToken.kind === ts.SyntaxKind.EqualsToken);
|
|
540
496
|
if (assignment)
|
|
541
497
|
return assignment;
|
|
498
|
+
// 5. Expressions
|
|
542
499
|
const expression = nodes.find(node => ts.isExpressionStatement(node) || ts.isExpression(node));
|
|
543
500
|
if (expression)
|
|
544
501
|
return expression;
|
|
545
|
-
|
|
502
|
+
// Default: first node
|
|
503
|
+
return nodes[0];
|
|
546
504
|
};
|
|
505
|
+
/**
|
|
506
|
+
* Write data to a CSV file
|
|
507
|
+
*/
|
|
547
508
|
const writeToCsv = (filePath, headers, rows) => {
|
|
548
509
|
const content = [
|
|
549
510
|
headers.join(","),
|
|
@@ -551,8 +512,14 @@ const writeToCsv = (filePath, headers, rows) => {
|
|
|
551
512
|
].join("\n");
|
|
552
513
|
writeFile(filePath, content);
|
|
553
514
|
};
|
|
515
|
+
/**
|
|
516
|
+
* Escape string for CSV format
|
|
517
|
+
*/
|
|
554
518
|
const escapeForCsv = (value) => {
|
|
555
|
-
if (value.includes(",") || value.includes('"') || value.includes("\n"))
|
|
519
|
+
if (value.includes(",") || value.includes('"') || value.includes("\n")) {
|
|
520
|
+
// If the value contains commas, double quotes, or newlines, wrap it in quotes
|
|
521
|
+
// and escape any double quotes by doubling them
|
|
556
522
|
return `"${value.replaceAll('"', '""')}"`;
|
|
523
|
+
}
|
|
557
524
|
return value;
|
|
558
525
|
};
|
package/out/config.d.ts
CHANGED
|
@@ -8,7 +8,6 @@ type BaseAttestConfig = {
|
|
|
8
8
|
tsconfig: string | null | undefined;
|
|
9
9
|
compilerOptions: ts.CompilerOptions;
|
|
10
10
|
updateSnapshots: boolean;
|
|
11
|
-
failOnMissingSnapshots: boolean;
|
|
12
11
|
/** A string or list of strings representing the TypeScript version aliases to run.
|
|
13
12
|
*
|
|
14
13
|
* Aliases must be specified as a package.json dependency or devDependency beginning with "typescript".
|
package/out/config.js
CHANGED
|
@@ -7,7 +7,6 @@ export const getDefaultAttestConfig = () => ({
|
|
|
7
7
|
tsconfig: existsSync(fromCwd("tsconfig.json")) ? fromCwd("tsconfig.json") : undefined,
|
|
8
8
|
compilerOptions: {},
|
|
9
9
|
attestAliases: ["attest", "attestInternal"],
|
|
10
|
-
failOnMissingSnapshots: "CI" in process.env,
|
|
11
10
|
updateSnapshots: false,
|
|
12
11
|
skipTypes: false,
|
|
13
12
|
skipInlineInstantiations: false,
|
package/out/tsVersioning.js
CHANGED
|
@@ -111,39 +111,14 @@ export const findAttestTypeScriptVersions = () => {
|
|
|
111
111
|
if (!existsSync(nodeModulesPath) ||
|
|
112
112
|
!statSync(nodeModulesPath).isDirectory())
|
|
113
113
|
continue;
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
const fullPath = join(nodeModulesPath, dirName);
|
|
121
|
-
if (!statSync(fullPath).isDirectory())
|
|
122
|
-
continue;
|
|
123
|
-
const alias = getDirAlias(dirName);
|
|
124
|
-
if (!alias)
|
|
125
|
-
continue;
|
|
126
|
-
// Skip if we already found this alias in a closer package
|
|
127
|
-
if (foundVersionAliases.has(alias))
|
|
128
|
-
continue;
|
|
129
|
-
const version = getTsVersion(fullPath);
|
|
130
|
-
if (version) {
|
|
131
|
-
foundVersionAliases.add(alias);
|
|
132
|
-
versions.push({
|
|
133
|
-
alias,
|
|
134
|
-
version,
|
|
135
|
-
path: fullPath
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
// Check for @ark/attest-ts-* directories
|
|
140
|
-
const arkDir = join(nodeModulesPath, "@ark");
|
|
141
|
-
if (existsSync(arkDir) && statSync(arkDir).isDirectory()) {
|
|
142
|
-
const arkDirs = readdirSync(arkDir);
|
|
143
|
-
for (const dirName of arkDirs) {
|
|
144
|
-
if (!dirName.startsWith("attest-ts-"))
|
|
114
|
+
try {
|
|
115
|
+
// Check for regular typescript or typescript-* directories
|
|
116
|
+
const dirNames = readdirSync(nodeModulesPath);
|
|
117
|
+
for (const dirName of dirNames) {
|
|
118
|
+
// Skip node_modules/@* directories - we'll handle them below
|
|
119
|
+
if (dirName.startsWith("@"))
|
|
145
120
|
continue;
|
|
146
|
-
const fullPath = join(
|
|
121
|
+
const fullPath = join(nodeModulesPath, dirName);
|
|
147
122
|
if (!statSync(fullPath).isDirectory())
|
|
148
123
|
continue;
|
|
149
124
|
const alias = getDirAlias(dirName);
|
|
@@ -162,6 +137,36 @@ export const findAttestTypeScriptVersions = () => {
|
|
|
162
137
|
});
|
|
163
138
|
}
|
|
164
139
|
}
|
|
140
|
+
// Check for @ark/attest-ts-* directories
|
|
141
|
+
const arkDir = join(nodeModulesPath, "@ark");
|
|
142
|
+
if (existsSync(arkDir) && statSync(arkDir).isDirectory()) {
|
|
143
|
+
const arkDirs = readdirSync(arkDir);
|
|
144
|
+
for (const dirName of arkDirs) {
|
|
145
|
+
if (!dirName.startsWith("attest-ts-"))
|
|
146
|
+
continue;
|
|
147
|
+
const fullPath = join(arkDir, dirName);
|
|
148
|
+
if (!statSync(fullPath).isDirectory())
|
|
149
|
+
continue;
|
|
150
|
+
const alias = getDirAlias(dirName);
|
|
151
|
+
if (!alias)
|
|
152
|
+
continue;
|
|
153
|
+
// Skip if we already found this alias in a closer package
|
|
154
|
+
if (foundVersionAliases.has(alias))
|
|
155
|
+
continue;
|
|
156
|
+
const version = getTsVersion(fullPath);
|
|
157
|
+
if (version) {
|
|
158
|
+
foundVersionAliases.add(alias);
|
|
159
|
+
versions.push({
|
|
160
|
+
alias,
|
|
161
|
+
version,
|
|
162
|
+
path: fullPath
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
console.warn(`Warning: Error scanning ${nodeModulesPath}: ${err}`);
|
|
165
170
|
}
|
|
166
171
|
}
|
|
167
172
|
return versions;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ark/attest",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.49.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "David Blass",
|
|
@@ -36,9 +36,9 @@
|
|
|
36
36
|
"@typescript/analyze-trace": "0.10.1",
|
|
37
37
|
"@typescript/vfs": "1.6.1",
|
|
38
38
|
"prettier": "3.5.3",
|
|
39
|
-
"
|
|
40
|
-
"@ark/util": "0.
|
|
41
|
-
"
|
|
39
|
+
"@ark/fs": "0.49.0",
|
|
40
|
+
"@ark/util": "0.49.0",
|
|
41
|
+
"arktype": "2.1.22"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"typescript": "5.8.2"
|