Reference

Guide and API

This page covers installing adorn, the full constraint vocabulary, parameter names, constructor contracts, what each projection emits, the knobs, the CLI and the add-ons, the build-time lint included. At the end is a searchable index of every runtime export.

Getting started

1 · Install

terminal
npm i adorn

The only runtime dependency is tslib. It ships dual ESM + CommonJS through its exports map (import → a tree-shakeable ESM build, require → CommonJS, one shared set of .d.ts) and supports Node.js 20.19 and later (CI runs 20.19, 22 and 24). The ESM build shares one core across its entry points, so importing adorn and any subpath loads one copy, as CommonJS always did; a dual-loaded ESM and CommonJS copy also shares one registry.

The root is the authoring surface. The rest of the API sits on subpaths, so a consumer imports only what it uses, and each subpath also exports the types for what it holds:

Entry pointWhat it holds
adornDecorators, the descriptor namespaces and the Contracts facade, contract / contract.checked, Verify / Enforce, defineConstraint, and the configuration setters.
adorn/schemaThe projections: toolSchemaForMethod, toolSchemaForFunction, toolSchemaFrom, schemaForClass and the docs generators.
adorn/introspectionThe registry reads, parameterNameOf, the shared evaluators, normalise / sameNormalForm, and the breaking-change checks contractDiff / contractSnapshot / fragmentImplies.
adorn/observeObservation plumbing: getObservationSink, nextCallId, settle, violationFromCheck, numericBoundOf.
adorn/privacyThe privacy-review projection: telemetryForClass, generateTelemetryReport.
adorn/test
adorn/otel
adorn/eslint
The add-ons (property-based testing, OpenTelemetry, and the build-time contract lint), each behind an optional peer dependency.
adorn/package.jsonThe package manifest, so a consumer can record which adorn it ran: require('adorn/package.json').version.

2 · Enable decorators

tsconfig.json
{ "compilerOptions": { "experimentalDecorators": true } }

Decorator syntax needs only experimentalDecorators. emitDecoratorMetadata and reflect-metadata are optional and purely cosmetic: together they fill the inferred Type column in generated docs from design:paramtypes, and nothing else — enforcement, every projection and the tool schemas read the reified descriptor, not reflected metadata. Any experimentalDecorators-capable compiler works; for that optional Type column, tsc, ts-node, ts-jest and SWC (legacyDecorator + decoratorMetadata) emit the metadata, while esbuild, Vite and Bun don't. The descriptor-first path (Verify, contract(), toolSchemaFrom) works with no flags at all.

3 · Contract a method

weather.ts
import {
    Contract, Describe, Name, NotEmpty, OneOf,
    GreaterThanEqual, LessThanEqual,
} from 'adorn';

@Contract()
export class WeatherService {
    getWeather(
        @Name('location') @Describe('the city to look up') @NotEmpty() location: string,
        @Name('unit') @OneOf(['celsius', 'fahrenheit']) unit: string,
        @Name('days') @GreaterThanEqual(1) @LessThanEqual(7) days: number,
    ): string {
        return `${days}-day forecast for ${location} in ${unit}`;
    }
}

4 · Call it — invalid input never reaches the body

usage.ts
const weather = new WeatherService();

weather.getWeather('Lisbon', 'celsius', 3);   // ok — the body runs
weather.getWeather('Lisbon', 'celsius', 99);  // throws: 'days' must be ≤ 7; the body never runs

Every parameter of a contracted method is typed by a decorator that states what it holds: a constraint, or @Defined() for a value adorn can't type further, such as a store or a framework object. An untyped parameter throws a TypeError naming it when the class is installed, and a call that passes more arguments than the signature declares is refused before the body (see Signatures). @Name declares each parameter's name, which keys the tool schema below and survives minification (see Parameter names).

5 · Project the same contract

projections.ts
import { schemaForClass, documentClass, renderMarkdown, toolSchemaForMethod } from 'adorn/schema';

