The old page had been quietly broken for some time. It loaded
@babel/standalone from an **unpinned** CDN URL, which rolled over to Babel
8 and dropped the `proposal-class-properties` plugin the page asked for, so
Babel.transform threw before it ever reached the decorators — and the
decorator config it passed was `{ legacy: true }`, which 0.2.0 had already
made wrong. Nothing on the page said so. The copy was still selling the
0.1.0 pitch ("Spring-like"), listed about half the decorators, showed
`npm install cereale` for a package the registry returns 404 for, and
claimed "Zero overhead" against a README that publishes the real
microsecond costs.
The rebuild is one self-contained page: hand-written CSS, no Tailwind CDN,
no CodeMirror, and a vendored compiler pinned by package.json. It loads
nothing from the network. The playground runs the real bundled library
across six examples, all verified in a headless browser. The reference
covers all 68 decorators and the full API, counted from the bundle at
runtime so it cannot drift.
The hero's compiler error is not typed into the HTML. scripts/build-docs.mjs
compiles the snippets with the real tsc and writes the verbatim diagnostics
into docs/diagnostics.js, failing the build if a snippet the page calls a
compile error ever compiles — and two snippets that must compile guard
against the harness passing vacuously.
Three guards keep it honest, all wired into CI:
- check:docs fails on any remote subresource
- build:docs + git diff fails if docs/ is stale against src/
- check:types compiles a consumer against dist/ with no DOM lib, no
@types/node and no skipLibCheck
That last one found a real packaging defect: `fromRequest` was declared as
taking the global `Request`, so cereale's own published .d.ts raised
"Cannot find name 'Request'" in any project whose lib and types did not
happen to supply it — inside a dependency, in code they may never call, and
unfixable from the outside. It now takes a structural JsonBody, which a
Request still satisfies. The library's own type tests had been hiding it by
enabling both DOM and skipLibCheck.
An adversarial review of the finished page caught four more: the lede
claimed *every* rule is type-checked (@IsDefined and @IsNotIn deliberately
are not), the guarantee section was wrong about the mechanism (a legacy
decorator does get design:type under emitDecoratorMetadata — the real claim
is about its type signature), one sample called a Movie method on a Media[]
and did not compile, and "nested objects come back as real classes" omitted
that you have to declare them. WCAG contrast was measured rather than
eyeballed: seven real failures fixed in the two themes.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAcqrz3FcadkYr3xG32CjK
19 KiB
Changelog
All notable changes to this project are documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[0.3.0] - 2026-08-05
Every change here comes from the same question: where does cereale currently fail quietly? Three answers, each of which cost a real user nothing to hit and everything to diagnose.
Vite 8 and Vitest 4 silently drop decorators — cereale/vite
Both transform TypeScript with oxc, which does not implement the standard decorator transform and does not say so. It leaves the syntax in the output, so:
vitestreports0 testnext to a bareSyntaxErrorvite buildreports success, having emitted a bundle that throws the moment it is imported
Cereale now ships the plugin that fixes it:
// vite.config.ts / vitest.config.ts
import { standardDecorators } from 'cereale/vite';
export default defineConfig({ plugins: [standardDecorators()] });
It transforms with esbuild, falling back to the TypeScript compiler; cereale depends on
neither, and says which to install if somehow neither is present. Options: include,
target, and transformer to pin one deliberately. The library's own test suite runs
through it, so it is exercised by every test rather than by one test about itself.
Legacy decorators now say so
With experimentalDecorators: true — still the default in most existing TypeScript projects,
because class-validator required it — decorators are invoked as (prototype, "name") and
cereale died with TypeError: Cannot convert undefined or null to object, which names neither
the cause nor the fix. Every decorator now resolves its metadata through one checkpoint that
raises an error naming the tsconfig setting instead. The same checkpoint rejects application
to a method, getter or accessor field, all of which previously recorded metadata that
nothing would ever read.
Values JSON cannot carry are refused, not emptied
A populated Map serialized to {}. A Set serialized to {}. A Uint8Array to
{"0":1,"1":2}. A bigint passed straight through, so the caller's own JSON.stringify
threw somewhere unrelated. RegExp, Error, Promise, WeakMap, DataView, symbols and
functions all had their own version of the same failure. All of them now raise a
JsonMappingError that names the property path and the two ways out:
JsonMappingError: lines[1].tags[0] is a Set, which cannot be serialized to JSON.
Give the property a @JsonSerialize() serializer that converts it, or drop it from the
output with @JsonIgnore().
The check also covers what a @JsonSerialize serializer hands back, sync or async. This is
breaking for anyone relying on the old behaviour, though "relying on" is a strong word for
losing data without being told.
Circular-reference and depth-limit errors now name the path too (at child.parent), which
came free with the bookkeeping.
Fixed
defineRuleon a subclass with no decorators of its own wrote the rule into its base class, because the base's metadata object is inherited through the static prototype chain and??=found it non-nullish. Every sibling subclass then inherited a rule meant for one of them.- The plugin's TypeScript path emitted a
//# sourceMappingURL=comment pointing at a file nobody wrote, which Vite followed and failed to read on every transformed module. fromRequestwas declared as taking the globalRequest, so cereale's own published.d.tsraisedCannot find name 'Request'in any project whoselibandtypesdid not happen to supply it — an error inside a dependency, in code the consumer may never call, that they could not fix from the outside. It now takes a structuralJsonBody({ json(): Promise<any> }), which aRequeststill satisfies. The library's own type tests had been hiding this by enabling bothDOMandskipLibCheck;npm run check:typesnow compiles a consumer againstdist/with neither.
The landing page
docs/index.html was rebuilt. Its playground had been dead for some time and said nothing
about it: the page loaded @babel/standalone from an unpinned CDN URL, which rolled over
to Babel 8 and dropped the proposal-class-properties plugin the page asked for, so
Babel.transform threw before it ever reached the decorators — and the decorator config it
passed was { legacy: true }, which 0.2.0 had already made wrong. The copy was still selling
the 0.1.0 pitch ("Spring-like"), listed about half the decorators, and claimed "Zero overhead"
against a README that publishes the real microsecond costs.
The rebuild is one self-contained page: hand-written CSS, no Tailwind CDN, no CodeMirror, and
a vendored compiler pinned by package.json. It loads nothing from the network, which
npm run check:docs now enforces in CI. The playground runs the real bundled library across
six examples; the reference lists all 68 decorators and the full API, counted from the bundle
at runtime so it cannot drift.
The hero's compiler error is not typed into the HTML — scripts/build-docs.mjs compiles the
snippet with the real tsc and writes the verbatim diagnostic into docs/diagnostics.js,
failing the build if a snippet the page calls a compile error ever compiles. A third snippet
that must compile guards against the harness passing vacuously.
Positioning
zod-alternative is out of the keywords, and the README leads with the comparison that
actually applies: cereale replaces class-validator + class-transformer. It does not infer
types from schemas, and framing it against Zod invited exactly the objection that it is
missing z.infer — which is a different design, not a gap.
The README's toolchain support table (tsc, esbuild, swc ✅, oxc ❌) is now
executed by a test: each row compiles a decorated class with that
tool and asserts the metadata arrived, so the table cannot quietly go stale.
Performance
Serialization is a few percent slower for the representability check. Primitives are handled
inline, and arrays and dates skip it, so it costs one Symbol.toStringTag read per object.
Validation is unchanged.
[0.2.0] - 2026-08-04
The project stays on 0.x while nothing has been published: under semver that signals the API may still move, which is honest for software with no real-world users. A breaking change is therefore a minor bump, which is why this is 0.2.0 rather than 2.0.0.
Breaking. Cereale moves to TC39 standard decorators, which is what makes validation rules type-checked against the fields they are attached to.
The headline
A rule that does not fit its field is now a compile error:
class User {
@IsString() name!: string; // fine
@IsString() age!: number; // Type 'number' is not assignable to type 'string'
}
Legacy decorators receive (target: any, key: string) and lose the field's type entirely, so
this was impossible in v1. Standard decorators receive ClassFieldDecoratorContext<This, Value>,
which carries it. Checked rules include:
- scalar rules against scalar fields (
@Minon a string is rejected) { each: true }against arrays (@IsString({ each: true })demands astring[], and a bare@IsString()on astring[]is rejected)@JsonType(() => Address)against the field's class@JsonSerialize/@JsonDeserializeagainst the field's type@IsIn([...])and@IsEnum(E)against the field's value type
17 tests invoke the real compiler to assert these stay rejected.
Migration
- Remove
"experimentalDecorators": true; add"ESNext.Decorators"tolib. registerDecorator({ target, propertyName, validator })is replaced bydefineRule(Class, 'field', constraint).- Decorators cannot be applied to
abstractfields. Declare the field concretely in the base. - Field types may need tightening where a rule narrows them:
@IsIn(['a','b']) x!: stringbecomesx!: 'a' | 'b'. @JsonPolymorphictakes its base type explicitly to check subtypes:@JsonPolymorphic<Media>('type', [...]).@ValidateIftakes the class as a type argument:@ValidateIf<Movie>(m => ...).
Everything else — the engine, options, naming strategies, access control, error helpers, the sync API — is unchanged.
Removed
metadata-storage.tsand its WeakMap singleton. Metadata now lives oncontext.metadata, the language's own mechanism, which also removes the dual ESM/CJS double-singleton hazard.registerDecorator, replaced bydefineRule.
Fixed
- Inheritance merging is now structural rather than reconstructed:
context.metadatainherits through the prototype chain, so the subclass-shadowing defect fixed by hand in 0.1.0 cannot reoccur by construction. Identical inherited rules are still collapsed so re-stating a rule on an override does not double-report.
Toolchain
Standard decorators are transformed by tsc and by esbuild; oxc does not implement them
yet. The library builds with tsc and consumers bundling with esbuild or Vite are fine, but
the test runner (Vitest 4, which uses oxc) needs an esbuild transform plugin — see
vitest.config.ts. Projects on an oxc-based toolchain should stay on 0.1.x for now.
[0.1.0] - 2026-08-05
Added
Synchronous API. validateSync, validateOrRejectSync, toPlainSync, toJsonSync,
toInstanceSync, toInstanceArraySync, fromJsonSync and fromJsonArraySync. Nothing on
the default path is genuinely asynchronous — only a user-supplied serializer, deserializer or
validator can be — so requiring await everywhere was a tax on the common case.
The engines are now written synchronously, and anything a hook makes asynchronous is recorded
and reconciled once at the end. There is no second copy of the traversal logic to keep in
step, and the async entry points stop paying for a microtask per property. If a hook does
return a Promise, the *Sync call raises a JsonMappingError naming the async alternative
rather than silently returning a half-built object.
fromRequest has no synchronous counterpart, because reading a request body is inherently
asynchronous.
maxDepthoption (default 64) on every mapping function and onconfigure(). All three engines recurse, so a hostile payload nested thousands of levels deep could exhaust the call stack; it now raises aJsonMappingError. Cycles were already handled, but legitimate deep nesting was not bounded.validate(obj, options?)accepts options, somaxDepthapplies to standalone validation.REDACTEDexport, the placeholder substituted for withheld values.
Security
- Validation errors no longer carry the value of a property that is never serialized.
A
@JsonWriteOnlypassword that failed@MinLengthput the rejected password intoValidationError.value, and from there into any log that recorded the error. Values for@JsonWriteOnlyand@JsonIgnoreproperties are replaced withREDACTED; the property name and the failure message are unchanged, so the error is still actionable.
Performance
Profiling the validator showed roughly half of all validation time was spent re-deriving
answers that cannot change: collectConstraints (22%), getOwnMetadata (12%),
getMetadataChain (9%), getProperties (4%) and getMetadata (3%), plus 8% garbage
collection from the allocation churn. The constraint predicates themselves accounted for
under 1%.
Decorator metadata is fixed once classes are declared, so the derived structures are now
memoized per prototype — the validation plan, the serialization plan, the deserialization
plan, and serializer/deserializer instances (previously constructed fresh for every property
of every object). MetadataStorage carries a version counter that invalidates every cache
if metadata is registered late, so registerDecorator after first use still works.
Together with the synchronous core, measured on a customer record with a nested address and
orders, against JSON.parse + JSON.stringify (5.8 us) as a fixed reference point:
| Operation | 0.1.0 | Now | Speedup |
|---|---|---|---|
validate (50 orders) |
221.6 us | 17.8 us | 12.4x |
validate (10 orders) |
47.8 us | 4.5 us | 10.6x |
toPlain (50 orders) |
294.4 us | 36.0 us | 8.2x |
toInstance (50 orders) |
255.1 us | 31.7 us | 8.0x |
toInstance (10 orders) |
64.6 us | 8.2 us | 7.9x |
toInstance (single) |
19.8 us | 5.2 us | 3.8x |
Changed
each: truefailures now report which element failed —"... (failed at index 3)". A bad entry in a 200-item array previously produced a message that could not locate it. A message function now receives the failing element asargs.valuerather than the whole array; caller-supplied string messages are still reported verbatim.
[0.1.0] - 2026-08-03
The first release with a working test suite. Everything below the "Fixed" heading was found by writing tests against the previous release; the suite has grown from 40 tests that never executed to 136 that do.
Added
Field-name mapping. A library whose headline feature is "JSON mapping" could not map a name. It can now.
@JsonProperty(name)renames a property in both directions.@JsonAlias(...names)accepts extra names on input only, so a field can be renamed without breaking older clients.- Naming strategies —
snake_case,kebab-case,SCREAMING_SNAKE_CASE,PascalCase,camelCase, or your own function — applied to properties with no explicit name. Acronyms split where a reader expects:parseHTTPResponse→parse_http_response.
Access control.
@JsonIgnore()— excluded in both directions.@JsonWriteOnly()— accepted from input, never echoed back (passwords).@JsonReadOnly()— serialized, never settable by a client (server-owned ids).
Transform options, per call or globally via configure().
validate: falsemaps without validating, for lenient parsing.unknownKeys: 'allow' | 'strip' | 'error'decides what happens to undeclared keys.namingStrategyselects the JSON naming convention.
Error ergonomics. Turning the nested ValidationError tree into an HTTP 400 body used
to be the caller's problem.
flattenErrors(errors)→{ "items[0].qty": ["qty must be at least 1"] }formatErrors(errors)→ one human-readable line per failurecollectErrorMessages(errors)→ just the messagesvalidateOrReject(obj)throws instead of returning an array you might forget to check
30 validation decorators. @Equals, @NotEquals, @IsEmpty, @IsEnum, @IsInstance,
@Length, @IsAlpha, @IsAlphanumeric, @IsNumberString, @IsLowercase, @IsUppercase,
@Contains, @NotContains, @StartsWith, @EndsWith, @IsUUID, @IsJSON,
@IsDateString, @IsSemVer, @IsHexColor, @IsIP, @IsDivisibleBy, @IsPort,
@IsLatitude, @IsLongitude, @IsBigInt, @MinDate, @MaxDate, @ArrayUnique,
@ArrayContains, @ArrayNotContains.
Conditional validation. @ValidateIf(o => ...) makes a property's rules depend on the
rest of the object; @Allow() declares a property that needs no rules of its own.
Correctly typed array entry points. toInstanceArray() and fromJsonArray().
toInstance/fromJson accept arrays at runtime but type the result as T, so callers had
to cast to reach the elements.
@JsonPolymorphic options. { onUnknown: 'error' } and { fallback: SomeClass }.
JsonMappingError — raised when a value cannot be mapped at all, as distinct from
mapping fine and failing validation.
Fixed
- Inheritance silently discarded base-class rules. A subclass re-decorating an inherited
property registered its constraints against its own prototype, and the engine read only the
nearest set. Constraints now merge down the whole prototype chain, base first. The
library's own example was affected:
Media's@IsString() titlehad never been enforced forBook. - A circular reference exhausted the heap.
serialize()recursed forever, taking 8 GB and the process with it. It now raises aJsonMappingErrornaming the cause. Diamonds still serialize;validate()skips back-edges. @Matcheswith agoryflag was stateful.RegExp.testadvanceslastIndex, so validating the same value twice gave different answers. Those flags are stripped.- An unmatched
@JsonPolymorphicdiscriminator silently dropped the value. The single-object branch fell through without assigning; the property came backundefined. The raw value is now preserved. @JsonSerializeserializers ran onnull/undefined, crashing on any unset optional property. They now only see real values.serialize()crashed on null-prototype objects. It readobj.constructor.prototype; both engines now agree onObject.getPrototypeOf.__proto__,constructorandprototypein untrusted JSON were copied onto the instance, detaching it from its own class. They are dropped.- Caller-supplied messages were mangled by the
each element in ...prefix, producing sentences like "each element in tags must all be strings". - Two rules sharing a name overwrote each other, so only one failure was ever reported.
fromRequestleaked a rawSyntaxErrorfor a non-JSON body; it now reports aJsonMappingError.@ValidateNested({ each: true })was documented in the README but did not compile —ValidateNested()accepted no arguments. It now does, and asserts the value is an array.
Changed
toPlain,toJson,toInstance,fromJson,fromJsonArray,toInstanceArrayandfromRequestaccept an optional trailing options argument. All defaults preserve the previous behaviour.src/example.tsis no longer published indist. It calledrunExample()at import time — an import side effect in a package declaring"sideEffects": false.- Minimum supported Node is 20.
Infrastructure
- The test suite had never run. Vitest 4 transpiles with oxc, which does not read
experimentalDecoratorsfrom a tsconfig that excludes the files it is transforming, so every decorator-using suite failed to parse and was reported as "0 test" rather than as an error. Avitest.config.tsenabling legacy decorators brought all 40 existing tests back to life. - Test files are now type-checked, which surfaced 17 strict-mode errors.
- CI runs lint, coverage tests, build and ESM/CJS entry-point smoke checks across Node
20/22/24, and
npm ciworks becausepackage-lock.jsonis committed. npm run build:docsregenerates the previously hand-maintaineddocs/cereale.js.
[0.0.1]
Initial release: mapping and validation decorators, polymorphic types, custom
serializers/deserializers, and the toJson / fromJson / toPlain / toInstance API.