@alexify/metaschema 1.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +551 -1
  2. package/README.md +235 -34
  3. package/SECURITY.md +32 -11
  4. package/index.d.ts +798 -23
  5. package/package.json +30 -6
  6. package/src/codec.js +490 -0
  7. package/src/compile/code.js +92 -0
  8. package/src/compile/emit.js +512 -0
  9. package/src/compile/index.d.ts +38 -0
  10. package/src/compile/index.js +176 -0
  11. package/src/context.js +141 -0
  12. package/src/errors.js +10 -1
  13. package/src/generators/index.d.ts +29 -0
  14. package/src/generators/index.js +90 -0
  15. package/src/generators/jsonschema.js +535 -0
  16. package/src/generators/typescript.js +237 -0
  17. package/src/index.js +1 -3
  18. package/src/issues.js +291 -0
  19. package/src/kinds.js +9 -12
  20. package/src/lint.js +98 -0
  21. package/src/locales/en.d.ts +5 -0
  22. package/src/locales/en.js +66 -0
  23. package/src/locales/uk.d.ts +5 -0
  24. package/src/locales/uk.js +62 -0
  25. package/src/metadata.js +65 -119
  26. package/src/metautil.js +8 -1
  27. package/src/model.js +31 -20
  28. package/src/preprocessor.js +45 -27
  29. package/src/prototypes/abstract.js +101 -51
  30. package/src/prototypes/collections.js +106 -41
  31. package/src/prototypes/json.js +9 -5
  32. package/src/prototypes/reference.js +91 -20
  33. package/src/prototypes/scalars.js +124 -16
  34. package/src/prototypes/schema.js +31 -6
  35. package/src/prototypes/tuple.js +57 -29
  36. package/src/prototypes/union.js +139 -0
  37. package/src/result.js +115 -0
  38. package/src/rules.js +185 -0
  39. package/src/runtime/browser.js +2 -2
  40. package/src/runtime/node.js +4 -2
  41. package/src/schema.js +181 -68
  42. package/src/struct.js +101 -33
  43. package/src/types.js +14 -14
  44. package/src/util.js +41 -50