// One declaration, read many ways — none can disagree:
const schema = schemaForClass(WeatherService);                 // descriptive JSON Schema (2020-12)
const docs = renderMarkdown([documentClass(WeatherService)]);  // Markdown documentation
const tool = toolSchemaForMethod(WeatherService, 'getWeather', {
    description: 'Look up a weather forecast.',                 // the prescriptive LLM tool schema
});
One application: an LLM tool

Hand tool to a function-calling API as the tool's parameters (subject to the provider's dialect; add { provider: 'openai', strict: true } for OpenAI strict mode). When the model replies, route its arguments back through new WeatherService().getWeather(...) — the same contract that produced the schema rejects a bad reply before the body runs.

Prefer a value to an exception?

Validate the parsed arguments first with Verify.check(ObjectContracts.Fields({...}), 'args', args), which returns {ok, value} or {ok: false, path, expected, message}. A Fields is exact, so a key the tool doesn't declare is refused too. See Working with values.

Parameter constraints

Each one is a decorator for a parameter (@Between(1, 10)) and a descriptor in a namespace (NumberContracts.Between(1, 10)). Every predicate is total: a wrong-type value is a violation, never a TypeError.

The descriptor namespaces are also exposed through one fluent facade, Contracts, grouped by the type they constrain: Contracts.number.between(1, 10), Contracts.string.uuid(), Contracts.enum(['celsius', 'fahrenheit']), Contracts.nullable(Contracts.number.finite()). It is the same factories under one entry point — a second spelling, not a second implementation — usable anywhere a descriptor is.

DecoratorAcceptsSchema
@GreaterThan(n) / @GreaterThanEqual(n)number > n / ≥ nexclusiveMinimum / minimum
@LessThan(n) / @LessThanEqual(n)number < n / ≤ nexclusiveMaximum / maximum
@Between(a, b)a ≤ number ≤ bminimum + maximum
@Integer() · @MultipleOf(n)whole number · divisible by ntype: integer · multipleOf
@MinLength(n) · @MaxLength(n) · @StringMinLength(n)length boundsminLength · maxLength
@NotEmpty()a non-empty stringminLength: 1
@Matches(pattern, flags?)matches the patternpattern
@Email() · @Url()a simple-shape ASCII email · URLformat: email · format: uri
@Uuid() · @DateTime() · @Ipv4() · @Format(name)validating formats; date-time is strict RFC 3339format
@OneOf([...])strict === membershipenum
@Const(v)exactly vconst

String lengths count Unicode code points, so they agree with the minLength/maxLength they emit. @Format(name) also takes the named formats hex, lowercase-hex, digits, ascii-letters, iso-date, iso-datetime, email, e164-phone and url-http. Literal text is descriptor-only: StringContracts.StartsWith(prefix), EndsWith(suffix) and Contains(part) compare UTF-16 code units, case-sensitive, and project to an escaped, anchored pattern.

Times are descriptor-only too. TimeContracts.Date(), Timestamp() and Duration() accept RFC 3339 dates and timestamps and ISO 8601 durations, with optional inclusive {min, max} bounds written in the same form, and compare them as instants and lengths rather than as strings: '2026-01-01T00:30:00+01:00' is refused by Timestamp({min: '2026-01-01T00:00:00Z'}), because it is half an hour before it. A value that is not a valid time is refused, never coerced.

ValueContracts.Defined() (also Contracts.defined(), and the parameter decorator @Defined()) accepts any value except undefined: the declared type of a parameter or field adorn can't type further. ValueContracts.Func() (Contracts.func()) accepts a function. Both are descriptors like any other: stored, generated by the fuzzer and read by contractDiff. Prefer a real type where one exists.

Stacked decorators conjoin and evaluate top to bottom. @Positive() and friends were removed on purpose, because a name can't carry a boundary. Write @GreaterThan(0).

Composition

nested shapes, as data
const member = ObjectContracts.Fields({
    name: StringContracts.NotEmpty(),
    roles: ArrayContracts.ArrayOf(EnumContracts.OneOf(['admin', 'editor', 'viewer']), { minItems: 1 }),
    note: NullableContracts.Nullable(StringContracts.NotEmpty()),
});

