@final-hill/decorator-contracts 1.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +488 -9
- package/dist/AssertionError.d.mts +50 -1
- package/dist/Contracted.d.mts +15 -3
- package/dist/admissibility.d.mts +81 -0
- package/dist/assert.d.mts +53 -0
- package/dist/decorator.d.mts +12 -0
- package/dist/demands.d.mts +51 -3
- package/dist/ensures.d.mts +36 -3
- package/dist/iff.d.mts +6 -1
- package/dist/implies.d.mts +4 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/invariant.d.mts +23 -1
- package/dist/read-only.d.mts +45 -0
- package/dist/rescue.d.mts +58 -3
- package/dist/standard-schema.d.mts +46 -0
- package/package.json +33 -21
package/README.md
CHANGED
|
@@ -8,16 +8,21 @@
|
|
|
8
8
|
|
|
9
9
|
- [Introduction](#introduction)
|
|
10
10
|
- [Library Installation](#library-installation)
|
|
11
|
+
- [Node.js version](#nodejs-version)
|
|
12
|
+
- [Development](#development)
|
|
11
13
|
- [Usage](#usage)
|
|
12
14
|
- [Checked Mode](#checked-mode)
|
|
13
15
|
- [Assertions](#assertions)
|
|
14
16
|
- [Implies](#implies)
|
|
15
17
|
- [Iff](#iff)
|
|
18
|
+
- [Contracts are Hoare triples](#contracts-are-hoare-triples)
|
|
19
|
+
- [Contract failures](#contract-failures)
|
|
16
20
|
- [Encapsulation](#encapsulation)
|
|
17
21
|
- [Invariants](#invariants)
|
|
18
22
|
- [Demands](#demands)
|
|
19
23
|
- [Ensures](#ensures)
|
|
20
24
|
- [Rescue](#rescue)
|
|
25
|
+
- [Standard Schema](#standard-schema)
|
|
21
26
|
- [The order of assertions](#the-order-of-assertions)
|
|
22
27
|
- [Further Reading](#further-reading)
|
|
23
28
|
|
|
@@ -62,6 +67,33 @@ Via [skypack.dev](https://www.skypack.dev/):
|
|
|
62
67
|
|
|
63
68
|
`<script type="module" src="https://cdn.skypack.dev/@final-hill/decorator-contracts"></script>`
|
|
64
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
|
+
|
|
65
97
|
## Usage
|
|
66
98
|
|
|
67
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.
|
|
@@ -135,6 +167,8 @@ This is required so that the instance is wrapped in a Proxy and invariants are a
|
|
|
135
167
|
|
|
136
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.
|
|
137
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
|
+
|
|
138
172
|
By default, Checked Mode is enabled. You can control it via the static `[checkedMode]` symbol property of Contracted:
|
|
139
173
|
|
|
140
174
|
```typescript
|
|
@@ -184,9 +218,11 @@ When defining predicates it is a common use case to encode [material implication
|
|
|
184
218
|
import { implies } from '@final-hill/decorator-contracts';
|
|
185
219
|
|
|
186
220
|
implies(weather.isSunny, person.visitsBeach);
|
|
187
|
-
//
|
|
221
|
+
// Logically equivalent to: !weather.isSunny || person.visitsBeach
|
|
188
222
|
```
|
|
189
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
|
+
|
|
190
226
|
## Iff
|
|
191
227
|
|
|
192
228
|
When defining predicates it is a common use case to encode [if and only if](https://en.wikipedia.org/wiki/Logical_biconditional):
|
|
@@ -195,20 +231,218 @@ When defining predicates it is a common use case to encode [if and only if](http
|
|
|
195
231
|
import { iff } from '@final-hill/decorator-contracts';
|
|
196
232
|
|
|
197
233
|
iff(person.hasTicket, person.ridesTrain);
|
|
198
|
-
//
|
|
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
|
+
}
|
|
199
271
|
```
|
|
200
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
|
+
|
|
201
289
|
## Encapsulation
|
|
202
290
|
|
|
203
|
-
|
|
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.
|
|
204
292
|
|
|
205
293
|
```typescript
|
|
206
294
|
class Example extends Contracted {
|
|
207
295
|
_private = 1; // Allowed
|
|
208
|
-
publicProp = 2; // Not 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
|
+
}
|
|
209
309
|
}
|
|
210
310
|
```
|
|
211
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
|
+
|
|
212
446
|
## Note on Private Fields and Accessors
|
|
213
447
|
|
|
214
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:
|
|
@@ -244,6 +478,52 @@ class Foo extends Contracted {
|
|
|
244
478
|
}
|
|
245
479
|
```
|
|
246
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
|
+
|
|
247
527
|
### Subcontracting and Invariants
|
|
248
528
|
|
|
249
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.
|
|
@@ -282,17 +562,19 @@ When subclassing, if a subclass defines its own `@demands` for a method, the res
|
|
|
282
562
|
|
|
283
563
|
```typescript
|
|
284
564
|
class Base extends Contracted {
|
|
285
|
-
@demands((_self, x: number) => x >= 0)
|
|
565
|
+
@demands((_self, [x]: [number]) => x >= 0)
|
|
286
566
|
foo(x: number) { /* ... */ }
|
|
287
567
|
}
|
|
288
568
|
|
|
289
569
|
class Sub extends Base {
|
|
290
|
-
@demands((_self, x: number) => x === 42)
|
|
570
|
+
@demands((_self, [x]: [number]) => x === 42)
|
|
291
571
|
override foo(x: number) { /* ... */ }
|
|
292
572
|
}
|
|
293
573
|
// The effective demand for Sub#foo is: (x >= 0) || (x === 42)
|
|
294
574
|
```
|
|
295
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
|
+
|
|
296
578
|
## Ensures
|
|
297
579
|
|
|
298
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.
|
|
@@ -308,23 +590,55 @@ class Foo extends Contracted {
|
|
|
308
590
|
}
|
|
309
591
|
```
|
|
310
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
|
+
|
|
311
623
|
### Subcontracting and Ensures
|
|
312
624
|
|
|
313
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.
|
|
314
626
|
|
|
315
627
|
```typescript
|
|
316
628
|
class Base extends Contracted {
|
|
317
|
-
@ensures((_self,
|
|
629
|
+
@ensures((_self, [x]: [number]) => x >= 0)
|
|
318
630
|
foo(x: number) { /* ... */ }
|
|
319
631
|
}
|
|
320
632
|
|
|
321
633
|
class Sub extends Base {
|
|
322
|
-
@ensures((_self,
|
|
634
|
+
@ensures((_self, [x]: [number]) => x <= 10)
|
|
323
635
|
override foo(x: number) { /* ... */ }
|
|
324
636
|
}
|
|
325
637
|
// The effective ensures for Sub#foo is: (x >= 0) && (x <= 10)
|
|
326
638
|
```
|
|
327
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
|
+
|
|
328
642
|
## Rescue
|
|
329
643
|
|
|
330
644
|
Use the `@rescue` decorator to handle exceptions thrown by a method, restore invariants, or retry execution:
|
|
@@ -356,12 +670,70 @@ class Example extends Contracted {
|
|
|
356
670
|
}
|
|
357
671
|
```
|
|
358
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
|
+
|
|
359
693
|
### Robustness, Organized Panic, and the Benefits of `@rescue`
|
|
360
694
|
|
|
361
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**.
|
|
362
696
|
|
|
363
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.
|
|
364
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
|
+
|
|
365
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:
|
|
366
738
|
|
|
367
739
|
- You can lexically determine where exception handling occurs.
|
|
@@ -375,20 +747,127 @@ If a base class declares a `@rescue` handler for a method, that handler is inher
|
|
|
375
747
|
|
|
376
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.
|
|
377
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
|
+
|
|
378
847
|
## The order of assertions
|
|
379
848
|
|
|
380
849
|
When `obj.feature` is called the happy path is:
|
|
381
850
|
|
|
382
851
|

|
|
383
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
|
+
|
|
384
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.
|
|
385
862
|
|
|
386
863
|
If an error is thrown in the `@invariant` then it is raised to the caller.
|
|
387
864
|
|
|
388
|
-
If an error is thrown in the `@demands` then the error is raised to the caller. In this case the `@invariant` is not checked because the feature body has not been entered and the
|
|
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.
|
|
389
866
|
|
|
390
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.
|
|
391
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
|
+
|
|
392
871
|
If `@rescue` throws an error or does not call `retry` then the `@invariant` is checked before the error is raised to the caller.
|
|
393
872
|
|
|
394
873
|

|