Skip to main content

Examples

You'll leave with: how Nudo observes real call sites, how sidecar contracts gate obligations, and what still degrades to unknown.

Product path first. Observation is nudo check signatures (call sites are evidence). Contracts are *.nudo.js / @nudo:contract. @nudo:case is a debug witness only — optional, not the contract product.

Every output block below is excerpted from a real engine run of the code above it (nudo check / nudo test header lines and the assertions summary are elided where noted). The repo's CI-pinned suite lives in docs/examples/ (pnpm run verify:examples); this guide browses the same engine by theme.

The suite's topic directories at a glance (exit codes are the command matrix's pinned expectations — negative rows exit non-zero on purpose, the reported lines are the demo):

Topic directoryWhat it demonstratesRepresentative filesExpected exit
constraints/@nudo:contract × Pred: scalars / shapes / return refinement; an if is not a refinementset-delay.js · register.js · return-contract.js · similarity.js · levenshtein.js1 negatives · 0 register / test:cli / @nudo:assume / @nudo:invariant
structure/Abs leq: assignment / argument structure (width subtyping)assign.js · arg-structure.js1 (both rows)
vs-ts/Same logic, side by side with TypeScriptconstraints/nudo.js · constraints/tsc.ts · structure/nudo.jsnudo 1 · tsc 0 / 2
mini-repo/Multi-file integration (ESM + class + async)user-service.js · store.js · validators.js1 user-service check (L2) · 0 rest
algebra/Types as computation (spread / HOF / reduce / mixin)0-add-intensional.js · b-hof-map.js · c-reduce-sum.js0
contract-derivation/Contract tier derivation (handwritten root → generated rows)lib.js · lib.nudo.js · add.js0
contract-draft/Code first: reviewable contract drafts from logicgreet.js · README.md0 (contract --draft)
migrate/Retire the tsc boilerplate package (one-way before/after gate)before/src/math.ts · after/src/math.js · before/package.json0 (status / strip / verify / retire)
errors/Top-10 error faces (Nudo real output)01-constraint-gt.js · 04-entry-throws.js · 10-fix-path.js1 (all ten)
retire-real/Real-package ms retire-tsc case (not a synthetic fixture)before/src/age.ts · after/src/age.js0
retire-debug/Real-package debug retire-tsc case (visionmedia/debug)before/src/logger.ts · after/src/logger.js0

Root-level l2-export-any.js pins L2 export-any gating outside any directory: check exits 1, --ignore-throws TypeError exits 0. One command verifies the whole matrix: pnpm run verify:examples.

Try any sample in the Playground.


Call sites and contracts (product path)​

1. Call-site subtraction — Observation​

Plain JS + call sites. No annotations. nudo check prints signatures; call sites supply evidence.

engine-verifiedRun in Playground
export function subtract(a, b) {
return a - b;
}

subtract(5, 3);
subtract(1, 10);
npx nudojs check subtract.js
nudo check subtract.js
OK
0 error · 0 warning · 0 info · 1 fn

signatures
subtract(a: any, b: any) => number

(no issues)

Unconstrained entry params display as any. With richer call evidence (or a sidecar), Abs keeps literals and algebra — run nudo check --abs or open the file in the IDE.

Optional debug case report (nudo test — not required for the gate):

=== subtract ===
call@L5 (5, 3) => 2
call@L6 (1, 10) => -9

2. Sidecar contract — Contracts obligation​

engine-verifiedRun in Playground
// pricing.js
export function lineTotal(price, qty) {
return price * qty;
}

lineTotal(12, 3);
lineTotal(0, 2);
engine-verifiedRun in Playground
// pricing.nudo.js — contract (also plain JS)
import { number, fn } from "@nudojs/core";

export const lineTotal = fn(
{ price: number().gt(0), qty: number().ge(1) },
number().gt(0)
);
npx nudojs check pricing.js
nudo check pricing.js
FAILED
1 error · 0 warning · 0 info · 1 fn

signatures
lineTotal(price: number, qty: number) => number

issues
[ERROR L6 lineTotal] lineTotal[price]: argument ⊭ precondition (nudo:constraint-violated)
actual: 0 #exact
expected: price > 0
→ use a value satisfying price > 0, or relax the precondition on price

if guards are not refinements. Obligations come from the sidecar / @nudo:contract. See Contracts and nudo check.