Verify.check(member, 'member', { name: 'Ada', roles: ['admin', 'wizard'], note: null });
// { ok: false, path: ['roles', 1], expected: 'one of "admin", "editor", "viewer"', … }
  • @ArrayOf(item, {minItems?, maxItems?}): every element satisfies item. A failure names the element's index.
  • @Dictionary(value): an open map of string keys to values matching value.
  • @Shape(FieldClass): a DTO validated against another class's declared fields. It builds a Fields descriptor from the fields that carry a field decorator (base classes included), so it is exact in the same way; @Optional() on a field lets its key be absent.
  • ObjectContracts.Fields({...}, {extra?}): an optional-aware object literal, with no class needed. Exact by default; {extra: 'allow'} opens it (below).
  • @Nullable(item): also accepts null. This is different from @Optional, which means the value may be absent.

Exact objects, and {extra: 'allow'}

A Fields({...}) or @Shape is exact. Once every declared field holds, the first own key that isn't declared is refused at its path, and the schema emits additionalProperties: false, which is a statement about enforcement rather than producer-steering. A declared optional key is never extra. Pass {extra: 'allow'} (the FieldsOptions type; Contracts.object and Shape take it too) to let one object accept undeclared keys; its schema then emits no additionalProperties. Openness belongs to the one object that opts out, not to the objects nested in it. In violation facts and telemetry, an undeclared key is [REDACTED] by default, because the caller chose it.

an exact list item, the default
const items = ArrayContracts.ArrayOf(
    ObjectContracts.Fields({ id: NumberContracts.Integer() }),
);

Verify.check(items, 'items', [{ id: 1 }, { id: 2, debug: true }]);
// { ok: false, path: [1, 'debug'], expected: "no field 'debug' (exact object with fields id)", … }

Markers

MarkerEffect
@Optional()An absent argument is fine, and the parameter is dropped from the tool schema's required. If any inheritance level requires it, it stays required. It marks a position without typing it, so it sits beside a constraint. On a field, it lets a @Shape key be absent.
@Default(v)Publishes {default: v} into the schema and implies @Optional. It does not inject the value; the host applies it.
@Name('…')The parameter's declared name: the key of its tool-schema property, its snapshot entry and its OpenTelemetry attribute, and its label in messages and docs. See Parameter names.
@Describe('…')The property's description, which the model reads.
@Tool('…')The tool's top-level description.
@Defined()Not a marker but the loosest type: any value except undefined, for a parameter adorn can't type further (a store, a class instance, a callback). @Optional() @Defined() is any value, or absent. The fuzzer fills such a position from gapFill.

Pre- and postconditions

bank.ts
@Contract()
class Bank {
    @Requires((amount: number, balance: number) => amount <= balance, 'cannot overdraw')
    @Returns(NumberContracts.GreaterThanEqual(0))
    @Ensures((result: unknown, amount: number, balance: number) =>
        (result as number) === balance - amount, 'balance drops by exactly the amount')
    withdraw(@GreaterThanEqual(1) amount: number, @GreaterThanEqual(0) balance: number): number {
        return balance - amount;
    }
}

new Bank().withdraw(30, 100);   // 70
new Bank().withdraw(150, 100);  // throws @Requires (caller overdrew)
new Bank().withdraw(0, 100);    // throws @GreaterThanEqual(1) on `amount`
DecoratorWhenBlamesProjects
@EnabledWhen((self, ...args) => bool)before, reads statecallerno
@Requires((...args) => bool) or a relationbeforecallerclosure: no; relation: docs
@Returns(descriptor)after, on the settled valuecalleeyes
@Ensures((result, ...args) => bool) or a relationafter, on the settled valuecalleeclosure: no; relation: docs

All four stack on one signature. A guard that returns false means "not enabled"; a guard that throws is treated as a defect in the guard itself and propagates unchanged.

