@alexify/metaschema 3.1.0 → 3.2.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/SECURITY.md CHANGED
@@ -55,13 +55,32 @@ Some things work as intended and are not vulnerabilities:
55
55
  check the generator cannot build is reported (`compile().error`, `register({ onFallback })`),
56
56
  never installed. The core entry never calls `new Function`.
57
57
  - **Input shape is checked strictly.** Every key that is not in the schema is reported as
58
- unexpected (`has unexpected keys: ...`), including `constructor`, `__proto__` and `toString`,
59
- unless the schema or the call says `unknown: 'ignore'`. Fields live in a
60
- null-prototype dictionary, so nothing on `Object.prototype` is ever read as a field, and
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.
58
+ unexpected (`has unexpected keys: ...`, the first ten of them), including `constructor`,
59
+ `__proto__` and `toString`, unless the schema or the call says `unknown: 'ignore'`. Fields
60
+ live in a null-prototype dictionary, so nothing on `Object.prototype` is ever read as a
61
+ field, and metaschema never writes to the value it checks. A built-in (`Map`, `Set`, `Date`)
62
+ is recognised by the name of its constructor and by its shape (an iterator, `getTime`), so a
63
+ value parsed from JSON that carries `{ "constructor": { "name": "Map" } }` is a type issue,
64
+ not a value the check iterates. A value with a `then` function is data: the passes of
65
+ `parse` and `parseAsync` await only the promises their own decoders make, never a thenable
66
+ of the value. A graph nested deeper than `maxDepth` embedded records (128 by default) is a
67
+ `depth` issue, not a stack overflow.
68
+ - **A `pattern` or a `format` is never run over a string longer than `length.max`.** The bound
69
+ is what keeps a backtracking expression fast, so give every pattern one (the lint says where
70
+ one is missing); the built-in formats are linear and anchored, a custom format's `test` is
71
+ the program's code, like a `validate` function. A pattern taken from a document given to
72
+ `fromJSONSchema` or a snapshot given to `fromJSON` runs as a regular expression in `check`
73
+ all the same: those documents are untrusted input for their structure (a keyword outside the
74
+ subset, a key named `__proto__`, a depth past the limit are errors, never a looser schema),
75
+ but a pattern in them is the importer's to review or to bound.
76
+ - **Samples are input.** `infer` of the model subpath walks the values it is given with a depth
77
+ limit, trusts no key (`__proto__`, `constructor` and the names of the methods of a field are
78
+ keys of the definition, written as own properties), and checks the definition it built
79
+ against every sample before it returns it. A key of a sample that reaches an error message
80
+ is truncated to 100 characters, as a key of a value under check is.
81
+ - **The error a stream ends with carries the record.** `ERR_INVALID_RECORD` of the stream
82
+ subpath has `record` and `result` on it, since the stream carries them no further; a logger
83
+ that serializes error objects writes the record.
65
84
  - **Validation errors are data.** `check` collects problems as issues (a code, a path and params,
66
85
  with a rendered message) instead of throwing on bad input. The messages contain field paths (which can include key names taken from the input,
67
86
  truncated to 100 characters) and, for `enum`, the allowed values; they never contain the
package/index.d.ts CHANGED
@@ -37,6 +37,7 @@ export type IssueCode =
37
37
  | 'length'
38
38
  | 'range'
39
39
  | 'pattern'
40
+ | 'format'
40
41
  | 'union'
41
42
  | 'reference'
42
43
  | 'circular'
