@ark/attest 0.9.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.
Files changed (51) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +284 -0
  3. package/out/assert/assertions.d.ts +28 -0
  4. package/out/assert/assertions.js +119 -0
  5. package/out/assert/attest.d.ts +26 -0
  6. package/out/assert/attest.js +40 -0
  7. package/out/assert/chainableAssertions.d.ts +68 -0
  8. package/out/assert/chainableAssertions.js +176 -0
  9. package/out/bench/await1k.d.ts +1 -0
  10. package/out/bench/await1k.js +1002 -0
  11. package/out/bench/baseline.d.ts +5 -0
  12. package/out/bench/baseline.js +60 -0
  13. package/out/bench/bench.d.ts +58 -0
  14. package/out/bench/bench.js +216 -0
  15. package/out/bench/call1k.d.ts +1 -0
  16. package/out/bench/call1k.js +1002 -0
  17. package/out/bench/measure.d.ts +29 -0
  18. package/out/bench/measure.js +48 -0
  19. package/out/bench/type.d.ts +16 -0
  20. package/out/bench/type.js +36 -0
  21. package/out/cache/getCachedAssertions.d.ts +11 -0
  22. package/out/cache/getCachedAssertions.js +70 -0
  23. package/out/cache/snapshots.d.ts +29 -0
  24. package/out/cache/snapshots.js +153 -0
  25. package/out/cache/ts.d.ts +45 -0
  26. package/out/cache/ts.js +127 -0
  27. package/out/cache/utils.d.ts +9 -0
  28. package/out/cache/utils.js +114 -0
  29. package/out/cache/writeAssertionCache.d.ts +42 -0
  30. package/out/cache/writeAssertionCache.js +141 -0
  31. package/out/cli/cli.d.ts +2 -0
  32. package/out/cli/cli.js +25 -0
  33. package/out/cli/precache.d.ts +1 -0
  34. package/out/cli/precache.js +7 -0
  35. package/out/cli/shared.d.ts +1 -0
  36. package/out/cli/shared.js +1 -0
  37. package/out/cli/stats.d.ts +1 -0
  38. package/out/cli/stats.js +54 -0
  39. package/out/cli/trace.d.ts +1 -0
  40. package/out/cli/trace.js +37 -0
  41. package/out/config.d.ts +42 -0
  42. package/out/config.js +94 -0
  43. package/out/fixtures.d.ts +6 -0
  44. package/out/fixtures.js +29 -0
  45. package/out/index.d.ts +9 -0
  46. package/out/index.js +8 -0
  47. package/out/tsVersioning.d.ts +45 -0
  48. package/out/tsVersioning.js +119 -0
  49. package/out/utils.d.ts +15 -0
  50. package/out/utils.js +36 -0
  51. package/package.json +48 -0
