@final-hill/decorator-contracts 2.0.0 → 3.1.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.
@@ -13,7 +13,14 @@ export type ContractKind = '@invariant' | '@demands' | '@ensures';
13
13
  export interface ContractViolation {
14
14
  /** Which contract failed. */
15
15
  contract: ContractKind;
16
- /** The class the contract belongs to. */
16
+ /**
17
+ * The class the contract belongs to.
18
+ *
19
+ * This is the class's declared `contractName` when it has one, and the
20
+ * constructor's name otherwise — which is the build's output rather than the
21
+ * author's declaration, and degrades under minification. Declare a name for a
22
+ * `className` that survives a production build.
23
+ */
17
24
  className: string;
18
25
  /** The feature the contract belongs to, absent for `@invariant`. */
19
26
  feature?: string;
@@ -24,6 +31,26 @@ export interface ContractViolation {
24
31
  * `@invariant` are AND-composed, so a failure lists the one that broke.
25
32
  */
26
33
  failedIndices: number[];
34
+ /**
35
+ * The indices of the arms that failed by throwing, in evaluation order.
36
+ *
37
+ * Absent when every failing arm reported a verdict. An arm that throws is a
38
+ * failed arm, so it also appears in {@link ContractViolation.failedIndices};
39
+ * this field separates the arms that threw from the arms that returned
40
+ * `false`, which is how a deliberate throw is told apart from a predicate bug.
41
+ */
42
+ thrownIndices?: number[];
43
+ /**
44
+ * Descriptions of the values thrown by the failing arms, aligned with
45
+ * `thrownIndices`.
46
+ *
47
+ * These are strings rather than the values themselves. The rest of this record
48
+ * is plain data, and a violation is logged, retained, and serialised; holding a
49
+ * reference to the consumer's error would keep it alive and could make the
50
+ * record unserialisable. The value the contract re-raised is the error the
51
+ * caller caught, which is where they read it.
52
+ */
53
+ thrown?: string[];
27
54
  /** The source text of the failing arms, aligned with `failedIndices`. */
28
55
  predicates: string[];
29
56
  /**
@@ -1,15 +1,47 @@
1
- import { InvariantPredicate } from './invariant.mjs';
2
- import { DemandsPredicate } from './demands.mjs';
3
- import { EnsuresPredicate } from './ensures.mjs';
4
- import { RescueDeclaration } from './rescue.mjs';
1
+ import type { ContractMetadata } from './metadata.mjs';
5
2
  export declare const checkedMode: unique symbol;
3
+ /**
4
+ * The switch for encapsulation, independent of {@link checkedMode}.
5
+ *
6
+ * Encapsulation is the `set`, `defineProperty`, and `deleteProperty` traps: the
7
+ * rule that an external caller may not mutate state without a postcondition to
8
+ * catch it. Contracts are whether `@invariant`, `@demands`, `@ensures`, and
9
+ * `@rescue` are evaluated at all.
10
+ *
11
+ * They are separate because they answer different questions. A test double or a
12
+ * plain data holder wants the contract checks off while still refusing an
13
+ * assignment to a field it never declared. A class that is deliberately
14
+ * configured with its state exposed wants the reverse. A single switch cannot
15
+ * express either, because it would have to answer both at once.
16
+ *
17
+ * A class opts out by assigning a static, exactly as with {@link checkedMode}, and
18
+ * the nearest declaration on the class chain wins.
19
+ */
20
+ export declare const encapsulationMode: unique symbol;
21
+ /**
22
+ * Whether the contracts of `Class` are evaluated.
23
+ *
24
+ * @internal
25
+ * Exported only because the four contract modules live in their own files and
26
+ * import it. It takes a constructor rather than an instance because the caller
27
+ * often has one without the other, and it is not part of the published surface.
28
+ */
29
+ export declare const contractsEnabled: (Class: unknown) => boolean;
6
30
  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
- };
31
+ /**
32
+ * The contracts declared on this class, keyed by the feature they belong to.
33
+ *
34
+ * `undefined` when the class declares none, because the metadata record is
35
+ * created by the first decorator to run rather than by the class itself.
36
+ *
37
+ * Read it through {@link getContractMetadata} rather than indexing this symbol:
38
+ * the accessor returns copies, so a consumer cannot corrupt the contracts a
39
+ * class is checked against by mutating what it was handed.
40
+ *
41
+ * The shape is stable for the major version. Fields may be added, but an
42
+ * existing field will not change meaning without one.
43
+ */
44
+ static [Symbol.metadata]: ContractMetadata | undefined;
13
45
  /**
14
46
  * Grants permission for exactly one `Contracted` constructor call.
15
47
  *
@@ -23,7 +55,37 @@ export declare class Contracted {
23
55
  * constructor call it implicitly; classes that do must call `super()` once.
24
56
  */
25
57
  protected static _allowedConstructions: number;
58
+ /**
59
+ * Whether the contracts declared on this class are evaluated.
60
+ *
61
+ * Assign it on a class to opt that class — and any class extending it that
62
+ * does not declare its own — out of `@invariant`, `@demands`, `@ensures`, and
63
+ * `@rescue`, without affecting a sibling or the rest of the process:
64
+ *
65
+ * ```typescript
66
+ * class DataHolder extends Contracted {
67
+ * static [checkedMode] = false;
68
+ * }
69
+ * ```
70
+ *
71
+ * It is separate from {@link encapsulationMode} so a class can keep the write
72
+ * protection while skipping the checks. Both default to `true`, and the
73
+ * nearest declaration on the class chain decides.
74
+ *
75
+ * Set it **through the class**. An instance write would land on the raw target,
76
+ * where no trap can refuse it.
77
+ */
26
78
  static [checkedMode]: boolean;
79
+ /**
80
+ * Whether an external write, definition, or deletion on this class's instances
81
+ * is trapped.
82
+ *
83
+ * Assign it on a class exactly as {@link checkedMode}, with the same scope: the
84
+ * class and the subclasses that do not declare their own. Disabling it makes
85
+ * the instance behave like a plain object for mutation, while the contracts
86
+ * still run when `checkedMode` is left on.
87
+ */
88
+ static [encapsulationMode]: boolean;
27
89
  static new<C extends typeof Contracted, Args extends ConstructorParameters<C>>(this: C, ...args: Args): InstanceType<C>;
28
90
  constructor(..._args: any[]);
29
91
  }
