@ark/attest 0.10.2 → 0.11.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
@@ -37,7 +37,7 @@ export default defineConfig({
37
37
  `setupVitest.ts`
38
38
 
39
39
  ```ts
40
- import { setup, teardown } from "@ark/attest"
40
+ import { setup } from "@ark/attest"
41
41
 
42
42
  // config options can be passed here
43
43
  export default () => setup({})
@@ -140,6 +140,88 @@ describe("attest features", () => {
140
140
  })
141
141
  ```
142
142
 
143
+ ## Options
144
+
145
+ Options can be specified in one of 3 ways:
146
+
147
+ - An argument passed to your test process, e.g. `--skipTypes` or `--benchPercentThreshold 10`
148
+ - An environment variable with an `ATTEST_` prefix, e.g. `ATTEST_skipTypes=1` or `ATTEST_benchPercentThreshold=10`
149
+ - Passed as an option to attest's `setup` function, e.g.:
150
+
151
+ `setupVitest.ts`
152
+
153
+ ```ts
154
+ import * as attest from "@ark/attest"
155
+
156
+ export const setup = () =>
157
+ attest.setup({
158
+ skipTypes: true,
159
+ benchPercentThreshold: 10
160
+ })
161
+ ```
162
+
163
+ Here are the current defaults for all available options. Please note, some of these are experimental and subject to change:
164
+
165
+ ```ts
166
+ export const getDefaultAttestConfig = (): BaseAttestConfig => ({
167
+ tsconfig:
168
+ existsSync(fromCwd("tsconfig.json")) ? fromCwd("tsconfig.json") : undefined,
169
+ attestAliases: ["attest", "attestInternal"],
170
+ updateSnapshots: false,
171
+ skipTypes: false,
172
+ skipInlineInstantiations: false,
173
+ tsVersions: "typescript",
174
+ benchPercentThreshold: 20,
175
+ benchErrorOnThresholdExceeded: true,
176
+ filter: undefined,
177
+ testDeclarationAliases: ["bench", "it", "test"],
178
+ formatter: `npm exec --no -- prettier --write`,
179
+ shouldFormat: true,
180
+ typeToStringFormat: {}
181
+ })
182
+ ```
183
+
184
+ ### `skipTypes`
185
+
186
+ `skipTypes` is extremely useful for iterating quickly during development without having to typecheck your project to test runtime logic.
187
+
188
+ When this setting is enabled, setup will skip typechecking and all assertions requiring type information will be skipped.
189
+
190
+ You likely want two scripts, one for running tests with types and one for tests without:
191
+
192
+ ```json
193
+ "test": "ATTEST_skipTypes=1 vitest run",
194
+ "testWithTypes": "vitest run",
195
+ ```
196
+
197
+ Our recommendation is to use `test` when:
198
+
199
+ - Only wanting to test runtime logic during development
200
+ - Running tests in watch mode or via VSCode's Test Explorer
201
+
202
+ Use `testWithTypes` when:
203
+
204
+ - You've made changes to your types and want to recheck your type-level assertions
205
+ - You're running your tests in CI
206
+
207
+ ### `typeToStringFormat`
208
+
209
+ A set of [`prettier.Options`](https://prettier.io/docs/en/options.html) overrides that apply specifically `type.toString` formatting.
210
+
211
+ Any options you provide will override the defaults, which are as follows:
212
+
213
+ ```jsonc
214
+ {
215
+ "semi": false,
216
+ // note this print width is optimized for type serialization, not general code
217
+ "printWidth": 60,
218
+ "trailingComma": "none",
219
+ "parser": "typescript"
220
+ }
221
+ ```
222
+
223
+ 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`.
224
+
143
225
  ## Benches
144
226
 
145
227
  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`:
@@ -221,7 +303,7 @@ If no directories are provided, defaults to CWD.
221
303
  npm run attest trace .
222
304
  ```
223
305
 
224
- Creates a trace.json file in a .tstrace directory 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`.
306
+ 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`.
225
307
 
226
308
  Trace expects a single argument representing the root directory of the root package for which to gather type information.
227
309
 
@@ -18,6 +18,7 @@ export declare class TypeAssertionMapping {
18
18
  }
19
19
  export declare const versionableAssertion: (fn: AssertFn) => AssertFn;
20
20
  export declare const assertEquals: AssertFn;
21
+ export declare const assertSatisfies: AssertFn;
21
22
  export declare const typeEqualityMapping: TypeAssertionMapping;
22
23
  export declare const assertEqualOrMatching: AssertFn;
23
24
  export type AssertedFnCallResult = {
@@ -59,6 +59,16 @@ const unversionedAssertEquals = (expected, actual, ctx) => {
59
59
  }
60
60
  };
61
61
  export const assertEquals = versionableAssertion(unversionedAssertEquals);
62
+ const unversionedAssertSatisfies = (t, data, ctx) => {
63
+ try {
64
+ t.assert(data);
65
+ }
66
+ catch (e) {
67
+ e.stack = ctx.assertionStack;
68
+ throw e;
69
+ }
70
+ };
71
+ export const assertSatisfies = versionableAssertion(unversionedAssertSatisfies);
62
72
  export const typeEqualityMapping = new TypeAssertionMapping(data => {
63
73
  const expected = data.typeArgs[0];
64
74
  const actual = data.typeArgs[1] ?? data.args[0];
@@ -5,10 +5,10 @@ import { type VersionedTypeAssertion } from "../cache/getCachedAssertions.js";
5
5
  import { type AttestConfig } from "../config.js";
6
6
  import { ChainableAssertions, type AssertionKind, type rootAssertions } from "./chainableAssertions.js";
7
7
  export type AttestFn = {
8
+ <expected>(actual: expected): rootAssertions<expected, AssertionKind>;
8
9
  <expected, actual extends expected = never>(...args: actual extends never ? [
9
10
  ErrorMessage<"Type-only assertion requires two explicit genreic params, e.g. attest<expected, actual>">
10
11
  ] : []): void;
11
- <expected>(actual: expected): rootAssertions<expected, AssertionKind>;
12
12
  instantiations: (count?: Measure<"instantiations"> | undefined) => void;
13
13
  };
14
14
  export type AssertionContext = {
@@ -58,7 +58,7 @@ export type TypeAssertionsRoot = {
58
58
  type: TypeAssertionProps;
59
59
  };
60
60
  export type TypeAssertionProps = {
61
- toString: valueFromTypeAssertion<string>;
61
+ toString: valueFromTypeAssertion<string | RegExp>;
62
62
  errors: valueFromTypeAssertion<string | RegExp, string>;
63
63
  completions: (value?: Completions) => void;
64
64
  };
@@ -5,7 +5,7 @@ import * as assert from "node:assert/strict";
5
5
  import { isDeepStrictEqual } from "node:util";
6
6
  import { getSnapshotByName, queueSnapshotUpdate, updateExternalSnapshot } from "../cache/snapshots.js";
7
7
  import { chainableNoOpProxy } from "../utils.js";
8
- import { TypeAssertionMapping, assertEqualOrMatching, assertEquals, callAssertedFunction, getThrownMessage, throwAssertionError } from "./assertions.js";
8
+ import { TypeAssertionMapping, assertEqualOrMatching, assertEquals, assertSatisfies, callAssertedFunction, getThrownMessage, throwAssertionError } from "./assertions.js";
9
9
  export class ChainableAssertions {
10
10
  ctx;
11
11
  constructor(ctx) {
@@ -41,7 +41,7 @@ export class ChainableAssertions {
41
41
  return this;
42
42
  }
43
43
  satisfies(def) {
44
- type(def).assert(def);
44
+ assertSatisfies(type.raw(def), this.ctx.actual, this.ctx);
45
45
  return this;
46
46
  }
47
47
  instanceOf(expected) {
@@ -155,6 +155,7 @@ export class ChainableAssertions {
155
155
  self.ctx.actual = new TypeAssertionMapping(data => ({
156
156
  actual: data.args[0].type
157
157
  }));
158
+ self.ctx.allowRegex = true;
158
159
  return self.immediateOrChained();
159
160
  },
160
161
  get errors() {
@@ -1,4 +1,3 @@
1
- import type { TypeRelationship } from "../cache/writeAssertionCache.js";
2
1
  import type { BenchContext } from "./bench.js";
3
2
  import { type Measure, type TypeUnit } from "./measure.js";
4
3
  export type BenchTypeAssertions = {
@@ -6,11 +5,4 @@ export type BenchTypeAssertions = {
6
5
  };
7
6
  export declare const createBenchTypeAssertion: (ctx: BenchContext) => BenchTypeAssertions;
8
7
  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
8
  export declare const instantiationDataHandler: (ctx: BenchContext, args?: Measure<TypeUnit>, isBenchFunction?: boolean) => void;
@@ -83,7 +83,9 @@ const writeCachedInlineSnapshotUpdates = () => {
83
83
  const snapshotArgsToQueuedUpdate = ({ position, serializedValue, snapFunctionName = "snap", baselinePath }) => {
84
84
  const snapCall = findCallExpressionAncestor(position, snapFunctionName);
85
85
  const newArgText = typeof serializedValue === "string" && serializedValue.includes("\n") ?
86
- "`" + serializedValue.replaceAll("`", "\\`") + "`"
86
+ "`" +
87
+ serializedValue.replaceAll("`", "\\`").replaceAll("${", "\\${") +
88
+ "`"
87
89
  : JSON.stringify(serializedValue);
88
90
  return {
89
91
  position,
@@ -110,7 +112,7 @@ export const writeUpdates = (queuedUpdates) => {
110
112
  runFormatterIfAvailable(queuedUpdates);
111
113
  };
112
114
  const runFormatterIfAvailable = (queuedUpdates) => {
113
- const { formatter, shouldFormat } = getConfig();
115
+ const { formatCmd: formatter, shouldFormat } = getConfig();
114
116
  if (!shouldFormat)
115
117
  return;
116
118
  try {
package/out/cache/ts.js CHANGED
@@ -44,9 +44,9 @@ export const nearestCallExpressionChild = (node, position) => {
44
44
  return result;
45
45
  };
46
46
  const nearestBoundingCallExpression = (node, position) => node.pos <= position && node.end >= position ?
47
- node
47
+ (node
48
48
  .getChildren()
49
- .flatMap(child => nearestBoundingCallExpression(child, position) ?? [])[0] ?? (ts.isCallExpression(node) ? node : undefined)
49
+ .flatMap(child => nearestBoundingCallExpression(child, position) ?? [])[0] ?? (ts.isCallExpression(node) ? node : undefined))
50
50
  : undefined;
51
51
  export const getAbsolutePosition = (file, position) => {
52
52
  const pos = ts.getPositionOfLineAndCharacter(file,
@@ -98,15 +98,17 @@ export const getProgram = (env) => env?.languageService.getProgram() ??
98
98
  TsServer.instance.virtualEnv.languageService.getProgram();
99
99
  export const getInternalTypeChecker = (env) => getProgram(env).getTypeChecker();
100
100
  const declarationPrefix = "type T = ";
101
- const typeFormatOptions = {
102
- parser: "typescript",
101
+ const baseTypeFormatOptions = {
103
102
  semi: false,
104
- useTabs: true,
105
103
  printWidth: 60,
106
- trailingComma: "none"
104
+ trailingComma: "none",
105
+ parser: "typescript"
107
106
  };
108
107
  const formatTypeString = (typeString) => prettier
109
- .format(`${declarationPrefix}${typeString}`, typeFormatOptions)
108
+ .format(`${declarationPrefix}${typeString}`, {
109
+ ...baseTypeFormatOptions,
110
+ ...getConfig().typeToStringFormat
111
+ })
110
112
  .slice(declarationPrefix.length)
111
113
  .trimEnd();
112
114
  const replaceKnownInvalidSyntax = (typeString) => {
package/out/cli/trace.js CHANGED
@@ -1,20 +1,21 @@
1
+ import { ensureDir } from "@ark/fs";
1
2
  import { execSync } from "child_process";
2
- import { existsSync } from "fs";
3
- import { join } from "path";
3
+ import { resolve } from "path";
4
+ import { getConfig } from "../config.js";
4
5
  import { baseDiagnosticTscCmd } from "./shared.js";
5
6
  export const trace = async (args) => {
6
7
  const packageDir = args[0] ?? process.cwd();
7
- if (!existsSync(packageDir)) {
8
- throw new Error(`trace requires an argument for an existing directory to trace, e.g. 'pnpm attest trace packages/api'`);
9
- }
8
+ const config = getConfig();
9
+ const traceDir = resolve(config.cacheDir, "trace");
10
+ ensureDir(traceDir);
10
11
  try {
11
12
  console.log(`⏳ Gathering type trace data for ${packageDir}...`);
12
13
  // These cache files have to be removed before any analysis is done otherwise
13
14
  // the results will be meaningless.
14
- // the .tstrace directory will contain a trace.json file and a types.json file.
15
+ // the .attest/trace directory will contain a trace.json file and a types.json file.
15
16
  // the trace.json file can be viewed via a tool like https://ui.perfetto.dev/
16
17
  // the types.json file can be used to associate IDs from the trace file with type aliases
17
- execSync(`${baseDiagnosticTscCmd} --generateTrace .tstrace`, {
18
+ execSync(`${baseDiagnosticTscCmd} --generateTrace ${traceDir}`, {
18
19
  cwd: packageDir,
19
20
  stdio: "inherit"
20
21
  });
@@ -28,7 +29,7 @@ export const trace = async (args) => {
28
29
  process.argv = [
29
30
  "node",
30
31
  "node_modules/@typescript/analyze-trace/dist/analyze-trace-dir.js",
31
- join(packageDir, ".tstrace")
32
+ traceDir
32
33
  ];
33
34
  // TypeScript's analyze-trace tool can be used to automatically detect hot-spots in your code.
34
35
  // It's not a perfect match for what can be optimized, but it can be a helpful place to start
package/out/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type autocomplete } from "@ark/util";
2
+ import type * as prettier from "prettier";
2
3
  import { type TsVersionData } from "./tsVersioning.js";
3
4
  export type TsVersionAliases = autocomplete<"*"> | string[];
4
5
  type BaseAttestConfig = {
@@ -25,8 +26,19 @@ type BaseAttestConfig = {
25
26
  benchErrorOnThresholdExceeded: boolean;
26
27
  filter: string | undefined;
27
28
  testDeclarationAliases: string[];
28
- formatter: string;
29
+ formatCmd: string;
29
30
  shouldFormat: boolean;
31
+ /**
32
+ * Provided options will override the following defaults.
33
+ * Any options not listed will fallback to Prettier's default value.
34
+ *
35
+ * {
36
+ * semi: false,
37
+ * printWidth: 60,
38
+ * trailingComma: "none",
39
+ * }
40
+ */
41
+ typeToStringFormat: prettier.Options;
30
42
  };
31
43
  export type AttestConfig = Partial<BaseAttestConfig>;
32
44
  export declare const getDefaultAttestConfig: () => BaseAttestConfig;
package/out/config.js CHANGED
@@ -14,8 +14,9 @@ export const getDefaultAttestConfig = () => ({
14
14
  benchErrorOnThresholdExceeded: true,
15
15
  filter: undefined,
16
16
  testDeclarationAliases: ["bench", "it", "test"],
17
- formatter: `npm exec --no -- prettier --write`,
18
- shouldFormat: true
17
+ formatCmd: `npm exec --no -- prettier --write`,
18
+ shouldFormat: true,
19
+ typeToStringFormat: {}
19
20
  });
20
21
  const hasFlag = (flag) => process.argv.some(arg => arg.includes(flag));
21
22
  const getParamValue = (param) => {
@@ -31,6 +32,8 @@ const getParamValue = (param) => {
31
32
  return tryParseNumber(raw, { errorOnFail: true });
32
33
  if (param === "tsVersions" || param === "attestAliases")
33
34
  return raw.split(",");
35
+ if (param === "typeToStringFormat")
36
+ return JSON.parse(raw);
34
37
  return raw;
35
38
  };
36
39
  export const attestEnvPrefix = "ATTEST_";
@@ -86,9 +89,10 @@ const parseTsVersions = (aliases) => {
86
89
  return matching;
87
90
  });
88
91
  };
89
- const cachedConfig = parseConfig();
90
- export const getConfig = () => cachedConfig;
92
+ let cachedConfig;
93
+ export const getConfig = () => parseConfig();
91
94
  export const ensureCacheDirs = () => {
95
+ cachedConfig ??= getConfig();
92
96
  ensureDir(cachedConfig.cacheDir);
93
97
  ensureDir(cachedConfig.assertionCacheDir);
94
98
  };
package/out/fixtures.js CHANGED
@@ -5,9 +5,12 @@ import { writeSnapshotUpdatesOnExit } from "./cache/snapshots.js";
5
5
  import { analyzeProjectAssertions } from "./cache/writeAssertionCache.js";
6
6
  import { ensureCacheDirs, getConfig } from "./config.js";
7
7
  import { forTypeScriptVersions } from "./tsVersioning.js";
8
- export const setup = (options = {}) => {
8
+ export const setup = (options) => {
9
+ if (options) {
10
+ const existing = process.env.ATTEST_CONFIG ? JSON.parse(process.env.ATTEST_CONFIG) : {};
11
+ process.env.ATTEST_CONFIG = JSON.stringify(Object.assign(existing, options));
12
+ }
9
13
  const config = getConfig();
10
- Object.assign(config, options);
11
14
  rmSync(config.cacheDir, { recursive: true, force: true });
12
15
  ensureCacheDirs();
13
16
  if (config.skipTypes)
package/out/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
+ export { cleanup, setup, teardown, writeAssertionData } from "./fixtures.js";
1
2
  export { caller, type CallerOfOptions } from "@ark/fs";
2
3
  export { attest } from "./assert/attest.js";
3
4
  export { bench } from "./bench/bench.js";
4
5
  export { getBenchAssertionsAtPosition, getTypeAssertionsAtPosition } from "./cache/getCachedAssertions.js";
5
6
  export type { ArgAssertionData, LinePositionRange, TypeAssertionData, TypeRelationship } from "./cache/writeAssertionCache.js";
6
7
  export { getDefaultAttestConfig, type AttestConfig } from "./config.js";
7
- export { cleanup, setup, teardown, writeAssertionData } from "./fixtures.js";
8
8
  export { findAttestTypeScriptVersions, getPrimaryTsVersionUnderTest } from "./tsVersioning.js";
9
9
  export { contextualize } from "./utils.js";
package/out/index.js CHANGED
@@ -1,8 +1,9 @@
1
+ export { cleanup, setup, teardown, writeAssertionData } from "./fixtures.js";
2
+ // ensure fixtures are exported before config so additional settings can load
1
3
  export { caller } from "@ark/fs";
2
4
  export { attest } from "./assert/attest.js";
3
5
  export { bench } from "./bench/bench.js";
4
6
  export { getBenchAssertionsAtPosition, getTypeAssertionsAtPosition } from "./cache/getCachedAssertions.js";
5
7
  export { getDefaultAttestConfig } from "./config.js";
6
- export { cleanup, setup, teardown, writeAssertionData } from "./fixtures.js";
7
8
  export { findAttestTypeScriptVersions, getPrimaryTsVersionUnderTest } from "./tsVersioning.js";
8
9
  export { contextualize } from "./utils.js";
@@ -1,4 +1,4 @@
1
- import { findPackageRoot, fsRoot, readJson } from "@ark/fs";
1
+ import { assertPackageRoot, fsRoot, readJson } from "@ark/fs";
2
2
  import { existsSync, renameSync, symlinkSync, unlinkSync } from "fs";
3
3
  import { dirname } from "path";
4
4
  import { join } from "path/posix";
@@ -20,7 +20,7 @@ import ts from "typescript";
20
20
  export const forTypeScriptVersions = (versions, fn) => {
21
21
  const passedVersions = [];
22
22
  const failedVersions = [];
23
- const nodeModules = join(findPackageRoot(process.cwd()), "node_modules");
23
+ const nodeModules = join(assertPackageRoot(process.cwd()), "node_modules");
24
24
  const tsPrimaryPath = join(nodeModules, "typescript");
25
25
  const tsTemporaryPath = join(nodeModules, "typescript-temp");
26
26
  if (existsSync(tsPrimaryPath))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ark/attest",
3
- "version": "0.10.2",
3
+ "version": "0.11.0",
4
4
  "author": {
5
5
  "name": "David Blass",
6
6
  "email": "david@arktype.io",
@@ -29,9 +29,9 @@
29
29
  "@typescript/analyze-trace": "0.10.1",
30
30
  "prettier": "3.3.3",
31
31
  "@prettier/sync": "0.5.2",
32
- "arktype": "2.0.0-beta.2",
33
- "@ark/fs": "0.1.2",
34
- "@ark/util": "0.1.2"
32
+ "@ark/util": "0.2.0",
33
+ "@ark/fs": "0.2.0",
34
+ "arktype": "2.0.0-beta.3"
35
35
  },
36
36
  "devDependencies": {
37
37
  "typescript": "5.5.4"