@alexify/metaschema 2.0.0 → 3.1.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 (51) hide show
  1. package/CHANGELOG.md +443 -1
  2. package/README.md +124 -12
  3. package/SECURITY.md +27 -8
  4. package/index.d.ts +537 -84
  5. package/package.json +25 -6
  6. package/src/codec.js +544 -0
  7. package/src/compile/code.js +92 -0
  8. package/src/compile/emit.js +540 -0
  9. package/src/compile/index.d.ts +38 -0
  10. package/src/compile/index.js +176 -0
  11. package/src/context.js +68 -19
  12. package/src/errors.js +19 -1
  13. package/src/generators/fromjsonschema.js +520 -0
  14. package/src/generators/index.d.ts +46 -0
  15. package/src/generators/index.js +95 -0
  16. package/src/generators/jsonschema.js +535 -0
  17. package/src/generators/typescript.js +237 -0
  18. package/src/index.js +0 -2
  19. package/src/issues.js +117 -22
  20. package/src/kinds.js +9 -12
  21. package/src/lint.js +31 -14
  22. package/src/locales/en.js +10 -2
  23. package/src/locales/uk.js +7 -2
  24. package/src/metadata.js +41 -44
  25. package/src/metautil.js +8 -1
  26. package/src/model/data.js +122 -0
  27. package/src/model/diff.js +438 -0
  28. package/src/model/index.d.ts +56 -0
  29. package/src/model/index.js +42 -0
  30. package/src/model/merge.js +254 -0
  31. package/src/model/pattern.js +322 -0
  32. package/src/model/restore.js +226 -0
  33. package/src/model/sample.js +394 -0
  34. package/src/model.js +18 -15
  35. package/src/preprocessor.js +9 -11
  36. package/src/prototypes/abstract.js +14 -1
  37. package/src/prototypes/collections.js +20 -3
  38. package/src/prototypes/reference.js +17 -3
  39. package/src/prototypes/scalars.js +1 -3
  40. package/src/prototypes/schema.js +15 -2
  41. package/src/prototypes/tuple.js +14 -9
  42. package/src/prototypes/union.js +57 -18
  43. package/src/result.js +5 -14
  44. package/src/rules.js +55 -26
  45. package/src/runtime/browser.js +2 -2
  46. package/src/runtime/node.js +4 -2
  47. package/src/schema.js +129 -101
  48. package/src/snapshot.js +111 -0
  49. package/src/struct.js +80 -23
  50. package/src/types.js +5 -11
  51. package/src/util.js +39 -0
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,37 @@ 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
+ - **The model as data.** `model.toJSON()` is a snapshot other programs read the model through
83
+ (a migration tool, an introspecting service, a committed baseline), and
84
+ `@alexify/metaschema/model` tells two versions apart (`diff`), classifies the change by the
85
+ Confluent rules (`compatibility`), draws a value every schema accepts (`sample`) and unifies
86
+ two schemas (`merge`); `aliases` and `deprecated` let a model carry its history, and
87
+ `fromJSONSchema` of the generators reads a JSON Schema document back.
88
+ - **Zero dependencies, 17.2 KB min+gzip.** CommonJS with ESM named imports, no build step,
89
+ one package for Node.js and browsers; the generators add 7.1 KB, the JIT backend 4.0 KB and
90
+ the model tools 9.5 KB where they are imported.
65
91
 
66
92
  ## Installation
67
93
 
@@ -131,7 +157,9 @@ model.order; // Set { 'Address', 'Company', 'User' }
131
157
  model.warnings; // [] (lint and consistency warnings, `Warning [code]: text`, end up here)
132
158
  model.entities.get('User').check({ login: 'ab', company: 'c1', active: true }).errors;
133
159
  // [ 'Field "User.login" value is too short' ]
134
- console.log(model.dts);
160
+
161
+ const { toTypeScript } = require('@alexify/metaschema/generators');
162
+ console.log(toTypeScript(model));
135
163
  ```
136
164
 
137
165
  ```ts
@@ -156,7 +184,10 @@ interface User {
156
184
  }
