yeptris 0.6.59 → 0.6.60

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/src/index.js CHANGED
@@ -1,5 +1,14 @@
1
1
  // The public surface: YAML <-> JSON at libyeptris speed.
2
2
  // Engine FFI through ../dist/yeptris.mjs (built by build.sh).
3
+ //
4
+ // Two call postures over one initialized module: the async forms
5
+ // (load/dump/validate/...) initialize the wasm on demand and stay the
6
+ // default entry; the *Sync forms (loadSync/dumpSync/validateSync/...)
7
+ // run synchronously against the module an earlier await already
8
+ // initialized (the wasm executes synchronously — init-then-work is
9
+ // sync by construction). Every exported function shares its body
10
+ // with its Sync twin through the *Core helpers below, so the two
11
+ // postures cannot drift.
3
12
 
4
13
  function cstr(mod, s) {
5
14
  const bytes = mod.lengthBytesUTF8(s) + 1;
@@ -21,14 +30,32 @@ class YamlError extends Error {
21
30
  }
22
31
  }
23
32
 
24
- function run(mod, fn, input) {
33
+ /** Raised by load/loadAll when the input PARSES but the schema walk
34
+ * (schema: / jsonSchema:) produced diagnostics. Carries the whole
35
+ * report as `diagnostics` — never first-fail, never a raw pointer.
36
+ * Not a YamlError: the input is well-formed (the same split the
37
+ * ruby/py faces draw between their parse errors and
38
+ * Validation::Error / ValidationError). */
39
+ export class ValidationError extends Error {
40
+ constructor(diagnostics) {
41
+ const first = diagnostics[0];
42
+ const detail = first
43
+ ? `${first.keyword} at ${first.pointer || "(root)"}: ${first.message}`
44
+ : "no diagnostics";
45
+ super(`validation failed (${diagnostics.length} diagnostics): ${detail}`);
46
+ this.name = "ValidationError";
47
+ this.diagnostics = diagnostics;
48
+ }
49
+ }
50
+
51
+ function run(mod, fn, input, ...args) {
25
52
  const [ptr, len] = cstr(mod, input);
26
53
  try {
27
54
  // len is the UTF-8 byte count: input.length counts UTF-16 code
28
55
  // units, which is strictly shorter than the wire bytes for any
29
56
  // non-ASCII text (é is 1 unit / 2 bytes) — every such document
30
57
  // parsed truncated
31
- const st = fn(ptr, len);
58
+ const st = fn(ptr, len, ...args);
32
59
  if (st !== 0) {
33
60
  const msg = mod.UTF8ToString(mod._yeptris_wasm_last_error());
34
61
  throw new YamlError(
@@ -62,12 +89,23 @@ async function mod() {
62
89
  "_yeptris_wasm_load",
63
90
  "_yeptris_wasm_load_all",
64
91
  "_yeptris_wasm_dump",
92
+ "_yeptris_wasm_dump_ex",
65
93
  "_yeptris_wasm_events",
66
94
  "_yeptris_wasm_event_records",
67
95
  "_yeptris_wasm_event_count",
68
96
  "_yeptris_wasm_event_arena",
69
97
  "_yeptris_wasm_event_arena_len",
70
98
  "_yeptris_wasm_events_free",
99
+ "_yeptris_wasm_each_open",
100
+ "_yeptris_wasm_each_next",
101
+ "_yeptris_wasm_each_frame",
102
+ "_yeptris_wasm_each_index",
103
+ "_yeptris_wasm_each_close",
104
+ "_yeptris_wasm_validate",
105
+ "_yeptris_wasm_json_schema_validate",
106
+ "_yeptris_wasm_schema_compile",
107
+ "_yeptris_wasm_schema_validate",
108
+ "_yeptris_wasm_schema_free",
71
109
  "_yeptris_wasm_out",
72
110
  "_yeptris_wasm_out_len",
73
111
  "_yeptris_wasm_out_free",
@@ -86,34 +124,551 @@ async function mod() {
86
124
  return cached;
87
125
  }
88
126
 
89
- /** Parse YAML text and return the document as a JavaScript value
90
- * (the engine's canonical JSON, JSON.parse'd). Throws YamlError with
91
- * line/column on malformed input. A multi-document stream answers
92
- * with the FIRST document (the engine's json contract); every
93
- * document of a stream comes from loadAll. */
94
- export async function load(yaml) {
127
+ /** Initialize the wasm module (idempotent). The async forms call this
128
+ * on demand; calling it first is what unlocks the Sync forms
129
+ * (loadSync/dumpSync/validateSync/...), which run synchronously
130
+ * against the same module instance. */
131
+ export async function init() {
132
+ await mod();
133
+ }
134
+
135
+ /** The module this package caches, when an async call (or init())
136
+ * has already initialized it; undefined before that. The Sync forms
137
+ * exist for the initialized posture only — they refuse to lazily
138
+ * import (that door is async by nature). */
139
+ function requireMod(who) {
140
+ if (!cached) {
141
+ throw new Error(
142
+ `yeptris: ${who} needs an initialized module — await init() first ` +
143
+ "(the async forms initialize on demand)",
144
+ );
145
+ }
146
+ return cached;
147
+ }
148
+
149
+ // ---- the validate face (validate.h) ------------------------------------
150
+ //
151
+ // The engine's three doors, all fused parse+validate over the same
152
+ // front door load uses (encodings, BOM, every document of a stream):
153
+ // the SCHEMA-FAMILY walk (yeptris_validate — the YeptrisSchema kind
154
+ // rides as a parameter), the one-shot JSON SCHEMA walk (draft 2020-12
155
+ // subset), and the COMPILED economy (yeptris_schema_compile: parse
156
+ // the schema once, validate many streams). The engine carries NO kind
157
+ // on the compile door — a compiled handle is a JSON-Schema document
158
+ // by validate.h's contract; the family-kind selection lives on the
159
+ // validate door, spelled exactly as the C surface spells it.
160
+ //
161
+ // Diagnostics cross as data: the whole report drains as one JSON
162
+ // array of raw records (code/path/message/line/col/offset) and is
163
+ // mapped here into plain objects. The code -> keyword table is
164
+ // binding-owned (the same law the ruby/py faces follow); `path` is
165
+ // the JSON-pointer split into ~0/~1-unescaped segments, `pointer` its
166
+ // raw string form.
167
+
168
+ // YeptrisDiagCode -> the spec-spelled keyword (validate.h). The
169
+ // 2020-12 walk's codes name their JSON Schema keyword; the
170
+ // schema-family walk's codes name the violated YAML rule. Values are
171
+ // ABI-pinned (validate.h, appending-only).
172
+ const DIAG_KEYWORDS = {
173
+ 0: "none",
174
+ 1: "tag", // explicit tag contradicts content
175
+ 2: "keyType", // json12: a mapping key is not a string
176
+ 3: "jsonType", // json12: plain scalar matches no JSON production
177
+ 4: "duplicateKey",
178
+ 5: "type",
179
+ 6: "required",
180
+ 7: "enum",
181
+ 8: "const",
182
+ 9: "pattern",
183
+ 10: "minimum",
184
+ 11: "maximum",
185
+ 12: "exclusiveMinimum",
186
+ 13: "exclusiveMaximum",
187
+ 14: "minLength",
188
+ 15: "maxLength",
189
+ 16: "minItems",
190
+ 17: "maxItems",
191
+ 18: "uniqueItems",
192
+ 19: "additionalProperties",
193
+ 20: "anyOf",
194
+ 21: "oneOf",
195
+ 22: "not",
196
+ 23: "$ref",
197
+ 24: "false",
198
+ 25: "depth",
199
+ 26: "limit",
200
+ 27: "multipleOf",
201
+ 28: "minProperties",
202
+ 29: "maxProperties",
203
+ 30: "contains",
204
+ 31: "minContains",
205
+ 32: "maxContains",
206
+ 33: "dependentRequired",
207
+ };
208
+
209
+ // YeptrisStatus values that carry a report in the wasm out-buffer:
210
+ // 0 = valid (an empty report is a valid answer), 9 =
211
+ // YEPTRIS_ERROR_SCHEMA (invalid: drain the diagnostics). Anything
212
+ // else is a call failure (the parse itself failed).
213
+ const ST_OK = 0;
214
+ const ST_SCHEMA_ERROR = 9;
215
+
216
+ /** '/a/b/0' -> ['a', 'b', '0'], with ~1 and ~0 unescaped; '' (the
217
+ * root) -> []. */
218
+ function pointerSegments(raw) {
219
+ if (typeof raw !== "string" || raw.length === 0) return [];
220
+ return raw
221
+ .split("/")
222
+ .slice(1)
223
+ .map((s) => s.replaceAll("~1", "/").replaceAll("~0", "~"));
224
+ }
225
+
226
+ function toDiagnostic(raw) {
227
+ return {
228
+ code: raw.code,
229
+ keyword: DIAG_KEYWORDS[raw.code] ?? `unknown-${raw.code}`,
230
+ path: pointerSegments(raw.path),
231
+ pointer: raw.path,
232
+ message: raw.message,
233
+ line: raw.line, // 1-based; 0 = unknown (unpositioned scalars)
234
+ col: raw.col,
235
+ offset: raw.offset,
236
+ };
237
+ }
238
+
239
+ function drainReport(mod, st) {
240
+ const raw = JSON.parse(
241
+ mod.UTF8ToString(mod._yeptris_wasm_out(), mod._yeptris_wasm_out_len()));
242
+ mod._yeptris_wasm_out_free();
243
+ return raw.map(toDiagnostic);
244
+ }
245
+
246
+ function failFrom(mod) {
247
+ return new YamlError(
248
+ mod.UTF8ToString(mod._yeptris_wasm_last_error()),
249
+ mod._yeptris_wasm_last_error_line(),
250
+ mod._yeptris_wasm_last_error_column());
251
+ }
252
+
253
+ function runFamilyValidate(mod, input, kind) {
254
+ const [ptr, len] = cstr(mod, input);
255
+ try {
256
+ const st = mod._yeptris_wasm_validate(ptr, len, kind);
257
+ if (st === ST_OK || st === ST_SCHEMA_ERROR) return drainReport(mod, st);
258
+ throw failFrom(mod);
259
+ } finally {
260
+ freeCstr(mod, ptr);
261
+ mod._yeptris_wasm_out_free();
262
+ }
263
+ }
264
+
265
+ function runJsonSchemaValidate(mod, schemaBytes, input) {
266
+ const [sptr, slen] = cstr(mod, schemaBytes);
267
+ const [ptr, len] = cstr(mod, input);
268
+ try {
269
+ const st = mod._yeptris_wasm_json_schema_validate(sptr, slen, ptr, len);
270
+ if (st === ST_OK || st === ST_SCHEMA_ERROR) return drainReport(mod, st);
271
+ throw failFrom(mod);
272
+ } finally {
273
+ freeCstr(mod, sptr);
274
+ freeCstr(mod, ptr);
275
+ mod._yeptris_wasm_out_free();
276
+ }
277
+ }
278
+
279
+ function runCompiledValidate(mod, handle, input) {
280
+ const [ptr, len] = cstr(mod, input);
281
+ try {
282
+ const st = mod._yeptris_wasm_schema_validate(handle, ptr, len);
283
+ if (st === ST_OK || st === ST_SCHEMA_ERROR) return drainReport(mod, st);
284
+ throw failFrom(mod);
285
+ } finally {
286
+ freeCstr(mod, ptr);
287
+ mod._yeptris_wasm_out_free();
288
+ }
289
+ }
290
+
291
+ /** A COMPILED JSON Schema (the compiled economy): the schema parses
292
+ * once — its DOM and pattern programs retained behind one handle —
293
+ * and validates MANY instance streams. Build with compileSchema();
294
+ * direct construction is refused. After free() the handle is dead:
295
+ * reuse throws, double-free is a no-op (the engine frees NULL as a
296
+ * documented no-op; the flag makes the JS door idempotent). */
297
+ export class Schema {
298
+ /** @private — produced by compileSchema() only */
299
+ constructor() {
300
+ throw new TypeError(
301
+ "yeptris: build schemas with compileSchema(), not new Schema()");
302
+ }
303
+
304
+ static _take(mod, handle) {
305
+ const s = Object.create(Schema.prototype);
306
+ s._mod = mod; // the module the handle lives in (compile ran => initialized)
307
+ s._handle = handle;
308
+ s._freed = false;
309
+ return s;
310
+ }
311
+
312
+ /** True once free() ran. */
313
+ get freed() {
314
+ return this._freed;
315
+ }
316
+
317
+ _requireAlive(who) {
318
+ if (this._freed) {
319
+ throw new Error(
320
+ `yeptris: the schema handle is freed — ${who} on a freed schema ` +
321
+ "is refused (compile a fresh one with compileSchema())");
322
+ }
323
+ }
324
+
325
+ /** Every diagnostic across every document of `input` ([] when
326
+ * valid). Same contract as validate(). Synchronous: the handle only
327
+ * exists once the module is initialized. */
328
+ validate(input) {
329
+ this._requireAlive("validate");
330
+ return runCompiledValidate(this._mod, this._handle, input);
331
+ }
332
+
333
+ /** True when validate() answers no diagnostics. */
334
+ isValid(input) {
335
+ return this.validate(input).length === 0;
336
+ }
337
+
338
+ /** Frees the handle and everything it owns in one call. Idempotent;
339
+ * afterwards the handle is dead (reuse throws, never segfaults). */
340
+ free() {
341
+ if (this._freed) return;
342
+ this._freed = true;
343
+ this._mod._yeptris_wasm_schema_free(this._handle);
344
+ this._handle = 0;
345
+ }
346
+ }
347
+
348
+ // The options door: schema: "core" | "json" (the YAML 1.2 family
349
+ // walk — js-yaml's load(str, { schema }) analog) | a compiled Schema;
350
+ // jsonSchema: object | string (the JSON Schema 2020-12 walk); collect:
351
+ // load-only (load answers { document, diagnostics } instead of
352
+ // raising). Strictness law (the dump precedent): unknown options are
353
+ // rejected, never silently ignored.
354
+ function parseValidateOptions(options, who, allowCollect) {
355
+ if (options === undefined || options === null) {
356
+ return { door: "family", kind: 0, collect: false }; // core_12, the engine default
357
+ }
358
+ if (typeof options !== "object") {
359
+ throw new TypeError(`yeptris: ${who} options must be an object`);
360
+ }
361
+ const KEYS = new Set(["schema", "jsonSchema", "collect"]);
362
+ for (const key of Object.keys(options)) {
363
+ if (!KEYS.has(key)) {
364
+ throw new TypeError(
365
+ `yeptris: ${who} option "${key}" is not supported ` +
366
+ `(the surface is schema + jsonSchema${allowCollect ? " + collect" : ""})`);
367
+ }
368
+ }
369
+ let collect = false;
370
+ if (options.collect !== undefined) {
371
+ if (typeof options.collect !== "boolean") {
372
+ throw new TypeError(`yeptris: ${who} option collect must be a boolean`);
373
+ }
374
+ if (!allowCollect) {
375
+ throw new TypeError(
376
+ `yeptris: ${who} takes no collect option — collect rides load() ` +
377
+ "(loadAll validates the whole stream and returns documents)");
378
+ }
379
+ collect = options.collect;
380
+ }
381
+ let schema = options.schema;
382
+ if (schema !== undefined && schema !== null) {
383
+ if (typeof schema === "string") {
384
+ if (schema !== "core" && schema !== "json") {
385
+ throw new TypeError(
386
+ `yeptris: ${who} option schema must be "core", "json", or a ` +
387
+ `compiled Schema (got ${JSON.stringify(schema)})`);
388
+ }
389
+ } else if (!(schema instanceof Schema)) {
390
+ throw new TypeError(
391
+ `yeptris: ${who} option schema must be "core", "json", or a ` +
392
+ "compiled Schema (got " + typeof schema + ")");
393
+ }
394
+ }
395
+ let jsonSchema = options.jsonSchema;
396
+ if (jsonSchema !== undefined && jsonSchema !== null) {
397
+ if (typeof jsonSchema !== "string" && typeof jsonSchema !== "object") {
398
+ throw new TypeError(
399
+ `yeptris: ${who} option jsonSchema must be an object or a string ` +
400
+ "(the schema document)");
401
+ }
402
+ if (jsonSchema instanceof Schema) {
403
+ throw new TypeError(
404
+ `yeptris: ${who}: a compiled Schema rides schema:, not jsonSchema: ` +
405
+ "(jsonSchema takes the schema document itself)");
406
+ }
407
+ }
408
+ if (jsonSchema !== undefined && jsonSchema !== null && schema !== undefined && schema !== null) {
409
+ // the two doors are alternatives, not layers: a caller passing both
410
+ // is one edit away from the door they meant, so refuse instead of
411
+ // silently picking one (the dump precedent)
412
+ throw new TypeError(
413
+ `yeptris: ${who}: pass the compiled schema as schema: OR the ` +
414
+ "schema document as jsonSchema: — not both");
415
+ }
416
+ if (jsonSchema !== undefined && jsonSchema !== null) {
417
+ const bytes = typeof jsonSchema === "string" ? jsonSchema : JSON.stringify(jsonSchema);
418
+ return { door: "json", schemaBytes: bytes, collect, armed: true };
419
+ }
420
+ if (schema instanceof Schema) {
421
+ return { door: "handle", handle: schema, collect, armed: true };
422
+ }
423
+ if (schema !== undefined && schema !== null) {
424
+ const kind = schema === "json" ? 2 : 0; // YEPTRIS_SCHEMA_12_JSON / _12_CORE
425
+ return { door: "family", kind, collect, armed: true };
426
+ }
427
+ if (collect) {
428
+ throw new TypeError(
429
+ `yeptris: ${who}: collect requires a schema — pass schema: or jsonSchema: ` +
430
+ "(collect:true without a gate has nothing to collect)");
431
+ }
432
+ return { door: "family", kind: 0, collect: false, armed: false };
433
+ }
434
+
435
+ function validateWithOptions(mod, input, vo) {
436
+ if (vo.door === "handle") return vo.handle.validate(input);
437
+ if (vo.door === "json") {
438
+ return runJsonSchemaValidate(mod, vo.schemaBytes, input);
439
+ }
440
+ return runFamilyValidate(mod, input, vo.kind);
441
+ }
442
+
443
+ /** Validate a YAML stream, answering the WHOLE report: every
444
+ * diagnostic, in engine order ([] when valid). Each diagnostic:
445
+ * `{ code, keyword, path, pointer, message, line, col, offset }` —
446
+ * `path` is the JSON-pointer instance path split into ~0/~1-unescaped
447
+ * segments ([] at the root), `pointer` its raw string form, `line`/
448
+ * `col` the offending node's 1-based mark (0 = unknown: scalars whose
449
+ * bytes the DOM owns have no input position; the path still
450
+ * identifies them).
451
+ *
452
+ * options picks the walk (js-yaml parity names):
453
+ * schema: "core" (default) — explicit-tag consistency + canonical-
454
+ * form key uniqueness; "json" — the spec 10.2 JSON productions
455
+ * (every plain scalar a JSON type, string mapping keys);
456
+ * schema: a compiled Schema (compileSchema()) — validate against
457
+ * the retained model;
458
+ * jsonSchema: object | string — the JSON Schema draft 2020-12 walk
459
+ * (the engine's keyword subset; unknown keywords are ignored).
460
+ * The doors are alternatives: passing schema AND jsonSchema throws
461
+ * TypeError (pick the door you meant — nothing is silently dropped).
462
+ * A stream that does not parse throws YamlError; a $ref that resolves
463
+ * nowhere is a diagnostic, not an exception. */
464
+ export async function validate(input, options) {
95
465
  const m = await mod();
96
- return JSON.parse(run(m, m._yeptris_wasm_load, yaml));
466
+ return validateWithOptions(m, input, parseValidateOptions(options, "validate", false));
97
467
  }
98
468
 
99
- /** Parse a multi-document YAML stream and return EVERY document as a
100
- * JavaScript value, in stream order (js-yaml's loadAll shape). An
101
- * empty or comment-only stream answers []; an empty document
102
- * ("---\n---") answers null at its position. options is accepted for
103
- * call-site symmetry and reserved (load takes none today). Throws
104
- * YamlError with line/column on malformed input. */
105
- export async function loadAll(yaml, options) {
469
+ /** True when validate() answers no diagnostics. */
470
+ export async function isValid(input, options) {
471
+ return (await validate(input, options)).length === 0;
472
+ }
473
+
474
+ /** Compile a JSON Schema document (object or string; JSON is YAML
475
+ * flow, so a YAML-shaped mapping schema compiles too) into a
476
+ * reusable Schema handle — parse ONCE, validate many. Throws
477
+ * TypeError for empty/absent schema bytes and YamlError (with the
478
+ * engine's message) for bytes that do not parse. */
479
+ export async function compileSchema(jsonSchema) {
106
480
  const m = await mod();
107
- return JSON.parse(run(m, m._yeptris_wasm_load_all, yaml));
481
+ return compileSchemaCore(m, jsonSchema);
108
482
  }
109
483
 
110
- /** Parse YAML text and return the engine's canonical JSON string. */
111
- export async function loadJSON(yaml) {
484
+ function compileSchemaCore(mod, jsonSchema) {
485
+ if (jsonSchema === undefined || jsonSchema === null) {
486
+ throw new TypeError("yeptris: schema bytes are required");
487
+ }
488
+ const bytes = typeof jsonSchema === "string"
489
+ ? jsonSchema
490
+ : JSON.stringify(jsonSchema);
491
+ if (bytes.length === 0) {
492
+ throw new TypeError("yeptris: schema bytes hold no document");
493
+ }
494
+ const [ptr, len] = cstr(mod, bytes);
495
+ let handle;
496
+ try {
497
+ handle = mod._yeptris_wasm_schema_compile(ptr, len);
498
+ } finally {
499
+ freeCstr(mod, ptr);
500
+ }
501
+ if (handle === 0) {
502
+ throw failFrom(mod); // the engine's why rides last_error
503
+ }
504
+ return Schema._take(mod, handle);
505
+ }
506
+
507
+ // ---- the tolerant stream walk (parse.h's stream iterator) ---------------
508
+ //
509
+ // loadAll is all-or-nothing: one bad document fails the whole stream.
510
+ // The engine's stream iterator (leptris/yeptris#921) walks document by
511
+ // document: a parse-class failure is ONE failed item carrying the
512
+ // failed document's OWN line/column, and the walk RESUMES at the next
513
+ // line-start marker — the valid documents after a bad one are kept.
514
+ // The stream-fatal classes (memory/encoding) end the walk after their
515
+ // item; an unrecoverable tail ends it.
516
+ //
517
+ // Across the wasm boundary the walk is RETAINED state (like the
518
+ // recorder above): open copies the feed into the heap (the engine
519
+ // iterator only borrows its buffer until free), every next() advances
520
+ // one step, close frees both. The step answer crosses through the
521
+ // g_out discipline: frame() says whether the last successful step
522
+ // published a document JSON, index() says which stream position it
523
+ // consumed (failures consume an index too — the yield order is the
524
+ // stream's). Each document serializes through the same serialize_json
525
+ // door load uses, so a frame's value is load's value by construction.
526
+ //
527
+ // The JS shape is the rs face's: an iterator of result objects —
528
+ // `{ document, index }` for a valid document, `{ error, index }` for
529
+ // a failed one. The engine default (schema 1.2 core) rides as-is; the
530
+ // options door (schema/max_depth) is the engine's parse-options struct
531
+ // and joins when the face needs it.
532
+
533
+ const ST_MEMORY = 2; // YEPTRIS_ERROR_MEMORY — stream-fatal
534
+ const ST_ENCODING = 4; // YEPTRIS_ERROR_ENCODING — stream-fatal
535
+
536
+ function eachDocumentCore(mod, yaml) {
537
+ return (function* () {
538
+ const [ptr, len] = cstr(mod, yaml);
539
+ try {
540
+ const openSt = mod._yeptris_wasm_each_open(ptr, len);
541
+ if (openSt !== 0) {
542
+ throw failFrom(mod);
543
+ }
544
+ for (;;) {
545
+ const st = mod._yeptris_wasm_each_next();
546
+ const index = mod._yeptris_wasm_each_index();
547
+ if (st === 0) {
548
+ if (mod._yeptris_wasm_each_frame() === 0) {
549
+ return; // the stream is over
550
+ }
551
+ const document = JSON.parse(
552
+ mod.UTF8ToString(mod._yeptris_wasm_out(), mod._yeptris_wasm_out_len()));
553
+ mod._yeptris_wasm_out_free();
554
+ yield { document, index, error: undefined };
555
+ } else {
556
+ yield {
557
+ document: undefined,
558
+ index,
559
+ error: new YamlError(
560
+ mod.UTF8ToString(mod._yeptris_wasm_last_error()),
561
+ mod._yeptris_wasm_last_error_line(),
562
+ mod._yeptris_wasm_last_error_column()),
563
+ };
564
+ if (st === ST_MEMORY || st === ST_ENCODING) {
565
+ return; // stream-fatal: the iterator is done
566
+ }
567
+ }
568
+ }
569
+ } finally {
570
+ mod._yeptris_wasm_out_free(); // idempotent (frees NULL = no-op)
571
+ mod._yeptris_wasm_each_close();
572
+ }
573
+ })();
574
+ }
575
+
576
+ /** Walk a multi-document stream one document at a time, TOLERANTLY
577
+ * (the engine's stream iterator): yields one result per document in
578
+ * stream order —
579
+ *
580
+ * { document: value, index: 0, error: undefined } // a valid document
581
+ * { document: undefined, index: 1, error: YamlError } // a failed one
582
+ *
583
+ * A parse-class failure carries the failed document's OWN line/column
584
+ * and its 0-based stream index, and the walk CONTINUES at the next
585
+ * `---` line-start marker — the valid documents after a bad one are
586
+ * kept (parse()/loadAll would fail the whole stream instead). The
587
+ * stream-fatal classes (memory/encoding) yield their item and end the
588
+ * walk; an unrecoverable tail ends it. Lazy: nothing parses until
589
+ * iteration starts. Documents materialize through load's serialize
590
+ * door, so each frame's value is load's value by construction. The
591
+ * engine default (schema 1.2 core) rides as-is. */
592
+ export async function* eachDocument(yaml) {
112
593
  const m = await mod();
113
- return run(m, m._yeptris_wasm_load, yaml);
594
+ yield* eachDocumentCore(m, yaml);
114
595
  }
115
596
 
116
- // ---- the event face (the recorder's bulk drain) -------------------------
597
+ /** eachDocument's Sync twin: a sync generator over an initialized
598
+ * module (await init() first). */
599
+ export function eachDocumentSync(yaml) {
600
+ return eachDocumentCore(requireMod("eachDocumentSync"), yaml);
601
+ }
602
+
603
+ // ---- load/dump cores (shared by the async and Sync forms) --------------
604
+
605
+ function loadCore(mod, yaml, options) {
606
+ const vo = parseValidateOptions(options, "load", true);
607
+ if (!vo.armed) {
608
+ return JSON.parse(run(mod, mod._yeptris_wasm_load, yaml));
609
+ }
610
+ // validate BEFORE loading (the ruby/py law): the document only
611
+ // materializes when the walk is clean — or when collect asked for
612
+ // both, in which case the pair answers even for a dirty walk
613
+ const diags = validateWithOptions(mod, yaml, vo);
614
+ if (vo.collect) {
615
+ return { document: JSON.parse(run(mod, mod._yeptris_wasm_load, yaml)), diagnostics: diags };
616
+ }
617
+ if (diags.length > 0) {
618
+ throw new ValidationError(diags);
619
+ }
620
+ return JSON.parse(run(mod, mod._yeptris_wasm_load, yaml));
621
+ }
622
+
623
+ function loadAllCore(mod, yaml, options) {
624
+ const vo = parseValidateOptions(options, "loadAll", false);
625
+ if (vo.armed) {
626
+ // whole-stream validation BEFORE the parse (the ruby/py law): one
627
+ // walk over every document, then the materialization
628
+ const diags = validateWithOptions(mod, yaml, vo);
629
+ if (diags.length > 0) {
630
+ throw new ValidationError(diags);
631
+ }
632
+ }
633
+ return JSON.parse(run(mod, mod._yeptris_wasm_load_all, yaml));
634
+ }
635
+
636
+ function dumpCore(mod, json, options) {
637
+ const text = typeof json === "string" ? json : JSON.stringify(json);
638
+ let canonical = 0;
639
+ let lineWidth = 0; // <= 0 rides the library default (emit.h)
640
+ if (options !== undefined && options !== null) {
641
+ if (typeof options !== "object") {
642
+ throw new TypeError("yeptris: dump options must be an object");
643
+ }
644
+ for (const key of Object.keys(options)) {
645
+ if (key !== "lineWidth" && key !== "canonical") {
646
+ throw new TypeError(
647
+ `yeptris: dump option "${key}" is not supported ` +
648
+ `(the engine surface is lineWidth + canonical)`);
649
+ }
650
+ }
651
+ if (options.lineWidth !== undefined) {
652
+ const w = options.lineWidth;
653
+ if (typeof w !== "number" || !Number.isInteger(w) || w === 0 || w < -1) {
654
+ throw new TypeError(
655
+ "yeptris: dump option lineWidth must be an integer > 0 (or -1 for no folding)");
656
+ }
657
+ // -1 is js-yaml's "unlimited": the engine folds only past the
658
+ // width, so the largest width IS "never fold"
659
+ lineWidth = w === -1 ? 0x7fffffff : w;
660
+ }
661
+ if (options.canonical !== undefined) {
662
+ if (typeof options.canonical !== "boolean") {
663
+ throw new TypeError("yeptris: dump option canonical must be a boolean");
664
+ }
665
+ canonical = options.canonical ? 1 : 0;
666
+ }
667
+ }
668
+ return run(mod, mod._yeptris_wasm_dump_ex, text, canonical, lineWidth);
669
+ }
670
+
671
+ // ---- the event face (the recorder's bulk drain) ------------------------
117
672
  //
118
673
  // The engine ships three event models over the one parse: push (a
119
674
  // callback per event), pull (a StAX cursor) and the recorder (fixed
@@ -181,48 +736,23 @@ function decodeArena(u8, off, len) {
181
736
  return utf8Decoder.decode(u8.subarray(off, off + len));
182
737
  }
183
738
 
184
- /** Parse YAML text and return EVERY event of the stream as an array
185
- * of plain objects, in stream order (leptris/yeptris#886). One event
186
- * is:
187
- *
188
- * { type: "stream-start" | "stream-end" | "document-start" |
189
- * "document-end" | "sequence-start" | "sequence-end" |
190
- * "mapping-start" | "mapping-end" | "scalar" | "alias",
191
- * line, column, // 1-based start mark (0 = no position)
192
- * endLine, endColumn, // libyaml end_mark: col one past the end
193
- * value?, // scalar content; the alias NAME for alias
194
- * anchor?, tag?, // node properties, present when written
195
- * style?, // scalars: plain|single|double|literal|folded
196
- * tagId?, // scalars: the resolved kind (str|int|...)
197
- * implicit?, // scalars: plain style (the typing trigger)
198
- * flow?, // collection starts: flow context
199
- * explicit? } // document start/end: --- / ... marker seen
200
- *
201
- * Absent properties are omitted, never null. The faces of
202
- * ruby/py/rs consume the same normalized vocabulary (see
203
- * test/fixtures/events.json, whose header documents it as data).
204
- * options is accepted for call-site symmetry and reserved. Throws
205
- * YamlError on malformed input (position from the recorder's status;
206
- * its message is the generic "parse failed" — the recorder carries
207
- * status + position, not the error text). */
208
- export async function events(yaml, options) {
209
- const m = await mod();
210
- const [ptr, len] = cstr(m, yaml);
739
+ function eventsCore(mod, yaml, options) {
740
+ const [ptr, len] = cstr(mod, yaml);
211
741
  try {
212
- const st = m._yeptris_wasm_events(ptr, len);
742
+ const st = mod._yeptris_wasm_events(ptr, len);
213
743
  if (st !== 0) {
214
744
  throw new YamlError(
215
- m.UTF8ToString(m._yeptris_wasm_last_error()),
216
- m._yeptris_wasm_last_error_line(),
217
- m._yeptris_wasm_last_error_column());
745
+ mod.UTF8ToString(mod._yeptris_wasm_last_error()),
746
+ mod._yeptris_wasm_last_error_line(),
747
+ mod._yeptris_wasm_last_error_column());
218
748
  }
219
- const n = m._yeptris_wasm_event_count();
220
- const recs = m._yeptris_wasm_event_records();
221
- const arena = m._yeptris_wasm_event_arena();
749
+ const n = mod._yeptris_wasm_event_count();
750
+ const recs = mod._yeptris_wasm_event_records();
751
+ const arena = mod._yeptris_wasm_event_arena();
222
752
  // Heap views fetched AFTER the call: the feed may have grown the
223
753
  // memory, and the exported views are re-bound on growth.
224
- const u8 = m.HEAPU8;
225
- const u32 = m.HEAPU32;
754
+ const u8 = mod.HEAPU8;
755
+ const u32 = mod.HEAPU32;
226
756
  const out = new Array(n);
227
757
  for (let i = 0; i < n; i++) {
228
758
  const base = recs + i * EV_RECORD_SIZE;
@@ -270,17 +800,96 @@ export async function events(yaml, options) {
270
800
  } finally {
271
801
  // the drain is decoded: release the recorder (nothing retained
272
802
  // past this call — the answer left the heap as JS objects)
273
- m._yeptris_wasm_events_free();
803
+ mod._yeptris_wasm_events_free();
274
804
  }
275
805
  }
276
806
 
807
+ /** Parse YAML text and return the document as a JavaScript value
808
+ * (the engine's canonical JSON, JSON.parse'd). Throws YamlError with
809
+ * line/column on malformed input. A multi-document stream answers
810
+ * with the FIRST document (the engine's json contract); every
811
+ * document of a stream comes from loadAll.
812
+ *
813
+ * options arms a validation gate (the ruby/py load law: validate
814
+ * BEFORE loading) — schema: "core" | "json" | a compiled Schema,
815
+ * jsonSchema: object | string. With diagnostics present the load
816
+ * raises ValidationError carrying the whole report; with `collect:
817
+ * true` it answers `{ document, diagnostics }` instead (collect
818
+ * requires an armed gate). */
819
+ export async function load(yaml, options) {
820
+ const m = await mod();
821
+ return loadCore(m, yaml, options);
822
+ }
823
+
824
+ /** Parse a multi-document YAML stream and return EVERY document as a
825
+ * JavaScript value, in stream order (js-yaml's loadAll shape). An
826
+ * empty or comment-only stream answers []; an empty document
827
+ * ("---\n---") answers null at its position. options arms a
828
+ * whole-stream validation gate (schema:/jsonSchema:) that runs
829
+ * BEFORE the parse and raises ValidationError carrying the whole
830
+ * report (collect rides load() only). Throws YamlError with
831
+ * line/column on malformed input. */
832
+ export async function loadAll(yaml, options) {
833
+ const m = await mod();
834
+ return loadAllCore(m, yaml, options);
835
+ }
836
+
837
+ /** Parse YAML text and return the engine's canonical JSON string. */
838
+ export async function loadJSON(yaml) {
839
+ const m = await mod();
840
+ return run(m, m._yeptris_wasm_load, yaml);
841
+ }
842
+
843
+ // ---- the async entries (initialize on demand) ---------------------------
844
+
845
+ /** Parse YAML text and return EVERY event of the stream as an array
846
+ * of plain objects, in stream order (leptris/yeptris#886). One event
847
+ * is:
848
+ *
849
+ * { type: "stream-start" | "stream-end" | "document-start" |
850
+ * "document-end" | "sequence-start" | "sequence-end" |
851
+ * "mapping-start" | "mapping-end" | "scalar" | "alias",
852
+ * line, column, // 1-based start mark (0 = no position)
853
+ * endLine, endColumn, // libyaml end_mark: col one past the end
854
+ * value?, // scalar content; the alias NAME for alias
855
+ * anchor?, tag?, // node properties, present when written
856
+ * style?, // scalars: plain|single|double|literal|folded
857
+ * tagId?, // scalars: the resolved kind (str|int|...)
858
+ * implicit?, // scalars: plain style (the typing trigger)
859
+ * flow?, // collection starts: flow context
860
+ * explicit? } // document start/end: --- / ... marker seen
861
+ *
862
+ * Absent properties are omitted, never null. The faces of
863
+ * ruby/py/rs consume the same normalized vocabulary (see
864
+ * test/fixtures/events.json, whose header documents it as data).
865
+ * options is accepted for call-site symmetry and reserved. Throws
866
+ * YamlError on malformed input (position from the recorder's status;
867
+ * its message is the generic "parse failed" — the recorder carries
868
+ * status + position, not the error text). */
869
+ export async function events(yaml, options) {
870
+ const m = await mod();
871
+ return eventsCore(m, yaml, options);
872
+ }
873
+
277
874
  /** Convert JSON text (or any JSON-serializable value) to the engine's
278
- * canonical, byte-stable YAML. JSON is a subset of YAML 1.2 flow, so
279
- * the one parse engine takes it. */
280
- export async function dump(json) {
875
+ * byte-stable YAML. JSON is a subset of YAML 1.2 flow, so the one
876
+ * parse engine takes it.
877
+ *
878
+ * options (js-yaml parity names over emit.h's yeptris_emit_options):
879
+ * lineWidth — fold flow collections once the current line exceeds
880
+ * this column (the engine's best_width). Default: the engine
881
+ * default (80); -1 disables folding.
882
+ * canonical — the engine's fixed form: flow collections, quoted
883
+ * strings, typed words, shortest floats — a parse of the output
884
+ * re-serializes byte-identically. Default: false.
885
+ *
886
+ * `indent` and `flowLevel` have no engine option (the block indent is
887
+ * fixed at 2; there is no flow-level override) — they are not accepted
888
+ * here rather than silently ignored. Throws TypeError on a mistyped
889
+ * known option; throws YamlError on malformed JSON input. */
890
+ export async function dump(json, options) {
281
891
  const m = await mod();
282
- const text = typeof json === "string" ? json : JSON.stringify(json);
283
- return run(m, m._yeptris_wasm_dump, text);
892
+ return dumpCore(m, json, options);
284
893
  }
285
894
 
286
895
  /** The libyeptris version string. */
@@ -289,6 +898,63 @@ export async function version() {
289
898
  return m.UTF8ToString(m._yeptris_wasm_version());
290
899
  }
291
900
 
901
+ // ---- the Sync entries (usable once the module is initialized) ----------
902
+ //
903
+ // The wasm executes synchronously; every async form is async only
904
+ // because the FIRST call may initialize the module. After one await
905
+ // (init(), or any async call) the same bodies run synchronously. Each
906
+ // Sync twin refuses to run uninitialized — the lazy import is an
907
+ // async door and half-initializing it would be a lie — and names the
908
+ // way out in the error.
909
+
910
+ /** Parse YAML text (load's Sync twin). Throws unless the module is
911
+ * initialized (await init() first). */
912
+ export function loadSync(yaml, options) {
913
+ return loadCore(requireMod("loadSync"), yaml, options);
914
+ }
915
+
916
+ /** loadAll's Sync twin. Throws unless the module is initialized. */
917
+ export function loadAllSync(yaml, options) {
918
+ return loadAllCore(requireMod("loadAllSync"), yaml, options);
919
+ }
920
+
921
+ /** loadJSON's Sync twin. Throws unless the module is initialized. */
922
+ export function loadJSONSync(yaml) {
923
+ return run(requireMod("loadJSONSync"), cached._yeptris_wasm_load, yaml);
924
+ }
925
+
926
+ /** events' Sync twin. Throws unless the module is initialized. */
927
+ export function eventsSync(yaml, options) {
928
+ return eventsCore(requireMod("eventsSync"), yaml, options);
929
+ }
930
+
931
+ /** dump's Sync twin. Throws unless the module is initialized. */
932
+ export function dumpSync(json, options) {
933
+ return dumpCore(requireMod("dumpSync"), json, options);
934
+ }
935
+
936
+ /** validate's Sync twin. Throws unless the module is initialized. */
937
+ export function validateSync(input, options) {
938
+ return validateWithOptions(
939
+ requireMod("validateSync"), input, parseValidateOptions(options, "validate", false));
940
+ }
941
+
942
+ /** isValid's Sync twin. Throws unless the module is initialized. */
943
+ export function isValidSync(input, options) {
944
+ return validateSync(input, options).length === 0;
945
+ }
946
+
947
+ /** compileSchema's Sync twin. Throws unless the module is initialized. */
948
+ export function compileSchemaSync(jsonSchema) {
949
+ return compileSchemaCore(requireMod("compileSchemaSync"), jsonSchema);
950
+ }
951
+
952
+ /** version's Sync twin. Throws unless the module is initialized. */
953
+ export function versionSync() {
954
+ const m = requireMod("versionSync");
955
+ return m.UTF8ToString(m._yeptris_wasm_version());
956
+ }
957
+
292
958
  /** The wasm module instance this package caches (diagnostics:
293
959
  * heap/memory inspection, the engine's raw exports). The load/dump
294
960
  * calls all share this one instance. */