Pre-state capture: old

@Ensures also has an options form, @Ensures({ predicate, capture?, description?, id? }). When capture is given, capture(...args) runs at call entry; its deep-cloned, frozen result is passed to the predicate as old, ahead of the arguments. That lets a postcondition compare the final result against pre-call state, so a body that mutates one of its arguments can't mask its own violation. The same capture form is available on contract() and contract.checked's ensures.

old — the snapshot taken before the call
@Ensures({
    capture: (account: Account) => ({ balance: account.balance }),       // snapshot at entry
    predicate: (result: number, old, account: Account) =>
        account.balance === old.balance - result,                        // compare against the frozen snapshot
})
withdraw(@Defined() account: Account, @GreaterThan(0) amount: number): number {
    account.balance -= amount;   // mutates the argument; `old` still holds the entry balance
    return amount;
}

Relations as data: RelationContracts

A clause that relates arguments to each other, or the result to the inputs, can be a descriptor instead of a closure. Operands are Arg(index, ...path), Result(...path), Old(...path) and Value(json); clauses are Equal, NotEqual, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, Satisfies, All, Any, Not and Implies. A relation is enforced exactly as a closure is, and it also names itself in the violation message and facts, appears in generated docs, and round-trips through JSON. A built-in relation is passed bare; any other descriptor over the call's bindings, such as a TimeContracts comparison, goes in as {relation: d}.

the overdraw check, as data
const { Arg } = RelationContracts;

const withdraw = contract.checked(
    {
        params: [NumberContracts.Finite(), NumberContracts.Finite()],
        requires: [RelationContracts.LessThanEqual(Arg(0), Arg(1))],
    },
    (amount: number, balance: number) => balance - amount,
);
withdraw(150, 100);   // { ok: false, band: 'requires', message: 'Precondition not met (args[0] <= args[1])', … }

// Times compare as instants, not strings.
const stay = { relation: TimeContracts.LessThan('date', Arg(0), Arg(1)) };

normalise(clause) and sameNormalForm(a, b) (from adorn/introspection) give a relational clause a normal form, so a reworded clause (De Morgan, a mirrored comparison, reordered operands) can be told from a changed one. The rules are sound, not complete: true means the two hold on the same bindings, false shows nothing.

Field contracts

account.ts
@Contract()
class Account {
    @Enforce.greaterThanEqual(0) balance = 0;   // validated on every assignment
    @Enforce.notEmpty() owner = 'unknown';
}

Enforce has a method for every constraint (greaterThan, between, oneOf, uuid, arrayOf, shape, nullable and so on). CreateFieldDecorator(descriptor) wraps any descriptor, including your own. Field contracts are inherited: a subclass can strengthen them but never weaken them.

A field contract is checked on every assignment, and on a @Contract() class also once at the end of construction: a required field the constructor never assigned is refused, and an @Optional() one may stay undefined (see Constructor contracts). Only the class actually constructed must establish its required fields: a field a plain (uncontracted) subclass sets after super() is accepted, and its value is still checked on that assignment. That check also covers useDefineForClassFields, the TypeScript default from target: ES2022, under which a field declaration would otherwise shadow adorn's accessor.

Constructor contracts

A constructor takes the same parameter decorators and markers as a method. @Requires and @Ensures go on the class, written below @Contract(); in a class-level @Ensures, Result() is the new instance. A contracted constructor follows the method rules: every parameter typed, no required parameter after an optional one, and a call past the signature refused unless extraArgs: 'allow'.

account.ts
import {
    Contract, Enforce, GreaterThanEqual, Name, NotEmpty, Optional, Requires,
    RelationContracts as R,
} from 'adorn';

@Contract()
@Requires(R.LessThanEqual(R.Arg(0), 1_000_000), 'opening at most a million')
class Account {
    @Enforce.greaterThanEqual(0) balance: number;
    @Enforce.notEmpty() owner: string;

