@ark/attest 0.56.6 → 0.57.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 +11 -24
- package/out/assert/assertions.d.ts +1 -1
- package/out/assert/assertions.js +12 -18
- package/out/assert/attest.d.ts +2 -3
- package/out/assert/attest.js +3 -3
- package/out/assert/chainableAssertions.d.ts +1 -1
- package/out/assert/chainableAssertions.js +2 -1
- package/out/bench/type.js +6 -3
- package/out/cache/getCachedAssertions.d.ts +33 -11
- package/out/cache/getCachedAssertions.js +23 -46
- package/out/cache/snapshots.d.ts +6 -2
- package/out/cache/snapshots.js +32 -26
- package/out/cache/ts.js +3 -1
- package/out/cache/utils.d.ts +1 -1
- package/out/cache/writeAssertionCache.d.ts +1 -30
- package/out/cache/writeAssertionCache.js +2 -1
- package/out/cli/precache.js +3 -4
- package/out/cli/shared.d.ts +1 -1
- package/out/cli/shared.js +4 -1
- package/out/cli/trace.js +60 -25
- package/out/config.d.ts +4 -22
- package/out/config.js +4 -30
- package/out/fixtures.js +5 -18
- package/out/index.d.ts +1 -3
- package/out/index.js +1 -2
- package/out/ts7/analyze.d.ts +10 -0
- package/out/ts7/analyze.js +188 -0
- package/out/ts7/countInstantiations.d.ts +1 -0
- package/out/ts7/countInstantiations.js +44 -0
- package/out/ts7/instantiations.d.ts +13 -0
- package/out/ts7/instantiations.js +113 -0
- package/out/ts7/server.d.ts +48 -0
- package/out/ts7/server.js +224 -0
- package/out/ts7/snapshots.d.ts +5 -0
- package/out/ts7/snapshots.js +27 -0
- package/out/utils.d.ts +2 -0
- package/out/utils.js +3 -0
- package/package.json +8 -6
- package/out/tsVersioning.d.ts +0 -31
- package/out/tsVersioning.js +0 -172
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { throwError } from "@ark/util";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { basename, dirname, extname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { isPositionWithinRange } from "../cache/getCachedAssertions.js";
|
|
6
|
+
import { getConfig } from "../config.js";
|
|
7
|
+
import { TsgoServer, ast, getCallExpressionsByName, getCallLocation, getFirstFunctionDescendant, tempId, tscPath } from "./server.js";
|
|
8
|
+
const countInstantiationsScript = fileURLToPath(new URL(`./countInstantiations${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
|
|
9
|
+
/**
|
|
10
|
+
* tsgo's API doesn't expose instantiation counts, so each block is checked by
|
|
11
|
+
* a separate tsc process alongside the rest of its file with test calls
|
|
12
|
+
* removed, and compared against that file on its own.
|
|
13
|
+
*
|
|
14
|
+
* Unlike TS 5's in-process measurement, tsc fully checks every file the
|
|
15
|
+
* program includes, so work a block shares with its dependencies is counted
|
|
16
|
+
* in the baseline rather than attributed to the block.
|
|
17
|
+
*/
|
|
18
|
+
export const getInstantiationsContributedByNodes = (file, blocks) => {
|
|
19
|
+
if (!blocks.length)
|
|
20
|
+
return [];
|
|
21
|
+
const baselineText = getBaselineText(file);
|
|
22
|
+
const variants = [
|
|
23
|
+
baselineText,
|
|
24
|
+
...blocks.map(block => `${baselineText}\nconst $attestIsolatedBench = ${block.getFullText()}`)
|
|
25
|
+
];
|
|
26
|
+
const { projectConfig } = TsgoServer.instance;
|
|
27
|
+
const fileDir = dirname(file.fileName);
|
|
28
|
+
const fileBase = basename(file.fileName);
|
|
29
|
+
const files = {};
|
|
30
|
+
const configPaths = variants.map((text, i) => {
|
|
31
|
+
// dot-prefixed so test runner globs don't pick it up
|
|
32
|
+
const sourcePath = join(fileDir, `.attest-${tempId}-${i}-${fileBase}`);
|
|
33
|
+
const configPath = join(projectConfig.dir, `.attest-${tempId}-${i}.tsconfig.json`);
|
|
34
|
+
files[sourcePath] = text;
|
|
35
|
+
files[configPath] = JSON.stringify({
|
|
36
|
+
extends: projectConfig.extends,
|
|
37
|
+
compilerOptions: {
|
|
38
|
+
...projectConfig.compilerOptions,
|
|
39
|
+
// reused build info would skip checking unchanged files
|
|
40
|
+
incremental: false,
|
|
41
|
+
composite: false,
|
|
42
|
+
tsBuildInfoFile: null,
|
|
43
|
+
// declaration emit would fully check the exported types of both the
|
|
44
|
+
// baseline and the variant, hiding work a bench shares with them
|
|
45
|
+
declaration: false,
|
|
46
|
+
declarationMap: false,
|
|
47
|
+
declarationDir: null,
|
|
48
|
+
emitDeclarationOnly: false,
|
|
49
|
+
isolatedDeclarations: false,
|
|
50
|
+
// a bench excluded from the project may be outside its rootDir
|
|
51
|
+
rootDir: null,
|
|
52
|
+
// otherwise counts depend on whether declarations are checked
|
|
53
|
+
skipLibCheck: true
|
|
54
|
+
},
|
|
55
|
+
files: [sourcePath],
|
|
56
|
+
include: []
|
|
57
|
+
});
|
|
58
|
+
return configPath;
|
|
59
|
+
});
|
|
60
|
+
const [baseline, ...counts] = JSON.parse(execFileSync(process.execPath, [countInstantiationsScript, tscPath], {
|
|
61
|
+
input: JSON.stringify({ files, configPaths }),
|
|
62
|
+
encoding: "utf8",
|
|
63
|
+
maxBuffer: 1e8
|
|
64
|
+
}));
|
|
65
|
+
return counts.map(count => count - baseline);
|
|
66
|
+
};
|
|
67
|
+
const getBaselineText = (file) => {
|
|
68
|
+
const text = file.getFullText();
|
|
69
|
+
// remove each complete test expression, e.g. bench(...).types(...)
|
|
70
|
+
const removedRanges = getCallExpressionsByName(file, getConfig().testDeclarationAliases)
|
|
71
|
+
.map(call => {
|
|
72
|
+
let node = call;
|
|
73
|
+
while (node.parent && !ast.isExpressionStatement(node))
|
|
74
|
+
node = node.parent;
|
|
75
|
+
return node;
|
|
76
|
+
})
|
|
77
|
+
.sort((l, r) => l.pos - r.pos);
|
|
78
|
+
let baselineText = "";
|
|
79
|
+
let position = 0;
|
|
80
|
+
for (const statement of removedRanges) {
|
|
81
|
+
// nested test calls are removed with the statement containing them
|
|
82
|
+
if (statement.pos < position)
|
|
83
|
+
continue;
|
|
84
|
+
baselineText += text.slice(position, statement.pos);
|
|
85
|
+
position = statement.end;
|
|
86
|
+
}
|
|
87
|
+
return baselineText + text.slice(position);
|
|
88
|
+
};
|
|
89
|
+
const benchCountsByFile = new Map();
|
|
90
|
+
export const getBenchInstantiations = (position) => {
|
|
91
|
+
let benchCounts = benchCountsByFile.get(position.file);
|
|
92
|
+
if (!benchCounts) {
|
|
93
|
+
// count every bench in the file at once so tsc can run in parallel
|
|
94
|
+
const file = TsgoServer.instance.getSourceFileOrThrow(position.file);
|
|
95
|
+
const benches = getCallExpressionsByName(file, getConfig().testDeclarationAliases).flatMap(call => {
|
|
96
|
+
const body = getFirstFunctionDescendant(call);
|
|
97
|
+
// e.g. bench("name", fn), which has no inline body to measure
|
|
98
|
+
return body ? [{ call, body }] : [];
|
|
99
|
+
});
|
|
100
|
+
const counts = getInstantiationsContributedByNodes(file, benches.map(bench => bench.body));
|
|
101
|
+
benchCounts = benches.map((bench, i) => ({
|
|
102
|
+
location: getCallLocation(bench.call),
|
|
103
|
+
count: counts[i]
|
|
104
|
+
}));
|
|
105
|
+
benchCountsByFile.set(position.file, benchCounts);
|
|
106
|
+
}
|
|
107
|
+
// calls are listed outermost first, e.g. it(...) before a bench inside it
|
|
108
|
+
const innermost = benchCounts
|
|
109
|
+
.filter(({ location }) => isPositionWithinRange(position, location))
|
|
110
|
+
.pop();
|
|
111
|
+
return (innermost?.count ??
|
|
112
|
+
throwError(`No call expressions with an inline function matching the name(s) '${getConfig().testDeclarationAliases.join()}' were found at ${position.file}:${position.line}:${position.char}`));
|
|
113
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type JsonObject } from "@ark/util";
|
|
2
|
+
import type * as tsgoAst from "typescript/unstable/ast";
|
|
3
|
+
import type * as tsgoApi from "typescript/unstable/sync";
|
|
4
|
+
import type { LinePositionRange } from "../cache/getCachedAssertions.ts";
|
|
5
|
+
export declare const ast: typeof tsgoAst;
|
|
6
|
+
export declare const noTruncation: number;
|
|
7
|
+
export declare const tscPath: string;
|
|
8
|
+
export declare const tempId: string;
|
|
9
|
+
export type Node = tsgoAst.Node;
|
|
10
|
+
export type SourceFile = tsgoAst.SourceFile;
|
|
11
|
+
export type CallExpression = tsgoAst.CallExpression;
|
|
12
|
+
export type Project = tsgoApi.Project;
|
|
13
|
+
export type Type = tsgoApi.Type;
|
|
14
|
+
export declare class TsgoServer {
|
|
15
|
+
projectConfig: ProjectConfig;
|
|
16
|
+
configPath: string;
|
|
17
|
+
project: Project;
|
|
18
|
+
rootFiles: string[];
|
|
19
|
+
private api;
|
|
20
|
+
private config;
|
|
21
|
+
private snapshot;
|
|
22
|
+
private originalTextByPath;
|
|
23
|
+
private filesOutsideProject;
|
|
24
|
+
private static _instance;
|
|
25
|
+
static get instance(): TsgoServer;
|
|
26
|
+
private constructor();
|
|
27
|
+
/**
|
|
28
|
+
* tsgo only reports diagnostics after applying @ts-expect-error and
|
|
29
|
+
* @ts-ignore, so they're disabled in root files without shifting positions
|
|
30
|
+
*/
|
|
31
|
+
disableCommentDirectives(): void;
|
|
32
|
+
/** the node's text as written, before any directives were disabled */
|
|
33
|
+
getOriginalText(node: Node): string;
|
|
34
|
+
getSourceFileOrThrow(path: string): SourceFile;
|
|
35
|
+
private getFileOutsideProject;
|
|
36
|
+
private openProject;
|
|
37
|
+
}
|
|
38
|
+
export type ProjectConfig = {
|
|
39
|
+
/** where attest's configs are written, beside the base config if any */
|
|
40
|
+
dir: string;
|
|
41
|
+
extends: string | undefined;
|
|
42
|
+
compilerOptions: JsonObject;
|
|
43
|
+
};
|
|
44
|
+
export declare const getDescendants: (node: Node) => Node[];
|
|
45
|
+
export declare const getAncestors: (node: Node) => Node[];
|
|
46
|
+
export declare const getCallExpressionsByName: (startNode: Node, names: string[]) => CallExpression[];
|
|
47
|
+
export declare const getCallLocation: (call: CallExpression) => LinePositionRange;
|
|
48
|
+
export declare const getFirstFunctionDescendant: (node: Node) => Node | undefined;
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { fromCwd } from "@ark/fs";
|
|
2
|
+
import { throwError, throwInternalError } from "@ark/util";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { threadId } from "node:worker_threads";
|
|
7
|
+
import ts from "typescript";
|
|
8
|
+
import { getConfig } from "../config.js";
|
|
9
|
+
import { isTs7 } from "../utils.js";
|
|
10
|
+
// resolved relative to attest so the API matches the installed typescript
|
|
11
|
+
const requireTypeScript = createRequire(import.meta.url);
|
|
12
|
+
// only loaded for TS 7+ so this module can be imported unconditionally
|
|
13
|
+
export const ast = isTs7 ? requireTypeScript("typescript/unstable/ast") : undefined;
|
|
14
|
+
const { API, TypeFormatFlags } = isTs7 ? requireTypeScript("typescript/unstable/sync") : {};
|
|
15
|
+
const { createFileSystemLayer } = isTs7 ? requireTypeScript("typescript/unstable/fs") : {};
|
|
16
|
+
export const noTruncation = isTs7 ? TypeFormatFlags.NoTruncation : 0;
|
|
17
|
+
export const tscPath = join(dirname(requireTypeScript.resolve("typescript/package.json")), "bin", "tsc");
|
|
18
|
+
// unique to this thread, since worker threads share a pid
|
|
19
|
+
export const tempId = `${process.pid}-${threadId}`;
|
|
20
|
+
export class TsgoServer {
|
|
21
|
+
projectConfig;
|
|
22
|
+
configPath;
|
|
23
|
+
project;
|
|
24
|
+
rootFiles;
|
|
25
|
+
api;
|
|
26
|
+
config;
|
|
27
|
+
snapshot;
|
|
28
|
+
originalTextByPath = new Map();
|
|
29
|
+
filesOutsideProject = new Map();
|
|
30
|
+
static _instance = null;
|
|
31
|
+
static get instance() {
|
|
32
|
+
return (TsgoServer._instance ??= new TsgoServer());
|
|
33
|
+
}
|
|
34
|
+
constructor() {
|
|
35
|
+
if (ts.version.startsWith("7.0."))
|
|
36
|
+
throwError(`@ark/attest requires TypeScript 7.1+ (found ${ts.version})`);
|
|
37
|
+
this.api = new API({ cwd: fromCwd() });
|
|
38
|
+
this.projectConfig = getProjectConfig();
|
|
39
|
+
// only exists in tsgo's view of the filesystem, so nothing is written
|
|
40
|
+
this.configPath = join(this.projectConfig.dir, ".attest.tsconfig.json");
|
|
41
|
+
this.config = JSON.stringify({
|
|
42
|
+
extends: this.projectConfig.extends,
|
|
43
|
+
compilerOptions: this.projectConfig.compilerOptions
|
|
44
|
+
});
|
|
45
|
+
this.project = this.openProject();
|
|
46
|
+
const configErrors = this.project.program.getConfigFileParsingDiagnostics();
|
|
47
|
+
if (configErrors.length)
|
|
48
|
+
throwError(configErrors.map(error => error.text).join("\n"));
|
|
49
|
+
const normalizedCwd = fromCwd().replace(/\\/g, "/");
|
|
50
|
+
this.rootFiles = this.project.parsedCommandLine.fileNames.filter(path => path.startsWith(normalizedCwd));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* tsgo only reports diagnostics after applying @ts-expect-error and
|
|
54
|
+
* @ts-ignore, so they're disabled in root files without shifting positions
|
|
55
|
+
*/
|
|
56
|
+
disableCommentDirectives() {
|
|
57
|
+
if (this.originalTextByPath.size)
|
|
58
|
+
return;
|
|
59
|
+
const files = [];
|
|
60
|
+
for (const path of this.rootFiles) {
|
|
61
|
+
const file = this.getSourceFileOrThrow(path);
|
|
62
|
+
const contents = getTextWithoutCommentDirectives(file);
|
|
63
|
+
if (contents === undefined)
|
|
64
|
+
continue;
|
|
65
|
+
this.originalTextByPath.set(path, file.getFullText());
|
|
66
|
+
files.push([path, contents]);
|
|
67
|
+
}
|
|
68
|
+
if (files.length)
|
|
69
|
+
this.project = this.openProject(files);
|
|
70
|
+
}
|
|
71
|
+
/** the node's text as written, before any directives were disabled */
|
|
72
|
+
getOriginalText(node) {
|
|
73
|
+
const text = this.originalTextByPath.get(node.getSourceFile().fileName);
|
|
74
|
+
return text?.slice(node.getStart(), node.end) ?? node.getText();
|
|
75
|
+
}
|
|
76
|
+
getSourceFileOrThrow(path) {
|
|
77
|
+
const normalizedPath = path.replace(/\\/g, "/");
|
|
78
|
+
return (this.project.program.getSourceFile(normalizedPath) ??
|
|
79
|
+
this.getFileOutsideProject(normalizedPath) ??
|
|
80
|
+
throwInternalError(`@ark/attest: TypeScript was unable to resolve expected file at ${path}.`));
|
|
81
|
+
}
|
|
82
|
+
// e.g. benches excluded by tsconfig, which are only read for their syntax
|
|
83
|
+
getFileOutsideProject(path) {
|
|
84
|
+
if (!this.filesOutsideProject.has(path) && existsSync(path)) {
|
|
85
|
+
this.filesOutsideProject.set(path, this.api.createSourceFileFromFile(path).sourceFile);
|
|
86
|
+
}
|
|
87
|
+
return this.filesOutsideProject.get(path);
|
|
88
|
+
}
|
|
89
|
+
openProject(files = []) {
|
|
90
|
+
const snapshot = this.api.createSnapshot({
|
|
91
|
+
openProjects: [this.configPath],
|
|
92
|
+
fileSystem: createFileSystemLayer([
|
|
93
|
+
[this.configPath, this.config],
|
|
94
|
+
...files
|
|
95
|
+
])
|
|
96
|
+
});
|
|
97
|
+
this.snapshot?.dispose();
|
|
98
|
+
this.snapshot = snapshot;
|
|
99
|
+
return (snapshot.getConfiguredProject(this.configPath) ??
|
|
100
|
+
throwInternalError(`@ark/attest: Unable to load ${this.configPath}`));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* tsgo only loads projects from config files, so attest's compilerOptions are
|
|
105
|
+
* applied by configs beside the base config, which keeps relative paths and
|
|
106
|
+
* ${configDir} resolving exactly as they would from the base config
|
|
107
|
+
*/
|
|
108
|
+
const getProjectConfig = () => {
|
|
109
|
+
const { tsconfig, compilerOptions } = getConfig();
|
|
110
|
+
const baseConfigPath = tsconfig === null ? undefined
|
|
111
|
+
: tsconfig === undefined ? findTsconfig(fromCwd())
|
|
112
|
+
: resolve(tsconfig);
|
|
113
|
+
return {
|
|
114
|
+
dir: baseConfigPath ? dirname(baseConfigPath) : fromCwd(),
|
|
115
|
+
extends: baseConfigPath,
|
|
116
|
+
compilerOptions
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
const findTsconfig = (fromDir) => {
|
|
120
|
+
const path = join(fromDir, "tsconfig.json");
|
|
121
|
+
if (existsSync(path))
|
|
122
|
+
return path;
|
|
123
|
+
const parentDir = dirname(fromDir);
|
|
124
|
+
return parentDir === fromDir ? undefined : findTsconfig(parentDir);
|
|
125
|
+
};
|
|
126
|
+
// tsgo's grammar, which unlike TS 5 allows any number of leading slashes but
|
|
127
|
+
// only spaces and tabs as whitespace
|
|
128
|
+
const singleLineDirective = /^\/{2,}[\t ]*@ts-(?:expect-error|ignore)/;
|
|
129
|
+
const multiLineDirective = /^[\t ]*[*/]*[\t ]*@ts-(?:expect-error|ignore)/;
|
|
130
|
+
const lineBreak = /[\n\r\u2028\u2029]/g;
|
|
131
|
+
const literalKinds = () => new Set([
|
|
132
|
+
ast.SyntaxKind.StringLiteral,
|
|
133
|
+
ast.SyntaxKind.NoSubstitutionTemplateLiteral,
|
|
134
|
+
ast.SyntaxKind.TemplateHead,
|
|
135
|
+
ast.SyntaxKind.TemplateMiddle,
|
|
136
|
+
ast.SyntaxKind.TemplateTail,
|
|
137
|
+
ast.SyntaxKind.RegularExpressionLiteral,
|
|
138
|
+
ast.SyntaxKind.JsxText
|
|
139
|
+
]);
|
|
140
|
+
/**
|
|
141
|
+
* Returns the file's text with each comment tsgo would treat as a directive
|
|
142
|
+
* changed from @ts- to @ts_, or undefined if it has none
|
|
143
|
+
*/
|
|
144
|
+
const getTextWithoutCommentDirectives = (file) => {
|
|
145
|
+
const text = file.getFullText();
|
|
146
|
+
if (!text.includes("@ts-"))
|
|
147
|
+
return;
|
|
148
|
+
const kinds = literalKinds();
|
|
149
|
+
const literalEnds = new Map();
|
|
150
|
+
// like a literal, a shebang line can't contain a comment
|
|
151
|
+
if (text.startsWith("#!")) {
|
|
152
|
+
const shebangEnd = text.search(lineBreak);
|
|
153
|
+
literalEnds.set(0, shebangEnd === -1 ? text.length : shebangEnd);
|
|
154
|
+
}
|
|
155
|
+
for (const node of getDescendants(file)) {
|
|
156
|
+
if (kinds.has(node.kind)) {
|
|
157
|
+
// JsxText has no trivia, so its leading whitespace is part of it
|
|
158
|
+
literalEnds.set(ast.isJsxText(node) ? node.pos : node.getStart(), node.end);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const chars = text.split("");
|
|
162
|
+
let changed = false;
|
|
163
|
+
const disable = (start, end, directive) => {
|
|
164
|
+
const comment = text.slice(start, end);
|
|
165
|
+
if (!directive.test(comment))
|
|
166
|
+
return;
|
|
167
|
+
chars[start + comment.indexOf("@ts-") + 3] = "_";
|
|
168
|
+
changed = true;
|
|
169
|
+
};
|
|
170
|
+
for (let i = 0; i < text.length; i++) {
|
|
171
|
+
const literalEnd = literalEnds.get(i);
|
|
172
|
+
if (literalEnd !== undefined && literalEnd > i)
|
|
173
|
+
i = literalEnd - 1;
|
|
174
|
+
else if (text.startsWith("//", i)) {
|
|
175
|
+
lineBreak.lastIndex = i;
|
|
176
|
+
const commentEnd = lineBreak.exec(text)?.index ?? text.length;
|
|
177
|
+
disable(i, commentEnd, singleLineDirective);
|
|
178
|
+
i = commentEnd;
|
|
179
|
+
}
|
|
180
|
+
else if (text.startsWith("/*", i)) {
|
|
181
|
+
const closeStart = text.indexOf("*/", i + 2);
|
|
182
|
+
const commentEnd = closeStart === -1 ? text.length : closeStart + 2;
|
|
183
|
+
// only the last line of a block comment can be a directive
|
|
184
|
+
let lastLineStart = i;
|
|
185
|
+
lineBreak.lastIndex = i;
|
|
186
|
+
while (lineBreak.test(text) && lineBreak.lastIndex <= commentEnd)
|
|
187
|
+
lastLineStart = lineBreak.lastIndex;
|
|
188
|
+
disable(lastLineStart, commentEnd, multiLineDirective);
|
|
189
|
+
i = commentEnd - 1;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return changed ? chars.join("") : undefined;
|
|
193
|
+
};
|
|
194
|
+
export const getDescendants = (node) => {
|
|
195
|
+
const descendants = [];
|
|
196
|
+
const collect = (descendant) => {
|
|
197
|
+
descendants.push(descendant);
|
|
198
|
+
descendant.forEachChild(collect);
|
|
199
|
+
};
|
|
200
|
+
collect(node);
|
|
201
|
+
return descendants;
|
|
202
|
+
};
|
|
203
|
+
export const getAncestors = (node) => {
|
|
204
|
+
const ancestors = [];
|
|
205
|
+
let baseNode = node.parent;
|
|
206
|
+
while (baseNode?.parent !== undefined) {
|
|
207
|
+
ancestors.push(baseNode);
|
|
208
|
+
baseNode = baseNode.parent;
|
|
209
|
+
}
|
|
210
|
+
return ancestors;
|
|
211
|
+
};
|
|
212
|
+
export const getCallExpressionsByName = (startNode, names) => getDescendants(startNode).filter((node) => ast.isCallExpression(node) &&
|
|
213
|
+
(!names.length || names.includes(node.expression.getText())));
|
|
214
|
+
export const getCallLocation = (call) => {
|
|
215
|
+
const file = call.getSourceFile();
|
|
216
|
+
const start = file.getLineAndCharacterOfPosition(call.getStart());
|
|
217
|
+
const end = file.getLineAndCharacterOfPosition(call.getEnd());
|
|
218
|
+
// trace positions are 1-based and TS positions are 0-based
|
|
219
|
+
return {
|
|
220
|
+
start: { line: start.line + 1, char: start.character + 1 },
|
|
221
|
+
end: { line: end.line + 1, char: end.character + 1 }
|
|
222
|
+
};
|
|
223
|
+
};
|
|
224
|
+
export const getFirstFunctionDescendant = (node) => getDescendants(node).find(descendant => ast.isArrowFunction(descendant) || ast.isFunctionExpression(descendant));
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type SourcePosition } from "@ark/fs";
|
|
2
|
+
import type { SnapCallArgs } from "../cache/snapshots.ts";
|
|
3
|
+
import { type CallExpression, type Node } from "./server.ts";
|
|
4
|
+
export declare const getSnapCallArgs: (position: SourcePosition, functionName: string) => SnapCallArgs;
|
|
5
|
+
export declare const nearestBoundingCallExpression: (node: Node, position: number) => CallExpression | undefined;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { positionToString } from "@ark/fs";
|
|
2
|
+
import { throwInternalError } from "@ark/util";
|
|
3
|
+
import { TsgoServer, ast, getDescendants } from "./server.js";
|
|
4
|
+
export const getSnapCallArgs = (position, functionName) => {
|
|
5
|
+
const file = TsgoServer.instance.getSourceFileOrThrow(position.file);
|
|
6
|
+
const call = nearestBoundingCallExpression(file,
|
|
7
|
+
// TS uses 0-based line and char #s
|
|
8
|
+
file.getPositionOfLineAndCharacter(position.line - 1, position.char - 1));
|
|
9
|
+
if (!call ||
|
|
10
|
+
!getDescendants(call).some(node => ast.isIdentifier(node) && node.text === functionName)) {
|
|
11
|
+
throwInternalError(`Unable to locate expected inline ${functionName} call from assertion at ${positionToString(position)}.`);
|
|
12
|
+
}
|
|
13
|
+
return {
|
|
14
|
+
pos: call.arguments.pos,
|
|
15
|
+
end: call.arguments.end,
|
|
16
|
+
firstArgText: call.arguments[0]?.getText()
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
export const nearestBoundingCallExpression = (node, position) => {
|
|
20
|
+
if (node.pos > position || node.end < position)
|
|
21
|
+
return;
|
|
22
|
+
let nearest;
|
|
23
|
+
node.forEachChild(child => {
|
|
24
|
+
nearest ??= nearestBoundingCallExpression(child, position);
|
|
25
|
+
});
|
|
26
|
+
return nearest ?? (ast.isCallExpression(node) ? node : undefined);
|
|
27
|
+
};
|
package/out/utils.d.ts
CHANGED
package/out/utils.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { caller } from "@ark/fs";
|
|
2
2
|
import { throwError } from "@ark/util";
|
|
3
3
|
import { basename, relative } from "node:path";
|
|
4
|
+
import ts from "typescript";
|
|
5
|
+
/** TypeScript 7+ is native and only exposes its API via tsgo's IPC client */
|
|
6
|
+
export const isTs7 = Number.parseInt(ts.version) >= 7;
|
|
4
7
|
export const getFileKey = (path) => relative(".", path);
|
|
5
8
|
/**
|
|
6
9
|
* Can be used to allow arbitrarily chained property access and function calls.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ark/attest",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.57.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "David Blass",
|
|
@@ -40,13 +40,15 @@
|
|
|
40
40
|
"@typescript/analyze-trace": "0.10.1",
|
|
41
41
|
"@typescript/vfs": "1.6.1",
|
|
42
42
|
"prettier": "3.6.2",
|
|
43
|
-
"@ark/fs": "0.56.
|
|
44
|
-
"@ark/util": "0.56.
|
|
45
|
-
"
|
|
46
|
-
"
|
|
43
|
+
"@ark/fs": "0.56.7",
|
|
44
|
+
"@ark/util": "0.56.7",
|
|
45
|
+
"@ark/schema": "0.56.7",
|
|
46
|
+
"arktype": "2.2.8"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
-
"typescript": "
|
|
49
|
+
"typescript": "7.1.0-dev.20261006.1",
|
|
50
|
+
"typescript-6": "npm:typescript@6.0.3",
|
|
51
|
+
"typescript-7": "npm:typescript@7.1.0-dev.20261006.1"
|
|
50
52
|
},
|
|
51
53
|
"peerDependencies": {
|
|
52
54
|
"typescript": "*"
|
package/out/tsVersioning.d.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import type { Digit } from "@ark/util";
|
|
2
|
-
/**
|
|
3
|
-
* Executes a provided function for an installed set of TypeScript versions.
|
|
4
|
-
*
|
|
5
|
-
* Your primary TypeScript version at node_modules/typescript will be
|
|
6
|
-
* temporarily renamed to node_modules/typescript-temp, and reset after each
|
|
7
|
-
* version has been executed, regardless of failures.
|
|
8
|
-
*
|
|
9
|
-
* Throws an error if any version fails when the associated function is executed.
|
|
10
|
-
*
|
|
11
|
-
* fn should spawn a new process so the new symlinked version can be loaded.
|
|
12
|
-
*/
|
|
13
|
-
export declare const forTypeScriptVersions: (versions: TsVersionData[], fn: (version: TsVersionData) => void) => void;
|
|
14
|
-
export type TsVersionData = {
|
|
15
|
-
alias: string;
|
|
16
|
-
version: string;
|
|
17
|
-
path: string;
|
|
18
|
-
};
|
|
19
|
-
/**
|
|
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.
|
|
22
|
-
*
|
|
23
|
-
* This function only looks at directories, bypassing package.json entirely.
|
|
24
|
-
*
|
|
25
|
-
* @returns {TsVersionData[]} Information about each TypeScript version found
|
|
26
|
-
*/
|
|
27
|
-
export declare const findAttestTypeScriptVersions: () => TsVersionData[];
|
|
28
|
-
/** Get the TypeScript version being used by attest as as string like "5.0"
|
|
29
|
-
* Does not include alternate versions that may be referenced by cache files
|
|
30
|
-
*/
|
|
31
|
-
export declare const getPrimaryTsVersionUnderTest: () => `${Digit}.${Digit}`;
|
package/out/tsVersioning.js
DELETED
|
@@ -1,172 +0,0 @@
|
|
|
1
|
-
import { assertPackageRoot, findPackageAncestors, readJson } from "@ark/fs";
|
|
2
|
-
import { existsSync, readdirSync, renameSync, statSync, symlinkSync, unlinkSync } from "node:fs";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import ts from "typescript";
|
|
5
|
-
/**
|
|
6
|
-
* Executes a provided function for an installed set of TypeScript versions.
|
|
7
|
-
*
|
|
8
|
-
* Your primary TypeScript version at node_modules/typescript will be
|
|
9
|
-
* temporarily renamed to node_modules/typescript-temp, and reset after each
|
|
10
|
-
* version has been executed, regardless of failures.
|
|
11
|
-
*
|
|
12
|
-
* Throws an error if any version fails when the associated function is executed.
|
|
13
|
-
*
|
|
14
|
-
* fn should spawn a new process so the new symlinked version can be loaded.
|
|
15
|
-
*/
|
|
16
|
-
export const forTypeScriptVersions = (versions, fn) => {
|
|
17
|
-
const passedVersions = [];
|
|
18
|
-
const failedVersions = [];
|
|
19
|
-
const nodeModules = join(assertPackageRoot(process.cwd()), "node_modules");
|
|
20
|
-
const tsPrimaryPath = join(nodeModules, "typescript");
|
|
21
|
-
const tsTemporaryPath = join(nodeModules, "typescript-temp");
|
|
22
|
-
if (existsSync(tsTemporaryPath))
|
|
23
|
-
unlinkSync(tsTemporaryPath);
|
|
24
|
-
if (existsSync(tsPrimaryPath))
|
|
25
|
-
renameSync(tsPrimaryPath, tsTemporaryPath);
|
|
26
|
-
try {
|
|
27
|
-
for (const version of versions) {
|
|
28
|
-
const targetPath = version.path === tsPrimaryPath ? tsTemporaryPath : version.path;
|
|
29
|
-
console.log(`⛵ Switching to TypeScript version ${version.alias} (${version.version})...`);
|
|
30
|
-
try {
|
|
31
|
-
if (existsSync(tsPrimaryPath))
|
|
32
|
-
unlinkSync(tsPrimaryPath);
|
|
33
|
-
symlinkSync(targetPath, tsPrimaryPath, "junction");
|
|
34
|
-
fn(version);
|
|
35
|
-
passedVersions.push(version);
|
|
36
|
-
}
|
|
37
|
-
catch (e) {
|
|
38
|
-
console.error(e);
|
|
39
|
-
failedVersions.push(version);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
if (failedVersions.length !== 0) {
|
|
43
|
-
throw new Error(`❌ The following TypeScript versions threw: ${failedVersions
|
|
44
|
-
.map(v => `${v.alias} (${v.version})`)
|
|
45
|
-
.join(", ")}`);
|
|
46
|
-
}
|
|
47
|
-
console.log(`✅ Successfully ran TypeScript versions ${passedVersions
|
|
48
|
-
.map(v => `${v.alias} (${v.version})`)
|
|
49
|
-
.join(", ")}`);
|
|
50
|
-
}
|
|
51
|
-
finally {
|
|
52
|
-
if (existsSync(tsTemporaryPath)) {
|
|
53
|
-
console.log(`⏮️ Restoring your original TypeScript version...`);
|
|
54
|
-
unlinkSync(tsPrimaryPath);
|
|
55
|
-
renameSync(tsTemporaryPath, tsPrimaryPath);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
};
|
|
59
|
-
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")
|
|
66
|
-
return "default";
|
|
67
|
-
if (dirName.startsWith(possibleTsVersionPrefix))
|
|
68
|
-
return dirName.slice(possibleTsVersionPrefix.length);
|
|
69
|
-
if (dirName.startsWith(strictTsVersionPrefix))
|
|
70
|
-
return dirName.slice(strictTsVersionPrefix.length);
|
|
71
|
-
return null;
|
|
72
|
-
};
|
|
73
|
-
/**
|
|
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.
|
|
99
|
-
*
|
|
100
|
-
* This function only looks at directories, bypassing package.json entirely.
|
|
101
|
-
*
|
|
102
|
-
* @returns {TsVersionData[]} Information about each TypeScript version found
|
|
103
|
-
*/
|
|
104
|
-
export const findAttestTypeScriptVersions = () => {
|
|
105
|
-
const packagePaths = findPackageAncestors(process.cwd());
|
|
106
|
-
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())
|
|
113
|
-
continue;
|
|
114
|
-
// Check for regular typescript or typescript-* directories
|
|
115
|
-
const dirNames = readdirSync(nodeModulesPath);
|
|
116
|
-
for (const dirName of dirNames) {
|
|
117
|
-
// Skip node_modules/@* directories - we'll handle them below
|
|
118
|
-
if (dirName.startsWith("@"))
|
|
119
|
-
continue;
|
|
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-"))
|
|
145
|
-
continue;
|
|
146
|
-
const fullPath = join(arkDir, dirName);
|
|
147
|
-
if (!statSync(fullPath).isDirectory())
|
|
148
|
-
continue;
|
|
149
|
-
const alias = getDirAlias(dirName);
|
|
150
|
-
if (!alias)
|
|
151
|
-
continue;
|
|
152
|
-
// Skip if we already found this alias in a closer package
|
|
153
|
-
if (foundVersionAliases.has(alias))
|
|
154
|
-
continue;
|
|
155
|
-
const version = getTsVersion(fullPath);
|
|
156
|
-
if (version) {
|
|
157
|
-
foundVersionAliases.add(alias);
|
|
158
|
-
versions.push({
|
|
159
|
-
alias,
|
|
160
|
-
version,
|
|
161
|
-
path: fullPath
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
return versions;
|
|
168
|
-
};
|
|
169
|
-
/** Get the TypeScript version being used by attest as as string like "5.0"
|
|
170
|
-
* Does not include alternate versions that may be referenced by cache files
|
|
171
|
-
*/
|
|
172
|
-
export const getPrimaryTsVersionUnderTest = () => ts.versionMajorMinor;
|