157
185
  ```
158
186
 
159
- `saveTypes(outputFile, model)` writes `model.dts` to a file. The first key of a definition sets
187
+ `saveTypes(outputFile, model, options?)` of the same subpath writes the interfaces to a file
188
+ (`{ named: true }` names enums and nested structs, and a field's `description` is its JSDoc); its
189
+ `register()` adds `model.dts`, `model.toTypeScript` and `schema.toInterface` as methods. The first
190
+ key of a definition sets
160
191
  its kind and metadata (`Entity`, `Registry`, `Dictionary`, `Journal`, `Details`, `Relation`,
161
192
  `View`, `Struct`, `Form`, `Projection`, or any custom kind). Stored kinds default to
162
193
  `scope: 'application'` and `store: 'persistent'`, and they get an id field; a reference to a
@@ -198,7 +229,7 @@ type User = InferSchema<typeof user>;
198
229
  Every form of the language is covered: optional and nullable fields, collections, enums,
199
230
  tuples, unions, nested structs, references (an id, or the record through an entity map with
200
231
  `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
232
+ augmentation of `CustomTypes`. A model renders its entities as interfaces with `toTypeScript`. See
202
233
  [TypeScript](https://metaschema.vercel.app/guide/typescript).
203
234
 
204
235
  A `Schema<D>` is also a `StandardSchemaV1<Infer<D>, Infer<D>>` of `@standard-schema/spec`:
@@ -206,14 +237,77 @@ A `Schema<D>` is also a `StandardSchemaV1<Infer<D>, Infer<D>>` of `@standard-sch
206
237
  `StandardOptions` beside it. See
207
238
  [Standard Schema](https://metaschema.vercel.app/guide/standard-schema).
208
239
 
240
+ ## JSON Schema
241
+
242
+ `toJSONSchema(schema, options)` of `@alexify/metaschema/generators` renders the rules of `check`
243
+ as a JSON Schema document, and `toJSONSchema(model, options)` every entity of a model as a
244
+ definition:
245
+
246
+ ```js
247
+ const { toJSONSchema } = require('@alexify/metaschema/generators');
248
+
249
+ toJSONSchema(user, { target: 'draft-07' });
250
+ // {
251
+ // $schema: 'http://json-schema.org/draft-07/schema#',
252
+ // type: 'object',
253
+ // properties: {
254
+ // name: { type: 'object', properties: { first: { type: 'string' }, last: { type: 'string' } }, required: ['first', 'last'], additionalProperties: false },
255
+ // email: { type: 'string', minLength: 5, maxLength: 64 },
256
+ // age: { type: ['number', 'null'] },
257
+ // roles: { type: 'array', items: { enum: ['admin', 'editor', 'viewer'] } }
258
+ // },
259
+ // required: ['name', 'email', 'roles'],
260
+ // additionalProperties: false
261
+ // }
262
+
263
+ toJSONSchema(answer, { profile: 'strict' }); // the dialect of OpenAI and Anthropic structured outputs
264
+ toJSONSchema(model, { target: 'mongodb' }); // one $jsonSchema validator per entity
265
+ ```
266
+
267
+ The targets are `draft-2020-12` (the default), `draft-07`, `openapi-3.0` and `mongodb`; an
268
+ optional field accepts `null`, a reference to a stored kind is its id and a reference to a memory
269
+ kind a `$ref`, `validate` functions are not exported, and a type with no form in the target
270
+ (`bigint`, a `Date` on the way out) throws unless the call says `unrepresentable: 'any'`. The
271
+ export is checked against ajv for every form of the language. `register()` of the subpath turns
272
+ the functions into methods (`schema.toJSONSchema`, `model.toJSONSchema`) and adds the Standard
273
+ JSON Schema converter to `schema['~standard']`. See
274
+ [JSON Schema](https://metaschema.vercel.app/guide/json-schema).
275
+
276
+ ## Compiled checks
277
+
278
+ `compile(schema)` of `@alexify/metaschema/compile` replaces the check of a schema, or of every
279
+ entity of a model, with one function generated from the same plan the closures walk and built
280
+ with `new Function`; `register()` does it for every schema built from then on. The issues are
281
+ the ones the closures record, only sooner: about three times faster on a flat struct, six on a
282
+ nested one. Where code generation from strings is not allowed (a Content Security Policy,
283
+ Cloudflare Workers, `node --disallow-code-generation-from-strings`) nothing changes: the
284
+ closures stay, silently unless `{ jit: true }` asks for an error.
285
+
286
+ ```js
287
+ const { compile, register, canEval } = require('@alexify/metaschema/compile');
288
+
289
+ compile(user); // { accelerated: true }: user.check runs generated code now
290
+ compile(model); // every entity; { accelerated: false } where there is no eval
291
+ register(); // every schema built from here on is compiled as it is built
292
+ canEval(); // whether this environment builds functions from source
293
+ ```
294
+
295
+ The generated source holds identifiers, numbers and JSON strings only; regular expressions, enum
296
+ sets, validate functions and nested schemas reach it through a scope, never through the source
297
+ text. See [The JIT backend](https://metaschema.vercel.app/guide/compile).
298
+
209
299
  ## Exports
210
300
 
211
301
  ```js
212
302
  const {
213
303
  KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW,
214
- getKindMetadata, saveTypes, Schema, Model, SchemaDefinitionError, ValidationResult,
304
+ getKindMetadata, Schema, Model, SchemaDefinitionError, ValidationResult,
215
305
  } = require('@alexify/metaschema');
216
306
 
307
+ const { toJSONSchema, toTypeScript, saveTypes, fromJSONSchema, register } = require('@alexify/metaschema/generators');
308
+ const { compile, canEval } = require('@alexify/metaschema/compile'); // and its own register()
309
+ const { fromJSON, diff, compatibility, sample, merge } = require('@alexify/metaschema/model'); // and its own register()
310
+
217
311
  const en = require('@alexify/metaschema/locales/en'); // the built-in messages
218
312
  const uk = require('@alexify/metaschema/locales/uk'); // schema.check(value, { messages: uk })
219
313
  ```
@@ -223,12 +317,30 @@ import { Schema, Model } from '@alexify/metaschema';
223
317
  import type { Infer, InferSchema, InferEntity, CustomTypes, ValidationIssue } from '@alexify/metaschema';
224
318
  ```
225
319
 
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
320
+ In the browser every export works the same, except `saveTypes` of the generators, which rejects
321
+ because there is no file system, and `compile`, which keeps the closures where a Content
322
+ Security Policy forbids `new Function`. The [API reference](https://metaschema.vercel.app/api/exports) lists every member
228
323
  and every exported type.
229
324
 
230
325
  ## Migrating
231
326
 
327
+ ### From 2.x
328
+
329
+ 3.0 has two breaking changes. The generators left the core entry: `model.dts`,
330
+ `schema.toInterface()` and `saveTypes` are `toTypeScript(target, options)` and
331
+ `saveTypes(file, target, options)` of `@alexify/metaschema/generators`, whose `register()` puts
332
+ the methods back on the classes once per process. And `schema['~standard'].validate` is `parse`
333
+ rather than `check`: a consumer of Standard Schema gets the defaults filled in and the `parse`
334
+ functions applied, and a promise for a schema with an `async function`. The smaller changes: a
335
+ struct rejects an array, the synchronous `check` and `parse` throw `ERR_ASYNC_VALIDATOR` for a
336
+ promise, a graph deeper than 128 embedded records is a `depth` issue (`maxDepth` raises it),
337
+ `Infer` makes a defaulted key optional, and a few definitions that could never work throw when
338
+ the schema is built. Everything else is additive: `parse`, `serialize`, `checkAsync` and
339
+ `parseAsync`, the JSON Schema export, the JIT backend of `@alexify/metaschema/compile`, JSDoc
340
+ and named types. The step-by-step guide with before-and-after examples is
341
+ [Migrating from 2.x](https://metaschema.vercel.app/guide/migrating-from-2); the full list is
342
+ under "Upgrading from 2.0" in the [CHANGELOG](./CHANGELOG.md).
343
+
232
344
  ### From 1.x
233
345
 
234
346
  2.0 changes the shape of a result (`issue.path` is an array of keys, `issue.message` has no
@@ -259,7 +371,7 @@ the same schema language. What changed in 1.0:
259
371
  - **`browser.js`** replaces `dist.js`, and an `exports` map closes deep imports.
260
372
 
261
373
  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.
374
+ and the 2.0 and 3.0 changes above apply on top of it.
263
375
 
264
376
  ## Changelog
265
377
 
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