    constructor(
        @Name('opening') @GreaterThanEqual(0) opening: number,
        @Name('owner') @NotEmpty() owner: string,
        @Name('note') @Optional() @NotEmpty() note?: string,
    ) {
        this.balance = opening;
        this.owner = owner;
    }
}

new Account(10, 'Ada');   // ok
new Account(-1, 'Ada');   // throws: Account.constructor(opening, owner, note) parameter 'opening' …

The checks run in order: the parameters and the signature, @Requires, the constructor body, the field invariant, then @Ensures. The input checks blame the caller; the invariant and @Ensures blame the class. The invariant is its own band, 'invariant': a required field contract the constructor left unestablished is an Invariant Error naming the field, with facts.field.

A validating subclass

When there is something to check at construction (a constructor contract, or an instance field contract on the class or a base), @Contract() returns a validating subclass, and TypeScript binds the class name to it. instanceof, name, length, a.constructor === Class and design:paramtypes are kept, and getContractedClasses() lists the subclass. With nothing to check, the class is returned unchanged.

@Contract({ construction })Means
omittedThe constructor contract comes from the decorators, if any.
{ params, requires?, ensures? }The same contract as data, with contract()'s slot rules. Both forms on one class are refused.
'none'Keep the class as written, and give up the end-of-construction field check. Refused when the constructor is contracted.

Every projection reads the constructor as 'constructor': contractSnapshot(Account, 'constructor') to diff it (a new required parameter is breaking, a new optional one compatible), toolSchemaForMethod(Account, 'constructor') for a "create" tool keyed by @Name, a constructor annotation in schemaForClass, and new Account(opening, owner, note) in the generated docs (ClassDoc.construction). The fuzzers build their receivers from it too (see Add-ons). A static member named constructor on a @Contract() class is refused.

Parameter names

A name read from a function's source text is renamed by a minifier, to different letters in two builds of the same code, so adorn keys nothing on it. @Name('location') on a parameter, or name on a contract() slot, declares the name callers and projections use.

A declared name keysWithout one
The tool-schema property and requiredtoolSchemaForMethod and toolSchemaForFunction throw, naming each position and the fix.
The snapshot's name, read by the diff's name bandNo name is recorded, and the name band says nothing.
The OpenTelemetry attribute adorn.param.<name>adorn.param.<index>, such as adorn.param.0.

Labels (violation messages, facts, docs and the privacy report) use the declared name, else the one read from the source, else arg{i}. A name matches /^[A-Za-z_][A-Za-z0-9_]*$/, is at most 64 characters, is not __proto__, and is unique within a signature; each rule is checked when the name is declared or installed. @Name is record-only, so the position still needs a type. parameterNameOf(target, key, index) (from adorn/introspection) returns {name, source}, where source is 'declared' or 'parsed'.

a named contract() function, projected as a tool
import { contract, Contracts } from 'adorn';
import { toolSchemaForFunction } from 'adorn/schema';

const quote = contract(
    {
        params: [
            { descriptor: Contracts.string.notEmpty(), name: 'city' },
            { descriptor: Contracts.number.between(1, 7), name: 'days', optional: true },
        ],
    },
    function quote(city: string, days?: number) { /* … */ },
);

toolSchemaForFunction(quote, { description: 'Quote a trip.' });
// { title: 'quote', properties: { city: {…}, days: {…} }, required: ['city'], additionalProperties: false, … }
quote('');   // throws: city expected a non-empty string …

Working with values

Use these when there's no signature to decorate. They take the same descriptors and run the same oracles, as functions.

FunctionUse it for
Verify.check(d, name, value)Untrusted input as a value, such as an HTTP 400. Narrows unknown and reports path and expected; inside a composite, rejectedBy names the inner rule that refused.
Verify.that(d, name, value)The same check, but it throws, returning the narrowed value on success.
toolSchemaFrom({name, description, params}, opts)Tool schemas whose permitted values are known only at runtime.
contract(spec, fn)Enforcing params, requires, ensures and returns on a plain function, sync or async. params is the signature: one typed slot per parameter.
contract.checked(spec, fn)The non-throwing twin of contract(). Each call returns a ContractVerdict as a value instead of throwing, so a verdict consumer and a thrown violation can't disagree.
violationFromCheck(result)Emitting a functional refusal on the observation stream.
numericBoundOf(facts)Reading a refusal by a numeric bound as data: where the bound is and which side refused, or undefined for any other refusal. From adorn/observe.
defineConstraint({...})Your own first-class constraint, which projects like a built-in.