3. Object shapes from call sites​

engine-verifiedRun in Playground
function greet(user) {
return user.name + " is " + user.age;
}
greet({ name: "Alice", age: 30 });
=== greet ===
call@L4 ({ name: "Alice", age: 30 }) => "Alice is 30"

Concatenation keeps the literal result "Alice is 30" — not a flattened string. Parameter destructuring folds argument shapes the same way:

engine-verifiedRun in Playground
function addP({ x, y }) { return x + y; }
addP({ x: 1, y: 2 });
=== addP ===
call@L2 ({ x: 1, y: 2 }) => 3

Shape merge through spread:

engine-verifiedRun in Playground
function mixin(base, ext) {
return { ...base, ...ext };
}
mixin({ host: "localhost", port: 8080 }, { port: 3000, debug: true });
=== mixin ===
call@L9 ({ host: "localhost", port: 8080 }, { port: 3000, debug: true }) => { host: "localhost", port: 3000, debug: true }

Strings and templates​

4. Template strings — beyond declared types​

engine-verifiedRun in Playground
export function coupon(code) {
return `SAVE-${code.toUpperCase()}`;
}

coupon("vip");
=== coupon ===
call@L5 ("vip") => "SAVE-VIP"

TypeScript often widens this to string. Nudo observes the concrete template result at the call site. Compare the table in Why Nudo and the homepage “Beyond declared types” section.

5. Precise string methods​

toUpperCase, toLowerCase, slice, .length, and split (literal receiver) produce exact results on the call-site path: "a,b,c".split(",") folds to ["a", "b", "c"]. See Language semantics for the full precise/degrade map.


Loops and ranges​

6. Concrete-bound loops​

engine-verifiedRun in Playground
function sumTo(n) {
let sum = 0;
for (let i = 0; i < n; i++) sum += i;
return sum;
}
sumTo(5);
=== sumTo ===
call@L6 (5) => 10

Loop sums stay literal when bounds are concrete — same Abs algebra powers nudo check.

7. Range narrowing​

Path predicates narrow Abs inside branches (x > 5 → range preds on the term). Details: Control flow narrowing.


Unions and safe access​

8. Discriminated by typeof​

engine-verifiedRun in Playground
export function transform(x) {
if (typeof x === "string") return x.toUpperCase();
if (typeof x === "number") return x + 1;
return null;
}

transform("hi");
transform(41);
transform(null);

Each call site keeps its precise arm ("HI", 42, null). Symbolic unknown conditions currently join branches — see semantics.

9. Optional chaining​

Known-shape receivers fold at any depth (a.b.c ?? 5 with { b: {} } → 5); on unconstrained (any) receivers the result stays any with throws TypeError (engine debt unknown does not apply — see Control flow narrowing).


Runtime environments and mocks​

10. Web APIs via @nudo:env web​

engine-verifiedRun in Playground
/// @nudo:env web

Built-in es / web / node env modules type common APIs; third-party @types fill in automatically at analysis time. See Dependency types. Env/harvest is not a substitute for mocks on native runtime callbacks — see Limits.

11. Mock external dependencies​

engine-verifiedRun in Playground
// @nudo:mock fetch = (url) => ({ ok: true, json: () => ({ id: 1 }) })

Prefer the single-line arrow mock form. Full syntax: Mocking External Dependencies.


Debug witnesses (optional, not the product)​

@nudo:case injects scenario inputs for nudo test / LSP case switching. It does not create CI obligations.

engine-verifiedRun in Playground
/**
* @nudo:case "double digits" (10)
*/
export function scale(x) {
return x + 1;
}
=== scale ===
debug "double digits" (10) => 11

Prefer concrete values or constraint builders (number(), lit(42)). Assertions (=> expected) only from declared cases affect nudo test exit code — synthetic call@ / entry@ never fail the run.


Where to go next​

TopicPage
Contract draft / accept / emitContracts
CI gate + diagnostic codesnudo check · Diagnostics
What degrades to unknownLanguage semantics
Abs algebraAbs
Recipes (CI, monorepo, export)Recipes
DirectiveRole in this guide
Call sitesObservation evidence (primary)
*.nudo.js / @nudo:contractContracts (primary)
@nudo:env / @nudo:mockEnvironment & boundaries
@nudo:caseOptional debug witnesses only