package/CHANGELOG.md CHANGED
@@ -7,6 +7,554 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.0.0] - 2026-10-11
11
+
12
+ 3.0 moves the generators of JSON Schema and TypeScript from the core entry to the
13
+ `@alexify/metaschema/generators` subpath, which takes `model.dts`, `schema.toInterface()`
14
+ and `saveTypes` with them (a breaking change, hence the major), and `schema['~standard'].validate`
15
+ is `parse` rather than `check` (a second one). The rest is additive: `parse`, `serialize`,
16
+ `checkAsync` and `parseAsync` in the core, the JIT backend of the new
17
+ `@alexify/metaschema/compile` subpath, the JSON Schema export with its four targets and the
18
+ strict profile, Standard JSON Schema, JSDoc and named types in the generated TypeScript, and a
19
+ fix in `check`.
20
+
21
+ ### Upgrading from 2.0
22
+
23
+ The same guide with before-and-after examples is
24
+ [Migrating from 2.x](https://metaschema.vercel.app/guide/migrating-from-2).
25
+
26
+ - **`schema['~standard'].validate` is `parse`.** A consumer of Standard Schema (tRPC, TanStack
27
+ Form, Hono, …) gets the value `parse` gives: the `default` of a missing key filled in and the
28
+ `parse` function of every field applied, with the schema's own `unknown` metadata as the
29
+ policy for other keys (`libraryOptions` are the options of `parse`, `unknown: 'strip'`
30
+ included). A schema without defaults and decoders returns the value it was given, the same
31
+ reference, as 2.0 did. A schema with an `async function` among its validators, decoders and
32
+ custom `checkType`s (in it or in an entity it references) returns a promise of the result,
33
+ which the specification allows and its consumers await; the typings of `validate` say
34
+ `StandardResult<T> | Promise<StandardResult<T>>` now, with `types.input` as `Infer<D>` and
35
+ `types.output` as `InferOutput<D>`.
36
+ - **`Infer<D>` leaves out a key with a `default`.** A field with a `default` is an optional
37
+ property on the input side, because `parse` fills it; `InferOutput<D>` has it present. The
38
+ generated TypeScript interfaces are unchanged (every field present), so a value typed from the
39
+ dts is still assignable to `Infer`, and the output type to the dts.
40
+ - **`CheckContext` has `async`, `source`, `scratch`, `depth` and `maxDepth` slots** (`async`
41
+ is `null` in a synchronous check), and `issues.exception` takes the key of the field, for
42
+ code that builds on the internals.
43
+ - **A graph nested deeper than 128 embedded records is invalid.** `check`, `parse` and
44
+ `serialize({ check: true })` record a `depth` issue at the first record past `maxDepth`
45
+ (128 by default, an option of the call) instead of overflowing the stack; a program that
46
+ validates deeper graphs passes a larger `maxDepth`.
47
+ - **A struct rejects an array** (see Fixed), and **the synchronous `check` and `parse` throw
48
+ `ERR_ASYNC_VALIDATOR`** for a validator, a custom `checkType` or a decoder that returns a
49
+ promise: use `checkAsync` and `parseAsync`.
50
+ - **Definitions that could never work are errors now:** an `object` or `map` without a key type
51
+ of `'string'` or `'number'` (`ERR_INVALID_DEFINITION`), a `default` on the discriminator field
52
+ of a union (`ERR_INVALID_UNION`). `maxErrors` must be a whole number (or `Infinity`).
53
+ - **The `validate`, `parse` and `serialize` of a nested struct are not keys of the value.** A
54
+ value carrying `inner: { parse: ... }` was accepted under `unknown: 'reject'` and kept under
55
+ `strip`; the key is `unexpected`, as it is at the root.
56
+ - **`compile()` reports what stopped the JIT:** `{ accelerated: false, error }` where a check
57
+ could not be generated (the `ERR_JIT_BUILD` error, the generator's error as its `cause`), and
58
+ `compile(target, { jit: false })` puts the closures back.
59
+ - **The generators moved to `@alexify/metaschema/generators`.** `model.dts`,
60
+ `schema.toInterface()` and `saveTypes` are no longer in the core entry: the subpath exports
61
+ `toTypeScript(target, options)` (a `Schema` or a `Model`), `saveTypes(outputFile, target,
62
+ options)` and `toJSONSchema(target, options)`, and its `register()` installs the methods on
63
+ the classes (`model.dts`, `model.toTypeScript`, `schema.toInterface`, `schema.toJSONSchema`,
64
+ `model.toJSONSchema`) once per process. Replace `model.dts` with `toTypeScript(model)` or call
65
+ `register()` at startup; import `saveTypes` from the subpath. The core entry no longer carries
66
+ the generators (4.5 KB min+gzip in the subpath) nor any Node runtime; the browser entry is the
67
+ same.
68
+
69
+ ### Added
70
+
71
+ - **`parse`.** `schema.parse(value, options)` validates a value and builds the value of the
72
+ program from it: `{ valid, value, issues }`, where `issues` is always an array and `value`
73
+ is `undefined` for an invalid value. The pipeline is the `default` of every missing or
74
+ `undefined` struct key (a value, or a function called on every parse, at any depth: nested
75
+ structs, the elements of collections, the records a reference embeds), the check of the
76
+ schema (whichever backend installed it: the passes validate nothing, so a compiled schema
77
+ parses through its generated code), `unknown: 'strip'` (a third policy, of `parse` alone:
78
+ the keys the schema does not have are accepted and left out of every struct of the output),
79
+ the `parse` function of every field on its validated value, from the parts of a value up to
80
+ the value (elements before the collection, the fields of a nested struct before its own
81
+ `parse`, an embedded record through its entity), and the schema's own `parse` last. A
82
+ decoder's exception is an `exception` issue at the field and makes the result invalid.
83
+ `default` is applied by `parse` only: `check` still reports a missing required key. The value
84
+ given is never written to, and it is the output itself when nothing was applied; otherwise
85
+ the containers on the way to a change are new and the rest is shared. The options are those
86
+ of `check`, with `unknown` also `'strip'`.
87
+ - **`serialize`.** `schema.serialize(value, options)` is the other direction: the schema's own
88
+ `serialize`, then the `serialize` function of every field from the value down to its parts,
89
+ through the same collections, tuples, nested structs and embedded references; `{ value }`
90
+ without validation, or `{ valid, value, issues }` with `options.check`, the other options
91
+ being those of `check`. `format` stays collected and uncalled. `parse` and `serialize` are
92
+ known keys of every field for the lint, and a non-function one is `ERR_INVALID_DEFINITION`.
93
+ - **`checkAsync` and `parseAsync`.** A `validate` function (of a field or of the schema), a
94
+ custom type's `checkType` and a decoder may return a promise. The walk of the value is
95
+ synchronous; a validator that returns a promise is set aside with its path, and every
96
+ validator met after it with it, so that a validator still runs only when nothing under it
97
+ failed; after the walk they are settled one after the other, in field order, each recording
98
+ at its path, and `maxErrors` stops the list. The synchronous `check` and `parse` throw a
99
+ `TypeError` with the new code `ERR_ASYNC_VALIDATOR` for such a promise (`RuntimeErrorCode`
100
+ in the typings). Both backends go through the same helper, so the JIT needed no change.
101
+ - **Typings for parse.** `InferOutput<D, E>` is the type of the value `parse` gives: `Infer`
102
+ with the result of every `parse` function (`Awaited`) in place of the value it decodes and
103
+ every defaulted key present (`null` stays where the key was optional); `ParseResult<T>`,
104
+ `ParseOptions`, `SerializeOptions`, `Serialized<T>` and `SerializeChecked<T>` type the new
105
+ methods, `FieldType` declares `parse`, `serialize` and `default`, and `Validator` and
106
+ `TypeEntry.checkType` may return a promise.
107
+ - **The JIT backend.** `compile(target, options)` of the new `@alexify/metaschema/compile`
108
+ subpath replaces the check of a schema, or of every entity of a model, with one straight-line
109
+ function generated from the plan the closures walk and built with `new Function`; it records
110
+ exactly the issues the closures record (codes, paths, params, order and messages) and returns
111
+ `{ accelerated }`. `register(options)` compiles every schema built from then on (a later call
112
+ replaces the options, `{ jit: false }` stops it; a schema built before is not touched), and
113
+ `canEval()` says whether the environment allows code generation from strings. The `jit`
114
+ option is `'auto'` (the default: where `new Function` is not allowed, under a Content
115
+ Security Policy, in Cloudflare Workers or under `node --disallow-code-generation-from-strings`,
116
+ the closures stay silently), `true` (throw `SchemaDefinitionError` with the new code
117
+ `ERR_NO_EVAL` instead; `register` throws at the call) or `false` (never generate code).
118
+ Nothing happens on import. The generated source holds identifiers, numbers, booleans and JSON
119
+ strings only; regular expressions, enum sets, validate functions, custom types, references and
120
+ the issue constructors reach it through a scope. Structs, every scalar with its rules, enums,
121
+ collections, tuples, unions, `nullable` and optional fields and the limits of a check are
122
+ inlined; a reference, a custom type's `checkType` and a `validate` function are the same
123
+ calls as before. Measured on Node 24 (`bench/baseline.json`): 30.0 M checks a second of a flat
124
+ struct (10.4 M on the closures), 17.4 M of a nested one (2.5 M), 5.6 M for a flat value with
125
+ four problems (3.4 M), 24–33 M on the moltar scenarios (4–7 M). The subpath is 3.9 KB min+gzip
126
+ on top of the core and
127
+ has typings of its own (`CompileOptions`, `Compiled`); the core gains one internal slot,
128
+ `Schema[Symbol.for('alexify.metaschema.hook')]`, that `register()` fills.
129
+ - **JSON Schema export.** `toJSONSchema(schema, options)` of the generators subpath renders the
130
+ rules of `check` as a JSON Schema document and `toJSONSchema(model, options)` every entity of
131
+ a model as a definition (`$defs`, `definitions` or `components.schemas` by target), or the
132
+ document of `options.root`. Targets: `draft-2020-12` (the default), `draft-07`, `openapi-3.0`
133
+ (a schema object: `nullable`, no type lists, `oneOf` with `discriminator` for a discriminated
134
+ union) and `mongodb` (a `$jsonSchema` validator: `bsonType`, references inlined, no `$ref`,
135
+ `format` or `default`, `_id` allowed at the root). A struct is a closed object with its
136
+ required keys (open when the root says `unknown: 'ignore'`), an optional or nullable field
137
+ accepts `null`, `length`/`pattern`/`min`/`max` are the matching keywords, a required
138
+ `object` or `map` has `minProperties: 1` as `check` requires, a tuple is `prefixItems` (an
139
+ `items` list before 2020-12), a union is `anyOf`, an enum of one value is `const`, and a
140
+ reference follows the kind of its target (an id for a stored kind, a `$ref` for a memory
141
+ kind; `references: 'kind' | 'embed' | 'id'` as in `check`). `title`, `description`,
142
+ `default`, `examples` and `deprecated` pass through where the dialect has them; a custom type
143
+ renders through `metadata.jsonSchema` (`metadata.bson` for mongodb) or the built-in it
144
+ aliases. `io: 'input'` (the default) describes the JSON a value is parsed from (a `date` is a
145
+ `date-time` string, a `set` an array of unique items, a `map` an object); `io: 'output'`
146
+ describes the value itself, where those three have no form. What has no form in the target
147
+ (`bigint`, a tuple for openapi-3.0, a cycle for mongodb, a custom type without metadata)
148
+ throws `SchemaDefinitionError` with the new code `ERR_UNREPRESENTABLE`, located in the
149
+ schema and the field, or renders as `{}` with `unrepresentable: 'any'`. `validate`
150
+ functions, custom `checkType`s, calculated fields, indexes and kind metadata are not
151
+ exported.
152
+ - **The strict profile.** `toJSONSchema(schema, { profile: 'strict' })` renders the dialect of
153
+ LLM structured outputs (OpenAI, Anthropic): an object at the root, every property listed as
154
+ required (an optional one as `['T', 'null']`, an optional `$ref` as an `anyOf` with null),
155
+ `additionalProperties: false` on every object, and the structure only: `minLength`,
156
+ `maxLength`, `pattern`, `minimum`, `maximum`, `minItems`, `maxItems`, `uniqueItems` and
157
+ `minProperties` are left out, and a value without a type (`any`, `json`, an `object` or
158
+ `map` of free keys) has no form. For the `draft-2020-12` and `draft-07` targets.
159
+ - **Standard JSON Schema.** After `register()` of the generators, `schema['~standard'].jsonSchema`
160
+ is the converter of the specification: `input(options)` and `output(options)` are
161
+ `toJSONSchema` for the `target` the consumer names (`draft-2020-12`, `draft-07` or
162
+ `openapi-3.0`; anything else throws, as the specification asks) with `libraryOptions` as the
163
+ other options. A `Schema<D>` is a `StandardJSONSchemaV1<Infer<D>, Infer<D>>`; the typings
164
+ add `StandardConverter` and `StandardJSONSchemaOptions`.
165
+ - **JSDoc and named types in the generated TypeScript.** The `description` of a field is the
166
+ JSDoc of its member and `deprecated: true` adds `@deprecated`. `toTypeScript(target, { named:
167
+ true })` gives every enum a `type` and every nested struct an `interface`, named after the
168
+ entity and the field (`type UserRole`, `interface UserName`) and rendered before the
169
+ interface that uses them; `saveTypes(file, target, options)` passes the options on.
170
+ `InterfaceOptions` is the type of the options.
171
+ - **`maxDepth`.** An option of `check`, `checkAsync`, `parse`, `parseAsync` and `serialize`
172
+ (an integer of at least 1, 128 by default): how deep a value may nest through embedded
173
+ references. A record past that depth is a `depth` issue (`{ max }` as params, `is nested
174
+ deeper than 128 references`, rendered by both locales) instead of a `RangeError` from the
175
+ stack; the passes of parse leave the record as it is for the check to report. The type
176
+ `IssueCode` has `'depth'`.
177
+ - **`compile()` returns `{ accelerated, error }` and `register()` takes `onFallback`.** In the
178
+ default mode a check that could not be generated keeps its closures and the reason comes
179
+ back as `error` (a `SchemaDefinitionError` with the new code `ERR_JIT_BUILD`, the
180
+ generator's error as its `cause`), or reaches `register({ onFallback(schema, error) })` for
181
+ every such schema; with `jit: true` that error is thrown and nothing of a model is installed.
182
+ `compile(target, { jit: false })` restores the closures a schema was built with. The
183
+ generated source is strict and ends with a `sourceURL` named after the schema, so a stack
184
+ trace through a compiled check names it.
185
+ - **Typings** for the generators: `JSONSchema` (`Record<string, unknown>`), `JSONSchemaOptions`,
186
+ `ModelJSONSchemaOptions`, `JSONSchemaTarget`, `InterfaceOptions` in the core,
187
+ `src/generators/index.d.ts` for the subpath, and `ERR_UNREPRESENTABLE` in
188
+ `DefinitionErrorCode`. The methods `register()` installs are declared on `Schema` and `Model`.
189
+
190
+ ### Changed
191
+
192
+ - **The core entry is 16.1 KB min+gzip** (2.0 was 12.6 KB: the TypeScript generator left it,
193
+ 3.9 KB; the array check of a struct and the hook of the compile subpath joined it; `parse`,
194
+ `serialize` and the async calls added 3.1 KB, in the core rather than a subpath because
195
+ `~standard.validate` is `parse` and every schema is a Standard Schema; the fixes of the
196
+ review below, `maxDepth` and the lazy cycle set added about 1 KB and the loops, the shared
197
+ tables and the trims gave 0.3 KB back), the generators subpath adds 4.5 KB and the compile
198
+ subpath 3.9 KB. CI gates at 17 KB per core entry, 5 KB for the generators and 4 KB for the
199
+ compile subpath (`pnpm size --max-gzip 17 --max-gzip-generators 5 --max-gzip-compile 4`).
200
+ - **Fewer allocations on the hot path.** The root value joins the cycle set only when a record
201
+ is actually embedded (a check of an entity with references in the storage view allocated a
202
+ `Set` each time); a validator or a custom `checkType` is called without a closure made per
203
+ call, and the params of a failing `checkType` are built only when it fails; the pass over an
204
+ `object` field iterates its own keys instead of allocating `Object.entries`; the trial that
205
+ picks the branch of a plain union in `parse` uses one scratch context per parse instead of
206
+ one per union value; the length of a value is measured by what the value is (an object with a
207
+ `size` key is an object) and an object's keys are counted without listing them; the
208
+ discriminator table of a union is built once and shared by the check, the passes and the JIT.
209
+ - **Loops instead of `forEach`, `map` and spreads** wherever a pass could be saved or a closure
210
+ or a list per call avoided, and null-prototype dictionaries wherever a definition key or a
211
+ code a validator makes up is looked up (the schema's `indexes` and `options`, the metadata of
212
+ a type, the rule formatters, the parsers, the locale tables).
213
+
214
+ ### Fixed
215
+
216
+ - **A struct rejects an array.** `check` accepted `[]` for a struct whose fields are all
217
+ optional (`typeof [] === 'object'`, no keys to look at) and reported the missing keys of
218
+ any other struct; an array is now `not of expected type: object`, whatever the fields.
219
+ Found by the differential test against ajv.
220
+ - **A failed branch of a plain union left its deferred validators behind** in `checkAsync` and
221
+ `parseAsync`, so a value that matched a later branch was reported invalid by the validators
222
+ of a branch it did not match. Both backends drop them with the issues of the branch. A plain
223
+ union picks the first branch whose synchronous checks pass; an async validator of that branch
224
+ settles after the walk and may still fail the value, but no further branch is tried: use a
225
+ `discriminator` where branches carry async validators.
226
+ - **A thenable in the data was taken for a promise.** Under `unknown: 'strip'`, and at a field
227
+ with a decoder, any value with a `then` function was awaited: a synchronous `parse` returned a
228
+ `Promise` as the valid value, and `parseAsync` ran the `then` of the data, which could replace
229
+ the value. Only a `Promise` instance made by a decoder in an async parse is pending now, and
230
+ the promises of the passes resolve to a box around the value, so a field called `then` is
231
+ never adopted.
232
+ - **Unhandled rejections.** The synchronous `check` and `parse` threw `ERR_ASYNC_VALIDATOR` and
233
+ dropped the promise; `settle` stopped at `maxErrors` before the promises it held; the trial of
234
+ a union branch in `parseAsync` set validators aside it never ran. Every such promise is
235
+ observed before it is left behind.
236
+ - **Async decoders respect `maxErrors`**, and the trial of a plain union branch in `parse` runs
237
+ under the path and root of the parse (a validator met in it saw `"n"` instead of
238
+ `"Doc.u.n"`), tolerates an async validator (`serialize` threw `ERR_ASYNC_VALIDATOR` for one
239
+ inside a union with a serializer) and uses one context per parse.
240
+ - **`compile(target, { jit: false })` returned `{ accelerated: false }` and left the generated
241
+ check installed;** it restores the closures. With `jit: true` a model is compiled all or
242
+ nothing. An `object` or `map` without a valid key type made the JIT fail with a raw
243
+ `TypeError` at construction under `register({ jit: true })`; the definition is rejected when
244
+ the field is built.
245
+ - **The `validate`, `parse` and `serialize` of a nested struct were keys a value could carry**
246
+ (see Upgrading). A calculated field declared as `'x?'` is stored under `x`.
247
+ - **`toJSONSchema`** lost a field called `__proto__`, wrote the segments of the `definitions`
248
+ pointer onto the document the same way, left the name of an entity unescaped inside a `$ref`
249
+ (RFC 6901: `A/b~c` is `#/$defs/A~1b~0c`), looked renderers up on a plain object (a custom type
250
+ called `constructor` resolved to `Object`), pushed the null branch into the `anyOf` of a custom
251
+ type's metadata on every export, and copied `deprecated: 'a note'` through (a boolean in every
252
+ dialect). The `definitions` pointer merges into an object already on its path.
253
+ - **`toTypeScript`** wrote keys that are no identifiers bare (`a-b: string;`), let `*/` in a
254
+ `description` close the JSDoc, dropped the note of a `deprecated` string (it is
255
+ `@deprecated <note>` now), gave two nested types one name (`aB` and `AB` both `TAB`; the
256
+ second is `TAB2`, and a nested type never takes the name of an entity of the model),
257
+ stringified `NaN` and BigInt enum values through JSON (`number` and `10n` now), rendered an
258
+ entity or an embedded reference whose name is no identifier (`ERR_UNREPRESENTABLE` now), and
259
+ declared the alias of a one-type schema twice under `named`. `saveTypes` rejects instead of
260
+ throwing, as its typing says.
261
+ - **An object with a `size` or `length` key was measured as a collection** by the `length`
262
+ rule; a value is measured by what it is.
263
+ - **A validator's own code could break the rendering:** a code such as `'constructor'` or
264
+ `'__proto__'` is rendered with the validator's message; what a validator throws or returns is
265
+ rendered whatever it is (a symbol, an object without a prototype).
266
+ - **An index or a top-level option called like a method broke construction** (`indexes` and
267
+ `options` were instances with an `extract` method); they are dictionaries. The metadata of a
268
+ type is a dictionary too, so `__proto__` is a key of it.
269
+ - **`schema['~standard']` kept the first answer of `hasAsync`** after `attach` or `detach`; the
270
+ props are rebuilt. **`schema.validate(value, path)`** ran the schema-level function without
271
+ the schema as `this` and turned a promise into `"[object Promise]"`; it throws
272
+ `ERR_ASYNC_VALIDATOR` for a promise. **`maxErrors: 1.5`** gave two issues and a bigint broke
273
+ the option's error message.
274
+
275
+ ### Removed
276
+
277
+ - `model.dts`, `schema.toInterface()` and `saveTypes` from the core entry: they are in
278
+ `@alexify/metaschema/generators` (see Upgrading).
279
+
280
+ ### Tooling
281
+
282
+ - `forEach` and `reduce` are lint errors everywhere oxlint runs (`no-restricted-properties`),
283
+ `no-var` and `object-shorthand` errors rather than warnings; lint and format cover `index.js`
284
+ and `browser.js`; `check:dts` compiles the typings of the generators and compile subpaths;
285
+ `ci-success` fails on a skipped job; `pnpm bench --compare --fail-under=<percent>` exits
286
+ non-zero on a scenario slower than the baseline by more than that.
287
+ - New tests: the async union, thenable data, the unhandled rejections (through an
288
+ `unhandledRejection` listener), the union trial's path, `maxDepth` over a 3000-level chain on
289
+ both backends, `jit: false` and the atomic model compile, the compile `error`/`onFallback`,
290
+ the strict source, the key type of collections, the nested codec keys, the generator
291
+ hardening cases (`__proto__` fields, odd `definitions` pointers, escaped `$ref`s, shared
292
+ metadata, quoted keys, JSDoc, name collisions), `lengthOf` on objects with `size` keys,
293
+ dictionaries called like methods, codes a validator makes up, and `maxErrors` as a whole number.
294
+ - `pnpm bench` has `parse — flat struct, valid`, `parse — nested struct, valid` and `parse —
295
+ flat struct, defaults and a decoder` on both backends, measured as `check` is (through a
296
+ megamorphic call site); `bench/baseline.json` is re-saved, and the performance guide quotes
297
+ the rows.
298
+ - New test suites `parse`, `serialize` and `async`, the Standard Schema suite extended for
299
+ `validate` as parse and for a promise, the compile suite holding `parse`, `parseAsync`,
300
+ `checkAsync` and `serialize` to the same results on both backends, the bundle test running
301
+ them through the minified bundles, and `tests/types/parse.test-d.ts` for the typings; all
302
+ under `test`, `test:jit` and `test:nojit`.
303
+ - `pnpm run test:jit` runs the whole suite with every schema compiled by the JIT
304
+ (`tests/helpers/jit.js` registers it before the suites) and `pnpm run test:nojit` the same
305
+ under `--disallow-code-generation-from-strings`, through the fallback; CI runs both on Node
306
+ 22. `tests/unit/compile.test.js` holds the two backends to the same issues over every form of
307
+ the language, the fixture model, every check option and keys and values that look like code,
308
+ and covers the modes, the errors, `register()` and the no-eval environment in a child process;
309
+ `tests/types/compile.test-d.ts` pins the typings. The bundle test, the export-parity test and
310
+ the size script (`pnpm size --max-gzip-compile`) cover the subpath; the ajv differential test
311
+ is skipped where ajv cannot generate code.
312
+ - **The moltar scenarios of `pnpm bench` measure a struct now.** The first key of their schema,
313
+ `number`, made it a `number` field under the first-key rule of 2.0, so every check failed at
314
+ the root, and the 14 M ops/s the 2.0 notes quoted for those rows measured that; marked as a
315
+ struct, the closures do 7.1–7.4 M (flat) and 4.2–4.4 M (nested). Every `check` scenario runs
316
+ on both backends (`check (jit) — …`), and `pnpm bench --compare-libs` runs the moltar
317
+ scenarios through zod 4, valibot, ajv and @sinclair/typebox (devDependencies, `bench/libs.js`);
318
+ the tables are in the performance guide, and `bench/baseline.json` is re-saved.
319
+ - `ajv` and `ajv-formats` are devDependencies, used by `tests/unit/jsonschema-ajv.test.js`: for
320
+ values a deterministic generator produces from the schemas (every form of the language, the
321
+ fixture model, references by kind, embedded and as ids), `check` and ajv over `toJSONSchema`
322
+ must agree on every verdict, for draft 2020-12 and draft-07. The known differences (UTF-16
323
+ units against code points, instances on the output side, number keys) are documented in the
324
+ file and in the guide.
325
+ - New test suites: `generators` (the subpath: the functions, `register()`, the core without it),
326
+ `jsonschema` (every form by target, the strict profile, the mongodb target, the fixture model,
327
+ the Standard converter), `jsonschema-ajv`, `dts` (JSDoc and named types),
328
+ `tests/types/jsonschema.test-d.ts`; the bundle test builds the core entry with the subpath,
329
+ the export-parity test covers the subpath, `pnpm size` reports the generators on top of the
330
+ core.
331
+
332
+ ## [2.0.0] - 2026-10-10
333
+
334
+ 2.0 rewrites the validation core and settles the semantics of the schema language. Every check
335
+ is compiled into a closure when the schema is built and runs in a context of its own; issues
336
+ are data (a code, the path as an array of keys, the params the message is made from), messages
337
+ are rendered through a locale at the end of a check, and `check` takes an options object. The
338
+ first key of a definition decides what it is, numbers are bounded by `min` and `max`, a
339
+ reference follows the kind of its target, and `integer`, `date`, `null`, `any`, `union`,
340
+ `nullable` and `pattern` join the language. TypeScript infers the type of a value from the
341
+ definition (`Infer`), and every schema is a Standard Schema. Everything that changes the shape
342
+ of a result or the meaning of a definition is listed under Upgrading; the rest is additive.
343
+
344
+ ### Upgrading from 1.x
345
+
346
+ The same guide with before-and-after examples is
347
+ [Migrating from 1.x](https://metaschema.vercel.app/guide/migrating-from-1).
348
+
349
+ **Validation**
350
+
351
+ - **`check(value, path, options)` → `check(value, options)`.** The root label of the error
352
+ lines is `options.root`: `schema.check(value, 'body', { maxErrors: 1 })` becomes
353
+ `schema.check(value, { root: 'body', maxErrors: 1 })`, and a string in place of the options
354
+ throws a `TypeError` that says so. The options are `root`, `maxErrors`, `unknown`,
355
+ `references` and `messages`.
356
+ - **`issue.path` is an array of keys** (`['tags', 1, 'name']`, what Standard Schema expects),
357
+ not a string, and it never includes the root. `issue.message` describes the problem without
358
+ its location (`is required`) and `issue.params` carries what it was made from
359
+ (`{ expected: 'number', received: 'string' }`); the line with the location is
360
+ `result.errors[i]` (`Field "User.name" is required`), rendered on first use. A key that is
361
+ not an identifier is bracketed (`o["a.b"]`, was `o.a.b`) and a tuple element is addressed by
362
+ index (`point[1]`, was `point(item1)` or `point(y1)` for a named element). A `validate`
363
+ function may return `{ code, message, path, params }` of its own; its `path` (a key or an
364
+ array of keys) is relative to the field (`{ message, path: 'x' }` on `a` reports `a.x`; 1.x
365
+ ignored it).
366
+ - **Unknown keys are one issue per struct**: `{ code: 'unexpected', params: { keys } }` at the
367
+ path of the struct, rendered as `Field "" has unexpected keys: b, c` (was one
368
+ `Field "b" is not expected` per key), and `maxErrors` counts them as one.
369
+ `check(value, { unknown: 'ignore' })` accepts them, and `{ Form: { unknown: 'ignore' }, ... }`
370
+ makes that the default of the schema.
371
+ - **A type failure cancels the rules and `validate` of the field.** A field is checked in the
372
+ order type, rules, `validate`, each step only when the one before it passed; 1.x reported
373
+ `not of expected type: string`, the `length` message and the validator's message together.
374
+ The schema-level `validate` runs after the fields and only when every field passed (it used
375
+ to run first, and always).
376
+ - **`new ValidationResult(path)` → `new ValidationResult(options?)`** (`{ root, messages }`). A
377
+ result a `validate` function returns is relative to its field, so build it with no arguments
378
+ and `add` messages. `ValidationResult.format` is gone;
379
+ `ValidationResult.issuesOf(error, path?, code?)` takes the path as keys.
380
+ - **Cycle detection lives at references.** A value that refers back to itself is reported as
381
+ `circular` where a reference (`'Category'`, `{ many }`) meets it again, as before; a schema
382
+ without references cannot recurse, so such a value is walked as far as the schema goes and
383
+ reported for what it is (unexpected keys, wrong types, or nothing) instead of as `circular`.
384
+ - **The tuple length message** is `exceeds the maximum length` with `params: { max, actual }`
385
+ (was `value length is more than expected in tuple`). The wording of every other message is
386
+ unchanged.
387
+ - **Warnings carry a code**: `Warning [missing-reference]: "Customer" referenced by "Order" is
388
+ not found` (was `Warning: "Customer" ...`), `Warning [recursive-reference]: ...`, and the new
389
+ lint adds `unknown-option`, `unbounded-pattern` and `missing-index-field` to `model.warnings`,
390
+ which is computed on first use.
391
+ - **`field.check(value, context, key)`** is the compiled check of a field and records into the
392
+ context of a check; call `schema.check`. `compile` joins the reserved keys of a field
393
+ definition (`ERR_RESERVED_KEY`).
394
+
395
+ **The schema language**
396
+
397
+ - **The first key of an object decides what it is.** The long form is read only when `type` is
398
+ the first key; a capitalized first key is a kind, a type name is that type's shorthand, and
399
+ any other first key is a nested struct. `{ name: 'string', type: 'string' }` is a struct with
400
+ two fields (1.x read it as a string); `{ required: false, type: 'string' }` throws
401
+ `ERR_INVALID_DEFINITION`. A struct whose first field is called `type`, or named like a type
402
+ (`date`, `null`, `any`, `unknown`, `integer` and `union` are type names now), needs a kind
403
+ (`{ Struct: {}, ... }`) or the `schema` shorthand; `schema.warnings` reports the options such
404
+ a struct would otherwise leave on the type.
405
+ - **`length` on a number is an error.** `number`, `bigint` and the new `integer` are bounded by
406
+ `min` and `max`: `{ type: 'number', length: [18, 120] }` becomes
407
+ `{ type: 'integer', min: 18, max: 120 }`. A `length` there throws `ERR_INVALID_RULE` with
408
+ that hint, and a failed bound is a `range` issue (`is greater than 120`), not `length`
409
+ (`exceeds the maximum length`). Every type lists the rules it accepts, so `min` on a string
410
+ or `length` on a boolean throws too; a custom type opts in with `rules: [...]`, and an alias
411
+ takes the rules of its base. A `length` whose `min` is above its `max` throws
412
+ `ERR_INVALID_LENGTH` (1.x accepted it).
413
+ - **A reference follows the kind of its target.** A reference to a stored kind (`Entity`,
414
+ `Registry`, ...) validates as an id (`employer: 'c1'`, `addresses: ['a1']`) and a reference
415
+ to a memory kind (`Struct`, `Form`, ...) as the record; 1.x always expected the record and
416
+ rejected an id as `not of expected type: object`. Validate a whole graph with
417
+ `check(value, { references: 'embed' })`, rows with `{ references: 'id' }`, or fix one field
418
+ with `embed: true`/`false`. An id never recurses, so a cyclic value through stored kinds is a
419
+ type error, not `circular`. The generated TypeScript follows the same rule, so a memory-kind
420
+ reference renders as its interface (`label: Tag`) instead of `labelId: string`.
421
+ - **`set` renders as `Set<T>`** in the generated TypeScript (it was `T[]` while `check`
422
+ accepted only a `Set`; `map` was already `Map<K, V>`).
423
+ - **The `relations` labels are swapped** to the conventional direction, read from the
424
+ referencing side: a `many` field is `'one-to-many'` and a single reference `'many-to-one'`.
425
+ - **A tuple element may be any definition**, not only a scalar. `[{ x: 'number' }]` is still a
426
+ named number (one key holding a type name); `[{ x: 'number', y: 'number' }]` is a struct
427
+ element (1.x read it as the named number `x` and reported `t(x0)`). `ERR_INVALID_TUPLE` is
428
+ for a definition that is not an array or an element that is a function.
429
+ - **A `Schema` instance as a field keeps its schema-level `validate`** in every form (bare,
430
+ `{ schema }`, the long form); 1.x dropped it, so a value that passed may now fail.
431
+
432
+ **Tooling**
433
+
434
+ - **The typings need TypeScript 5.0 or later.** `Schema` is generic over its definition
435
+ (`Schema<D>`, a const type parameter); `Schema` written on its own is still any schema, and
436
+ `Model.entities` is still a `Map<string, Schema>`.
437
+ - **The bundle is 12.6 KB min+gzip** (1.0 was under 8 KB), and CI gates at 13 KB.
438
+
439
+ ### Added
440
+
441
+ - **Static inference.** `Infer<D>` is the TypeScript type of a value `check` accepts for the
442
+ definition type `D`, over every form of the language: scalars (`integer` → `number`, `date`
443
+ → `Date`, `json` → `unknown`), `'?T'`, `'key?'` and `required: false` as optional properties
444
+ that accept `null`, `nullable: true` as `T | null`, the long form, `array`/`set`/`object`/`map`,
445
+ `enum` as a union of literals, tuples (named elements included), nested structs, `schema`
446
+ and `Schema` instances, `union`, and references as ids (`string`, `string[]`). A kind key,
447
+ index definitions, calculated fields and the schema-level options are not fields. `Schema` is
448
+ `Schema<D>` with a const type parameter, so `Schema.from({ ... })` keeps the literal types of
449
+ an inline definition and `InferSchema<typeof schema>` reads them; a definition declared apart
450
+ needs `as const`. `Infer<D, E>` takes an entity map and resolves a reference to a memory kind
451
+ (or `embed: true`) as the record and a projection as its parent's fields;
452
+ `InferEntity<E, 'Name'>` adds the id field of a stored kind. Custom types are declared for
453
+ inference through module augmentation of `CustomTypes`; an unknown name infers as `unknown`.
454
+ - **Standard Schema v1.** Every `Schema` exposes `schema['~standard']`
455
+ (`{ version: 1, vendor: 'alexify.metaschema', validate }`), the interface tRPC, TanStack Form,
456
+ Hono and the other consumers of [standardschema.dev](https://standardschema.dev) accept
457
+ without an adapter. `validate(value)` is `check(value)` read as the specification does:
458
+ `{ value }` (the same reference) or `{ issues }`, the issues of the result themselves
459
+ (`message` and an array `path`, plus `code` and `params`); the `libraryOptions` of a call are
460
+ the options of `check`. The accessor lives on the prototype and stays out of `toJSON` and
461
+ `Object.keys`. The typings declare it as `StandardProps<D>` (with `StandardResult<T>` and
462
+ `StandardOptions`), and a `Schema<D>` is a `StandardSchemaV1<Infer<D>, Infer<D>>` of
463
+ `@standard-schema/spec`, which the package does not depend on.
464
+ - **New built-in types.** `integer` (`Number.isInteger`), `date` (a `Date` with a valid time),
465
+ `null`, `any` and `unknown` (one type under two names, differing in the TypeScript they
466
+ render), and `union`: `{ union: ['string', 'number'] }` keeps the first branch that reports
467
+ nothing; `{ union: [...], discriminator: 'kind' }` picks the branch from an enum field in one
468
+ lookup, built when the schema is built, and reports an unknown value as one `union` issue at
469
+ the discriminator's path. A definition that cannot discriminate throws `ERR_INVALID_UNION`.
470
+ - **`nullable: true`**: a required key whose value may be `null`, apart from optional (`'?type'`,
471
+ `undefined` or `null`). It applies to any type, skips the rules and `validate` for `null`,
472
+ and renders as `T | null`.
473
+ - **`min` and `max`** for `number`, `integer` and `bigint`, as numbers or bigints compared
474
+ exactly (never through `Number`), with the `range` issue `{ min, max, actual }`.
475
+ - **`pattern`** for strings, a string or a `RegExp` compiled once with the `u` flag (and without
476
+ `g`/`y`), with the `pattern` issue `{ pattern }`; the validation guide has a section on ReDoS.
477
+ - **`unicode: true`** measures a string's `length` in code points instead of UTF-16 units.
478
+ - **The unknown-keys policy as metadata**: `{ Form: { unknown: 'ignore' }, ... }` is the default
479
+ of that schema's `check`; the option of a call still wins.
480
+ - **`check` options** `root`, `maxErrors`, `unknown` (`'reject'` | `'ignore'`), `references`
481
+ (`'kind'`, `'embed'`, `'id'`) and `messages`, validated when the check starts, and the field
482
+ option `embed` on a reference.
483
+ - **Issues with params.** `result.issues` is `{ code, path, message, params }`:
484
+ `type { expected, received }` (plus `key` for a wrong key type in an `object` or `map`),
485
+ `unexpected { keys }`, `enum { values }`, `length { min, max, actual }`,
486
+ `range { min, max, actual }`, `pattern { pattern }`, `union { expected, discriminator }`,
487
+ `reference { entity }`, `exception { error }`.
488
+ - **Locales.** Messages are rendered once, at the end of a check, from the code and params of
489
+ each issue through `options.messages`: a locale table (partial tables fall back to English) or
490
+ a function. English is built in, Ukrainian is exported as `@alexify/metaschema/locales/uk`
491
+ (and English as `@alexify/metaschema/locales/en`).
492
+ - **`result.summary`, `result.flatten()` and `result.tree()`** for CLIs and forms, and
493
+ `result.errors` as a lazy view rendered on first use.
494
+ - **Definition lint.** `schema.warnings` reports an option the field's type does not read
495
+ (`unknown-option`; `default`, `unique`, `index`, `primary`, `title`, `description`, `examples`
496
+ and `deprecated` are known annotations), a `pattern` without `length.max`
497
+ (`unbounded-pattern`) and an index over a missing field (`missing-index-field`);
498
+ `model.warnings` adds `missing-reference`, `missing-type` and `recursive-reference`. Both are
499
+ computed on first use.
500
+ - **Definition error codes** `ERR_INVALID_RULE` and `ERR_INVALID_UNION`.
501
+ - **Types**: `Infer`, `InferSchema`, `InferEntity`, `CustomTypes`, `StandardProps`,
502
+ `StandardResult`, `StandardOptions`, `IssueParams`, `IssueOf<Code>`, `Locale`, `Messages`,
503
+ `ResultOptions`, `FlatIssues`, `IssueTree` and `CheckContext`; `ValidationIssue` is a union by
504
+ code; `FieldType.nullable` and `embed`, `Schema.unknown` and `warnings`,
505
+ `CheckOptions.references` and `KindMetadata.unknown`.
506
+ - **Benchmarks**: the four modes of the typescript-runtime-type-benchmarks suite (`parseSafe`,
507
+ `parseStrict`, `assertLoose`, `assertStrict`) over its object, flat and nested, next to the
508
+ `check`, `Schema.from` and `Model` scenarios.
509
+
510
+ ### Changed
511
+
512
+ - **Validation is compiled.** `createStruct` builds a frozen plan and a dictionary of known keys
513
+ and compiles the struct check as an index loop over the plan; every field's `check` is a
514
+ closure chosen when the field is built (one `typeof` for a scalar without rules, a `Set` for
515
+ an `enum` with more than eight values, `Map` and `Set` iterated directly, `object` through
516
+ `for...in`, a lookup plus cycle tracking for a reference), and `Object.hasOwn` is consulted
517
+ only for a required field set to `undefined` or a field named after a member of
518
+ `Object.prototype`. A check runs in a context of its own
519
+ (`{ issues, count, limit, path, seen, unknown, references, root, messages }`) instead of
520
+ module globals, so two checks can no longer interfere and a validator may run another check.
521
+ On the benchmark of the repository (Node 24, the same machine) `check` goes from 2.1 M to
522
+ 10.7 M ops/s for a valid flat value and from 0.87 M to 3.5 M for an invalid one, nested from
523
+ 0.33 M to 2.7 M; construction stays where it was. See
524
+ [Performance](https://metaschema.vercel.app/guide/performance).
525
+ - **Generated TypeScript** follows the language: `integer` → `number`, `date` → `Date`, `null`,
526
+ `any`, `unknown`, a `union` as `A | B`, a nullable field as `T | null`, a `set` as `Set<T>`, a
527
+ reference by the kind of its target (see Upgrading).
528
+ - **Construction** reads the first key of a definition once, re-parses a projection's fields
529
+ from their definitions so the copies belong to the projection, and lints on first use of
530
+ `warnings`.
531
+
532
+ ### Removed
533
+
534
+ - **The positional root path of `check`** and **`ValidationResult.format`** (see Upgrading).
535
+ - **`length` on `number` and `bigint`**, replaced by `min` and `max` (see Upgrading).
536
+ - **Module-level validation state.** Nothing in the package is global to a check any more; the
537
+ type registry is still process-wide, as before.
538
+
539
+ ### Fixed
540
+
541
+ - **A `Schema` instance used as a field lost its schema-level `validate`** (see Upgrading).
542
+ - **A `length` whose `min` is above its `max`**, which could never pass, is rejected when the
543
+ schema is built instead of failing every value.
544
+ - **A `bigint` bound is compared exactly.** `length` on a `bigint` went through `Number` and
545
+ lost precision past 2^53; `min` and `max` compare a bigint bound as a bigint.
546
+
547
+ ### Tooling
548
+
549
+ - `pnpm size --max-gzip 13` is the CI gate (the entries are 12.6 KB min+gzip).
550
+ - `pnpm bench` reads the clock once per hundred calls and calls `check` through a megamorphic
551
+ site, so it is measured as a callee instead of being inlined into the measuring loop;
552
+ `bench/baseline.json` is the snapshot of this branch.
553
+ - `@standard-schema/spec` is a devDependency, used only by `tests/types/standard.test-d.ts`.
554
+ - New test suites: `context`, `issues`, `result`, `check-options`, `syntax`, `numbers`,
555
+ `pattern`, `nullable`, `values`, `union`, `references`, `lint`, `standard`, and
556
+ `tests/types/infer.test-d.ts`, which also compiles the examples of the TypeScript guide.
557
+
10
558
  ## [1.0.0] - 2026-10-09
11
559
 
12
560
  The first release of `@alexify/metaschema`. It is a fork of
@@ -417,7 +965,9 @@ published.
417
965
 
418
966
  ### [metaschema 0.x][upstream-0.x] - First generation of metaschema
419
967
 
420
- [unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/v1.0.0...HEAD
968
+ [unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/v3.0.0...HEAD
969
+ [3.0.0]: https://github.com/Alexis-Technologies/metaschema/compare/v2.0.0...v3.0.0
970
+ [2.0.0]: https://github.com/Alexis-Technologies/metaschema/compare/v1.0.0...v2.0.0
421
971
  [1.0.0]: https://github.com/Alexis-Technologies/metaschema/releases/tag/v1.0.0
422
972
  [upstream-2.2.2]: https://github.com/metarhia/metaschema/compare/v2.2.1...v2.2.2
423
973
  [upstream-2.2.1]: https://github.com/metarhia/metaschema/compare/v2.2.0...v2.2.1