@@ -1,14 +1,36 @@
1
+ import type { ContractViolation } from './AssertionError.mjs';
1
2
  import type { StandardSchemaV1 } from './standard-schema.mjs';
3
+ /**
4
+ * Converts a failed contract into the error its caller receives.
5
+ *
6
+ * It is called once, after **every** arm has failed, with the structured
7
+ * violation. That position is the whole reason the option exists: a predicate
8
+ * must not throw, because an arm that throws is one opinion that the call should
9
+ * not proceed rather than an abort of the composition, so a typed error cannot be
10
+ * raised from inside one. A factory runs where the decision is already made.
11
+ *
12
+ * The return value must be an object. The violation and the `AssertionError` that
13
+ * describes every unsatisfied arm are attached to it, so an error that could carry
14
+ * neither would silently lose the contract details.
15
+ */
16
+ export type ViolationFactory = (violation: ContractViolation) => object;
2
17
  /**
3
18
  * The result of checking a subject against one contract arm.
4
19
  *
5
20
  * Predicates and schemas are adapted to this shape so that the composition rule
6
21
  * in each contract — OR for `@demands`, AND for `@invariant` and `@ensures` — is
7
22
  * written once rather than twice.
23
+ *
24
+ * An arm that threw reports `ok: false` with the thrown value preserved in
25
+ * `thrown`. Composition continues past it: an `@demands` arm that throws is one
26
+ * opinion that the call should not proceed, and a later arm may still permit it.
27
+ * Keeping the value instead of letting it propagate is what makes an arm's own
28
+ * error reachable without making the composition rule unreachable.
8
29
  */
