@alexify/metaschema 2.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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,328 @@ 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
+
10
332
  ## [2.0.0] - 2026-10-10
11
333
 
12
334
  2.0 rewrites the validation core and settles the semantics of the schema language. Every check
@@ -643,7 +965,8 @@ published.
643
965
 
644
966
  ### [metaschema 0.x][upstream-0.x] - First generation of metaschema
645
967
 
646
- [unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/v2.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
647
970
  [2.0.0]: https://github.com/Alexis-Technologies/metaschema/compare/v1.0.0...v2.0.0
648
971
  [1.0.0]: https://github.com/Alexis-Technologies/metaschema/releases/tag/v1.0.0
649
972
  [upstream-2.2.2]: https://github.com/metarhia/metaschema/compare/v2.2.1...v2.2.2
package/README.md CHANGED
@@ -36,6 +36,14 @@ result.issues;
36
36
  // { code: 'length', path: ['email'], message: 'value is too short', params: { min: 5, max: 64, actual: 3 } },
37
37
  // { code: 'enum', path: ['roles', 0], message: 'value is not of enum: admin, editor, viewer', params: { values: ['admin', 'editor', 'viewer'] } }
38
38
  // ]
39
+
40
+ const event = Schema.from({
41
+ name: 'string',
42
+ 'level?': { type: 'integer', default: 1 },
43
+ when: { type: 'string', parse: (text) => new Date(text) },
44
+ });
45
+ event.parse({ name: 'deploy', when: '2026-10-10T12:00:00.000Z' }).value;
46
+ // { name: 'deploy', when: 2026-10-10T12:00:00.000Z, level: 1 }
39
47
  ```
40
48
 
41
49
  ### 📖 [Read the documentation →](https://metaschema.vercel.app/)
@@ -49,19 +57,31 @@ result.issues;
49
57
  a code, the path as an array of keys, the params it was made from, and a message rendered through
50
58
  a locale (English built in, `@alexify/metaschema/locales/uk` shipped). Only a broken definition
51
59
  throws.
60
+ - **Parse, not only a verdict.** `parse` runs the same check and gives the value of the program:
61
+ defaults filled in, unknown keys stripped on request, a field's `parse` function decoding its
62
+ value (a date-time string into a `Date`) and `serialize` the way back; `checkAsync` and
63
+ `parseAsync` await validators and decoders that return promises.
52
64
  - **Domain models.** Entities, registries, dictionaries and projections, with references,
53
65
  relations and indexes, ordered by dependency and checked for missing references.
54
66
  - **TypeScript.** `InferSchema<typeof schema>` is the type of a value the schema accepts,
55
67
  computed from the definition with nothing generated, and a model renders its entities as
56
68
  interfaces. The package ships hand-written typings for its own API.
57
69
  - **Standard Schema.** Every schema implements [Standard Schema v1](https://standardschema.dev)
58
- (`schema['~standard']`), so tRPC, TanStack Form, Hono and any other consumer of the interface
59
- take it as they take a zod or valibot schema.
70
+ (`schema['~standard']`, which is `parse`), so tRPC, TanStack Form, Hono and any other consumer
71
+ of the interface take it as they take a zod or valibot schema.
72
+ - **JSON Schema.** `toJSONSchema` renders a schema or a whole model as JSON Schema draft 2020-12
73
+ or draft-07, an OpenAPI 3.0 schema object or a MongoDB `$jsonSchema`, with a strict profile for
74
+ LLM structured outputs; `~standard.jsonSchema` is the Standard JSON Schema converter. The
75
+ generators live in the `@alexify/metaschema/generators` subpath, so a program that only
76
+ validates does not carry them.
60
77
  - **Fast.** Every check is compiled into a closure when the schema is built and runs in a context
61
- of its own: about 10 million validations a second of a flat struct on Node 24 (`pnpm bench`,
78
+ of its own: about 10 million validations a second of a flat struct on Node 24, and about 30
79
+ million through the JIT backend of `@alexify/metaschema/compile`, which generates the same
80
+ check where `new Function` is allowed and keeps the closures where it is not (`pnpm bench`,
62
81
  see [Performance](https://metaschema.vercel.app/guide/performance)).
63
- - **Zero dependencies, 12.6 KB min+gzip.** CommonJS with ESM named imports, no build step,
64
- one package for Node.js and browsers.
82
+ - **Zero dependencies, 16.1 KB min+gzip.** CommonJS with ESM named imports, no build step,
83
+ one package for Node.js and browsers; the generators add 4.5 KB and the JIT backend 3.9 KB
84
+ where they are imported.
65
85
 
66
86
  ## Installation
67
87
 
@@ -131,7 +151,9 @@ model.order; // Set { 'Address', 'Company', 'User' }
131
151
  model.warnings; // [] (lint and consistency warnings, `Warning [code]: text`, end up here)
132
152
  model.entities.get('User').check({ login: 'ab', company: 'c1', active: true }).errors;
133
153
  // [ 'Field "User.login" value is too short' ]
134
- console.log(model.dts);
154
+
155
+ const { toTypeScript } = require('@alexify/metaschema/generators');
156
+ console.log(toTypeScript(model));
135
157
  ```
136
158
 
137
159
  ```ts
@@ -156,7 +178,10 @@ interface User {
156
178
  }
157
179
  ```
158
180
 
159
- `saveTypes(outputFile, model)` writes `model.dts` to a file. The first key of a definition sets
181
+ `saveTypes(outputFile, model, options?)` of the same subpath writes the interfaces to a file
182
+ (`{ named: true }` names enums and nested structs, and a field's `description` is its JSDoc); its
183
+ `register()` adds `model.dts`, `model.toTypeScript` and `schema.toInterface` as methods. The first
184
+ key of a definition sets
160
185
  its kind and metadata (`Entity`, `Registry`, `Dictionary`, `Journal`, `Details`, `Relation`,
161
186
  `View`, `Struct`, `Form`, `Projection`, or any custom kind). Stored kinds default to
162
187
  `scope: 'application'` and `store: 'persistent'`, and they get an id field; a reference to a
@@ -198,7 +223,7 @@ type User = InferSchema<typeof user>;
198
223
  Every form of the language is covered: optional and nullable fields, collections, enums,
199
224
  tuples, unions, nested structs, references (an id, or the record through an entity map with
200
225
  `Infer<D, E>` and `InferEntity<E, 'Name'>`) and custom types declared through module
201
- augmentation of `CustomTypes`. A model renders its entities as interfaces with `model.dts`. See
226
+ augmentation of `CustomTypes`. A model renders its entities as interfaces with `toTypeScript`. See
202
227
  [TypeScript](https://metaschema.vercel.app/guide/typescript).
203
228
 
204
229
  A `Schema<D>` is also a `StandardSchemaV1<Infer<D>, Infer<D>>` of `@standard-schema/spec`:
@@ -206,14 +231,76 @@ A `Schema<D>` is also a `StandardSchemaV1<Infer<D>, Infer<D>>` of `@standard-sch
206
231
  `StandardOptions` beside it. See
207
232
  [Standard Schema](https://metaschema.vercel.app/guide/standard-schema).
208
233
 
234
+ ## JSON Schema
235
+
236
+ `toJSONSchema(schema, options)` of `@alexify/metaschema/generators` renders the rules of `check`
237
+ as a JSON Schema document, and `toJSONSchema(model, options)` every entity of a model as a
238
+ definition:
239
+
240
+ ```js
241
+ const { toJSONSchema } = require('@alexify/metaschema/generators');
242
+
243
+ toJSONSchema(user, { target: 'draft-07' });
244
+ // {
245
+ // $schema: 'http://json-schema.org/draft-07/schema#',
246
+ // type: 'object',
247
+ // properties: {
248
+ // name: { type: 'object', properties: { first: { type: 'string' }, last: { type: 'string' } }, required: ['first', 'last'], additionalProperties: false },
249
+ // email: { type: 'string', minLength: 5, maxLength: 64 },
250
+ // age: { type: ['number', 'null'] },
251
+ // roles: { type: 'array', items: { enum: ['admin', 'editor', 'viewer'] } }
252
+ // },
253
+ // required: ['name', 'email', 'roles'],
254
+ // additionalProperties: false
255
+ // }
256
+
257
+ toJSONSchema(answer, { profile: 'strict' }); // the dialect of OpenAI and Anthropic structured outputs
258
+ toJSONSchema(model, { target: 'mongodb' }); // one $jsonSchema validator per entity
259
+ ```
260
+
261
+ The targets are `draft-2020-12` (the default), `draft-07`, `openapi-3.0` and `mongodb`; an
262
+ optional field accepts `null`, a reference to a stored kind is its id and a reference to a memory
263
+ kind a `$ref`, `validate` functions are not exported, and a type with no form in the target
264
+ (`bigint`, a `Date` on the way out) throws unless the call says `unrepresentable: 'any'`. The
265
+ export is checked against ajv for every form of the language. `register()` of the subpath turns
266
+ the functions into methods (`schema.toJSONSchema`, `model.toJSONSchema`) and adds the Standard
267
+ JSON Schema converter to `schema['~standard']`. See
268
+ [JSON Schema](https://metaschema.vercel.app/guide/json-schema).
269
+
270
+ ## Compiled checks
271
+
272
+ `compile(schema)` of `@alexify/metaschema/compile` replaces the check of a schema, or of every
273
+ entity of a model, with one function generated from the same plan the closures walk and built
274
+ with `new Function`; `register()` does it for every schema built from then on. The issues are
275
+ the ones the closures record, only sooner: about three times faster on a flat struct, six on a
276
+ nested one. Where code generation from strings is not allowed (a Content Security Policy,
277
+ Cloudflare Workers, `node --disallow-code-generation-from-strings`) nothing changes: the
278
+ closures stay, silently unless `{ jit: true }` asks for an error.
279
+
280
+ ```js
281
+ const { compile, register, canEval } = require('@alexify/metaschema/compile');
282
+
283
+ compile(user); // { accelerated: true }: user.check runs generated code now
284
+ compile(model); // every entity; { accelerated: false } where there is no eval
285
+ register(); // every schema built from here on is compiled as it is built
286
+ canEval(); // whether this environment builds functions from source
287
+ ```
288
+
289
+ The generated source holds identifiers, numbers and JSON strings only; regular expressions, enum
290
+ sets, validate functions and nested schemas reach it through a scope, never through the source
291
+ text. See [The JIT backend](https://metaschema.vercel.app/guide/compile).
292
+
209
293
  ## Exports
210
294
 
211
295
  ```js
212
296
  const {
213
297
  KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW,
214
- getKindMetadata, saveTypes, Schema, Model, SchemaDefinitionError, ValidationResult,
298
+ getKindMetadata, Schema, Model, SchemaDefinitionError, ValidationResult,
215
299
  } = require('@alexify/metaschema');
216
300
 
301
+ const { toJSONSchema, toTypeScript, saveTypes, register } = require('@alexify/metaschema/generators');
302
+ const { compile, canEval } = require('@alexify/metaschema/compile'); // and its own register()
303
+
217
304
  const en = require('@alexify/metaschema/locales/en'); // the built-in messages
218
305
  const uk = require('@alexify/metaschema/locales/uk'); // schema.check(value, { messages: uk })
219
306
  ```
@@ -223,12 +310,30 @@ import { Schema, Model } from '@alexify/metaschema';
223
310
  import type { Infer, InferSchema, InferEntity, CustomTypes, ValidationIssue } from '@alexify/metaschema';
224
311
  ```
225
312
 
226
- In the browser every export works the same, except `saveTypes`, which rejects because there is no
227
- file system. The [API reference](https://metaschema.vercel.app/api/exports) lists every member
313
+ In the browser every export works the same, except `saveTypes` of the generators, which rejects
314
+ because there is no file system, and `compile`, which keeps the closures where a Content
315
+ Security Policy forbids `new Function`. The [API reference](https://metaschema.vercel.app/api/exports) lists every member
228
316
  and every exported type.
229
317
 
230
318
  ## Migrating
231
319
 
320
+ ### From 2.x
321
+
322
+ 3.0 has two breaking changes. The generators left the core entry: `model.dts`,
323
+ `schema.toInterface()` and `saveTypes` are `toTypeScript(target, options)` and
324
+ `saveTypes(file, target, options)` of `@alexify/metaschema/generators`, whose `register()` puts
325
+ the methods back on the classes once per process. And `schema['~standard'].validate` is `parse`
326
+ rather than `check`: a consumer of Standard Schema gets the defaults filled in and the `parse`
327
+ functions applied, and a promise for a schema with an `async function`. The smaller changes: a
328
+ struct rejects an array, the synchronous `check` and `parse` throw `ERR_ASYNC_VALIDATOR` for a
329
+ promise, a graph deeper than 128 embedded records is a `depth` issue (`maxDepth` raises it),
330
+ `Infer` makes a defaulted key optional, and a few definitions that could never work throw when
331
+ the schema is built. Everything else is additive: `parse`, `serialize`, `checkAsync` and
332
+ `parseAsync`, the JSON Schema export, the JIT backend of `@alexify/metaschema/compile`, JSDoc
333
+ and named types. The step-by-step guide with before-and-after examples is
334
+ [Migrating from 2.x](https://metaschema.vercel.app/guide/migrating-from-2); the full list is
335
+ under "Upgrading from 2.0" in the [CHANGELOG](./CHANGELOG.md).
336
+
232
337
  ### From 1.x
233
338
 
234
339
  2.0 changes the shape of a result (`issue.path` is an array of keys, `issue.message` has no
@@ -259,7 +364,7 @@ the same schema language. What changed in 1.0:
259
364
  - **`browser.js`** replaces `dist.js`, and an `exports` map closes deep imports.
260
365
 
261
366
  The full list is in [Migrating from metarhia](https://metaschema.vercel.app/guide/migrating-from-metarhia),
262
- and the 2.0 changes above apply on top of it.
367
+ and the 2.0 and 3.0 changes above apply on top of it.
263
368
 
264
369
  ## Changelog
265
370
 
package/SECURITY.md CHANGED
@@ -6,7 +6,8 @@ Only the latest published version receives fixes.
6
6
 
7
7
  | Version | Supported |
8
8
  |---|---|
9
- | 2.x | ✅ |
9
+ | 3.x | ✅ |
10
+ | 2.x | ❌ (upgrade: the CHANGELOG has the notes) |
10
11
  | 1.x | ❌ |
11
12
  | `metaschema` (metarhia) 2.x | ❌ (report upstream) |
12
13
 
@@ -32,17 +33,35 @@ timeline once the report is confirmed.
32
33
  Some things work as intended and are not vulnerabilities:
33
34
 
34
35
  - **Schemas are code.** A schema is a JavaScript value supplied by the application. Field and
35
- schema `validate` functions, custom types' `construct` / `checkType`, and calculated fields are
36
- live functions that run with the privileges of your process. Build schemas only from definitions
37
- you trust, the same as any other module you `require`.
38
- - **metaschema never loads or evaluates code.** Since 1.0 it has no loader: it does not read schema
39
- files, evaluate source strings or run a sandbox. Turning untrusted input into a schema definition
40
- is the application's decision and responsibility.
36
+ schema `validate` functions, custom types' `construct` / `checkType`, calculated fields, the
37
+ `parse` and `serialize` functions of a field and of a schema (decoders and serializers), and
38
+ `default` factories are live functions that run with the privileges of your process; a
39
+ decoder's exception is an issue, a serializer's or a default factory's exception is yours. A
40
+ getter on the value under check is the program's code too, and an exception from it leaves
41
+ `check`. Build schemas only from definitions you trust, the same as any other module you
42
+ `require`.
43
+ - **metaschema never loads or evaluates code it did not write.** Since 1.0 it has no loader: it
44
+ does not read schema files, evaluate source strings or run a sandbox. Turning untrusted input
45
+ into a schema definition is the application's decision and responsibility. The one place that
46
+ builds a function from source is the `@alexify/metaschema/compile` subpath (3.0), and only when
47
+ the application calls its `compile()` or `register()`: the source is generated by the package
48
+ from the schema's plan, nothing taken from a schema or from a value under check reaches it
49
+ except as a JSON string literal (regular expressions, enum values, functions and nested schemas
50
+ are passed by reference through a scope), the generated code is strict and named in a
51
+ `sourceURL`, and where `new Function` is not allowed (a Content Security Policy, Cloudflare
52
+ Workers, `node --disallow-code-generation-from-strings`) the closure backend stays. The probe
53
+ `canEval()` runs `new Function('')` once; under a CSP with a `report-uri` that one violation
54
+ is reported, and under a report-only policy the probe succeeds and every build is reported. A
55
+ check the generator cannot build is reported (`compile().error`, `register({ onFallback })`),
56
+ never installed. The core entry never calls `new Function`.
41
57
  - **Input shape is checked strictly.** Every key that is not in the schema is reported as
42
58
  unexpected (`has unexpected keys: ...`), including `constructor`, `__proto__` and `toString`,
43
59
  unless the schema or the call says `unknown: 'ignore'`. Fields live in a
44
60
  null-prototype dictionary, so nothing on `Object.prototype` is ever read as a field, and
45
- metaschema never writes to the value it checks.
61
+ metaschema never writes to the value it checks. A value with a `then` function is data: the
62
+ passes of `parse` and `parseAsync` await only the promises their own decoders make, never a
63
+ thenable of the value. A graph nested deeper than `maxDepth` embedded records (128 by
64
+ default) is a `depth` issue, not a stack overflow.
46
65
  - **Validation errors are data.** `check` collects problems as issues (a code, a path and params,
47
66
  with a rendered message) instead of throwing on bad input. The messages contain field paths (which can include key names taken from the input,
48
67
  truncated to 100 characters) and, for `enum`, the allowed values; they never contain the