@final-hill/decorator-contracts 1.0.0 → 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.
@@ -1,5 +1,54 @@
1
+ import type { StandardSchemaV1 } from './standard-schema.mjs';
1
2
  /**
2
- * An AssertionError represents a failed assertion with an associated message
3
+ * The contract kinds that can raise an {@link AssertionError}.
4
+ */
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.
3
42
  */
4
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);
5
54
  }
@@ -1,16 +1,28 @@
1
1
  import { InvariantPredicate } from './invariant.mjs';
2
2
  import { DemandsPredicate } from './demands.mjs';
3
3
  import { EnsuresPredicate } from './ensures.mjs';
4
- import { RescueHandler } from './rescue.mjs';
4
+ import { RescueDeclaration } from './rescue.mjs';
5
5
  export declare const checkedMode: unique symbol;
6
6
  export declare class Contracted {
7
7
  static [Symbol.metadata]: {
8
8
  invariants: InvariantPredicate<typeof Contracted>[];
9
9
  demands: Record<PropertyKey, DemandsPredicate<Contracted>[]>;
10
10
  ensures: Record<PropertyKey, EnsuresPredicate<Contracted>[]>;
11
- rescue: Record<PropertyKey, RescueHandler<Contracted>>;
11
+ rescue: Record<PropertyKey, RescueDeclaration<Contracted>>;
12
12
  };
13
- protected static _allowConstruction: boolean;
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;
14
26
  static [checkedMode]: boolean;
15
27
  static new<C extends typeof Contracted, Args extends ConstructorParameters<C>>(this: C, ...args: Args): InstanceType<C>;
16
28
  constructor(..._args: any[]);
@@ -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,3 +1,5 @@
1
+ import { AssertionError, type ContractKind, type ContractViolation } from "./AssertionError.mjs";
2
+ import type { StandardSchemaV1 } from './standard-schema.mjs';
1
3
  /**
2
4
  * An assertion is an expression of a property that must be true at a particular
3
5
  * point of step of program execution. It consists of a boolean expression
@@ -18,3 +20,54 @@
18
20
  * ```
19
21
  */
20
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;
@@ -1,6 +1,54 @@
1
1
  import { Contracted } from "./Contracted.mjs";
2
+ import { type ArmOptions } from './admissibility.mjs';
3
+ import type { StandardSchemaV1 } from './standard-schema.mjs';
2
4
  import type { FeatureDecoratorContext } from './types.mjs';
3
- export type DemandsPredicate<This extends Contracted> = (self: This, ...args: any[]) => boolean;
4
- export type DemandsDecorator = <This extends Contracted, Feature = unknown>(predicate: DemandsPredicate<This>) => (value: Feature, context: FeatureDecoratorContext) => Feature | void;
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
+ }
5
39
  export declare const demands: DemandsDecorator;
6
- export declare function assertDemands(instance: Contracted, propertyKey: PropertyKey, ...args: any[]): void;
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[];
@@ -1,6 +1,39 @@
1
1
  import { Contracted } from './Contracted.mjs';
2
+ import { type ArmOptions } from './admissibility.mjs';
3
+ import type { StandardSchemaV1 } from './standard-schema.mjs';
2
4
  import type { FeatureDecoratorContext } from './types.mjs';
3
- export type EnsuresPredicate<This extends Contracted> = (self: This, args: any[], old: This) => boolean;
4
- export type EnsuresDecorator = <This extends Contracted>(predicate: EnsuresPredicate<This>) => (value: unknown, context: FeatureDecoratorContext) => void;
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
+ }
5
28
  export declare const ensures: EnsuresDecorator;
6
- export declare function assertEnsures(instance: Contracted, old: Contracted, propertyKey: PropertyKey, args: any): void;
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
@@ -7,7 +7,12 @@
7
7
  *
8
8
  * @param p - The first boolean value (the antecedent).
9
9
  * @param q - The second boolean value (the consequent).
10
- * @returns - The result (biconditional) of p and q.
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.
11
16
  *
12
17
  * @example
13
18
  * ```ts
@@ -7,7 +7,10 @@
7
7
  *
8
8
  * @param p - The first boolean value (the antecedent).
9
9
  * @param q - The second boolean value (the consequent).
10
- * @returns - The result (material implication) of p and q.
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}.
11
14
  *
12
15
  * @example
13
16
  * ```ts
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './types.mjs';
2
+ export * from './standard-schema.mjs';
2
3
  export * from "./AssertionError.mjs";
3
4
  export * from "./assert.mjs";