9
30
  export type Admissibility = {
10
31
  ok: boolean;
11
32
  value?: unknown;
33
+ thrown?: unknown;
12
34
  issues?: ReadonlyArray<StandardSchemaV1.Issue>;
13
35
  };
14
36
  /** Options a decorator accepts alongside an arm. */
@@ -22,6 +44,92 @@ export interface ArmOptions {
22
44
  * validation. Only a schema can normalize.
23
45
  */
24
46
  normalize?: boolean;
47
+ /**
48
+ * Build the error raised when the arm's contract fails.
49
+ *
50
+ * Receives the full `ContractViolation`, because that record is the only
51
+ * machine-readable part of a failure: an error boundary or a metadata-driven
52
+ * test needs `failedIndices`, `thrownIndices`, and the schema `issues`, and a
53
+ * bare constructor would discard them.
54
+ *
55
+ * Scope is **per contract, not per arm.** When several arms declare a factory,
56
+ * the one belonging to the **first arm evaluated** decides, matching the rule
57
+ * that the first arm decides a normalized value. Arms evaluate in the contract's
58
+ * composition order — reverse source order within a class, inherited arms
59
+ * first — so the factory that wins is the one whose declaration is read first by
60
+ * the runtime.
61
+ *
62
+ * The returned error carries the violation as `violation` and the
63
+ * `AssertionError` describing every unsatisfied arm as `cause`, both
64
+ * non-enumerable. A factory that returns a non-object is refused when it runs,
65
+ * since neither field could be attached to it; what it produces depends on the
66
+ * violation, so there is nothing to check at decoration time. The guard admits
67
+ * anything `typeof` reports as an object, so an array passes and carries both
68
+ * fields — it is the author's choice whether an error boundary can branch on it.
69
+ *
70
+ * A `@rescue` that retries calls the factory once per failed attempt, because
71
+ * each attempt is a separate failure with its own violation.
72
+ */
73
+ onViolation?: ViolationFactory;
74
+ /**
75
+ * Suppress the warning a subclass `@demands` arm raises for narrowing.
76
+ *
77
+ * `@demands` is OR-composed, so an arm added below an inherited one cannot
78
+ * narrow the precondition — satisfying any inherited arm still permits the
79
+ * call. That is easy to misread as a restriction, so declaring an arm on a
80
+ * feature that already has inherited arms warns.
81
+ *
82
+ * The arm is a legal weakening, so the warning is a diagnostic and not a
83
+ * refusal. Set this when the weakening is what was meant.
84
+ *
85
+ * Only `@demands` reports it. `@ensures` and `@invariant` are AND-composed, so
86
+ * a subclass arm strengthens the obligation rather than appearing to restrict
87
+ * it, and those decorators **refuse** the option rather than accepting one that
88
+ * could never do anything.
89
+ */
90
+ allowWeakening?: boolean;
91
+ /**
92
+ * Allow the predicate to answer with a promise, which the lifecycle awaits
93
+ * before it decides the arm.
94
+ *
95
+ * Off by default, and off is load-bearing: a `Promise` is always truthy, so
96
+ * coercing a verdict that has not settled yet would treat a contract that has
97
+ * not been checked as satisfied. Accepting one only where the feature's own
98
+ * boundary is a promise keeps that rule intact — the check moves to the same
99
+ * microtask the exit checks already occupy.
100
+ *
101
+ * Only an `async` method qualifies. A synchronous feature has evaluated its
102
+ * contracts by the time a promise could settle; a generator hands the caller an
103
+ * iterator rather than a promise; and `@invariant` runs on every accessor read
104
+ * and write, where nothing can be awaited. Each of those refuses the option
105
+ * where it is written, and a schema arm refuses it too because `validate` is
106
+ * synchronous.
107
+ *
108
+ * A rejected predicate is a failed arm, exactly as a throwing predicate is: the
109
+ * rejection is recorded and composition continues, so a sibling `@demands` arm
110
+ * can still permit the call. Only a value that resolves to `true` or `false`
111
+ * decides anything.
112
+ *
113
+ * The cost is a window: the instance stays reachable across one more await
114
+ * boundary between the precondition and the body, so a concurrent caller can
115
+ * observe it in the state the precondition just approved.
116
+ */
117
+ awaitPredicate?: boolean;
118
+ }
119
+ /**
120
+ * The object a predicate is called with.
121
+ *
122
+ * A predicate takes one argument rather than a positional list, so a contract
123
+ * that supplies a field the predicate does not need costs nothing at the call
124
+ * site: the predicate destructures the fields it reads. Each contract publishes
125
+ * a precise version of this shape — `DemandsSubject`, `EnsuresSubject`,
126
+ * `InvariantSubject`, `RescueSubject` — and this is the part the runtime has in
127
+ * common.
128
+ */
129
+ export interface PredicateSubject {
130
+ /** The instance, replaced with a read-only view before the call. */
131
+ readonly self: unknown;
132
+ readonly [field: string]: unknown;
25
133
  }
