@final-hill/decorator-contracts 0.25.3 → 2.0.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 +580 -542
- package/dist/AssertionError.d.mts +52 -8
- package/dist/Contracted.d.mts +29 -21
- package/dist/admissibility.d.mts +81 -0
- package/dist/assert.d.mts +73 -8
- package/dist/decorator.d.mts +12 -0
- package/dist/demands.d.mts +54 -0
- package/dist/ensures.d.mts +39 -0
- package/dist/iff.d.mts +24 -6
- package/dist/implies.d.mts +22 -6
- package/dist/index.d.mts +11 -13
- package/dist/index.mjs +1 -2
- package/dist/index.mjs.map +1 -1
- package/dist/invariant.d.mts +27 -0
- package/dist/read-only.d.mts +45 -0
- package/dist/rescue.d.mts +61 -0
- package/dist/standard-schema.d.mts +46 -0
- package/dist/types.d.mts +7 -0
- package/package.json +33 -18
- package/dist/Contract.d.mts +0 -39
- package/dist/Messages.d.mts +0 -16
- package/dist/index.mjs.LICENSE.txt +0 -6
- package/dist/lib/ClassRegistration.d.mts +0 -23
- package/dist/lib/ClassType.d.mts +0 -10
- package/dist/lib/Feature.d.mts +0 -26
- package/dist/lib/assertDemands.d.mts +0 -9
- package/dist/lib/assertEnsures.d.mts +0 -10
- package/dist/lib/assertInvariants.d.mts +0 -9
- package/dist/lib/classRegistry.d.mts +0 -12
- package/dist/lib/deepFreeze.d.mts +0 -8
- package/dist/lib/index.d.mts +0 -18
- package/dist/lib/takeWhile.d.mts +0 -8
- package/dist/lib/unChecked.d.mts +0 -9
- package/dist/tests/Contract.test.d.mts +0 -7
- package/dist/tests/Stack.test.d.mts +0 -7
- package/dist/tests/assert.test.d.mts +0 -7
- package/dist/tests/deepFreeze.test.d.mts +0 -7
- package/dist/tests/demands.test.d.mts +0 -7
- package/dist/tests/ensures.test.d.mts +0 -7
- package/dist/tests/factoryPattern.test.d.mts +0 -7
- package/dist/tests/iff.test.d.mts +0 -7
- package/dist/tests/implies.test.d.mts +0 -7
- package/dist/tests/invariant.test.d.mts +0 -7
- package/dist/tests/public-properties.test.d.mts +0 -7
- package/dist/tests/rescue.test.d.mts +0 -7
- package/dist/tests/within.test.d.mts +0 -7
|
@@ -1,10 +1,54 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*
|
|
4
|
-
* SPDX-License-Identifier: AGPL-3.0-only
|
|
5
|
-
* @see <https://spdx.org/licenses/AGPL-3.0-only.html>
|
|
1
|
+
import type { StandardSchemaV1 } from './standard-schema.mjs';
|
|
2
|
+
/**
|
|
3
|
+
* The contract kinds that can raise an {@link AssertionError}.
|
|
6
4
|
*/
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
export type ContractKind = '@invariant' | '@demands' | '@ensures';
|
|
6
|
+
/**
|
|
7
|
+
* Structured description of a failed contract.
|
|
8
|
+
*
|
|
9
|
+
* Attached to {@link AssertionError} so that callers — including integration
|
|
10
|
+
* layers such as a schema adapter — can react to a specific violation without
|
|
11
|
+
* parsing the message.
|
|
12
|
+
*/
|
|
13
|
+
export interface ContractViolation {
|
|
14
|
+
/** Which contract failed. */
|
|
15
|
+
contract: ContractKind;
|
|
16
|
+
/** The class the contract belongs to. */
|
|
17
|
+
className: string;
|
|
18
|
+
/** The feature the contract belongs to, absent for `@invariant`. */
|
|
19
|
+
feature?: string;
|
|
20
|
+
/**
|
|
21
|
+
* The indices, within the contract's composition list, that failed.
|
|
22
|
+
*
|
|
23
|
+
* `@demands` is OR-composed, so a failure lists every arm; `@ensures` and
|
|
24
|
+
* `@invariant` are AND-composed, so a failure lists the one that broke.
|
|
25
|
+
*/
|
|
26
|
+
failedIndices: number[];
|
|
27
|
+
/** The source text of the failing arms, aligned with `failedIndices`. */
|
|
28
|
+
predicates: string[];
|
|
29
|
+
/**
|
|
30
|
+
* The `issues` reported by failing schema arms, in the order they were
|
|
31
|
+
* raised. Absent when the failure came only from predicate arms, so a caller
|
|
32
|
+
* can distinguish "a schema rejected this" from "a predicate returned
|
|
33
|
+
* false".
|
|
34
|
+
*/
|
|
35
|
+
issues?: ReadonlyArray<StandardSchemaV1.Issue>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* An `AssertionError` represents a failed assertion with an associated message.
|
|
39
|
+
*
|
|
40
|
+
* When the failure came from a contract, {@link AssertionError.violation}
|
|
41
|
+
* describes it structurally.
|
|
42
|
+
*/
|
|
43
|
+
export declare class AssertionError extends Error {
|
|
44
|
+
/**
|
|
45
|
+
* Set explicitly rather than relying on the class name.
|
|
46
|
+
*
|
|
47
|
+
* Bundlers rename classes, so the published build would otherwise expose a
|
|
48
|
+
* mangled name such as `t` to consumers.
|
|
49
|
+
*/
|
|
50
|
+
name: string;
|
|
51
|
+
/** Structured description of the failure, when it came from a contract. */
|
|
52
|
+
readonly violation?: ContractViolation;
|
|
53
|
+
constructor(message?: string, violation?: ContractViolation);
|
|
9
54
|
}
|
|
10
|
-
export default AssertionError;
|
package/dist/Contracted.d.mts
CHANGED
|
@@ -1,21 +1,29 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
import { InvariantPredicate } from './invariant.mjs';
|
|
2
|
+
import { DemandsPredicate } from './demands.mjs';
|
|
3
|
+
import { EnsuresPredicate } from './ensures.mjs';
|
|
4
|
+
import { RescueDeclaration } from './rescue.mjs';
|
|
5
|
+
export declare const checkedMode: unique symbol;
|
|
6
|
+
export declare class Contracted {
|
|
7
|
+
static [Symbol.metadata]: {
|
|
8
|
+
invariants: InvariantPredicate<typeof Contracted>[];
|
|
9
|
+
demands: Record<PropertyKey, DemandsPredicate<Contracted>[]>;
|
|
10
|
+
ensures: Record<PropertyKey, EnsuresPredicate<Contracted>[]>;
|
|
11
|
+
rescue: Record<PropertyKey, RescueDeclaration<Contracted>>;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Grants permission for exactly one `Contracted` constructor call.
|
|
15
|
+
*
|
|
16
|
+
* A boolean would leave the gate open for the whole duration of the
|
|
17
|
+
* constructor, so a class that called `new Foo()` inside its own
|
|
18
|
+
* constructor — directly or through a superclass — would obtain a raw,
|
|
19
|
+
* unproxied instance and defeat every contract.
|
|
20
|
+
*
|
|
21
|
+
* `Contracted`'s constructor runs exactly once per construction, so a
|
|
22
|
+
* single-use token is enough. Classes that do not declare their own
|
|
23
|
+
* constructor call it implicitly; classes that do must call `super()` once.
|
|
24
|
+
*/
|
|
25
|
+
protected static _allowedConstructions: number;
|
|
26
|
+
static [checkedMode]: boolean;
|
|
27
|
+
static new<C extends typeof Contracted, Args extends ConstructorParameters<C>>(this: C, ...args: Args): InstanceType<C>;
|
|
28
|
+
constructor(..._args: any[]);
|
|
29
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from './standard-schema.mjs';
|
|
2
|
+
/**
|
|
3
|
+
* The result of checking a subject against one contract arm.
|
|
4
|
+
*
|
|
5
|
+
* Predicates and schemas are adapted to this shape so that the composition rule
|
|
6
|
+
* in each contract — OR for `@demands`, AND for `@invariant` and `@ensures` — is
|
|
7
|
+
* written once rather than twice.
|
|
8
|
+
*/
|
|
9
|
+
export type Admissibility = {
|
|
10
|
+
ok: boolean;
|
|
11
|
+
value?: unknown;
|
|
12
|
+
issues?: ReadonlyArray<StandardSchemaV1.Issue>;
|
|
13
|
+
};
|
|
14
|
+
/** Options a decorator accepts alongside an arm. */
|
|
15
|
+
export interface ArmOptions {
|
|
16
|
+
/**
|
|
17
|
+
* Replace the subject with the schema's `Output`.
|
|
18
|
+
*
|
|
19
|
+
* Off by default. `validate` may transform what it returns, and applying that
|
|
20
|
+
* transformation changes what the feature body receives and what later
|
|
21
|
+
* contracts observe, so it is an explicit choice rather than a side effect of
|
|
22
|
+
* validation. Only a schema can normalize.
|
|
23
|
+
*/
|
|
24
|
+
normalize?: boolean;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The two subjects a contract arm can observe.
|
|
28
|
+
*
|
|
29
|
+
* A predicate and a schema look at different things even within one contract: an
|
|
30
|
+
* `@ensures` predicate needs the invocation and the historical instance, while a
|
|
31
|
+
* schema in the same position validates the result. Passing both explicitly keeps
|
|
32
|
+
* that difference visible at each call site instead of hiding it behind a
|
|
33
|
+
* convention.
|
|
34
|
+
*/
|
|
35
|
+
export interface ArmSubjects {
|
|
36
|
+
/** The arguments a predicate is called with. */
|
|
37
|
+
predicate: () => any[];
|
|
38
|
+
/** The value a schema arm validates. */
|
|
39
|
+
schema: () => unknown;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* True when a value is a `StandardSchemaV1` rather than a predicate.
|
|
43
|
+
*
|
|
44
|
+
* The check is structural: any object exposing a `~standard` property is treated
|
|
45
|
+
* as a schema, which is what makes the protocol provider-agnostic. A predicate is
|
|
46
|
+
* callable and has no such property.
|
|
47
|
+
*/
|
|
48
|
+
export declare const isSchema: (arm: unknown) => arm is StandardSchemaV1;
|
|
49
|
+
/**
|
|
50
|
+
* Describes an arm for a failure message.
|
|
51
|
+
*
|
|
52
|
+
* Schemas are identified by vendor because their `String()` form is opaque and
|
|
53
|
+
* the caller needs to know which provider produced the arm.
|
|
54
|
+
*/
|
|
55
|
+
export declare const describeArm: (arm: unknown) => string;
|
|
56
|
+
/**
|
|
57
|
+
* Rejects `normalize` on an arm that cannot honour it.
|
|
58
|
+
*
|
|
59
|
+
* Called at decoration time so an impossible declaration fails where it is
|
|
60
|
+
* written rather than on the first invocation. A predicate reports a verdict, not
|
|
61
|
+
* a replacement value.
|
|
62
|
+
*/
|
|
63
|
+
export declare const assertNormalizable: (arm: unknown, contract: string, options: ArmOptions | undefined) => void;
|
|
64
|
+
/**
|
|
65
|
+
* Checks one arm against the subject that belongs to it.
|
|
66
|
+
*
|
|
67
|
+
* @param arm - A predicate or a `StandardSchemaV1` value.
|
|
68
|
+
* @param subjects - What the arm observes, chosen by the calling contract.
|
|
69
|
+
* @param contract - The contract name, for the diagnostic.
|
|
70
|
+
* @param label - The feature, for the diagnostic.
|
|
71
|
+
* @param index - The arm's position in its composition list.
|
|
72
|
+
* @param options - Declaration options for this arm.
|
|
73
|
+
*/
|
|
74
|
+
export declare const evaluateArm: (arm: unknown, subjects: ArmSubjects, contract: string, label: string, index: number, options?: ArmOptions) => Admissibility;
|
|
75
|
+
/**
|
|
76
|
+
* Renders schema `issues` for a message.
|
|
77
|
+
*
|
|
78
|
+
* A path is reported as a dotted trail of keys, matching how the providers
|
|
79
|
+
* describe a nested failure themselves.
|
|
80
|
+
*/
|
|
81
|
+
export declare const describeIssues: (issues: ReadonlyArray<StandardSchemaV1.Issue>) => string;
|
package/dist/assert.d.mts
CHANGED
|
@@ -1,8 +1,73 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import { AssertionError, type ContractKind, type ContractViolation } from "./AssertionError.mjs";
|
|
2
|
+
import type { StandardSchemaV1 } from './standard-schema.mjs';
|
|
3
|
+
/**
|
|
4
|
+
* An assertion is an expression of a property that must be true at a particular
|
|
5
|
+
* point of step of program execution. It consists of a boolean expression
|
|
6
|
+
* and a message. This function tests the provided condition. If the condition
|
|
7
|
+
* is false an AssertionError is raised with an optional message.
|
|
8
|
+
* If the provided condition is true then the function returns without raising an error
|
|
9
|
+
*
|
|
10
|
+
* @param condition - The condition to test. If it is false an error is raised.
|
|
11
|
+
* @param message - The message to display if the condition is false. If not provided a default message is used.
|
|
12
|
+
* @throws {AssertionError} If the condition is false an AssertionError is raised.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* import assert from "assert.mjs";
|
|
17
|
+
*
|
|
18
|
+
* let x = 15;
|
|
19
|
+
* assert(x > 5, `Expected: x > 5. Actual: x = ${x}`);
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function assert(condition: unknown, message?: string): asserts condition;
|
|
23
|
+
/**
|
|
24
|
+
* Asserts that a contract predicate returned a `boolean`.
|
|
25
|
+
*
|
|
26
|
+
* Contract predicates must return a boolean. Coercing the result would silently
|
|
27
|
+
* accept a non-boolean, which is how an accidentally asynchronous predicate
|
|
28
|
+
* passes: a `Promise` is always truthy. Treating a contract that never actually
|
|
29
|
+
* ran as satisfied is worse than failing, so a non-boolean result raises an
|
|
30
|
+
* `AssertionError` naming the contract, the feature, and the predicate index.
|
|
31
|
+
*
|
|
32
|
+
* @param result - The value returned by the predicate.
|
|
33
|
+
* @param contract - The name of the contract, e.g. `@demands`.
|
|
34
|
+
* @param label - A human-readable description of the feature, e.g. `Foo.method`.
|
|
35
|
+
* @param index - The zero-based index of the predicate in its composition list.
|
|
36
|
+
* @returns The predicate result, narrowed to `boolean`.
|
|
37
|
+
* @throws {AssertionError} If the predicate did not return a boolean.
|
|
38
|
+
*/
|
|
39
|
+
export declare function assertContractResult(result: unknown, contract: string, label: string, index: number): boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Builds a message for a failed contract and describes it structurally.
|
|
42
|
+
*
|
|
43
|
+
* Every contract reports the same way: which contract failed, on which feature,
|
|
44
|
+
* which arm(s) failed, and how each one is described. A caller can use the
|
|
45
|
+
* returned violation instead of parsing the message.
|
|
46
|
+
*
|
|
47
|
+
* @param contract - Which contract failed.
|
|
48
|
+
* @param className - The class the contract belongs to.
|
|
49
|
+
* @param feature - The feature the contract belongs to, absent for `@invariant`.
|
|
50
|
+
* @param arms - The full composition list, so indices are meaningful.
|
|
51
|
+
* @param failedIndices - The indices in `arms` that failed.
|
|
52
|
+
* @param summary - A per-contract description of what the failure means.
|
|
53
|
+
* @param issues - `issues` reported by failing schema arms, if any.
|
|
54
|
+
* @param describe - Renders one arm for the message.
|
|
55
|
+
* @returns The message and the structured violation.
|
|
56
|
+
*/
|
|
57
|
+
export declare function describeViolation(contract: ContractKind, className: string, feature: string | undefined, arms: readonly unknown[], failedIndices: number[], summary: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>, describe?: (arm: unknown) => string): {
|
|
58
|
+
message: string;
|
|
59
|
+
violation: ContractViolation;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Builds the error for a contract whose arms were not satisfied.
|
|
63
|
+
*
|
|
64
|
+
* Every contract reports the same way — a message naming the feature and the
|
|
65
|
+
* arms that failed, plus the structured violation — so the identical
|
|
66
|
+
* `describeViolation` + `throw new AssertionError` tail is produced here instead
|
|
67
|
+
* of being written in each of `@invariant`, `@demands`, and `@ensures`.
|
|
68
|
+
*
|
|
69
|
+
* The composition rule stays with each contract, because it is not shared:
|
|
70
|
+
* `@demands` is OR-composed (a subtype may weaken a precondition) while
|
|
71
|
+
* `@invariant` and `@ensures` are AND-composed.
|
|
72
|
+
*/
|
|
73
|
+
export declare function violationError(contract: ContractKind, className: string, feature: string | undefined, arms: readonly unknown[], failedIndices: number[], summary: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>, describe?: (arm: unknown) => string): AssertionError;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { FeatureDecoratorContext } from './types.mjs';
|
|
2
|
+
/**
|
|
3
|
+
* The gate every feature contract decorator shares.
|
|
4
|
+
*
|
|
5
|
+
* `@demands`, `@ensures`, and `@rescue` apply to exactly the same kind of member:
|
|
6
|
+
* an instance feature of a `Contracted` subclass, whose name is not `_`-prefixed.
|
|
7
|
+
* Each used to repeat the same four assertions and the same `addInitializer`
|
|
8
|
+
* check, so a rule added to one was easy to miss in the others.
|
|
9
|
+
*
|
|
10
|
+
* The name of the contract is passed in so the messages stay specific.
|
|
11
|
+
*/
|
|
12
|
+
export declare function assertFeatureContractTarget(contract: string, feature: unknown, ctx: FeatureDecoratorContext): void;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Contracted } from "./Contracted.mjs";
|
|
2
|
+
import { type ArmOptions } from './admissibility.mjs';
|
|
3
|
+
import type { StandardSchemaV1 } from './standard-schema.mjs';
|
|
4
|
+
import type { FeatureDecoratorContext } from './types.mjs';
|
|
5
|
+
/**
|
|
6
|
+
* A precondition predicate.
|
|
7
|
+
*
|
|
8
|
+
* `args` is the argument list of the invocation, matching `EnsuresPredicate`,
|
|
9
|
+
* so a predicate destructures it: `(_self, [x]) => x > 0`.
|
|
10
|
+
*
|
|
11
|
+
* The type is generic over the argument tuple so the element types are inferred
|
|
12
|
+
* from the predicate. Writing `(_self, x: number) => x > 0` does not compile:
|
|
13
|
+
* the second parameter is the array, not the first argument, and a predicate
|
|
14
|
+
* that compares against the array passes only through coercion, which is how
|
|
15
|
+
* the previous documentation ended up describing contracts that never held.
|
|
16
|
+
*/
|
|
17
|
+
export type DemandsPredicate<This extends Contracted, Args extends any[] = any[]> = (self: This, args: Args) => boolean;
|
|
18
|
+
/**
|
|
19
|
+
* A precondiction arm: a predicate, or a schema the argument tuple must satisfy.
|
|
20
|
+
*
|
|
21
|
+
* A schema validates the **argument tuple**, which is the subject `@demands`
|
|
22
|
+
* already describes, so a method with two parameters is written as
|
|
23
|
+
* `z.tuple([A, B])`. Keeping one subject for both kinds of arm is what lets the
|
|
24
|
+
* composition rule below be the same for both.
|
|
25
|
+
*
|
|
26
|
+
* The schema's `Input` is left unpinned (`unknown`) rather than constrained to
|
|
27
|
+
* `any[]`, because every real provider declares a concrete input type and
|
|
28
|
+
* `StandardSchemaV1` is invariant in it: pinning it here would reject a
|
|
29
|
+
* `z.tuple([...])` whose input is `[number, number]`. The tuple shape is an
|
|
30
|
+
* obligation on the declaration, checked at runtime by the schema itself.
|
|
31
|
+
*/
|
|
32
|
+
export type DemandsArm<This extends Contracted, Args extends any[] = any[]> = DemandsPredicate<This, Args> | StandardSchemaV1<unknown, any>;
|
|
33
|
+
export type DemandsDecorator = <This extends Contracted, Args extends any[], Feature = unknown>(arm: DemandsArm<This, Args>, options?: ArmOptions) => (value: Feature, context: FeatureDecoratorContext) => Feature | void;
|
|
34
|
+
/** A registered precondition arm, with the options it was declared with. */
|
|
35
|
+
export interface RegisteredDemands {
|
|
36
|
+
arm: DemandsArm<Contracted>;
|
|
37
|
+
options?: ArmOptions;
|
|
38
|
+
}
|
|
39
|
+
export declare const demands: DemandsDecorator;
|
|
40
|
+
/**
|
|
41
|
+
* Evaluates the precondition for an invocation.
|
|
42
|
+
*
|
|
43
|
+
* The arms are OR-composed, which is the contravariance rule: a subtype may
|
|
44
|
+
* weaken a precondition, so satisfying any inherited arm is enough. A schema arm
|
|
45
|
+
* composes exactly like a predicate arm.
|
|
46
|
+
*
|
|
47
|
+
* When an arm asks for normalization, the value it produced replaces the
|
|
48
|
+
* arguments, and because OR-composition short-circuits, the **first passing arm**
|
|
49
|
+
* decides what that value is. That is deterministic and matches evaluation order.
|
|
50
|
+
*
|
|
51
|
+
* @returns The arguments to use, which are the originals unless an arm
|
|
52
|
+
* normalized them.
|
|
53
|
+
*/
|
|
54
|
+
export declare function assertDemands(instance: Contracted, propertyKey: PropertyKey, args: any[]): any[];
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Contracted } from './Contracted.mjs';
|
|
2
|
+
import { type ArmOptions } from './admissibility.mjs';
|
|
3
|
+
import type { StandardSchemaV1 } from './standard-schema.mjs';
|
|
4
|
+
import type { FeatureDecoratorContext } from './types.mjs';
|
|
5
|
+
/**
|
|
6
|
+
* A postcondition predicate.
|
|
7
|
+
*
|
|
8
|
+
* `args` is the argument list of the invocation and `old` is the snapshot of
|
|
9
|
+
* the instance from before the feature ran, so a predicate reads
|
|
10
|
+
* `(self, [x], old) => ...`. See `DemandsPredicate` for why the tuple is generic.
|
|
11
|
+
*/
|
|
12
|
+
export type EnsuresPredicate<This extends Contracted, Args extends any[] = any[]> = (self: This, args: Args, old: This) => boolean;
|
|
13
|
+
/**
|
|
14
|
+
* A postcondition arm: a predicate, or a schema the feature's **result** must
|
|
15
|
+
* satisfy.
|
|
16
|
+
*
|
|
17
|
+
* A schema validates the result, which is the value the caller receives. This is
|
|
18
|
+
* the covariant position: a subtype may promise a narrower result, so the arms
|
|
19
|
+
* are AND-composed.
|
|
20
|
+
*/
|
|
21
|
+
export type EnsuresArm<This extends Contracted, Args extends any[] = any[]> = EnsuresPredicate<This, Args> | StandardSchemaV1<unknown, any>;
|
|
22
|
+
export type EnsuresDecorator = <This extends Contracted, Args extends any[]>(arm: EnsuresArm<This, Args>, options?: ArmOptions) => (value: unknown, context: FeatureDecoratorContext) => void;
|
|
23
|
+
/** A registered postcondition arm, with the options it was declared with. */
|
|
24
|
+
export interface RegisteredEnsures {
|
|
25
|
+
arm: EnsuresArm<Contracted>;
|
|
26
|
+
options?: ArmOptions;
|
|
27
|
+
}
|
|
28
|
+
export declare const ensures: EnsuresDecorator;
|
|
29
|
+
/**
|
|
30
|
+
* Evaluates the postcondition for an invocation.
|
|
31
|
+
*
|
|
32
|
+
* The arms are AND-composed, which is the covariance rule: a subtype may
|
|
33
|
+
* strengthen a postcondition, so every inherited arm has to keep holding.
|
|
34
|
+
*
|
|
35
|
+
* @param result - The value the caller receives. A schema arm validates it.
|
|
36
|
+
* @returns The result to hand the caller, which is the original unless an arm
|
|
37
|
+
* normalized it.
|
|
38
|
+
*/
|
|
39
|
+
export declare function assertEnsures(instance: Contracted, old: Contracted, propertyKey: PropertyKey, args: any[], result: unknown): unknown;
|
package/dist/iff.d.mts
CHANGED
|
@@ -1,7 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
1
|
+
/**
|
|
2
|
+
* Biconditional.
|
|
3
|
+
* p ↔ q.
|
|
4
|
+
* "P if and only if Q".
|
|
5
|
+
* An example of usage is the encoding of "You can ride the train if and only if you have a ticket"
|
|
6
|
+
* This is logically equivalent to: implies(p,q) && implies(q,p)
|
|
7
|
+
*
|
|
8
|
+
* @param p - The first boolean value (the antecedent).
|
|
9
|
+
* @param q - The second boolean value (the consequent).
|
|
10
|
+
* @returns - The result (biconditional) of p and q, always a `boolean`.
|
|
11
|
+
*
|
|
12
|
+
* A non-boolean operand is coerced rather than rejected, because this is a
|
|
13
|
+
* general-purpose logical helper. Inside a contract the coercion is redundant:
|
|
14
|
+
* `@demands` and the other contracts already require a literal `true` or `false`
|
|
15
|
+
* and will report a non-boolean result by name.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { iff } from '@final-hill/decorator-contracts';
|
|
20
|
+
*
|
|
21
|
+
* // You can ride the train if and only if you have a ticket
|
|
22
|
+
* iff(person.hasTicket, person.ridesTrain)
|
|
23
|
+
* ```
|
|
6
24
|
*/
|
|
7
|
-
export
|
|
25
|
+
export declare function iff(p: boolean, q: boolean): boolean;
|
package/dist/implies.d.mts
CHANGED
|
@@ -1,7 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
1
|
+
/**
|
|
2
|
+
* Material Implication.
|
|
3
|
+
* `p → q`
|
|
4
|
+
* Also referred to as `if-then`.
|
|
5
|
+
* An example of usage is the encoding of "sunny weather is a precondition of visiting the beach"
|
|
6
|
+
* This is logically equivalent to: !p || q
|
|
7
|
+
*
|
|
8
|
+
* @param p - The first boolean value (the antecedent).
|
|
9
|
+
* @param q - The second boolean value (the consequent).
|
|
10
|
+
* @returns - The result (material implication) of p and q, always a `boolean`.
|
|
11
|
+
*
|
|
12
|
+
* A non-boolean consequent is coerced rather than rejected, for the same reason
|
|
13
|
+
* as {@link iff}.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* import { implies } from '@final-hill/decorator-contracts';
|
|
18
|
+
*
|
|
19
|
+
* // Sunny weather is a precondition of visiting the beach
|
|
20
|
+
* implies(weather.isSunny, person.visitsBeach)
|
|
21
|
+
* ```
|
|
6
22
|
*/
|
|
7
|
-
export
|
|
23
|
+
export declare function implies(p: boolean, q: boolean): boolean;
|
package/dist/index.d.mts
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
export
|
|
12
|
-
export { Contract, extend, invariant, type Invariant, checkedMode, type Rescue } from './Contract.mjs';
|
|
13
|
-
export { type Constructor, type AbstractConstructor, type ClassType } from './lib/ClassType.mjs';
|
|
1
|
+
export * from './types.mjs';
|
|
2
|
+
export * from './standard-schema.mjs';
|
|
3
|
+
export * from "./AssertionError.mjs";
|
|
4
|
+
export * from "./assert.mjs";
|
|
5
|
+
export * from './iff.mjs';
|
|
6
|
+
export * from './implies.mjs';
|
|
7
|
+
export * from './Contracted.mjs';
|
|
8
|
+
export * from './invariant.mjs';
|
|
9
|
+
export * from './demands.mjs';
|
|
10
|
+
export * from './ensures.mjs';
|
|
11
|
+
export * from './rescue.mjs';
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
/*! For license information please see index.mjs.LICENSE.txt */
|
|
2
|
-
var t={d:(e,s)=>{for(var r in s)t.o(s,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:s[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};t.d(e,{pf:()=>r,NZ:()=>a,eR:()=>M,vA:()=>P,zf:()=>n,X$:()=>i,M0:()=>j,JG:()=>w,V1:()=>o});class s extends Error{constructor(t){super(t)}}const r=s,n=Symbol("checkedMode"),o=Symbol("invariant"),i=Symbol("extend");class a{#t;[n];[i];assertions=Object.create(null);constructor(t=Object.create(null)){this[i]=t[i],this[n]=t[n]??!0,this.#t=t[o]??O,Object.keys(t).forEach((e=>{const s=t[e];Object.defineProperty(this.assertions,e,{value:{demands:s.demands??O,ensures:s.ensures??O,rescue:s.rescue,within:s.within}})})),b(this.assertions)}get[o](){return this.#t}}const c=(t,e)=>{try{t[n]=!1,e()}finally{t[n]=!0}},l=function t(e,s,r,o,a){let l=!0;const u=Reflect.get(s.assertions,o)?.demands,h=`demands not met on ${r}.prototype.${String(o)}\r\n${u}`;s[n]&&u&&c(s,(()=>l=u.call(e,e,...a))),s[i]&&!l?t(e,s[i],r,o,a):P(l,h)},u=function t(e,s,r,o,a,l){const u=Reflect.get(s.assertions,o)?.ensures,h=`ensures not met on ${r}.prototype.${String(o)}\r\n${u}`;s[n]&&u&&c(s,(()=>P(u.call(e,e,a,...l),h))),s[i]&&t(e,s[i],r,o,a,l)},h=function t(e,s){s[n]&&c(s,(()=>{const t=s[o];P(t.call(e,e),`Invariant violated. ${t.toString()}`)})),s[i]&&t(e,s[i])};class d extends WeakMap{getOrCreate(t){return this.has(t)||this.set(t,new y(t)),this.get(t)}}const f=new d;var p;function g(t,e,s){return function r(...o){const{Class:i}=s,a=i.name;P(this instanceof i,`${p.MsgInvalidContext}. Expected: this instanceof ${a}. this: ${this.constructor.name}`);const d=Reflect.get(this,w);if(!d[n])return e.apply(this,o);let f;h(this,d),l(this,d,a,t,o);try{const r=Object.create(null);c(d,(()=>{s.features.forEach((({name:t,hasGetter:e})=>{e&&Object.defineProperty(r,t,{value:this[t]})}))}));const n=Reflect.get(d.assertions,t)?.within,i=Date.now();f=e.apply(this,o);const l=Date.now();n&&P(l-i<n,`Timing constraint violated. Constraint: ${n}ms, actual: ${l-i}ms`),u(this,d,a,t,r,o)}catch(e){const s=Reflect.get(d.assertions,t)?.rescue;if(null==s)throw h(this,d),e;let o=!1;if(c(d,(()=>{s.call(this,this,e,[],((...t)=>{P(!o,p.MsgSingleRetry),o=!0,d[n]=!0,f=r.call(this,...t)}))})),!o)throw h(this,d),e}return h(this,d),f}}!function(t){t.AssertionFailed="Assertion failure",t.MsgNoProperties="Public properties are forbidden",t.MsgNotContracted="The current class or one of its ancestors must declare @Contracted(...)",t.MsgMissingFeature="The requested feature is not registered",t.MsgSingleContract="Only a single @Contracted decorator is allowed per class",t.MsgSingleRetry="retry can only be called once",t.MsgInvalidContext="A contracted feature can not be applied to objects of a different base class",t.MsgBadSubcontract="A sub contract must extend a base contract"}(p||(p={}));const y=class{Class;#e;contract;contractsChecked=!1;constructor(t){this.Class=t;const e=this.Class.prototype;this.#e=Reflect.ownKeys(e).filter((t=>"constructor"!=t&&t!==w)).map((t=>new C(this,t,Object.getOwnPropertyDescriptor(e,t))))}get features(){return[...this.#e]}get ParentClass(){return Object.getPrototypeOf(this.Class.prototype)?.constructor}get parentRegistration(){return null==this.ParentClass?null:f.getOrCreate(this.ParentClass)}ancestry(){if(null==this.ParentClass)return[];{const t=f.getOrCreate(this.ParentClass);return[t,...t.ancestry()]}}ancestryFeatures(){return this.ancestry().flatMap((({features:t})=>t))}bindContract(t){if(this.contract=t,!t[n])return;const e=this.Class.prototype;this.features.forEach((t=>{const{name:s,hasGetter:r,hasSetter:n,isMethod:o}=t;Object.defineProperty(e,s,{enumerable:!0,...r?{get:g(s,t.getter,this)}:{},...n?{set:g(s,t.setter,this)}:{},...o?{value:g(s,t.value,this)}:{}}),t.descriptor=Object.getOwnPropertyDescriptor(e,s)}))}findFeature(t){return this.features.find((({name:e})=>e===t))??this.parentRegistration?.findFeature(t)}},b=function t(e){for(const[,s]of Object.entries(e))null!=s&&"object"==typeof s&&t(s);Object.freeze(e)},C=class{classRegistration;name;#s;constructor(t,e,s){this.classRegistration=t,this.name=e,this.#s=s}get ancestorFeature(){return this.classRegistration.ancestryFeatures().filter((t=>t.name===this.name))[0]}get getter(){return this.#s.get}get hasGetter(){return this.isAccessor&&null!=this.#s.get}get hasSetter(){return this.isAccessor&&null!=this.#s.set}get isProperty(){return"function"!=typeof this.#s.value&&void 0!==this.#s.value}get isMethod(){return"function"==typeof this.#s.value}get isAccessor(){return void 0===this.#s.value}get memberType(){return this.isMethod?"method":this.isProperty?"property":"accessor"}get setter(){return this.#s.set}get value(){return this.#s.value}get descriptor(){return this.#s}set descriptor(t){this.#s=t}},m=function t(e,s){return e.length&&s(e[0])?[e[0],...t(e.slice(1),s)]:[]},O=()=>!0,v=Symbol("isContracted"),w=Symbol("innerContract"),M=function(t=new a){return function(e,s){if("class"!==s.kind)throw new TypeError(p.MsgNotContracted);if(P(!Object.getOwnPropertySymbols(e).includes(v),p.MsgSingleContract),!1===t[n])return e;const r=e[w];P(!r||r&&t[i]instanceof r.constructor,p.MsgBadSubcontract);class o extends e{static[v]=!0;constructor(...t){super(...t);const s=this.constructor,r=f.getOrCreate(s);var n;if(P((n=r,!Object.entries(Object.getOwnPropertyDescriptors(this)).some((([t,e])=>new C(n,t,e).isProperty))),p.MsgNoProperties),!r.contractsChecked){const t=m(r.ancestry(),(t=>t.Class!==e));[r,...t,f.get(e)].forEach((t=>{t.bindContract(o[w])}))}return h(this,o[w]),this}static get[w](){return t}get[w](){return t}}return f.getOrCreate(o).contractsChecked=!1,Object.freeze(e),o}};function P(t,e=p.AssertionFailed,s=r){if(0==Boolean(t))throw new s(e)}function j(t,e){return!t||e}var S=e.pf,R=e.NZ,$=e.eR,A=e.vA,x=e.zf,k=e.X$,E=e.M0,F=e.JG,N=e.V1;export{S as AssertionError,R as Contract,$ as Contracted,A as assert,x as checkedMode,k as extend,E as implies,F as innerContract,N as invariant};
|
|
1
|
+
Symbol.metadata??=Symbol.for("Symbol.metadata");class t extends Error{name="AssertionError";violation;constructor(t,e){super(t),this.violation=e}}const e=new WeakMap,n=t=>"object"==typeof t&&null!==t&&"~standard"in t,r=t=>{if(n(t)){const{vendor:e,version:n}=t["~standard"];return`Standard Schema (vendor: ${String(e)}, version: ${String(n)})`}return String(t)},o=(t,e,r)=>{if(r?.normalize&&!n(t))throw new TypeError(`${e} cannot normalize: only a Standard Schema arm produces a replacement value.`)},a=(t,e,r,o,a,i)=>n(t)?c(t,e.schema(),r,o,a,i):s(t,e.predicate(),r,o,a),s=(t,n,r,o,a)=>{const[s,...c]=n;return{ok:l(t("object"==typeof s&&null!==s?(t=>{const n=e.get(t);if(n)return n;const r=new Proxy(t,{set(t,e){throw new TypeError(`A contract predicate may not assign '${String(e)}'. Contract predicates answer a question; they must not change the state they are asked about.`)},deleteProperty(t,e){throw new TypeError(`A contract predicate may not delete '${String(e)}'. Contract predicates answer a question; they must not change the state they are asked about.`)},defineProperty(){throw new TypeError("A contract predicate may not define properties. Contract predicates answer a question; they must not change the state they are asked about.")}});return e.set(t,r),r})(s):s,...c),r,o,a)}},c=(t,e,n,r,o,a)=>{const s=t["~standard"].validate(e);if("function"==typeof s?.then)throw new TypeError(`${n} schema #${o+1} for ${r} returned a Promise; contract evaluation is synchronous, so use a synchronous schema.`);return s.issues?{ok:!1,issues:s.issues}:a?.normalize?{ok:!0,value:s.value}:{ok:!0}};function i(e,n="Assertion Error"){if(0==Boolean(e))throw new t(n)}const u=t=>"object"==typeof t&&null!==t&&"function"==typeof t.then?"a Promise (contract predicates must be synchronous)":"string"==typeof t?`the string ${JSON.stringify(t)}`:void 0===t?"undefined":null===t?"null":"object"==typeof t?`an object (${Object.prototype.toString.call(t)})`:`a ${typeof t} (${String(t)})`;function l(t,e,n,r){return i("boolean"==typeof t,`${e} predicate #${r+1} for ${n} returned ${u(t)}; contract predicates must return a boolean`),t}function d(t,e,r,o,a,s,c,i=String){const u={contract:t,className:e,feature:r,failedIndices:a,predicates:a.map(t=>i(o[t])),...c&&c.length>0?{issues:c}:{}},l=void 0===r?e:`${e}.${r}`,d=t=>n(t)?"schema":"predicate",f=u.predicates.map((t,e)=>{const n=o[a[e]];return`${d(n)} #${a[e]+1}: ${t}`}).join("; ");var p,m,y,h,g;return{message:`${t} failed for ${l} (${m=a.length,y=o.length,h=d(o[0]),p=o[0],g=n(p)?"schemas":"predicates",`${m} of ${y} ${1===y?h:g}`} unsatisfied: ${f}).${c&&c.length>0?` Reported: ${c.map(t=>(t=>{const e=(t.path??[]).map(t=>"object"==typeof t&&null!==t?t.key:t).join(".");return e?`${e}: ${t.message}`:t.message})(t)).join("; ")}.`:""} ${s}`,violation:u}}function f(e,n,r,o,a,s,c,i=String){const{message:u,violation:l}=d(e,n,r,o,a,s,c,i);return new t(u,l)}function p(t,e){return Boolean(t&&e||!t&&!e)}function m(t,e){return!t||Boolean(e)}function y(t,e){if(!W[P])return;const n=t[Symbol.metadata]?.invariants??[],o=[],s=[];for(const[r,c]of n.entries()){const n=a(c.arm,{predicate:()=>[e],schema:()=>e},"@invariant",t.name,r,c.options);n.ok||(o.push(r),n.issues&&s.push(...n.issues))}if(0!==o.length)throw f("@invariant",t.name,void 0,n.map(t=>t.arm),o,"The instance left the invariant unsatisfied.",s,r)}const h=(t,e)=>(n,{kind:r,metadata:o})=>{i("class"===r,"@invariant decorator can only be applied to classes"),i(n.prototype instanceof W,"@invariant decorator can only be applied to classes that extend Contracted");const a=o.invariants??[];o.invariants=[...a,{arm:t,options:e}]};function g(t,e,n){i(["method","getter","setter"].includes(n.kind),`${t} decorator can only be applied to methods, getters, or setters`),i(!1===n.static,`${t} decorator cannot be applied to static features`),i(!1===n.private,`${t} decorator cannot be applied to private features`),i(!String(n.name).startsWith("_"),`${t} decorator cannot be applied to private/protected features`),n.addInitializer(function(){i(this instanceof W,`${t} decorator can only be applied to classes that extend Contracted`)})}const w=(t,e)=>(n,r)=>{g("@demands",0,r),o(t,"@demands",e);const a=[...r.metadata?.demands?.[r.name]??[],{arm:t,options:e}];r.metadata.demands={...r.metadata?.demands??{},[r.name]:a}};function b(t,e,n){if(!W[P])return n;const o=t.constructor,s=o[Symbol.metadata]?.demands?.[e]??[];if(0===s.length)return n;const c=`${t.constructor.name}.${String(e)}`,i=[],u=[];for(const[e,{arm:r,options:o}]of s.entries()){const s=a(r,{predicate:()=>[t,n],schema:()=>n},"@demands",c,e,o);if(s.ok)return void 0===s.value?n:s.value;i.push(e),s.issues&&u.push(...s.issues)}throw f("@demands",t.constructor.name,String(e),s.map(t=>t.arm),i,"A precondition was not satisfied, so the feature was not entered.",u,r)}const v=(t,e)=>(n,r)=>{g("@ensures",0,r),o(t,"@ensures",e);const a=[...r.metadata?.ensures?.[r.name]??[],{arm:t,options:e}],s=a.filter(t=>t.options?.normalize);if(s.length>1)throw new TypeError(`@ensures for ${String(r.name)} declares ${s.length} normalizing arms; at most one arm may normalize the result, because they would disagree about what the caller receives.`);r.metadata.ensures={...r.metadata?.ensures??{},[r.name]:a}};function $(t,e,n,o,s){if(!W[P])return s;const c=t.constructor,i=c[Symbol.metadata]?.ensures?.[n]??[];if(0===i.length)return s;const u=`${t.constructor.name}.${String(n)}`,l=[],d=[];let p=s;for(const[n,r]of i.entries()){const c=a(r.arm,{predicate:()=>[t,o,e],schema:()=>s},"@ensures",u,n,r.options);c.ok?void 0!==c.value&&(p=c.value):(l.push(n),c.issues&&d.push(...c.issues))}if(0===l.length)return p;throw f("@ensures",t.constructor.name,String(n),i.map(t=>t.arm),l,"A postcondition was not satisfied after the feature ran.",d,r)}const S=(t,e)=>(n,r)=>{g("@rescue",0,r),i(void 0===e?.maxRetries||e.maxRetries>=0,"maxRetries must not be negative"),r.metadata.rescue={...r.metadata?.rescue??{},[r.name]:{handler:t,maxRetries:e?.maxRetries}},r.addInitializer(function(){i(this instanceof W,"@rescue decorator can only be applied to classes that extend Contracted")})};function j(t,e){let n=t.constructor;for(;n&&n!==Function.prototype;){const t=n[Symbol.metadata]?.rescue?.[e];if(t)return t;n=Object.getPrototypeOf(n)}}const O=(t,e,n,r)=>{if(!W[P])throw n;const o=j(t,e);if(!o)throw n;let a=!1,s=[];if(o.handler.call(t,t,n,r,(...t)=>{i(!a,"retry can only be called once per rescue execution"),a=!0,s=t}),!a)throw n;return s},P=Symbol.for("Contracted.checkedMode"),x=(t,e)=>{if("object"!=typeof t||null===t)return t;const n=e.get(t);if(void 0!==n)return n;if(t instanceof Date)return new Date(t.getTime());if(Array.isArray(t)){const n=[];e.set(t,n);for(const r of t)n.push(x(r,e));return n}if(t instanceof Map){const n=new Map;e.set(t,n);for(const[r,o]of t)n.set(x(r,e),x(o,e));return n}if(t instanceof Set){const n=new Set;e.set(t,n);for(const r of t)n.add(x(r,e));return n}if(!(t=>{const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e})(t))return t;const r=Object.create(Object.getPrototypeOf(t));e.set(t,r);for(const n of Reflect.ownKeys(t)){const o=Object.getOwnPropertyDescriptor(t,n);Reflect.defineProperty(r,n,"value"in o?{...o,value:x(o.value,e)}:o)}return r},R=t=>{if(!W[P])return;const e=Object.create(t),n=new WeakMap;for(const r of Reflect.ownKeys(t)){const o=Object.getOwnPropertyDescriptor(t,r);Reflect.defineProperty(e,r,"value"in o?{...o,value:x(o.value,n)}:o)}return e},k=t=>{switch(t.constructor.name){case"AsyncFunction":return"async";case"GeneratorFunction":return"generator";case"AsyncGeneratorFunction":return"async-generator";default:return"sync"}},C=new WeakMap;function E(t,e){let n=t;for(;n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(t)return t;n=Object.getPrototypeOf(n)}}const A=(t,e,n)=>"get"===t?[e]:n,T=(t,e)=>"get"===t?[]:e;function _(t,e,n,r,o,a){if(o>=(j(e,n)?.maxRetries??1/0))throw y(t,e),r;try{return O(e,n,r,a)}catch(n){throw y(t,e),n}}function z(t,e,n,r,o,a="sync"){return"async"===a?async function(t,e,n,r,o){const a=e.constructor,s=(a[Symbol.metadata]?.ensures?.[n]??[]).length>0;let c=r,i=0;for(;;){const r=s?R(e):void 0;let u;y(a,e),c=b(e,n,c);try{u=await o(c),s&&(u=$(e,r,n,A(t,u,c),u))}catch(r){c=_(a,e,n,r,i,T(t,c)),i++;continue}return y(a,e),u}}(t,e,n,r,o):"generator"===a||"async-generator"===a?function(t,e,n,r,o){const a=t.constructor,s=(a[Symbol.metadata]?.ensures?.[e]??[]).length>0;let c,i,u=n,l=0,d=!0;const f=n=>(y(a,t),d?(d=!1,b(t,e,u)):n.length>0?b(t,e,n):n),p=(n,r)=>{s&&$(t,r,e,[n],n),y(a,t),i=void 0},m=()=>{if(y(a,t),void 0===i)return;const e=i;throw i=void 0,e},h=n=>{u=_(a,t,e,n,l,u),l++,c=r(u),d=!0,i=n},g=(e,n)=>{for(;;)try{n=f(n);const r=s?R(t):void 0,o=e(c,n);return o.done?(m(),o):(p(o.value,r),o)}catch(t){h(t)}},w=async(e,n)=>{for(;;)try{n=f(n);const r=s?R(t):void 0,o=await e(c,n);return o.done?(m(),o):(p(o.value,r),o)}catch(t){h(t)}};y(a,t),u=b(t,e,u),d=!1,c=r(u);const v={};return"generator"===o?(v.next=function(...t){return g((t,e)=>t.next(e[0]),t)},v.return=function(...t){return g((e,n)=>e.return(t[0]??n[0]),[])},v.throw=function(...t){return g((e,n)=>e.throw(t[0]??n[0]),[])},v[Symbol.iterator]=function(){return this}):(v.next=function(...t){return w((t,e)=>t.next(e[0]),t)},v.return=function(...t){return w((e,n)=>e.return(t[0]??n[0]),[])},v.throw=function(...t){return w((e,n)=>e.throw(t[0]??n[0]),[])},v[Symbol.asyncIterator]=function(){return this}),v}(e,n,r,o,a):function(t,e,n,r,o){const a=e.constructor,s=(a[Symbol.metadata]?.ensures?.[n]??[]).length>0;let c=r,i=0;for(;;){const r=s?R(e):void 0;let u;y(a,e),c=b(e,n,c);try{u=o(c),M(u,e,n),s&&(u=$(e,r,n,A(t,u,c),u))}catch(r){c=_(a,e,n,r,i,T(t,c)),i++;continue}return y(a,e),u}}(t,e,n,r,o)}const M=(e,n,r)=>{if(null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then)throw new t(`${n.constructor.name}.${String(r)} returned a promise but is not declared 'async', so its contracts were evaluated before its body finished. Declare the feature 'async'.`)},D={get(t,e,n){if(!W[P])return Reflect.get(t,e,n);const r=E(Object.getPrototypeOf(t),e);if("function"==typeof r?.value){let n=C.get(t);n||(n=new Map,C.set(t,n));const o=n.get(e);if(o)return o;const a=k(r.value),s=function(...n){return z("func",t,e,n,e=>Reflect.apply(r.value,t,e),a)};return n.set(e,s),s}return"function"==typeof r?.get?z("get",t,e,[],()=>r.get.call(t),k(r.get)):Reflect.get(t,e,n)},set(t,e,n,r){if(!W[P])return Reflect.set(t,e,n,r);const o=E(Object.getPrototypeOf(t),e);if(!(o&&"function"==typeof o.set||"string"!=typeof e||e.startsWith("_")))throw new TypeError(`Cannot assign to property '${String(e)}': only properties starting with '_' or with a setter can be set on Contracted instances.`);const a="function"==typeof o?.set?o.set:void 0;return z("set",t,e,[n],n=>a?(a.call(t,n[0]),!0):Reflect.set(t,e,n[0],r)),!0},deleteProperty(t,e){if(!W[P])return Reflect.deleteProperty(t,e);if("string"==typeof e&&!e.startsWith("_"))throw new TypeError(`Cannot delete property '${String(e)}' from Contracted instances: only properties starting with '_' can be deleted.`);return z("delete",t,e,[],()=>Reflect.deleteProperty(t,e))}};class W{static[Symbol.metadata];static _allowedConstructions=0;static[P]=!0;static new(...t){const e=this._allowedConstructions;this._allowedConstructions=e+1;try{const e=new this(...t);return y(this,e),new Proxy(e,D)}finally{this._allowedConstructions=e}}constructor(...t){const e=this.constructor;if(e._allowedConstructions<=0)throw new TypeError("Use the static 'new' method to instantiate this class.");e._allowedConstructions--}}export{t as AssertionError,W as Contracted,O as applyRescueHandler,i as assert,l as assertContractResult,b as assertDemands,$ as assertEnsures,y as assertInvariants,P as checkedMode,w as demands,d as describeViolation,v as ensures,j as getRescueDeclaration,p as iff,m as implies,h as invariant,S as rescue,f as violationError};
|
|
3
2
|
//# sourceMappingURL=index.mjs.map
|