@final-hill/decorator-contracts 2.0.0 → 3.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 CHANGED
@@ -1,879 +1,1716 @@
1
- # Decorator Contracts
2
-
3
- [![Build](https://github.com/final-hill/decorator-contracts/workflows/Build/badge.svg?branch=master)](https://github.com/final-hill/decorator-contracts/actions?query=workflow%3ABuild%2FRelease)
4
- [![npm version](https://badge.fury.io/js/%40final-hill%2Fdecorator-contracts.svg)](https://www.npmjs.com/package/@final-hill/decorator-contracts)
5
- [![Downloads](https://img.shields.io/npm/dm/@final-hill/decorator-contracts.svg)](https://www.npmjs.com/package/@final-hill/decorator-contracts)
6
-
7
- ## Table of Contents
8
-
9
- - [Introduction](#introduction)
10
- - [Library Installation](#library-installation)
11
- - [Node.js version](#nodejs-version)
12
- - [Development](#development)
13
- - [Usage](#usage)
14
- - [Checked Mode](#checked-mode)
15
- - [Assertions](#assertions)
16
- - [Implies](#implies)
17
- - [Iff](#iff)
18
- - [Contracts are Hoare triples](#contracts-are-hoare-triples)
19
- - [Contract failures](#contract-failures)
20
- - [Encapsulation](#encapsulation)
21
- - [Invariants](#invariants)
22
- - [Demands](#demands)
23
- - [Ensures](#ensures)
24
- - [Rescue](#rescue)
25
- - [Standard Schema](#standard-schema)
26
- - [The order of assertions](#the-order-of-assertions)
27
- - [Further Reading](#further-reading)
28
-
29
- ## Introduction
30
-
31
- Decorator Contracts is a library that provides the ability to create and assign
32
- Code Contracts to ECMAScript and TypeScript classes. This enables
33
- enforcement of the
34
- [Liskov substitution principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle)
35
- of [SOLID](https://en.wikipedia.org/wiki/SOLID)
36
- and [Organized Panic](https://en.wikipedia.org/wiki/Exception_handling#Exception_handling_based_on_design_by_contract) to support
37
- [Design By Contract™](https://en.wikipedia.org/wiki/Design_by_contract).
38
-
39
- Note that the license for this library is [AGPL-3.0-only](https://www.gnu.org/licenses/agpl-3.0.en.html).
40
- You should [know what that means](https://choosealicense.com/licenses/agpl-3.0/) before
41
- using this. If you would like an exception to this license per section 7
42
- [contact the author](mailto:michael.haufe@final-hill.com).
43
-
44
- ## Library Installation
45
-
46
- The latest version:
47
-
48
- `npm install @final-hill/decorator-contracts`
49
-
50
- A specific version:
51
-
52
- `npm install @final-hill/decorator-contracts@x.x.x`
53
-
54
- For use in a browser (no build step) via [unpkg.com](https://unpkg.com/):
55
-
56
- ```html
57
- <script type="importmap">
58
- {
59
- "imports": {
60
- "@final-hill/decorator-contracts": "https://unpkg.com/@final-hill/decorator-contracts"
61
- }
62
- }
63
- </script>
64
- ```
65
-
66
- Via [skypack.dev](https://www.skypack.dev/):
67
-
68
- `<script type="module" src="https://cdn.skypack.dev/@final-hill/decorator-contracts"></script>`
69
-
70
- ## Node.js version
71
-
72
- This library requires **Node.js 26 or later**, as declared in `engines.node`. It relies on decorator metadata and targets ES2024, so an older runtime will fail at class definition rather than at an obvious call site.
73
-
74
- ## Development
75
-
76
- A [development container](https://containers.dev/) is provided, pinned to the same Node version CI uses:
77
-
78
- ```bash
79
- # open the repository in the container, then
80
- npm ci # installed automatically on create
81
- npm run build
82
- npm test
83
- ```
84
-
85
- `npm ci` honours the lockfile and fails if it disagrees with `package.json`, which is what CI runs. Running `npm install` locally can rewrite the lockfile and is the usual cause of a build that passes locally and fails in CI.
86
-
87
- | Script | Purpose |
88
- | --- | --- |
89
- | `npm run lint` | Lint, failing on warnings; does not modify files |
90
- | `npm run lint:fix` | Lint and autofix |
91
- | `npm run typecheck` | Type-check the library and the test suite |
92
- | `npm test` | Type-check, then run the tests |
93
- | `npm run test:coverage` | Run the tests with coverage, writing `coverage/lcov.info` |
94
-
95
- The test suite imports the package by name, so it exercises the built `dist/` output rather than the sources. `npm test` builds first for that reason; running a single test file directly requires an existing `dist/`.
96
-
97
- ## Usage
98
-
99
- After installation, use the decorators directly on your class methods and properties. All contracted classes must extend `Contracted` and be instantiated using the static `.new()` method.
100
-
101
- ```typescript
102
- import { Contracted, invariant, demands, ensures } from '@final-hill/decorator-contracts';
103
-
104
- @invariant((self: Stack<any>) =>
105
- self.isEmpty() == (self.size == 0) &&
106
- self.isFull() == (self.size == self.limit) &&
107
- self.size >= 0 && self.size <= self.limit
108
- )
109
- class Stack<T> extends Contracted {
110
- private _implementation: T[] = [];
111
- private _size = 0;
112
- private _limit: number;
113
-
114
- constructor(limit: number) {
115
- super();
116
- this._limit = limit;
117
- }
118
-
119
- get limit() { return this._limit; }
120
- get size() { return this._size; }
121
-
122
- clear(): void {
123
- this._implementation = [];
124
- this._size = 0;
125
- }
126
-
127
- isEmpty(): boolean { return this._implementation.length == 0; }
128
- isFull(): boolean { return this._implementation.length == this.limit; }
129
-
130
- @demands((self: Stack<any>) => !self.isEmpty())
131
- @ensures((self: Stack<any>, _args, old: Stack<any>) =>
132
- !self.isFull() && self.size == old.size - 1)
133
- pop(): T {
134
- this._size--;
135
- return this._implementation.pop()!;
136
- }
137
-
138
- @demands((self: Stack<any>) => !self.isFull())
139
- @ensures((self, [item], old: Stack<any>) =>
140
- !self.isEmpty() &&
141
- self.top === item &&
142
- self.size === old.size + 1
143
- )
144
- push(item: T): void {
145
- this._size++;
146
- this._implementation.push(item);
147
- }
148
-
149
- get top(): T | undefined {
150
- return this._implementation.at(-1);
151
- }
152
- }
153
-
154
- const stack = Stack.new(3);
155
- stack.push(1);
156
- stack.push(2);
157
- stack.pop();
158
- ```
159
-
160
- ## Instantiation: Using the Static `.new(...)` Method
161
-
162
- Because this library uses JavaScript `Proxy` to enforce contracts, you **must** instantiate all classes that extend `Contracted` using the static `.new(...)` method (not with `new MyClass(...)`).
163
-
164
- This is required so that the instance is wrapped in a Proxy and invariants are asserted immediately after construction. Direct use of the `new` keyword will throw an error.
165
-
166
- ## Checked Mode
167
-
168
- Checked Mode controls whether contract checking (invariants, demands, ensures, and rescue) is enabled or disabled at runtime. This feature allows you to turn off contract enforcement in production environments for maximum performance, while keeping it enabled during development and testing to catch bugs and contract violations early.
169
-
170
- Checked Mode is a coarse switch over the whole library, not a re-entrancy mechanism. When it is disabled, contract evaluation is skipped entirely and external encapsulation is not enforced either, so an instance behaves like a plain object.
171
-
172
- By default, Checked Mode is enabled. You can control it via the static `[checkedMode]` symbol property of Contracted:
173
-
174
- ```typescript
175
- Contracted[checkedMode] = false; // Disable Checked Mode
176
- ```
177
-
178
- One approach to managing this is to leverage environment variables. For example, you can interrogate `NODE_ENV` to determine whether to enable or disable Checked Mode:
179
-
180
- ```typescript
181
- Contracted[checkedMode] = process.env.NODE_ENV === 'development'
182
- ```
183
-
184
- ## Assertions
185
-
186
- Use the `assert` function for inline assertions:
187
-
188
- ```typescript
189
- import { assert } from '@final-hill/decorator-contracts';
190
-
191
- function avg(xs: number[]): number {
192
- assert(xs.length > 0, 'The list can not be empty');
193
- return xs.reduce((sum, next) => sum + next) / xs.length;
194
- }
195
- ```
196
-
197
- If you are using TypeScript, `assert` will also assert the type of the condition:
198
-
199
- ```typescript
200
- let str: any = 'foo';
201
-
202
- str.toUpperCase(); // str is any
203
-
204
- assert(typeof str == 'string');
205
-
206
- str.toUpperCase(); // str is now a string
207
- ```
208
-
209
- **`assert` should not be used for validating arguments**
210
-
211
- Use the `@demands` decorator for this purpose.
212
-
213
- ## Implies
214
-
215
- When defining predicates it is a common use case to encode [material implication](https://en.wikipedia.org/wiki/Material_conditional):
216
-
217
- ```typescript
218
- import { implies } from '@final-hill/decorator-contracts';
219
-
220
- implies(weather.isSunny, person.visitsBeach);
221
- // Logically equivalent to: !weather.isSunny || person.visitsBeach
222
- ```
223
-
224
- Both functions always return a `boolean`, even when an operand is not a boolean: a truthy object is coerced rather than passed through. Inside a contract this is redundant, because `@demands` and friends already require a literal `true` or `false` and name the offending feature.
225
-
226
- ## Iff
227
-
228
- When defining predicates it is a common use case to encode [if and only if](https://en.wikipedia.org/wiki/Logical_biconditional):
229
-
230
- ```typescript
231
- import { iff } from '@final-hill/decorator-contracts';
232
-
233
- iff(person.hasTicket, person.ridesTrain);
234
- // Logically equivalent to: implies(p, q) && implies(q, p)
235
- ```
236
-
237
- Both functions always return a `boolean`, even when an operand is not a boolean: a truthy object is coerced rather than passed through. Inside a contract this is redundant, because `@demands` and friends already require a literal `true` or `false` and name the offending feature.
238
-
239
- ## Contracts are Hoare triples
240
-
241
- A contract describes the **observable boundary** of a feature, in the sense of a [Hoare triple](https://en.wikipedia.org/wiki/Hoare_logic):
242
-
243
- $$\{P\}\; C\; \{Q\}$$
244
-
245
- `@demands` is $P$, `@ensures` is $Q$, and the feature body is $C$. Nothing inside $C$ is constrained: a body may assign to its own properties, including public ones, and may call its own features without re-entering the contracts. Correctness is the obligation that $P$ and $Q$ hold at the boundary, with the invariant additionally holding on entry and exit.
246
-
247
- This is why there is no need to police what a body does to itself. If a body leaves the object in an invalid state, `@invariant` rejects it on exit. If it produces the wrong result, `@ensures` rejects it. Attempting to enforce correctness *inside* $C$ as well would mean the same guarantee twice, at the cost of forbidding legitimate intermediate states.
248
-
249
- ## Contract failures
250
-
251
- A failed contract throws an `AssertionError`. Its `name` is `AssertionError` regardless of how the bundle was minified, and its message names the contract, the feature, and the predicate(s) that failed:
252
-
253
- ```text
254
- @ensures failed for Account.withdraw (1 of 2 predicates unsatisfied: predicate #2: (self,[amount],old)=>self.balance===old.balance-amount). A postcondition was not satisfied after the feature ran.
255
- ```
256
-
257
- The predicate text is whatever the predicate's `toString()` returns, which is minified in a bundled build. The structured `violation` below is the reliable way to identify a failure.
258
-
259
- The error also carries a `violation` property so callers can react without parsing the message:
260
-
261
- ```typescript
262
- import { AssertionError } from '@final-hill/decorator-contracts';
263
-
264
- try {
265
- account.withdraw({ amount: 500 });
266
- } catch (error) {
267
- if (error instanceof AssertionError && error.violation?.contract === '@demands') {
268
- // a precondition failed; the feature was never entered
269
- }
270
- }
271
- ```
272
-
273
- `violation` has the shape:
274
-
275
- ```typescript
276
- interface ContractViolation {
277
- contract: '@invariant' | '@demands' | '@ensures';
278
- className: string;
279
- feature?: string; // absent for `@invariant`
280
- failedIndices: number[]; // positions in the contract's composition list
281
- predicates: string[]; // source text, aligned with `failedIndices`
282
- }
283
- ```
284
-
285
- `@demands` is OR-composed, so a failure lists **every** arm — any of them could have permitted the call. `@ensures` and `@invariant` are AND-composed, so a failure lists only the predicates that broke.
286
-
287
- An `AssertionError` thrown by `assert()` itself has no `violation`.
288
-
289
- ## Encapsulation
290
-
291
- Encapsulation governs the **external surface**. Public property assignment is forbidden from outside a contracted class, so a caller cannot mutate state without a postcondition to catch it. All interactions must go through a method or getter/setter, and only properties starting with `_` (conventionally private) can be assigned to after construction.
292
-
293
- ```typescript
294
- class Example extends Contracted {
295
- _private = 1; // Allowed
296
- publicProp = 2; // Not allowed from outside
297
- }
298
- ```
299
-
300
- The boundary begins *after* construction. A constructor runs before the instance is proxied, so its assignments — to public properties included — are unrestricted. That is deliberate: field initialisers and `Object.assign(this, ...)` are ordinary ways to establish initial state, and the invariant evaluated at the end of `Contracted.new()` is what validates the result.
301
-
302
- ```typescript
303
- class Example extends Contracted {
304
- publicProp = 2; // allowed: field initialiser
305
- constructor() {
306
- super();
307
- this.publicProp = 3; // allowed: still inside construction
308
- }
309
- }
310
- ```
311
-
312
- An external write to a public property raises a `TypeError`:
313
-
314
- ```typescript
315
- const example = Example.new();
316
-
317
- example.publicProp = 3; // TypeError
318
- ```
319
-
320
- A feature body is $C$ and is **not** subject to this rule. It runs against the instance directly, so internal state — public or private — is its own business:
321
-
322
- ```typescript
323
- class Example extends Contracted {
324
- publicProp = 1;
325
-
326
- update(): void {
327
- this.publicProp = 2; // allowed; `@ensures` and `@invariant` are the guarantee
328
- }
329
- }
330
- ```
331
-
332
- A method calling another method of the same instance likewise does not start a second contract lifecycle. The enclosing invocation owns the assertions, so the invariant is evaluated once on entry and once on exit regardless of how many internal accesses the body performs.
333
-
334
- One consequence: a body that leaks `this` outward — passing it to a callback, storing it in a module-level variable, or returning it — hands out a reference that bypasses the traps. Do not do that; expose an explicit API instead.
335
-
336
- ### Deletion
337
-
338
- Deletion is an external mutation, so it follows exactly the same rule as assignment: `_`-prefixed properties may be deleted, public properties may not, and the invariant is evaluated around the deletion.
339
-
340
- | Expression | Result |
341
- | --- | --- |
342
- | `delete example._private` | allowed |
343
- | `delete example.publicProp` | `TypeError` |
344
- | `delete example.nonexistent` | `TypeError` (the name is not `_`-prefixed) |
345
-
346
- The last row surprises people, but it is the same rule `set` applies to an assignment of a property that does not exist: the restriction is on the *name*, not on whether the property is present. Once checked mode is disabled the proxy steps aside and `delete` behaves as it does on a plain object.
347
-
348
- `Object.defineProperty`, `Reflect.defineProperty`, and `Reflect.deleteProperty` operate below the proxy and are not intercepted.
349
-
350
- ## Asynchronous features
351
-
352
- A feature declared `async` is fully contracted. Because an `async` body returns its promise before a single line of it has run, the exit boundary follows the value: `@ensures` and the exit `@invariant` are evaluated after the promise settles, against the state the body actually reached.
353
-
354
- ```typescript
355
- class Account extends Contracted {
356
- protected _balance = 0;
357
- public _ledger!: Ledger; // a collaborator the caller sets
358
- get balance() { return this._balance; }
359
-
360
- @demands((self, [amount]: [number]) => self.balance + amount >= 0)
361
- @ensures((self, [amount]: [number], old) => self.balance === old.balance + amount)
362
- async deposit(amount: number): Promise<void> {
363
- await this._ledger.record(amount); // suspension happens here
364
- this._balance += amount; // observed by @ensures
365
- }
366
- }
367
- ```
368
-
369
- The lifecycle is unchanged in order and in count: `@invariant` -> `@demands` -> body -> `@ensures` -> `@invariant`, with the invariant evaluated twice per call. Only the *position* of the exit checks differs, because the body has not finished until the promise settles. A `@rescue` observes rejections as it observes synchronous throws, and `retry` restarts the lifecycle for an asynchronous feature too.
370
-
371
- ### Failure is delivered as a rejection
372
-
373
- A contract violation on an `async` feature reaches the caller as a rejected promise, never as a synchronous throw — the same way the feature's own errors reach it. Adding a contract to a feature must not change how its failures are observed.
374
-
375
- ```typescript
376
- await assert.rejects(() => account.deposit(-5)); // AssertionError, not a sync throw
377
- ```
378
-
379
- This follows from substitutability. `() => T` and `() => Promise<T>` are mutually non-assignable in TypeScript, so neither is a subtype of the other and no sync/async conversion is implied. What must hold is the observable surface: a caller of the undecorated feature receives a promise that may reject, so a caller of the contracted feature must receive the same.
380
-
381
- ### A synchronous feature must not return a promise
382
-
383
- Contracts on a feature that is not declared `async` are evaluated when its body returns. A body that defers its work through a promise would therefore be checked before it has done anything, so this is rejected:
384
-
385
- ```typescript
386
- @ensures(...)
387
- thenable(): Promise<void> { // AssertionError: not declared 'async'
388
- return (async () => { await work(); this._value++; })();
389
- }
390
- ```
391
-
392
- Declare the feature `async` instead. Awaiting arbitrary thenables was rejected as a rule because it would make the `async` keyword optional while silently changing when failures are reported: a plain function cannot return pending work *and* raise the resulting failure itself.
393
-
394
- ### Generators
395
-
396
- A generator has a contract boundary per **step**, not one per call. Calling the feature runs nothing; each `next()` runs the body from where it was suspended up to the following `yield`. When `next()` returns the segment has finished and the instance holds the state it will be observed with, so the contracts bracket each step:
397
-
398
- ```
399
- call -> @invariant, @demands the call arguments are P
400
- next() -> @invariant entry of the step
401
- segment -> body up to the next yield
402
- next() -> @ensures, @invariant the yielded value and the new state are Q
403
- ```
404
-
405
- This is the same sandwich shown above, applied once per step. A yield is the observable delivery of a traversal, which is what `@ensures` describes, so every yielded value must satisfy it:
406
-
407
- ```typescript
408
- class Counter extends Contracted {
409
- protected _count = 0;
410
-
411
- @ensures((self, [_value]: [number], old) => self._count === old._count + 1)
412
- *tick(): Generator<number> {
413
- this._count++; yield this._count; // each step is checked
414
- this._count++; yield this._count;
415
- }
416
- }
417
- ```
418
-
419
- The `old` snapshot is per step, not per traversal: it describes the state the segment is about to change. A `return` value is not covered by `@ensures`, because nothing is yielded.
420
-
421
- #### Why the invariant runs on every resume
422
-
423
- A suspended generator's instance is publicly reachable, so another feature can be called on it between yields. Checking the invariant only at completion would leave the object knowingly invalid for the whole traversal, and would never check at all if the iterator were abandoned or only partially drained. Evaluating it on each resume is what keeps the guarantee every other feature already has: no public interaction leaves the object invalid.
424
-
425
- ```typescript
426
- const iterator = ledger.payments();
427
- iterator.next(); // segment 1 checked on exit
428
- ledger.audit(); // a public call, and it sees a valid object
429
- ```
430
-
431
- #### `@demands` describes the call
432
-
433
- `@demands` runs once, on the first step: there is one call, so there is one precondition. A later step may also be *given* a value through `next(value)`, which becomes the value of the preceding `yield` expression and is not an argument of the call; that input is checked as a precondition **when it is present**. `for...of` iterates with `next()` and injects nothing, so it never re-enters the precondition with `undefined`:
434
-
435
- ```typescript
436
- @demands((_self, [count]: [number]) => count > 0)
437
- *gen(count: number): Generator<number> { /* ... */ }
438
-
439
- for (const value of obj.gen(3)) { /* works: no value is injected */ }
440
- ```
441
-
442
- #### `@rescue` covers the traversal
443
-
444
- A generator that has already been consumed cannot be resumed from the beginning, so `retry` restarts the traversal, rerunning the body exactly as it does for an ordinary feature. A throw escaping a step is what the handler observes.
445
-
446
- ## Note on Private Fields and Accessors
447
-
448
- Due to the use of JavaScript `Proxy` in the implementation of this library, native `#private` fields and the `accessor` keyword are **not supported**. Instead, use conventional private fields (e.g., `_private`) and define explicit getter/setter pairs for encapsulation:
449
-
450
- ```typescript
451
- class Example extends Contracted {
452
- private _value = 0;
453
- get value() { return this._value; }
454
- set value(v: number) { this._value = v; }
455
- }
456
- ```
457
-
458
- Do **not** use:
459
-
460
- - `#privateField` syntax
461
- - `accessor foo` syntax
462
-
463
- These will not work correctly with the contract enforcement provided by this library.
464
-
465
- ## Invariants
466
-
467
- Use the `@invariant` decorator on your class to enforce relationships between properties and methods. The invariant is checked after construction, before and after every method execution, and before and after every get/set usage.
468
-
469
- ```typescript
470
- @invariant(self => self.value >= 0)
471
- class Foo extends Contracted {
472
- protected _value = 0;
473
- get value() { return this._value; }
474
- set value(v: number) { this._value = v; }
475
-
476
- inc(): void { this.value++; }
477
- dec(): void { this.value--; }
478
- }
479
- ```
480
-
481
- ### Contract predicates must return a boolean
482
-
483
- `@invariant`, `@demands`, and `@ensures` predicates must return `true` or `false`. The result is not coerced: a non-boolean result raises an `AssertionError` naming the contract, the feature, and which predicate in the composition failed.
484
-
485
- ```typescript
486
- @demands(() => Promise.resolve(true)) // AssertionError: returned a Promise
487
- ```
488
-
489
- This is deliberate. A `Promise` is always truthy, so coercing the result would silently treat an accidentally asynchronous predicate — one that has not actually checked anything yet — as a satisfied contract. Failing closed is the only safe option, and the message points at the mistake.
490
-
491
- Asynchronous *predicates* are therefore not supported: a predicate that needs the result of an asynchronous operation cannot be expressed as a boolean.
492
-
493
- Asynchronous *features* are supported; see [Asynchronous features](#asynchronous-features).
494
-
495
- ### Contract predicates may not change the instance
496
-
497
- A predicate answers a question, so it cannot change the state it is asked about. `@invariant`, `@demands`, and `@ensures` receive a **read-only view** of the instance: assigning, deleting, or defining a property raises a `TypeError` naming the property.
498
-
499
- ```typescript
500
- @demands((self) => { self._value = 0; return true; })
501
- // TypeError: A contract predicate may not assign '_value'.
502
- ```
503
-
504
- This matters because a predicate runs *between* the entry and exit `@invariant`. A write inside a predicate can therefore hide a violation the invariant would otherwise have reported, turning a detectable bug into a silent one.
505
-
506
- ```typescript
507
- @invariant((self) => {
508
- self._value = 0; // would repair the state being checked
509
- return self._value >= 0; // and then pass
510
- })
511
- ```
512
-
513
- `@rescue` is deliberately **not** restricted. Restoring corrupted state is its purpose, so its handler receives the raw instance.
514
-
515
- #### What is not blocked
516
-
517
- The guard covers the instance's own surface. A mutation *through* a nested value still reaches the shared object:
518
-
519
- ```typescript
520
- @demands((self) => { self._items.push(item); return true; }) // not intercepted
521
- ```
522
-
523
- Closing that would mean deep-wrapping every value a predicate reads, which changes object identity and would break legitimate comparisons such as `old.child === self.child`. The guarantee is therefore "a predicate cannot assign to the instance", which is the case that corrupts contract evaluation.
524
-
525
- The feature body is unaffected: it still receives the instance itself and mutates freely. The view is scoped to the predicate call, which is why a scoped `Proxy` is used rather than `Object.freeze` — freezing is permanent, and would leave the body unable to change anything afterwards.
526
-
527
- ### Subcontracting and Invariants
528
-
529
- When subclassing, if a subclass defines its own `@invariant`, the resulting invariant is **strengthened**: the subclass invariant and the base class invariant are both enforced (they are logically AND-ed together). This means all invariants in the inheritance chain must hold for the object to be valid.
530
-
531
- ```typescript
532
- @invariant(self => self.value >= 0)
533
- class Base extends Contracted {
534
- // ...
535
- }
536
-
537
- @invariant(self => self.value <= 10)
538
- class Sub extends Base {
539
- // ...
540
- }
541
- // The effective invariant for Sub is: (self.value >= 0) && (self.value <= 10)
542
- ```
543
-
544
- ## Demands
545
-
546
- Use the `@demands` decorator to specify preconditions for methods or get/set. If the condition fails, an error is thrown before the method executes.
547
-
548
- ```typescript
549
- class Foo extends Contracted {
550
- protected _value = 0;
551
- get value() { return this._value; }
552
- set value(v: number) { this._value = v; }
553
-
554
- @demands(self => self.value >= 0)
555
- dec(): void { this.value--; }
556
- }
557
- ```
558
-
559
- ### Subcontracting and Demands
560
-
561
- When subclassing, if a subclass defines its own `@demands` for a method, the resulting precondition is **weakened**: the subclass and base class demands are OR-ed together. The method can be called if **any** of the demands in the inheritance chain are satisfied.
562
-
563
- ```typescript
564
- class Base extends Contracted {
565
- @demands((_self, [x]: [number]) => x >= 0)
566
- foo(x: number) { /* ... */ }
567
- }
568
-
569
- class Sub extends Base {
570
- @demands((_self, [x]: [number]) => x === 42)
571
- override foo(x: number) { /* ... */ }
572
- }
573
- // The effective demand for Sub#foo is: (x >= 0) || (x === 42)
574
- ```
575
-
576
- A demand receives the **argument list**, so destructure it: `(_self, [x])`. Writing `(_self, x: number) => x >= 0` does not compile, because the second parameter is the array rather than the first argument.
577
-
578
- ## Ensures
579
-
580
- Use the `@ensures` decorator to specify postconditions for methods or get/set. If the condition fails, an error is thrown after the method executes.
581
-
582
- ```typescript
583
- class Foo extends Contracted {
584
- protected _value = 0;
585
- get value() { return this._value; }
586
- set value(v: number) { this._value = v; }
587
-
588
- @ensures(self => self.value >= 0)
589
- dec(): void { this.value--; }
590
- }
591
- ```
592
-
593
- ### The `old` instance
594
-
595
- A postcondition receives `old`, a snapshot of the instance taken immediately before the feature ran. `old` inherits from the instance, so prototype getters and methods remain usable, and reading a prototype getter on `old` returns the historical value:
596
-
597
- ```typescript
598
- class Counter extends Contracted {
599
- protected _n = 0;
600
- get n() { return this._n; }
601
-
602
- @ensures((self, _args, old) => self.n === old.n + 1)
603
- inc(): void { this._n++; }
604
- }
605
- ```
606
-
607
- Own state is copied, so mutations made by the feature body are not visible through `old`. The copy is deep for the containers contracts routinely compare:
608
-
609
- | Value | Behaviour in `old` |
610
- | --- | --- |
611
- | Primitives | copied |
612
- | Arrays | cloned recursively |
613
- | `Date` | cloned |
614
- | `Map`, `Set` | cloned (keys and values recursively) |
615
- | Plain objects | cloned recursively, including cycles |
616
- | Class instances | **shared by reference** |
617
- | Functions | **shared by reference** |
618
-
619
- Class instances and functions are shared deliberately. They carry behaviour, so a structural copy would produce an object that is not a real instance of its class, and many cannot be cloned meaningfully at all. The consequence is that mutating a class instance held in a field *is* visible through `old`; if a postcondition depends on such an object's previous state, copy it explicitly in the predicate.
620
-
621
- Accessors are copied as descriptors rather than evaluated, so snapshotting never invokes a getter.
622
-
623
- ### Subcontracting and Ensures
624
-
625
- When subclassing, if a subclass defines its own `@ensures` for a method, the resulting postcondition is **strengthened**: the subclass and base class ensures are AND-ed together. The method's result must satisfy **all** ensures in the inheritance chain.
626
-
627
- ```typescript
628
- class Base extends Contracted {
629
- @ensures((_self, [x]: [number]) => x >= 0)
630
- foo(x: number) { /* ... */ }
631
- }
632
-
633
- class Sub extends Base {
634
- @ensures((_self, [x]: [number]) => x <= 10)
635
- override foo(x: number) { /* ... */ }
636
- }
637
- // The effective ensures for Sub#foo is: (x >= 0) && (x <= 10)
638
- ```
639
-
640
- The signature is `(self, args, old)`: the argument list, then the snapshot of the instance from before the feature ran. Writing `(_self, _args, x: number) => x >= 0` does not compile — the third parameter is `old`, and comparing it to a number is always `false`.
641
-
642
- ## Rescue
643
-
644
- Use the `@rescue` decorator to handle exceptions thrown by a method, restore invariants, or retry execution:
645
-
646
- ```typescript
647
- import { rescue } from '@final-hill/decorator-contracts';
648
-
649
- class Example extends Contracted {
650
- private _value = 3;
651
- get value() { return this._value; }
652
- set value(v) { this._value = v; }
653
-
654
- @rescue(self => self.value = 5)
655
- method1(): void { throw new Error('I am error'); }
656
- }
657
- ```
658
-
659
- You can also use the `retry` function in your rescue handler to attempt the method again:
660
-
661
- ```typescript
662
- class Example extends Contracted {
663
- @rescue((_self, _error, _args, retry) => retry(3))
664
- method(value: number): number {
665
- if (value <= 0)
666
- throw new Error('value must be greater than 0');
667
- else
668
- return value;
669
- }
670
- }
671
- ```
672
-
673
- `retry` passes **only** the arguments you give it — it does not replay the original arguments. To retry with the same arguments, forward the `args` you received:
674
-
675
- ```typescript
676
- @rescue((_self, _error, args, retry) => retry(...args))
677
- ```
678
-
679
- Calling `retry()` retries with no arguments.
680
-
681
- A `@rescue` handler **cannot supply the feature's result**. Only `retry` can produce one, by running the body again; a value returned from the handler is ignored, and the original error is raised to the caller when `retry` is not called. To recover with a substitute value, restructure the body to accept the alternative and retry with it:
682
-
683
- ```typescript
684
- @rescue((_self, _error, args, retry) => {
685
- // the handler restores state, then asks for a second attempt
686
- retry(...args);
687
- })
688
- method(value: number): number { /* ... */ }
689
- ```
690
-
691
- This keeps the postcondition meaningful: a result the body never produced would not be covered by `@ensures`.
692
-
693
- ### Robustness, Organized Panic, and the Benefits of `@rescue`
694
-
695
- The `@rescue` decorator enables a mechanism for **Robustness** in your code. It allows your implementation to respond to situations not specified, providing the ability to handle exceptions in a structured way. This is sometimes called **Organized Panic**.
696
-
697
- In addition, `@rescue` provides a foundation for **N-Version programming**, **Fault-Tolerance**, and **Redundancy**. You can implement multiple strategies for handling errors, retrying with alternative logic or data, and ensuring your application can recover from unexpected failures.
698
-
699
- A retried invocation re-enters the full assertion lifecycle (`@invariant` -> `@demands` -> body -> `@ensures`), and if it fails again the `@rescue` handler runs again. This means the handler is executed once per attempt, which is what N-Version programming requires: each invocation of the handler can select the next alternative.
700
-
701
- A dated example of this is performing ajax requests in a multi-browser environment:
702
-
703
- ```typescript
704
- class AjaxRequest extends Contracted {
705
- private _version = 0;
706
- private _versions = ['legacy', 'activex', 'xhr'] as const;
707
-
708
- @rescue((self: AjaxRequest, _error, args, retry) => {
709
- self._version++;
710
- retry(...args);
711
- }, { maxRetries: 2 })
712
- get(url: string): string {
713
- const version = this._versions[this._version];
714
-
715
- switch (version) {
716
- case 'legacy':
717
- if (!window.XMLHttpRequest) throw new Error(`${version} unsupported`);
718
- return legacyGet(url);
719
- case 'activex':
720
- if (!window.ActiveXObject) throw new Error(`${version} unsupported`);
721
- return activeXGet(url);
722
- default:
723
- return xhrGet(url);
724
- }
725
- }
726
- }
727
- ```
728
-
729
- Because a rescue handler may retry unconditionally, retries are unbounded by default. Set the `maxRetries` option on the `@rescue` declaration to bound them; when the limit is reached the last error is raised to the caller:
730
-
731
- ```typescript
732
- @rescue((_self, _error, args, retry) => retry(...args), { maxRetries: 3 })
733
- ```
734
-
735
- The option belongs to the declaration because the number of alternatives is a property of the feature, not of an individual failure. It is enforced per invocation of the feature, so a single call performs at most `maxRetries` retries however many `@rescue` executions that involves.
736
-
737
- Unlike traditional `try/catch`, where exceptions are non-resumable and often handled far from the source (leading to scattered and redundant error handling), `@rescue` allows for **resumable exceptions** and localized, declarative error handling. This means:
738
-
739
- - You can lexically determine where exception handling occurs.
740
- - You can restore invariants or perform corrective actions before retrying or failing.
741
- - You can optionally call `retry` to attempt the method again with new arguments or after fixing state, providing a form of fault tolerance and robustness.
742
- - You can implement alternative strategies for error recovery, supporting N-Version programming and redundancy.
743
-
744
- **Inheritance:**
745
-
746
- If a base class declares a `@rescue` handler for a method, that handler is inherited by subclasses unless the subclass overrides it with its own `@rescue` declaration. This ensures that robust error handling is preserved throughout the inheritance chain, unless explicitly changed.
747
-
748
- This approach leads to more maintainable and robust code, as error handling is organized and closely tied to the contract of the class feature, rather than being scattered throughout the call stack.
749
-
750
- ## Standard Schema
751
-
752
- `@invariant`, `@demands`, and `@ensures` accept a [Standard Schema V1](https://github.com/standard-schema/standard-schema) value anywhere they accept a predicate. Zod, Valibot, ArkType, and Effect Schema are then interchangeable: the library consumes the protocol and never depends on a provider.
753
-
754
- ```typescript
755
- import { z } from 'zod';
756
-
757
- const positive = z.number().positive();
758
- const quantity = z.tuple([z.number().positive()]);
759
-
760
- class Inventory extends Contracted {
761
- protected _stock = 0;
762
- get stock() { return this._stock; }
763
-
764
- @demands(quantity) // validates the argument tuple
765
- @ensures(positive) // validates the result
766
- add(...[count]: [number]): number {
767
- this._stock += count;
768
-
769
- return this._stock;
770
- }
771
- }
772
- ```
773
-
774
- ### What a schema validates
775
-
776
- The subject is the subject the contract already describes, so the two kinds of arm are interchangeable:
777
-
778
- | Decorator | A schema validates | A predicate receives | Composition |
779
- | --- | --- | --- | --- |
780
- | `@invariant` | the instance | `(self)` | AND |
781
- | `@demands` | the **argument tuple** | `(self, args)` | OR |
782
- | `@ensures` | the **result** | `(self, args, old)` | AND |
783
-
784
- Because `@demands` validates the argument tuple rather than the first argument, a one-parameter method is written as a tuple of one (`z.tuple([...])`). This keeps the subject unambiguous for any arity.
785
-
786
- ### Composition follows variance
787
-
788
- The rules above are the substitution rules, not a convention:
789
-
790
- - **`@demands` is contravariant.** A subtype may accept *wider* input, so conditions are OR-composed and any inherited arm satisfies the call. A subtype adding an arm therefore **weakens** the precondition.
791
- - **`@ensures` and `@invariant` are covariant.** A subtype may promise *narrower* output and must preserve *more* state, so conditions are AND-composed and every arm must hold. A subtype adding an arm therefore **strengthens** the obligation.
792
-
793
- A schema arm composes exactly like a predicate arm, which is why no separate decorators exist: the rule belongs to the contract, not to the kind of arm.
794
-
795
- **A narrowing subtype precondition has no effect, and that is correct.** Writing `@demands(z.number().min(5))` in a subtype does not restrict anything, because OR-composition keeps the inherited arm. A subtype is not permitted to narrow what its supertype accepts, so the runtime refuses to give it that power. TypeScript will not catch the mistake either — **method parameters are bivariant** under `strictFunctionTypes` — so this is a review obligation. Declare input schemas on the base feature.
796
-
797
- ### Failure reporting
798
-
799
- A schema failure carries the provider's own `issues` in the structured payload, and renders them into the message:
800
-
801
- ```typescript
802
- try {
803
- inventory.add(-1);
804
- } catch (error) {
805
- error.violation?.contract; // '@demands'
806
- error.violation?.issues; // ReadonlyArray<{ message, path? }>
807
- }
808
- ```
809
-
810
- One consequence of validating the argument tuple is that an issue's `path` is also relative to it, so the first argument is index `0`:
811
-
812
- ```text
813
- @demands failed for Shipping.send (1 of 1 schema unsatisfied: schema #1: ...).
814
- Reported: 0.zip: Invalid string: must match pattern /^\d{5}$/.
815
- ```
816
-
817
- ### Normalization is opt-in
818
-
819
- `validate` may transform its input. Applying that transformation changes what the body receives and what later contracts observe, so it is an explicit choice:
820
-
821
- ```typescript
822
- @demands(trimmedName, { normalize: true })
823
- rename(name: string): void { /* receives the trimmed name */ }
824
- ```
825
-
826
- - **`@demands`** is OR-composed, so the **first passing arm** decides the normalized value. That is deterministic and matches evaluation order.
827
- - **`@ensures`** is AND-composed, so two normalizing arms would disagree about what the caller receives. That is refused at decoration time rather than resolved arbitrarily.
828
-
829
- Off by default: without `normalize`, a schema only reports a verdict.
830
-
831
- ### Synchronous only
832
-
833
- Contract evaluation is synchronous, so a `validate` that returns a Promise is refused with a message asking for a synchronous schema. Treating a pending validation as satisfied would be worse than failing, and awaiting would move the feature's boundary.
834
-
835
- ### No type inference
836
-
837
- Decorators cannot change a feature's signature, so a schema gives **runtime enforcement only**: it neither narrows the declared parameter types nor infers `Input`/`Output`. Accurate inference needs a builder API, which this library does not have.
838
-
839
- ### Providers
840
-
841
- Any implementation of the protocol works, and no provider is a dependency. The `StandardSchemaV1` types are exported if you want to annotate your own schemas:
842
-
843
- ```typescript
844
- import type { StandardSchemaV1 } from '@final-hill/decorator-contracts';
845
- ```
846
-
847
- ## The order of assertions
848
-
849
- When `obj.feature` is called the happy path is:
850
-
851
- ![image](./docs/happy-path.png)
852
-
853
- The invariant is evaluated **twice** per successful call: once on entry and once on exit. Each of `@demands`, the feature body, and `@ensures` runs once. Accessors follow the same lifecycle as methods, and an accessor that reads another accessor or calls a method does not start a nested lifecycle.
854
-
855
- An `async` feature follows the same order with the exit checks moved after the promise settles, so they observe the state the body actually reached; its failures reach the caller as a rejection. A generator applies the same order **once per step**, as described in [Generators](#generators).
856
-
857
- The entry check is not redundant with `Contracted.new()`. Object state can be corrupted without going through a checked feature — via `Object.defineProperty`, by running with checked mode disabled and re-enabling it, or internally from a feature body. The entry check is what turns that into a precise error at the next public interaction rather than letting an invalid object keep operating.
858
-
859
- Because the invariant is checked first, an invalid object reports its invariant violation rather than a precondition failure. That ordering is deliberate: the object is broken in a way that makes the caller's arguments moot.
860
-
861
- If an error is thrown and there is no `@rescue` defined then the `@invariant` is checked before the error is raised to the caller.
862
-
863
- If an error is thrown in the `@invariant` then it is raised to the caller.
864
-
865
- If an error is thrown in the `@demands` then the error is raised to the caller. In this case the exit `@invariant` is not checked because the feature body has not been entered and the instance cannot have changed.
866
-
867
- If an error is thrown by the feature body or the `@ensures` then the `@rescue` is executed. If `retry` is called then the process starts from the beginning.
868
-
869
- If the retried invocation fails, its `@rescue` is executed again, so the handler runs once per attempt. Retries are bounded by the `maxRetries` option; without it they are unbounded.
870
-
871
- If `@rescue` throws an error or does not call `retry` then the `@invariant` is checked before the error is raised to the caller.
872
-
873
- ![image](./docs/order-of-assertions.png)
874
-
875
- ## Further Reading
876
-
877
- - [Design by Contract](https://en.wikipedia.org/wiki/Design_by_contract)
878
- - [Liskov Substitution Principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle)
879
- - [Object-Oriented Software Construction](https://en.wikipedia.org/wiki/Object-Oriented_Software_Construction)
1
+ # Decorator Contracts
2
+
3
+ [![Build](https://github.com/final-hill/decorator-contracts/workflows/Build/badge.svg?branch=master)](https://github.com/final-hill/decorator-contracts/actions?query=workflow%3ABuild%2FRelease)
4
+ [![npm version](https://badge.fury.io/js/%40final-hill%2Fdecorator-contracts.svg)](https://www.npmjs.com/package/@final-hill/decorator-contracts)
5
+ [![Downloads](https://img.shields.io/npm/dm/@final-hill/decorator-contracts.svg)](https://www.npmjs.com/package/@final-hill/decorator-contracts)
6
+
7
+ ## Table of Contents
8
+
9
+ - [Introduction](#introduction)
10
+ - [Library Installation](#library-installation)
11
+ - [Node.js version](#nodejs-version)
12
+ - [Development](#development)
13
+ - [Usage](#usage)
14
+ - [Checked Mode](#checked-mode)
15
+ - [Assertions](#assertions)
16
+ - [Implies](#implies)
17
+ - [Iff](#iff)
18
+ - [Contracts are Hoare triples](#contracts-are-hoare-triples)
19
+ - [Contract failures](#contract-failures)
20
+ - [Encapsulation](#encapsulation)
21
+ - [Inspecting and serializing](#inspecting-and-serializing)
22
+ - [Asynchronous features](#asynchronous-features)
23
+ - [An awaited predicate](#an-awaited-predicate)
24
+ - [Internal calls are not contracted](#an-internal-call-runs-none-of-the-callees-contracts)
25
+ - [Invariants](#invariants)
26
+ - [Demands](#demands)
27
+ - [Ensures](#ensures)
28
+ - [Rescue](#rescue)
29
+ - [Standard Schema](#standard-schema)
30
+ - [Inspecting contracts](#inspecting-contracts)
31
+ - [Contracts and your test suite](#contracts-and-your-test-suite)
32
+ - [The order of assertions](#the-order-of-assertions)
33
+ - [The subject a predicate is called with](#the-subject-a-predicate-is-called-with)
34
+ - [Further Reading](#further-reading)
35
+
36
+ ## Introduction
37
+
38
+ Decorator Contracts is a library that provides the ability to create and assign
39
+ Code Contracts to ECMAScript and TypeScript classes. This enables
40
+ enforcement of the
41
+ [Liskov substitution principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle)
42
+ of [SOLID](https://en.wikipedia.org/wiki/SOLID)
43
+ and [Organized Panic](https://en.wikipedia.org/wiki/Exception_handling#Exception_handling_based_on_design_by_contract) to support
44
+ [Design By Contract™](https://en.wikipedia.org/wiki/Design_by_contract).
45
+
46
+ Note that the license for this library is [AGPL-3.0-only](https://www.gnu.org/licenses/agpl-3.0.en.html).
47
+ You should [know what that means](https://choosealicense.com/licenses/agpl-3.0/) before
48
+ using this. If you would like an exception to this license per section 7
49
+ [contact the author](mailto:michael.haufe@final-hill.com).
50
+
51
+ ## Library Installation
52
+
53
+ The latest version:
54
+
55
+ `npm install @final-hill/decorator-contracts`
56
+
57
+ A specific version:
58
+
59
+ `npm install @final-hill/decorator-contracts@x.x.x`
60
+
61
+ For use in a browser (no build step) via [unpkg.com](https://unpkg.com/):
62
+
63
+ ```html
64
+ <script type="importmap">
65
+ {
66
+ "imports": {
67
+ "@final-hill/decorator-contracts": "https://unpkg.com/@final-hill/decorator-contracts"
68
+ }
69
+ }
70
+ </script>
71
+ ```
72
+
73
+ Via [skypack.dev](https://www.skypack.dev/):
74
+
75
+ `<script type="module" src="https://cdn.skypack.dev/@final-hill/decorator-contracts"></script>`
76
+
77
+ ## Node.js version
78
+
79
+ This library requires **Node.js 26 or later**, as declared in `engines.node`. It relies on decorator metadata and targets ES2024, so an older runtime will fail at class definition rather than at an obvious call site.
80
+
81
+ ## Development
82
+
83
+ A [development container](https://containers.dev/) is provided, pinned to the same Node version CI uses:
84
+
85
+ ```bash
86
+ # open the repository in the container, then
87
+ npm ci # installed automatically on create
88
+ npm run build
89
+ npm test
90
+ ```
91
+
92
+ `npm ci` honours the lockfile and fails if it disagrees with `package.json`, which is what CI runs. Running `npm install` locally can rewrite the lockfile and is the usual cause of a build that passes locally and fails in CI.
93
+
94
+ | Script | Purpose |
95
+ | --- | --- |
96
+ | `npm run lint` | Lint, failing on warnings; does not modify files |
97
+ | `npm run lint:fix` | Lint and autofix |
98
+ | `npm run typecheck` | Type-check the library and the test suite |
99
+ | `npm test` | Type-check, then run the tests |
100
+ | `npm run test:coverage` | Run the tests with coverage, writing `coverage/lcov.info` |
101
+
102
+ The test suite imports the package by name, so it exercises the built `dist/` output rather than the sources. `npm test` builds first for that reason; running a single test file directly requires an existing `dist/`.
103
+
104
+ ## Usage
105
+
106
+ After installation, use the decorators directly on your class methods and properties. All contracted classes must extend `Contracted` and be instantiated using the static `.new()` method.
107
+
108
+ ```typescript
109
+ import {
110
+ Contracted, demands, ensures, invariant,
111
+ } from '@final-hill/decorator-contracts';
112
+
113
+ @invariant(({ self }) =>
114
+ self.isEmpty() == (self.size == 0) &&
115
+ self.isFull() == (self.size == self.limit) &&
116
+ self.size >= 0 && self.size <= self.limit
117
+ )
118
+ class Stack<T> extends Contracted {
119
+ private _implementation: T[] = [];
120
+ private _size = 0;
121
+ private _limit: number;
122
+
123
+ constructor(limit: number) {
124
+ super();
125
+ this._limit = limit;
126
+ }
127
+
128
+ get limit() { return this._limit; }
129
+ get size() { return this._size; }
130
+
131
+ clear(): void {
132
+ this._implementation = [];
133
+ this._size = 0;
134
+ }
135
+
136
+ isEmpty(): boolean { return this._implementation.length == 0; }
137
+ isFull(): boolean { return this._implementation.length == this.limit; }
138
+
139
+ @demands(({ self }) => !self.isEmpty())
140
+ @ensures(({ self, old }) =>
141
+ !self.isFull() && self.size == old.size - 1)
142
+ pop(): T {
143
+ this._size--;
144
+ return this._implementation.pop()!;
145
+ }
146
+
147
+ @demands(({ self }) => !self.isFull())
148
+ @ensures(({ self, args: [item], old }) =>
149
+ !self.isEmpty() &&
150
+ self.top === item &&
151
+ self.size === old.size + 1
152
+ )
153
+ push(item: T): void {
154
+ this._size++;
155
+ this._implementation.push(item);
156
+ }
157
+
158
+ get top(): T | undefined {
159
+ return this._implementation.at(-1);
160
+ }
161
+ }
162
+
163
+ const stack = Stack.new(3);
164
+ stack.push(1);
165
+ stack.push(2);
166
+ stack.pop();
167
+ ```
168
+
169
+ ## Instantiation: Using the Static `.new(...)` Method
170
+
171
+ Because this library uses JavaScript `Proxy` to enforce contracts, you **must** instantiate all classes that extend `Contracted` using the static `.new(...)` method (not with `new MyClass(...)`).
172
+
173
+ This is required so that the instance is wrapped in a Proxy and invariants are asserted immediately after construction. Direct use of the `new` keyword will throw an error.
174
+
175
+ ## Checked Mode
176
+
177
+ Checked Mode controls whether the contracts (invariants, demands, ensures, and rescue) are evaluated at runtime, so a production build can skip the checking cost while development and tests keep it.
178
+
179
+ It is a coarse switch, not a re-entrancy mechanism: disabling it skips contract evaluation entirely, so a feature call and a field read look the same and no lifecycle starts. A body still runs on the instance itself, so it may mutate its own state exactly as it may with the checks on — the switch removes the checks, not the place the body runs.
180
+
181
+ **It is separate from encapsulation.** Encapsulation is the name rule: an external caller cannot assign, define, or delete a public property. It has its own switch, `[encapsulationMode]`. The two answer different questions — a test double may want the checks off while still refusing a write to a field it never declared, and a class may want the write protection without the checks.
182
+
183
+ By default both are enabled. Assign the static on a class to change it for that class and the subclasses that do not declare their own:
184
+
185
+ ```typescript
186
+ import { checkedMode, Contracted, encapsulationMode } from '@final-hill/decorator-contracts';
187
+
188
+ class DataHolder extends Contracted {
189
+ static [checkedMode] = false; // skip the contracts
190
+ }
191
+
192
+ class OpenBox extends Contracted {
193
+ static [encapsulationMode] = false; // allow external writes, keep the contracts
194
+ }
195
+ ```
196
+
197
+ The nearest declaration on the class chain wins, and each switch is resolved independently, so a subclass can re-enable what an ancestor disabled. A sibling or a base class that declares nothing is unaffected. Assigning on `Contracted` itself sets the default for every class that declares neither.
198
+
199
+ | | contracts on | contracts off |
200
+ | --- | --- | --- |
201
+ | **encapsulation on** | full enforcement | public writes still refused, no checks |
202
+ | **encapsulation off** | public writes allowed, checks still run on the write | neither |
203
+
204
+ Disabling encapsulation removes one verdict — whether the name may be written at all. It does not remove the write from the lifecycle: a permitted write is still an external mutation, so `@invariant` runs on entry and exit and a setter's `@demands` and `@ensures` describe it. Turning the contracts off is what removes the checks, in every quadrant.
205
+
206
+ **The switch is set on the class, never on an instance.** Assigning, defining, or deleting either symbol on an instance raises a `TypeError`, including when both switches are off — a switch a caller can set is a guarantee a caller can remove.
207
+
208
+ The switch is read on every trap rather than captured at construction, so a class assigned during a test affects instances that already exist.
209
+
210
+ One approach to managing this is to leverage environment variables. For example, you can interrogate `NODE_ENV` to decide the default:
211
+
212
+ ```typescript
213
+ Contracted[checkedMode] = process.env.NODE_ENV === 'development';
214
+ ```
215
+
216
+ ### Interaction with `@rescue`
217
+
218
+ `@rescue` is one of the contracts, so disabling the contracts disables it: the body's own error reaches the caller and no handler runs. This is deliberate — a handler exists to translate and repair a contract failure, and with no contract failure to report there is nothing for it to act on.
219
+
220
+ Note that a `@rescue` handler cannot observe a failed `@demands` at all, whatever the switch says: a rejected precondition never enters a body. See [What a `@rescue` observes](#what-a-rescue-observes).
221
+
222
+ ## Assertions
223
+
224
+ Use the `assert` function for inline assertions:
225
+
226
+ ```typescript
227
+ import { assert } from '@final-hill/decorator-contracts';
228
+
229
+ function avg(xs: number[]): number {
230
+ assert(xs.length > 0, 'The list can not be empty');
231
+ return xs.reduce((sum, next) => sum + next) / xs.length;
232
+ }
233
+ ```
234
+
235
+ If you are using TypeScript, `assert` will also assert the type of the condition:
236
+
237
+ ```typescript
238
+ let str: any = 'foo';
239
+
240
+ str.toUpperCase(); // str is any
241
+
242
+ assert(typeof str == 'string');
243
+
244
+ str.toUpperCase(); // str is now a string
245
+ ```
246
+
247
+ **`assert` should not be used for validating arguments**
248
+
249
+ Use the `@demands` decorator for this purpose.
250
+
251
+ ## Implies
252
+
253
+ When defining predicates it is a common use case to encode [material implication](https://en.wikipedia.org/wiki/Material_conditional):
254
+
255
+ ```typescript
256
+ import { implies } from '@final-hill/decorator-contracts';
257
+
258
+ implies(weather.isSunny, person.visitsBeach);
259
+ // Logically equivalent to: !weather.isSunny || person.visitsBeach
260
+ ```
261
+
262
+ Both functions always return a `boolean`, even when an operand is not a boolean: a truthy object is coerced rather than passed through. Their parameters are `boolean` as well, so a typed non-boolean operand does not compile. The coercion therefore decides only what a value means when it reached the helper past the type system — typed `any`, or plain JavaScript — where a truthy operand answers `true` instead of being named:
263
+
264
+ ```typescript
265
+ @invariant(({ self }) => implies(true, self._entry)) // passes: the object is truthy
266
+ class CacheEntry extends Contracted {
267
+ public _entry: any = { loaded: false }; // `any`: the operand type is not checked
268
+ }
269
+ ```
270
+
271
+ A contract names a non-boolean *result*, but it cannot inspect an operand, so state a contract through a helper only when both operands are already booleans, and write the comparison when you want the operand itself checked.
272
+
273
+ Use these combinators to state a **relationship between two properties**, which is what an invariant and a precondition are. Do not use one in place of a postcondition's target-state conjunction: it weakens the obligation. A body that does nothing satisfies `iff(self.onHold, !self.available)` and `implies(!self.available, self.onHold)`, while `self.onHold && !self.available` rejects it.
274
+
275
+ ## Iff
276
+
277
+ When defining predicates it is a common use case to encode [if and only if](https://en.wikipedia.org/wiki/Logical_biconditional):
278
+
279
+ ```typescript
280
+ import { iff } from '@final-hill/decorator-contracts';
281
+
282
+ iff(person.hasTicket, person.ridesTrain);
283
+ // Logically equivalent to: implies(p, q) && implies(q, p)
284
+ ```
285
+
286
+ It returns a `boolean`, coerces a non-boolean operand, and must not stand in for a postcondition's target-state conjunction — all three stated under [Implies](#implies), which applies to both.
287
+
288
+ ## Contracts are Hoare triples
289
+
290
+ A contract describes the **observable boundary** of a feature, in the sense of a [Hoare triple](https://en.wikipedia.org/wiki/Hoare_logic):
291
+
292
+ $$\{P\}\; C\; \{Q\}$$
293
+
294
+ `@demands` is $P$, `@ensures` is $Q$, and the feature body is $C$. Nothing inside $C$ is constrained: a body may assign to its own properties, including public ones, and may call its own features without re-entering the contracts. Correctness is the obligation that $P$ and $Q$ hold at the boundary, with the invariant additionally holding on entry and exit.
295
+
296
+ This is why there is no need to police what a body does to itself. If a body leaves the object in an invalid state, `@invariant` rejects it on exit. If it produces the wrong result, `@ensures` rejects it. Attempting to enforce correctness *inside* $C$ as well would mean the same guarantee twice, at the cost of forbidding legitimate intermediate states.
297
+
298
+ ## Contract failures
299
+
300
+ A failed contract throws an `AssertionError`. Its `name` is `AssertionError` regardless of how the bundle was minified, and its message names the contract, the feature, and the predicate(s) that failed:
301
+
302
+ ```text
303
+ @ensures failed for Account.withdraw (1 of 2 predicates unsatisfied: predicate #2: (self,[amount],old)=>self.balance===old.balance-amount). A postcondition was not satisfied after the feature ran.
304
+ ```
305
+
306
+ The predicate text is whatever the predicate's `toString()` returns, which is minified in a bundled build. The structured `violation` below is the reliable way to identify a failure. The class name in `violation.className` and in the message is likewise the build's output unless the class declares one — see [Naming a class in a failure](#naming-a-class-in-a-failure).
307
+
308
+ The error also carries a `violation` property so callers can react without parsing the message:
309
+
310
+ ```typescript
311
+ import { AssertionError } from '@final-hill/decorator-contracts';
312
+
313
+ try {
314
+ account.withdraw({ amount: 500 });
315
+ } catch (error) {
316
+ if (error instanceof AssertionError && error.violation?.contract === '@demands') {
317
+ // a precondition failed; the feature was never entered
318
+ }
319
+ }
320
+ ```
321
+
322
+ `violation` has the shape:
323
+
324
+ ```typescript
325
+ interface ContractViolation {
326
+ contract: '@invariant' | '@demands' | '@ensures';
327
+ className: string;
328
+ feature?: string; // absent for `@invariant`
329
+ failedIndices: number[]; // positions in the contract's composition list
330
+ thrownIndices?: number[]; // the failing arms that threw, in evaluation order
331
+ thrown?: string[]; // what they threw, described, aligned with `thrownIndices`
332
+ predicates: string[]; // source text, aligned with `failedIndices`
333
+ }
334
+ ```
335
+
336
+ `@demands` is OR-composed, so a failure lists **every** arm that rejected the call — any of them could have permitted it. `@ensures` and `@invariant` are AND-composed, so a failure lists only the arms that broke.
337
+
338
+ An `AssertionError` thrown by `assert()` itself has no `violation`.
339
+
340
+ ### Naming a class in a failure
341
+
342
+ `className` is read from the constructor, so it is only as stable as the name the build emitted. Without minification that is the class's name. With it, it degrades: a minifier is free to rename the class, and the standard decorator lowering wraps a decorated class in an immediately invoked arrow that returns a **class expression**, which a compressor may leave anonymous outright. The message then reads:
343
+
344
+ ```text
345
+ @demands failed for .withdraw (1 of 1 predicate unsatisfied: ...)
346
+ ```
347
+
348
+ There is no earlier moment with a better name. The class object is created once, and a class decorator observes the same name the violation would report later, so capturing it at decoration time cannot improve it. A declaration is the only signal that survives a build:
349
+
350
+ ```typescript
351
+ import { contractName, Contracted, demands } from '@final-hill/decorator-contracts';
352
+
353
+ class Cart extends Contracted {
354
+ static [contractName] = 'Cart';
355
+
356
+ @demands(({ args: [quantity] }) => quantity > 0)
357
+ withdraw(quantity: number): number { return quantity; }
358
+ }
359
+ ```
360
+
361
+ Every failure that names the class uses the declaration: `violation.className`, the message, a non-boolean predicate diagnostic, and the "returned a promise but is not declared `async`" message. An empty or non-string declaration falls back to the constructor name, so a mistyped one cannot produce the empty label above. A declaration that throws falls back the same way, because a name is read on the way to reporting a failure and must not become the error the caller receives instead of it.
362
+
363
+ Set it on the class, as with the enforcement switches: it is read from the constructor, so an instance write has no effect. The lookup is made once per contract that has arms to label, so a class with none of them never pays for it.
364
+
365
+ **A name is declared, not inherited**, which parts company with `[checkedMode]` and `[encapsulationMode]`. Those inherit because they answer how a class *behaves*, and a subclass that says nothing about behaviour should behave like its base. A name answers who the class *is*, so applying the base's name to a subclass would report a failure in `Base` when it happened in `Derived`. A subclass that wants a stable name declares one.
366
+
367
+ The **feature name is unaffected**, because it is not a name lookup: `@demands` receives `ctx.name`, which the lowering emits as a string literal in the decorator context, and a minifier does not touch it.
368
+
369
+ If a declaration is not an option, a `keepNames` setting keeps the constructor name intact and nothing else is needed:
370
+
371
+ - `esbuild`: `keepNames: true`
372
+ - `terser`: `keep_classnames` is not sufficient on its own, because compression inlines the class expression and drops the name. Also set `compress: { keep_classnames: true }`, or disable compression.
373
+
374
+ Neither setting reaches the feature names, which never needed help. Exclude the library and the decorator lowering helpers from property mangling (`mangle.properties`), which renames the context and descriptor fields the lowering reads.
375
+
376
+ ### A predicate that throws is a failed predicate
377
+
378
+ A predicate that throws has answered *no*. It has not withdrawn the other arms, so evaluation continues and a later arm can still permit the call. This is what makes OR-composition hold: a subtype may weaken a precondition, and an arm that throws must not be able to deny a call its sibling allows.
379
+
380
+ ```typescript
381
+ class Base extends Contracted {
382
+ @demands(({ args: [x] }) => { if (x !== 42) throw new Denied(); return true; })
383
+ method(x: number): number { return x; }
384
+ }
385
+
386
+ class Sub extends Base {
387
+ @demands(({ args: [x] }) => x === 7) // a legal weakening arm
388
+ override method(x: number): number { return x; }
389
+ }
390
+
391
+ Sub.new().method(7); // permitted: the second arm holds, so the first arm's throw is moot
392
+ ```
393
+
394
+ When **every** arm fails and at least one of them threw, that thrown value is raised in place of the `AssertionError`, so a typed error reaches the caller. The **first arm that threw** decides which value that is. The structured violation is still attached to it, non-enumerable, so `error.violation` describes the contract the same way it does for a verdict; the underlying `AssertionError`, whose message names every unsatisfied arm, travels as `error.cause`:
395
+
396
+ ```typescript
397
+ try {
398
+ Sub.new().method(1); // both arms fail
399
+ } catch (error) {
400
+ error instanceof Denied; // true; the typed error, not an AssertionError
401
+ error.violation.contract; // '@demands'
402
+ error.violation.thrownIndices; // [0]
403
+ error.cause.message; // names every arm, marking the one that threw
404
+ }
405
+ ```
406
+
407
+ The record describes each thrown value rather than holding it, because `ContractViolation` is otherwise plain data that a caller logs and serialises; the value itself is the error in their `catch`.
408
+
409
+ A thrown primitive is raised unchanged, since it has nowhere to carry the violation. A `TypeError` from inside a predicate — a bug rather than a decision — keeps its own class, so a caller's `catch` still branches on the bug rather than on a contract failure.
410
+
411
+ An error the contract did not create is never damaged: a frozen or non-extensible one is raised without the annotation, and a `cause` the consumer set is left alone. A contract's own `cause` never replaces one.
412
+
413
+ ### Raising a typed error with `onViolation`
414
+
415
+ A predicate must not throw, so a typed error cannot be raised from inside one. `@demands` and `@ensures` therefore accept an `onViolation` factory on their options, which runs **once, after every arm has failed**, and its result is what the caller receives:
416
+
417
+ ```typescript
418
+ import { Contracted, demands, type ContractViolation, type DemandsSubject } from '@final-hill/decorator-contracts';
419
+
420
+ class PermissionDenied extends Error {
421
+ override name = 'PermissionDenied';
422
+
423
+ constructor(message: string, readonly violation?: ContractViolation) {
424
+ super(message);
425
+ }
426
+ }
427
+
428
+ class Account extends Contracted {
429
+ private _balance = 0;
430
+
431
+ @demands(({ self }: DemandsSubject<Account>) => self._balance > 0, {
432
+ onViolation: violation => new PermissionDenied('insufficient funds', violation),
433
+ })
434
+ withdraw(): void {
435
+ this._balance--;
436
+ }
437
+ }
438
+ ```
439
+
440
+ The factory receives the full `ContractViolation`, which is the only machine-readable part of a failure. That is why the option takes a factory rather than a bare error constructor: an error boundary or a metadata-driven test needs `failedIndices`, `thrownIndices`, and the schema `issues`, and a constructor called without the violation would discard them.
441
+
442
+ The returned error carries the violation as `violation` and the `AssertionError` naming every unsatisfied arm as `cause`, both non-enumerable. A factory may supply its own `violation` and `cause`; those are kept, so an error that records what actually went wrong underneath keeps its record. The factory must return an object, since a primitive has nowhere to hold either field — that is reported as a `TypeError` naming the contract and feature, with the contract failure as its `cause`.
443
+
444
+ **Precedence across arms.** Scope is per contract, not per arm: there is no case where two arms of one contract need different error types, and per-arm would make precedence meaningless. When several arms declare a factory, the one belonging to the **first arm evaluated** decides — the same rule that makes the first passing arm decide a normalized value. Arms evaluate in the contract's composition order, so a decorator written last in source is evaluated first, and inherited arms come before a subclass's own. An arm that declares no factory defers to the next.
445
+
446
+ **When an arm also throws.** The factory still decides. A declared factory is the caller's explicit choice of error type, and it is given `thrownIndices` and `thrown`, so preferring it loses nothing.
447
+
448
+ **`@ensures` vs `@invariant`.** `@ensures` accepts the option on the same terms, with one difference at the boundary: when the body also leaves the instance invariant-invalid, the invariant failure is what the caller receives and the factory's error travels as its `cause`, because a broken instance is the state that has to surface. `@invariant` **refuses the option at decoration time**, because an invariant failure is what tells the lifecycle that the instance is in a state a `@rescue` handler must repair: the check is recognised by being an `AssertionError` whose `violation.contract` is `'@invariant'`. An error built by a factory is neither, so the repair protocol would not see it. Use a `@rescue` handler instead — it observes a failure a feature raised and can raise a typed error of its own.
449
+
450
+ That route covers the entry and exit checks only. The invariant `Contracted.new()` evaluates before it proxies the instance is outside every handler, so a class whose initial state violates an invariant reports an untyped `AssertionError`.
451
+
452
+ `checkedMode` disables the factory along with the contract, since a contract that does not run cannot fail.
453
+
454
+ ## Encapsulation
455
+
456
+ Encapsulation governs the **external surface**. Public property assignment is forbidden from outside a contracted class, so a caller cannot mutate state without a postcondition to catch it. All interactions must go through a method or getter/setter, and only properties starting with `_` (conventionally private) can be assigned to after construction.
457
+
458
+ ```typescript
459
+ class Example extends Contracted {
460
+ _private = 1; // Allowed
461
+ publicProp = 2; // Not allowed from outside
462
+ }
463
+ ```
464
+
465
+ The boundary begins *after* construction. A constructor runs before the instance is proxied, so its assignments — to public properties included — are unrestricted. That is deliberate: field initialisers and `Object.assign(this, ...)` are ordinary ways to establish initial state, and the invariant evaluated at the end of `Contracted.new()` is what validates the result.
466
+
467
+ ```typescript
468
+ class Example extends Contracted {
469
+ publicProp = 2; // allowed: field initialiser
470
+ constructor() {
471
+ super();
472
+ this.publicProp = 3; // allowed: still inside construction
473
+ }
474
+ }
475
+ ```
476
+
477
+ An external write to a public property raises a `TypeError`:
478
+
479
+ ```typescript
480
+ const example = Example.new();
481
+
482
+ example.publicProp = 3; // TypeError
483
+ ```
484
+
485
+ A feature body is $C$ and is **not** subject to this rule. It runs against the instance directly, so internal state — public or private — is its own business:
486
+
487
+ ```typescript
488
+ class Example extends Contracted {
489
+ publicProp = 1;
490
+
491
+ update(): void {
492
+ this.publicProp = 2; // allowed; `@ensures` and `@invariant` are the guarantee
493
+ }
494
+ }
495
+ ```
496
+
497
+ A method calling another method of the same instance likewise does not start a second contract lifecycle. The enclosing invocation owns the assertions, so the invariant is evaluated once on entry and once on exit regardless of how many internal accesses the body performs.
498
+
499
+ One consequence: a body that leaks `this` outward — passing it to a callback, storing it in a module-level variable, or returning it — hands out a reference that bypasses the traps. Do not do that; expose an explicit API instead.
500
+
501
+ ### An internal call runs none of the callee's contracts
502
+
503
+ Replacing a guard call with a contract does not widen coverage: it **turns the check off** at every internal call site.
504
+
505
+ ```typescript
506
+ import { Contracted, demands } from '@final-hill/decorator-contracts';
507
+
508
+ class Range extends Contracted {
509
+ @demands(({ args: [x] }) => x > 0)
510
+ inner(x: number) { return x; }
511
+
512
+ outer(x: number) { return this.inner(x); }
513
+ }
514
+
515
+ Range.new().outer(-1); // -1, and no error: `inner`'s @demands never ran
516
+ ```
517
+
518
+ Every contract on `inner` is skipped this way — `@demands`, `@ensures`, and the `@invariant` around it. Only `outer` is a boundary, so only `outer` is checked, and it returns whatever `inner` produced.
519
+
520
+ The mechanism is that a feature body runs against the **raw** instance, not the proxy (see above), so `this.inner(…)` reaches the undecorated function directly.
521
+
522
+ ### Why the body gets the raw instance
523
+
524
+ Handing the body the proxy instead would contract the internal call, which sounds like strictly more checking. It is not available, and the reason is not a preference about cost.
525
+
526
+ **A predicate is evaluated inside a trap, so its view must not start a lifecycle.** `@invariant(({ self }) => self.value >= 0)` reads `self.value` on every evaluation — twice for one getter read. A predicate therefore receives a purpose-built read-only proxy, not the instance's lifecycle proxy: reading through it is an ordinary property access, while assignment, deletion, and definition are refused. A feature body receives the raw target for the same reason — its internal accesses are not feature boundaries — and the two together are what keep one invocation to one lifecycle.
527
+
528
+ **The alternative also changes what the contract is about.** `{ P } C { Q }` treats `C` as unconstrained. If `C` ran other features' contracts, `outer`'s postcondition would be asserted over a composition of `inner`'s pre- and postconditions; a failure would name `inner` while `outer` is what the caller invoked, and the caller has no way to act on it.
529
+
530
+ **And it would make two ordinary shapes impossible.** A lenient façade delegating to a stricter core is a boundary today — a `@demands` of `x > 0` on `read` reaching a core requiring `x > 100` accepts `read(50)`, and the façade's arm runs exactly once. So is recursion: `down(n - 1)` is one lifecycle for the entry call. Contracting the internal call rejects the first and re-evaluates the invariant per frame for the second.
531
+
532
+ The cost of the rule is per call rather than per internal access: three internal calls to contracted features measure **2** invariant evaluations, not 4 or 6.
533
+
534
+ ### The cross-instance case is checked
535
+
536
+ A call on a **different** instance is a boundary, because the callee is reached through that instance's proxy. The same class, both directions:
537
+
538
+ ```typescript
539
+ class Range extends Contracted {
540
+ @demands(({ args: [x] }) => x > 0)
541
+ inner(x: number) { return x; }
542
+
543
+ viaThis(x: number) { return this.inner(x); } // `this` is raw: unchecked
544
+ viaPeer(peer: Range, x: number) { return peer.inner(x); } // peer is a proxy: checked
545
+ }
546
+
547
+ const range = Range.new();
548
+
549
+ range.viaThis(-1); // -1
550
+ range.viaPeer(range, -1); // @demands failed
551
+ ```
552
+
553
+ The second line fails even though `peer` is the same object, because what decides is whether the reference reaches the proxy, not whether the instances are equal. The rejection crosses the boundary as a throw into the calling feature's body, so the calling feature's `@rescue` observes it. A failure in the callee's own body runs the callee's handler first, on the callee's lifecycle; a failed `@demands` consults no handler at all, for the reason given under [What a `@rescue` observes](#what-a-rescue-observes).
554
+
555
+ ### Which shape to use
556
+
557
+ A public feature that another public feature calls needs one of two shapes. Both are correct; they trade a redundant declaration against a longer call chain.
558
+
559
+ **Every public verb declares its own arm.** The delegating verb declares the guard it would otherwise rely on the callee for, so the check is redundant by design:
560
+
561
+ ```typescript
562
+ class Repository extends Contracted {
563
+ @demands(({ args: [id] }) => id.length > 0)
564
+ read(id: string): unknown { return { id }; }
565
+
566
+ @demands(({ args: [id] }) => id.length > 0) // redundant, and the point
567
+ describe(id: string): unknown { return this.read(id); }
568
+ }
569
+ ```
570
+
571
+ This is the shape to reach for when a verb is cheap to describe and the precondition is short. The duplication is a property of the boundary rather than an accident, so it does not drift: a call from outside reaches `describe` and runs its arm, and the call it makes inward is the same computation it already authorised.
572
+
573
+ **A public verb is a guard plus a delegation to a private core.** The guarded work lives in one place, and each public entry point guards it:
574
+
575
+ ```typescript
576
+ class Repository extends Contracted {
577
+ @demands(({ args: [id] }) => id.length > 0)
578
+ read(id: string): unknown { return this.core(id); }
579
+
580
+ @demands(({ args: [id] }) => id.length > 0)
581
+ describe(id: string): unknown { return this.core(id); }
582
+
583
+ /** Not contracted: every public path to it is. */
584
+ core(id: string): unknown { return { id }; }
585
+ }
586
+ ```
587
+
588
+ The `core` method is deliberately undecorated. It is not a boundary a caller can reach, so a contract on it would be unreachable code; the guard belongs to the verbs that are reachable.
589
+
590
+ ### The declaration still reads as enforcement
591
+
592
+ The consequence that follows from all of this is that `@demands` on a feature reached only internally declares an obligation nothing enforces, and the library cannot refuse it at the point it is written. Every other contract in this library refuses a declaration it cannot honour — `normalize` on a predicate arm, `normalize` on `@invariant`, `allowWeakening` on an AND-composed contract — because a declaration that cannot act reads as an intention that is in force when it is not. This is the one case where the check would have to see a call, and a decorator is handed the element and a context, never the body.
593
+
594
+ A runtime warning cannot close it either. The body holds the raw target, so `this.inner(x)` is a direct function call with no trap to observe it, and making the body's `this` an observing proxy would fire on the redundant-arm shape above, which is correct code.
595
+
596
+ So the rule is a review question about your class rather than something the compiler or this library can check: a feature that is only ever reached from inside the class needs its guard on the verb a caller actually invokes.
597
+
598
+ ### Deletion
599
+
600
+ Deletion is an external mutation, so it follows exactly the same rule as assignment: `_`-prefixed properties may be deleted, public properties may not, and the invariant is evaluated around the deletion.
601
+
602
+ | Expression | Result |
603
+ | --- | --- |
604
+ | `delete example._private` | allowed |
605
+ | `delete example.publicProp` | `TypeError` |
606
+ | `delete example.nonexistent` | `TypeError` (the name is not `_`-prefixed) |
607
+
608
+ The last row surprises people, but it is the same rule `set` applies to an assignment of a property that does not exist: the restriction is on the *name*, not on whether the property is present. Once checked mode is disabled the proxy steps aside and `delete` behaves as it does on a plain object.
609
+
610
+ ### Property definition
611
+
612
+ Defining a property is the same kind of external mutation as assigning one, so it follows the same rule: only `_`-prefixed names may be defined, and `Object.defineProperty`, `Reflect.defineProperty`, and `Object.defineProperties` are all intercepted.
613
+
614
+ This matters because definition can do more than assignment. Redefining a public field escapes the postcondition that would have caught the change, and replacing a contracted **method** routes callers around its `@demands` and `@ensures` entirely:
615
+
616
+ ```typescript
617
+ const example = Example.new();
618
+
619
+ Object.defineProperty(example, 'publicProp', { value: 3 }); // TypeError
620
+ Object.defineProperty(example, 'guard', { value: () => 1 }); // TypeError
621
+ ```
622
+
623
+ A **prototype setter does not authorise defining the same name**, unlike assignment. Assignment invokes the setter, which is the sanctioned route; defining an own property shadows the accessor instead of invoking it, so it is refused.
624
+
625
+ Two operations remain available for every property name, because neither changes nor shadows state:
626
+
627
+ | Expression | Result |
628
+ | --- | --- |
629
+ | `Object.freeze(example)` | allowed (seals each existing property) |
630
+ | `Object.seal(example)` | allowed |
631
+ | `Object.preventExtensions(example)` | allowed (no property definition involved) |
632
+
633
+ Once an instance is frozen, a write it cannot accept **throws**, rather than being reported as a successful assignment.
634
+
635
+ ### Replacing the prototype
636
+
637
+ `Object.setPrototypeOf` and `Reflect.setPrototypeOf` throw. A replacement changes which descriptors a feature resolves to, which would leave the instance running methods that do not match the contracts it reports.
638
+
639
+ ## Inspecting and serializing
640
+
641
+ A contracted instance holds its state in `_`-prefixed properties, so the two ways of turning an instance into something printable behave differently on purpose: one shows a developer everything, and the other publishes a shape the class declares.
642
+
643
+ ### `util.inspect` shows the instance, not the proxy
644
+
645
+ `util.inspect` renders the class name and the instance's own state:
646
+
647
+ ```text
648
+ Account { _balance: 5, _orgId: 'o' }
649
+ ```
650
+
651
+ Without this the fallback rendering labels it as a proxy — `Proxy(Account { ... })` — so a reader cannot tell a contracted instance from an accidental one, and a nested instance renders the same way again.
652
+
653
+ The `_`-prefixed fields **are** shown. That is the point: `inspect` is the surface a developer uses to see what an object actually holds, and hiding the state would defeat it. It is not a serialization format.
654
+
655
+ The rendering reads own property *descriptors*, so it runs no contract and cannot fail because one does. A contracted instance is therefore inspectable in exactly the situation a reader most needs it: when its invariant is broken, or when a getter throws.
656
+
657
+ An accessor is not rendered, because it holds no state — its value is already visible through the field it reads. A reference back to an instance already being rendered is shown as `[Circular]`.
658
+
659
+ The name reported is the class's [`contractName`](#naming-a-class-in-a-failure) when it declares one, and the constructor's name otherwise, so a class that named itself is named the same way in a debugger as in a failure.
660
+
661
+ `depth` is honoured the way `util.inspect` honours it for a plain object: the instance itself is shown at `depth: 0`, each unit of depth shows one more level, and the first value with no budget left is rendered `[Object]`.
662
+
663
+ Two options are **not** honoured, because the rendering reports state rather than evaluating it: `showHidden` does not filter the `_`-prefixed fields out (they are the state being shown), and `getters: true` cannot opt an accessor in.
664
+
665
+ A subclass may replace the rendering by declaring its own method:
666
+
667
+ ```typescript
668
+ class Account extends Contracted {
669
+ protected _balance = 0;
670
+
671
+ get balance() { return this._balance; }
672
+
673
+ [Symbol.for('nodejs.util.inspect.custom')]() {
674
+ return `Account(${this.balance})`;
675
+ }
676
+ }
677
+ ```
678
+
679
+ ### `JSON.stringify` is opt-in
680
+
681
+ By default `JSON.stringify` emits the instance's own data properties, which are the `_`-prefixed ones:
682
+
683
+ ```typescript
684
+ JSON.stringify(Account.new()); // {"_balance":5,"_orgId":"o"}
685
+ ```
686
+
687
+ That is a leak, but it cannot be fixed by a default `toJSON`. Which fields are *public* is a decision about your domain, and `_` is a convention this library enforces for assignment rather than a declaration of what may be published. A default would also change the output of every existing `JSON.stringify`, which is the kind of silent break a library must not make.
688
+
689
+ So a class opts in with `@serializable`, naming the getters to publish:
690
+
691
+ ```typescript
692
+ import { Contracted, serializable } from '@final-hill/decorator-contracts';
693
+
694
+ @serializable('balance', 'orgId')
695
+ class Account extends Contracted {
696
+ protected _balance = 0;
697
+ protected _orgId = 'o';
698
+
699
+ get balance() { return this._balance; }
700
+ get orgId() { return this._orgId; }
701
+ }
702
+
703
+ JSON.stringify(Account.new()); // {"balance":0,"orgId":"o"}
704
+ ```
705
+
706
+ Naming **getters** rather than fields is deliberate: a field name is storage, while a getter is the class's own statement of what is observable, and it is already the only way a caller reads state the encapsulation rule protects. The published shape is therefore the shape a caller can already see. Every name is checked when the decorator runs, so a typo fails at the declaration rather than producing an empty object in whichever logger calls it.
707
+
708
+ One class declares one shape. Applying `@serializable` twice, or applying it to a class that already declares its own `toJSON`, is a `TypeError` at decoration time — the two declarations cannot both be the shape the class publishes, and silently preferring one of them would publish a shape the author did not choose.
709
+
710
+ The published shape follows substitution: a subclass that declares its own `@serializable` publishes its own list, and one that declares nothing inherits the base's, because the subclass *is* a base instance. `toJSON` is a public feature, so the entry and exit `@invariant` hold around the whole serialization.
711
+
712
+ ### What is not supported
713
+
714
+ Neither of these produces a usable copy, and both are limitations rather than defects:
715
+
716
+ | Expression | Result |
717
+ | --- | --- |
718
+ | `{ ...instance }` | own data only; methods live on the prototype, so they are lost, and the copy is not contracted |
719
+ | `structuredClone(instance)` | `DataCloneError` |
720
+
721
+ `structuredClone` fails on **any** `Proxy`, not just this library's — a bare `new Proxy({ a: 1 }, {})` fails the same way. A `toJSON` does not help it either, since cloning does not consult that method. A copy that is both useful and contracted needs an explicit copy protocol, which is a larger question than a serialization surface and is not provided here.
722
+
723
+ ## Asynchronous features
724
+
725
+ A feature declared `async` is fully contracted. Because an `async` body returns its promise before a single line of it has run, the exit boundary follows the value: `@ensures` and the exit `@invariant` are evaluated after the promise settles, against the state the body actually reached.
726
+
727
+ ```typescript
728
+ class Account extends Contracted {
729
+ protected _balance = 0;
730
+ public _ledger!: Ledger; // a collaborator the caller sets
731
+ get balance() { return this._balance; }
732
+
733
+ @demands(({ self, args: [amount] }) => self.balance + amount >= 0)
734
+ @ensures(({ self, args: [amount], old }) => self.balance === old.balance + amount)
735
+ async deposit(amount: number): Promise<void> {
736
+ await this._ledger.record(amount); // suspension happens here
737
+ this._balance += amount; // observed by @ensures
738
+ }
739
+ }
740
+ ```
741
+
742
+ The lifecycle is unchanged in order and in count: `@invariant` -> `@demands` -> body -> `@ensures` -> `@invariant`, with the invariant evaluated twice per call. Only the *position* of the exit checks differs, because the body has not finished until the promise settles. A `@rescue` observes rejections as it observes synchronous throws, and `retry` restarts the lifecycle for an asynchronous feature too.
743
+
744
+ ### Failure is delivered as a rejection
745
+
746
+ A contract violation on an `async` feature reaches the caller as a rejected promise, never as a synchronous throw — the same way the feature's own errors reach it. Adding a contract to a feature must not change how its failures are observed.
747
+
748
+ ```typescript
749
+ await assert.rejects(() => account.deposit(-5)); // AssertionError, not a sync throw
750
+ ```
751
+
752
+ This follows from substitutability. `() => T` and `() => Promise<T>` are mutually non-assignable in TypeScript, so neither is a subtype of the other and no sync/async conversion is implied. What must hold is the observable surface: a caller of the undecorated feature receives a promise that may reject, so a caller of the contracted feature must receive the same.
753
+
754
+ ### A synchronous feature must not return a promise
755
+
756
+ Contracts on a feature that is not declared `async` are evaluated when its body returns. A body that defers its work through a promise would therefore be checked before it has done anything, so this is rejected:
757
+
758
+ ```typescript
759
+ @ensures(...)
760
+ thenable(): Promise<void> { // AssertionError: not declared 'async'
761
+ return (async () => { await work(); this._value++; })();
762
+ }
763
+ ```
764
+
765
+ Declare the feature `async` instead. Awaiting arbitrary thenables was rejected as a rule because it would make the `async` keyword optional while silently changing when failures are reported: a plain function cannot return pending work *and* raise the resulting failure itself.
766
+
767
+ ### An awaited predicate
768
+
769
+ An `async` feature's exit checks already sit behind its promise, so its entry checks can wait for one too. Declaring `awaitPredicate` allows a `@demands` or `@ensures` predicate to answer with a promise, which the lifecycle awaits before it decides the arm:
770
+
771
+ ```typescript
772
+ class Account extends Contracted {
773
+ protected _limit = 100;
774
+ protected _balance = 0;
775
+
776
+ @demands(async ({ self, args: [amount] }) => self._balance + amount <= self._limit, { awaitPredicate: true })
777
+ @ensures(async ({ self, args: [amount], old }) => self._balance === old._balance + amount, { awaitPredicate: true })
778
+ async deposit(amount: number): Promise<void> {
779
+ this._balance += amount;
780
+ }
781
+ }
782
+ ```
783
+
784
+ The option is the opt-in, not the predicate's shape. Without it an `async` predicate is a compile error and, at runtime, the same refusal a synchronous feature gives: a verdict that has not settled must not be read as a yes.
785
+
786
+ Awaiting a predicate decides only *when* the verdict arrives, not what it means:
787
+
788
+ - Only a resolved `true` permits the call. A resolved non-boolean is refused, exactly as a synchronous non-boolean is.
789
+ - A predicate that throws or rejects is a **failed arm**, not an abort. `@demands` is OR-composed, so a sibling arm may still permit the call; the rejection is raised only if every arm fails. `@ensures` is AND-composed, so every arm is still evaluated and the rejection is reported with the others.
790
+
791
+ The option is refused where nothing could await it: a getter or setter (read or assigned synchronously), a generator or async generator (one boundary per step — awaiting one would make every `next()` asynchronous), `@invariant` (evaluated on every accessor access), and a schema arm (`validate` is synchronous). Each refusal happens where the declaration is written, naming the reason.
792
+
793
+ The exit checks keep their place. When no arm asked to be awaited, `@ensures` and the exit `@invariant` run in the tick the body settles in, so a caller that resumes cannot observe state the invariant has not approved. Only a declaring arm adds a suspension, and the exit `@invariant` runs as soon as that suspension settles.
794
+
795
+ An awaited `@demands` keeps the instance reachable across one more await boundary, so a concurrent caller can observe it between the check and the body. That window is the same one a hand-written guard that reads a database already has; it is not hidden here.
796
+
797
+ ### Generators
798
+
799
+ A generator has a contract boundary per **step**, not one per call. Calling the feature runs nothing; each `next()` runs the body from where it was suspended up to the following `yield`. When `next()` returns the segment has finished and the instance holds the state it will be observed with, so the contracts bracket each step:
800
+
801
+ ```text
802
+ call -> @invariant, @demands the call arguments are P
803
+ next() -> @invariant entry of the step
804
+ segment -> body up to the next yield
805
+ next() -> @ensures, @invariant the yielded value and the new state are Q
806
+ ```
807
+
808
+ This is the same sandwich shown above, applied once per step. A yield is the observable delivery of a traversal, which is what `@ensures` describes, so every yielded value must satisfy it:
809
+
810
+ ```typescript
811
+ class Counter extends Contracted {
812
+ protected _count = 0;
813
+
814
+ @ensures(({ self, args: [_value], old }: EnsuresSubject<Counter, [number], unknown>) => self._count === old._count + 1)
815
+ *tick(): Generator<number> {
816
+ this._count++; yield this._count; // each step is checked
817
+ this._count++; yield this._count;
818
+ }
819
+ }
820
+ ```
821
+
822
+ The `old` snapshot is per step, not per traversal: it describes the state the segment is about to change. A `return` value is not covered by `@ensures`, because nothing is yielded.
823
+
824
+ #### Why the invariant runs on every resume
825
+
826
+ A suspended generator's instance is publicly reachable, so another feature can be called on it between yields. Checking the invariant only at completion would leave the object knowingly invalid for the whole traversal, and would never check at all if the iterator were abandoned or only partially drained. Evaluating it on each resume is what keeps the guarantee every other feature already has: no public interaction leaves the object invalid.
827
+
828
+ ```typescript
829
+ const iterator = ledger.payments();
830
+ iterator.next(); // segment 1 checked on exit
831
+ ledger.audit(); // a public call, and it sees a valid object
832
+ ```
833
+
834
+ #### `@demands` describes the call
835
+
836
+ `@demands` runs once, on the first step: there is one call, so there is one precondition. A later step may also be *given* a value through `next(value)`, which becomes the value of the preceding `yield` expression and is not an argument of the call; that input is checked as a precondition **when it is present**. `for...of` iterates with `next()` and injects nothing, so it never re-enters the precondition with `undefined`:
837
+
838
+ ```typescript
839
+ @demands(({ args: [count] }) => count > 0)
840
+ *gen(count: number): Generator<number> { /* ... */ }
841
+
842
+ for (const value of obj.gen(3)) { /* works: no value is injected */ }
843
+ ```
844
+
845
+ #### `@rescue` covers the traversal
846
+
847
+ A generator that has already been consumed cannot be resumed from the beginning, so `retry` restarts the traversal, rerunning the body exactly as it does for an ordinary feature. A throw escaping a step is what the handler observes.
848
+
849
+ ## Note on Private Fields and Accessors
850
+
851
+ Due to the use of JavaScript `Proxy` in the implementation of this library, native `#private` fields and the `accessor` keyword are **not supported**. Instead, use conventional private fields (e.g., `_private`) and define explicit getter/setter pairs for encapsulation:
852
+
853
+ ```typescript
854
+ class Example extends Contracted {
855
+ private _value = 0;
856
+ get value() { return this._value; }
857
+ set value(v: number) { this._value = v; }
858
+ }
859
+ ```
860
+
861
+ Do **not** use:
862
+
863
+ - `#privateField` syntax
864
+ - `accessor foo` syntax
865
+
866
+ These will not work correctly with the contract enforcement provided by this library.
867
+
868
+ ## Invariants
869
+
870
+ Use the `@invariant` decorator on your class to enforce relationships between properties and methods. The invariant is checked after construction, before and after every method execution, and before and after every get/set usage.
871
+
872
+ ```typescript
873
+ @invariant(({ self }) => self.value >= 0)
874
+ class Foo extends Contracted {
875
+ protected _value = 0;
876
+ get value() { return this._value; }
877
+ set value(v: number) { this._value = v; }
878
+
879
+ inc(): void { this.value++; }
880
+ dec(): void { this.value--; }
881
+ }
882
+ ```
883
+
884
+ ### Contract predicates must return a boolean
885
+
886
+ `@invariant`, `@demands`, and `@ensures` predicates must return `true` or `false`. The result is not coerced: a non-boolean result raises an `AssertionError` naming the contract, the feature, and which predicate in the composition failed.
887
+
888
+ ```typescript
889
+ @demands(() => Promise.resolve(true)) // AssertionError: returned a Promise
890
+ ```
891
+
892
+ This is deliberate. A `Promise` is always truthy, so coercing the result would silently treat an accidentally asynchronous predicate — one that has not actually checked anything yet — as a satisfied contract. Failing closed is the only safe option, and the message points at the mistake.
893
+
894
+ A predicate that needs an asynchronous answer is supported on an `async` feature, when the declaration opts in: see [An awaited predicate](#an-awaited-predicate).
895
+
896
+ Asynchronous *features* are supported; see [Asynchronous features](#asynchronous-features).
897
+
898
+ ### Contract predicates may not change the instance
899
+
900
+ A predicate answers a question, so it cannot change the state it is asked about. `@invariant`, `@demands`, and `@ensures` receive a **read-only view** of the instance: assigning, deleting, or defining a property raises a `TypeError` naming the property.
901
+
902
+ ```typescript
903
+ @demands(({ self }) => { self._value = 0; return true; })
904
+ // TypeError: A contract predicate may not assign '_value'.
905
+ ```
906
+
907
+ This matters because a predicate runs *between* the entry and exit `@invariant`. A write inside a predicate can therefore hide a violation the invariant would otherwise have reported, turning a detectable bug into a silent one.
908
+
909
+ ```typescript
910
+ @invariant(({ self }) => {
911
+ self._value = 0; // would repair the state being checked
912
+ return self._value >= 0; // and then pass
913
+ })
914
+ ```
915
+
916
+ `@rescue` is deliberately **not** restricted. Restoring corrupted state is its purpose, so its handler receives the raw instance.
917
+
918
+ #### What is not blocked
919
+
920
+ The guard covers the instance's own surface. A mutation *through* a nested value still reaches the shared object:
921
+
922
+ ```typescript
923
+ @demands(({ self }) => { self._items.push(item); return true; }) // not intercepted
924
+ ```
925
+
926
+ Closing that would mean deep-wrapping every value a predicate reads, which changes object identity and would break legitimate comparisons such as `old.child === self.child`. The guarantee is therefore "a predicate cannot assign to the instance", which is the case that corrupts contract evaluation.
927
+
928
+ The feature body is unaffected: it still receives the instance itself and mutates freely. The view is scoped to the predicate call, which is why a scoped `Proxy` is used rather than `Object.freeze` — freezing is permanent, and would leave the body unable to change anything afterwards.
929
+
930
+ ### Subcontracting and Invariants
931
+
932
+ When subclassing, if a subclass defines its own `@invariant`, the resulting invariant is **strengthened**: the subclass invariant and the base class invariant are both enforced (they are logically AND-ed together). This means all invariants in the inheritance chain must hold for the object to be valid.
933
+
934
+ ```typescript
935
+ @invariant(({ self }) => self.value >= 0)
936
+ class Base extends Contracted {
937
+ // ...
938
+ }
939
+
940
+ @invariant(({ self }) => self.value <= 10)
941
+ class Sub extends Base {
942
+ // ...
943
+ }
944
+ // The effective invariant for Sub is: (self.value >= 0) && (self.value <= 10)
945
+ ```
946
+
947
+ ## Demands
948
+
949
+ Use the `@demands` decorator to specify preconditions for methods or get/set. If the condition fails, an error is thrown before the method executes.
950
+
951
+ ```typescript
952
+ class Foo extends Contracted {
953
+ protected _value = 0;
954
+ get value() { return this._value; }
955
+ set value(v: number) { this._value = v; }
956
+
957
+ @demands(({ self }) => self.value >= 0)
958
+ dec(): void { this.value--; }
959
+ }
960
+ ```
961
+
962
+ ### Subcontracting and Demands
963
+
964
+ When subclassing, if a subclass defines its own `@demands` for a method, the resulting precondition is **weakened**: the subclass and base class demands are OR-ed together. The method can be called if **any** of the demands in the inheritance chain are satisfied.
965
+
966
+ ```typescript
967
+ class Base extends Contracted {
968
+ @demands(({ args: [x] }) => x >= 0)
969
+ foo(x: number) { /* ... */ }
970
+ }
971
+
972
+ class Sub extends Base {
973
+ @demands(({ args: [x] }) => x === 42)
974
+ override foo(x: number) { /* ... */ }
975
+ }
976
+ // The effective demand for Sub#foo is: (x >= 0) || (x === 42)
977
+ ```
978
+
979
+ A demand is called with a `DemandsSubject`: `{ self, args }`. `args` is the
980
+ **argument list** of the invocation, so destructure it inside the parameter:
981
+ `({ args: [x] }) => x >= 0`. Writing `({ args }) => args >= 0` does not compile,
982
+ because `args` is the array rather than the first argument.
983
+
984
+ A predicate takes one object rather than a positional list, so the shape it
985
+ expects is visible where it is declared: a predicate that reads only `self` is
986
+ written `({ self }) => ...`, and the parameter list says so. The runtime supplies
987
+ every field listed above whether or not the predicate destructures it.
988
+
989
+ ## Ensures
990
+
991
+ Use the `@ensures` decorator to specify postconditions for methods or get/set. If the condition fails, an error is thrown after the method executes.
992
+
993
+ ```typescript
994
+ class Foo extends Contracted {
995
+ protected _value = 0;
996
+ get value() { return this._value; }
997
+ set value(v: number) { this._value = v; }
998
+
999
+ @ensures(({ self }) => self.value >= 0)
1000
+ dec(): void { this.value--; }
1001
+ }
1002
+ ```
1003
+
1004
+ ### The `old` instance
1005
+
1006
+ A postcondition receives `old`, a snapshot of the instance taken immediately before the feature ran. `old` inherits from the instance, so prototype getters and methods remain usable, and reading a prototype getter on `old` returns the historical value:
1007
+
1008
+ ```typescript
1009
+ class Counter extends Contracted {
1010
+ protected _n = 0;
1011
+ get n() { return this._n; }
1012
+
1013
+ @ensures(({ self, old }) => self.n === old.n + 1)
1014
+ inc(): void { this._n++; }
1015
+ }
1016
+ ```
1017
+
1018
+ Own state is copied, so mutations made by the feature body are not visible through `old`. The copy is deep for the containers contracts routinely compare:
1019
+
1020
+ | Value | Behaviour in `old` |
1021
+ | --- | --- |
1022
+ | Primitives | copied |
1023
+ | Arrays | cloned recursively |
1024
+ | `Date` | cloned |
1025
+ | `Map`, `Set` | cloned (keys and values recursively) |
1026
+ | Plain objects | cloned recursively, including cycles |
1027
+ | Class instances | **shared by reference** |
1028
+ | Functions | **shared by reference** |
1029
+
1030
+ Class instances and functions are shared deliberately. They carry behaviour, so a structural copy would produce an object that is not a real instance of its class, and many cannot be cloned meaningfully at all. The consequence is that mutating a class instance held in a field *is* visible through `old`; if a postcondition depends on such an object's previous state, copy it explicitly in the predicate.
1031
+
1032
+ Accessors are copied as descriptors rather than evaluated, so snapshotting never invokes a getter.
1033
+
1034
+ ### The `oldArgs` arguments
1035
+
1036
+ `oldArgs` is the same snapshot, taken over the call's arguments instead of the
1037
+ instance. It is what lets a postcondition describe an object it was *given*: a
1038
+ consequence that spans two objects belongs to neither one, so it is stated by a class
1039
+ that takes both as arguments, and `oldArgs` is how that class asks what its argument
1040
+ was before the call.
1041
+
1042
+ ```typescript
1043
+ class Usage extends Contracted {
1044
+ @demands(({ args: [book] }) => !book.onHold)
1045
+ @ensures(({ args: [book], oldArgs: [before] }) => book.onHold && !before.onHold)
1046
+ holdForPatron(book: Book, _patron: string): void { book.placeHold(_patron); }
1047
+ }
1048
+ ```
1049
+
1050
+ Without `oldArgs` the only spelling of that property is `book.onHold && !book.onHold`,
1051
+ which is false for every book, or a comparison against the argument itself, which is
1052
+ vacuously true: `old` shares a class instance by reference, so `old.…` and `self.…` are
1053
+ the same object when the instance is held in a field.
1054
+
1055
+ It follows `old`'s policy exactly, and one detail is worth stating because it differs
1056
+ from the instance case: a **contracted argument** is copied the way `old` is. The copy
1057
+ is a new object that shares the argument's prototype and its own state, so a getter on
1058
+ it reads the historical value. Its descriptors are read below the proxy, so
1059
+ snapshotting an argument does not run that object's contracts and does not fail on an
1060
+ instance that is already invalid. Every other argument takes the field rule: plain
1061
+ containers are cloned, class instances are shared by reference.
1062
+
1063
+ The snapshot is taken **after `@demands` and before the body**, so it is the argument
1064
+ the body actually receives — a normalizing precondition has already replaced it — and
1065
+ a mutation the body makes is not visible through it. A `@rescue` that retries takes a
1066
+ fresh snapshot for the retried attempt.
1067
+
1068
+ It is taken whenever the feature declares a predicate `@ensures` arm, whether or
1069
+ not that particular arm reads it, because an arm is not inspectable for what it
1070
+ references. One case is excluded on the strength of the declaration rather than a
1071
+ guess: when **every** `@ensures` arm is a Standard Schema, no arm is handed the
1072
+ subject at all — a schema validates the result — so neither snapshot is taken.
1073
+
1074
+ Two consequences follow when an arm could read it:
1075
+
1076
+ - An argument that cannot be described fails the call. A `Proxy` with a throwing
1077
+ `getPrototypeOf`, for instance, raises a `TypeError` naming the feature and the
1078
+ argument's position before the body runs.
1079
+ - A large plain-data argument is deep-cloned on every call. A 200 000-element array
1080
+ measured 1.4 ms per call, against about 1 µs for the same feature with no `@ensures`.
1081
+
1082
+ A getter and a generator carry an empty `oldArgs`: their `args` describes a result or
1083
+ a yielded value, neither of which has a pre-state.
1084
+
1085
+ ### Subcontracting and Ensures
1086
+
1087
+ When subclassing, if a subclass defines its own `@ensures` for a method, the resulting postcondition is **strengthened**: the subclass and base class ensures are AND-ed together. The method's result must satisfy **all** ensures in the inheritance chain.
1088
+
1089
+ ```typescript
1090
+ class Base extends Contracted {
1091
+ @ensures(({ args: [x] }) => x >= 0)
1092
+ foo(x: number) { /* ... */ }
1093
+ }
1094
+
1095
+ class Sub extends Base {
1096
+ @ensures(({ args: [x] }) => x <= 10)
1097
+ override foo(x: number) { /* ... */ }
1098
+ }
1099
+ // The effective ensures for Sub#foo is: (x >= 0) && (x <= 10)
1100
+ ```
1101
+
1102
+ A postcondition is called with an `EnsuresSubject`: `{ self, args, old, result }`.
1103
+ `args` is the argument list, `old` is the snapshot of the instance from before the
1104
+ feature ran, and `result` is the value the feature produced. Destructure the
1105
+ fields the predicate reads; the runtime supplies the rest unused.
1106
+
1107
+ ### The `result`
1108
+
1109
+ A postcondition receives `result`, the value the feature returned:
1110
+
1111
+ ```typescript
1112
+ class Proposal extends Contracted {
1113
+ protected _state = 'Draft';
1114
+ get state() { return this._state; }
1115
+
1116
+ @ensures(({ result }: EnsuresSubject<Contracted, any[], any>) => result.state === 'Proposed')
1117
+ submit(): Proposal {
1118
+ this._state = 'Proposed';
1119
+ return this;
1120
+ }
1121
+ }
1122
+ ```
1123
+
1124
+ For a getter, `result` is the value the getter returned. For an `async` feature
1125
+ it is the settled value, so the postcondition observes the promise's resolution
1126
+ rather than the promise. For a generator it is the value yielded by the step being
1127
+ checked, because a generator's boundary is per step.
1128
+
1129
+ A rejected `async` feature has no value to describe, so `@ensures` does not run for
1130
+ it; the rejection reaches the caller (or `@rescue`) directly. The same holds for a
1131
+ getter that returns a promise, which is refused as an `async` mistake before any
1132
+ postcondition is evaluated: `result` is therefore the value a *synchronous* getter
1133
+ returned.
1134
+
1135
+ Every arm receives the **same** result: the raw value the body produced. A
1136
+ normalizing schema arm validates that value and only then replaces what the caller
1137
+ receives, so a predicate and a normalizing schema in one composition agree about
1138
+ what they were shown. `result` is therefore *not* the post-normalization value.
1139
+
1140
+ A write has no value to deliver, so for a setter `result` is the value that was
1141
+ assigned.
1142
+
1143
+ ## Rescue
1144
+
1145
+ Use the `@rescue` decorator to handle exceptions thrown by a method, restore invariants, or retry execution:
1146
+
1147
+ ```typescript
1148
+ import { Contracted, rescue } from '@final-hill/decorator-contracts';
1149
+
1150
+ class Example extends Contracted {
1151
+ private _value = 3;
1152
+ get value() { return this._value; }
1153
+ set value(v) { this._value = v; }
1154
+
1155
+ @rescue(({ self }) => self.value = 5)
1156
+ method1(): void { throw new Error('I am error'); }
1157
+ }
1158
+ ```
1159
+
1160
+ You can also use the `retry` function in your rescue handler to attempt the method again:
1161
+
1162
+ ```typescript
1163
+ class Example extends Contracted {
1164
+ @rescue(({ retry }) => retry(3))
1165
+ method(value: number): number {
1166
+ if (value <= 0)
1167
+ throw new Error('value must be greater than 0');
1168
+ else
1169
+ return value;
1170
+ }
1171
+ }
1172
+ ```
1173
+
1174
+ `retry` passes **only** the arguments you give it — it does not replay the original arguments. To retry with the same arguments, forward the `args` you received:
1175
+
1176
+ ```typescript
1177
+ @rescue(({ args, retry }) => retry(...args))
1178
+ ```
1179
+
1180
+ Calling `retry()` retries with no arguments.
1181
+
1182
+ A `@rescue` handler **cannot supply the feature's result**. Only `retry` can produce one, by running the body again; a value returned from the handler is ignored, and the original error is raised to the caller when `retry` is not called. To recover with a substitute value, restructure the body to accept the alternative and retry with it:
1183
+
1184
+ ```typescript
1185
+ @rescue(({ args, retry }) => {
1186
+ // the handler restores state, then asks for a second attempt
1187
+ retry(...args);
1188
+ })
1189
+ method(value: number): number { /* ... */ }
1190
+ ```
1191
+
1192
+ This keeps the postcondition meaningful: a result the body never produced would not be covered by `@ensures`.
1193
+
1194
+ ### What a `@rescue` observes
1195
+
1196
+ A handler is the place to repair an instance, so it sees every failure that leaves state worth repairing:
1197
+
1198
+ | Failure | Reaches the feature's own `@rescue`? |
1199
+ | --- | --- |
1200
+ | the body throws | **yes** |
1201
+ | own `@ensures` fails | **yes** |
1202
+ | own `@invariant` fails, on entry or exit | **yes** |
1203
+ | own `@demands` fails | **no** |
1204
+
1205
+ The last row is deliberate. A precondition rejects a call that has not begun, so there is no body to resume, and a handler that retried with an argument the precondition also rejects would recurse without end. A failed precondition therefore reaches the caller directly.
1206
+
1207
+ The third row is what makes a broken instance recoverable. Once an instance fails its invariant, every accessor throws on exit, so without this a handler could not even reach the state it would fix:
1208
+
1209
+ ```typescript
1210
+ import nodeAssert from 'node:assert/strict';
1211
+ import { Contracted, invariant, rescue } from '@final-hill/decorator-contracts';
1212
+
1213
+ @invariant(({ self }) => self._balance >= 0)
1214
+ class Account extends Contracted {
1215
+ public _balance = 1;
1216
+ @rescue(({ self }) => { self._balance = 0; })
1217
+ withdraw(amount: number): void { this._balance -= amount; }
1218
+ }
1219
+
1220
+ const account = Account.new();
1221
+ nodeAssert.throws(() => account.withdraw(5), /@invariant failed/); // overdrawn
1222
+ account._balance; // 0 — usable again
1223
+ ```
1224
+
1225
+ The call still fails, because `@rescue` resumes a body and this one has already run. What the handler buys is an instance that is valid again, which a later `retry` can use.
1226
+
1227
+ A getter or setter behaves the same way: the handler runs and can repair the instance, but the access is not resumed, because an accessor has no body to re-run. A handler that repairs a getter's state therefore leaves the instance usable without that particular read succeeding.
1228
+
1229
+ A handler is called **before** the invariant is re-tested, so it can repair the state rather than being denied the attempt. That means a handler observes the error that failed, which is the body's own error when the body threw.
1230
+
1231
+ When nothing has repaired the instance, the invariant failure supersedes the original on the way to the caller, and the original travels as `cause`:
1232
+
1233
+ ```typescript
1234
+ import { Contracted, invariant } from '@final-hill/decorator-contracts';
1235
+
1236
+ @invariant(({ self }) => self._balance >= 0)
1237
+ class Account extends Contracted {
1238
+ public _balance = 1;
1239
+
1240
+ withdraw(amount: number): void {
1241
+ this._balance -= amount;
1242
+ if (this._balance < 0) throw new Error('insufficient funds');
1243
+ }
1244
+ }
1245
+
1246
+ try {
1247
+ Account.new().withdraw(5); // body throws, and leaves the balance negative
1248
+ } catch (error: any) {
1249
+ error.violation.contract; // '@invariant'
1250
+ error.cause.message; // 'insufficient funds'
1251
+ }
1252
+ ```
1253
+
1254
+ A handler that repairs the state before declining to retry prevents that: the instance is valid by the time the invariant is re-tested, so the body's own error is what the caller receives.
1255
+
1256
+ Because a handler runs before the invariant is re-tested, it receives the error that failed rather than the invariant failure that may supersede it. A per-feature handler knows which feature it was attached to, so that is unambiguous; a class-level handler covers every feature, which is why the subject carries `feature` (see [One handler for a whole class](#one-handler-for-a-whole-class)).
1257
+
1258
+ ### Retry bounds
1259
+
1260
+ `retry` restarts the body, so it can always be attempted again. The one boundary that cannot be restarted is the *entry* check: nothing has run yet, so a retry can only re-check the state the handler just set. That repair is attempted **once**; if the invariant still fails, the failure is raised rather than looping, because every further attempt would fail identically.
1261
+
1262
+ Everywhere else, retries are unbounded by default and `maxRetries` bounds them, as described under [N-Version programming](#robustness-organized-panic-and-the-benefits-of-rescue). An unbounded handler that never repairs will therefore loop until it does — that is the price of allowing a handler to choose the next alternative.
1263
+
1264
+ ### One handler for a whole class
1265
+
1266
+ `@rescue` also applies to a class, where it covers every feature that declares none of its own:
1267
+
1268
+ ```typescript
1269
+ import { Contracted, rescue } from '@final-hill/decorator-contracts';
1270
+
1271
+ @rescue(({ feature, error }) => {
1272
+ // one translation and one telemetry event, whichever verb failed
1273
+ console.log(`${String(feature)} failed`, error);
1274
+ })
1275
+ class Service extends Contracted {
1276
+ charge(_amount: number): void { /* ... */ }
1277
+ refund(_amount: number): void { /* ... */ }
1278
+ }
1279
+ ```
1280
+
1281
+ The subject is unchanged, and `feature` is what makes the form usable: a per-feature handler knows its own name because it was written next to it, while a class-level handler serves all of them. It holds the property key the lifecycle was running for, so `delete` reports the deleted property and an accessor reports its own name.
1282
+
1283
+ **Precedence** is fixed, and the two rules answer different questions:
1284
+
1285
+ 1. A **feature-level** declaration wins over any class-level one, including one on the class that declares the feature. Inheriting a feature declaration from a base class already works, and being inherited is not a reason to lose to the class-level form.
1286
+ 2. Otherwise the **nearest class-level** declaration walking up the constructor chain applies, so a subclass overrides a handler its base declared without restating it per feature.
1287
+
1288
+ ```typescript
1289
+ class Base extends Contracted {
1290
+ @rescue(({ self }) => { self._reset(); }) // 1: wins for `run`
1291
+ run(): void { throw new Error('boom'); }
1292
+
1293
+ _reset(): void { /* ... */ }
1294
+ }
1295
+
1296
+ @rescue(({ error }) => { console.log(error); }) // 2: wins for `other`
1297
+ class Sub extends Base {
1298
+ other(): void { throw new Error('boom'); }
1299
+ }
1300
+ ```
1301
+
1302
+ **What it covers** is every feature the lifecycle runs for: methods, getters, setters, async functions, generators, and the `delete` trap. A getter has no body to re-run, so `retry` on a failing read restarts the read rather than supplying a value, which is what a per-feature handler does already.
1303
+
1304
+ A `_`-prefixed feature is covered by neither form. The decorator refuses a feature-level `@rescue` on one, so the class-level form leaves it out too: a feature a consumer cannot override is a feature they could not exempt from the class handler.
1305
+
1306
+ **What it does not solve.** A class-level handler inherits the per-feature semantics exactly, so it does not make a typed precondition reachable: a failed `@demands` still never consults a handler, because nothing ran. Rescue means "resume the body", and a failed precondition has no body to resume; use the [`onViolation` factory](#raising-a-typed-error-with-onviolation) for that.
1307
+
1308
+ `maxRetries` is counted per invocation of the feature the handler served, not across the class, so two failing calls each get their own budget, and one failing feature does not spend another's.
1309
+
1310
+ ### Robustness, Organized Panic, and the Benefits of `@rescue`
1311
+
1312
+ The `@rescue` decorator enables a mechanism for **Robustness** in your code. It allows your implementation to respond to situations not specified, providing the ability to handle exceptions in a structured way. This is sometimes called **Organized Panic**.
1313
+
1314
+ In addition, `@rescue` provides a foundation for **N-Version programming**, **Fault-Tolerance**, and **Redundancy**. You can implement multiple strategies for handling errors, retrying with alternative logic or data, and ensuring your application can recover from unexpected failures.
1315
+
1316
+ A retried invocation re-enters the full assertion lifecycle (`@invariant` -> `@demands` -> body -> `@ensures`), and if it fails again the `@rescue` handler runs again. This means the handler is executed once per attempt, which is what N-Version programming requires: each invocation of the handler can select the next alternative.
1317
+
1318
+ A dated example of this is performing ajax requests in a multi-browser environment:
1319
+
1320
+ ```typescript
1321
+ import { Contracted, rescue } from '@final-hill/decorator-contracts';
1322
+
1323
+ declare function legacyGet(url: string): string;
1324
+ declare function activeXGet(url: string): string;
1325
+ declare function xhrGet(url: string): string;
1326
+ declare const window: any;
1327
+
1328
+ class AjaxRequest extends Contracted {
1329
+ private _version = 0;
1330
+ private _versions = ['legacy', 'activex', 'xhr'] as const;
1331
+
1332
+ @rescue(({ self, args, retry }) => {
1333
+ self._version++;
1334
+ retry(...args);
1335
+ }, { maxRetries: 2 })
1336
+ get(url: string): string {
1337
+ const version = this._versions[this._version];
1338
+
1339
+ switch (version) {
1340
+ case 'legacy':
1341
+ if (!window.XMLHttpRequest) throw new Error(`${version} unsupported`);
1342
+ return legacyGet(url);
1343
+ case 'activex':
1344
+ if (!window.ActiveXObject) throw new Error(`${version} unsupported`);
1345
+ return activeXGet(url);
1346
+ default:
1347
+ return xhrGet(url);
1348
+ }
1349
+ }
1350
+ }
1351
+ ```
1352
+
1353
+ Because a rescue handler may retry unconditionally, retries are unbounded by default. Set the `maxRetries` option on the `@rescue` declaration to bound them; when the limit is reached the last error is raised to the caller:
1354
+
1355
+ ```typescript
1356
+ @rescue(({ args, retry }) => retry(...args), { maxRetries: 3 })
1357
+ ```
1358
+
1359
+ The option belongs to the declaration because the number of alternatives is a property of the feature, not of an individual failure. It is enforced per invocation of the feature, so a single call performs at most `maxRetries` retries however many `@rescue` executions that involves.
1360
+
1361
+ Unlike traditional `try/catch`, where exceptions are non-resumable and often handled far from the source (leading to scattered and redundant error handling), `@rescue` allows for **resumable exceptions** and localized, declarative error handling. This means:
1362
+
1363
+ - You can lexically determine where exception handling occurs.
1364
+ - You can restore invariants or perform corrective actions before retrying or failing.
1365
+ - You can optionally call `retry` to attempt the method again with new arguments or after fixing state, providing a form of fault tolerance and robustness.
1366
+ - You can implement alternative strategies for error recovery, supporting N-Version programming and redundancy.
1367
+
1368
+ **Inheritance:**
1369
+
1370
+ If a base class declares a `@rescue` handler for a method, that handler is inherited by subclasses unless the subclass overrides it with its own `@rescue` declaration. A class-level declaration follows the same rule and is inherited by a subclass that declares none of its own; see [One handler for a whole class](#one-handler-for-a-whole-class) for how the two forms rank against each other.
1371
+
1372
+ This approach leads to more maintainable and robust code, as error handling is organized and closely tied to the contract of the class feature, rather than being scattered throughout the call stack.
1373
+
1374
+ ## Standard Schema
1375
+
1376
+ `@invariant`, `@demands`, and `@ensures` accept a [Standard Schema V1](https://github.com/standard-schema/standard-schema) value anywhere they accept a predicate. Zod, Valibot, ArkType, and Effect Schema are then interchangeable: the library consumes the protocol and never depends on a provider.
1377
+
1378
+ ```typescript
1379
+ import { z } from 'zod';
1380
+ import { Contracted, demands, ensures } from '@final-hill/decorator-contracts';
1381
+
1382
+ const positive = z.number().positive();
1383
+ const quantity = z.tuple([z.number().positive()]);
1384
+
1385
+ class Inventory extends Contracted {
1386
+ protected _stock = 0;
1387
+ get stock() { return this._stock; }
1388
+
1389
+ @demands(quantity) // validates the argument tuple
1390
+ @ensures(positive) // validates the result
1391
+ add(...[count]: [number]): number {
1392
+ this._stock += count;
1393
+
1394
+ return this._stock;
1395
+ }
1396
+ }
1397
+ ```
1398
+
1399
+ ### What a schema validates
1400
+
1401
+ The subject is the subject the contract already describes, so the two kinds of arm are interchangeable:
1402
+
1403
+ | Decorator | A schema validates | A predicate receives | Composition |
1404
+ | --- | --- | --- | --- |
1405
+ | `@invariant` | the instance | `({ self })` | AND |
1406
+ | `@demands` | the **argument tuple** | `({ self, args })` | OR |
1407
+ | `@ensures` | the **result** | `({ self, args, old, oldArgs, result })` | AND |
1408
+
1409
+ Because `@demands` validates the argument tuple rather than the first argument, a one-parameter method is written as a tuple of one (`z.tuple([...])`). This keeps the subject unambiguous for any arity, and it is what makes an issue's `path` point at the argument that failed.
1410
+
1411
+ A schema is the subject for the contract, not for the feature it happens to guard: `@demands` takes the tuple, `@ensures` takes the result, `@invariant` takes the instance. Declaring the tuple once and sharing it keeps that true across every feature with the same shape:
1412
+
1413
+ ```typescript
1414
+ const quantity = z.tuple([z.number().positive()]);
1415
+
1416
+ class Inventory extends Contracted {
1417
+ @demands(quantity) add(count: number): number { /* ... */ }
1418
+ @demands(quantity) remove(count: number): number { /* ... */ }
1419
+ }
1420
+ ```
1421
+
1422
+ ### `normalize` and `@invariant`
1423
+
1424
+ `normalize` replaces the contract's subject with the schema's output, which is meaningful where the subject is something the runtime can substitute: the arguments for `@demands`, and the result for `@ensures`.
1425
+
1426
+ An invariant's subject is the instance, and nothing replaces it. `normalize` is therefore **refused at decoration time**, for either kind of arm:
1427
+
1428
+ ```text
1429
+ @invariant cannot normalize: its subject is the instance, which no arm can replace.
1430
+ ```
1431
+
1432
+ The option is refused for what it would do rather than for appearing, so
1433
+ `normalize: false` is still accepted.
1434
+
1435
+ ### Composition follows variance
1436
+
1437
+ The rules above are the substitution rules, not a convention:
1438
+
1439
+ - **`@demands` is contravariant.** A subtype may accept *wider* input, so conditions are OR-composed and any inherited arm satisfies the call. A subtype adding an arm therefore **weakens** the precondition.
1440
+ - **`@ensures` and `@invariant` are covariant.** A subtype may promise *narrower* output and must preserve *more* state, so conditions are AND-composed and every arm must hold. A subtype adding an arm therefore **strengthens** the obligation.
1441
+
1442
+ A schema arm composes exactly like a predicate arm, which is why no separate decorators exist: the rule belongs to the contract, not to the kind of arm.
1443
+
1444
+ **A narrowing subtype precondition has no effect, and that is correct.** Writing `@demands(z.number().min(5))` in a subtype does not restrict anything, because OR-composition keeps the inherited arm. A subtype is not permitted to narrow what its supertype accepts, so the runtime refuses to give it that power. TypeScript will not catch the mistake either — **method parameters are bivariant** under `strictFunctionTypes` — so this is a review obligation. Declare input schemas on the base feature.
1445
+
1446
+ Because that mistake is easy to make and silent, declaring a `@demands` arm on a feature that already has inherited arms **warns** at decoration time, naming the feature and the inherited arm count:
1447
+
1448
+ ```text
1449
+ @demands on add adds an arm to a precondition that already has 2 inherited arm(s).
1450
+ `@demands` is OR-composed, so this arm cannot narrow what the base permits:
1451
+ satisfying any inherited arm still allows the call. Move the restriction to the
1452
+ base feature, or declare the arm with `allowWeakening` if a genuine weakening is
1453
+ what was meant.
1454
+ ```
1455
+
1456
+ It warns rather than throws because the arm is always a legal weakening — the defect is the author's model of it, not the declaration. Pass `{ allowWeakening: true }` when the wider precondition is what you meant.
1457
+
1458
+ The warning is issued once per feature however many arms the class declares, since it describes the feature rather than any one arm.
1459
+
1460
+ `allowWeakening` is refused on `@ensures` and `@invariant`. It suppresses a diagnostic about OR-composition, which only a precondition has, so on an AND-composed contract it would be a declaration that could never do anything. This is the same rule `normalize` and `onViolation` follow: an option that cannot act is a mistake about which contract the declaration belongs to.
1461
+
1462
+ **This asymmetry is `@demands`-only.** An `@ensures` arm on a subclass is AND-composed, so it genuinely strengthens the obligation and takes effect:
1463
+
1464
+ ```typescript
1465
+ class Base extends Contracted {
1466
+ @ensures(({ result }: { result: number }) => result >= 0)
1467
+ m(): number { return 5; }
1468
+ }
1469
+
1470
+ class Sub extends Base {
1471
+ @ensures(({ result }: { result: number }) => result <= 3) // does restrict the result
1472
+ override m(): number { return 5; }
1473
+ }
1474
+
1475
+ Base.new().m(); // 5
1476
+ Sub.new().m(); // @ensures failed: the base arm passes, the subclass arm does not
1477
+ ```
1478
+
1479
+ `@invariant` behaves like `@ensures`: it is AND-composed and covariant. Only a precondition is contravariant, which is why only a precondition has an arm that cannot narrow.
1480
+
1481
+ ### Failure reporting
1482
+
1483
+ A schema failure carries the provider's own `issues` in the structured payload, and renders them into the message:
1484
+
1485
+ ```typescript
1486
+ try {
1487
+ inventory.add(-1);
1488
+ } catch (error) {
1489
+ error.violation?.contract; // '@demands'
1490
+ error.violation?.issues; // ReadonlyArray<{ message, path? }>
1491
+ }
1492
+ ```
1493
+
1494
+ One consequence of validating the argument tuple is that an issue's `path` is also relative to it, so the first argument is index `0`:
1495
+
1496
+ ```text
1497
+ @demands failed for Shipping.send (1 of 1 schema unsatisfied: schema #1: ...).
1498
+ Reported: 0.zip: Invalid string: must match pattern /^\d{5}$/.
1499
+ ```
1500
+
1501
+ ### Normalization is opt-in
1502
+
1503
+ `validate` may transform its input. Applying that transformation changes what the body receives and what later contracts observe, so it is an explicit choice:
1504
+
1505
+ ```typescript
1506
+ @demands(trimmedName, { normalize: true })
1507
+ rename(name: string): void { /* receives the trimmed name */ }
1508
+ ```
1509
+
1510
+ - **`@demands`** is OR-composed, so the **first passing arm** decides the normalized value. That is deterministic and matches evaluation order.
1511
+ - **`@ensures`** is AND-composed, so two normalizing arms would disagree about what the caller receives. That is refused at decoration time rather than resolved arbitrarily.
1512
+
1513
+ Off by default: without `normalize`, a schema only reports a verdict.
1514
+
1515
+ ### Synchronous only
1516
+
1517
+ Contract evaluation is synchronous, so a `validate` that returns a Promise is refused with a message asking for a synchronous schema. Treating a pending validation as satisfied would be worse than failing, and awaiting would move the feature's boundary.
1518
+
1519
+ ### No type inference
1520
+
1521
+ Decorators cannot change a feature's signature, so a schema gives **runtime enforcement only**: it neither narrows the declared parameter types nor infers `Input`/`Output`. Accurate inference needs a builder API, which this library does not have.
1522
+
1523
+ ### Providers
1524
+
1525
+ Any implementation of the protocol works, and no provider is a dependency. The `StandardSchemaV1` types are exported if you want to annotate your own schemas:
1526
+
1527
+ ```typescript
1528
+ import type { StandardSchemaV1 } from '@final-hill/decorator-contracts';
1529
+ ```
1530
+
1531
+ ## Inspecting contracts
1532
+
1533
+ `getContractMetadata(Class)` reports the contracts a class declares, and
1534
+ `getFeatureContracts(Class, feature)` reports the arms that apply to one feature
1535
+ in the order they are evaluated. Use them instead of reading `Contracted[Symbol.metadata]`
1536
+ directly: the symbol holds the record the runtime consults, so a consumer who edits
1537
+ it edits their own class's contracts. The accessors return frozen copies.
1538
+
1539
+ This is what turns "every public verb declares a precondition" into one
1540
+ architectural test rather than one test per verb:
1541
+
1542
+ ```typescript
1543
+ import {
1544
+ Contracted, getContractMetadata, getFeatureContracts, demands,
1545
+ } from '@final-hill/decorator-contracts';
1546
+
1547
+ class Repository extends Contracted {
1548
+ public _connected = true;
1549
+ get connected() { return this._connected; }
1550
+
1551
+ @demands(({ self }) => self.connected)
1552
+ read(_id: string): unknown { return { id: _id }; }
1553
+ }
1554
+
1555
+ const metadata = getContractMetadata(Repository);
1556
+
1557
+ metadata.invariants; // every class-level arm
1558
+ metadata.demands['read'].length; // 1: the arms declared for `read`
1559
+ getFeatureContracts(Repository, 'read').demands.length; // 1
1560
+ ```
1561
+
1562
+ The lists are already **effective**: a subclass's record contains its own
1563
+ declarations and the inherited ones, so there is no prototype chain to walk. The
1564
+ order is the evaluation order — inherited arms first, then the class's own, and
1565
+ within one class in **reverse source order**, because decorators evaluate
1566
+ bottom-up.
1567
+
1568
+ A class that declares nothing has no record at all, so both accessors report empty
1569
+ lists rather than `undefined`.
1570
+
1571
+ `@rescue` is reported as the declaration the runtime would apply. A feature’s own
1572
+ handler is `metadata.rescue[feature]`; when it declares none, `metadata.classRescue`
1573
+ is the handler a [class-level declaration](#one-handler-for-a-whole-class) gives it,
1574
+ and `getFeatureContracts` returns that one. A `_`-prefixed feature has neither, so
1575
+ both report `undefined` for it.
1576
+
1577
+ ### A predicate arm and a schema arm are not equally readable
1578
+
1579
+ The arm you get back is the one you declared, so a test can compare it against the
1580
+ declaration by identity. What it can then *do* with it depends on the kind:
1581
+
1582
+ - A **predicate** is opaque. Calling it is the whole interface: `({ args }) => args[0] > 0`
1583
+ describes its domain nowhere else, and reading its source text would be a second
1584
+ implementation of the predicate that also breaks under minification.
1585
+ - A **schema** may describe its own input when its provider carries the Standard JSON
1586
+ Schema trait, `schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' })`. That
1587
+ is a *separate* trait layered on Standard Schema V1, so it is optional and its
1588
+ coverage varies by provider; and it is lossy, because it reports bounds and `enum` but
1589
+ not refinements, transforms, or a `Date`.
1590
+
1591
+ So a schema arm can *propose* candidate inputs for a contract, and a predicate arm
1592
+ cannot. The verdict is still the contract's either way: a proposed value is only
1593
+ plausible until `validate` accepts it.
1594
+
1595
+ ### The stability guarantee
1596
+
1597
+ The shape of `ContractMetadata` and `FeatureContracts` is stable for the major
1598
+ version: fields may be added, but an existing field will not change meaning
1599
+ without one. The *arms* are whatever you declared — a predicate, a schema, and the
1600
+ options passed alongside it — so their identity is preserved and comparing an arm
1601
+ against the one you wrote works.
1602
+
1603
+ ## Contracts and your test suite
1604
+
1605
+ A contracted class already *is* a specification: `@demands` states what every
1606
+ permitted call assumes, `@ensures` what it guarantees, and `@invariant` what holds
1607
+ throughout. A test that restates one of those is a second copy of the same claim, and
1608
+ the copy is the one that drifts.
1609
+
1610
+ Three roles split the work. A **requirements class** declares the contracts and does
1611
+ not sequence them. A **specification driver** is a `Contracted` class with no state of
1612
+ its own whose features take the objects they relate as arguments; it states what no
1613
+ single class can, such as *a patron cannot hold a book that is already held*, using
1614
+ `@demands` over its own arguments and `@ensures` over `oldArgs`. A **scenario** is a
1615
+ test that supplies the inputs and shows the behaviour; it validates the
1616
+ specification and does not provide it.
1617
+
1618
+ The rule for a test you already have:
1619
+
1620
+ - An arrange block that only establishes a precondition → the precondition belongs in
1621
+ `@demands`, and the test goes.
1622
+ - An assertion that restates an `@ensures` or an `@invariant` → the test goes.
1623
+ - A property spanning two objects → keep it as a scenario, and if it is not yet a
1624
+ declaration, add the driver that states it.
1625
+ - A house rule over a set of classes → keep it; it reads `getContractMetadata` and no
1626
+ class's contracts can state it.
1627
+ - A regression or an interaction with the environment → keep it; no contract can
1628
+ state either.
1629
+
1630
+ What contracts cannot do is *show behaviour*: they say a property must hold, never
1631
+ what the system does or which inputs are interesting. So a sweep of inputs whose
1632
+ verdicts are the contract's is still a test, and a property over inputs the contract
1633
+ has already approved is still the strongest form of one. [Testing a contracted
1634
+ class](./docs/testing.md) is the long form: arranging state, asserting a failure,
1635
+ mocking, `async`, and generating inputs — including where a schema arm can propose
1636
+ them and a predicate arm cannot.
1637
+
1638
+ ## The order of assertions
1639
+
1640
+ When `obj.feature` is called the happy path is:
1641
+
1642
+ ![image](./docs/happy-path.png)
1643
+
1644
+ The invariant is evaluated **twice** per successful call: once on entry and once on exit. Each of `@demands`, the feature body, and `@ensures` runs once. Accessors follow the same lifecycle as methods, and an accessor that reads another accessor or calls a method does not start a nested lifecycle. That means the nested feature's own contracts do not run; see [An internal call runs none of the callee's contracts](#an-internal-call-runs-none-of-the-callees-contracts).
1645
+
1646
+ An `async` feature follows the same order with the exit checks moved after the promise settles, so they observe the state the body actually reached; its failures reach the caller as a rejection. A generator applies the same order **once per step**, as described in [Generators](#generators).
1647
+
1648
+ The entry check is not redundant with `Contracted.new()`. Object state can be corrupted without going through a checked feature — via `Object.defineProperty`, by running with checked mode disabled and re-enabling it, or internally from a feature body. The entry check is what turns that into a precise error at the next public interaction rather than letting an invalid object keep operating.
1649
+
1650
+ Because the invariant is checked first, an invalid object reports its invariant violation rather than a precondition failure. That ordering is deliberate: the object is broken in a way that makes the caller's arguments moot.
1651
+
1652
+ If an error is thrown and there is no `@rescue` defined then the `@invariant` is checked before the error is raised to the caller. If the instance has become invalid, that invariant failure is what reaches the caller, with the original error as its `cause`.
1653
+
1654
+ If an error is thrown in the `@invariant` then the `@rescue` is executed, so a handler can restore the state. Without a handler, or once its attempts are spent, the failure is raised to the caller.
1655
+
1656
+ If an error is thrown in the `@demands` then the error is raised to the caller, and `@rescue` is not consulted. A precondition rejects a call that has not begun, so there is no body to resume. The exit `@invariant` is not checked either, because the feature body has not been entered and the instance cannot have changed.
1657
+
1658
+ If an error is thrown by the feature body or the `@ensures` then the `@rescue` is executed. If `retry` is called then the process starts from the beginning.
1659
+
1660
+ If the retried invocation fails, its `@rescue` is executed again, so the handler runs once per attempt. Retries are bounded by the `maxRetries` option; without it they are unbounded.
1661
+
1662
+ If `@rescue` throws an error or does not call `retry` then the `@invariant` is checked before the error is raised to the caller.
1663
+
1664
+ ![image](./docs/order-of-assertions.png)
1665
+
1666
+ ## The subject a predicate is called with
1667
+
1668
+ Every contract calls its predicate with a single object. Destructuring is what
1669
+ makes the shape visible at the declaration, and it keeps every declaration to one
1670
+ parameter so a `max-params: 1` configuration is satisfied.
1671
+
1672
+ | Contract | Subject fields |
1673
+ | --- | --- |
1674
+ | `@demands` | `{ self, args }` |
1675
+ | `@ensures` | `{ self, args, old, oldArgs, result }` |
1676
+ | `@invariant` | `{ self }` |
1677
+ | `@rescue` | `{ self, error, args, retry, feature }` |
1678
+
1679
+ Bind the fields a predicate reads and omit the rest; the runtime supplies them all
1680
+ whether or not the parameter list names them. A predicate that destructured its
1681
+ arguments as `[x]` writes `({ args: [x] }) => x > 0`, so the body is unchanged.
1682
+
1683
+ The compiler rejects a parameter list that does not line up with the subject.
1684
+ A two-parameter leftover fails with *Target signature provides too few arguments*:
1685
+ `(self: Cart, [x]: [number]) => ...`. A one-parameter leftover is rejected
1686
+ because the instance is not assignable to a `DemandsSubject`: `(self: Cart) =>
1687
+ ...`. Parameters typed `any` are the one case the compiler cannot check, and such
1688
+ a predicate receives the subject object where it expects the instance.
1689
+
1690
+ `retry` is a field of the subject, so a handler that forwards its arguments
1691
+ writes `({ args, retry }) => retry(...args)`.
1692
+
1693
+ The subject is **inferred**, so a predicate that reads instance state usually needs
1694
+ no annotation at all:
1695
+
1696
+ ```typescript
1697
+ @demands(({ self, args }) => self.total + args[0] >= 0) // `self` is the class, `args` is the call tuple
1698
+ ```
1699
+
1700
+ An annotation is only needed when the runtime subject differs from the call
1701
+ signature. The one place that happens is a generator's `@ensures`, whose `args` is
1702
+ the value the step yielded rather than the call arguments:
1703
+
1704
+ ```typescript
1705
+ @ensures(({ args: [yielded] }: EnsuresSubject<Counter, [number]>) => ...)
1706
+ ```
1707
+
1708
+ `result` always stays `unknown`, because a method's return type and a getter's
1709
+ property type are both inference sites for it and the compiler would resolve it to
1710
+ their intersection. Name it on the subject when a predicate needs more.
1711
+
1712
+ ## Further Reading
1713
+
1714
+ - [Design by Contract](https://en.wikipedia.org/wiki/Design_by_contract)
1715
+ - [Liskov Substitution Principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle)
1716
+ - [Object-Oriented Software Construction](https://en.wikipedia.org/wiki/Object-Oriented_Software_Construction)