4
5
  export * from './iff.mjs';
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- Symbol.metadata??=Symbol.for("Symbol.metadata");class t extends Error{}function e(e,r="Assertion Error"){if(0==Boolean(e))throw new t(r)}function r(t,e){return t&&e||!t&&!e}function n(t,e){return!t||e}function a(t,r){if(!h[u])return;h[u]=!1;const n=t[Symbol.metadata]?.invariants??[];try{for(const a of n)e(a(r),`Invariant violated in class ${t.name}: ${a.toString()}`)}finally{h[u]=!0}}const o=t=>(r,{kind:n,metadata:a})=>{e("class"===n,"@invariant decorator can only be applied to classes"),e(r.prototype instanceof h,"@invariant decorator can only be applied to classes that extend Contracted");const o=a.invariants??[];a.invariants=[...o,t]},s=t=>(r,n)=>{e(["method","getter","setter"].includes(n.kind),"@demands decorator can only be applied to methods, getters, or setters"),e(!1===n.static,"@demands decorator cannot be applied to static features"),e(!1===n.private,"@demands decorator cannot be applied to private/protected features"),e(!String(n.name).startsWith("_"),"@demands decorator cannot be applied to private/protected features"),n.addInitializer((function(){e(this instanceof h,"@demands decorator can only be applied to classes that extend Contracted");const r=[...n.metadata?.demands?.[n.name]??[],t];n.metadata.demands={...n.metadata?.demands??{},[n.name]:r}}))};function c(t,r,...n){if(!h[u])return;h[u]=!1;const a=t.constructor,o=a[Symbol.metadata]?.demands?.[r]??[];try{if(0===o.length)return;for(const e of o)if(e(t,...n))return;e(!1,`No demands were satisfied for ${t.constructor.name}.${String(r)}`)}finally{h[u]=!0}}const i=t=>(r,n)=>{e(["method","getter","setter"].includes(n.kind),"@ensures decorator can only be applied to methods, getters, or setters"),e(!1===n.static,"@ensures decorator cannot be applied to static features"),e(!1===n.private,"@ensures decorator cannot be applied to private features"),e(!String(n.name).startsWith("_"),"@ensures decorator cannot be applied to private/protected features"),n.addInitializer((function(){e(this instanceof h,"@ensures decorator can only be applied to classes that extend Contracted");const r=[...n.metadata?.ensures?.[n.name]??[],t];n.metadata.ensures={...n.metadata?.ensures??{},[n.name]:r}}))};function d(t,r,n,a){if(!h[u])return;h[u]=!1;const o=t.constructor,s=o[Symbol.metadata]?.ensures?.[n]??[];try{if(0===s.length)return;for(const o of s)o(t,a,r)||e(!1,`No ensurances were satisfied for ${t.constructor.name}.${String(n)}`)}finally{h[u]=!0}}const l=t=>(r,n)=>{e(["method","getter","setter"].includes(n.kind),"@rescue decorator can only be applied to methods, getters, or setters"),e(!1===n.static,"@rescue decorator cannot be applied to static features"),e(!1===n.private,"@rescue decorator cannot be applied to private features"),e(!String(n.name).startsWith("_"),"@rescue decorator cannot be applied to private/protected features"),n.addInitializer((function(){e(this instanceof h,"@rescue decorator can only be applied to classes that extend Contracted"),n.metadata.rescue={...n.metadata?.rescue??{},[n.name]:t}}))},f=(t,r,n,a,o)=>{if(!h[u])return a;const s=r.constructor,c=Object.getOwnPropertyDescriptor(s.prototype,n),i=s[Symbol.metadata]?.rescue?.[n];if(!i)throw a;let d,l=!1;h[u]=!1;try{if(i.call(r,r,a,o,((...a)=>{e(!l,"retry can only be called once"),l=!0,h[u]=!0,"get"==t?d=Reflect.get(r,n,r):"set"==t?d=Reflect.set(r,n,a[0],r):"func"==t&&(d=Reflect.apply(c.value,r,a))})),!l)throw a}finally{h[u]=!0}return d},u=Symbol.for("Contracted.checkedMode"),p=t=>{if(!h[u])return;h[u]=!1;const e=Object.create(t);for(const r in t)Reflect.set(e,r,Reflect.get(t,r));return h[u]=!0,e};function y(t,e){let r=t;for(;r&&r!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(r,e);if(t)return t;r=Object.getPrototypeOf(r)}}const m={get(t,e,r){if(!h[u])return Reflect.get(t,e,r);const n=t.constructor,o=y(Object.getPrototypeOf(t),e),s=(n[Symbol.metadata]?.ensures?.[e]??[]).length>0,i=s?p(t):void 0;if("function"==typeof o?.value)return function(...r){let l;a(n,t),c(t,e,r);try{l=Reflect.apply(o.value,t,r),s&&d(t,i,e,r)}catch(n){l=f("func",t,e,n,r)}finally{a(n,t)}return l};if("function"==typeof o?.get){let o;a(n,t),c(t,e,[]);try{o=Reflect.get(t,e,r),s&&d(t,i,e,[o])}catch(r){o=f("get",t,e,r,[])}finally{a(n,t)}return o}return Reflect.get(t,e,r)},set(t,e,r,n){if(!h[u])return Reflect.set(t,e,r,n);const o=y(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 s=t.constructor,i=(s[Symbol.metadata]?.ensures?.[e]??[]).length>0,l=i?p(t):void 0;let m;a(s,t),c(t,e,[r]);try{m=Reflect.set(t,e,r,n),i&&d(t,l,e,[r])}catch(n){m=f("set",t,e,n,[r])}finally{a(s,t)}return m},deleteProperty(t,e){throw new TypeError(`Cannot delete property '${String(e)}' from Contracted instances.`)}};class h{static[Symbol.metadata];static _allowConstruction=!1;static[u]=!0;static new(...t){this._allowConstruction=!0;try{const e=new this(...t);return a(this,e),new Proxy(e,m)}finally{this._allowConstruction=!1}}constructor(...t){if(!this.constructor._allowConstruction)throw new TypeError("Use the static 'new' method to instantiate this class.")}}export{t as AssertionError,h as Contracted,f as applyRescueHandler,e as assert,c as assertDemands,d as assertEnsures,a as assertInvariants,u as checkedMode,s as demands,i as ensures,r as iff,n as implies,o as invariant,l as rescue};
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};
2
2
  //# sourceMappingURL=index.mjs.map