@@ -56,6 +57,8 @@ export interface IssueParams {
56
57
  range: { min: number | bigint | undefined; max: number | bigint | undefined; actual: number | bigint };
57
58
  // The source of the pattern the string did not match.
58
59
  pattern: { pattern: string };
60
+ // The name of the format the string is not of.
61
+ format: { format: string };
59
62
  // No branch of a union matched: the branch names, or the discriminator
60
63
  // values when the union has a discriminator (the path then ends with it).
61
64
  union: { expected: unknown[]; discriminator: string | undefined };
@@ -192,6 +195,8 @@ export class ValidationResult {
192
195
  add(error: ValidationReturn, code?: IssueCode): this;
193
196
  flatten(): FlatIssues;
194
197
  tree(): IssueTree;
198
+ // The result as data: what JSON.stringify(result) writes.
199
+ toJSON(): { valid: boolean; issues: ValidationIssue[] };
195
200
  static issuesOf(error: ValidationReturn, path?: PropertyKey[], code?: IssueCode): ValidationIssue[];
196
201
  static isInstance(error: unknown): boolean;
197
202
  }
@@ -220,6 +225,9 @@ export interface CheckContext {
220
225
  async: unknown[] | null;
221
226
  // The context parse tries the branches of a plain union in; null in a check.
222
227
  scratch: CheckContext | null;
228
+ // Whether the check read a field from one of its aliases: the pass after it
229
+ // renames only when it did.
230
+ renamed: boolean;
223
231
  }
224
232
 
225
233
  // A validator may return a promise of its result to checkAsync and parseAsync;
@@ -346,6 +354,16 @@ export type DefinitionErrorCode =
346
354
  | 'ERR_SAMPLE_TYPE'
347
355
  // Thrown by `merge` of the same subpath for what no value can satisfy.
348
356
  | 'ERR_MERGE_CONFLICT'
357
+ // Thrown by `infer` of the same subpath: a sample nested deeper than
358
+ // `maxDepth`, and a definition that rejects a sample it was inferred from
359
+ // (a bug of the inference, to report).
360
+ | 'ERR_INFER_DEPTH'
361
+ | 'ERR_INFER_MISMATCH'
362
+ // Thrown by `register` of the `@alexify/metaschema/formats` subpath: an
363
+ // entry that is not a format, and a name registered again with another
364
+ // test.
365
+ | 'ERR_INVALID_FORMAT'
366
+ | 'ERR_FORMAT_REGISTERED'
349
367
  // Thrown by `compile` and `register` of the `@alexify/metaschema/compile`
350
368
  // subpath with `jit: true` where code generation from strings is not allowed.
351
369
  | 'ERR_NO_EVAL'
@@ -368,7 +386,7 @@ export class SchemaDefinitionError extends TypeError {
368
386
  // `ERR_INVALID_TARGET` is the same kind of error from a function of a subpath
369
387
  // given something other than what it takes (a Schema, a Model, a snapshot, a
370
388
  // list of changes).
371
- export type RuntimeErrorCode = 'ERR_ASYNC_VALIDATOR' | 'ERR_INVALID_TARGET';
389
+ export type RuntimeErrorCode = 'ERR_ASYNC_VALIDATOR' | 'ERR_INVALID_TARGET' | 'ERR_INVALID_RECORD';
372
390
 
373
391
  // ---------------------------------------------------------------------------
374
392
  // The snapshot: `model.toJSON()`, what JSON.stringify(model) writes. The
@@ -492,6 +510,36 @@ export interface MergeOptions {
492
510
  metadata?: Partial<KindMetadata>;
493
511
  }
494
512
 
513
+ // The options of `infer` of the `@alexify/metaschema/model` subpath (the
514
+ // name sits beside the type `Infer<D>`: the function reads samples, the type
515
+ // reads a definition).
516
+ export interface InferOptions {
517
+ // What comes back: the definition ('definition', the default), or a Schema
518
+ // built from it ('schema').
519
+ as?: 'definition' | 'schema';
520
+ // The name of the Schema, and of the error locations ('').
521
+ name?: string;
522
+ // The kind of a root that is a struct ('struct'); a stored kind adds its
523
+ // id field, which wins over an inferred field of that name.
524
+ kind?: string;
525
+ // The most distinct strings a place may hold to be an enum (8), each
526
+ // value seen twice on average over at least four samples; 0 or false never.
527
+ enum?: number | false;
528
+ // Whether whole numbers are `integer` (true) rather than `number`.
529
+ integer?: boolean;
530
+ // The distinct keys past which records of a place read as a dictionary
531
+ // (16) when every key is missing from some record and the values are of
532
+ // one kind; keys that are not names are a dictionary from one sample on;
533
+ // false keeps every record a struct.
534
+ map?: number | false;
535
+ // How deep a sample may nest (128, the most); past it `ERR_INFER_DEPTH`.
536
+ maxDepth?: number;
537
+ // Whether a place whose every string passes a registered format is that
538
+ // format (true); the formats subpath registers them, in the order `infer`
539
+ // tries them, and nothing is registered until its `register()` ran.
540
+ formats?: boolean;
541
+ }
542
+
495
543
  // The options of `sample` of the `@alexify/metaschema/model` subpath.
496
544
  export interface SampleOptions {
497
545
  // The seed of the generator (1): the same seed gives the same value.
@@ -507,6 +555,50 @@ export interface SampleOptions {
507
555
  maxDepth?: number;
508
556
  }
509
557
 
558
+ // The options of `checkEach` and `checkEachAsync` of the
559
+ // `@alexify/metaschema/stream` subpath: those of `check`, and how many invalid
560
+ // records end the iteration (no limit by default).
561
+ export interface EachOptions extends CheckOptions {
562
+ maxInvalid?: number;
563
+ }
564
+
565
+ // The options of `parseEach` and `parseEachAsync`: those of `parse`, and
566
+ // `maxInvalid`.
567
+ export interface ParseEachOptions extends ParseOptions {
568
+ maxInvalid?: number;
569
+ }
570
+
571
+ // The option of the async pair: how many records are in flight at once (1).
572
+ export interface EachAsyncOptions {
573
+ concurrency?: number;
574
+ }
575
+
576
+ // The options of `transform`: those of `parse` (or of `check`, with
577
+ // `mode: 'check'`), `maxInvalid`, and what the stream does with an invalid
578
+ // record.
579
+ export interface TransformOptions extends ParseOptions {
580
+ // What goes on down the stream: the parsed value ('parse', the default) or
581
+ // the record as it is ('check').
582
+ mode?: 'parse' | 'check';
583
+ // Whether the stream runs `parseAsync`/`checkAsync` (false).
584
+ async?: boolean;
585
+ // Told of every invalid record, which is then dropped; without it the
586
+ // stream ends with the error at the first one.
587
+ onInvalid?: (record: unknown, result: ValidationResult | ParseResult<unknown>, index: number) => void;
588
+ // After that many invalid records the stream ends with the error even with
589
+ // `onInvalid` (no limit by default).
590
+ maxInvalid?: number;
591
+ }
592
+
593
+ // What `checkEach` and its kin yield for a record: its position in the
594
+ // sequence, the record as the source gave it, and the result of `check` or
595
+ // `parse`.
596
+ export interface RecordEntry<T, R> {
597
+ index: number;
598
+ record: T;
599
+ result: R;
600
+ }
601
+
510
602
  export const KIND: Array<string>;
511
603
  export const KIND_STORED: Array<string>;
512
604
  export const KIND_MEMORY: Array<string>;
@@ -1060,7 +1152,7 @@ export type InferEntity<E, Name extends keyof E & string> = Simplify<
1060
1152
  // consumers of the specification accept it without an adapter. The shape is
1061
1153
  // written out here because this file cannot import `@standard-schema/spec` (a
1062
1154
  // devDependency); tests/types/standard.test-d.ts pins that a `Schema<D>` is a
1063
- // `StandardSchemaV1<Infer<D>, Infer<D>>` of that package.
1155
+ // `StandardSchemaV1<Infer<D>, InferOutput<D>>` of that package.
1064
1156
 
1065
1157
  // The vendor-specific options of a `validate` call are the options of `parse`.
1066
1158
  export interface StandardOptions {
@@ -1115,6 +1207,11 @@ export class Schema<const D extends string | object = string | object> {
1115
1207
  // of the `@alexify/metaschema/model` subpath has run; its `merge(a, b)` is
1116
1208
  // the same without it.
1117
1209
  static merge(a: Schema, b: Schema, options?: MergeOptions): Schema;
1210
+ // A definition (or a Schema) that accepts every sample: exists once
1211
+ // `register()` of the `@alexify/metaschema/model` subpath has run; its
1212
+ // `infer(samples, options)` is the same without it.
1213
+ static infer(samples: Iterable<unknown>, options: InferOptions & { as: 'schema' }): Schema;
1214
+ static infer(samples: Iterable<unknown>, options?: InferOptions): object | string;
1118
1215
 
1119
1216
  kind: Kind;
1120
1217
  scope: Scope;
@@ -1165,6 +1262,27 @@ export class Schema<const D extends string | object = string | object> {
1165
1262
  // of the `@alexify/metaschema/model` subpath has run; its `sample(schema,
1166
1263
  // options)` is the same without it.
1167
1264
  sample(options?: SampleOptions): Infer<D>;
1265
+ // The five members below exist once `register()` of the
1266
+ // `@alexify/metaschema/stream` subpath has run; its `checkEach(schema,
1267
+ // records, options)` and kin are the same without it.
1268
+ checkEach<T>(
1269
+ records: Iterable<T>,
1270
+ options?: EachOptions,
1271
+ ): Generator<RecordEntry<T, ValidationResult>, void, undefined>;
1272
+ parseEach<T>(
1273
+ records: Iterable<T>,
1274
+ options?: ParseEachOptions,
1275
+ ): Generator<RecordEntry<T, ParseResult<InferOutput<D>>>, void, undefined>;
1276
+ checkEachAsync<T>(
1277
+ records: Iterable<T> | AsyncIterable<T>,
1278
+ options?: EachOptions & EachAsyncOptions,
1279
+ ): AsyncGenerator<RecordEntry<T, ValidationResult>, void, undefined>;
1280
+ parseEachAsync<T>(
1281
+ records: Iterable<T> | AsyncIterable<T>,
1282
+ options?: ParseEachOptions & EachAsyncOptions,
1283
+ ): AsyncGenerator<RecordEntry<T, ParseResult<InferOutput<D>>>, void, undefined>;
1284
+ transform(options: TransformOptions & { mode: 'check' }): TransformStream<unknown, Infer<D>>;
1285
+ transform(options?: TransformOptions): TransformStream<unknown, InferOutput<D>>;
1168
1286
  // The two methods below exist once `register()` of the generators subpath
1169
1287
  // has run; the subpath's `toJSONSchema(schema)` and `toTypeScript(schema)`
1170
1288
  // are the same without it.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@alexify/metaschema",
3
- "version": "3.1.0",
4
- "description": "Zero-dependency metadata schema and interface definition language (IDL) for Node.js and browsers — data validation, domain models and TypeScript generation",
3
+ "version": "3.2.0",
4
+ "description": "Fast, zero-dependency metadata schema and interface definition language (IDL) for Node.js and browsers — validation and parsing with a JIT backend, domain models, TypeScript and JSON Schema",
5
5
  "license": "MIT",
6
6
  "author": "Alex Dolid <dolid.sasha@gmail.com>",
7
7
  "repository": {
@@ -46,6 +46,14 @@
46
46
  "./model": {
47
47
  "types": "./src/model/index.d.ts",
48
48
  "default": "./src/model/index.js"
49
+ },
50
+ "./stream": {
51
+ "types": "./src/stream/index.d.ts",
52
+ "default": "./src/stream/index.js"
53
+ },
54
+ "./formats": {
55
+ "types": "./src/formats/index.d.ts",
56
+ "default": "./src/formats/index.js"
49
57
  }
50
58
  },
51
59
  "directories": {
@@ -61,6 +69,7 @@
61
69
  "LICENSE",
62
70
  "SECURITY.md"
63
71
  ],
72
+ "sideEffects": false,
64
73
  "publishConfig": {
65
74
  "access": "public"
66
75
  },
@@ -76,6 +85,11 @@
76
85
  "dsl",
77
86
  "validation",
78
87
  "data-validation",
88
+ "fast",
89
+ "jit",
90
+ "parse",
91
+ "standard-schema",
92
+ "json-schema",
79
93
  "domain-model",
80
94
  "model",
81
95
  "typescript",
@@ -85,21 +99,35 @@
85
99
  "metarhia"
86
100
  ],
87
101
  "devDependencies": {
88
- "@sinclair/typebox": "^0.34.52",
102
+ "@braintree/sanitize-url": "^7.1.2",
89
103
  "@standard-schema/spec": "^1.1.0",
90
104
  "@vercel/analytics": "^2.0.1",
91
105
  "@vercel/speed-insights": "^2.0.0",
92
106
  "ajv": "^8.20.0",
93
107
  "ajv-formats": "^3.0.1",
108
+ "arktype": "^2.2.8",
94
109
  "c8": "^12.0.0",
110
+ "cytoscape": "^3.34.3",
111
+ "cytoscape-cose-bilkent": "^4.1.0",
112
+ "dayjs": "^1.11.23",
113
+ "debug": "^4.4.3",
114
+ "effect": "^4.0.3",
95
115
  "esbuild": "^0.28.2",
116
+ "fastdom": "1.0.12",
117
+ "joi": "^18.2.9",
118
+ "mermaid": "^11.17.2",
119
+ "metaschema": "2.2.2",
96
120
  "oxfmt": "^0.72.0",
97
121
  "oxlint": "^1.75.0",
122
+ "superstruct": "^2.0.2",
98
123
  "tsd": "^0.33.0",
124
+ "typebox": "^1.3.36",
99
125
  "typescript": "^7.0.2",
100
126
  "valibot": "^1.5.0",
101
127
  "vitepress": "^1.6.4",
102
- "zod": "^4.6.5"
128
+ "vitepress-plugin-mermaid": "^2.0.17",
129
+ "yup": "^1.7.1",
130
+ "zod": "^4.6.6"
103
131
  },
104
132
  "scripts": {
105
133
  "test": "node --test tests/unit/*.test.js",
@@ -107,15 +135,20 @@
107
135
  "test:nojit": "node --disallow-code-generation-from-strings --require ./tests/helpers/jit.js --test tests/unit/*.test.js",
108
136
  "test:coverage": "c8 --all --include 'src/**' --check-coverage --lines 98 --statements 98 --branches 90 --functions 100 --reporter text --reporter lcov node --test tests/unit/*.test.js",
109
137
  "test:types": "tsd",
110
- "check:dts": "tsc --noEmit --strict --target es2022 --skipLibCheck false index.d.ts src/locales/en.d.ts src/locales/uk.d.ts src/generators/index.d.ts src/compile/index.d.ts src/model/index.d.ts",
138
+ "check:dts": "tsc --noEmit --strict --target es2022 --skipLibCheck false index.d.ts src/locales/en.d.ts src/locales/uk.d.ts src/generators/index.d.ts src/compile/index.d.ts src/model/index.d.ts src/stream/index.d.ts src/formats/index.d.ts",
111
139
  "lint": "oxlint index.js browser.js src tests scripts bench",
112
140
  "format": "oxfmt index.js browser.js src tests scripts bench",
113
141
  "format:check": "oxfmt --check index.js browser.js src tests scripts bench",
114
142
  "size": "node scripts/size.js",
115
143
  "bench": "node bench/bench.js",
144
+ "bench:compare": "node bench/compare.js",
145
+ "bench:releases": "node bench/releases.js",
146
+ "bench:report": "node bench/report.js",
147
+ "size:compare": "node scripts/size-compare.js",
116
148
  "docs:dev": "vitepress dev docs",
117
149
  "docs:build": "vitepress build docs",
118
150
  "docs:preview": "vitepress preview docs",
151
+ "docs:comparison": "node scripts/comparison.js",
119
152
  "release": "pnpm publish"
120
153
  }
121
154
  }
package/src/codec.js CHANGED
@@ -7,8 +7,17 @@
7
7
  // whose subtree carries nothing for a phase is returned as it is, and a
8
8
  // container is copied only when one of its parts changed: the value given is
9
9
  // never written to.
10
- const { hasBrand, define } = require('./util.js');
11
- const { EMPTY, NONE, issues, isThenable, abandon, pathOf, toDotPath } = require('./issues.js');
10
+ const { hasBrand, define, isMap, isSet } = require('./util.js');
11
+ const {
12
+ EMPTY,
13
+ NONE,
14
+ issues,
15
+ isThenable,
16
+ abandon,
17
+ release,
18
+ pathOf,
19
+ toDotPath,
20
+ } = require('./issues.js');
12
21
  const { createContext } = require('./context.js');
13
22
  const { STRUCT, isStruct, aliasOf } = require('./struct.js');
14
23
  const { asyncReturn } = require('./errors.js');
@@ -176,14 +185,13 @@ const toMap = (value) => new Map(value);
176
185
 
177
186
  const toSet = (list) => new Set(list);
178
187
 
179
- // The output of a container under construction: the container is copied at
180
- // the first part that changed (`clone`), a part is written with `put`, and
181
- // the parts that decoded asynchronously are written in once they settle (a
182
- // decoder that failed resolved to nothing and recorded its issue). A
183
- // container pushes its key on the path for its parts.
184
- const enter = (context, key, value, clone, put) => {
185
- if (key !== undefined) context.path.push(key);
186
- return { context, key, value, clone, put, out: null, pending: null };
188
+ // The output of a container under construction, kept in the locals of its
189
+ // walker (no state object per container): null until a part changes, then a
190
+ // copy of the container (`clone`) the parts are written into (`put`).
191
+ const written = (out, value, clone, put, key, result) => {
192
+ const target = out === null ? clone(value) : out;
193
+ put(target, key, result);
194
+ return target;
187
195
  };
188
196
 
189
197
  // A part that is still decoding: only a decoder makes a promise (a thenable
@@ -191,13 +199,11 @@ const enter = (context, key, value, clone, put) => {
191
199
  // of the data with a `then` of its own is data, never awaited.
192
200
  const isPending = (context, value) => context.async !== null && value instanceof Promise;
193
201
 
194
- const take = (state, key, result, phase) => {
195
- if (state.out === null) state.out = state.clone(state.value);
196
- state.put(state.out, key, result);
197
- if (phase === DECODERS && isPending(state.context, result)) {
198
- if (state.pending === null) state.pending = [];
199
- state.pending.push(key, result);
200
- }
202
+ // The parts of a container still decoding, as key, promise, key, promise.
203
+ const queued = (pending, key, result) => {
204
+ const list = pending === null ? [] : pending;
205
+ list.push(key, result);
206
+ return list;
201
207
  };
202
208
 
203
209
  // What a promise of the passes resolves to: a box around the value, never
@@ -205,10 +211,11 @@ const take = (state, key, result, phase) => {
205
211
  // own and the value of a program may well have one.
206
212
  const boxed = (value) => ({ value });
207
213
 
208
- const leave = (state, wrap) => {
209
- const { context, key, out, pending, put } = state;
210
- if (key !== undefined) context.path.pop();
211
- if (out === null) return state.value;
214
+ // What a container comes back as: the value when no part changed, its copy,
215
+ // or a promise of a box when parts are still decoding, written in once they
216
+ // settle (a decoder that failed resolved to nothing and recorded its issue).
217
+ const settled = (value, out, pending, put, wrap) => {
218
+ if (out === null) return value;
212
219
  if (pending === null) return wrap === undefined ? out : wrap(out);
213
220
  const promises = [];
214
221
  for (let index = 1; index < pending.length; index += 2) promises.push(pending[index]);
@@ -323,8 +330,10 @@ const walkFields = (info, fields, value, context, key, phase, want) => {
323
330
  const { plan, infos, extra } = info;
324
331
  const strip = (want & STRUCTS) !== 0;
325
332
  const parts = info.parts[strip ? STRUCTS : phase];
326
- const state = enter(context, key, value, copy, putKey);
327
- if (strip) state.out = {};
333
+ const nested = key !== undefined;
334
+ if (nested) context.path.push(key);
335
+ let out = strip ? {} : null;
336
+ let pending = null;
328
337
  let renames = null;
329
338
  for (let position = 0; position < parts.length; position += 1) {
330
339
  const index = parts[position];
@@ -341,15 +350,18 @@ const walkFields = (info, fields, value, context, key, phase, want) => {
341
350
  const fallback = entry.type.default;
342
351
  if (fallback === undefined) continue;
343
352
  item = typeof fallback === 'function' ? fallback() : fallback;
344
- take(state, from, item, phase);
353
+ out = written(out, value, copy, putKey, from, item);
345
354
  }
346
355
  const result = apply(infos[index], entry.type, item, context, from, phase, want);
347
- if (result !== item) take(state, from, result, phase);
356
+ if (result !== item) out = written(out, value, copy, putKey, from, result);
348
357
  continue;
349
358
  }
350
359
  const result = apply(infos[index], entry.type, item, context, from, phase, want);
351
360
  const renamed = from !== name;
352
- if (strip ? result !== undefined : renamed || result !== item) take(state, name, result, phase);
361
+ if (strip ? result !== undefined : renamed || result !== item) {
362
+ out = written(out, value, copy, putKey, name, result);
363
+ if (phase === DECODERS && isPending(context, result)) pending = queued(pending, name, result);
364
+ }
353
365
  if (renamed && !strip) {
354
366
  if (renames === null) renames = [];
355
367
  renames.push(from, name);
@@ -358,27 +370,37 @@ const walkFields = (info, fields, value, context, key, phase, want) => {
358
370
  if (strip) {
359
371
  for (let index = 0; index < extra.length; index += 1) {
360
372
  const name = extra[index];
361
- if (Object.hasOwn(value, name)) putKey(state.out, name, value[name]);
373
+ if (Object.hasOwn(value, name)) putKey(out, name, value[name]);
362
374
  }
363
- } else if (renames !== null) state.out = renameKeys(state.out, renames);
364
- return leave(state);
375
+ } else if (renames !== null) out = renameKeys(out, renames);
376
+ if (nested) context.path.pop();
377
+ return settled(value, out, pending, putKey, undefined);
365
378
  };
366
379
 
367
380
  // The elements of an array, a Set or a tuple, by position; a Set comes back
368
381
  // as a Set.
369
382
  const walkItems = (children, infos, fixed, value, context, key, phase, want) => {
370
383
  const set = !Array.isArray(value);
371
- if (set && (fixed || value.constructor?.name !== 'Set')) return value;
372
- const state = enter(context, key, value, Array.from, putIndex);
384
+ if (set && (fixed || !isSet(value))) return value;
385
+ const nested = key !== undefined;
386
+ if (nested) context.path.push(key);
387
+ let out = null;
388
+ let pending = null;
373
389
  let index = 0;
374
390
  for (const item of value) {
375
391
  const slot = fixed ? index : 0;
376
392
  if (slot >= children.length) break;
377
393
  const result = apply(infos[slot], children[slot], item, context, index, phase, want);
378
- if (result !== item) take(state, index, result, phase);
394
+ if (result !== item) {
395
+ out = written(out, value, Array.from, putIndex, index, result);
396
+ if (phase === DECODERS && isPending(context, result)) {
397
+ pending = queued(pending, index, result);
398
+ }
399
+ }
379
400
  index += 1;
380
401
  }
381
- return leave(state, set ? toSet : undefined);
402
+ if (nested) context.path.pop();
403
+ return settled(value, out, pending, putIndex, set ? toSet : undefined);
382
404
  };
383
405
 
384
406
  const walkList = (info, node, value, context, key, phase, want) =>
@@ -386,17 +408,27 @@ const walkList = (info, node, value, context, key, phase, want) =>
386
408
 
387
409
  // The values of an object or a Map, by key.
388
410
  const walkKeyed = (info, node, value, context, key, phase, want) => {
389
- const map = value.constructor?.name === 'Map';
411
+ const map = isMap(value);
390
412
  if (!map && (typeof value !== 'object' || Array.isArray(value))) return value;
391
413
  const child = info.children[0];
392
414
  const sub = info.infos[0];
393
- const state = enter(context, key, value, map ? toMap : copy, map ? putEntry : putKey);
415
+ const clone = map ? toMap : copy;
416
+ const put = map ? putEntry : putKey;
417
+ const nested = key !== undefined;
418
+ if (nested) context.path.push(key);
419
+ let out = null;
420
+ let pending = null;
394
421
  if (map) {
395
422
  for (const pair of value) {
396
423
  const name = pair[0];
397
424
  const item = pair[1];
398
425
  const result = apply(sub, child, item, context, name, phase, want);
399
- if (result !== item) take(state, name, result, phase);
426
+ if (result !== item) {
427
+ out = written(out, value, clone, put, name, result);
428
+ if (phase === DECODERS && isPending(context, result)) {
429
+ pending = queued(pending, name, result);
430
+ }
431
+ }
400
432
  }
401
433
  } else {
402
434
  // The own keys of the object, in order, as the check iterates them.
@@ -404,10 +436,16 @@ const walkKeyed = (info, node, value, context, key, phase, want) => {
404
436
  if (!Object.hasOwn(value, name)) continue;
405
437
  const item = value[name];
406
438
  const result = apply(sub, child, item, context, name, phase, want);
407
- if (result !== item) take(state, name, result, phase);
439
+ if (result !== item) {
440
+ out = written(out, value, clone, put, name, result);
441
+ if (phase === DECODERS && isPending(context, result)) {
442
+ pending = queued(pending, name, result);
443
+ }
444
+ }
408
445
  }
409
446
  }
410
- return leave(state);
447
+ if (nested) context.path.pop();
448
+ return settled(value, out, pending, put, undefined);
411
449
  };
412
450
 
413
451
  // The context for trying the branches of a plain union, one per parse, made
@@ -434,12 +472,8 @@ const accepts = (branch, value, scratch, path, key) => {
434
472
  scratch.issues = NONE;
435
473
  scratch.count = 0;
436
474
  scratch.path = path;
437
- const list = scratch.async;
438
- list.length = 0;
439
475
  branch.check(value, scratch, key);
440
- for (let index = 0; index < list.length; index += 1) {
441
- if (list[index].promise !== null) abandon(list[index].promise);
442
- }
476
+ release(scratch.async, 0);
443
477
  return scratch.count === 0;
444
478
  };
445
479
 
@@ -1,7 +1,7 @@
1
1
  // The builder of the generated source. Generated code holds identifiers,
2
2
  // numbers, booleans and JSON strings only: a regular expression, a Set, a
3
3
  // function, a nested check or a dictionary of known keys goes into the scope
4
- // and is reached by name (the ajv and schemasafe rule, ROADMAP P9), so
4
+ // and is reached by name (the ajv and schemasafe rule), so
5
5
  // nothing taken from a schema is ever part of the source text.
6
6
  const { IDENTIFIER } = require('../util.js');
7
7