@alexify/metaschema 0.0.0-stage → 2.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 ADDED
@@ -0,0 +1,679 @@
1
+ # Changelog
2
+
3
+ All notable changes to **`@alexify/metaschema`** are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [2.0.0] - 2026-10-10
11
+
12
+ 2.0 rewrites the validation core and settles the semantics of the schema language. Every check
13
+ is compiled into a closure when the schema is built and runs in a context of its own; issues
14
+ are data (a code, the path as an array of keys, the params the message is made from), messages
15
+ are rendered through a locale at the end of a check, and `check` takes an options object. The
16
+ first key of a definition decides what it is, numbers are bounded by `min` and `max`, a
17
+ reference follows the kind of its target, and `integer`, `date`, `null`, `any`, `union`,
18
+ `nullable` and `pattern` join the language. TypeScript infers the type of a value from the
19
+ definition (`Infer`), and every schema is a Standard Schema. Everything that changes the shape
20
+ of a result or the meaning of a definition is listed under Upgrading; the rest is additive.
21
+
22
+ ### Upgrading from 1.x
23
+
24
+ The same guide with before-and-after examples is
25
+ [Migrating from 1.x](https://metaschema.vercel.app/guide/migrating-from-1).
26
+
27
+ **Validation**
28
+
29
+ - **`check(value, path, options)` → `check(value, options)`.** The root label of the error
30
+ lines is `options.root`: `schema.check(value, 'body', { maxErrors: 1 })` becomes
31
+ `schema.check(value, { root: 'body', maxErrors: 1 })`, and a string in place of the options
32
+ throws a `TypeError` that says so. The options are `root`, `maxErrors`, `unknown`,
33
+ `references` and `messages`.
34
+ - **`issue.path` is an array of keys** (`['tags', 1, 'name']`, what Standard Schema expects),
35
+ not a string, and it never includes the root. `issue.message` describes the problem without
36
+ its location (`is required`) and `issue.params` carries what it was made from
37
+ (`{ expected: 'number', received: 'string' }`); the line with the location is
38
+ `result.errors[i]` (`Field "User.name" is required`), rendered on first use. A key that is
39
+ not an identifier is bracketed (`o["a.b"]`, was `o.a.b`) and a tuple element is addressed by
40
+ index (`point[1]`, was `point(item1)` or `point(y1)` for a named element). A `validate`
41
+ function may return `{ code, message, path, params }` of its own; its `path` (a key or an
42
+ array of keys) is relative to the field (`{ message, path: 'x' }` on `a` reports `a.x`; 1.x
43
+ ignored it).
44
+ - **Unknown keys are one issue per struct**: `{ code: 'unexpected', params: { keys } }` at the
45
+ path of the struct, rendered as `Field "" has unexpected keys: b, c` (was one
46
+ `Field "b" is not expected` per key), and `maxErrors` counts them as one.
47
+ `check(value, { unknown: 'ignore' })` accepts them, and `{ Form: { unknown: 'ignore' }, ... }`
48
+ makes that the default of the schema.
49
+ - **A type failure cancels the rules and `validate` of the field.** A field is checked in the
50
+ order type, rules, `validate`, each step only when the one before it passed; 1.x reported
51
+ `not of expected type: string`, the `length` message and the validator's message together.
52
+ The schema-level `validate` runs after the fields and only when every field passed (it used
53
+ to run first, and always).
54
+ - **`new ValidationResult(path)` → `new ValidationResult(options?)`** (`{ root, messages }`). A
55
+ result a `validate` function returns is relative to its field, so build it with no arguments
56
+ and `add` messages. `ValidationResult.format` is gone;
57
+ `ValidationResult.issuesOf(error, path?, code?)` takes the path as keys.
58
+ - **Cycle detection lives at references.** A value that refers back to itself is reported as
59
+ `circular` where a reference (`'Category'`, `{ many }`) meets it again, as before; a schema
60
+ without references cannot recurse, so such a value is walked as far as the schema goes and
61
+ reported for what it is (unexpected keys, wrong types, or nothing) instead of as `circular`.
62
+ - **The tuple length message** is `exceeds the maximum length` with `params: { max, actual }`
63
+ (was `value length is more than expected in tuple`). The wording of every other message is
64
+ unchanged.
65
+ - **Warnings carry a code**: `Warning [missing-reference]: "Customer" referenced by "Order" is
66
+ not found` (was `Warning: "Customer" ...`), `Warning [recursive-reference]: ...`, and the new
67
+ lint adds `unknown-option`, `unbounded-pattern` and `missing-index-field` to `model.warnings`,
68
+ which is computed on first use.
69
+ - **`field.check(value, context, key)`** is the compiled check of a field and records into the
70
+ context of a check; call `schema.check`. `compile` joins the reserved keys of a field
71
+ definition (`ERR_RESERVED_KEY`).
72
+
73
+ **The schema language**
74
+
75
+ - **The first key of an object decides what it is.** The long form is read only when `type` is
76
+ the first key; a capitalized first key is a kind, a type name is that type's shorthand, and
77
+ any other first key is a nested struct. `{ name: 'string', type: 'string' }` is a struct with
78
+ two fields (1.x read it as a string); `{ required: false, type: 'string' }` throws
79
+ `ERR_INVALID_DEFINITION`. A struct whose first field is called `type`, or named like a type
80
+ (`date`, `null`, `any`, `unknown`, `integer` and `union` are type names now), needs a kind
81
+ (`{ Struct: {}, ... }`) or the `schema` shorthand; `schema.warnings` reports the options such
82
+ a struct would otherwise leave on the type.
83
+ - **`length` on a number is an error.** `number`, `bigint` and the new `integer` are bounded by
84
+ `min` and `max`: `{ type: 'number', length: [18, 120] }` becomes
85
+ `{ type: 'integer', min: 18, max: 120 }`. A `length` there throws `ERR_INVALID_RULE` with
86
+ that hint, and a failed bound is a `range` issue (`is greater than 120`), not `length`
87
+ (`exceeds the maximum length`). Every type lists the rules it accepts, so `min` on a string
88
+ or `length` on a boolean throws too; a custom type opts in with `rules: [...]`, and an alias
89
+ takes the rules of its base. A `length` whose `min` is above its `max` throws
90
+ `ERR_INVALID_LENGTH` (1.x accepted it).
91
+ - **A reference follows the kind of its target.** A reference to a stored kind (`Entity`,
92
+ `Registry`, ...) validates as an id (`employer: 'c1'`, `addresses: ['a1']`) and a reference
93
+ to a memory kind (`Struct`, `Form`, ...) as the record; 1.x always expected the record and
94
+ rejected an id as `not of expected type: object`. Validate a whole graph with
95
+ `check(value, { references: 'embed' })`, rows with `{ references: 'id' }`, or fix one field
96
+ with `embed: true`/`false`. An id never recurses, so a cyclic value through stored kinds is a
97
+ type error, not `circular`. The generated TypeScript follows the same rule, so a memory-kind
98
+ reference renders as its interface (`label: Tag`) instead of `labelId: string`.
99
+ - **`set` renders as `Set<T>`** in the generated TypeScript (it was `T[]` while `check`
100
+ accepted only a `Set`; `map` was already `Map<K, V>`).
101
+ - **The `relations` labels are swapped** to the conventional direction, read from the
102
+ referencing side: a `many` field is `'one-to-many'` and a single reference `'many-to-one'`.
103
+ - **A tuple element may be any definition**, not only a scalar. `[{ x: 'number' }]` is still a
104
+ named number (one key holding a type name); `[{ x: 'number', y: 'number' }]` is a struct
105
+ element (1.x read it as the named number `x` and reported `t(x0)`). `ERR_INVALID_TUPLE` is
106
+ for a definition that is not an array or an element that is a function.
107
+ - **A `Schema` instance as a field keeps its schema-level `validate`** in every form (bare,
108
+ `{ schema }`, the long form); 1.x dropped it, so a value that passed may now fail.
109
+
110
+ **Tooling**
111
+
112
+ - **The typings need TypeScript 5.0 or later.** `Schema` is generic over its definition
113
+ (`Schema<D>`, a const type parameter); `Schema` written on its own is still any schema, and
114
+ `Model.entities` is still a `Map<string, Schema>`.
115
+ - **The bundle is 12.6 KB min+gzip** (1.0 was under 8 KB), and CI gates at 13 KB.
116
+
117
+ ### Added
118
+
119
+ - **Static inference.** `Infer<D>` is the TypeScript type of a value `check` accepts for the
120
+ definition type `D`, over every form of the language: scalars (`integer` → `number`, `date`
121
+ → `Date`, `json` → `unknown`), `'?T'`, `'key?'` and `required: false` as optional properties
122
+ that accept `null`, `nullable: true` as `T | null`, the long form, `array`/`set`/`object`/`map`,
123
+ `enum` as a union of literals, tuples (named elements included), nested structs, `schema`
124
+ and `Schema` instances, `union`, and references as ids (`string`, `string[]`). A kind key,
125
+ index definitions, calculated fields and the schema-level options are not fields. `Schema` is
126
+ `Schema<D>` with a const type parameter, so `Schema.from({ ... })` keeps the literal types of
127
+ an inline definition and `InferSchema<typeof schema>` reads them; a definition declared apart
128
+ needs `as const`. `Infer<D, E>` takes an entity map and resolves a reference to a memory kind
129
+ (or `embed: true`) as the record and a projection as its parent's fields;
130
+ `InferEntity<E, 'Name'>` adds the id field of a stored kind. Custom types are declared for
131
+ inference through module augmentation of `CustomTypes`; an unknown name infers as `unknown`.
132
+ - **Standard Schema v1.** Every `Schema` exposes `schema['~standard']`
133
+ (`{ version: 1, vendor: 'alexify.metaschema', validate }`), the interface tRPC, TanStack Form,
134
+ Hono and the other consumers of [standardschema.dev](https://standardschema.dev) accept
135
+ without an adapter. `validate(value)` is `check(value)` read as the specification does:
136
+ `{ value }` (the same reference) or `{ issues }`, the issues of the result themselves
137
+ (`message` and an array `path`, plus `code` and `params`); the `libraryOptions` of a call are
138
+ the options of `check`. The accessor lives on the prototype and stays out of `toJSON` and
139
+ `Object.keys`. The typings declare it as `StandardProps<D>` (with `StandardResult<T>` and
140
+ `StandardOptions`), and a `Schema<D>` is a `StandardSchemaV1<Infer<D>, Infer<D>>` of
141
+ `@standard-schema/spec`, which the package does not depend on.
142
+ - **New built-in types.** `integer` (`Number.isInteger`), `date` (a `Date` with a valid time),
143
+ `null`, `any` and `unknown` (one type under two names, differing in the TypeScript they
144
+ render), and `union`: `{ union: ['string', 'number'] }` keeps the first branch that reports
145
+ nothing; `{ union: [...], discriminator: 'kind' }` picks the branch from an enum field in one
146
+ lookup, built when the schema is built, and reports an unknown value as one `union` issue at
147
+ the discriminator's path. A definition that cannot discriminate throws `ERR_INVALID_UNION`.
148
+ - **`nullable: true`**: a required key whose value may be `null`, apart from optional (`'?type'`,
149
+ `undefined` or `null`). It applies to any type, skips the rules and `validate` for `null`,
150
+ and renders as `T | null`.
151
+ - **`min` and `max`** for `number`, `integer` and `bigint`, as numbers or bigints compared
152
+ exactly (never through `Number`), with the `range` issue `{ min, max, actual }`.
153
+ - **`pattern`** for strings, a string or a `RegExp` compiled once with the `u` flag (and without
154
+ `g`/`y`), with the `pattern` issue `{ pattern }`; the validation guide has a section on ReDoS.
155
+ - **`unicode: true`** measures a string's `length` in code points instead of UTF-16 units.
156
+ - **The unknown-keys policy as metadata**: `{ Form: { unknown: 'ignore' }, ... }` is the default
157
+ of that schema's `check`; the option of a call still wins.
158
+ - **`check` options** `root`, `maxErrors`, `unknown` (`'reject'` | `'ignore'`), `references`
159
+ (`'kind'`, `'embed'`, `'id'`) and `messages`, validated when the check starts, and the field
160
+ option `embed` on a reference.
161
+ - **Issues with params.** `result.issues` is `{ code, path, message, params }`:
162
+ `type { expected, received }` (plus `key` for a wrong key type in an `object` or `map`),
163
+ `unexpected { keys }`, `enum { values }`, `length { min, max, actual }`,
164
+ `range { min, max, actual }`, `pattern { pattern }`, `union { expected, discriminator }`,
165
+ `reference { entity }`, `exception { error }`.
166
+ - **Locales.** Messages are rendered once, at the end of a check, from the code and params of
167
+ each issue through `options.messages`: a locale table (partial tables fall back to English) or
168
+ a function. English is built in, Ukrainian is exported as `@alexify/metaschema/locales/uk`
169
+ (and English as `@alexify/metaschema/locales/en`).
170
+ - **`result.summary`, `result.flatten()` and `result.tree()`** for CLIs and forms, and
171
+ `result.errors` as a lazy view rendered on first use.
172
+ - **Definition lint.** `schema.warnings` reports an option the field's type does not read
173
+ (`unknown-option`; `default`, `unique`, `index`, `primary`, `title`, `description`, `examples`
174
+ and `deprecated` are known annotations), a `pattern` without `length.max`
175
+ (`unbounded-pattern`) and an index over a missing field (`missing-index-field`);
176
+ `model.warnings` adds `missing-reference`, `missing-type` and `recursive-reference`. Both are
177
+ computed on first use.
178
+ - **Definition error codes** `ERR_INVALID_RULE` and `ERR_INVALID_UNION`.
179
+ - **Types**: `Infer`, `InferSchema`, `InferEntity`, `CustomTypes`, `StandardProps`,
180
+ `StandardResult`, `StandardOptions`, `IssueParams`, `IssueOf<Code>`, `Locale`, `Messages`,
181
+ `ResultOptions`, `FlatIssues`, `IssueTree` and `CheckContext`; `ValidationIssue` is a union by
182
+ code; `FieldType.nullable` and `embed`, `Schema.unknown` and `warnings`,
183
+ `CheckOptions.references` and `KindMetadata.unknown`.
184
+ - **Benchmarks**: the four modes of the typescript-runtime-type-benchmarks suite (`parseSafe`,
185
+ `parseStrict`, `assertLoose`, `assertStrict`) over its object, flat and nested, next to the
186
+ `check`, `Schema.from` and `Model` scenarios.
187
+
188
+ ### Changed
189
+
190
+ - **Validation is compiled.** `createStruct` builds a frozen plan and a dictionary of known keys
191
+ and compiles the struct check as an index loop over the plan; every field's `check` is a
192
+ closure chosen when the field is built (one `typeof` for a scalar without rules, a `Set` for
193
+ an `enum` with more than eight values, `Map` and `Set` iterated directly, `object` through
194
+ `for...in`, a lookup plus cycle tracking for a reference), and `Object.hasOwn` is consulted
195
+ only for a required field set to `undefined` or a field named after a member of
196
+ `Object.prototype`. A check runs in a context of its own
197
+ (`{ issues, count, limit, path, seen, unknown, references, root, messages }`) instead of
198
+ module globals, so two checks can no longer interfere and a validator may run another check.
199
+ On the benchmark of the repository (Node 24, the same machine) `check` goes from 2.1 M to
200
+ 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
201
+ 0.33 M to 2.7 M; construction stays where it was. See
202
+ [Performance](https://metaschema.vercel.app/guide/performance).
203
+ - **Generated TypeScript** follows the language: `integer` → `number`, `date` → `Date`, `null`,
204
+ `any`, `unknown`, a `union` as `A | B`, a nullable field as `T | null`, a `set` as `Set<T>`, a
205
+ reference by the kind of its target (see Upgrading).
206
+ - **Construction** reads the first key of a definition once, re-parses a projection's fields
207
+ from their definitions so the copies belong to the projection, and lints on first use of
208
+ `warnings`.
209
+
210
+ ### Removed
211
+
212
+ - **The positional root path of `check`** and **`ValidationResult.format`** (see Upgrading).
213
+ - **`length` on `number` and `bigint`**, replaced by `min` and `max` (see Upgrading).
214
+ - **Module-level validation state.** Nothing in the package is global to a check any more; the
215
+ type registry is still process-wide, as before.
216
+
217
+ ### Fixed
218
+
219
+ - **A `Schema` instance used as a field lost its schema-level `validate`** (see Upgrading).
220
+ - **A `length` whose `min` is above its `max`**, which could never pass, is rejected when the
221
+ schema is built instead of failing every value.
222
+ - **A `bigint` bound is compared exactly.** `length` on a `bigint` went through `Number` and
223
+ lost precision past 2^53; `min` and `max` compare a bigint bound as a bigint.
224
+
225
+ ### Tooling
226
+
227
+ - `pnpm size --max-gzip 13` is the CI gate (the entries are 12.6 KB min+gzip).
228
+ - `pnpm bench` reads the clock once per hundred calls and calls `check` through a megamorphic
229
+ site, so it is measured as a callee instead of being inlined into the measuring loop;
230
+ `bench/baseline.json` is the snapshot of this branch.
231
+ - `@standard-schema/spec` is a devDependency, used only by `tests/types/standard.test-d.ts`.
232
+ - New test suites: `context`, `issues`, `result`, `check-options`, `syntax`, `numbers`,
233
+ `pattern`, `nullable`, `values`, `union`, `references`, `lint`, `standard`, and
234
+ `tests/types/infer.test-d.ts`, which also compiles the examples of the TypeScript guide.
235
+
236
+ ## [1.0.0] - 2026-10-09
237
+
238
+ The first release of `@alexify/metaschema`. It is a fork of
239
+ [`metaschema`](https://github.com/metarhia/metaschema) 2.2.2. The schema language and the
240
+ validation semantics are unchanged. The package around them now follows the other Alexis
241
+ libraries: zero runtime dependencies, one package for Node.js and browsers, and typings that match
242
+ the runtime.
243
+
244
+ ### Upgrading from metaschema 2.x
245
+
246
+ Replace `metaschema` with `@alexify/metaschema`, then follow
247
+ [Migrating from metarhia](https://metaschema.vercel.app/guide/migrating-from-metarhia). The
248
+ breaking changes are the removed loader functions, the renamed `detouch`, the `exports` map,
249
+ `SchemaDefinitionError` for every broken definition, and the corrected and more precise
250
+ validation messages listed under Changed and Fixed.
251
+
252
+ ### Added
253
+
254
+ - **`SchemaDefinitionError`.** Every broken definition throws this `TypeError` subclass with a
255
+ `code` (`ERR_UNKNOWN_TYPE`, `ERR_INVALID_DEFINITION`, `ERR_MISSING_SCHEMA`, `ERR_INVALID_ENUM`,
256
+ `ERR_INVALID_LENGTH`, `ERR_INVALID_TUPLE`, `ERR_INVALID_REFERENCE`, `ERR_RESERVED_KEY`,
257
+ `ERR_PROJECTION`, `ERR_INVALID_CUSTOM_TYPE`, `ERR_TYPE_REGISTERED`, `ERR_UNKNOWN_JS_TYPE`,
258
+ `ERR_INVALID_OPTIONS`) and the `schema` and `field` it was found in, and the message says
259
+ where: `Unknown type "strng" in "Order.total"`. Previously a model with many
260
+ entities threw a bare `Error: Unknown type strng` with no hint of the entity or field, and a
261
+ `null` field definition threw `Cannot read properties of null`.
262
+ - **Structured issues.** `result.issues` holds `{ code, path, message }` for every message, with
263
+ the codes `required`, `type`, `unexpected`, `enum`, `length`, `reference`, `circular`,
264
+ `exception` and `custom`, so a form, a logger or an i18n layer need not parse the text. A
265
+ `validate` function may return `{ code, message }` objects of its own.
266
+ - **`check(value, path, { maxErrors })`** stops collecting at that many messages and stops walking
267
+ fields, elements and records as soon as the limit is reached.
268
+ - **An isolated type registry per model.** `new Model(types, entities, database, { registry:
269
+ 'isolated' })` gives the model its own copy of the built-in types to register into, so two
270
+ models with conflicting custom types can live in one process. The default, `'shared'`, is the
271
+ process-wide registry as before.
272
+ - **Readable `console.log`.** A schema or a field printed with `util.inspect` shows its definition
273
+ (`Schema(User) { name: { required: true, type: 'string' } }`) instead of the whole graph with
274
+ `[Circular]` markers.
275
+ - **`ValidationResult`** is exported, so a `validate` function can build the result it returns.
276
+ The typings describe it as the class it is, with `add` and `ValidationResult.format`, instead of
277
+ a two-property interface.
278
+ - **`Schema#detach`**, the correctly spelt replacement for `detouch`.
279
+ - **Exported types** for everything public: `Kind`, `KnownKind`, `Scope`, `Store`, `Allow`,
280
+ `Cardinality`, `Relation`, `Fields`, `FieldType`, `CalculatedField`, `TypeTable`,
281
+ `TypeConstructor`, `TypeEntry`, `KindMetadata`, `SchemaOptions`, `ModelOptions`,
282
+ `CheckOptions`, `Validator`, `ValidationReturn`, `ValidationIssue`, `IssueInput`, `IssueCode`
283
+ and `DefinitionErrorCode`.
284
+ - **Documentation site** at [metaschema.vercel.app](https://metaschema.vercel.app/).
285
+
286
+ ### Changed
287
+
288
+ - **Package name** is `@alexify/metaschema`, published from `Alexis-Technologies/metaschema`.
289
+ - **Browser entry.** `dist.js` is replaced by `browser.js`, which exports the same names as the
290
+ main entry. `saveTypes` lives in `src/runtime/node.js`, and its browser twin rejects. Both the
291
+ `browser` field and the `browser` export condition point bundlers to it.
292
+ - **ESM named imports** work: the root barrel lists every export by name, so
293
+ `import { Schema } from '@alexify/metaschema'` resolves.
294
+ - **`Model`** accepts any iterable of `[name, definition]` pairs, not only a `Map`.
295
+ - **Paths and coverage of messages.** An unexpected key inside a nested struct carries the parent
296
+ path (`Field "nested.field2" is not expected`, was `Field "field2"`); records of a `many`
297
+ reference carry their index (`Person.companies[1].name`, was `Person.companies.name`); every
298
+ element of a tuple and every record of a `many` reference is reported instead of only the
299
+ first; and a wrong key type in an `object` or `map` reads `Field "o" keys must be of type string`
300
+ (was `Field "o" In object "o": type of key must be a string`).
301
+ - **`model.dts` keeps the shape of every field.** Arrays and sets render as `T[]`, an `enum` as
302
+ a union of its values, `bigint` as `bigint`, a tuple as `[number, number]`, `object` as
303
+ `Record<K, V>`, `map` as `Map<K, V>`, a nested struct inline and `json` as `unknown`; before,
304
+ everything but `string`, `number` and `boolean` was rendered as `string`. References still
305
+ become ids and custom scalar types still render as `string`.
306
+ - **Validation is faster.** A field chooses its rule checks once when it is built instead of
307
+ scanning the rule table on every check, arrays are walked in place, and a schema caches the type
308
+ table of its namespaces: `check` runs about 1.7× faster on flat values and 1.5× on nested ones
309
+ than the 2.2.2 code on the same machine (`pnpm bench`).
310
+
311
+ ### Removed
312
+
313
+ - **Loading schemas from files and strings.** `createSchema`, `loadSchema`, `readDirectory` and
314
+ `loadModel` are gone, together with the `metavm` sandbox they ran schema sources in. Pass schema
315
+ objects to `Schema` and `Model` directly.
316
+ - **Runtime dependencies.** `metautil`, `metavm` and `metaskills` are no longer installed. The
317
+ `metautil` helpers metaschema uses are copied into `src/metautil.js`.
318
+ - **Deep imports.** The `exports` map exposes only the package root.
319
+ - **`Schema#detouch`.** It is renamed to `detach`, with no alias for the old spelling.
320
+
321
+ ### Fixed
322
+
323
+ - **Error messages.** Typos and grammar in validation messages are fixed, with no compatibility
324
+ for the old text:
325
+ - `Filed "..." is required` → `Field "..." is required`;
326
+ - `Filed "..." is not a object` (and `is not a map`) →
327
+ `Field "..." not of expected type: object` (and `map`), like every other type error;
328
+ - `more then expected in tuple` → `more than expected in tuple`.
329
+ - **Optional nested structs in collections.** A nested struct marked `required: false` (long form,
330
+ `{ type: 'schema', schema, required: false }`) was still required as an array, set, object or map
331
+ element, so `null` elements were rejected. It is now optional there too, like `{ array: '?string' }`.
332
+ Optional nested struct fields (`'key?'`, `required: false`) already worked and are unchanged.
333
+ - **Silent and misleading type registration.** `{ string: { js: 'number' } }` was ignored without
334
+ a word, and both an unknown alias (`{ js: 'strng' }`) and an alias of a custom type registered
335
+ earlier in the table failed with `Custom type must contain "construct" and "checkType" methods`.
336
+ Redefining a registered name now throws `ERR_TYPE_REGISTERED` (the same definition, or a
337
+ metadata-only entry, is still accepted, so one table can serve every model), an unknown `js`
338
+ throws `ERR_UNKNOWN_JS_TYPE`, and `js` may name any type registered earlier in the table.
339
+ - **Reserved keys in a field definition.** `{ type: 'string', constructor: 'x' }` silently
340
+ switched validation of that field off, `check: 'x'` broke `check` with
341
+ `type.check is not a function`, and a `__proto__` key (as `JSON.parse` produces) failed with
342
+ `typeFormatters[key] is not a function`. A key that names a method of the field (`check`,
343
+ `checkType`, `construct`, `isInstance`, `toJSON`, `constructor`, …) or `__proto__`/`prototype`
344
+ is now rejected when the schema is built (`ERR_RESERVED_KEY`).
345
+ - **A validator returning more than ~110,000 messages lost all of them.** `ValidationResult#add`
346
+ spread them into `push`, which throws past the engine's argument limit, and `check` reported a
347
+ single `validation failed RangeError` instead. Every message is kept.
348
+ - **`JSON.stringify` of a schema whose definition is a single type** (`Schema.from('string')`,
349
+ `Schema.from({ array: 'number' })`) threw `Schema cannot be serialized`. It serializes like a
350
+ field now, and `toString()` is `JSON.stringify(schema)`.
351
+ - **A `Schema` instance passed to `new Schema(name, instance, namespaces)` lost the namespaces**,
352
+ so a prebuilt schema given to a `Model` could not resolve its references through the model. The
353
+ instance is still returned as is, keeping its own name; the namespaces are attached, and a
354
+ different `name` is a definition error.
355
+ - **A huge input key made a huge message.** Key names taken from the value under check are
356
+ truncated to 100 characters in `is not expected` messages and nested paths.
357
+ - **Circular values.** A value that referred back to itself through a reference, a nested struct
358
+ or a collection was walked until the engine threw `RangeError`, reported as
359
+ `validation failed RangeError` at whatever depth the stack ran out, with a path thousands of
360
+ segments long. It is now reported where the cycle closes:
361
+ `Field "Category.parent" is a circular reference`.
362
+ - **Ordinary bad input reported as an internal error.** `null` for a required `object` field
363
+ produced `validation failed TypeError: Cannot convert undefined or null to object`, an array was
364
+ accepted as an `object`, and a number for a `many` reference produced
365
+ `validation failed TypeError: source is not iterable`. They are now type errors like any other:
366
+ `Field "o" not of expected type: object` and
367
+ `Field "Person.companies" not of expected type: array of Company`.
368
+ - **Broken definitions that only failed inside `check`.** `{ type: 'enum' }` without values
369
+ reported `validation failed TypeError: Cannot read properties of undefined` for every value;
370
+ `length: 'abc'` was silently ignored; `length: { max: 0 }` was ignored too because `0` is falsy;
371
+ `{ many: 5 }` was accepted; and a projection naming a field its parent does not have failed with
372
+ `Invalid definition: "undefined" of type undefined`. Each is now a `SchemaDefinitionError` when
373
+ the schema is built (`ERR_INVALID_ENUM`, `ERR_INVALID_LENGTH`, `ERR_INVALID_REFERENCE`,
374
+ `ERR_PROJECTION`), and `length: { max: 0 }` works.
375
+ - **Tuple fields in the short form were never required.** `point: ['number', 'number']` left
376
+ `required` undefined, so a missing `point` passed validation and `model.dts` rendered it as
377
+ optional; only the long form `{ type: 'tuple', value: [...] }` was required. The short form is now
378
+ required by default like every other field, and `'point?': [...]` makes it optional.
379
+ - **Field names `check`, `name`, `constructor` and other `Object.prototype` names.** A struct was a
380
+ class instance used as a dictionary, so a field named `check` replaced the method
381
+ (`this.fields.check is not a function`), a field named `name` corrupted the message for a value
382
+ that is not an object (`Field "[object Object]"`), and input keys such as `constructor`,
383
+ `__proto__` or `check` were silently accepted instead of reported as not expected. Fields now
384
+ live in a null-prototype dictionary. A value that is not an object is reported as
385
+ `Field "<path>" not of expected type: object`, like every other type error (was
386
+ `Value of "<path>" must be an object`).
387
+ - **Bundled and minified builds.** Schemas, fields and validation results were recognised by
388
+ `constructor.name`. esbuild emits `class _Schema` for the self-referencing `Schema` class, so in
389
+ any esbuild bundle (Vite, tsup, serverless builds) a `Schema` instance used as a field, or passed
390
+ to `new Schema`, failed with `Unknown type struct`; with minification the `Type` class was
391
+ renamed too and `check` accepted every value. Identity is now a global symbol brand
392
+ (`Symbol.for`), which also recognises results from a second copy of the package.
393
+ `tests/unit/bundle.test.js` validates through esbuild bundles of both entries, minified and not.
394
+ - **Reference cycles that do not pass through the first entity** (`A → B → C → B`) made `new Model`
395
+ fail with `RangeError: Maximum call stack size exceeded`, and whether a cycle crashed or produced a
396
+ warning depended on the order of the entities. Every cycle is now a warning, in the same format
397
+ as a missing reference: `Warning: "C" depends on "B" recursively` (was
398
+ `Recursive dependency: C.B`).
399
+ `Model#preprocess` and `Model#reorderEntity` are constructor internals and are no longer public.
400
+ - **A schema type without a definition** (`data: 'schema'`, `{ type: 'schema' }`, or an alias
401
+ such as `{ js: 'schema' }` used as `'address'`) failed with
402
+ `Cannot convert undefined or null to object`, and a non-object `schema` with an unrelated
403
+ `Unknown type` error. It now throws `SchemaDefinitionError` (`ERR_MISSING_SCHEMA`):
404
+ `Type "address" needs a schema definition: { type: 'address', schema: { ... } } in "Order.delivery"`.
405
+ - **Typings.** `index.d.ts` matches the runtime:
406
+ - the static `Schema.KIND`, `KIND_STORED`, `KIND_MEMORY`, `SCOPE`, `STORE` and `ALLOW` fields,
407
+ which never existed, are removed;
408
+ - `'system'` is removed from `Scope`;
409
+ - `Schema.from` accepts strings and arrays;
410
+ - `validate`, `findReference` and `Model#database` may be `null`;
411
+ - `fields`, `indexes`, `custom`, the type table and the entries passed to `Model` are typed
412
+ (`Fields`, `FieldType`, `TypeTable`, `TypeEntry`, ...) instead of `object` and `Function`;
413
+ - `Cardinality` is the two values the runtime produces, and `Kind` admits a custom kind.
414
+
415
+ ### Tooling
416
+
417
+ - pnpm, oxlint and oxfmt replace npm, ESLint and Prettier; c8, tsd and TypeScript (7.x) check
418
+ coverage and the typings. oxlint runs with its `correctness` and `suspicious` categories on.
419
+ - Sources move to `src/`, tests to `tests/unit/` (with `tests/types/` for tsd), fixtures to
420
+ `tests/fixtures/`.
421
+ - c8 coverage gate, tsd type tests, an export-parity test and a platform test that keeps Node
422
+ builtins out of everything but `src/runtime/node.js`.
423
+ - CI runs lint, types, tests on Node 18–24 (Ubuntu) and 22–24 (Windows), coverage and the docs
424
+ build, with a single `ci-success` check.
425
+ - `pnpm size` reports bundle sizes and, with `--max-gzip <KB>`, fails over budget (CI gates at
426
+ 8 KB; the bundles are under 8 KB). `pnpm bench` runs the benchmarks and, with `--json`, `--save`
427
+ and `--compare`, snapshots them to `bench/baseline.json` and reports the change. The coverage
428
+ table appears in the CI job summary.
429
+
430
+ ## Upstream history (metarhia/metaschema)
431
+
432
+ Releases of [`metaschema`](https://github.com/metarhia/metaschema) before the fork, kept as
433
+ published.
434
+
435
+ ### [metaschema 2.2.2][upstream-2.2.2] - 2025-05-24
436
+
437
+ - Add node.js 23 and 24 to CI
438
+ - Update dependencies
439
+
440
+ ### [metaschema 2.2.1][upstream-2.2.1] - 2024-08-31
441
+
442
+ - Update eslint to 9.x and prettier with configs
443
+ - Add node.js 22 to CI
444
+
445
+ ### [metaschema 2.2.0][upstream-2.2.0] - 2024-03-27
446
+
447
+ - Add browser support
448
+ - Rename `SchemaError` to `ValidationResult`
449
+ - Update dependencies
450
+
451
+ ### [metaschema 2.1.5][upstream-2.1.5] - 2023-07-15
452
+
453
+ - Fix: remove debug output
454
+ - Update dependencies
455
+ - Package maintenance: AUTHORS, .prettierignore
456
+
457
+ ### [metaschema 2.1.4][upstream-2.1.4] - 2023-05-01
458
+
459
+ - Drop node.js 14 support, add node.js 20
460
+ - Convert package_lock.json to lockfileVersion 2
461
+ - Update dependencies
462
+
463
+ ### [metaschema 2.1.3][upstream-2.1.3] - 2023-03-13
464
+
465
+ - Add `BigInt` to known glabals
466
+ - Add `node:` prefix in require for built-in modules
467
+
468
+ ### [metaschema 2.1.2][upstream-2.1.2] - 2023-02-18
469
+
470
+ - Update dependencies and security issues
471
+ - Package maintenance: json autoformatting, CI, license
472
+
473
+ ### [metaschema 2.1.1][upstream-2.1.1] - 2022-08-16
474
+
475
+ - Non required fields can be `null`
476
+ - Using optional chaining operator
477
+
478
+ ### [metaschema 2.1.0][upstream-2.1.0] - 2022-07-11
479
+
480
+ - Test fixups from <https://github.com/metarhia/metaschema/pull/420/commits/5732714114a14e0f8a71617c779d73eb4b345fb4>
481
+ - toJSON and toString methods implementation for Schema
482
+
483
+ ### [metaschema 2.0.2][upstream-2.0.2] - 2022-06-25
484
+
485
+ - Hotfix: added missed exports to metaschema.js
486
+
487
+ ### [metaschema 2.0.1][upstream-2.0.1] - 2022-06-24
488
+
489
+ - json type for any plain javascript object
490
+ - fix names issue while using built-in prototypes for custom types
491
+
492
+ ### [metaschema 2.0.0][upstream-2.0.0] - 2022-06-22
493
+
494
+ - Struct implementation
495
+ - Refactoring and code quality improvement
496
+ - Metadata handled separetely
497
+ - Error handling improved now errors are chained
498
+ - Custom Kinds support implemented with custom metadata
499
+ `{ CustomKind: { customMetadata: 'meta' } }`
500
+ - Update dependencies: "eslint", "eslint-config-metarhia"
501
+ - Custom types syntax changed. No more hardcoded `pg`.
502
+ Now you must use `metadata` which is static property of Type constructor.
503
+ - Nested schema with relations bugfix
504
+ - Tuple type implementation
505
+ - Properly report error if trying to use `field: 'type'` shorthand for
506
+ `'enum', 'array', 'set', 'map', 'object'` types
507
+ - Rewrite schemas and implement custom types
508
+ - elegant syntax/format for custom types and internal types
509
+ - custom types support
510
+ - preprocessor to reduce Schema preprocess complexity
511
+ - any kind of nested arrays, array of references https://github.com/metarhia/metaschema/issues/378
512
+ - nested schemas with Schema instances support
513
+ - any level of complex nested types support
514
+ - custom validate for field
515
+ - changed validate for schema, simplified for user
516
+ - all user's validate functions support 4 types of syntax: boolean return, throw Error, error message as string return and array of error messages
517
+ - reserved words permitted in schema if kind provided
518
+ - function fields stored in schema
519
+ - shorthand required key for collections support `{ 'array?': 'string' }`
520
+ - many relation now checks in runtime
521
+ - model now loads projections at the end, to fix bug
522
+ - schema kinds moved to separate file and kinds now have logic to remove hardcoded projection from Schema
523
+ - ts interfaces from schema now have relation ids as well
524
+ - deps update metautil
525
+ - nested object support https://github.com/metarhia/metaschema/issues/395
526
+ - syntax for validate function changed
527
+ - Model no more require metavm for browser compatibility: need `impress` update
528
+ - loadModel moved to loader: need `impress` update
529
+ - Model no more writes d.ts file to disk moved to loader as well: need `metasql` update
530
+ - syntax for pg types changed a bit, no more not-working types: need `metasql` update
531
+
532
+ ### [metaschema 1.4.1][upstream-1.4.1] - 2022-03-17
533
+
534
+ - Skip calculated fields in schemas
535
+ - Update dependencies
536
+ - Fix tests after update metatests to 0.8.1
537
+
538
+ ### [metaschema 1.4.0][upstream-1.4.0] - 2022-02-23
539
+
540
+ - Fix nullable field long-form
541
+ - Optional for nested structures
542
+ - Shorthand for optional nested structure
543
+ - Fix paths in validation errors
544
+ - Unify nested schema fields to
545
+ `{ type: 'schema', schema: Schema, /* other fields */ }`
546
+ - Support Schema#validate function
547
+
548
+ ### [metaschema 1.3.4][upstream-1.3.4] - 2021-09-10
549
+
550
+ - Show path to the field in warnings
551
+ - Remove spread operator in `toLongForm`
552
+ - Update dependencies
553
+
554
+ ### [metaschema 1.3.3][upstream-1.3.3] - 2021-07-19
555
+
556
+ - Improve code style
557
+ - Move types to package root
558
+ - Package maintenance: update dependencies, update engines, security
559
+
560
+ ### [metaschema 1.3.2][upstream-1.3.2] - 2021-06-30
561
+
562
+ - Schema projection
563
+ - Schema.prototype.relations: Set<{ to: string, type: string }>
564
+
565
+ ### [metaschema 1.3.1][upstream-1.3.1] - 2021-06-26
566
+
567
+ - Add namespaces to Schema.from factory
568
+ - Fix "not expected" warning
569
+
570
+ ### [metaschema 1.3.0][upstream-1.3.0] - 2021-06-25
571
+
572
+ - Check schemas with references to schemas from attached models
573
+ - Add Schema.prototype.namespaces and attach/detouch methods to add/remove
574
+ - Add types to Schema.prototype.references (in addition to entities)
575
+ - Move Model.prototype.checkReferences to Schema.prototype.checkConsistency
576
+ - Fix lost json subfields checking
577
+ - Improve Schema kinds
578
+
579
+ ### [metaschema 1.2.3][upstream-1.2.3] - 2021-05-22
580
+
581
+ - Restrict 'type' property in db schemas
582
+ - Simplify schema examples
583
+
584
+ ### [metaschema 1.2.2][upstream-1.2.2] - 2021-05-17
585
+
586
+ - Fix unique alternative keys
587
+
588
+ ### [metaschema 1.2.1][upstream-1.2.1] - 2021-05-15
589
+
590
+ - Move Identifier ahead of entity order
591
+ - Collect all references: Schema.prototype.references
592
+ - Improve check references for Model
593
+ - Reorder entities including many-to-many references
594
+ - Fix recursion detection on many-to-many and parent
595
+
596
+ ### [metaschema 1.2.0][upstream-1.2.0] - 2021-05-13
597
+
598
+ - Change Schema metadata `{ kind, scope, store, allow }`
599
+ - Update dependencies and fix security issue
600
+
601
+ ### [metaschema 1.1.2][upstream-1.1.2] - 2021-05-08
602
+
603
+ - Shorthand for optional (not required) fields
604
+ - Nested schema of json type (for pg json fields)
605
+
606
+ ### [metaschema 1.1.1][upstream-1.1.1] - 2021-05-07
607
+
608
+ - Support nested schemas for Model class
609
+
610
+ ### [metaschema 1.1.0][upstream-1.1.0] - 2021-05-06
611
+
612
+ - Move Schema.prototype.toInterface from metasql
613
+ - Move Directory loader from metasql
614
+ - Move Model class from metasql (previous name DomainModel)
615
+ - Move Reference checker from metasql
616
+ - Move Entity reordering algorithm from metasql
617
+ - Improve Model and Schema classes
618
+
619
+ ### [metaschema 1.0.3][upstream-1.0.3] - 2021-04-13
620
+
621
+ - Add .d.ts typings
622
+ - Update metavm (added typings)
623
+
624
+ ### [metaschema 1.0.2][upstream-1.0.2] - 2021-03-11
625
+
626
+ - Support enumerated type
627
+ - Fix single value validation
628
+ - Fix bugs in not required fields checking
629
+
630
+ ### [metaschema 1.0.1][upstream-1.0.1] - 2021-03-06
631
+
632
+ - Fix database schema: index detection
633
+ - Add loaders from string and file
634
+
635
+ ### [metaschema 1.0.0][upstream-1.0.0] - 2021-03-02
636
+
637
+ - See specs: https://github.com/metarhia/Contracts
638
+ - Moved implementation from impress
639
+ - Implement schemas for structures and scalars
640
+ - Schema field shorthand
641
+ - Schema for collections: array, object, set, map
642
+ - Schema custom validation method
643
+
644
+ ### [metaschema 0.x][upstream-0.x] - First generation of metaschema
645
+
646
+ [unreleased]: https://github.com/Alexis-Technologies/metaschema/compare/v2.0.0...HEAD
647
+ [2.0.0]: https://github.com/Alexis-Technologies/metaschema/compare/v1.0.0...v2.0.0
648
+ [1.0.0]: https://github.com/Alexis-Technologies/metaschema/releases/tag/v1.0.0
649
+ [upstream-2.2.2]: https://github.com/metarhia/metaschema/compare/v2.2.1...v2.2.2
650
+ [upstream-2.2.1]: https://github.com/metarhia/metaschema/compare/v2.2.0...v2.2.1
651
+ [upstream-2.2.0]: https://github.com/metarhia/metaschema/compare/v2.1.5...v2.2.0
652
+ [upstream-2.1.5]: https://github.com/metarhia/metaschema/compare/v2.1.4...v2.1.5
653
+ [upstream-2.1.4]: https://github.com/metarhia/metaschema/compare/v2.1.3...v2.1.4
654
+ [upstream-2.1.3]: https://github.com/metarhia/metaschema/compare/v2.1.2...v2.1.3
655
+ [upstream-2.1.2]: https://github.com/metarhia/metaschema/compare/v2.1.1...v2.1.2
656
+ [upstream-2.1.1]: https://github.com/metarhia/metaschema/compare/v2.1.0...v2.1.1
657
+ [upstream-2.1.0]: https://github.com/metarhia/metaschema/compare/v2.0.2...v2.1.0
658
+ [upstream-2.0.2]: https://github.com/metarhia/metaschema/compare/v2.0.1...v2.0.2
659
+ [upstream-2.0.1]: https://github.com/metarhia/metaschema/compare/v2.0.0...v2.0.1
660
+ [upstream-2.0.0]: https://github.com/metarhia/metaschema/compare/v1.4.1...v2.0.0
661
+ [upstream-1.4.1]: https://github.com/metarhia/metaschema/compare/v1.4.0...v1.4.1
662
+ [upstream-1.4.0]: https://github.com/metarhia/metaschema/compare/v1.3.4...v1.4.0
663
+ [upstream-1.3.4]: https://github.com/metarhia/metaschema/compare/v1.3.3...v1.3.4
664
+ [upstream-1.3.3]: https://github.com/metarhia/metaschema/compare/v1.3.2...v1.3.3
665
+ [upstream-1.3.2]: https://github.com/metarhia/metaschema/compare/v1.3.1...v1.3.2
666
+ [upstream-1.3.1]: https://github.com/metarhia/metaschema/compare/v1.3.0...v1.3.1
667
+ [upstream-1.3.0]: https://github.com/metarhia/metaschema/compare/v1.2.3...v1.3.0
668
+ [upstream-1.2.3]: https://github.com/metarhia/metaschema/compare/v1.2.2...v1.2.3
669
+ [upstream-1.2.2]: https://github.com/metarhia/metaschema/compare/v1.2.1...v1.2.2
670
+ [upstream-1.2.1]: https://github.com/metarhia/metaschema/compare/v1.2.0...v1.2.1
671
+ [upstream-1.2.0]: https://github.com/metarhia/metaschema/compare/v1.1.2...v1.2.0
672
+ [upstream-1.1.2]: https://github.com/metarhia/metaschema/compare/v1.1.1...v1.1.2
673
+ [upstream-1.1.1]: https://github.com/metarhia/metaschema/compare/v1.1.0...v1.1.1
674
+ [upstream-1.1.0]: https://github.com/metarhia/metaschema/compare/v1.0.3...v1.1.0
675
+ [upstream-1.0.3]: https://github.com/metarhia/metaschema/compare/v1.0.2...v1.0.3
676
+ [upstream-1.0.2]: https://github.com/metarhia/metaschema/compare/v1.0.1...v1.0.2
677
+ [upstream-1.0.1]: https://github.com/metarhia/metaschema/compare/v1.0.0...v1.0.1
678
+ [upstream-1.0.0]: https://github.com/metarhia/metaschema/compare/v0.x...v1.0.0
679
+ [upstream-0.x]: https://github.com/metarhia/metaschema/releases/tag/v0.x