@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
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2023 ArkType
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,284 @@
1
+ # Attest
2
+
3
+ Attest is a testing library that makes your TypeScript types available at runtime, giving you access to precise type-level assertions and performance benchmarks.
4
+
5
+ Assertions are framework agnostic and can be seamlessly integrated with your existing Vitest, Jest, or Mocha tests.
6
+
7
+ Benchmarks can run from anywhere and will deterministically report the number of type instantiations contributed by the contents of the `bench` call.
8
+
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
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install @ark/attest
15
+ ```
16
+
17
+ _Note: This package is still in alpha! Your feedback will help us iterate toward a stable 1.0._
18
+
19
+ ## Setup
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.
22
+
23
+ ### Vitest
24
+
25
+ `vitest.config.ts`
26
+
27
+ ```ts
28
+ import { defineConfig } from "vitest/config"
29
+
30
+ export default defineConfig({
31
+ test: {
32
+ globalSetup: ["setupVitest.ts"]
33
+ }
34
+ })
35
+ ```
36
+
37
+ `setupVitest.ts`
38
+
39
+ ```ts
40
+ import { setup, teardown } from "@ark/attest"
41
+
42
+ // config options can be passed here
43
+ export default () => setup({})
44
+ ```
45
+
46
+ ### Mocha
47
+
48
+ `package.json`
49
+
50
+ ```json
51
+ "mocha": {
52
+ "require": "./setupMocha.ts"
53
+ }
54
+ ```
55
+
56
+ `setupMocha.ts`
57
+
58
+ ```ts
59
+ import { setup, teardown } from "@ark/attest"
60
+
61
+ // config options can be passed here
62
+ export const mochaGlobalSetup = () => setup({})
63
+
64
+ export const mochaGlobalTeardown = teardown
65
+ ```
66
+
67
+ You should also add `.attest` to your repository's `.gitignore` file.
68
+
69
+ Bun support is currently pending a [bug in the way their source maps translate to stack traces](https://github.com/oven-sh/bun/issues/7120). If this is a problem for you, please 👍 that issue so they prioritize it!
70
+
71
+ ## Assertions
72
+
73
+ Here are some simple examples of type assertions and snapshotting:
74
+
75
+ ```ts
76
+ // @ark/attest assertions can be made from any unit test framework with a global setup/teardown
77
+ describe("attest features", () => {
78
+ it("type and value assertions", () => {
79
+ const even = type("number%2")
80
+ // asserts even.infer is exactly number
81
+ attest<number>(even.infer)
82
+ // make assertions about types and values seamlessly
83
+ attest(even.infer).type.toString.snap("number")
84
+ // including object literals- no more long inline strings!
85
+ attest(even.json).snap({
86
+ intersection: [{ domain: "number" }, { divisor: 2 }]
87
+ })
88
+ })
89
+
90
+ it("error assertions", () => {
91
+ // Check type errors, runtime errors, or both at the same time!
92
+ // @ts-expect-error
93
+ attest(() => type("number%0")).throwsAndHasTypeError(
94
+ "% operator must be followed by a non-zero integer literal (was 0)"
95
+ )
96
+ // @ts-expect-error
97
+ attest(() => type({ "[object]": "string" })).type.errors(
98
+ "Indexed key definition 'object' must be a string, number or symbol"
99
+ )
100
+ })
101
+
102
+ it("completion snapshotting", () => {
103
+ // snapshot expected completions for any string literal!
104
+ // @ts-expect-error (if your expression would throw, prepend () =>)
105
+ attest(() => type({ a: "a", b: "b" })).completions({
106
+ a: ["any", "alpha", "alphanumeric"],
107
+ b: ["bigint", "boolean"]
108
+ })
109
+ type Legends = { faker?: "🐐"; [others: string]: unknown }
110
+ // works for keys or index access as well (may need prettier-ignore to avoid removing quotes)
111
+ // prettier-ignore
112
+ attest({ "f": "🐐" } as Legends).completions({ "f": ["faker"] })
113
+ })
114
+
115
+ it("integrate runtime logic with type assertions", () => {
116
+ const arrayOf = type("<t>", "t[]")
117
+ const numericArray = arrayOf("number | bigint")
118
+ // flexibly combine runtime logic with type assertions to customize your
119
+ // tests beyond what is possible from pure static-analysis based type testing tools
120
+ if (getTsVersionUnderTest().startsWith("5")) {
121
+ // this assertion will only occur when testing TypeScript 5+!
122
+ attest<(number | bigint)[]>(numericArray.infer)
123
+ }
124
+ })
125
+
126
+ it("integrated type performance benchmarking", () => {
127
+ const user = type({
128
+ kind: "'admin'",
129
+ "powers?": "string[]"
130
+ })
131
+ .or({
132
+ kind: "'superadmin'",
133
+ "superpowers?": "string[]"
134
+ })
135
+ .or({
136
+ kind: "'pleb'"
137
+ })
138
+ attest.instantiations([7574, "instantiations"])
139
+ })
140
+ })
141
+ ```
142
+
143
+ ## Benches
144
+
145
+ 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`:
146
+
147
+ ```ts
148
+ // Combinatorial template literals often result in expensive types- let's benchmark this one!
149
+ type makeComplexType<s extends string> =
150
+ s extends `${infer head}${infer tail}` ? head | tail | makeComplexType<tail>
151
+ : s
152
+
153
+ bench("bench type", () => {
154
+ return {} as makeComplexType<"defenestration">
155
+ // This is an inline snapshot that will be populated or compared when you run the file
156
+ }).types([169, "instantiations"])
157
+
158
+ bench(
159
+ "bench runtime and type",
160
+ () => {
161
+ return {} as makeComplexType<"antidisestablishmentarianism">
162
+ },
163
+ fakeCallOptions
164
+ )
165
+ // Average time it takes the function execute
166
+ .mean([2, "ms"])
167
+ // Seems like our type is O(n) with respect to the length of the input- not bad!
168
+ .types([337, "instantiations"])
169
+ ```
170
+
171
+ 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):
172
+
173
+ ```
174
+ tsx ./p99/within-limit/p99-tall-simple.bench.ts --benchErrorOnThresholdExceeded --benchPercentThreshold 10
175
+ ```
176
+
177
+ ## CLI
178
+
179
+ Attest also includes a builtin `attest` CLI including the following commands:
180
+
181
+ ### `stats`
182
+
183
+ ```bash
184
+ npm run attest stats packages/*
185
+ ```
186
+
187
+ Summarizes key type performance metrics for each package (check time, instantiations, and type count).
188
+
189
+ Expects any number of args representing package directories to check, optionally specified using glob patterns like `packages/*`.
190
+
191
+ If no directories are provided, defaults to CWD.
192
+
193
+ ### `trace`
194
+
195
+ ```bash
196
+ npm run attest trace .
197
+ ```
198
+
199
+ 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`.
200
+
201
+ Trace expects a single argument representing the root directory of the root package for which to gather type information.
202
+
203
+ ## Integration
204
+
205
+ ### Setup
206
+
207
+ 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:
208
+
209
+ ```ts
210
+ // attest will only collect type data from functions with names listed in `attestAliases`
211
+ setup({ attestAliases: ["yourCustomAssert"] })
212
+
213
+ // There are many other config options, but some are primarily internal- use others at your own risk!
214
+ ```
215
+
216
+ 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.
217
+
218
+ This ensures that type assertions can be made across processes without creating a new TSServer instance for each.
219
+
220
+ ### TS Versions
221
+
222
+ There is a tsVersions setting that allows testing multiple TypeScript aliases at once.
223
+
224
+ ````ts globalSetup.ts
225
+ import { setup } from "@ark/attest"
226
+ /** A string or list of strings representing the TypeScript version aliases to run.
227
+ *
228
+ * Aliases must be specified as a package.json dependency or devDependency beginning with "typescript".
229
+ * Alternate aliases can be specified using the "npm:" prefix:
230
+ * ```json
231
+ * "typescript": "latest",
232
+ * "typescript-next": "npm:typescript@next",
233
+ * "typescript-1": "npm:typescript@5.2"
234
+ * "typescript-2": "npm:typescript@5.1"
235
+ * ```
236
+ *
237
+ * "*" can be pased to run all discovered versions beginning with "typescript".
238
+ */
239
+ setup({ tsVersions: "*" })
240
+ ````
241
+
242
+ ### APIs
243
+
244
+ The most flexible attest APIs are `getTypeAssertionsAtPosition` and `caller`.
245
+
246
+ Here's an example of how you might use them in your own API:
247
+
248
+ ```ts
249
+ import { getTypeAssertionsAtPosition, caller } from "@ark/attest"
250
+
251
+ const yourCustomAssert = <expectedType>(actualValue: expectedType) => {
252
+ const position = caller()
253
+ const types = getTypeAssertionsAtPosition(position)
254
+ // assert that the type of actualValue is the same as the type of expectedType
255
+ const relationship = types[0].args[0].relationships.typeArgs[0]
256
+ if (relationship === undefined) {
257
+ throw new Error(
258
+ `yourCustomAssert requires a type arg representing the expected type, e.g. 'yourCustomAssert<"foo">("foo")'`
259
+ )
260
+ }
261
+ if (relationship !== "equality") {
262
+ throw new Error(
263
+ `Expected ${types.typeArgs[0].type}, got ${types.args[0].type} with relationship ${relationship}`
264
+ )
265
+ }
266
+ }
267
+ ```
268
+
269
+ A user might then use `yourCustomAssert` like this:
270
+
271
+ ```ts
272
+ import { yourCustomAssert } from "your-package"
273
+
274
+ test("my code", () => {
275
+ // Ok
276
+ yourCustomAssert<"foo">(`${"f"}oo` as const)
277
+ // Error: `Expected boolean, got true with relationship subtype`
278
+ yourCustomAssert<boolean>(true)
279
+ // Error: `Expected 5, got number with relationship supertype`
280
+ yourCustomAssert<5>(2 + 3)
281
+ })
282
+ ```
283
+
284
+ 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! ⛵
@@ -0,0 +1,28 @@
1
+ import type { TypeRelationshipAssertionData } from "../cache/writeAssertionCache.js";
2
+ import type { AssertionContext } from "./attest.js";
3
+ export type ThrowAssertionErrorContext = {
4
+ message: string;
5
+ expected?: unknown;
6
+ actual?: unknown;
7
+ ctx: AssertionContext;
8
+ };
9
+ export declare const throwAssertionError: ({ ctx, ...errorArgs }: ThrowAssertionErrorContext) => never;
10
+ export type AssertFn = (expected: unknown, actual: unknown, ctx: AssertionContext) => void;
11
+ export type MappedTypeAssertionResult = {
12
+ actual: unknown;
13
+ expected?: unknown;
14
+ } | null;
15
+ export declare class TypeAssertionMapping {
16
+ fn: (data: TypeRelationshipAssertionData, ctx: AssertionContext) => MappedTypeAssertionResult;
17
+ constructor(fn: (data: TypeRelationshipAssertionData, ctx: AssertionContext) => MappedTypeAssertionResult);
18
+ }
19
+ export declare const versionableAssertion: (fn: AssertFn) => AssertFn;
20
+ export declare const assertEquals: AssertFn;
21
+ export declare const typeEqualityMapping: TypeAssertionMapping;
22
+ export declare const assertEqualOrMatching: AssertFn;
23
+ export type AssertedFnCallResult = {
24
+ returned?: unknown;
25
+ threw?: string;
26
+ };
27
+ export declare const getThrownMessage: (result: AssertedFnCallResult, ctx: AssertionContext) => string | undefined;
28
+ export declare const callAssertedFunction: (asserted: Function) => AssertedFnCallResult;
@@ -0,0 +1,119 @@
1
+ import { printable, throwInternalError } from "@ark/util";
2
+ import { AssertionError } from "node:assert";
3
+ import * as assert from "node:assert/strict";
4
+ export const throwAssertionError = ({ ctx, ...errorArgs }) => {
5
+ const e = new assert.AssertionError(errorArgs);
6
+ e.stack = ctx.assertionStack;
7
+ throw e;
8
+ };
9
+ export class TypeAssertionMapping {
10
+ fn;
11
+ constructor(fn) {
12
+ this.fn = fn;
13
+ }
14
+ }
15
+ export const versionableAssertion = (fn) => (expected, actual, ctx) => {
16
+ if (actual instanceof TypeAssertionMapping) {
17
+ if (!ctx.typeRelationshipAssertionEntries) {
18
+ throwInternalError(`Unexpected missing typeAssertionEntries when passed a TypeAssertionMapper`);
19
+ }
20
+ for (const [version, data] of ctx.typeRelationshipAssertionEntries) {
21
+ let errorMessage = "";
22
+ try {
23
+ const mapped = actual.fn(data, ctx);
24
+ if (mapped !== null) {
25
+ fn("expected" in mapped ? mapped.expected : expected, mapped.actual, ctx);
26
+ }
27
+ }
28
+ catch (e) {
29
+ errorMessage += `❌TypeScript@${version}:${e}\n`;
30
+ }
31
+ if (errorMessage)
32
+ throw new AssertionError({ message: errorMessage });
33
+ }
34
+ }
35
+ else
36
+ fn(expected, actual, ctx);
37
+ };
38
+ const unversionedAssertEquals = (expected, actual, ctx) => {
39
+ if (expected === actual)
40
+ return;
41
+ if (typeof expected === "object" && typeof actual === "object") {
42
+ try {
43
+ assert.deepStrictEqual(actual, expected);
44
+ }
45
+ catch (e) {
46
+ e.stack = ctx.assertionStack;
47
+ throw e;
48
+ }
49
+ }
50
+ else {
51
+ // some nonsense to get a good stack trace
52
+ try {
53
+ assert.strictEqual(actual, expected);
54
+ }
55
+ catch (e) {
56
+ e.stack = ctx.assertionStack;
57
+ throw e;
58
+ }
59
+ }
60
+ };
61
+ export const assertEquals = versionableAssertion(unversionedAssertEquals);
62
+ export const typeEqualityMapping = new TypeAssertionMapping(data => {
63
+ const expected = data.typeArgs[0];
64
+ const actual = data.typeArgs[1] ?? data.args[0];
65
+ if (!expected || !actual)
66
+ throwInternalError(`Unexpected type data ${printable(data)}`);
67
+ if (actual.relationships.typeArgs[0] !== "equality") {
68
+ return {
69
+ expected: expected.type,
70
+ actual: expected.type === actual.type ?
71
+ "(serializes to same value)"
72
+ : actual.type
73
+ };
74
+ }
75
+ return null;
76
+ });
77
+ export const assertEqualOrMatching = versionableAssertion((expected, actual, ctx) => {
78
+ const assertionArgs = { actual, expected, ctx };
79
+ if (typeof actual !== "string") {
80
+ throwAssertionError({
81
+ message: `Value was of type ${typeof actual} (expected a string).`,
82
+ ...assertionArgs
83
+ });
84
+ }
85
+ else if (typeof expected === "string") {
86
+ if (!actual.includes(expected)) {
87
+ throwAssertionError({
88
+ message: `Expected string '${expected}' did not appear in actual string '${actual}'.`,
89
+ ...assertionArgs
90
+ });
91
+ }
92
+ }
93
+ else if (expected instanceof RegExp) {
94
+ if (!expected.test(actual)) {
95
+ throwAssertionError({
96
+ message: `Actual string '${actual}' did not match regex '${expected.source}'.`,
97
+ ...assertionArgs
98
+ });
99
+ }
100
+ }
101
+ else {
102
+ throw new Error(`Expected value for this assertion should be a string or RegExp.`);
103
+ }
104
+ });
105
+ export const getThrownMessage = (result, ctx) => {
106
+ if (!("threw" in result))
107
+ throwAssertionError({ message: "Function didn't throw.", ctx });
108
+ return result.threw;
109
+ };
110
+ export const callAssertedFunction = (asserted) => {
111
+ const result = {};
112
+ try {
113
+ result.returned = asserted();
114
+ }
115
+ catch (error) {
116
+ result.threw = String(error);
117
+ }
118
+ return result;
119
+ };
@@ -0,0 +1,26 @@
1
+ import { type SourcePosition } from "@ark/fs";
2
+ import type { Measure } from "../bench/measure.js";
3
+ import { type VersionedTypeAssertion } from "../cache/getCachedAssertions.js";
4
+ import { type AttestConfig } from "../config.js";
5
+ import { ChainableAssertions, type AssertionKind, type rootAssertions } from "./chainableAssertions.js";
6
+ export type AttestFn = {
7
+ <expected, actual extends expected = never>(...args: [actual] extends [never] ? [value: expected] : []): [expected] extends [never] ? rootAssertions<unknown, AssertionKind> : rootAssertions<expected, AssertionKind>;
8
+ instantiations: (count?: Measure<"instantiations"> | undefined) => void;
9
+ };
10
+ export type AssertionContext = {
11
+ actual: unknown;
12
+ originalAssertedValue: unknown;
13
+ cfg: AttestConfig;
14
+ allowRegex: boolean;
15
+ position: SourcePosition;
16
+ defaultExpected?: unknown;
17
+ assertionStack: string;
18
+ typeRelationshipAssertionEntries?: VersionedTypeAssertion<"type">[];
19
+ typeBenchmarkingAssertionEntries?: VersionedTypeAssertion<"bench">[];
20
+ lastSnapName?: string;
21
+ };
22
+ export type InternalAssertionHooks = {
23
+ [k in keyof AssertionContext]?: k extends "cfg" ? Partial<AttestConfig> : AssertionContext[k];
24
+ };
25
+ export declare const attestInternal: (value?: unknown, { cfg: cfgHooks, ...ctxHooks }?: InternalAssertionHooks) => ChainableAssertions;
26
+ export declare const attest: AttestFn;
@@ -0,0 +1,40 @@
1
+ import { caller, getCallStack } from "@ark/fs";
2
+ import { getBenchCtx } from "../bench/bench.js";
3
+ import { instantiationDataHandler } from "../bench/type.js";
4
+ import { getTypeAssertionsAtPosition } from "../cache/getCachedAssertions.js";
5
+ import { getConfig } from "../config.js";
6
+ import { assertEquals, typeEqualityMapping } from "./assertions.js";
7
+ import { ChainableAssertions } from "./chainableAssertions.js";
8
+ export const attestInternal = (value, { cfg: cfgHooks, ...ctxHooks } = {}) => {
9
+ const position = caller();
10
+ const cfg = { ...getConfig(), ...cfgHooks };
11
+ const ctx = {
12
+ actual: value,
13
+ allowRegex: false,
14
+ originalAssertedValue: value,
15
+ position,
16
+ cfg,
17
+ assertionStack: getCallStack({ offset: 1 }).join("\n"),
18
+ ...ctxHooks
19
+ };
20
+ if (!cfg.skipTypes) {
21
+ ctx.typeRelationshipAssertionEntries = getTypeAssertionsAtPosition(position);
22
+ if (ctx.typeRelationshipAssertionEntries[0][1].typeArgs[0]) {
23
+ // if there is an expected type arg, check it immediately
24
+ assertEquals(undefined, typeEqualityMapping, ctx);
25
+ }
26
+ }
27
+ return new ChainableAssertions(ctx);
28
+ };
29
+ export const attest = Object.assign(attestInternal, {
30
+ instantiations: (args) => {
31
+ const attestConfig = getConfig();
32
+ if (attestConfig.skipInlineInstantiations)
33
+ return;
34
+ const calledFrom = caller();
35
+ const ctx = getBenchCtx([calledFrom.file]);
36
+ ctx.benchCallPosition = calledFrom;
37
+ ctx.lastSnapCallPosition = calledFrom;
38
+ instantiationDataHandler({ ...ctx, kind: "instantiations" }, args, false);
39
+ }
40
+ });
@@ -0,0 +1,68 @@
1
+ import { snapshot, type Constructor } from "@ark/util";
2
+ import { type validateTypeRoot } from "arktype";
3
+ import type { Completions } from "../cache/writeAssertionCache.js";
4
+ import type { AssertionContext } from "./attest.js";
5
+ export type ChainableAssertionOptions = {
6
+ allowRegex?: boolean;
7
+ defaultExpected?: unknown;
8
+ };
9
+ type AssertionRecord = Record<keyof rootAssertions<any, AssertionKind>, unknown>;
10
+ export declare class ChainableAssertions implements AssertionRecord {
11
+ private ctx;
12
+ constructor(ctx: AssertionContext);
13
+ private serialize;
14
+ private get unversionedActual();
15
+ private get serializedActual();
16
+ private snapRequiresUpdate;
17
+ get unknown(): this;
18
+ is(expected: unknown): this;
19
+ equals(expected: unknown): this;
20
+ satisfies(def: unknown): this;
21
+ instanceOf(expected: Constructor): this;
22
+ get snap(): snapProperty<unknown, AssertionKind>;
23
+ private immediateOrChained;
24
+ get throws(): unknown;
25
+ throwsAndHasTypeError(matchValue: string | RegExp): void;
26
+ get completions(): any;
27
+ get type(): any;
28
+ }
29
+ export type AssertionKind = "value" | "type";
30
+ export type rootAssertions<t, kind extends AssertionKind> = valueAssertions<t, kind> & TypeAssertionsRoot;
31
+ export type valueAssertions<t, kind extends AssertionKind> = comparableValueAssertion<t, kind> & (t extends () => unknown ? functionAssertions<kind> : {});
32
+ export type nextAssertions<kind extends AssertionKind> = "type" extends kind ? TypeAssertionsRoot : {};
33
+ export type inferredAssertions<argsType extends [value: any, ...rest: any[]], kind extends AssertionKind, chained = argsType[0]> = rootAssertions<chained, kind> & (<Args extends argsType | [] = []>(...args: Args) => nextAssertions<kind>);
34
+ export type ChainContext = {
35
+ allowRegex?: boolean;
36
+ defaultExpected?: unknown;
37
+ };
38
+ export type functionAssertions<kind extends AssertionKind> = {
39
+ throws: inferredAssertions<[message: string | RegExp], kind, string>;
40
+ } & ("type" extends kind ? {
41
+ throwsAndHasTypeError: (message: string | RegExp) => undefined;
42
+ } : {});
43
+ export type valueFromTypeAssertion<expected, chained = expected> = inferredAssertions<[expected: expected], "value", chained>;
44
+ type snapProperty<expected, kind extends AssertionKind> = {
45
+ (expected?: snapshot<expected>): nextAssertions<kind>;
46
+ toFile: (id: string, options?: ExternalSnapshotOptions) => nextAssertions<kind>;
47
+ };
48
+ export type comparableValueAssertion<expected, kind extends AssertionKind> = {
49
+ snap: snapProperty<expected, kind>;
50
+ equals: (value: expected) => nextAssertions<kind>;
51
+ instanceOf: (constructor: Constructor) => nextAssertions<kind>;
52
+ is: (value: expected) => nextAssertions<kind>;
53
+ completions: (value?: Completions) => void;
54
+ satisfies: <def>(def: validateTypeRoot<def>) => nextAssertions<kind>;
55
+ unknown: Omit<comparableValueAssertion<unknown, kind>, "unknown">;
56
+ };
57
+ export type TypeAssertionsRoot = {
58
+ type: TypeAssertionProps;
59
+ };
60
+ export type TypeAssertionProps = {
61
+ toString: valueFromTypeAssertion<string>;
62
+ errors: valueFromTypeAssertion<string | RegExp, string>;
63
+ completions: (value?: Completions) => void;
64
+ };
65
+ export type ExternalSnapshotOptions = {
66
+ path?: string;
67
+ };
68
+ export {};