26
134
  /**
27
135
  * The two subjects a contract arm can observe.
@@ -33,8 +141,8 @@ export interface ArmOptions {
33
141
  * convention.
34
142
  */
35
143
  export interface ArmSubjects {
36
- /** The arguments a predicate is called with. */
37
- predicate: () => any[];
144
+ /** The fields a predicate is called with. */
145
+ predicate: () => PredicateSubject;
38
146
  /** The value a schema arm validates. */
39
147
  schema: () => unknown;
40
148
  }
@@ -61,17 +169,258 @@ export declare const describeArm: (arm: unknown) => string;
61
169
  * a replacement value.
62
170
  */
63
171
  export declare const assertNormalizable: (arm: unknown, contract: string, options: ArmOptions | undefined) => void;
172
+ /**
173
+ * Rejects `normalize` on a contract that has nothing to replace.
174
+ *
175
+ * `@invariant` describes the instance, and an invariant predicate or schema answers
176
+ * a question about it; neither produces a value the runtime could substitute. The
177
+ * option was previously accepted here and silently ignored, which reads as a
178
+ * declared intention that is not in force. Rejecting it where it is written keeps
179
+ * the declaration and the behaviour in agreement.
180
+ */
181
+ export declare const assertNotNormalizable: (contract: string, options: ArmOptions | undefined) => void;
182
+ /**
183
+ * Rejects `awaitPredicate` on an arm that cannot answer with a promise.
184
+ *
185
+ * A schema's `validate` that returns a promise is refused when it runs, because
186
+ * contract evaluation is synchronous at that point. Accepting the option on a
187
+ * schema arm would therefore declare that waiting is in force when it is not, so
188
+ * the mistake is refused where it is written rather than on the first call.
189
+ */
190
+ export declare const assertAwaitableArm: (arm: unknown, contract: string, options: ArmOptions | undefined) => void;
191
+ /**
192
+ * Rejects `awaitPredicate` on a contract whose boundaries nothing can await.
193
+ *
194
+ * `@invariant` is evaluated on entry and exit of every feature, on both halves of
195
+ * an accessor, and once after construction. An accessor read has no promise for a
196
+ * caller to await, so the option could only be honoured where it is not needed and
197
+ * silently skipped where it is — an invisible semantic hole in the one contract
198
+ * that is supposed to hold always. Refusing it keeps the declaration and the
199
+ * behaviour in agreement, following `normalize` and `onViolation`.
200
+ */
201
+ export declare const assertNotAwaitable: (contract: string, options: ArmOptions | undefined) => void;
202
+ /**
203
+ * Rejects a factory that is not callable.
204
+ *
205
+ * The return value is checked when the factory runs, because what it produces
206
+ * depends on the violation it is given. What can be checked here is that the
207
+ * declaration names a function at all, which catches the mistake where it is
208
+ * written rather than on the first failed call.
209
+ */
210
+ export declare const assertViolationFactory: (contract: string, options: ArmOptions | undefined) => void;
211
+ /**
212
+ * Rejects a factory on a contract whose failure cannot carry one.
213
+ *
214
+ * `@invariant` is checked on entry, on exit, and once per construction, and its
215
+ * failure is what tells the lifecycle that the instance is in a state a `@rescue`
216
+ * handler must repair: `isInvariantFailure` in `Contracted.mts` recognises it as an
217
+ * `AssertionError` whose `violation.contract` is `'@invariant'`. An error built by
218
+ * a factory has neither, so a failure it raised would be re-tested, the factory
219
+ * called a second time, and the first error replaced by the second. The repair
220
+ * protocol would then act on an error the handler never saw.
221
+ *
222
+ * `@invariant` also has its own route to a typed error for a failure a feature
223
+ * raises: the entry and exit checks run inside the rescuable scope, so a `@rescue`
224
+ * handler observes the failure and can translate it. The check in `Contracted.new`
225
+ * is outside every handler — the constructor has returned and no feature is in
226
+ * play — so a class whose initial state violates an invariant reports an untyped
227
+ * `AssertionError`. `@demands` has no route at all, because a rejected precondition
228
+ * never enters a body, which is why the factory exists for it.
229
+ */
230
+ export declare const assertNotViolationFactory: (contract: string, options: ArmOptions | undefined) => void;
231
+ /**
232
+ * Picks the factory that decides a contract's error.
233
+ *
234
+ * Scope is per contract rather than per arm, so the arms have to agree on which
235
+ * declaration is authoritative. The **first arm evaluated** wins, matching the rule
236
+ * that the first passing arm decides a normalized value: an arm earlier in the
237
+ * composition is the one whose declaration the contract reads first, and an arm
238
+ * that declares no factory defers to the next.
239
+ *
240
+ * @param entries - The contract's registered arms, in evaluation order.
241
+ */
242
+ export declare const selectViolationFactory: (entries: ReadonlyArray<{
243
+ options?: ArmOptions;
244
+ }>) => ViolationFactory | undefined;
245
+ /**
246
+ * Rejects `allowWeakening` on a contract that never reports a weakening.
247
+ *
248
+ * The option suppresses a diagnostic about OR-composition, which only a
249
+ * precondition has. On an AND-composed contract it would be a declaration record
250
+ * that says something the runtime has no use for, discoverable only by reading the
251
+ * source, so it is refused at the point it is written rather than silently ignored.
252
+ *
253
+ * This follows the rule the other options already follow: `normalize` is refused
254
+ * where nothing can be replaced and `onViolation` where the failure must stay an
255
+ * `AssertionError`. An option that cannot act is a mistake about which contract
256
+ * the declaration belongs to.
257
+ *
258
+ * The test is for what the option would **do**, not for its presence, so
259
+ * `allowWeakening: false` is accepted: it asks for nothing, exactly as
260
+ * `normalize: false` is accepted on `@invariant`.
261
+ *
262
+ * @param contract - The contract name, for the message.
263
+ * @param options - The declaration's options.
264
+ * @internal
265
+ * Exported only because the AND-composed contract modules live in their own
266
+ * files and import it.
267
+ */
268
+ export declare const assertNotWeakenable: (contract: string, options: ArmOptions | undefined) => void;
269
+ /**
270
+ * The inherited precondition arms a class's new arm composes with.
271
+ *
272
+ * Read from the **metadata object's prototype**, not from
273
+ * `metadata.demands[feature]`. At the moment a decorator runs, that property still
274
+ * holds only what was inherited — the merged list is written afterwards — so both
275
+ * reads agree today. The prototype is used because it is the record the compiler
276
+ * gives each class for exactly this purpose — `Object.create(base[Symbol.metadata]
277
+ * ?? null)` — and it keeps working if a decorator ever runs after another one has
278
+ * already written the merged list.
279
+ *
280
+ * A class with no metadata of its own has a prototype of `null` and reports no
281
+ * inherited arms, which is correct: there is nothing to have weakened.
282
+ *
283
+ * @param metadata - The decorating class's metadata object.
284
+ * @param feature - The feature's name.
285
+ * @internal
286
+ * Exported only because `demands.mts` lives in its own file and imports it. The
287
+ * prototype walk relies on the compiler's metadata emission, which no consumer
288
+ * should build on.
289
+ */
290
+ export declare const inheritedArms: (metadata: object | undefined, feature: unknown) => readonly unknown[];
291
+ /**
292
+ * Whether this class has already been warned about this feature, marking it if not.
293
+ *
294
+ * Call before reporting, not after: the pair is recorded on the first call, so a
295
+ * class whose arms are evaluated again is not reported again.
296
+ *
297
+ * @param metadata - The decorating class's metadata object.
298
+ * @param feature - The feature's name.
299
+ * @returns Whether a report has already been made for this pair.
300
+ * @internal
301
+ * Exported only because `demands.mts` lives in its own file and imports it.
302
+ */
303
+ export declare const alreadyReported: (metadata: object, feature: unknown) => boolean;
304
+ /**
305
+ * Describes an inherited precondition that a new arm cannot narrow.
306
+ *
307
+ * A subclass declaring `@demands` reads as a restriction — "the feature now
308
+ * requires this as well" — and it is not one. `@demands` is OR-composed, because a
309
+ * subtype may accept wider input but never narrower, so satisfying any inherited
310
+ * arm still permits the call and the new arm decides nothing on its own. The
311
+ * author believes the feature is stricter than it is.
312
+ *
313
+ * Returns `undefined` when the arm is a genuine weakening (nothing inherited to be
314
+ * weaker than) or when the diagnostic is switched off. It **warns** rather than
315
+ * throws by default: a declared arm is always a legal weakening, and the defect is
316
+ * the author's model of it, so refusing the class would break legitimate code. The
317
+ * return value is the message so a stricter policy, or a test, can act on it.
318
+ *
319
+ * `@ensures` and `@invariant` are unaffected: they are AND-composed, so a subclass
320
+ * arm genuinely strengthens the obligation and there is nothing to report. They
321
+ * refuse `allowWeakening` outright; see {@link assertNotWeakenable}.
322
+ *
323
+ * @param contract - The contract name, for the message.
324
+ * @param label - The feature, for the message.
325
+ * @param inherited - The inherited arms this class's arm composes with.
326
+ * @param options - The declaration's options, which may switch the diagnostic off.
327
+ * @internal
328
+ * Exported only because `demands.mts` lives in its own file and imports it. A
329
+ * consumer who wants the warning suppressed sets `allowWeakening`; the message
330
+ * text is not part of the surface.
331
+ */
332
+ export declare const reportWeakeningArm: (contract: string, label: string, inherited: readonly unknown[], options: ArmOptions | undefined) => string | undefined;
333
+ /**
334
+ * Whether every arm is a schema, so no predicate will be shown the subject.
335
+ *
336
+ * A schema arm is handed the value it validates, never the predicate subject. When
337
+ * *every* arm of a contract is a schema, the fields that exist only for a predicate
338
+ * — `self`, `old`, `oldArgs` — cannot be observed by anything, so the work of
339
+ * producing them is unobservable too. That is a property of the declaration rather
340
+ * than an inference about code, which is what makes it safe to act on.
341
+ *
342
+ * An empty list answers `false`: a contract with no arms evaluates nothing, so there
343
+ * is no snapshot to skip and no reason to claim otherwise.
344
+ *
345
+ * @param arms - The contract's registered arms, in evaluation order.
346
+ */
347
+ export declare const observesNoSubject: (arms: readonly {
348
+ arm: unknown;
349
+ }[]) => boolean;
64
350
  /**
65
351
  * Checks one arm against the subject that belongs to it.
66
352
  *
67
353
  * @param arm - A predicate or a `StandardSchemaV1` value.
68
354
  * @param subjects - What the arm observes, chosen by the calling contract.
69
355
  * @param contract - The contract name, for the diagnostic.
70
- * @param label - The feature, for the diagnostic.
356
+ * @param label - Builds the feature's name **for a diagnostic**. A thunk because
357
+ * the name is a declaration read and a string concatenation that a satisfied
358
+ * arm never shows to anyone; see `classNameOf`.
71
359
  * @param index - The arm's position in its composition list.
72
360
  * @param options - Declaration options for this arm.
73
361
  */
