@ark/attest 0.45.11 → 0.48.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/README.md CHANGED
@@ -298,7 +298,7 @@ If you'd like to fail in CI above a threshold, you can add flags like the follow
298
298
 
299
299
  ## CLI
300
300
 
301
- Attest also includes a builtin `attest` CLI including the following commands:
301
+ Attest also includes a built-in `attest` CLI including the following commands:
302
302
 
303
303
  ### `stats`
304
304
 
@@ -19,7 +19,7 @@ export const attestInternal = (value, { cfg: cfgHooks, ...ctxHooks } = {}) => {
19
19
  };
20
20
  if (!cfg.skipTypes) {
21
21
  ctx.typeRelationshipAssertionEntries = getTypeAssertionsAtPosition(position);
22
- if (ctx.typeRelationshipAssertionEntries[0]?.[1].typeArgs[0]) {
22
+ if (ctx.typeRelationshipAssertionEntries[0][1].typeArgs[0]) {
23
23
  // if there is an expected type arg, check it immediately
24
24
  assertEquals(undefined, typeEqualityMapping, ctx);
25
25
  }
@@ -29,7 +29,7 @@ export const attestInternal = (value, { cfg: cfgHooks, ...ctxHooks } = {}) => {
29
29
  export const attest = Object.assign(attestInternal, {
30
30
  instantiations: (args) => {
31
31
  const attestConfig = getConfig();
32
- if (attestConfig.skipTypes || attestConfig.skipInlineInstantiations)
32
+ if (attestConfig.skipInlineInstantiations)
33
33
  return;
34
34
  const calledFrom = caller();
35
35
  const ctx = getBenchCtx([calledFrom.file]);
@@ -29,7 +29,6 @@ export declare class ChainableAssertions implements AssertionRecord {
29
29
  get throws(): unknown;
30
30
  throwsAndHasTypeError(matchValue: string | RegExp): void;
31
31
  get completions(): any;
32
- get jsdoc(): any;
33
32
  get type(): any;
34
33
  }
35
34
  export type AssertionKind = "value" | "type";
@@ -65,7 +64,6 @@ export type comparableValueAssertion<expected, kind extends AssertionKind> = {
65
64
  instanceOf: (constructor: Constructor) => nextAssertions<kind>;
66
65
  is: (value: expected) => nextAssertions<kind>;
67
66
  completions: CompletionsSnap;
68
- jsdoc: comparableValueAssertion<string, kind>;
69
67
  satisfies: <const def>(def: type.validate<def> & validateExpectedOverlaps<expected, type.infer.In<def>>) => nextAssertions<kind>;
70
68
  unknown: Omit<comparableValueAssertion<unknown, kind>, "unknown">;
71
69
  unwrap: Unwrapper<expected>;
@@ -160,15 +160,6 @@ export class ChainableAssertions {
160
160
  this.ctx.lastSnapName = "completions";
161
161
  return this.snap;
162
162
  }
163
- get jsdoc() {
164
- if (this.ctx.cfg.skipTypes)
165
- return chainableNoOpProxy;
166
- this.ctx.versionableActual = new TypeAssertionMapping(data => ({
167
- actual: formatTypeString(data.jsdoc ?? "")
168
- }));
169
- this.ctx.allowRegex = true;
170
- return this.immediateOrChained();
171
- }
172
163
  get type() {
173
164
  if (this.ctx.cfg.skipTypes)
174
165
  return chainableNoOpProxy;
package/out/cache/ts.d.ts CHANGED
@@ -12,7 +12,6 @@ export declare class TsServer {
12
12
  getSourceFileOrThrow(path: string): ts.SourceFile;
13
13
  }
14
14
  export declare const nearestCallExpressionChild: (node: ts.Node, position: number) => ts.CallExpression;
15
- export declare const nearestBoundingCallExpression: (node: ts.Node, position: number) => ts.CallExpression | undefined;
16
15
  export declare const getAbsolutePosition: (file: ts.SourceFile, position: SourcePosition) => number;
17
16
  export type TsconfigInfo = {
18
17
  path: string | undefined;
package/out/cache/ts.js CHANGED
@@ -1,4 +1,4 @@
1
- import { fromCwd, readFile } from "@ark/fs";
1
+ import { fromCwd } from "@ark/fs";
2
2
  import { printable, throwError, throwInternalError } from "@ark/util";
3
3
  import * as tsvfs from "@typescript/vfs";
4
4
  import { readFileSync } from "node:fs";
@@ -21,14 +21,7 @@ export class TsServer {
21
21
  const tsLibPaths = getTsLibFiles(this.tsConfigInfo.parsed.options);
22
22
  // TS represents windows paths as `C:/Users/ssalb/...`
23
23
  const normalizedCwd = fromCwd().replaceAll(/\\/g, "/");
24
- this.rootFiles = this.tsConfigInfo.parsed.fileNames.filter(path => {
25
- if (!path.startsWith(normalizedCwd))
26
- return;
27
- // exclude empty files as they lead to a crash
28
- // when createVirtualTypeScriptEnvironment is called
29
- const contents = readFile(path).trim();
30
- return contents !== "";
31
- });
24
+ this.rootFiles = this.tsConfigInfo.parsed.fileNames.filter(path => path.startsWith(normalizedCwd));
32
25
  const system = tsvfs.createFSBackedSystem(tsLibPaths.defaultMapFromNodeModules, this.tsConfigInfo.path ? dirname(this.tsConfigInfo.path) : fromCwd(), ts);
33
26
  this.virtualEnv = tsvfs.createVirtualTypeScriptEnvironment(system, this.rootFiles, ts, this.tsConfigInfo.parsed.options);
34
27
  this.program = this.virtualEnv.languageService.getProgram();
@@ -37,10 +30,8 @@ export class TsServer {
37
30
  getSourceFileOrThrow(path) {
38
31
  const tsPath = path.replaceAll(/\\/g, "/");
39
32
  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.`);
43
- }
33
+ if (!file)
34
+ throwInternalError(`Could not find TS path ${path}`);
44
35
  return file;
45
36
  }
46
37
  }
@@ -51,7 +42,7 @@ export const nearestCallExpressionChild = (node, position) => {
51
42
  }
52
43
  return result;
53
44
  };
54
- export const nearestBoundingCallExpression = (node, position) => node.pos <= position && node.end >= position ?
45
+ const nearestBoundingCallExpression = (node, position) => node.pos <= position && node.end >= position ?
55
46
  (node
56
47
  .getChildren()
57
48
  .flatMap(child => nearestBoundingCallExpression(child, position) ?? [])[0] ?? (ts.isCallExpression(node) ? node : undefined))
@@ -1,12 +1,8 @@
1
1
  import * as tsvfs from "@typescript/vfs";
2
2
  import ts from "typescript";
3
- import type { LinePositionRange } from "./writeAssertionCache.ts";
3
+ import type { AssertionsByFile, LinePositionRange } from "./writeAssertionCache.ts";
4
4
  export declare const getCallLocationFromCallExpression: (callExpression: ts.CallExpression) => LinePositionRange;
5
- /**
6
- * Processes inline instantiations from an attest call
7
- * Preserves any JSDoc comments that are associated with the original expression
8
- */
9
- export declare const gatherInlineInstantiationData: (file: ts.SourceFile, assertionsByFile: Record<string, any[]>, instantiationMethodCalls: string[]) => void;
5
+ export declare const gatherInlineInstantiationData: (file: ts.SourceFile, fileAssertions: AssertionsByFile, attestAliasInstantiationMethodCalls: string[]) => void;
10
6
  export declare const getCallExpressionsByName: (startNode: ts.Node, names: string[], isSnapCall?: boolean) => ts.CallExpression[];
11
7
  export declare const getInstantiationsContributedByNode: (file: ts.SourceFile, benchBlock: ts.FunctionExpression | ts.ArrowFunction) => number;
12
8
  export declare const createOrUpdateFile: (env: tsvfs.VirtualTypeScriptEnvironment, fileName: string, fileText: string) => ts.SourceFile | undefined;
@@ -21,12 +21,8 @@ export const getCallLocationFromCallExpression = (callExpression) => {
21
21
  };
22
22
  return location;
23
23
  };
24
- /**
25
- * Processes inline instantiations from an attest call
26
- * Preserves any JSDoc comments that are associated with the original expression
27
- */
28
- export const gatherInlineInstantiationData = (file, assertionsByFile, instantiationMethodCalls) => {
29
- const expressions = getCallExpressionsByName(file, instantiationMethodCalls);
24
+ export const gatherInlineInstantiationData = (file, fileAssertions, attestAliasInstantiationMethodCalls) => {
25
+ const expressions = getCallExpressionsByName(file, attestAliasInstantiationMethodCalls);
30
26
  if (!expressions.length)
31
27
  return;
32
28
  const enclosingFunctions = expressions.map(expression => {
@@ -47,8 +43,8 @@ ${enclosingFunction.ancestor.getText()}`);
47
43
  count: getInstantiationsContributedByNode(file, body)
48
44
  };
49
45
  });
50
- const assertions = assertionsByFile[getFileKey(file.fileName)] ?? [];
51
- assertionsByFile[getFileKey(file.fileName)] = [
46
+ const assertions = fileAssertions[getFileKey(file.fileName)] ?? [];
47
+ fileAssertions[getFileKey(file.fileName)] = [
52
48
  ...assertions,
53
49
  ...instantiationInfo
54
50
  ];
@@ -119,14 +115,8 @@ const getBaselineSourceFile = (originalFile) => {
119
115
  const functionNames = getConfig().testDeclarationAliases;
120
116
  const calls = getCallExpressionsByName(originalFile, functionNames);
121
117
  let baselineSourceFileText = originalFile.getFullText();
122
- // for each test function like `it` or `bench`, walk up the AST to find the complete expression
123
- for (const call of calls) {
124
- let currentNode = call;
125
- // ensure we capture the entire chain like bench(...).types(...)
126
- while (currentNode.parent && !ts.isExpressionStatement(currentNode))
127
- currentNode = currentNode.parent;
128
- const fullExpressionText = currentNode.getFullText();
129
- baselineSourceFileText = baselineSourceFileText.replace(fullExpressionText, "");
130
- }
118
+ calls.forEach(call => {
119
+ baselineSourceFileText = baselineSourceFileText.replace(call.getFullText(), "");
120
+ });
131
121
  return baselineSourceFileText;
132
122
  };
@@ -26,8 +26,6 @@ export type TypeRelationshipAssertionData = {
26
26
  typeArgs: ArgAssertionData[];
27
27
  errors: string[];
28
28
  completions: Completions;
29
- /** JSDoc comment for the first argument, if any */
30
- jsdoc?: string;
31
29
  };
32
30
  export type TypeBenchmarkingAssertionData = {
33
31
  location: LinePositionRange;
@@ -33,85 +33,13 @@ export const analyzeAssertCall = (assertCall, diagnosticsByFile) => {
33
33
  const typeArgs = types.typeArgs.map(typeArg => serializeArg(typeArg, types));
34
34
  const errors = checkDiagnosticMessages(assertCall, diagnosticsByFile);
35
35
  const completions = getCompletions(assertCall);
36
- // Extract JSDoc comment for first argument if available
37
- const jsdoc = extractJSDocFromArgument(assertCall);
38
- const result = {
36
+ return {
39
37
  location,
40
38
  args,
41
39
  typeArgs,
42
40
  errors,
43
41
  completions
44
42
  };
45
- if (jsdoc)
46
- result.jsdoc = jsdoc;
47
- return result;
48
- };
49
- /**
50
- * Extract JSDoc comments associated with the first argument of a call expression
51
- */
52
- const extractJSDocFromArgument = (callExpr) => {
53
- // We're only interested in the first argument
54
- const firstArg = callExpr.arguments[0];
55
- if (!firstArg)
56
- return undefined;
57
- const checker = getInternalTypeChecker();
58
- // If the argument is a property access expression (e.g., out.foo)
59
- if (ts.isPropertyAccessExpression(firstArg)) {
60
- // Try to find the symbol for the property
61
- const propSymbol = checker.getSymbolAtLocation(firstArg);
62
- if (propSymbol) {
63
- // Get JSDoc from property declarations
64
- return getJSDocFromSymbol(propSymbol);
65
- }
66
- }
67
- // If argument is an identifier, try to find its declaration's JSDoc
68
- else if (ts.isIdentifier(firstArg)) {
69
- const symbol = checker.getSymbolAtLocation(firstArg);
70
- if (symbol)
71
- return getJSDocFromSymbol(symbol);
72
- }
73
- return undefined;
74
- };
75
- /**
76
- * Extract JSDoc comments from a symbol's declarations
77
- */
78
- const getJSDocFromSymbol = (symbol) => {
79
- // Get JSDoc directly from the symbol if possible
80
- const symbolDocumentation = ts.displayPartsToString(symbol.getDocumentationComment(getInternalTypeChecker()));
81
- if (symbolDocumentation)
82
- return symbolDocumentation.trim();
83
- // If no symbol documentation, try to get JSDoc from declarations
84
- const declarations = symbol.getDeclarations() || [];
85
- for (const declaration of declarations) {
86
- // For property declarations in object literals, get the JSDoc comment
87
- if (ts.isPropertyAssignment(declaration) ||
88
- ts.isShorthandPropertyAssignment(declaration) ||
89
- ts.isPropertyDeclaration(declaration)) {
90
- const jsDocTags = ts.getJSDocTags(declaration);
91
- if (jsDocTags.length > 0) {
92
- return jsDocTags
93
- .map(tag => {
94
- const comment = tag.comment?.toString() || "";
95
- return tag.tagName.text + (comment ? ` ${comment}` : "");
96
- })
97
- .join("\n");
98
- }
99
- // Try to get JSDoc comment before the property
100
- const jsDocComments = ts.getJSDocCommentsAndTags(declaration);
101
- if (jsDocComments && jsDocComments.length > 0) {
102
- return jsDocComments
103
- .map(doc => {
104
- if (ts.isJSDoc(doc))
105
- return doc.comment || "";
106
- return "";
107
- })
108
- .filter(Boolean)
109
- .join("\n")
110
- .trim();
111
- }
112
- }
113
- }
114
- return undefined;
115
43
  };
116
44
  const serializeArg = (arg, context) => ({
117
45
  type: arg.toString(),
@@ -1 +1 @@
1
- export declare const baseDiagnosticTscCmd = "npm exec -- tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
1
+ export declare const baseDiagnosticTscCmd = "pnpm tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
package/out/cli/shared.js CHANGED
@@ -1 +1 @@
1
- export const baseDiagnosticTscCmd = "npm exec -- tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
1
+ export const baseDiagnosticTscCmd = "pnpm tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
package/out/cli/trace.js CHANGED
@@ -1,27 +1,8 @@
1
- import { ensureDir, getShellOutput, readJson, writeFile } from "@ark/fs";
2
- import { existsSync } from "node:fs";
3
- import { basename, join, relative } from "node:path";
1
+ import { ensureDir } from "@ark/fs";
2
+ import { execSync } from "child_process";
4
3
  import { resolve } from "path";
5
- import ts from "typescript";
6
- import { TsServer, getDescendants, getStringifiableType, nearestBoundingCallExpression } from "../cache/ts.js";
7
4
  import { getConfig } from "../config.js";
8
5
  import { baseDiagnosticTscCmd } from "./shared.js";
9
- /**
10
- * Helper to write output to both console and collect for file output
11
- */
12
- const outputCapture = (() => {
13
- let buffer = [];
14
- return {
15
- write: (text) => {
16
- console.log(text);
17
- buffer.push(text);
18
- },
19
- getBuffer: () => buffer.join("\n"),
20
- clear: () => {
21
- buffer = [];
22
- }
23
- };
24
- })();
25
6
  export const trace = async (args) => {
26
7
  const packageDir = resolve(args[0] ?? process.cwd());
27
8
  const config = getConfig();
@@ -31,491 +12,31 @@ export const trace = async (args) => {
31
12
  }
32
13
  const traceDir = resolve(config.cacheDir, "trace");
33
14
  ensureDir(traceDir);
34
- let tracingOutput = "";
35
- outputCapture.clear();
36
- outputCapture.write(`⏳ Gathering type trace data for ${packageDir}...`);
37
- tracingOutput = generateTraceData(traceDir, config.tsconfig, packageDir);
38
- const traceFile = join(traceDir, "trace.json");
39
- if (!existsSync(traceFile)) {
40
- outputCapture.write(`❌ No trace data found (expected a file at ${join(traceDir, "trace.json")})`);
41
- return;
42
- }
43
- outputCapture.write(`⏳ Analyzing type trace data for ${packageDir}...`);
44
- analyzeTypeInstantiations(traceDir);
45
- // Write summary file containing our messages followed by compiler output
46
- // This ensures the initial message comes first in the file
47
- const summaryPath = join(traceDir, "summary.txt");
48
- const summaryContent = outputCapture.getBuffer().split("\n")[0] +
49
- "\n" +
50
- tracingOutput +
51
- "\n" +
52
- outputCapture.getBuffer().split("\n").slice(1).join("\n");
53
- writeFile(summaryPath, summaryContent);
54
- };
55
- const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
56
- try {
57
- // Capture the output instead of just displaying it
58
- const output = getShellOutput(`${baseDiagnosticTscCmd} --project ${tsconfigPath} --generateTrace ${traceDir}`, { cwd: packageDir });
59
- // Display the output to the console as before
60
- process.stdout.write(output);
61
- return output;
62
- }
63
- catch (_) {
64
- // even if tsc returns a non-zero exit code,
65
- // we can still proceed as long as the trace.json
66
- // file was generated
67
- const e = _;
68
- const output = e.stdout ?? "";
69
- const errorOutput = e.stderr ?? "";
70
- process.stdout.write(output);
71
- process.stderr.write(errorOutput);
72
- return `${output}\n${errorOutput}`;
73
- }
74
- };
75
- const initializeAnalysisContext = (traceDir) => {
76
- const tsServer = TsServer.instance;
77
- // Load trace data
78
- const tracePath = join(traceDir, "trace.json");
79
- if (!existsSync(tracePath))
80
- throw new Error(`Expected a trace file at ${tracePath}`);
81
- const traceEntries = readJson(tracePath);
82
- return {
83
- traceDir,
84
- tsServer,
85
- traceEntries,
86
- durationEntries: [],
87
- callRanges: [],
88
- rootCalls: [],
89
- functionStats: {},
90
- allFunctions: []
91
- };
92
- };
93
- const filterDurationEntries = (ctx) => {
94
- ctx.durationEntries = ctx.traceEntries.filter(entry => entry.ph === "X" &&
95
- entry.dur !== undefined &&
96
- entry.args.path &&
97
- entry.args.pos &&
98
- entry.args.end);
99
- outputCapture.write(`Found ${ctx.durationEntries.length} traces with duration information`);
100
- };
101
- const processDurationEntry = (entry, ctx) => {
102
15
  try {
103
- const sourceFile = ctx.tsServer.getSourceFileOrThrow(entry.args.path);
104
- const pos = entry.args.pos;
105
- const end = entry.args.end;
106
- // First try to find any call expression in the range
107
- const callExpr = findCallExpressionInRange(sourceFile, pos, end);
108
- if (callExpr)
109
- processCallExpression(callExpr, entry, pos, end, ctx);
110
- else {
111
- // Try to process as another type of node
112
- processNonCallNode(sourceFile, entry, pos, end, ctx);
113
- }
16
+ console.log(`⏳ Gathering type trace data for ${packageDir}...`);
17
+ // These cache files have to be removed before any analysis is done otherwise
18
+ // the results will be meaningless.
19
+ // the .attest/trace directory will contain a trace.json file and a types.json file.
20
+ // the trace.json file can be viewed via a tool like https://ui.perfetto.dev/
21
+ // the types.json file can be used to associate IDs from the trace file with type aliases
22
+ execSync(`${baseDiagnosticTscCmd} --project ${config.tsconfig} --generateTrace ${traceDir}`, {
23
+ cwd: packageDir,
24
+ stdio: "inherit"
25
+ });
114
26
  }
115
27
  catch (e) {
116
- handleProcessingError(e, entry);
117
- }
118
- };
119
- /**
120
- * Find any call expression within the given range, with preference for method calls
121
- */
122
- const findCallExpressionInRange = (file, start, end) => {
123
- // First try the default nearest bounding call expression
124
- const boundingCall = nearestBoundingCallExpression(file, start);
125
- if (boundingCall)
126
- return boundingCall;
127
- // If that fails, search for any call expressions in the range
128
- const allNodes = getDescendants(file);
129
- const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
130
- // Find all call expressions in the range
131
- const callExpressions = nodesInRange.filter(node => ts.isCallExpression(node));
132
- if (callExpressions.length === 0)
133
- return undefined;
134
- // Prioritize method calls (e.g. x.and(), x.or())
135
- const methodCalls = callExpressions.filter(call => ts.isPropertyAccessExpression(call.expression));
136
- // Return a method call if found, otherwise the first call expression
137
- return methodCalls.length > 0 ? methodCalls[0] : callExpressions[0];
138
- };
139
- /**
140
- * Extract function or method name from a call expression, normalizing the format
141
- */
142
- const extractFunctionName = (callExpr) => {
143
- // For method calls like x.and()
144
- if (ts.isPropertyAccessExpression(callExpr.expression))
145
- return callExpr.expression.name.getText();
146
- // For direct function calls like type() or scope()
147
- if (ts.isIdentifier(callExpr.expression))
148
- return callExpr.expression.getText();
149
- // For other expressions, try to get a reasonable name
150
- return "anonymous";
151
- };
152
- const processCallExpression = (callExpr, entry, pos, end, ctx) => {
153
- // Simply use the function name for grouping
154
- const functionName = extractFunctionName(callExpr);
155
- // Use the function name for both ID and display name
156
- // This will ensure all calls to the same function are grouped together
157
- const typeId = `function-${functionName}`;
158
- const callSite = `${entry.args.path}:${pos}-${end}`;
159
- ctx.callRanges.push({
160
- id: `${entry.ts}-${pos}-${end}`,
161
- typeId,
162
- functionName,
163
- callSite,
164
- startTime: entry.ts,
165
- endTime: entry.ts + (entry.dur || 0),
166
- duration: entry.dur || 0,
167
- children: [],
168
- selfTime: entry.dur || 0
169
- });
170
- };
171
- const processNonCallNode = (sourceFile, entry, pos, end, ctx) => {
172
- const relevantNode = findMostSpecificNodeInRange(sourceFile, pos, end);
173
- if (!relevantNode)
174
- return;
175
- const nodeType = getStringifiableType(relevantNode);
176
- const nodeKind = ts.SyntaxKind[relevantNode.kind];
177
- const typeName = `${nodeKind}: ${nodeType.toString().substring(0, 25)}`;
178
- const typeId = `node-${relevantNode.kind}-${nodeType.id || nodeType.toString().substring(0, 20)}`;
179
- const callSite = `${entry.args.path}:${pos}-${end}`;
180
- ctx.callRanges.push({
181
- id: `${entry.ts}-${pos}-${end}`,
182
- typeId,
183
- functionName: typeName,
184
- callSite,
185
- startTime: entry.ts,
186
- endTime: entry.ts + (entry.dur || 0),
187
- duration: entry.dur || 0,
188
- children: [],
189
- selfTime: entry.dur || 0
190
- });
191
- };
192
- const handleProcessingError = (e, entry) => {
193
- if (!(e instanceof Error))
194
- throw e;
195
- // Silent failure for common case of not finding a call expression
196
- if (e.message?.includes("Unable to find bounding call expression"))
197
- return;
198
- console.warn(`Error processing entry at ${entry.args.path}:${entry.args.pos}: ${e.message}`);
199
- };
200
- const buildCallTree = (ctx) => {
201
- // Sort by start time for nesting analysis
202
- ctx.callRanges.sort((a, b) => a.startTime - b.startTime);
203
- const activeCallStack = [];
204
- ctx.callRanges.forEach(call => {
205
- popFinishedCalls(call, activeCallStack);
206
- assignToParentOrRoot(call, activeCallStack, ctx);
207
- activeCallStack.push(call);
208
- });
209
- };
210
- const popFinishedCalls = (call, activeCallStack) => {
211
- while (activeCallStack.length > 0 &&
212
- activeCallStack[activeCallStack.length - 1].endTime < call.startTime)
213
- activeCallStack.pop();
214
- };
215
- const assignToParentOrRoot = (call, activeCallStack, ctx) => {
216
- if (activeCallStack.length === 0) {
217
- // This is a root call
218
- ctx.rootCalls.push(call);
219
- }
220
- else {
221
- // This call is nested inside the current active call
222
- const parent = activeCallStack[activeCallStack.length - 1];
223
- parent.children.push(call);
224
- }
225
- };
226
- const calculateSelfTimes = (call) => {
227
- let childrenTime = 0;
228
- for (const child of call.children)
229
- childrenTime += calculateSelfTimes(child);
230
- call.selfTime = call.duration - childrenTime;
231
- return call.duration;
232
- };
233
- const collectFunctionStats = (call, ctx) => {
234
- // Initialize stats object if needed
235
- if (!ctx.functionStats[call.typeId]) {
236
- ctx.functionStats[call.typeId] = {
237
- typeId: call.typeId,
238
- functionName: call.functionName,
239
- totalTime: 0,
240
- selfTime: 0,
241
- count: 0,
242
- firstLocation: call.callSite,
243
- detailedCallSites: []
244
- };
245
- }
246
- const stats = ctx.functionStats[call.typeId];
247
- // Track detailed call site information
248
- addCallSiteToStats(call, stats);
249
- // Update aggregate metrics
250
- stats.totalTime += call.duration;
251
- stats.selfTime += call.selfTime;
252
- stats.count++;
253
- // Process children
254
- call.children.forEach(child => collectFunctionStats(child, ctx));
255
- };
256
- const addCallSiteToStats = (call, stats) => {
257
- const [filePath, positionRange] = call.callSite.split(":");
258
- const [posStr, endStr] = positionRange.split("-");
259
- stats.detailedCallSites.push({
260
- path: filePath,
261
- pos: parseInt(posStr),
262
- end: parseInt(endStr),
263
- selfTime: call.selfTime
264
- });
265
- };
266
- const sortAndRankFunctions = (ctx) => {
267
- // Sort each function's call sites by self-time
268
- Object.values(ctx.functionStats).forEach(stats => {
269
- stats.detailedCallSites.sort((a, b) => b.selfTime - a.selfTime);
270
- });
271
- // Sort functions by self-time
272
- ctx.allFunctions = Object.values(ctx.functionStats).sort((a, b) => b.selfTime - a.selfTime);
273
- };
274
- const analyzeTypeInstantiations = (traceDir) => {
275
- // Initialize the analysis context
276
- const ctx = initializeAnalysisContext(traceDir);
277
- // Filter entries with duration information
278
- filterDurationEntries(ctx);
279
- // Process each duration entry to extract call ranges
280
- ctx.durationEntries.forEach(entry => processDurationEntry(entry, ctx));
281
- // Build call tree from ranges
282
- buildCallTree(ctx);
283
- // Calculate self-time for each call
284
- ctx.rootCalls.forEach(calculateSelfTimes);
285
- // Collect statistics by view type
286
- const ungroupedStats = collectUngroupedStats(ctx);
287
- ctx.rootCalls.forEach(call => collectFunctionStats(call, ctx));
288
- // Sort and rank functions
289
- sortAndRankFunctions(ctx);
290
- // Display summaries to console
291
- outputCapture.write("\n📊 Performance Analysis - Top Individual Calls:\n");
292
- displayIndividualSummary(ungroupedStats);
293
- outputCapture.write("\n📊 Performance Analysis - Functions by Self Time:\n");
294
- displayGroupedSummary(ctx.allFunctions);
295
- // Write CSV reports
296
- const rangesCsvPath = join(traceDir, "ranges.csv");
297
- const namesCsvPath = join(traceDir, "names.csv");
298
- const summaryPath = join(traceDir, "summary.txt");
299
- // Export individual ranges to CSV
300
- writeToCsv(rangesCsvPath, ["Function Name", "Self (ms)", "Duration (ms)", "Location"], ungroupedStats.map(stat => [
301
- stat.functionName,
302
- (stat.selfTime / 1000).toFixed(3),
303
- (stat.duration / 1000).toFixed(3),
304
- formatLocation(stat.callSite)
305
- ]));
306
- // Export grouped functions to CSV
307
- writeToCsv(namesCsvPath, [
308
- "Function Name",
309
- "Total Self (ms)",
310
- "Avg Self (ms)",
311
- "Call Count",
312
- "Top Location",
313
- "Top Self (ms)"
314
- ], ctx.allFunctions.map(stats => {
315
- const topUsage = stats.detailedCallSites[0] || {
316
- path: "unknown",
317
- pos: 0,
318
- end: 0,
319
- selfTime: 0
320
- };
321
- return [
322
- stats.functionName,
323
- (stats.selfTime / 1000).toFixed(3),
324
- (stats.selfTime / stats.count / 1000).toFixed(3),
325
- stats.count.toString(),
326
- formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`),
327
- (topUsage.selfTime / 1000).toFixed(3)
28
+ console.error(String(e));
29
+ }
30
+ finally {
31
+ console.log(`⏳ Analyzing type trace data for ${packageDir}...`);
32
+ // allow analyze-trace to process the args
33
+ process.argv = [
34
+ "node",
35
+ "node_modules/@typescript/analyze-trace/dist/analyze-trace-dir.js",
36
+ traceDir
328
37
  ];
329
- }));
330
- outputCapture.write(`\n✅ Analysis complete! Results exported to:\n` +
331
- ` - ${rangesCsvPath} (individual calls)\n` +
332
- ` - ${namesCsvPath} (grouped by function name)\n` +
333
- ` - ${summaryPath} (complete analysis report)`);
334
- };
335
- /**
336
- * Collect statistics for individual (ungrouped) calls
337
- */
338
- const collectUngroupedStats = (ctx) => {
339
- const ungroupedStats = [];
340
- // Flatten the call tree into individual entries
341
- const flattenCallTree = (call) => {
342
- ungroupedStats.push({
343
- typeId: call.typeId,
344
- functionName: call.functionName,
345
- callSite: call.callSite,
346
- duration: call.duration,
347
- selfTime: call.selfTime
348
- });
349
- call.children.forEach(flattenCallTree);
350
- };
351
- ctx.rootCalls.forEach(flattenCallTree);
352
- // Sort by self time in descending order
353
- return ungroupedStats.sort((a, b) => b.selfTime - a.selfTime);
354
- };
355
- /**
356
- * Display a summary of individual calls
357
- */
358
- const displayIndividualSummary = (stats) => {
359
- displayTableHeader(["Rank", "Function Name", "Self (ms)", "Location"]);
360
- const top20 = stats.slice(0, 20);
361
- top20.forEach((stat, index) => {
362
- const typeNameFormatted = formatTypeName(stat.functionName, 20);
363
- const selfTimeMs = (stat.selfTime / 1000).toFixed(2).padStart(15);
364
- const location = formatLocation(stat.callSite);
365
- outputCapture.write(`${(index + 1).toString().padStart(4)} | ${typeNameFormatted} | ${selfTimeMs} | ${location}`);
366
- });
367
- };
368
- /**
369
- * Display a summary table header with aligned columns
370
- */
371
- const displayTableHeader = (columns) => {
372
- // Create header row with standard column widths
373
- const headerRow = [
374
- columns[0].padEnd(4),
375
- columns[1].padEnd(20),
376
- columns[2].padEnd(15),
377
- ...columns.slice(3)
378
- ].join(" | ");
379
- // Create separator line matching the header column widths
380
- const separatorRow = [
381
- "----",
382
- "--------------------",
383
- "---------------",
384
- ...columns.slice(3).map(col => "-".repeat(col.length))
385
- ].join("-|-");
386
- outputCapture.write(headerRow);
387
- outputCapture.write(separatorRow);
388
- };
389
- /**
390
- * Display a combined summary of grouped functions showing both total and average times
391
- */
392
- const displayGroupedSummary = (functions) => {
393
- displayTableHeader([
394
- "Rank",
395
- "Function Name",
396
- "Total Self (ms)",
397
- "Avg Self (ms)",
398
- "Calls",
399
- "Top Usage"
400
- ]);
401
- functions.slice(0, 20).forEach((stats, index) => {
402
- const typeNameFormatted = formatTypeName(stats.functionName, 20);
403
- const totalTimeMs = (stats.selfTime / 1000).toFixed(2).padStart(15);
404
- const avgTimeMs = (stats.selfTime / stats.count / 1000)
405
- .toFixed(2)
406
- .padStart(13);
407
- const calls = stats.count.toString().padStart(5);
408
- // Get details about top usage site
409
- const topUsage = stats.detailedCallSites[0] || {
410
- path: "unknown",
411
- pos: 0,
412
- end: 0,
413
- selfTime: 0
414
- };
415
- const topUsageTime = (topUsage.selfTime / 1000).toFixed(2) + "ms";
416
- const topUsageLocation = formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`);
417
- outputCapture.write(`${(index + 1).toString().padStart(4)} | ${typeNameFormatted} | ${totalTimeMs} | ${avgTimeMs} | ${calls} | ${topUsageLocation} (${topUsageTime})`);
418
- });
419
- };
420
- /**
421
- * Format a type name for display, ensuring the most identifiable parts are preserved
422
- */
423
- const formatTypeName = (typeName, maxLength) => {
424
- // Remove any () from the name
425
- typeName = typeName.replace(/\(\)$/, "");
426
- if (typeName.length <= maxLength)
427
- return typeName.padEnd(maxLength);
428
- // Default truncation strategy
429
- const charsToKeep = maxLength - 3; // Account for "..."
430
- const firstPart = Math.ceil(charsToKeep * 0.7); // Keep more of the start
431
- const lastPart = charsToKeep - firstPart;
432
- return (typeName.substring(0, firstPart) +
433
- "..." +
434
- (lastPart > 0 ? typeName.substring(typeName.length - lastPart) : "")).padEnd(maxLength);
435
- };
436
- /**
437
- * Format a file location to be more readable with relative path and line:char
438
- */
439
- const formatLocation = (location) => {
440
- if (!location || location === "unknown")
441
- return "unknown";
442
- // Extract file path and position range
443
- const [filePath, positionRange] = location.split(":");
444
- try {
445
- const relativePath = relative(process.cwd(), filePath);
446
- // Get position values
447
- const [posStr] = positionRange.split("-");
448
- const pos = parseInt(posStr);
449
- // Get the source file to convert position to line:character
450
- const sourceFile = TsServer.instance.getSourceFileOrThrow(filePath);
451
- const lineAndChar = sourceFile.getLineAndCharacterOfPosition(pos);
452
- // Format as relative-path:line:char
453
- return `${relativePath}:${lineAndChar.line + 1}:${lineAndChar.character + 1}`;
454
- }
455
- catch {
456
- // If any part fails, return the basic filename as fallback
457
- return basename(filePath) + (positionRange ? `:${positionRange}` : "");
458
- }
459
- };
460
- /**
461
- * Finds the most specific non-trivial node within the given range
462
- */
463
- const findMostSpecificNodeInRange = (file, start, end) => {
464
- // Get all descendants in the file
465
- const allNodes = getDescendants(file);
466
- // Filter nodes that are completely contained within our range
467
- const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
468
- // Find most specific nodes (leaf nodes)
469
- const leafNodes = nodesInRange.filter(node => !nodesInRange.some(other => other !== node && other.pos >= node.pos && other.end <= node.end));
470
- // Find nodes in order of preference
471
- return findNodeByPreference(leafNodes);
472
- };
473
- const findNodeByPreference = (nodes) => {
474
- // 1. Type references
475
- const typeReference = nodes.find(node => ts.isTypeReferenceNode(node) || ts.isTypeQueryNode(node));
476
- if (typeReference)
477
- return typeReference;
478
- // 2. Declarations
479
- const declaration = nodes.find(node => ts.isVariableDeclaration(node) ||
480
- ts.isFunctionDeclaration(node) ||
481
- ts.isClassDeclaration(node) ||
482
- ts.isInterfaceDeclaration(node));
483
- if (declaration)
484
- return declaration;
485
- // 3. Property accesses
486
- const propertyAccess = nodes.find(node => ts.isPropertyAccessExpression(node));
487
- if (propertyAccess)
488
- return propertyAccess;
489
- // 4. Assignments
490
- const assignment = nodes.find(node => ts.isBinaryExpression(node) &&
491
- node.operatorToken.kind === ts.SyntaxKind.EqualsToken);
492
- if (assignment)
493
- return assignment;
494
- // 5. Expressions
495
- const expression = nodes.find(node => ts.isExpressionStatement(node) || ts.isExpression(node));
496
- if (expression)
497
- return expression;
498
- // Default: first node
499
- return nodes[0];
500
- };
501
- /**
502
- * Write data to a CSV file
503
- */
504
- const writeToCsv = (filePath, headers, rows) => {
505
- const content = [
506
- headers.join(","),
507
- ...rows.map(row => row.map(escapeForCsv).join(","))
508
- ].join("\n");
509
- writeFile(filePath, content);
510
- };
511
- /**
512
- * Escape string for CSV format
513
- */
514
- const escapeForCsv = (value) => {
515
- if (value.includes(",") || value.includes('"') || value.includes("\n")) {
516
- // If the value contains commas, double quotes, or newlines, wrap it in quotes
517
- // and escape any double quotes by doubling them
518
- return `"${value.replace(/"/g, '""')}"`;
38
+ // TypeScript's analyze-trace tool can be used to automatically detect hot-spots in your code.
39
+ // It's not a perfect match for what can be optimized, but it can be a helpful place to start
40
+ await import("@typescript/analyze-trace/dist/analyze-trace-dir.js");
519
41
  }
520
- return value;
521
42
  };
@@ -6,6 +6,7 @@ import type { Digit } from "@ark/util";
6
6
  * temporarily renamed to node_modules/typescript-temp, and reset after each
7
7
  * version has been executed, regardless of failures.
8
8
  *
9
+ *
9
10
  * Throws an error if any version fails when the associated function is executed.
10
11
  *
11
12
  * fn should spawn a new process so the new symlinked version can be loaded.
@@ -17,12 +18,22 @@ export type TsVersionData = {
17
18
  path: string;
18
19
  };
19
20
  /**
20
- * Find and return the paths of all installed TypeScript versions by directly scanning
21
- * node_modules directories in the current package and all parent packages.
21
+ * Find and return the paths of all installed TypeScript versions, including the
22
+ * all dependencies beginning with "typescript" or "@ark/attest-ts-".
23
+ *
24
+ * Starts checking from the current directory and looks for node_modules in parent
25
+ * directories up to the file system root.
26
+ *
27
+ * Alternate versions can be installed using a package.json dependency like:
22
28
  *
23
- * This function only looks at directories, bypassing package.json entirely.
29
+ * ```json
30
+ * "@ark/attest-ts-min": "npm:typescript@5.1.6"
31
+ * ```
32
+ * @returns {TsVersionData[]} Each version mapped to data, e.g.:
33
+ * {alias: "@ark/attest-ts-min", version: "5.1.6", path: "/home/ssalb/arktype/node_modules/@ark/attest-ts-min" } *
24
34
  *
25
- * @returns {TsVersionData[]} Information about each TypeScript version found
35
+ * @throws {Error} If a TypeScript version specified in package.json is not
36
+ * installed at the expected location in node_modules.
26
37
  */
27
38
  export declare const findAttestTypeScriptVersions: () => TsVersionData[];
28
39
  /** Get the TypeScript version being used by attest as as string like "5.0"
@@ -1,6 +1,7 @@
1
- import { assertPackageRoot, findPackageAncestors, readJson } from "@ark/fs";
2
- import { existsSync, readdirSync, renameSync, statSync, symlinkSync, unlinkSync } from "fs";
3
- import { join } from "path";
1
+ import { assertPackageRoot, fsRoot, readJson } from "@ark/fs";
2
+ import { existsSync, renameSync, symlinkSync, unlinkSync } from "fs";
3
+ import { dirname } from "path";
4
+ import { join } from "path/posix";
4
5
  import ts from "typescript";
5
6
  /**
6
7
  * Executes a provided function for an installed set of TypeScript versions.
@@ -9,6 +10,7 @@ import ts from "typescript";
9
10
  * temporarily renamed to node_modules/typescript-temp, and reset after each
10
11
  * version has been executed, regardless of failures.
11
12
  *
13
+ *
12
14
  * Throws an error if any version fails when the associated function is executed.
13
15
  *
14
16
  * fn should spawn a new process so the new symlinked version can be loaded.
@@ -57,117 +59,70 @@ export const forTypeScriptVersions = (versions, fn) => {
57
59
  }
58
60
  };
59
61
  const possibleTsVersionPrefix = "typescript-";
60
- const strictTsVersionPrefix = "attest-ts-";
61
- /**
62
- * Determine the alias from the directory name
63
- */
64
- const getDirAlias = (dirName) => {
65
- if (dirName === "typescript")
62
+ const strictTsVersionPrefix = "@ark/attest-ts-";
63
+ const parseInstalledTsAlias = (installedAlias) => {
64
+ if (installedAlias === "typescript")
66
65
  return "default";
67
- if (dirName.startsWith(possibleTsVersionPrefix))
68
- return dirName.slice(possibleTsVersionPrefix.length);
69
- if (dirName.startsWith(strictTsVersionPrefix))
70
- return dirName.slice(strictTsVersionPrefix.length);
66
+ if (installedAlias.startsWith(possibleTsVersionPrefix))
67
+ return installedAlias.slice(possibleTsVersionPrefix.length);
68
+ if (installedAlias.startsWith(strictTsVersionPrefix))
69
+ return installedAlias.slice(strictTsVersionPrefix.length);
71
70
  return null;
72
71
  };
73
72
  /**
74
- * Try to get the TypeScript version from a directory
75
- */
76
- const getTsVersion = (fullPath) => {
77
- try {
78
- // Try to read package.json for version
79
- const packageJsonPath = join(fullPath, "package.json");
80
- if (existsSync(packageJsonPath)) {
81
- const packageJson = readJson(packageJsonPath);
82
- if (packageJson &&
83
- packageJson.name === "typescript" &&
84
- typeof packageJson.version === "string")
85
- return packageJson.version;
86
- }
87
- // As a fallback, check for the lib/typescript.js file which should exist in all TS installations
88
- if (existsSync(join(fullPath, "lib", "typescript.js")))
89
- return "unknown";
90
- return null;
91
- }
92
- catch {
93
- return null;
94
- }
95
- };
96
- /**
97
- * Find and return the paths of all installed TypeScript versions by directly scanning
98
- * node_modules directories in the current package and all parent packages.
73
+ * Find and return the paths of all installed TypeScript versions, including the
74
+ * all dependencies beginning with "typescript" or "@ark/attest-ts-".
75
+ *
76
+ * Starts checking from the current directory and looks for node_modules in parent
77
+ * directories up to the file system root.
99
78
  *
100
- * This function only looks at directories, bypassing package.json entirely.
79
+ * Alternate versions can be installed using a package.json dependency like:
101
80
  *
102
- * @returns {TsVersionData[]} Information about each TypeScript version found
81
+ * ```json
82
+ * "@ark/attest-ts-min": "npm:typescript@5.1.6"
83
+ * ```
84
+ * @returns {TsVersionData[]} Each version mapped to data, e.g.:
85
+ * {alias: "@ark/attest-ts-min", version: "5.1.6", path: "/home/ssalb/arktype/node_modules/@ark/attest-ts-min" } *
86
+ *
87
+ * @throws {Error} If a TypeScript version specified in package.json is not
88
+ * installed at the expected location in node_modules.
103
89
  */
104
90
  export const findAttestTypeScriptVersions = () => {
105
- const packagePaths = findPackageAncestors(process.cwd());
91
+ let currentDir = process.cwd();
106
92
  const versions = [];
107
- const foundVersionAliases = new Set();
108
- // Check each package's node_modules directory
109
- for (const packagePath of packagePaths) {
110
- const nodeModulesPath = join(packagePath, "node_modules");
111
- if (!existsSync(nodeModulesPath) ||
112
- !statSync(nodeModulesPath).isDirectory())
93
+ while (currentDir !== fsRoot) {
94
+ const packageJsonPath = join(currentDir, "package.json");
95
+ if (!existsSync(packageJsonPath)) {
96
+ currentDir = dirname(currentDir);
113
97
  continue;
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("@"))
120
- continue;
121
- const fullPath = join(nodeModulesPath, dirName);
122
- if (!statSync(fullPath).isDirectory())
123
- continue;
124
- const alias = getDirAlias(dirName);
125
- if (!alias)
126
- continue;
127
- // Skip if we already found this alias in a closer package
128
- if (foundVersionAliases.has(alias))
129
- continue;
130
- const version = getTsVersion(fullPath);
131
- if (version) {
132
- foundVersionAliases.add(alias);
133
- versions.push({
134
- alias,
135
- version,
136
- path: fullPath
137
- });
138
- }
98
+ }
99
+ const nodeModulesPath = join(currentDir, "node_modules");
100
+ const packageJson = readJson(packageJsonPath);
101
+ const dependencies = {
102
+ ...packageJson.dependencies,
103
+ ...packageJson.devDependencies
104
+ };
105
+ for (const installedAlias in dependencies) {
106
+ const alias = parseInstalledTsAlias(installedAlias);
107
+ if (alias === null)
108
+ continue;
109
+ const path = join(nodeModulesPath, installedAlias);
110
+ if (!existsSync(path)) {
111
+ throw Error(`TypeScript version ${installedAlias} specified in ${packageJsonPath} must be installed at ${path} `);
139
112
  }
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
- }
113
+ const typescriptJson = readJson(join(path, "package.json"));
114
+ if (typescriptJson.name !== "typescript") {
115
+ if (installedAlias.startsWith(strictTsVersionPrefix))
116
+ throw new Error(`Package at ${path} should be named "typescript"`);
117
+ continue;
166
118
  }
119
+ versions.push({
120
+ alias,
121
+ version: typescriptJson.version,
122
+ path
123
+ });
167
124
  }
168
- catch (err) {
169
- console.warn(`Warning: Error scanning ${nodeModulesPath}: ${err}`);
170
- }
125
+ currentDir = dirname(currentDir);
171
126
  }
172
127
  return versions;
173
128
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ark/attest",
3
- "version": "0.45.11",
3
+ "version": "0.48.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
- "@ark/fs": "0.45.10",
40
- "arktype": "2.1.19",
41
- "@ark/util": "0.45.10"
39
+ "@ark/fs": "0.46.0",
40
+ "@ark/util": "0.46.0",
41
+ "arktype": "2.1.20"
42
42
  },
43
43
  "devDependencies": {
44
44
  "typescript": "5.8.2"