contract.checked(spec, fn) is the non-throwing twin of contract(): it runs the same bands through the same oracles and builds any failure through the same builders, but each call returns a ContractVerdict as data rather than throwing, and it touches no global state (never the violation policy, never the sink). A verdict is {ok: true, value} on success, {ok: false, band, index, id?, facts, value?, message} on a contract failure, or {ok: false, band: 'body', error} when the body itself throws. It carries the settled return and a localized path, and {evaluate: 'all'} collects every failure rather than only the first. Because both paths share those builders, a verdict consumer and a thrown violation can't disagree.

a verdict as data, nothing thrown
const settle = contract.checked(
    {
        params: [NumberContracts.Finite(), NumberContracts.Finite()],
        returns: NumberContracts.GreaterThanEqual(0),
    },
    (amount: number, balance: number) => balance - amount,
);

settle(30, 100);     // { ok: true, value: 70, … }
settle(150, 100);    // { ok: false, band: 'returns', facts, value: -50, message, … }
settle(30, 100, 5);  // { ok: false, band: 'params', index: 2, facts: { constraint: 'signature.arity', … }, … }
per-session tool
const params = {
    slotId: EnumContracts.OneOf(availableSlots),  // known only now
    partySize: NumberContracts.Between(1, 8),
};
const schema = toolSchemaFrom({ name: 'book', params }, { provider: 'openai', strict: true });
const reply = Verify.check(ObjectContracts.Fields(params), 'args', modelArgs);

To try this live, use the playground.

Signatures