74
- export declare const evaluateArm: (arm: unknown, subjects: ArmSubjects, contract: string, label: string, index: number, options?: ArmOptions) => Admissibility;
362
+ export declare const evaluateArm: (arm: unknown, subjects: ArmSubjects, contract: string, label: () => string, index: number, options?: ArmOptions) => Admissibility;
363
+ /**
364
+ * Checks one arm, awaiting a predicate that was declared awaitable.
365
+ *
366
+ * The only difference from {@link evaluateArm} is that a predicate declared
367
+ * awaitable has its verdict awaited. Every other arm is decided synchronously, so
368
+ * a predicate that returns a promise without the option is still refused by the
369
+ * strict-boolean rule rather than quietly awaited — on an `async` feature as much
370
+ * as anywhere else.
371
+ *
372
+ * Awaiting decides when the verdict arrives, not what it means: a rejection is a
373
+ * failed arm with the reason in `thrown`, and a resolution that is not a boolean
374
+ * is still a defect rather than a decision.
375
+ */
376
+ export declare const evaluateArmAsync: (arm: unknown, subjects: ArmSubjects, contract: string, label: () => string, index: number, options?: ArmOptions) => Promise<Admissibility>;
377
+ /**
378
+ * The arms that rejected a call, gathered across a composition loop.
379
+ *
380
+ * The three contracts differ in their composition rule but not in what they
381
+ * record about a rejected arm: its index, any issues a schema reported, and the
382
+ * value a throwing predicate raised. Collecting it in one place keeps the loops
383
+ * about their rule rather than about bookkeeping.
384
+ */
385
+ export interface ArmFailures {
386
+ failed: number[];
387
+ thrown: {
388
+ index: number;
389
+ value: unknown;
390
+ }[];
391
+ issues: StandardSchemaV1.Issue[];
392
+ }
393
+ /** Starts an empty record for a composition pass. */
394
+ export declare const armFailures: () => ArmFailures;
395
+ /**
396
+ * Records one rejected arm.
397
+ *
398
+ * A throwing arm also lands in `failed`: it rejected the call, and the
399
+ * distinction the caller needs is `thrown`, not whether the arm was counted.
400
+ */
401
+ export declare const recordFailure: (failures: ArmFailures, index: number, result: Admissibility) => void;
402
+ /**
403
+ * A failure record that is allocated only once an arm rejects.
404
+ *
405
+ * A satisfied composition is the common case, and it would otherwise allocate three
406
+ * arrays it never reads. The log hands back the same interface as {@link ArmFailures},
407
+ * so the composition loops keep their rule rather than their bookkeeping, and
408
+ * `entries` stays `undefined` until something fails — which is the whole test a loop
409
+ * needs at the end.
410
+ *
411
+ * The methods live on the prototype rather than in a closure per call, because a
412
+ * closure pair allocated on every invocation costs more than the three arrays it is
413
+ * there to avoid.
414
+ */
415
+ export declare class FailureLog {
416
+ #private;
417
+ /** Records a rejected arm, allocating the record on the first one. */
418
+ record(index: number, result: Admissibility): void;
419
+ /** The record, or `undefined` when no arm has rejected. */
420
+ get entries(): ArmFailures | undefined;
421
+ }
422
+ /** Starts a failure log that allocates its record only when something fails. */
423
+ export declare const failureLog: () => FailureLog;
75
424
  /**
76
425
  * Renders schema `issues` for a message.
77
426
  *
package/dist/assert.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AssertionError, type ContractKind, type ContractViolation } from "./AssertionError.mjs";
2
2
  import type { StandardSchemaV1 } from './standard-schema.mjs';
3
+ import { type ArmFailures, type ViolationFactory } from './admissibility.mjs';
3
4
  /**
4
5
  * An assertion is an expression of a property that must be true at a particular
5
6
  * point of step of program execution. It consists of a boolean expression
@@ -31,12 +32,14 @@ export declare function assert(condition: unknown, message?: string): asserts co
31
32
  *
32
33
  * @param result - The value returned by the predicate.
33
34
  * @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 label - Builds a human-readable description of the feature, e.g.
36
+ * `Foo.method`. A thunk so the name is resolved only for the message it appears
37
+ * in: a boolean verdict is the common case and never reads it.
35
38
  * @param index - The zero-based index of the predicate in its composition list.
36
39
  * @returns The predicate result, narrowed to `boolean`.
37
40
  * @throws {AssertionError} If the predicate did not return a boolean.
38
41
  */
