@ark/attest 0.58.0 → 0.59.0-beta.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 +5 -5
- package/out/assert/assertions.d.ts +1 -0
- package/out/assert/assertions.js +82 -21
- package/out/assert/chainableAssertions.js +2 -3
- package/out/bench/baseline.js +2 -1
- package/out/bench/bench.d.ts +2 -3
- package/out/bench/bench.js +67 -27
- package/out/cache/snapshots.js +3 -2
- package/out/cache/utils.js +24 -2
- package/out/cli/shared.d.ts +1 -1
- package/out/cli/shared.js +16 -1
- package/out/cli/stats.js +2 -6
- package/out/cli/trace.js +3 -3
- package/out/config.js +8 -8
- package/out/index.d.ts +2 -1
- package/out/index.js +1 -0
- package/out/ts7/analyze.js +5 -2
- package/out/ts7/countInstantiations.js +17 -2
- package/out/ts7/instantiations.js +62 -8
- package/package.json +5 -5
- package/out/bench/await1k.d.ts +0 -1
- package/out/bench/await1k.js +0 -1002
- package/out/bench/call1k.d.ts +0 -1
- package/out/bench/call1k.js +0 -1002
package/README.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# Attest
|
|
2
2
|
|
|
3
|
-
Attest is a testing library that makes your TypeScript types available at runtime,
|
|
3
|
+
Attest is a testing library that makes your TypeScript types available at runtime, so a test can assert on a value's type, the type errors and completions of an expression, and the type instantiations a block costs.
|
|
4
4
|
|
|
5
|
-
Assertions
|
|
5
|
+
Assertions work from Vitest, Mocha, Jest or any runner with global setup and teardown hooks.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Benches run as plain scripts. They report how many type instantiations a block contributes, which is deterministic for a given TypeScript version, and how long a call takes.
|
|
8
8
|
|
|
9
9
|
If you've ever wondered how [ArkType](https://github.com/arktypeio/arktype) can guarantee identical behavior between its runtime and static parser implementations and highly optimized editor performance, Attest is your answer⚡
|
|
10
10
|
|
|
@@ -20,11 +20,11 @@ _Note: This package is still in alpha! Your feedback will help us iterate toward
|
|
|
20
20
|
|
|
21
21
|
See [arktype.io/docs/attest](https://arktype.io/docs/attest) for:
|
|
22
22
|
|
|
23
|
-
- [
|
|
23
|
+
- [Getting started](https://arktype.io/docs/attest) with Vitest, Mocha, Jest and Bun
|
|
24
24
|
- [Assertions](https://arktype.io/docs/attest/assertions) for types, values, errors, completions and JSDoc
|
|
25
25
|
- [Benches](https://arktype.io/docs/attest/benches) measuring type instantiations and runtime
|
|
26
26
|
- [Options](https://arktype.io/docs/attest/options) like `skipTypes` and `typeToStringFormat`
|
|
27
27
|
- The [CLI](https://arktype.io/docs/attest/cli) for type performance stats and traces
|
|
28
|
-
- [
|
|
28
|
+
- [Custom assertions](https://arktype.io/docs/attest/integration) built on the type data attest collects
|
|
29
29
|
|
|
30
30
|
Please don't hesitate to open a GitHub [issue](https://github.com/arktypeio/arktype/issues/new/choose) or [discussion](https://github.com/arktypeio/arktype/discussions/new/choose) or reach out on [ArkType's Discord](https://arktype.io/discord) if you have any questions or feedback- we'd love to hear from you! ⛵
|
|
@@ -20,6 +20,7 @@ export declare class TypeAssertionMapping {
|
|
|
20
20
|
constructor(fn: TypeAssertionMapper);
|
|
21
21
|
}
|
|
22
22
|
export declare const versionableAssertion: (fn: AssertFn) => AssertFn;
|
|
23
|
+
export declare const assertIs: (expected: unknown, actual: unknown) => void;
|
|
23
24
|
export declare const assertEquals: AssertFn;
|
|
24
25
|
export declare const assertSatisfies: AssertFn;
|
|
25
26
|
export declare const typeEqualityMapping: TypeAssertionMapping;
|
package/out/assert/assertions.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { printable, throwInternalError } from "@ark/util";
|
|
1
|
+
import { constructorNameOf, expressionOf, printable, throwInternalError } from "@ark/util";
|
|
2
2
|
import * as assert from "node:assert/strict";
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
4
|
export const throwAssertionError = ({ stack, ...errorArgs }) => {
|
|
4
5
|
const e = new assert.AssertionError(errorArgs);
|
|
5
6
|
e.stack = stack;
|
|
@@ -34,6 +35,79 @@ export const versionableAssertion = (fn) => (expected, actual, ctx) => {
|
|
|
34
35
|
else
|
|
35
36
|
fn(expected, actual, ctx);
|
|
36
37
|
};
|
|
38
|
+
// node:assert prints the values of a failed deepStrictEqual in full, which
|
|
39
|
+
// for a live graph like a Type's exhausts memory (#1287), so only plain data
|
|
40
|
+
// gets its diff
|
|
41
|
+
const isPlainData = (value, seen = new Set()) => {
|
|
42
|
+
if (typeof value === "function")
|
|
43
|
+
return false;
|
|
44
|
+
if (typeof value !== "object" || value === null || seen.has(value))
|
|
45
|
+
return true;
|
|
46
|
+
seen.add(value);
|
|
47
|
+
const proto = Object.getPrototypeOf(value);
|
|
48
|
+
if (proto === Date.prototype || proto === RegExp.prototype)
|
|
49
|
+
return true;
|
|
50
|
+
if (proto === Map.prototype || proto === Set.prototype) {
|
|
51
|
+
for (const entry of value.entries())
|
|
52
|
+
if (!isPlainData(entry, seen))
|
|
53
|
+
return false;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
if (proto !== Object.prototype && proto !== Array.prototype && proto !== null)
|
|
57
|
+
return false;
|
|
58
|
+
return Reflect.ownKeys(value).every(k => {
|
|
59
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, k);
|
|
60
|
+
return "value" in descriptor && isPlainData(descriptor.value, seen);
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
const maxPrintedDepth = 10;
|
|
64
|
+
// within plain objects and arrays, other objects print as they would at the
|
|
65
|
+
// root, by their expression or constructor
|
|
66
|
+
const printableCopyOf = (value, depth) => {
|
|
67
|
+
if (typeof value === "function")
|
|
68
|
+
return expressionOf(value) ?? value;
|
|
69
|
+
if (typeof value !== "object" || value === null)
|
|
70
|
+
return value;
|
|
71
|
+
const proto = Object.getPrototypeOf(value);
|
|
72
|
+
if (proto === Array.prototype) {
|
|
73
|
+
return depth === maxPrintedDepth ? "[...]" : (value.map(item => printableCopyOf(item, depth + 1)));
|
|
74
|
+
}
|
|
75
|
+
if (proto === Object.prototype || proto === null) {
|
|
76
|
+
return depth === maxPrintedDepth ? "{...}" : (Object.fromEntries(Object.entries(value).map(([k, v]) => [
|
|
77
|
+
k,
|
|
78
|
+
printableCopyOf(v, depth + 1)
|
|
79
|
+
])));
|
|
80
|
+
}
|
|
81
|
+
return depth ?
|
|
82
|
+
(expressionOf(value) ?? constructorNameOf(value) ?? "Object")
|
|
83
|
+
: value;
|
|
84
|
+
};
|
|
85
|
+
// a Type or node prints as its expression, unquoted unless nested
|
|
86
|
+
const printFailed = (value) => {
|
|
87
|
+
const copy = printableCopyOf(value, 0);
|
|
88
|
+
return typeof copy === "string" && typeof value !== "string" ?
|
|
89
|
+
copy
|
|
90
|
+
: printable(copy);
|
|
91
|
+
};
|
|
92
|
+
const throwUnequal = (message, expected, actual) => {
|
|
93
|
+
const serializedExpected = printFailed(expected);
|
|
94
|
+
const serializedActual = printFailed(actual);
|
|
95
|
+
throw new assert.AssertionError({
|
|
96
|
+
message: `${message}
|
|
97
|
+
Expected: ${serializedExpected}
|
|
98
|
+
Actual: ${serializedActual}`,
|
|
99
|
+
expected: serializedExpected,
|
|
100
|
+
actual: serializedActual
|
|
101
|
+
});
|
|
102
|
+
};
|
|
103
|
+
const isReference = (value) => typeof value === "function" || (typeof value === "object" && value !== null);
|
|
104
|
+
export const assertIs = (expected, actual) => {
|
|
105
|
+
if (Object.is(actual, expected))
|
|
106
|
+
return;
|
|
107
|
+
if (isReference(expected) || isReference(actual))
|
|
108
|
+
throwUnequal("Expected values to be reference-equal:", expected, actual);
|
|
109
|
+
assert.equal(actual, expected);
|
|
110
|
+
};
|
|
37
111
|
const unversionedAssertEquals = (expected, actual, ctx) => {
|
|
38
112
|
if (expected === actual)
|
|
39
113
|
return;
|
|
@@ -42,33 +116,20 @@ const unversionedAssertEquals = (expected, actual, ctx) => {
|
|
|
42
116
|
expected !== null &&
|
|
43
117
|
typeof actual === "object" &&
|
|
44
118
|
actual !== null) {
|
|
45
|
-
if (expected.constructor
|
|
119
|
+
if (expected.constructor !== actual.constructor) {
|
|
120
|
+
throwUnequal("Objects did not have the same constructor:", expected, actual);
|
|
121
|
+
}
|
|
122
|
+
else if (isPlainData(expected) && isPlainData(actual))
|
|
46
123
|
assert.deepStrictEqual(actual, expected);
|
|
47
|
-
else {
|
|
48
|
-
|
|
49
|
-
const serializedActual = printable(actual);
|
|
50
|
-
throw new assert.AssertionError({
|
|
51
|
-
message: `Objects did not have the same constructor:
|
|
52
|
-
Expected: ${serializedExpected}
|
|
53
|
-
Actual: ${serializedActual}`,
|
|
54
|
-
expected: serializedExpected,
|
|
55
|
-
actual: serializedActual
|
|
56
|
-
});
|
|
124
|
+
else if (!isDeepStrictEqual(actual, expected)) {
|
|
125
|
+
throwUnequal("Expected values to be strictly deep-equal:", expected, actual);
|
|
57
126
|
}
|
|
58
127
|
}
|
|
59
128
|
else if (typeof expected === "object" ||
|
|
60
129
|
typeof expected === "function" ||
|
|
61
130
|
typeof actual === "function" ||
|
|
62
131
|
typeof actual === "function") {
|
|
63
|
-
|
|
64
|
-
const serializedActual = printable(actual);
|
|
65
|
-
throw new assert.AssertionError({
|
|
66
|
-
message: `Assertion including at least one function or object was not between reference equal items
|
|
67
|
-
Expected: ${serializedExpected}
|
|
68
|
-
Actual: ${serializedActual}`,
|
|
69
|
-
expected: serializedExpected,
|
|
70
|
-
actual: serializedActual
|
|
71
|
-
});
|
|
132
|
+
throwUnequal("Assertion including at least one function or object was not between reference equal items", expected, actual);
|
|
72
133
|
// guaranteed to be two primitives at this point
|
|
73
134
|
}
|
|
74
135
|
else
|
|
@@ -2,12 +2,11 @@ import { caller, positionToString } from "@ark/fs";
|
|
|
2
2
|
import { printable, snapshot } from "@ark/util";
|
|
3
3
|
import prettier from "@prettier/sync";
|
|
4
4
|
import { type } from "arktype";
|
|
5
|
-
import * as assert from "node:assert/strict";
|
|
6
5
|
import { isDeepStrictEqual } from "node:util";
|
|
7
6
|
import { getSnapshotByName, queueSnapshotUpdate, updateExternalSnapshot } from "../cache/snapshots.js";
|
|
8
7
|
import { getConfig } from "../config.js";
|
|
9
8
|
import { chainableNoOpProxy } from "../utils.js";
|
|
10
|
-
import { MissingSnapshotError, TypeAssertionMapping, assertEqualOrMatching, assertEquals, assertSatisfies, callAssertedFunction, getThrownMessage, throwAssertionError } from "./assertions.js";
|
|
9
|
+
import { MissingSnapshotError, TypeAssertionMapping, assertEqualOrMatching, assertEquals, assertIs, assertSatisfies, callAssertedFunction, getThrownMessage, throwAssertionError } from "./assertions.js";
|
|
11
10
|
export class ChainableAssertions {
|
|
12
11
|
ctx;
|
|
13
12
|
constructor(ctx) {
|
|
@@ -40,7 +39,7 @@ export class ChainableAssertions {
|
|
|
40
39
|
return this;
|
|
41
40
|
}
|
|
42
41
|
is(expected) {
|
|
43
|
-
|
|
42
|
+
assertIs(expected, this.unversionedActual);
|
|
44
43
|
return this;
|
|
45
44
|
}
|
|
46
45
|
equals(expected) {
|
package/out/bench/baseline.js
CHANGED
|
@@ -44,7 +44,8 @@ const handlePositiveDelta = (formattedDelta, ctx) => {
|
|
|
44
44
|
const message = `'${ctx.qualifiedName}' exceeded baseline by ${formattedDelta} (threshold is ${ctx.cfg.benchPercentThreshold}%).`;
|
|
45
45
|
console.error(`📈 ${message}`);
|
|
46
46
|
const benchErrorConfig = ctx.cfg.benchErrorOnThresholdExceeded;
|
|
47
|
-
const isTypeBench = ctx.lastSnapFunctionName === "
|
|
47
|
+
const isTypeBench = ctx.lastSnapFunctionName === "types" ||
|
|
48
|
+
ctx.lastSnapFunctionName === "instantiations";
|
|
48
49
|
const shouldError = benchErrorConfig === true ||
|
|
49
50
|
(isTypeBench ?
|
|
50
51
|
benchErrorConfig === "types"
|
package/out/bench/bench.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ export declare const stats: {
|
|
|
13
13
|
mean: (callTimes: number[]) => number;
|
|
14
14
|
median: (callTimes: number[]) => number;
|
|
15
15
|
};
|
|
16
|
-
export declare class BenchAssertions<Fn extends BenchableFunction, NextAssertions = BenchTypeAssertions, ReturnedAssertions = Fn extends () =>
|
|
16
|
+
export declare class BenchAssertions<Fn extends BenchableFunction, NextAssertions = BenchTypeAssertions, ReturnedAssertions = Fn extends () => PromiseLike<unknown> ? Promise<NextAssertions> : NextAssertions> {
|
|
17
17
|
private label;
|
|
18
18
|
private lastCallTimes;
|
|
19
19
|
private fn;
|
|
@@ -56,9 +56,8 @@ export type BenchContext = {
|
|
|
56
56
|
benchCallPosition: SourcePosition;
|
|
57
57
|
lastSnapCallPosition: SourcePosition | undefined;
|
|
58
58
|
lastSnapFunctionName: string | undefined;
|
|
59
|
-
isAsync: boolean;
|
|
60
59
|
};
|
|
61
60
|
export type BenchableFunction = () => unknown | Promise<unknown>;
|
|
62
61
|
export type InitialBenchAssertions<Fn extends BenchableFunction> = BenchAssertions<Fn> & BenchTypeAssertions;
|
|
63
|
-
export declare const getBenchCtx: (qualifiedPath: string[],
|
|
62
|
+
export declare const getBenchCtx: (qualifiedPath: string[], options?: BenchOptions) => BenchContext;
|
|
64
63
|
export {};
|
package/out/bench/bench.js
CHANGED
|
@@ -2,16 +2,14 @@ import { caller, getCallStack, rmRf } from "@ark/fs";
|
|
|
2
2
|
import { performance } from "node:perf_hooks";
|
|
3
3
|
import { ensureCacheDirs, getConfig } from "../config.js";
|
|
4
4
|
import { chainableNoOpProxy } from "../utils.js";
|
|
5
|
-
import { await1K } from "./await1k.js";
|
|
6
5
|
import { compareToBaseline, queueBaselineUpdateIfNeeded } from "./baseline.js";
|
|
7
|
-
import { call1K } from "./call1k.js";
|
|
8
6
|
import { createTimeComparison, createTimeMeasure } from "./measure.js";
|
|
9
7
|
import { createBenchTypeAssertion } from "./type.js";
|
|
10
8
|
let benchHasRun = false;
|
|
11
9
|
const benchFn = (name, fn, options) => {
|
|
12
10
|
const qualifiedPath = [...currentSuitePath, name];
|
|
13
11
|
console.log(`🏌️ ${qualifiedPath.join("/")}`);
|
|
14
|
-
const ctx = getBenchCtx(qualifiedPath,
|
|
12
|
+
const ctx = getBenchCtx(qualifiedPath, options);
|
|
15
13
|
if (!benchHasRun) {
|
|
16
14
|
rmRf(ctx.cfg.cacheDir);
|
|
17
15
|
ensureCacheDirs();
|
|
@@ -44,20 +42,32 @@ export const stats = {
|
|
|
44
42
|
return ms;
|
|
45
43
|
}
|
|
46
44
|
};
|
|
45
|
+
const sampleMs = 0.2;
|
|
46
|
+
const warmupMs = 500;
|
|
47
|
+
let loopCount = 0;
|
|
48
|
+
const AsyncFunction = (async () => { }).constructor;
|
|
49
|
+
// a unique source per loop keeps V8 from sharing feedback between benches
|
|
50
|
+
const createLoop = (isAsync) => new (isAsync ? AsyncFunction : Function)("fn", "n", `// bench loop ${loopCount++}
|
|
51
|
+
let result
|
|
52
|
+
for (let i = 0; i < n; i++) result = ${isAsync ? "await " : ""}fn()
|
|
53
|
+
return result`);
|
|
47
54
|
class ResultCollector {
|
|
48
55
|
results = [];
|
|
49
|
-
|
|
56
|
+
callsPerSample = 1;
|
|
50
57
|
bounds;
|
|
58
|
+
isWarm = false;
|
|
59
|
+
phaseEnd;
|
|
51
60
|
lastInvocationStart;
|
|
52
61
|
ctx;
|
|
53
62
|
constructor(ctx) {
|
|
54
63
|
this.ctx = ctx;
|
|
55
|
-
// By default, will
|
|
64
|
+
// By default, will sample for either 5 seconds or 100_000 samples, whichever comes first
|
|
56
65
|
this.bounds = {
|
|
57
66
|
ms: 5000,
|
|
58
67
|
count: 100_000,
|
|
59
68
|
...ctx.options.until
|
|
60
69
|
};
|
|
70
|
+
this.phaseEnd = performance.now() + Math.min(warmupMs, this.bounds.ms);
|
|
61
71
|
this.lastInvocationStart = -1;
|
|
62
72
|
}
|
|
63
73
|
start() {
|
|
@@ -65,33 +75,54 @@ class ResultCollector {
|
|
|
65
75
|
this.lastInvocationStart = performance.now();
|
|
66
76
|
}
|
|
67
77
|
stop() {
|
|
68
|
-
|
|
78
|
+
const end = performance.now();
|
|
79
|
+
const ms = end - this.lastInvocationStart;
|
|
69
80
|
this.ctx.options.hooks?.afterCall?.();
|
|
81
|
+
if (this.isWarm)
|
|
82
|
+
this.results.push(ms / this.callsPerSample);
|
|
83
|
+
else if (end < this.phaseEnd) {
|
|
84
|
+
if (ms < sampleMs / 2)
|
|
85
|
+
this.callsPerSample *= 2;
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
this.callsPerSample = Math.max(1, Math.round((this.callsPerSample * sampleMs) / (ms || 1e-3)));
|
|
89
|
+
this.isWarm = true;
|
|
90
|
+
this.phaseEnd = end + this.bounds.ms;
|
|
91
|
+
}
|
|
70
92
|
}
|
|
71
93
|
done() {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
94
|
+
return (this.isWarm &&
|
|
95
|
+
(performance.now() >= this.phaseEnd ||
|
|
96
|
+
this.results.length >= this.bounds.count));
|
|
75
97
|
}
|
|
76
98
|
}
|
|
99
|
+
const warnIfUnused = (result, ctx) => {
|
|
100
|
+
if (result === undefined) {
|
|
101
|
+
console.warn(`⚠️ ${ctx.qualifiedName} returned undefined. Return the result it computes so V8 can't optimize the work away.`);
|
|
102
|
+
}
|
|
103
|
+
};
|
|
77
104
|
const loopCalls = (fn, ctx) => {
|
|
105
|
+
const loop = createLoop(false);
|
|
78
106
|
const collector = new ResultCollector(ctx);
|
|
107
|
+
let result;
|
|
79
108
|
while (!collector.done()) {
|
|
80
109
|
collector.start();
|
|
81
|
-
|
|
82
|
-
// to avoid certain optimizations V8 makes when looping
|
|
83
|
-
call1K(fn);
|
|
110
|
+
result = loop(fn, collector.callsPerSample);
|
|
84
111
|
collector.stop();
|
|
85
112
|
}
|
|
113
|
+
warnIfUnused(result, ctx);
|
|
86
114
|
return collector.results;
|
|
87
115
|
};
|
|
88
116
|
const loopAsyncCalls = async (fn, ctx) => {
|
|
117
|
+
const loop = createLoop(true);
|
|
89
118
|
const collector = new ResultCollector(ctx);
|
|
119
|
+
let result;
|
|
90
120
|
while (!collector.done()) {
|
|
91
121
|
collector.start();
|
|
92
|
-
await
|
|
122
|
+
result = await loop(fn, collector.callsPerSample);
|
|
93
123
|
collector.stop();
|
|
94
124
|
}
|
|
125
|
+
warnIfUnused(result, ctx);
|
|
95
126
|
return collector.results;
|
|
96
127
|
};
|
|
97
128
|
export class BenchAssertions {
|
|
@@ -115,7 +146,7 @@ export class BenchAssertions {
|
|
|
115
146
|
callTimesSync() {
|
|
116
147
|
if (!this.lastCallTimes) {
|
|
117
148
|
this.lastCallTimes = loopCalls(this.fn, this.ctx);
|
|
118
|
-
this.lastCallTimes.sort();
|
|
149
|
+
this.lastCallTimes.sort((l, r) => l - r);
|
|
119
150
|
}
|
|
120
151
|
this.applyCallTimeHooks();
|
|
121
152
|
return this.lastCallTimes;
|
|
@@ -123,7 +154,7 @@ export class BenchAssertions {
|
|
|
123
154
|
async callTimesAsync() {
|
|
124
155
|
if (!this.lastCallTimes) {
|
|
125
156
|
this.lastCallTimes = await loopAsyncCalls(this.fn, this.ctx);
|
|
126
|
-
this.lastCallTimes.sort();
|
|
157
|
+
this.lastCallTimes.sort((l, r) => l - r);
|
|
127
158
|
}
|
|
128
159
|
this.applyCallTimeHooks();
|
|
129
160
|
return this.lastCallTimes;
|
|
@@ -167,18 +198,28 @@ export class BenchAssertions {
|
|
|
167
198
|
return createBenchTypeAssertion(this.ctx);
|
|
168
199
|
}
|
|
169
200
|
createStatMethod(name, baseline) {
|
|
170
|
-
if (this.ctx.isAsync) {
|
|
171
|
-
return new Promise(resolve => {
|
|
172
|
-
this.callTimesAsync().then(callTimes => {
|
|
173
|
-
resolve(this.createAssertion(name, baseline, callTimes));
|
|
174
|
-
}, e => {
|
|
175
|
-
this.addUnhandledBenchException(e);
|
|
176
|
-
resolve(chainableNoOpProxy);
|
|
177
|
-
});
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
201
|
let assertions = chainableNoOpProxy;
|
|
202
|
+
const { hooks } = this.ctx.options;
|
|
181
203
|
try {
|
|
204
|
+
hooks?.beforeCall?.();
|
|
205
|
+
// fn may return a Promise without being an async function
|
|
206
|
+
const firstResult = this.fn();
|
|
207
|
+
if (typeof firstResult?.then === "function") {
|
|
208
|
+
return new Promise(resolve => {
|
|
209
|
+
Promise.resolve(firstResult)
|
|
210
|
+
.then(() => {
|
|
211
|
+
hooks?.afterCall?.();
|
|
212
|
+
return this.callTimesAsync();
|
|
213
|
+
})
|
|
214
|
+
.then(callTimes => {
|
|
215
|
+
resolve(this.createAssertion(name, baseline, callTimes));
|
|
216
|
+
}, e => {
|
|
217
|
+
this.addUnhandledBenchException(e);
|
|
218
|
+
resolve(chainableNoOpProxy);
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
hooks?.afterCall?.();
|
|
182
223
|
assertions = this.createAssertion(name, baseline, this.callTimesSync());
|
|
183
224
|
}
|
|
184
225
|
catch (e) {
|
|
@@ -213,7 +254,7 @@ process.on("beforeExit", () => {
|
|
|
213
254
|
process.exit(1);
|
|
214
255
|
}
|
|
215
256
|
});
|
|
216
|
-
export const getBenchCtx = (qualifiedPath,
|
|
257
|
+
export const getBenchCtx = (qualifiedPath, options = {}) => ({
|
|
217
258
|
qualifiedPath,
|
|
218
259
|
qualifiedName: qualifiedPath.join("/"),
|
|
219
260
|
options,
|
|
@@ -221,6 +262,5 @@ export const getBenchCtx = (qualifiedPath, isAsync = false, options = {}) => ({
|
|
|
221
262
|
benchCallPosition: caller(),
|
|
222
263
|
lastSnapCallPosition: undefined,
|
|
223
264
|
lastSnapFunctionName: undefined,
|
|
224
|
-
isAsync,
|
|
225
265
|
assertionStack: getCallStack({ offset: 1 }).join("\n")
|
|
226
266
|
});
|
package/out/cache/snapshots.js
CHANGED
|
@@ -12,9 +12,10 @@ export const resolveSnapshotPath = (testFile, customPath) => {
|
|
|
12
12
|
return customPath;
|
|
13
13
|
return join(dirname(testFile), customPath ?? "assert.snapshots.json");
|
|
14
14
|
};
|
|
15
|
+
const readSnapshotFile = (path) => existsSync(path) ? readJson(path) : {};
|
|
15
16
|
export const getSnapshotByName = (file, name, customPath) => {
|
|
16
17
|
const snapshotPath = resolveSnapshotPath(file, customPath);
|
|
17
|
-
return
|
|
18
|
+
return readSnapshotFile(snapshotPath)[basename(file)]?.[name];
|
|
18
19
|
};
|
|
19
20
|
/**
|
|
20
21
|
* Writes the update and position to cacheDir, which will eventually be read and copied to the source
|
|
@@ -49,7 +50,7 @@ const getSnapCallArgs = (position, functionName) => {
|
|
|
49
50
|
};
|
|
50
51
|
export const updateExternalSnapshot = ({ serializedValue: value, position, name, customPath }) => {
|
|
51
52
|
const snapshotPath = resolveSnapshotPath(position.file, customPath);
|
|
52
|
-
const snapshotData =
|
|
53
|
+
const snapshotData = readSnapshotFile(snapshotPath);
|
|
53
54
|
const fileKey = basename(position.file);
|
|
54
55
|
snapshotData[fileKey] = {
|
|
55
56
|
...snapshotData[fileKey],
|
package/out/cache/utils.js
CHANGED
|
@@ -79,9 +79,29 @@ export const getInstantiationsContributedByNode = (file, benchBlock) => {
|
|
|
79
79
|
const instantiationsWithoutNode = getInstantiationsWithFile(baselineFile, fakePath);
|
|
80
80
|
instantiationsByPath[fakePath] = instantiationsWithoutNode;
|
|
81
81
|
}
|
|
82
|
-
const instantiationsWithNode = getInstantiationsWithFile(baselineFileWithBenchBlock, fakePath
|
|
82
|
+
const instantiationsWithNode = getInstantiationsWithFile(baselineFileWithBenchBlock, fakePath,
|
|
83
|
+
// a generic block's result would be inferred from constraints it's
|
|
84
|
+
// never called with
|
|
85
|
+
!benchBlock.typeParameters?.length);
|
|
83
86
|
return instantiationsWithNode - instantiationsByPath[fakePath];
|
|
84
87
|
};
|
|
88
|
+
/**
|
|
89
|
+
* TS only evaluates the members of many types, e.g. mapped types, once
|
|
90
|
+
* something reads them, so the result of the block appended last is
|
|
91
|
+
* displayed to count it as if it were used.
|
|
92
|
+
*/
|
|
93
|
+
const displayBenchResult = (program, file) => {
|
|
94
|
+
const checker = program.getTypeChecker();
|
|
95
|
+
const bench = file.statements[file.statements.length - 1];
|
|
96
|
+
if (!ts.isVariableStatement(bench))
|
|
97
|
+
throwInternalError(`Expected a bench declaration, got ${bench.getText()}`);
|
|
98
|
+
const benchType = checker.getTypeAtLocation(bench.declarationList.declarations[0].name);
|
|
99
|
+
for (const signature of benchType.getCallSignatures()) {
|
|
100
|
+
checker.typeToString(signature.getReturnType(), undefined, ts.TypeFormatFlags.NoTruncation |
|
|
101
|
+
ts.TypeFormatFlags.AllowUniqueESSymbolType |
|
|
102
|
+
ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
85
105
|
export const createOrUpdateFile = (env, fileName, fileText) => {
|
|
86
106
|
if (env.sys.fileExists(fileName))
|
|
87
107
|
env.updateFile(fileName, fileText);
|
|
@@ -89,7 +109,7 @@ export const createOrUpdateFile = (env, fileName, fileText) => {
|
|
|
89
109
|
env.createFile(fileName, fileText);
|
|
90
110
|
return env.getSourceFile(fileName);
|
|
91
111
|
};
|
|
92
|
-
const getInstantiationsWithFile = (fileText, fileName) => {
|
|
112
|
+
const getInstantiationsWithFile = (fileText, fileName, displayResult = false) => {
|
|
93
113
|
const env = getIsolatedEnv();
|
|
94
114
|
const file = createOrUpdateFile(env, fileName, fileText);
|
|
95
115
|
const program = getProgram(env);
|
|
@@ -101,6 +121,8 @@ const getInstantiationsWithFile = (fileText, fileName) => {
|
|
|
101
121
|
// this may lead to additional type checking per Jake Bailey from the TS
|
|
102
122
|
// team, although it doesn't currently affect any of our internal benchmarks
|
|
103
123
|
program.getDeclarationDiagnostics(file);
|
|
124
|
+
if (displayResult && file)
|
|
125
|
+
displayBenchResult(program, file);
|
|
104
126
|
const count = program.getInstantiationCount();
|
|
105
127
|
return count;
|
|
106
128
|
};
|
package/out/cli/shared.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const
|
|
1
|
+
export declare const getDiagnosticTscOutput: (cwd: string, args?: string) => string;
|
package/out/cli/shared.js
CHANGED
|
@@ -1,4 +1,19 @@
|
|
|
1
|
+
import { getShellOutput, rmRf } from "@ark/fs";
|
|
2
|
+
import { mkdtempSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
1
5
|
import { isTs7 } from "../utils.js";
|
|
2
|
-
|
|
6
|
+
const baseDiagnosticTscCmd = "npm exec -- tsc --noEmit --extendedDiagnostics --incremental" +
|
|
3
7
|
// parallel checkers each instantiate their own copies of types
|
|
4
8
|
(isTs7 ? " --singleThreaded" : "");
|
|
9
|
+
export const getDiagnosticTscOutput = (cwd, args = "") => {
|
|
10
|
+
// composite projects can't disable incremental, so a fresh build info file
|
|
11
|
+
// keeps stale state from skipping the check
|
|
12
|
+
const buildInfoDir = mkdtempSync(join(tmpdir(), "attest-"));
|
|
13
|
+
try {
|
|
14
|
+
return getShellOutput(`${baseDiagnosticTscCmd} --tsBuildInfoFile "${join(buildInfoDir, "tsconfig.tsbuildinfo")}" ${args}`, { cwd });
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
rmRf(buildInfoDir);
|
|
18
|
+
}
|
|
19
|
+
};
|
package/out/cli/stats.js
CHANGED
|
@@ -1,15 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { baseDiagnosticTscCmd } from "./shared.js";
|
|
1
|
+
import { getDiagnosticTscOutput } from "./shared.js";
|
|
3
2
|
export const stats = (args) => {
|
|
4
3
|
const packageDirs = args.length ? args : [process.cwd()];
|
|
5
4
|
const listedStats = packageDirs.map((packageDir) => {
|
|
6
5
|
console.log(`⏳ Gathering type perf data for ${packageDir}...`);
|
|
7
6
|
let output;
|
|
8
7
|
try {
|
|
9
|
-
output =
|
|
10
|
-
cwd: packageDir,
|
|
11
|
-
stdio: "pipe"
|
|
12
|
-
}).toString();
|
|
8
|
+
output = getDiagnosticTscOutput(packageDir);
|
|
13
9
|
}
|
|
14
10
|
catch (e) {
|
|
15
11
|
output = e.stdout?.toString() ?? "";
|
package/out/cli/trace.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ensureDir,
|
|
1
|
+
import { ensureDir, readJson, writeFile } from "@ark/fs";
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
3
|
import { basename, join, relative, resolve } from "node:path";
|
|
4
4
|
import ts from "typescript";
|
|
@@ -8,7 +8,7 @@ import { stringifyTypeAtLocation } from "../ts7/analyze.js";
|
|
|
8
8
|
import { TsgoServer, ast, getDescendants as getDescendantsTs7 } from "../ts7/server.js";
|
|
9
9
|
import { nearestBoundingCallExpression as nearestBoundingCallExpressionTs7 } from "../ts7/snapshots.js";
|
|
10
10
|
import { isTs7 } from "../utils.js";
|
|
11
|
-
import {
|
|
11
|
+
import { getDiagnosticTscOutput } from "./shared.js";
|
|
12
12
|
// TS 7's AST matches TS 5's shape for everything used here
|
|
13
13
|
const syntax = isTs7 ? ast : ts;
|
|
14
14
|
const getSourceFile = (path) => isTs7 ?
|
|
@@ -190,7 +190,7 @@ export const trace = async (args) => {
|
|
|
190
190
|
};
|
|
191
191
|
const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
|
|
192
192
|
try {
|
|
193
|
-
const output =
|
|
193
|
+
const output = getDiagnosticTscOutput(packageDir, `--project ${tsconfigPath} --generateTrace ${traceDir}`);
|
|
194
194
|
process.stdout.write(output); // Display tsc output directly
|
|
195
195
|
return output;
|
|
196
196
|
}
|
package/out/config.js
CHANGED
|
@@ -53,14 +53,14 @@ const getParamValue = (param) => {
|
|
|
53
53
|
};
|
|
54
54
|
export const attestEnvPrefix = "ATTEST_";
|
|
55
55
|
const addEnvConfig = (config) => {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
56
|
+
// the config setup() passes to child processes comes first, so an option
|
|
57
|
+
// set on its own overrides it wherever the platform orders the environment
|
|
58
|
+
const { ATTEST_CONFIG, ...env } = process.env;
|
|
59
|
+
if (ATTEST_CONFIG)
|
|
60
|
+
Object.assign(config, JSON.parse(ATTEST_CONFIG));
|
|
61
|
+
for (const [k, v] of Object.entries(env)) {
|
|
62
|
+
if (k.startsWith(attestEnvPrefix))
|
|
63
|
+
config[k.slice(attestEnvPrefix.length)] = JSON.parse(v);
|
|
64
64
|
}
|
|
65
65
|
let k;
|
|
66
66
|
for (k in config) {
|
package/out/index.d.ts
CHANGED
|
@@ -3,5 +3,6 @@ export { caller, type CallerOfOptions } from "@ark/fs";
|
|
|
3
3
|
export { attest } from "./assert/attest.ts";
|
|
4
4
|
export { bench } from "./bench/bench.ts";
|
|
5
5
|
export { getBenchAssertionAtPosition, getTypeAssertionAtPosition, type ArgAssertionData, type LinePositionRange, type TypeAssertionData, type TypeRelationship } from "./cache/getCachedAssertions.ts";
|
|
6
|
-
export { getDefaultAttestConfig, type AttestConfig } from "./config.ts";
|
|
6
|
+
export { getDefaultAttestConfig, type AttestConfig, type Checker } from "./config.ts";
|
|
7
|
+
export { getChecker } from "./ts7/server.ts";
|
|
7
8
|
export { contextualize } from "./utils.ts";
|
package/out/index.js
CHANGED
|
@@ -5,4 +5,5 @@ export { attest } from "./assert/attest.js";
|
|
|
5
5
|
export { bench } from "./bench/bench.js";
|
|
6
6
|
export { getBenchAssertionAtPosition, getTypeAssertionAtPosition } from "./cache/getCachedAssertions.js";
|
|
7
7
|
export { getDefaultAttestConfig } from "./config.js";
|
|
8
|
+
export { getChecker } from "./ts7/server.js";
|
|
8
9
|
export { contextualize } from "./utils.js";
|
package/out/ts7/analyze.js
CHANGED
|
@@ -117,8 +117,11 @@ const getCompletions = (call, file) => {
|
|
|
117
117
|
return `Encountered multiple completion candidates for string(s) '${prefix}'. Assertions on the same prefix must be split into multiple attest calls so the results can be distinguished.`;
|
|
118
118
|
const entries = TsgoServer.instance.project.languageService.getCompletionsAtPosition(file.fileName, position)?.entries ?? [];
|
|
119
119
|
completions[prefix] = entries
|
|
120
|
-
// names of optional properties are suffixed with "?"
|
|
121
|
-
|
|
120
|
+
// names of optional properties are suffixed with "?", but a string's
|
|
121
|
+
// filter text can be just its last word, like "/a" for "#/a"
|
|
122
|
+
.map(entry => entry.filterText && entry.name.startsWith(entry.filterText) ?
|
|
123
|
+
entry.filterText
|
|
124
|
+
: entry.name)
|
|
122
125
|
.filter(name => name.startsWith(prefix) && name.length > prefix.length);
|
|
123
126
|
}
|
|
124
127
|
return flatMorph(completions, (prefix, entries) => entries.length >= 1 ? [prefix, entries.sort()] : []);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { availableParallelism } from "node:os";
|
|
4
|
+
import { basename } from "node:path";
|
|
4
5
|
const tscPath = process.argv[2];
|
|
5
6
|
const { files, configPaths } = JSON.parse(readFileSync(0, "utf8"));
|
|
6
7
|
// this process owns the files so they're removed even if a run is
|
|
@@ -30,9 +31,23 @@ const countInstantiations = (configPath) => new Promise((resolve, reject) => exe
|
|
|
30
31
|
if (count === undefined || !stdout.includes("Check time:")) {
|
|
31
32
|
reject(new Error(`Unable to read instantiations for ${configPath}:\n${stdout}${stderr}`));
|
|
32
33
|
}
|
|
33
|
-
else
|
|
34
|
-
resolve(
|
|
34
|
+
else {
|
|
35
|
+
resolve({
|
|
36
|
+
count: Number(count),
|
|
37
|
+
errorLines: getErrorLines(stdout, configPath)
|
|
38
|
+
});
|
|
39
|
+
}
|
|
35
40
|
}));
|
|
41
|
+
const getErrorLines = (stdout, configPath) => {
|
|
42
|
+
const rootFile = basename(JSON.parse(files[configPath]).files[0]);
|
|
43
|
+
const lines = [];
|
|
44
|
+
for (const line of stdout.split("\n")) {
|
|
45
|
+
const location = /^(.+)\((\d+),\d+\): error TS/.exec(line);
|
|
46
|
+
if (location && basename(location[1]) === rootFile)
|
|
47
|
+
lines.push(Number(location[2]));
|
|
48
|
+
}
|
|
49
|
+
return lines;
|
|
50
|
+
};
|
|
36
51
|
const counts = Array.from({ length: configPaths.length });
|
|
37
52
|
let next = 0;
|
|
38
53
|
const worker = async () => {
|