@ark/attest 0.57.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,378 +16,15 @@ npm install @ark/attest
16
16
 
17
17
  _Note: This package is still in alpha! Your feedback will help us iterate toward a stable 1.0._
18
18
 
19
- ## Setup
19
+ ## Docs
20
20
 
21
- To use attest's type assertions, you'll need to call our setup/cleanup methods before your first test and after your last test, respectively. This usually involves some kind of globalSetup/globalTeardown config.
21
+ See [arktype.io/docs/attest](https://arktype.io/docs/attest) for:
22
22
 
23
- > [!IMPORTANT]
24
- > If you run your tests in watch mode or otherwise iteratively during dev, you will want to enable [`--skipTypes` mode](#skiptypes).
23
+ - [Setup](https://arktype.io/docs/attest) with Vitest, Mocha and other test runners
24
+ - [Assertions](https://arktype.io/docs/attest/assertions) for types, values, errors, completions and JSDoc
25
+ - [Benches](https://arktype.io/docs/attest/benches) measuring type instantiations and runtime
26
+ - [Options](https://arktype.io/docs/attest/options) like `skipTypes` and `typeToStringFormat`
27
+ - The [CLI](https://arktype.io/docs/attest/cli) for type performance stats and traces
28
+ - [Integrating](https://arktype.io/docs/attest/integration) attest's type data into your own assertions
25
29
 
26
- ### Vitest
27
-
28
- `vitest.config.ts`
29
-
30
- ```ts
31
- import { defineConfig } from "vitest/config"
32
-
33
- export default defineConfig({
34
- test: {
35
- globalSetup: ["setupVitest.ts"]
36
- }
37
- })
38
- ```
39
-
40
- `setupVitest.ts`
41
-
42
- ```ts
43
- import { setup } from "@ark/attest"
44
-
45
- // config options can be passed here
46
- export default () => setup({})
47
- ```
48
-
49
- ### Mocha
50
-
51
- `package.json`
52
-
53
- ```json
54
- "mocha": {
55
- "require": "./setupMocha.ts"
56
- }
57
- ```
58
-
59
- `setupMocha.ts`
60
-
61
- ```ts
62
- import { setup, teardown } from "@ark/attest"
63
-
64
- // config options can be passed here
65
- export const mochaGlobalSetup = () => setup({})
66
-
67
- export const mochaGlobalTeardown = teardown
68
- ```
69
-
70
- You should also add `.attest` to your repository's `.gitignore` file.
71
-
72
- Bun support is currently pending [them supporting @prettier/sync for type formatting](https://github.com/oven-sh/bun/issues/10768). If this is a problem for you, please 👍 that issue so they prioritize it!
73
-
74
- ## Assertions
75
-
76
- Here are some simple examples of type assertions and snapshotting:
77
-
78
- ```ts
79
- // @ark/attest assertions can be made from any unit test framework with a global setup/teardown
80
- describe("attest features", () => {
81
- it("type and value assertions", () => {
82
- const even = type("number%2")
83
- // asserts even.infer is exactly number
84
- attest<number>(even.infer)
85
- // make assertions about types and values seamlessly
86
- attest(even.infer).type.toString.snap("number")
87
- // including object literals- no more long inline strings!
88
- attest(even.json).snap({
89
- intersection: [{ domain: "number" }, { divisor: 2 }]
90
- })
91
- })
92
-
93
- it("error assertions", () => {
94
- // Check type errors, runtime errors, or both at the same time!
95
- // @ts-expect-error
96
- attest(() => type("number%0")).throwsAndHasTypeError(
97
- "% operator must be followed by a non-zero integer literal (was 0)"
98
- )
99
- // @ts-expect-error
100
- attest(() => type({ "[object]": "string" })).type.errors(
101
- "Indexed key definition 'object' must be a string, number or symbol"
102
- )
103
- })
104
-
105
- it("completion snapshotting", () => {
106
- // snapshot expected completions for any string literal!
107
- // @ts-expect-error (if your expression would throw, prepend () =>)
108
- attest(() => type({ a: "a", b: "b" })).completions({
109
- a: ["any", "alpha", "alphanumeric"],
110
- b: ["bigint", "boolean"]
111
- })
112
- type Legends = { faker?: "🐐"; [others: string]: unknown }
113
- // works for keys or index access as well (may need prettier-ignore to avoid removing quotes)
114
- // prettier-ignore
115
- attest({ "f": "🐐" } as Legends).completions({ "f": ["faker"] })
116
- })
117
-
118
- it("jsdoc snapshotting", () => {
119
- // match or snapshot expected jsdoc associated with the value passed to attest
120
- const T = type({
121
- /** FOO */
122
- foo: "string"
123
- })
124
-
125
- const out = T.assert({ foo: "foo" })
126
-
127
- attest(out.foo).jsdoc.snap("FOO")
128
- })
129
-
130
- it("integrate runtime logic with type assertions", () => {
131
- const arrayOf = type("<t>", "t[]")
132
- const numericArray = arrayOf("number | bigint")
133
- // flexibly combine runtime logic with type assertions to customize your
134
- // tests beyond what is possible from pure static-analysis based type testing tools
135
- if (ts.version.startsWith("5")) {
136
- // this assertion will only occur when testing TypeScript 5+!
137
- attest<(number | bigint)[]>(numericArray.infer)
138
- }
139
- })
140
-
141
- it("integrated type performance benchmarking", () => {
142
- const User = type({
143
- kind: "'admin'",
144
- "powers?": "string[]"
145
- })
146
- .or({
147
- kind: "'superadmin'",
148
- "superpowers?": "string[]"
149
- })
150
- .or({
151
- kind: "'pleb'"
152
- })
153
- attest.instantiations([7574, "instantiations"])
154
- })
155
- })
156
- ```
157
-
158
- ## Options
159
-
160
- Options can be specified in one of 3 ways:
161
-
162
- - An argument passed to your test process, e.g. `--skipTypes` or `--benchPercentThreshold 10`
163
- - An environment variable with an `ATTEST_` prefix, e.g. `ATTEST_skipTypes=1` or `ATTEST_benchPercentThreshold=10`
164
- - Passed as an option to attest's `setup` function, e.g.:
165
-
166
- `setupVitest.ts`
167
-
168
- ```ts
169
- import * as attest from "@ark/attest"
170
-
171
- export const setup = () =>
172
- attest.setup({
173
- skipTypes: true,
174
- benchPercentThreshold: 10
175
- })
176
- ```
177
-
178
- Here are the current defaults for all available options. Please note, some of these are experimental and subject to change:
179
-
180
- ```ts
181
- export const getDefaultAttestConfig = (): BaseAttestConfig => ({
182
- tsconfig:
183
- existsSync(fromCwd("tsconfig.json")) ? fromCwd("tsconfig.json") : undefined,
184
- attestAliases: ["attest", "attestInternal"],
185
- updateSnapshots: false,
186
- skipTypes: false,
187
- skipInlineInstantiations: false,
188
- benchPercentThreshold: 20,
189
- benchErrorOnThresholdExceeded: true,
190
- filter: undefined,
191
- testDeclarationAliases: ["bench", "it", "test"],
192
- formatter: `npm exec --no -- prettier --write`,
193
- shouldFormat: true,
194
- typeToStringFormat: {}
195
- })
196
- ```
197
-
198
- ### `skipTypes`
199
-
200
- `skipTypes` is extremely useful for iterating quickly during development without having to typecheck your project to test runtime logic.
201
-
202
- When this setting is enabled, setup will skip type checking and all assertions requiring type information will be skipped.
203
-
204
- You likely want two scripts, one for running tests with types and one for tests without:
205
-
206
- ```json
207
- "test": "ATTEST_skipTypes=1 vitest run",
208
- "testWithTypes": "vitest run",
209
- ```
210
-
211
- Our recommendation is to use `test` when:
212
-
213
- - Only wanting to test runtime logic during development
214
- - Running tests in watch mode or via VSCode's Test Explorer
215
-
216
- Use `testWithTypes` when:
217
-
218
- - You've made changes to your types and want to recheck your type-level assertions
219
- - You're running your tests in CI
220
-
221
- ### `typeToStringFormat`
222
-
223
- A set of [`prettier.Options`](https://prettier.io/docs/en/options.html) overrides that apply specifically `type.toString` formatting.
224
-
225
- Any options you provide will override the defaults, which are as follows:
226
-
227
- ```jsonc
228
- {
229
- "semi": false,
230
- // note this print width is optimized for type serialization, not general code
231
- "printWidth": 60,
232
- "trailingComma": "none",
233
- "parser": "typescript"
234
- }
235
- ```
236
-
237
- The easiest way to provide overrides is to the `setup` function, but they can also be provided as a JSON serialized string either passed to a `--typeToStringFormat` CLI flag or set as the value of `ATTEST_typeToStringFormat` on `process.env`.
238
-
239
- ## Benches
240
-
241
- Benches are run separately from tests and don't require any special setup. If the below file was `benches.ts`, you could run it using something like `tsx benches.ts` or `ts-node benches.ts`:
242
-
243
- ```ts
244
- // Combinatorial template literals often result in expensive types- let's benchmark this one!
245
- type makeComplexType<s extends string> =
246
- s extends `${infer head}${infer tail}` ? head | tail | makeComplexType<tail>
247
- : s
248
-
249
- bench("bench type", () => {
250
- return {} as makeComplexType<"defenestration">
251
- // This is an inline snapshot that will be populated or compared when you run the file
252
- }).types([169, "instantiations"])
253
-
254
- bench(
255
- "bench runtime and type",
256
- () => {
257
- return {} as makeComplexType<"antidisestablishmentarianism">
258
- },
259
- fakeCallOptions
260
- )
261
- // Average time it takes the function execute
262
- .mean([2, "ms"])
263
- // Seems like our type is O(n) with respect to the length of the input- not bad!
264
- .types([337, "instantiations"])
265
- ```
266
-
267
- If you're benchmarking an API, you'll need to include a "baseline expression" so that instantiations created when your API is initially invoked don't add noise to the individual tests.
268
-
269
- Here's an example of what that looks like:
270
-
271
- ```ts
272
- import { bench } from "@ark/attest"
273
- import { type } from "arktype"
274
-
275
- // baseline expression
276
- type("boolean")
277
-
278
- bench("single-quoted", () => {
279
- const _ = type("'nineteen characters'")
280
- // would be 2697 without baseline
281
- }).types([610, "instantiations"])
282
-
283
- bench("keyword", () => {
284
- const _ = type("string")
285
- // would be 2507 without baseline
286
- }).types([356, "instantiations"])
287
- ```
288
-
289
- > [!WARNING]
290
- > Be sure your baseline expression is not identical to an expression you are using in any of your benchmarks. If it is, the individual benchmarks will reuse its cached types, leading to reduced (or 0) instantiations.
291
-
292
- If you'd like to fail in CI above a threshold, you can add flags like the following (default value is 20%, but it will not throw unless `--benchErrorOnThresholdExceeded` is set):
293
-
294
- ```
295
- tsx ./p99/within-limit/p99-tall-simple.bench.ts --benchErrorOnThresholdExceeded --benchPercentThreshold 10
296
- ```
297
-
298
- ## CLI
299
-
300
- Attest also includes a built-in `attest` CLI including the following commands:
301
-
302
- ### `stats`
303
-
304
- ```bash
305
- npm run attest stats packages/*
306
- ```
307
-
308
- Summarizes key type performance metrics for each package (check time, instantiations, and type count).
309
-
310
- Expects any number of args representing package directories to check, optionally specified using glob patterns like `packages/*`.
311
-
312
- If no directories are provided, defaults to CWD.
313
-
314
- ### `trace`
315
-
316
- ```bash
317
- npm run attest trace .
318
- ```
319
-
320
- Creates a trace.json file in `.attest/trace` that can be viewed as a type performance heat map via a tool like https://ui.perfetto.dev/. Also summarizes any hot spots as identified by `@typescript/analyze-trace`.
321
-
322
- Trace expects a single argument representing the root directory of the root package for which to gather type information.
323
-
324
- ## Integration
325
-
326
- ### Setup
327
-
328
- If you're a library author wanting to integrate type into your own assertions instead of using the `attest` API, you'll need to call `setup` with a list of `attestAliases` to ensure type data is collected from your own functions:
329
-
330
- ```ts
331
- // attest will only collect type data from functions with names listed in `attestAliases`
332
- setup({ attestAliases: ["yourCustomAssert"] })
333
-
334
- // There are many other config options, but some are primarily internal- use others at your own risk!
335
- ```
336
-
337
- You'll need to make sure that setup with whatever aliases you need before the first test runs. As part of the setup process, attest will search for the specified assertion calls and cache their types in a temporary file that will be referenced during test execution.
338
-
339
- This ensures that type assertions can be made across processes without creating a new TSServer instance for each.
340
-
341
- ### TS Versions
342
-
343
- Attest analyzes your project with whichever version of `typescript` is installed. To test multiple versions, run your suite once per version, e.g. via a CI matrix that installs each version before running tests.
344
-
345
- TypeScript 7.1+ is supported via its native API. Type assertions, completions, JSDoc, benches and the CLI work the same way, with a few differences:
346
-
347
- - Instantiation counts are measured by running `tsc --extendedDiagnostics --singleThreaded` per bench. Since `tsc` fully checks the bench's dependencies before measuring it, work a bench shares with them isn't attributed to the bench, so counts run lower than with TypeScript 5/6, by as much as most of the count for a bench whose cost is mostly shared with its dependencies, and baselines should be recorded separately.
348
- - Type strings, union ordering and error elaboration can differ from earlier versions, so snapshots may need to be updated when switching.
349
- - Benches write temporary copies beside their source files while measuring, so they need a writable source directory.
350
-
351
- ### APIs
352
-
353
- The most flexible attest APIs are `getTypeAssertionAtPosition` and `caller`.
354
-
355
- Here's an example of how you might use them in your own API:
356
-
357
- ```ts
358
- import { getTypeAssertionAtPosition, caller } from "@ark/attest"
359
-
360
- const yourCustomAssert = <expectedType>(actualValue: expectedType) => {
361
- const position = caller()
362
- const types = getTypeAssertionAtPosition(position)
363
- // assert that the type of actualValue is the same as the type of expectedType
364
- const relationship = types.args[0].relationships.typeArgs[0]
365
- if (relationship === undefined) {
366
- throw new Error(
367
- `yourCustomAssert requires a type arg representing the expected type, e.g. 'yourCustomAssert<"foo">("foo")'`
368
- )
369
- }
370
- if (relationship !== "equality") {
371
- throw new Error(
372
- `Expected ${types.typeArgs[0].type}, got ${types.args[0].type} with relationship ${relationship}`
373
- )
374
- }
375
- }
376
- ```
377
-
378
- A user might then use `yourCustomAssert` like this:
379
-
380
- ```ts
381
- import { yourCustomAssert } from "your-package"
382
-
383
- test("my code", () => {
384
- // Ok
385
- yourCustomAssert<"foo">(`${"f"}oo` as const)
386
- // Error: `Expected boolean, got true with relationship subtype`
387
- yourCustomAssert<boolean>(true)
388
- // Error: `Expected 5, got number with relationship supertype`
389
- yourCustomAssert<5>(2 + 3)
390
- })
391
- ```
392
-
393
- Please don't hesitate to 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! ⛵
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! ⛵
package/out/cache/ts.js CHANGED
@@ -5,6 +5,7 @@ import { readFileSync } from "node:fs";
5
5
  import { resolve, dirname, join } from "node:path";
6
6
  import ts from "typescript";
7
7
  import { getConfig } from "../config.js";
8
+ import { narrowToNamedTestFiles } from "../utils.js";
8
9
  export class TsServer {
9
10
  rootFiles;
10
11
  virtualEnv;
@@ -21,14 +22,14 @@ export class TsServer {
21
22
  const tsLibPaths = getTsLibFiles(this.tsConfigInfo.parsed.options);
22
23
  // TS represents windows paths as `C:/Users/ssalb/...`
23
24
  const normalizedCwd = fromCwd().replace(/\\/g, "/");
24
- this.rootFiles = this.tsConfigInfo.parsed.fileNames.filter(path => {
25
+ this.rootFiles = narrowToNamedTestFiles(this.tsConfigInfo.parsed.fileNames.filter(path => {
25
26
  if (!path.startsWith(normalizedCwd))
26
27
  return;
27
28
  // exclude empty files as they lead to a crash
28
29
  // when createVirtualTypeScriptEnvironment is called
29
30
  const contents = readFile(path).trim();
30
31
  return contents !== "";
31
- });
32
+ }));
32
33
  const system = tsvfs.createFSBackedSystem(tsLibPaths.defaultMapFromNodeModules, this.tsConfigInfo.path ? dirname(this.tsConfigInfo.path) : fromCwd(), ts);
33
34
  this.virtualEnv = tsvfs.createVirtualTypeScriptEnvironment(system, this.rootFiles, ts, this.tsConfigInfo.parsed.options);
34
35
  this.program = this.virtualEnv.languageService.getProgram();
package/out/config.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type JsonObject } from "@ark/util";
2
2
  import type * as prettier from "prettier";
3
+ /** tsjs is TypeScript's JS API, tsgo its native port and tsrs a Rust port */
4
+ export type Checker = "tsjs" | "tsgo" | "tsrs";
3
5
  export type BenchErrorConfig = "runtime" | "types" | boolean;
4
6
  type BaseAttestConfig = {
5
7
  tsconfig: string | null | undefined;
@@ -9,6 +11,14 @@ type BaseAttestConfig = {
9
11
  failOnMissingSnapshots: boolean;
10
12
  skipTypes: boolean;
11
13
  skipInlineInstantiations: boolean;
14
+ /**
15
+ * the type checker to analyze assertions with, defaulting to tsrs if its
16
+ * binary is installed alongside TypeScript 7, else tsgo for TypeScript 7,
17
+ * else tsjs
18
+ */
19
+ checker: Checker | undefined;
20
+ /** analyze only the test files named on the command line */
21
+ onlyNamedTestFiles: boolean;
12
22
  attestAliases: string[];
13
23
  benchPercentThreshold: number;
14
24
  benchErrorOnThresholdExceeded: BenchErrorConfig;
package/out/config.js CHANGED
@@ -10,6 +10,8 @@ export const getDefaultAttestConfig = () => ({
10
10
  updateSnapshots: false,
11
11
  skipTypes: false,
12
12
  skipInlineInstantiations: false,
13
+ checker: undefined,
14
+ onlyNamedTestFiles: false,
13
15
  benchPercentThreshold: 20,
14
16
  benchErrorOnThresholdExceeded: true,
15
17
  filter: undefined,
package/out/fixtures.js CHANGED
@@ -4,7 +4,7 @@ import { writeSnapshotUpdatesOnExit } from "./cache/snapshots.js";
4
4
  import { analyzeProjectAssertions } from "./cache/writeAssertionCache.js";
5
5
  import { ensureCacheDirs, getConfig } from "./config.js";
6
6
  import { analyzeProjectAssertions as analyzeProjectAssertionsTs7 } from "./ts7/analyze.js";
7
- import { isTs7 } from "./utils.js";
7
+ import { getChecker } from "./ts7/server.js";
8
8
  export const setup = (options) => {
9
9
  const { ...config } = getConfig();
10
10
  if (options)
@@ -19,7 +19,9 @@ export const setup = (options) => {
19
19
  };
20
20
  export const writeAssertionData = (toPath) => {
21
21
  console.log("⏳ Waiting for TypeScript to check your project (this may take a while)...");
22
- writeJson(toPath, isTs7 ? analyzeProjectAssertionsTs7() : analyzeProjectAssertions());
22
+ writeJson(toPath, getChecker() === "tsjs" ?
23
+ analyzeProjectAssertions()
24
+ : analyzeProjectAssertionsTs7());
23
25
  };
24
26
  export const cleanup = () => writeSnapshotUpdatesOnExit();
25
27
  /** alias for cleanup to align with vitest and others */
@@ -2,7 +2,7 @@ import { flatMorph, throwInternalError } from "@ark/util";
2
2
  import { getConfig } from "../config.js";
3
3
  import { getFileKey } from "../utils.js";
4
4
  import { getInstantiationsContributedByNodes } from "./instantiations.js";
5
- import { TsgoServer, ast, getAncestors, getCallExpressionsByName, getCallLocation, getDescendants, getFirstFunctionDescendant, noTruncation } from "./server.js";
5
+ import { TsgoServer, ast, getAncestors, getCallExpressionsByName, getCallLocation, getDescendants, getFirstFunctionDescendant, getNoTruncation } from "./server.js";
6
6
  export const analyzeProjectAssertions = () => {
7
7
  const config = getConfig();
8
8
  const server = TsgoServer.instance;
@@ -46,7 +46,7 @@ export const stringifyTypeAtLocation = (node) => {
46
46
  const type = checker.getTypeAtLocation(node);
47
47
  let string = checker.typeToString(type);
48
48
  if (string.includes("...")) {
49
- const nonTruncated = checker.typeToString(type, undefined, noTruncation);
49
+ const nonTruncated = checker.typeToString(type, undefined, getNoTruncation());
50
50
  string =
51
51
  nonTruncated.includes(" any") && !string.includes(" any") ?
52
52
  nonTruncated.replace(/ any/g, " cyclic")
@@ -4,7 +4,7 @@ import { basename, dirname, extname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { isPositionWithinRange } from "../cache/getCachedAssertions.js";
6
6
  import { getConfig } from "../config.js";
7
- import { TsgoServer, ast, getCallExpressionsByName, getCallLocation, getFirstFunctionDescendant, tempId, tscPath } from "./server.js";
7
+ import { TsgoServer, ast, getCallExpressionsByName, getCallLocation, getFirstFunctionDescendant, tempId, getTscPath } from "./server.js";
8
8
  const countInstantiationsScript = fileURLToPath(new URL(`./countInstantiations${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
9
9
  /**
10
10
  * tsgo's API doesn't expose instantiation counts, so each block is checked by
@@ -57,7 +57,7 @@ export const getInstantiationsContributedByNodes = (file, blocks) => {
57
57
  });
58
58
  return configPath;
59
59
  });
60
- const [baseline, ...counts] = JSON.parse(execFileSync(process.execPath, [countInstantiationsScript, tscPath], {
60
+ const [baseline, ...counts] = JSON.parse(execFileSync(process.execPath, [countInstantiationsScript, getTscPath()], {
61
61
  input: JSON.stringify({ files, configPaths }),
62
62
  encoding: "utf8",
63
63
  maxBuffer: 1e8
@@ -1,10 +1,14 @@
1
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";
2
+ import type * as tsgoAst from "typescript/ast";
3
+ import type * as tsgoApi from "typescript/sync";
4
4
  import type { LinePositionRange } from "../cache/getCachedAssertions.ts";
5
+ import { type Checker } from "../config.ts";
6
+ /** the checker from attest's config, or the best one installed */
7
+ export declare const getChecker: () => Checker;
8
+ /** populated on first use, after setup() has written attest's config */
5
9
  export declare const ast: typeof tsgoAst;
6
- export declare const noTruncation: number;
7
- export declare const tscPath: string;
10
+ export declare const getNoTruncation: () => number;
11
+ export declare const getTscPath: () => string;
8
12
  export declare const tempId: string;
9
13
  export type Node = tsgoAst.Node;
10
14
  export type SourceFile = tsgoAst.SourceFile;
package/out/ts7/server.js CHANGED
@@ -6,15 +6,64 @@ import { dirname, join, resolve } from "node:path";
6
6
  import { threadId } from "node:worker_threads";
7
7
  import ts from "typescript";
8
8
  import { getConfig } from "../config.js";
9
- import { isTs7 } from "../utils.js";
9
+ import { isTs7, narrowToNamedTestFiles } from "../utils.js";
10
10
  // resolved relative to attest so the API matches the installed typescript
11
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");
12
+ const isResolvable = (require, specifier) => {
13
+ try {
14
+ require.resolve(specifier);
15
+ return true;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ };
21
+ // tsrs's binary ships in a per-platform optional dependency, so it installs
22
+ // without one on unsupported platforms like Windows
23
+ const hasTsrsBinary = () => {
24
+ if (!isResolvable(requireTypeScript, "tsrs/package.json"))
25
+ return false;
26
+ if (process.env.TSRS_BINARY)
27
+ return true;
28
+ const packagePath = requireTypeScript.resolve("tsrs/package.json");
29
+ const requireTsrs = createRequire(packagePath);
30
+ const { optionalDependencies = {} } = requireTsrs(packagePath);
31
+ return Object.keys(optionalDependencies).some(name => isResolvable(requireTsrs, `${name}/package.json`));
32
+ };
33
+ /** the checker from attest's config, or the best one installed */
34
+ export const getChecker = () => {
35
+ const { checker } = getConfig();
36
+ if (checker === undefined) {
37
+ return (!isTs7 ? "tsjs"
38
+ : hasTsrsBinary() ? "tsrs"
39
+ : "tsgo");
40
+ }
41
+ if (checker !== "tsjs" && checker !== "tsgo" && checker !== "tsrs")
42
+ throwError(`checker must be "tsjs", "tsgo" or "tsrs" (was "${checker}")`);
43
+ if ((checker === "tsjs") === isTs7) {
44
+ throwError(`checker "${checker}" requires TypeScript ${checker === "tsjs" ? "<7" : "7+"} (found ${ts.version})`);
45
+ }
46
+ return checker;
47
+ };
48
+ let compiler;
49
+ /** populated on first use, after setup() has written attest's config */
50
+ export const ast = {};
51
+ // tsrs serves the same API as tsgo, so it only changes where it's loaded from
52
+ const loadCompiler = () => {
53
+ if (compiler)
54
+ return compiler;
55
+ const name = getChecker() === "tsrs" ? "tsrs" : "typescript";
56
+ // tsrs still exports the API from tsgo's previous unstable/ subpaths
57
+ const entry = name === "tsrs" ? "tsrs/unstable" : "typescript";
58
+ Object.assign(ast, requireTypeScript(`${entry}/ast`));
59
+ return (compiler = {
60
+ ...requireTypeScript(`${entry}/sync`),
61
+ ...requireTypeScript(`${entry}/fs`),
62
+ tscPath: join(dirname(requireTypeScript.resolve(`${name}/package.json`)), "bin", name === "tsrs" ? "tsrs" : "tsc")
63
+ });
64
+ };
65
+ export const getNoTruncation = () => loadCompiler().TypeFormatFlags.NoTruncation;
66
+ export const getTscPath = () => loadCompiler().tscPath;
18
67
  // unique to this thread, since worker threads share a pid
19
68
  export const tempId = `${process.pid}-${threadId}`;
20
69
  export class TsgoServer {
@@ -32,9 +81,9 @@ export class TsgoServer {
32
81
  return (TsgoServer._instance ??= new TsgoServer());
33
82
  }
34
83
  constructor() {
35
- if (ts.version.startsWith("7.0."))
84
+ if (getChecker() === "tsgo" && ts.version.startsWith("7.0."))
36
85
  throwError(`@ark/attest requires TypeScript 7.1+ (found ${ts.version})`);
37
- this.api = new API({ cwd: fromCwd() });
86
+ this.api = new (loadCompiler().API)({ cwd: fromCwd() });
38
87
  this.projectConfig = getProjectConfig();
39
88
  // only exists in tsgo's view of the filesystem, so nothing is written
40
89
  this.configPath = join(this.projectConfig.dir, ".attest.tsconfig.json");
@@ -47,7 +96,7 @@ export class TsgoServer {
47
96
  if (configErrors.length)
48
97
  throwError(configErrors.map(error => error.text).join("\n"));
49
98
  const normalizedCwd = fromCwd().replace(/\\/g, "/");
50
- this.rootFiles = this.project.parsedCommandLine.fileNames.filter(path => path.startsWith(normalizedCwd));
99
+ this.rootFiles = narrowToNamedTestFiles(this.project.parsedCommandLine.fileNames.filter(path => path.startsWith(normalizedCwd)));
51
100
  }
52
101
  /**
53
102
  * tsgo only reports diagnostics after applying @ts-expect-error and
@@ -89,7 +138,7 @@ export class TsgoServer {
89
138
  openProject(files = []) {
90
139
  const snapshot = this.api.createSnapshot({
91
140
  openProjects: [this.configPath],
92
- fileSystem: createFileSystemLayer([
141
+ fileSystem: loadCompiler().createFileSystemLayer([
93
142
  [this.configPath, this.config],
94
143
  ...files
95
144
  ])
package/out/utils.d.ts CHANGED
@@ -1,6 +1,21 @@
1
1
  /** TypeScript 7+ is native and only exposes its API via tsgo's IPC client */
2
2
  export declare const isTs7: boolean;
3
3
  export declare const getFileKey: (path: string) => string;
4
+ /**
5
+ * Narrows the files whose assertions are analyzed to the test files named on
6
+ * the command line, e.g. `pnpm testFiles ark/type/__tests__/brand.test.ts`,
7
+ * since those are the only tests that will run. Analysis cost scales with the
8
+ * files analyzed, so one file takes seconds where the whole project takes
9
+ * minutes. With no test file named, every root file is analyzed as before.
10
+ *
11
+ * Only applies with `--onlyNamedTestFiles`, which `testFiles` passes along with
12
+ * mocha's `--no-package`. Otherwise, mocha adds named files to the configured
13
+ * spec, so every test still runs.
14
+ *
15
+ * A test that runs without having been analyzed fails with "Found no assertion
16
+ * data", so a narrowing that missed a file can never pass silently.
17
+ */
18
+ export declare const narrowToNamedTestFiles: (rootFiles: string[]) => string[];
4
19
  /**
5
20
  * Can be used to allow arbitrarily chained property access and function calls.
6
21
  */
package/out/utils.js CHANGED
@@ -1,10 +1,39 @@
1
1
  import { caller } from "@ark/fs";
2
2
  import { throwError } from "@ark/util";
3
- import { basename, relative } from "node:path";
3
+ import { existsSync } from "node:fs";
4
+ import { basename, relative, resolve } from "node:path";
4
5
  import ts from "typescript";
6
+ import { getConfig } from "./config.js";
5
7
  /** TypeScript 7+ is native and only exposes its API via tsgo's IPC client */
6
8
  export const isTs7 = Number.parseInt(ts.version) >= 7;
7
9
  export const getFileKey = (path) => relative(".", path);
10
+ const testFilePattern = /\.test\.[cm]?[jt]sx?$/;
11
+ /**
12
+ * Narrows the files whose assertions are analyzed to the test files named on
13
+ * the command line, e.g. `pnpm testFiles ark/type/__tests__/brand.test.ts`,
14
+ * since those are the only tests that will run. Analysis cost scales with the
15
+ * files analyzed, so one file takes seconds where the whole project takes
16
+ * minutes. With no test file named, every root file is analyzed as before.
17
+ *
18
+ * Only applies with `--onlyNamedTestFiles`, which `testFiles` passes along with
19
+ * mocha's `--no-package`. Otherwise, mocha adds named files to the configured
20
+ * spec, so every test still runs.
21
+ *
22
+ * A test that runs without having been analyzed fails with "Found no assertion
23
+ * data", so a narrowing that missed a file can never pass silently.
24
+ */
25
+ export const narrowToNamedTestFiles = (rootFiles) => {
26
+ if (!getConfig().onlyNamedTestFiles)
27
+ return rootFiles;
28
+ const named = new Set(process.argv
29
+ .slice(2)
30
+ .filter(arg => testFilePattern.test(arg) && existsSync(arg))
31
+ .map(arg => resolve(arg).replace(/\\/g, "/")));
32
+ if (!named.size)
33
+ return rootFiles;
34
+ const narrowed = rootFiles.filter(path => named.has(path));
35
+ return narrowed.length ? narrowed : rootFiles;
36
+ };
8
37
  /**
9
38
  * Can be used to allow arbitrarily chained property access and function calls.
10
39
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ark/attest",
3
- "version": "0.57.0",
3
+ "version": "0.58.0",
4
4
  "license": "MIT",
5
5
  "author": {
6
6
  "name": "David Blass",
@@ -40,18 +40,25 @@
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.7",
44
- "@ark/util": "0.56.7",
45
- "@ark/schema": "0.56.7",
46
- "arktype": "2.2.8"
43
+ "@ark/fs": "0.56.8",
44
+ "@ark/schema": "0.56.8",
45
+ "arktype": "2.2.9",
46
+ "@ark/util": "0.56.8"
47
47
  },
48
48
  "devDependencies": {
49
- "typescript": "7.1.0-dev.20261006.1",
49
+ "tsrs": "0.18.0-ts7.1.0-dev.20260929",
50
+ "typescript": "7.1.0-beta",
50
51
  "typescript-6": "npm:typescript@6.0.3",
51
- "typescript-7": "npm:typescript@7.1.0-dev.20261006.1"
52
+ "typescript-7": "npm:typescript@7.1.0-beta"
52
53
  },
53
54
  "peerDependencies": {
54
- "typescript": "*"
55
+ "typescript": "*",
56
+ "tsrs": "*"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "tsrs": {
60
+ "optional": true
61
+ }
55
62
  },
56
63
  "publishConfig": {
57
64
  "access": "public"