39
- export declare function assertContractResult(result: unknown, contract: string, label: string, index: number): boolean;
42
+ export declare function assertContractResult(result: unknown, contract: string, label: () => string, index: number): boolean;
40
43
  /**
41
44
  * Builds a message for a failed contract and describes it structurally.
42
45
  *
@@ -54,7 +57,10 @@ export declare function assertContractResult(result: unknown, contract: string,
54
57
  * @param describe - Renders one arm for the message.
55
58
  * @returns The message and the structured violation.
56
59
  */
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): {
60
+ 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, thrown?: ReadonlyArray<{
61
+ index: number;
62
+ value: unknown;
63
+ }>): {
58
64
  message: string;
59
65
  violation: ContractViolation;
60
66
  };
@@ -70,4 +76,35 @@ export declare function describeViolation(contract: ContractKind, className: str
70
76
  * `@demands` is OR-composed (a subtype may weaken a precondition) while
71
77
  * `@invariant` and `@ensures` are AND-composed.
72
78
  */
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;
79
+ 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, thrown?: ReadonlyArray<{
80
+ index: number;
81
+ value: unknown;
82
+ }>): AssertionError;
83
+ /**
84
+ * Builds the value a contract raises when every arm has failed.
85
+ *
86
+ * A thrown arm is a failed arm, so when every arm failed and at least one of them
87
+ * threw, that value is what the caller receives. A typed error survives the
88
+ * composition it could not otherwise reach, and a predicate bug still surfaces as
89
+ * the bug it is rather than as an `AssertionError` describing a contract.
90
+ *
91
+ * The **first arm that threw** wins, matching the rule that the first arm
92
+ * evaluated decides a normalized value. Arm order is the composition list's, which
93
+ * for one class is reverse source order because decorators evaluate bottom-up, and
94
+ * which places inherited arms before a subclass's own.
95
+ *
96
+ * When no arm threw, the failure is a verdict rather than a fault and an
97
+ * `AssertionError` carrying the full violation is raised as usual.
98
+ *
99
+ * A declared {@link ViolationFactory} supersedes both rules, because it is the
100
+ * caller's explicit choice of error type and it receives the violation — including
101
+ * `thrownIndices` — so nothing is lost by preferring it. It runs only here, after
102
+ * every arm has been evaluated, which is the one point where the failure is final.
103
+ *
104
+ * @param factory - The contract's declared factory, if any arm declared one.
105
+ * @internal
106
+ * Exported only because the three contract modules live in their own files and
107
+ * import it. It takes an `ArmFailures`, which is not part of the published surface,
108
+ * so a consumer cannot call it without reaching into the library's internals.
109
+ */
110
+ export declare function violationFailure(contract: ContractKind, className: string, feature: string | undefined, arms: readonly unknown[], failures: ArmFailures, summary: string, describe?: (arm: unknown) => string, factory?: ViolationFactory): unknown;