@@ -0,0 +1,29 @@
1
+ import type { StatName } from "./bench.js";
2
+ type MeasureUnit = TimeUnit | TypeUnit;
3
+ export type Measure<Unit extends MeasureUnit = MeasureUnit> = [
4
+ value: number,
5
+ unit: Unit
6
+ ];
7
+ export type MeasureComparison<Unit extends MeasureUnit = MeasureUnit> = {
8
+ updated: Measure<Unit>;
9
+ baseline: Measure<Unit> | undefined;
10
+ };
11
+ export type MarkMeasure = Partial<Record<StatName, Measure>>;
12
+ export declare const stringifyMeasure: ([value, units]: Measure) => string;
13
+ export declare const TYPE_UNITS: readonly ["instantiations"];
14
+ export type TypeUnit = (typeof TYPE_UNITS)[number];
15
+ export declare const createTypeComparison: (value: number, baseline: Measure<TypeUnit> | undefined) => MeasureComparison<TypeUnit>;
16
+ export declare const timeUnitRatios: {
17
+ ns: number;
18
+ us: number;
19
+ ms: number;
20
+ s: number;
21
+ };
22
+ export type TimeUnit = keyof typeof timeUnitRatios;
23
+ export declare const stringifyTimeMeasure: ([value, unit]: Measure<TimeUnit>) => string;
24
+ /**
25
+ * Establish a new baseline using the most appropriate time unit
26
+ */
27
+ export declare const createTimeMeasure: (ms: number) => Measure<TimeUnit>;
28
+ export declare const createTimeComparison: (ms: number, baseline: Measure<TimeUnit> | undefined) => MeasureComparison<TimeUnit>;
29
+ export {};
@@ -0,0 +1,48 @@
1
+ export const stringifyMeasure = ([value, units]) => units in timeUnitRatios ?
2
+ stringifyTimeMeasure([value, units])
3
+ : `${value} ${units}`;
4
+ export const TYPE_UNITS = ["instantiations"];
5
+ export const createTypeComparison = (value, baseline) => ({
6
+ updated: [value, "instantiations"],
7
+ baseline
8
+ });
9
+ export const timeUnitRatios = {
10
+ ns: 0.000_001,
11
+ us: 0.001,
12
+ ms: 1,
13
+ s: 1000
14
+ };
15
+ export const stringifyTimeMeasure = ([value, unit]) => `${value.toFixed(2)}${unit}`;
16
+ const convertTimeUnit = (n, from, to) => round((n * timeUnitRatios[from]) / timeUnitRatios[to], 2);
17
+ /**
18
+ * Establish a new baseline using the most appropriate time unit
19
+ */
20
+ export const createTimeMeasure = (ms) => {
21
+ let bestMatch;
22
+ for (const u in timeUnitRatios) {
23
+ const candidateMeasure = createTimeMeasureForUnit(ms, u);
24
+ if (!bestMatch)
25
+ bestMatch = candidateMeasure;
26
+ else if (bestMatch[0] >= 1) {
27
+ if (candidateMeasure[0] >= 1 && candidateMeasure[0] < bestMatch[0])
28
+ bestMatch = candidateMeasure;
29
+ }
30
+ else if (candidateMeasure[0] >= bestMatch[0])
31
+ bestMatch = candidateMeasure;
32
+ }
33
+ return bestMatch;
34
+ };
35
+ const createTimeMeasureForUnit = (ms, unit) => [convertTimeUnit(ms, "ms", unit), unit];
36
+ const round = (value, decimalPlaces) => Math.round(value * 10 ** decimalPlaces) / 10 ** decimalPlaces;
37
+ export const createTimeComparison = (ms, baseline) => {
38
+ if (baseline) {
39
+ return {
40
+ updated: [convertTimeUnit(ms, "ms", baseline[1]), baseline[1]],
41
+ baseline
42
+ };
43
+ }
44
+ return {
45
+ updated: createTimeMeasure(ms),
46
+ baseline: undefined
47
+ };
48
+ };
@@ -0,0 +1,16 @@
1
+ import type { TypeRelationship } from "../cache/writeAssertionCache.js";
2
+ import type { BenchContext } from "./bench.js";
3
+ import { type Measure, type TypeUnit } from "./measure.js";
4
+ export type BenchTypeAssertions = {
5
+ types: (instantiations?: Measure<TypeUnit>) => void;
6
+ };
7
+ export declare const createBenchTypeAssertion: (ctx: BenchContext) => BenchTypeAssertions;
8
+ export declare const getContributedInstantiations: (ctx: BenchContext) => number;
9
+ export type ArgAssertionData = {
10
+ type: string;
11
+ relationships: {
12
+ args: TypeRelationship[];
13
+ typeArgs: TypeRelationship[];
14
+ };
15
+ };
16
+ export declare const instantiationDataHandler: (ctx: BenchContext, args?: Measure<TypeUnit>, isBenchFunction?: boolean) => void;
@@ -0,0 +1,36 @@
1
+ import { caller } from "@ark/fs";
2
+ import ts from "typescript";
3
+ import { getBenchAssertionsAtPosition } from "../cache/getCachedAssertions.js";
4
+ import { TsServer, getAbsolutePosition, getAncestors, getDescendants, nearestCallExpressionChild } from "../cache/ts.js";
5
+ import { getCallExpressionsByName, getInstantiationsContributedByNode } from "../cache/utils.js";
6
+ import { getConfig } from "../config.js";
7
+ import { compareToBaseline, queueBaselineUpdateIfNeeded } from "./baseline.js";
8
+ import { createTypeComparison } from "./measure.js";
9
+ export const createBenchTypeAssertion = (ctx) => ({
10
+ types: (...args) => {
11
+ ctx.lastSnapCallPosition = caller();
12
+ instantiationDataHandler({ ...ctx, kind: "types" }, args[0]);
13
+ }
14
+ });
15
+ export const getContributedInstantiations = (ctx) => {
16
+ const testDeclarationAliases = getConfig().testDeclarationAliases;
17
+ const instance = TsServer.instance;
18
+ const file = instance.getSourceFileOrThrow(ctx.benchCallPosition.file);
19
+ const node = nearestCallExpressionChild(file, getAbsolutePosition(file, ctx.benchCallPosition));
20
+ const firstMatchingNamedCall = getAncestors(node).find(call => getCallExpressionsByName(call, testDeclarationAliases).length);
21
+ if (!firstMatchingNamedCall) {
22
+ throw new Error(`No call expressions matching the name(s) '${testDeclarationAliases.join()}' were found`);
23
+ }
24
+ const body = getDescendants(firstMatchingNamedCall).find(node => ts.isArrowFunction(node) || ts.isFunctionExpression(node));
25
+ if (!body)
26
+ throw new Error("Unable to retrieve contents of the call expression");
27
+ return getInstantiationsContributedByNode(file, body);
28
+ };
29
+ export const instantiationDataHandler = (ctx, args, isBenchFunction = true) => {
30
+ const instantiationsContributed = isBenchFunction ?
31
+ getContributedInstantiations(ctx)
32
+ : getBenchAssertionsAtPosition(ctx.benchCallPosition)[0][1].count;
33
+ const comparison = createTypeComparison(instantiationsContributed, args);
34
+ compareToBaseline(comparison, ctx);
35
+ queueBaselineUpdateIfNeeded(comparison.updated, args, ctx);
36
+ };
@@ -0,0 +1,11 @@
1
+ import { type SourcePosition } from "@ark/fs";
2
+ import type { AssertionsByFile, TypeAssertionData, TypeAssertionKind } from "./writeAssertionCache.js";
3
+ export type VersionedAssertionsByFile = [
4
+ tsVersion: string,
5
+ relationshipAssertions: AssertionsByFile,
6
+ benchAssertions: AssertionsByFile
7
+ ];
8
+ export declare const getCachedAssertionEntries: () => VersionedAssertionsByFile[];
9
+ export type VersionedTypeAssertion<kind extends TypeAssertionKind = TypeAssertionKind> = [tsVersion: string, assertionData: TypeAssertionData<kind>];
10
+ export declare const getTypeAssertionsAtPosition: (position: SourcePosition) => VersionedTypeAssertion<"type">[];
11
+ export declare const getBenchAssertionsAtPosition: (position: SourcePosition) => VersionedTypeAssertion<"bench">[];
@@ -0,0 +1,70 @@
1
+ import { readJson } from "@ark/fs";
2
+ import { existsSync, readdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { getConfig } from "../config.js";
5
+ import { getFileKey } from "../utils.js";
6
+ let assertionEntries;
7
+ export const getCachedAssertionEntries = () => {
8
+ if (!assertionEntries) {
9
+ const config = getConfig();
10
+ if (!existsSync(config.assertionCacheDir))
11
+ throwMissingAssertionDataError(config.assertionCacheDir);
12
+ const assertionFiles = readdirSync(config.assertionCacheDir);
13
+ const relationshipAssertions = {};
14
+ const benchAssertions = {};
15
+ assertionEntries = assertionFiles.map(file => {
16
+ const data = readJson(join(config.assertionCacheDir, file));
17
+ for (const fileName of Object.keys(data)) {
18
+ const relationshipAssertionData = data[fileName].filter((entry) => "args" in entry);
19
+ const benchAssertionData = data[fileName].filter((entry) => "count" in entry);
20
+ relationshipAssertions[fileName] = relationshipAssertionData;
21
+ benchAssertions[fileName] = benchAssertionData;
22
+ }
23
+ return [
24
+ // remove .json extension
25
+ file.slice(0, -5),
26
+ relationshipAssertions,
27
+ benchAssertions
28
+ ];
29
+ });
30
+ }
31
+ return assertionEntries;
32
+ };
33
+ const throwMissingAssertionDataError = (location) => {
34
+ throw new Error(`Unable to find precached assertion data at '${location}'. ` +
35
+ `Ensure the 'setup' function from @ark/attest has been called before running your tests.`);
36
+ };
37
+ const isPositionWithinRange = ({ line, char }, { start, end }) => {
38
+ if (line < start.line || line > end.line)
39
+ return false;
40
+ if (line === start.line)
41
+ return char >= start.char;
42
+ if (line === end.line)
43
+ return char <= end.char;
44
+ return true;
45
+ };
46
+ const getAssertionsOfKindAtPosition = (position, kind) => {
47
+ const fileKey = getFileKey(position.file);
48
+ return getCachedAssertionEntries().map(([version, typeRelationshipAssertions, BenchAssertionAssertions]) => {
49
+ const assertions = kind === "type" ? typeRelationshipAssertions : BenchAssertionAssertions;
50
+ if (!assertions[fileKey]) {
51
+ throw new Error(`Found no assertion data for '${fileKey}' for TypeScript version ${version}.`);
52
+ }
53
+ const matchingAssertion = assertions[fileKey].find(assertion =>
54
+ /**
55
+ * Depending on the environment, a trace can refer to any of these points
56
+ * attest(...)
57
+ * ^ ^ ^
58
+ * Because of this, it's safest to check if the call came from anywhere in the expected range.
59
+ *
60
+ */
61
+ isPositionWithinRange(position, assertion.location));
62
+ if (!matchingAssertion) {
63
+ throw new Error(`Found no assertion for TypeScript version ${version} at line ${position.line} char ${position.char} in '${fileKey}'.
64
+ Are sourcemaps enabled and working properly?`);
65
+ }
66
+ return [version, matchingAssertion];
67
+ });
68
+ };
69
+ export const getTypeAssertionsAtPosition = (position) => getAssertionsOfKindAtPosition(position, "type");
70
+ export const getBenchAssertionsAtPosition = (position) => getAssertionsOfKindAtPosition(position, "bench");
@@ -0,0 +1,29 @@
1
+ import { type SourcePosition } from "@ark/fs";
2
+ import type ts from "typescript";
3
+ export type SnapshotArgs = {
4
+ position: SourcePosition;
5
+ serializedValue: unknown;
6
+ snapFunctionName?: string;
7
+ baselinePath?: string[];
8
+ };
9
+ export declare const resolveSnapshotPath: (testFile: string, customPath: string | undefined) => string;
10
+ export declare const getSnapshotByName: (file: string, name: string, customPath: string | undefined) => object;
11
+ /**
12
+ * Writes the update and position to cacheDir, which will eventually be read and copied to the source
13
+ * file by a cleanup process after all tests have completed.
14
+ */
15
+ export declare const queueSnapshotUpdate: (args: SnapshotArgs) => void;
16
+ export type QueuedUpdate = {
17
+ position: SourcePosition;
18
+ snapCall: ts.CallExpression;
19
+ snapFunctionName: string;
20
+ newArgText: string;
21
+ baselinePath: string[] | undefined;
22
+ };
23
+ export type ExternalSnapshotArgs = SnapshotArgs & {
24
+ name: string;
25
+ customPath: string | undefined;
26
+ };
27
+ export declare const updateExternalSnapshot: ({ serializedValue: value, position, name, customPath }: ExternalSnapshotArgs) => void;
28
+ export declare const writeSnapshotUpdatesOnExit: () => void;
29
+ export declare const writeUpdates: (queuedUpdates: QueuedUpdate[]) => void;
@@ -0,0 +1,153 @@
1
+ import { filePath, positionToString, readFile, readJson, shell, writeFile, writeJson } from "@ark/fs";
2
+ import { existsSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join } from "node:path";
4
+ import { getConfig } from "../config.js";
5
+ import { getFileKey } from "../utils.js";
6
+ import { TsServer, getAbsolutePosition, nearestCallExpressionChild } from "./ts.js";
7
+ import { getCallExpressionsByName } from "./utils.js";
8
+ export const resolveSnapshotPath = (testFile, customPath) => {
9
+ if (customPath && isAbsolute(customPath))
10
+ return customPath;
11
+ return join(dirname(testFile), customPath ?? "assert.snapshots.json");
12
+ };
13
+ export const getSnapshotByName = (file, name, customPath) => {
14
+ const snapshotPath = resolveSnapshotPath(file, customPath);
15
+ return readJson(snapshotPath)?.[basename(file)]?.[name];
16
+ };
17
+ /**
18
+ * Writes the update and position to cacheDir, which will eventually be read and copied to the source
19
+ * file by a cleanup process after all tests have completed.
20
+ */
21
+ export const queueSnapshotUpdate = (args) => {
22
+ const config = getConfig();
23
+ const path = config.defaultAssertionCachePath;
24
+ if (existsSync(path)) {
25
+ const existing = readJson(path);
26
+ writeJson(path, {
27
+ ...existing,
28
+ updates: Array.isArray(existing.updates) ? [...existing.updates, args] : [args]
29
+ });
30
+ }
31
+ else
32
+ writeJson(path, { updates: [args] });
33
+ };
34
+ const findCallExpressionAncestor = (position, functionName) => {
35
+ const server = TsServer.instance;
36
+ const file = server.getSourceFileOrThrow(position.file);
37
+ const absolutePosition = getAbsolutePosition(file, position);
38
+ const startNode = nearestCallExpressionChild(file, absolutePosition);
39
+ const calls = getCallExpressionsByName(startNode, [functionName], true);
40
+ if (calls.length)
41
+ return startNode;
42
+ throw new Error(`Unable to locate expected inline ${functionName} call from assertion at ${positionToString(position)}.`);
43
+ };
44
+ export const updateExternalSnapshot = ({ serializedValue: value, position, name, customPath }) => {
45
+ const snapshotPath = resolveSnapshotPath(position.file, customPath);
46
+ const snapshotData = readJson(snapshotPath) ?? {};
47
+ const fileKey = basename(position.file);
48
+ snapshotData[fileKey] = {
49
+ ...snapshotData[fileKey],
50
+ [name]: value
51
+ };
52
+ writeJson(snapshotPath, snapshotData);
53
+ };
54
+ let snapshotsWillBeWritten = false;
55
+ export const writeSnapshotUpdatesOnExit = () => {
56
+ if (snapshotsWillBeWritten)
57
+ return;
58
+ process.on("exit", writeCachedInlineSnapshotUpdates);
59
+ snapshotsWillBeWritten = true;
60
+ };
61
+ const writeCachedInlineSnapshotUpdates = () => {
62
+ const config = getConfig();
63
+ let snapshotData;
64
+ if (!existsSync(config.defaultAssertionCachePath))
65
+ return;
66
+ try {
67
+ snapshotData = readJson(config.defaultAssertionCachePath).updates;
68
+ }
69
+ catch {
70
+ // If we can't read the snapshot, log an error and move onto the next update
71
+ console.error(`Unable to read snapshot data from expected location ${config.defaultAssertionCachePath}.`);
72
+ }
73
+ if (snapshotData) {
74
+ try {
75
+ writeUpdates(snapshotData.map(snapshot => snapshotArgsToQueuedUpdate(snapshot)));
76
+ }
77
+ catch (error) {
78
+ // If writeInlineSnapshotToFile throws an error, log it and move on to the next update
79
+ console.error(String(error));
80
+ }
81
+ }
82
+ };
83
+ const snapshotArgsToQueuedUpdate = ({ position, serializedValue, snapFunctionName = "snap", baselinePath }) => {
84
+ const snapCall = findCallExpressionAncestor(position, snapFunctionName);
85
+ const newArgText = typeof serializedValue === "string" && serializedValue.includes("\n") ?
86
+ "`" + serializedValue.replaceAll("`", "\\`") + "`"
87
+ : JSON.stringify(serializedValue);
88
+ return {
89
+ position,
90
+ snapCall,
91
+ snapFunctionName,
92
+ newArgText,
93
+ baselinePath
94
+ };
95
+ };
96
+ // Waiting until process exit to write snapshots avoids invalidating existing source positions
97
+ export const writeUpdates = (queuedUpdates) => {
98
+ if (!queuedUpdates.length)
99
+ return;
100
+ const updatesByFile = {};
101
+ for (const update of queuedUpdates) {
102
+ updatesByFile[update.position.file] ??= [];
103
+ updatesByFile[update.position.file].push(update);
104
+ }
105
+ for (const k in updatesByFile) {
106
+ writeFileUpdates(k, updatesByFile[k].sort((l, r) => l.position.line > r.position.line ? 1
107
+ : r.position.line > l.position.line ? -1
108
+ : l.position.char - r.position.char));
109
+ }
110
+ runFormatterIfAvailable(queuedUpdates);
111
+ };
112
+ const runFormatterIfAvailable = (queuedUpdates) => {
113
+ const { formatter, shouldFormat } = getConfig();
114
+ if (!shouldFormat)
115
+ return;
116
+ try {
117
+ const updatedPaths = [
118
+ ...new Set(queuedUpdates.map(update => filePath(update.snapCall.getSourceFile().fileName)))
119
+ ];
120
+ shell(`${formatter} ${updatedPaths.join(" ")}`);
121
+ }
122
+ catch {
123
+ // If formatter is unavailable or skipped, do nothing.
124
+ }
125
+ };
126
+ const writeFileUpdates = (path, updates) => {
127
+ let fileText = readFile(path);
128
+ let offSet = 0;
129
+ for (const update of updates) {
130
+ const previousArgTextLength = update.snapCall.arguments.end - update.snapCall.arguments.pos;
131
+ fileText =
132
+ fileText.slice(0, update.snapCall.arguments.pos + offSet) +
133
+ update.newArgText +
134
+ fileText.slice(update.snapCall.arguments.end + offSet);
135
+ offSet += update.newArgText.length - previousArgTextLength;
136
+ summarizeSnapUpdate(update.snapCall.arguments, update);
137
+ }
138
+ writeFile(path, fileText);
139
+ };
140
+ const summarizeSnapUpdate = (originalArgs, update) => {
141
+ let updateSummary = `${originalArgs.length ? "🆙 Updated" : "📸 Established"} `;
142
+ updateSummary +=
143
+ update.baselinePath ?
144
+ `baseline '${update.baselinePath.join("/")}' `
145
+ : `snap at ${getFileKey(update.position.file)}:${update.position.line} `;
146
+ const previousValue = update.snapCall.arguments[0]?.getText();
147
+ updateSummary +=
148
+ previousValue ?
149
+ `from ${previousValue} to `
150
+ : `${update.baselinePath ? "at" : "as"} `;
151
+ updateSummary += update.newArgText;
152
+ console.log(updateSummary);
153
+ };
@@ -0,0 +1,45 @@
1
+ import { type SourcePosition } from "@ark/fs";
2
+ import * as tsvfs from "@typescript/vfs";
3
+ import ts from "typescript";
4
+ export declare class TsServer {
5
+ private tsConfigInfo;
6
+ rootFiles: string[];
7
+ virtualEnv: tsvfs.VirtualTypeScriptEnvironment;
8
+ private static _instance;
9
+ static get instance(): TsServer;
10
+ private constructor();
11
+ getSourceFileOrThrow(path: string): ts.SourceFile;
12
+ }
13
+ export declare const nearestCallExpressionChild: (node: ts.Node, position: number) => ts.CallExpression;
14
+ export declare const getAbsolutePosition: (file: ts.SourceFile, position: SourcePosition) => number;
15
+ export type TsconfigInfo = {
16
+ path: string;
17
+ parsed: ts.ParsedCommandLine;
18
+ };
19
+ export declare const getTsConfigInfoOrThrow: () => TsconfigInfo;
20
+ type TsLibFiles = {
21
+ defaultMapFromNodeModules: Map<string, string>;
22
+ resolvedPaths: string[];
23
+ };
24
+ export declare const getTsLibFiles: (tsconfigOptions: ts.CompilerOptions) => TsLibFiles;
25
+ export declare const getProgram: (env?: tsvfs.VirtualTypeScriptEnvironment) => ts.Program;
26
+ export interface InternalTypeChecker extends ts.TypeChecker {
27
+ getInstantiationCount: () => number;
28
+ isTypeAssignableTo: (source: ts.Type, target: ts.Type) => boolean;
29
+ getDiagnostics: () => ts.Diagnostic[];
30
+ }
31
+ export declare const getInternalTypeChecker: (env?: tsvfs.VirtualTypeScriptEnvironment) => InternalTypeChecker;
32
+ export interface StringifiableType extends ts.Type {
33
+ toString(): string;
34
+ isUnresolvable: boolean;
35
+ }
36
+ export declare const getStringifiableType: (node: ts.Node) => StringifiableType;
37
+ export type ArgumentTypes = {
38
+ args: StringifiableType[];
39
+ typeArgs: StringifiableType[];
40
+ };
41
+ export declare const extractArgumentTypesFromCall: (call: ts.CallExpression) => ArgumentTypes;
42
+ export declare const getDescendants: (node: ts.Node) => ts.Node[];
43
+ export declare const getAncestors: (node: ts.Node) => ts.Node[];
44
+ export declare const getFirstAncestorByKindOrThrow: (node: ts.Node, kind: ts.SyntaxKind) => ts.Node;
45
+ export {};
@@ -0,0 +1,127 @@
1
+ import { fromCwd } from "@ark/fs";
2
+ import { throwInternalError } from "@ark/util";
3
+ import * as tsvfs from "@typescript/vfs";
4
+ import { readFileSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import ts from "typescript";
7
+ import { getConfig } from "../config.js";
8
+ export class TsServer {
9
+ tsConfigInfo;
10
+ rootFiles;
11
+ virtualEnv;
12
+ static _instance = null;
13
+ static get instance() {
14
+ return new TsServer();
15
+ }
16
+ constructor(tsConfigInfo = getTsConfigInfoOrThrow()) {
17
+ this.tsConfigInfo = tsConfigInfo;
18
+ if (TsServer._instance)
19
+ return TsServer._instance;
20
+ const tsLibPaths = getTsLibFiles(tsConfigInfo.parsed.options);
21
+ // TS represents windows paths as `C:/Users/ssalb/...`
22
+ const normalizedCwd = fromCwd().replaceAll(/\\/g, "/");
23
+ this.rootFiles = tsConfigInfo.parsed.fileNames.filter(path => path.startsWith(normalizedCwd));
24
+ const system = tsvfs.createFSBackedSystem(tsLibPaths.defaultMapFromNodeModules, dirname(this.tsConfigInfo.path), ts);
25
+ this.virtualEnv = tsvfs.createVirtualTypeScriptEnvironment(system, this.rootFiles, ts, this.tsConfigInfo.parsed.options);
26
+ TsServer._instance = this;
27
+ }
28
+ getSourceFileOrThrow(path) {
29
+ const tsPath = path.replaceAll(/\\/g, "/");
30
+ const file = this.virtualEnv.getSourceFile(tsPath);
31
+ if (!file)
32
+ throw new Error(`Could not find ${path}.`);
33
+ return file;
34
+ }
35
+ }
36
+ export const nearestCallExpressionChild = (node, position) => {
37
+ const result = nearestBoundingCallExpression(node, position);
38
+ if (!result) {
39
+ throw new Error(`Unable to find bounding call expression at position ${position} in ${node.getSourceFile().fileName}`);
40
+ }
41
+ return result;
42
+ };
43
+ const nearestBoundingCallExpression = (node, position) => node.pos <= position && node.end >= position ?
44
+ node
45
+ .getChildren()
46
+ .flatMap(child => nearestBoundingCallExpression(child, position) ?? [])[0] ?? (ts.isCallExpression(node) ? node : undefined)
47
+ : undefined;
48
+ export const getAbsolutePosition = (file, position) => {
49
+ const pos = ts.getPositionOfLineAndCharacter(file,
50
+ // TS uses 0-based line and char #s
51
+ position.line - 1, position.char - 1);
52
+ if (!pos) {
53
+ throw new Error(`Absolute position was not able to be found in ${file.fileName}`);
54
+ }
55
+ return pos;
56
+ };
57
+ export const getTsConfigInfoOrThrow = () => {
58
+ const config = getConfig().tsconfig;
59
+ const configFilePath = config ?? ts.findConfigFile(fromCwd(), ts.sys.fileExists, "tsconfig.json");
60
+ if (!configFilePath) {
61
+ throw new Error(`File ${config ?? join(fromCwd(), "tsconfig.json")} must exist.`);
62
+ }
63
+ const configFileText = readFileSync(configFilePath).toString();
64
+ const result = ts.parseConfigFileTextToJson(configFilePath, configFileText);
65
+ if (result.error) {
66
+ throw new Error(ts.formatDiagnostics([result.error], {
67
+ getCanonicalFileName: fileName => fileName,
68
+ getCurrentDirectory: process.cwd,
69
+ getNewLine: () => ts.sys.newLine
70
+ }));
71
+ }
72
+ const configObject = result.config;
73
+ const configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, dirname(configFilePath), {}, configFilePath);
74
+ if (configParseResult.errors.length > 0) {
75
+ throw new Error(ts.formatDiagnostics(configParseResult.errors, {
76
+ getCanonicalFileName: fileName => fileName,
77
+ getCurrentDirectory: process.cwd,
78
+ getNewLine: () => ts.sys.newLine
79
+ }));
80
+ }
81
+ return {
82
+ path: configFilePath,
83
+ parsed: configParseResult
84
+ };
85
+ };
86
+ export const getTsLibFiles = (tsconfigOptions) => {
87
+ const defaultMapFromNodeModules = tsvfs.createDefaultMapFromNodeModules(tsconfigOptions);
88
+ const libPath = dirname(ts.getDefaultLibFilePath(tsconfigOptions));
89
+ return {
90
+ defaultMapFromNodeModules,
91
+ resolvedPaths: [...defaultMapFromNodeModules.keys()].map(path => join(libPath, path))
92
+ };
93
+ };
94
+ export const getProgram = (env) => env?.languageService.getProgram() ??
95
+ TsServer.instance.virtualEnv.languageService.getProgram();
96
+ export const getInternalTypeChecker = (env) => getProgram(env).getTypeChecker();
97
+ export const getStringifiableType = (node) => {
98
+ const typeChecker = getInternalTypeChecker();
99
+ // in a call like attest<object>({a: true}),
100
+ // passing arg.expression avoids inferring {a: true} as object
101
+ const nodeType = typeChecker.getTypeAtLocation(node);
102
+ const stringified = typeChecker.typeToString(nodeType);
103
+ return Object.assign(nodeType, {
104
+ toString: () => stringified,
105
+ isUnresolvable: nodeType.intrinsicName === "error"
106
+ });
107
+ };
108
+ export const extractArgumentTypesFromCall = (call) => ({
109
+ args: call.arguments.map(arg => getStringifiableType(arg)),
110
+ typeArgs: call.typeArguments?.map(typeArg => getStringifiableType(typeArg)) ?? []
111
+ });
112
+ export const getDescendants = (node) => getDescendantsRecurse(node);
113
+ const getDescendantsRecurse = (node) => [
114
+ node,
115
+ ...node.getChildren().flatMap(child => getDescendantsRecurse(child))
116
+ ];
117
+ export const getAncestors = (node) => {
118
+ const ancestors = [];
119
+ let baseNode = node.parent;
120
+ while (baseNode.parent !== undefined) {
121
+ ancestors.push(baseNode);
122
+ baseNode = baseNode.parent;
123
+ }
124
+ return ancestors;
125
+ };
126
+ export const getFirstAncestorByKindOrThrow = (node, kind) => getAncestors(node).find(ancestor => ancestor.kind === kind) ??
127
+ throwInternalError(`Could not find an ancestor of kind ${ts.SyntaxKind[kind]}`);
@@ -0,0 +1,9 @@
1
+ import * as tsvfs from "@typescript/vfs";
2
+ import ts from "typescript";
3
+ import type { AssertionsByFile, LinePositionRange } from "./writeAssertionCache.js";
4
+ export declare const getCallLocationFromCallExpression: (callExpression: ts.CallExpression) => LinePositionRange;
5
+ export declare const gatherInlineInstantiationData: (file: ts.SourceFile, fileAssertions: AssertionsByFile, attestAliasInstantiationMethodCalls: string[]) => void;
6
+ export declare const getCallExpressionsByName: (startNode: ts.Node, names: string[], isSnapCall?: boolean) => ts.CallExpression[];
7
+ export declare const getInstantiationsContributedByNode: (file: ts.SourceFile, benchBlock: ts.FunctionExpression | ts.ArrowFunction) => number;
8
+ export declare const createOrUpdateFile: (env: tsvfs.VirtualTypeScriptEnvironment, fileName: string, fileText: string) => ts.SourceFile | undefined;
9
+ export declare const getIsolatedEnv: () => tsvfs.VirtualTypeScriptEnvironment;