A contract's signature is its typed parameter list. For contract() and contract.checked it is params (no params is a function of no arguments); for a decorated method it is one past its highest typed position, never Function.length, so a wrapping decorator can't change it. A call that passes more arguments than that (a trailing undefined isn't counted) is refused before the body, in the params band, blaming the caller, with the value-free facts {constraint: 'signature.arity', params: {max}}.

A params slot (ParamSlot)Means
dRequired, checked against descriptor d.
{ descriptor: [a, b] }A stack at one position, checked in order. A bare array is refused.
{ descriptor: d, optional: true }An absent or undefined argument passes; a present value, null included, is checked. A required slot after an optional one is refused.
Contracts.defined()Any value except undefined, for a value adorn can't type. {descriptor: Contracts.defined(), optional: true} is any value, absence included.
{ descriptor: d, name: 'city' }Declares the parameter's name (with optional too, if needed). See Parameter names.

A null, a hole, a closure or any other non-descriptor slot throws at declaration, as does a function whose length exceeds params, or a clause that reads an argument past the signature. To hand a function extra arguments on purpose, such as a callback given to Array.prototype.map, pass extraArgs: 'allow' on the spec, on @Contract() or on @Validate() (the ContractOptions type; its values are the ExtraArgs type, 'refuse' | 'allow').

one typed slot per parameter
const reschedule = contract(
    {
        params: [
            Contracts.defined(),                                   // a store adorn can't type
            { descriptor: Contracts.string.notEmpty(), optional: true },
        ],
    },
    (store: Store, note?: string) => store.apply(note),
);

@Contract({ extraArgs: 'allow' })   // its methods are passed to .map on purpose
class Formatter { /* … */ }

Projections

ProjectionOne classWhole registry
LLM tool schema (prescriptive)toolSchemaForMethod(Cls, 'm', {provider?, strict?}); toolSchemaForFunction(fn) for a contract() functionn/a
JSON Schema 2020-12 (descriptive)schemaForClass(Cls)generateSchema()
Markdown docsrenderMarkdown([documentClass(Cls)])generateMarkdown()
Privacy reviewserializeTelemetry(telemetryForClass(Cls))generateTelemetryReport()

A tool schema keys each property by the declared name (@Name, or a slot's name), and refuses to build without one. toolSchemaFrom checks its keys by the same rule. The model types (ClassDoc, MethodDoc, ToolSchema, TelemetryReport and so on) are exported so you can type variables that hold them.

Configuration

Set these once at startup. They're process-level, not per-request.

CallEffect
setViolationPolicy('throw' | 'warn' | handler)'warn' proceeds into the method. Use it to stage a new contract over live traffic.
setEnforcementMode('development' | 'production' | 'auto')Production strips assert-trust contracts. guard contracts stay on.
setDefaultTrust('guard' | 'assert')The default for contracts that don't declare one.
disableGuardEnforcement({confirm, reason})The only way to strip guard contracts.
setValueDisclosure('none' | 'all')Shows raw values in adorn's own output, for local debugging only.
setContractDiagnosticsEnabled(bool)Dev-mode warnings, such as constraints declared without @Contract().
setContractDiagnosticsSink((message, { code }) => …)Routes those warnings. Each carries a stable ADN code as data, the id the lint rule for the same problem reports.

Privacy

Redaction is on by default and needs no annotation. @Sensitive() on a field, parameter or class vetoes disclosure even under setValueDisclosure('all'). @Telemetry.value(), .redact(strategy) and .result() opt values into the observation path. None takes a name: declare it with @Name('accountId') @Telemetry.value(), and adorn/otel keys the attribute adorn.param.accountId (without a declared name, adorn.param.<index>).

A permanent gap

transfer(ssn: string) has to be marked on the parameter itself. JavaScript's value semantics break the link back to a @Sensitive field once the primitive is passed.

CLI

terminal
adorn docs   --out CONTRACTS.md src/tools/*.ts   # Markdown documentation
adorn schema --out schema.json  src/tools/*.ts   # JSON Schema (draft 2020-12)
adorn check  tsconfig.json                       # @Sensitive values reaching an adorn emitter

docs and schema load, then project: they require each entry so its decorators run, which means importing executes the module, side effects included. .ts entries need ts-node and typescript in your project. check is static: it never runs your code, and it exits non-zero if it finds a leak.

Add-ons

All three ship inside the package as subpath exports. Importing the root never loads them, and each one needs its peer dependencies only when you use it.

adorn/test

Needs fast-check. fuzzMethod, fuzzClass and fuzzFunction (each with an async variant) test one unit against its own contract. fuzzSequence tests call sequences on stateful objects. Generated inputs always satisfy the descriptors; a clause that compares an argument with a literal adds that literal and its neighbours as boundary candidates (result.boundaryCandidates); result.premises counts how often each Implies premise held and warns when one never did; and determinism: true re-runs each passing case on a deep clone of its arguments, reporting a difference as a nondeterministic-result finding. The named formats, literal text and TimeContracts values are generated from their definitions. With no subject, a class @Contract() wraps for construction is built from generated constructor arguments, which shrink with any counterexample and are reported with it; a constructor that throws is a construction-crash, one that leaves a field contract broken a construction-invariant-violation. A clean result means no counterexample was found, not a proof. A worked example.

npm i -D fast-check

adorn/otel

Needs @opentelemetry/api. createOtelSink() turns the observation stream into spans, a duration histogram and value-free violation events.

setObservationSink(createOtelSink());

adorn/eslint

Needs eslint and typescript-eslint. A typed lint that moves adorn's refusals, and contracts that would silently go unenforced, to build time, with recommended, strict and boundary(globs) presets. An opt-out of a strict default says why in an // adorn-allow: <reason> comment. Every rule.

import adorn from 'adorn/eslint';
// in a typed flat config:
adorn.configs.recommended

Contract diff

contractDiff(old, next) (from adorn/introspection) answers whether a change between two versions of a contract is breaking. Each position of the new input contract (params[i], signature, requires[j]) and of the old output contract (returns, ensures[j]) is compatible (proved), breaking (with the direction, narrowed-input or widened-output, and a witness run through the real checks of both versions), or unknown (with the reason). Closures and Old(...) clauses are never proved.

contractSnapshot turns a contract() function, a ContractSpec, an installed decorated method (contractSnapshot(Class.prototype, 'method')) or a constructor (contractSnapshot(Class, 'constructor')) into plain JSON, so a stored release can be diffed against the current code in CI. A snapshot records the signature (arity, extraArgs), and a method's snapshot its trust, so what an old caller could pass is read from the old version's enforcement, never from a function's source. The overview has a worked CI example.

two descriptors, as an input and as a return
contractDiff(N.Between(0, 10), N.Between(0, 5));
// { verdict: 'breaking', positions: [{ position: 'value', direction: 'narrowed-input', witness: { value: 10 }, … }] }
contractDiff(N.Between(0, 10), N.Between(0, 5), { as: 'output' });
// { verdict: 'compatible', … }

fragmentImplies(N.Between(0, 5), N.Between(0, 10));   // { verdict: 'implies' }
fragmentImplies(N.Between(0, 10), N.Between(0, 5));   // { verdict: 'does-not-imply', witness: 10 }

Declared names have a band of their own, name[i]. A rename doesn't change which positional call is accepted, but it breaks a caller that sends arguments by name, such as a model calling a tool: renaming or dropping a declared name is breaking (renamed-input, witness {name: {before, after}}), and adding one is compatible. Pass {calls: 'positional'} when every caller is positional, and a rename is compatible.

fragmentImplies(a, b) asks whether every value a accepts also satisfies b. Numeric intervals, code-point lengths, literal text, OneOf / Const / Bool, Nullable, ArrayOf and Fields (exact or open) are read; any other descriptor is matched only by identity. Guide: docs/contract-diff.md.

Gotchas

  • @Contract() is required. Without it, constraints are neither enforced nor projected. adorn warns in development.
  • Decorator order with @Validate(). Method decorators it should see must sit below it; a @Requires, @Ensures, @Returns, @EnabledWhen or parameter decorator written above it throws at declaration instead of being silently unenforced. Class-level @Contract() doesn't care about order.
  • TypeScript defaults are honored. f(@GreaterThanEqual(1000) t = 30_000) called as f() uses the default. A defaulted parameter still needs a type to be in the signature; add @Default(30_000) to publish the default to the schema, or @Optional().
  • A TypeScript default and @Default can disagree. @Default(10) x = 20 publishes 10 and runs with 20. adorn doesn't reconcile the descriptor with TypeScript.
  • @Contract() may return a subclass. With a constructor or field contract, the class name is bound to a validating subclass. Code that compares Object.getPrototypeOf(Class.prototype) or needs the class exactly as written uses @Contract({construction: 'none'}).
  • Tool schemas need declared names. toolSchemaForMethod throws for a parameter with no @Name, since a name read from the source changes under a minifier.
  • static #private blocks class decorators (TS18036). Move it to module scope.
  • @NotEmpty() accepts whitespace. Pair it with @Matches(/\S/) when blank input should fail.
  • Extra arguments are refused. A contracted function handed to .map(fn) receives (value, index, array) and is refused past its signature. Wrap it in an arrow, or opt out with extraArgs: 'allow'.
  • Upgrading from 0.4? Add @Name to the parameters of every method you project as a tool, and to every disclosed parameter whose OpenTelemetry attribute a dashboard reads; drop the name argument from @Telemetry; and assign every required field contract in the constructor, or mark it @Optional(). Each breaking entry in the changelog carries its migration line.

API index

Every runtime export of adorn and its curated subpaths — adorn/schema, adorn/introspection, adorn/observe, adorn/privacy, adorn/test, adorn/otel and adorn/eslint. The site's build check fails if this list drifts from the library. Press / to search.