@orkestrel/contract 0.0.20 → 0.0.22

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.
@@ -1,5 +1,51 @@
1
1
  // src/core/constants.ts
2
2
  /**
3
+ * Lists the fields recognized for every contract declaration category, frozen.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * SHAPE_FIELDS.shape // ['description']
8
+ * ```
9
+ */
10
+ var SHAPE_FIELDS = Object.freeze({
11
+ string: Object.freeze([
12
+ "min",
13
+ "max",
14
+ "pattern",
15
+ "description"
16
+ ]),
17
+ number: Object.freeze([
18
+ "integer",
19
+ "min",
20
+ "max",
21
+ "description"
22
+ ]),
23
+ boolean: Object.freeze(["description"]),
24
+ null: Object.freeze(["description"]),
25
+ literal: Object.freeze(["values", "description"]),
26
+ array: Object.freeze([
27
+ "items",
28
+ "min",
29
+ "max",
30
+ "description"
31
+ ]),
32
+ object: Object.freeze([
33
+ "properties",
34
+ "additionalProperties",
35
+ "description"
36
+ ]),
37
+ union: Object.freeze([
38
+ "variants",
39
+ "mode",
40
+ "description"
41
+ ]),
42
+ optional: Object.freeze(["inner", "default"]),
43
+ nullable: Object.freeze(["inner"]),
44
+ json: Object.freeze(["description"]),
45
+ raw: Object.freeze(["schema"]),
46
+ shape: Object.freeze(["description"])
47
+ });
48
+ /**
3
49
  * Holds the registry-global key used to recognize {@link ContractError} values
4
50
  * across package copies.
5
51
  *
@@ -9,7 +55,7 @@
9
55
  * own. The registry makes the key discoverable; it is a recognition mechanism,
10
56
  * not an unforgeable provenance marker.
11
57
  */
12
- var CONTRACT_ERROR_BRAND = Symbol.for("@orkestrel/contract.error");
58
+ var CONTRACT_ERROR_BRAND = Symbol.for("@orkestrel/contract.ContractError");
13
59
  /**
14
60
  * Captures every host operation this package dispatches through, while this
15
61
  * module evaluates.
@@ -295,6 +341,48 @@ var JSON_SCHEMA_TYPES = Object.freeze([
295
341
  "string"
296
342
  ]);
297
343
  /**
344
+ * Lists the JSON Schema keywords a strict `schemaToShape` conversion reads, frozen.
345
+ *
346
+ * @remarks
347
+ * The keywords a shape can honour, plus the annotations that assert nothing and so
348
+ * lose nothing when a shape drops them: `title`, `$schema`, `$id`, `$comment`,
349
+ * `examples`, `deprecated`, `readOnly`, and `writeOnly`. Every other keyword refuses.
350
+ * `pattern` and `format` are absent because no compiled shape asserts them, so a
351
+ * schema holding one would convert to a shape wider than the schema it came from.
352
+ *
353
+ * @example
354
+ * ```ts
355
+ * STRICT_SCHEMA_KEYWORDS.includes('title') // true
356
+ * STRICT_SCHEMA_KEYWORDS.includes('pattern') // false
357
+ * ```
358
+ */
359
+ var STRICT_SCHEMA_KEYWORDS = Object.freeze([
360
+ "type",
361
+ "title",
362
+ "description",
363
+ "$schema",
364
+ "$id",
365
+ "$comment",
366
+ "examples",
367
+ "deprecated",
368
+ "readOnly",
369
+ "writeOnly",
370
+ "default",
371
+ "enum",
372
+ "minLength",
373
+ "maxLength",
374
+ "minimum",
375
+ "maximum",
376
+ "minItems",
377
+ "maxItems",
378
+ "items",
379
+ "properties",
380
+ "required",
381
+ "additionalProperties",
382
+ "anyOf",
383
+ "oneOf"
384
+ ]);
385
+ /**
298
386
  * Lists every declared {@link ContractCode} refusal category, frozen.
299
387
  *
300
388
  * @remarks
@@ -328,6 +416,47 @@ var CONTRACT_CODES = Object.freeze([
328
416
  "expansion"
329
417
  ]);
330
418
  /**
419
+ * Lists every {@link FaultKind}, frozen.
420
+ *
421
+ * @remarks
422
+ * The runtime source of truth for the vocabulary, which {@link isFault} reads.
423
+ *
424
+ * @example
425
+ * ```ts
426
+ * FAULT_KINDS.includes('string') // true
427
+ * ```
428
+ */
429
+ var FAULT_KINDS = Object.freeze([
430
+ "string",
431
+ "number",
432
+ "integer",
433
+ "boolean",
434
+ "null",
435
+ "literal",
436
+ "array",
437
+ "object",
438
+ "union",
439
+ "json",
440
+ "shape"
441
+ ]);
442
+ /**
443
+ * Lists every {@link FaultConstraint}, frozen.
444
+ *
445
+ * @remarks
446
+ * The runtime source of truth for the vocabulary, which {@link isFault} reads.
447
+ *
448
+ * @example
449
+ * ```ts
450
+ * FAULT_CONSTRAINTS.includes('min') // true
451
+ * ```
452
+ */
453
+ var FAULT_CONSTRAINTS = Object.freeze([
454
+ "min",
455
+ "max",
456
+ "pattern",
457
+ "integer"
458
+ ]);
459
+ /**
331
460
  * Caps at `64` the number of {@link Fault} / {@link AuditFault} entries a single
332
461
  * `explain` or `audit` report ever returns, frozen.
333
462
  *
@@ -547,6 +676,77 @@ var FORMAT_PATTERNS = Object.freeze({
547
676
  email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
548
677
  uri: /^[a-z][a-z0-9+.-]*:\/\//i
549
678
  });
679
+ /**
680
+ * Caps at `1024` the number of choices one schema field may offer, frozen.
681
+ *
682
+ * @remarks
683
+ * A retention limit that a declaring package, such as a form or table schema
684
+ * package, enforces; this package enforces none of the retention limits itself.
685
+ *
686
+ * @example
687
+ * ```ts
688
+ * CHOICE_LIMIT // 1024
689
+ * ```
690
+ */
691
+ var CHOICE_LIMIT = 1024;
692
+ /**
693
+ * Caps at `128` the length, in UTF-16 code units, of one name a schema declares, frozen:
694
+ * a schema, group, or field name, or a column key.
695
+ *
696
+ * @remarks
697
+ * A retention limit that a declaring package enforces, as {@link CHOICE_LIMIT} states.
698
+ *
699
+ * @example
700
+ * ```ts
701
+ * NAME_LIMIT // 128
702
+ * ```
703
+ */
704
+ var NAME_LIMIT = 128;
705
+ /**
706
+ * Caps at `65536` the length, in UTF-16 code units, of any single string one schema
707
+ * retains, frozen.
708
+ *
709
+ * @remarks
710
+ * A retention limit that a declaring package enforces, as {@link CHOICE_LIMIT} states.
711
+ *
712
+ * @example
713
+ * ```ts
714
+ * STRING_LIMIT // 65536
715
+ * ```
716
+ */
717
+ var STRING_LIMIT = 65536;
718
+ /**
719
+ * Caps at `1048576` the total length, in UTF-16 code units, of every string one schema
720
+ * retains, frozen.
721
+ *
722
+ * @remarks
723
+ * A retention limit that a declaring package enforces, as {@link CHOICE_LIMIT} states.
724
+ *
725
+ * @example
726
+ * ```ts
727
+ * TEXT_LIMIT // 1048576
728
+ * ```
729
+ */
730
+ var TEXT_LIMIT = 1048576;
731
+ /**
732
+ * Caps at `16384` the total number of records, arrays, and leaves one schema retains,
733
+ * frozen.
734
+ *
735
+ * @remarks
736
+ * A retention limit that a declaring package enforces, as {@link CHOICE_LIMIT} states.
737
+ *
738
+ * @example
739
+ * ```ts
740
+ * NODE_LIMIT // 16384
741
+ * ```
742
+ */
743
+ var NODE_LIMIT = 16384;
744
+ /** Caps a fault message at 2048 UTF-16 code units. */
745
+ var FAULT_TEXT_LIMIT = 2048;
746
+ /** Caps the keys or literal candidates named in a fault line. */
747
+ var FAULT_LIST_LIMIT = 12;
748
+ /** Caps a schema summary's UTF-16 code units. */
749
+ var FAULT_SCHEMA_LIMIT = 160;
550
750
  // src/core/errors.ts
551
751
  /**
552
752
  * Carries a machine-readable contract category, optional context, and an exact optional
@@ -1197,6 +1397,103 @@ function isObject(value) {
1197
1397
  function isRecord(value) {
1198
1398
  return holds(() => matchesRecordBrand(value));
1199
1399
  }
1400
+ /**
1401
+ * Determines whether a value is the {@link FieldPath} a fault carries: a key, or a dense list of keys.
1402
+ *
1403
+ * @param value - The value to inspect
1404
+ * @returns True if the value is a string or a dense array of strings; false otherwise
1405
+ *
1406
+ * @example
1407
+ * ```ts
1408
+ * isFaultPath(['user', 'name']) // true
1409
+ * isFaultPath([1]) // false
1410
+ * ```
1411
+ */
1412
+ function isFaultPath(value) {
1413
+ if (isString(value)) return true;
1414
+ return holds(() => {
1415
+ if (!isArray(value)) return false;
1416
+ const snapshot = readArrayEntries(value);
1417
+ if (isFailure(snapshot) || !snapshot.value.dense) return false;
1418
+ return !INTRINSICS.reflect.apply(INTRINSICS.some, snapshot.value.entries, [(entry) => !isString(entry)]);
1419
+ });
1420
+ }
1421
+ /**
1422
+ * Determines whether a value is exactly one {@link Fault}.
1423
+ *
1424
+ * @remarks
1425
+ * A closed reading of the union: each reason's required fields, each with its own
1426
+ * vocabulary, and no other key, so `{}` and a fault carrying a stray field both answer
1427
+ * `false`. An undeclared-key fault is an {@link AuditFault} and answers `false` here.
1428
+ *
1429
+ * @param value - The value to inspect
1430
+ * @returns True if the value is a well-formed fault; false otherwise
1431
+ *
1432
+ * @example
1433
+ * ```ts
1434
+ * isFault({ reason: 'missing', path: ['a'], expected: 'string' }) // true
1435
+ * isFault({}) // false
1436
+ * ```
1437
+ */
1438
+ function isFault(value) {
1439
+ return holds(() => {
1440
+ if (!isRecord(value) || !isFaultPath(value.path)) return false;
1441
+ const kind = INTRINSICS.reflect.apply(INTRINSICS.some, FAULT_KINDS, [(entry) => entry === value.expected]);
1442
+ const named = INTRINSICS.own(value, "key") || INTRINSICS.own(value, "expected");
1443
+ const list = readArrayEntries(isArray(value.expected) ? value.expected : [void 0]);
1444
+ const hinted = !named || isString(value.key) && !isFailure(list) && list.value.dense && !INTRINSICS.reflect.apply(INTRINSICS.some, list.value.entries, [(entry) => !isLiteralValue(entry) || isNumber(entry) && !isFiniteNumber(entry)]);
1445
+ switch (value.reason) {
1446
+ case "type": return kind && isString(value.received) && matchesExactKeys(value, [
1447
+ "reason",
1448
+ "path",
1449
+ "expected",
1450
+ "received"
1451
+ ]);
1452
+ case "missing": return kind && matchesExactKeys(value, [
1453
+ "reason",
1454
+ "path",
1455
+ "expected"
1456
+ ]);
1457
+ case "constraint": return kind && isString(value.received) && INTRINSICS.reflect.apply(INTRINSICS.some, FAULT_CONSTRAINTS, [(entry) => entry === value.constraint]) && (!INTRINSICS.own(value, "limit") || isFiniteNumber(value.limit) || isString(value.limit)) && matchesExactKeys(value, [
1458
+ "reason",
1459
+ "path",
1460
+ "expected",
1461
+ "constraint",
1462
+ "received"
1463
+ ], ["limit"]);
1464
+ case "variant": return isNonNegativeInteger(value.variants) && hinted && matchesExactKeys(value, [
1465
+ "reason",
1466
+ "path",
1467
+ "variants"
1468
+ ], named ? ["key", "expected"] : []);
1469
+ case "oneOf": return isNonNegativeInteger(value.matched) && hinted && matchesExactKeys(value, [
1470
+ "reason",
1471
+ "path",
1472
+ "matched"
1473
+ ], named ? ["key", "expected"] : []);
1474
+ default: return false;
1475
+ }
1476
+ });
1477
+ }
1478
+ /**
1479
+ * Determines whether a value is exactly one {@link AuditFault}.
1480
+ *
1481
+ * @remarks
1482
+ * Every {@link Fault}, and the undeclared-key fault an audit adds.
1483
+ *
1484
+ * @param value - The value to inspect
1485
+ * @returns True if the value is a well-formed audit fault; false otherwise
1486
+ *
1487
+ * @example
1488
+ * ```ts
1489
+ * isAuditFault({ reason: 'extra', path: ['a'] }) // true
1490
+ * isAuditFault({}) // false
1491
+ * ```
1492
+ */
1493
+ function isAuditFault(value) {
1494
+ if (isFault(value)) return true;
1495
+ return holds(() => isRecord(value) && value.reason === "extra" && isFaultPath(value.path) && matchesExactKeys(value, ["reason", "path"]));
1496
+ }
1200
1497
  /** Determines whether a value is a `Map`.
1201
1498
  *
1202
1499
  * @param value - The value to inspect
@@ -1840,6 +2137,126 @@ function isJSONPrimitive(value) {
1840
2137
  }
1841
2138
  // src/core/helpers.ts
1842
2139
  /**
2140
+ * Admits a stable readable value with only lossless repairs and returns the parser's value.
2141
+ *
2142
+ * @remarks
2143
+ * Reads must remain stable across artifacts. Guard-valid input skips both reports and parses
2144
+ * once. Repairs use audit, parse once, and explain only on parse failure. Unresolved unions,
2145
+ * extras, lossy repairs, and a capped audit refuse. An own optional undefined field omitted or
2146
+ * filled by its declared default is not a repair. The result preserves parser ownership, including union input identity.
2147
+ * A read failure returns its cause rather than throwing.
2148
+ * Snapshot a foreign object before admission, as Tool.execute does. A getter changing between
2149
+ * is and parse can publish a value that no recorded repair describes. A shallow snapshot only
2150
+ * stabilizes its own level; nested foreign values must also provide stable reads.
2151
+ *
2152
+ * @example
2153
+ * ```ts
2154
+ * admitValue(createContract(numberShape()), '3') // success carrying 3 and its type repair
2155
+ * ```
2156
+ */
2157
+ function admitValue(contract, value) {
2158
+ try {
2159
+ if (contract.is(value)) {
2160
+ const parsed = contract.parse(value);
2161
+ if (parsed === void 0 && value !== void 0) return failure({ faults: [] });
2162
+ return success({
2163
+ value: parsed === void 0 ? value : parsed,
2164
+ repairs: []
2165
+ });
2166
+ }
2167
+ const audited = contract.audit(value);
2168
+ const parsed = contract.parse(value);
2169
+ const explained = parsed === void 0 ? contract.explain(value) : [];
2170
+ const repairs = audited.filter((fault) => matchesLosslessRepair(fault, value, parsed));
2171
+ const refused = audited.filter((fault) => !repairs.includes(fault) && !matchesUndefinedField(fault, value, parsed));
2172
+ const merged = [...explained, ...refused];
2173
+ const faults = [...new Map(merged.map((fault) => [JSON.stringify([fault.reason, extractPath(fault)]), fault])).values()];
2174
+ const covers = faults.filter((fault) => fault.reason === "variant" || fault.reason === "oneOf").map((fault) => extractPath(fault));
2175
+ const uncovered = faults.filter((fault) => {
2176
+ const path = extractPath(fault);
2177
+ const room = fault.reason === "variant" || fault.reason === "oneOf" ? 1 : 0;
2178
+ return !covers.some((cover) => cover.length + room <= path.length && cover.every((segment, index) => segment === path[index]));
2179
+ });
2180
+ if (uncovered.length > 0) return failure({ faults: limitEntries(uncovered, 64) });
2181
+ if (audited.length >= 64) return failure({ faults: limitEntries(audited, 64) });
2182
+ if (parsed === void 0) return failure({ faults: limitEntries(audited, 64) });
2183
+ return success({
2184
+ value: parsed,
2185
+ repairs
2186
+ });
2187
+ } catch (cause) {
2188
+ return failure({
2189
+ faults: [],
2190
+ cause
2191
+ });
2192
+ }
2193
+ }
2194
+ /**
2195
+ * Checks whether a type fault describes an own undefined field omitted or defaulted by a successful parse.
2196
+ *
2197
+ * @remarks
2198
+ * Reads own members directly so absence and an unreadable member cannot stand for undefined.
2199
+ * A compiled parser fills an undefined field only through its declared default; it never coerces it.
2200
+ * Required reads propagate their cause to the admission boundary.
2201
+ *
2202
+ * @example
2203
+ * ```ts
2204
+ * matchesUndefinedField({ reason: 'type', path: ['note'], expected: 'string', received: 'undefined' }, { note: undefined }, {}) // true
2205
+ * ```
2206
+ */
2207
+ function matchesUndefinedField(fault, value, parsed) {
2208
+ if (fault.reason !== "type" || parsed === void 0) return false;
2209
+ const path = extractPath(fault);
2210
+ const key = path.at(-1);
2211
+ if (key === void 0) return false;
2212
+ const [raw, result] = path.slice(0, -1).reduce(([raw, result], segment) => [isObject(raw) && INTRINSICS.own(raw, segment) ? INTRINSICS.reflect.read(raw, segment) : void 0, isObject(result) && INTRINSICS.own(result, segment) ? INTRINSICS.reflect.read(result, segment) : void 0], [value, parsed]);
2213
+ return isObject(raw) && INTRINSICS.own(raw, key) && INTRINSICS.reflect.read(raw, key) === void 0 && isObject(result);
2214
+ }
2215
+ /**
2216
+ * Truncates text to a UTF-16 budget without splitting a surrogate pair.
2217
+ *
2218
+ * @example
2219
+ * ```ts
2220
+ * truncateFaultText('abcdef', 4) // 'abc…'
2221
+ * ```
2222
+ */
2223
+ function truncateFaultText(text, limit) {
2224
+ if (limit <= 0) return "";
2225
+ if (text.length <= limit) return text;
2226
+ return `${text.slice(0, limit - 1).replace(/[\uD800-\uDBFF]$/u, "")}…`;
2227
+ }
2228
+ /**
2229
+ * Describes bounded faults with encoded values and a schema-derived correction summary.
2230
+ *
2231
+ * @remarks
2232
+ * Default: 2048 UTF-16 code units. A smaller non-negative integer limit reserves a caller's
2233
+ * heading budget. The report reserves room for omitted-fault and cap notices, and ends with a
2234
+ * send summary when a schema is supplied. Untrusted names, descriptions, and strings use preview.
2235
+ *
2236
+ * @example
2237
+ * ```ts
2238
+ * describeFaults([{ reason: 'missing', path: ['age'], expected: 'number' }])
2239
+ * // 'age: missing; expected number'
2240
+ * ```
2241
+ */
2242
+ function describeFaults(faults, schema, options) {
2243
+ const requested = options?.limit ?? 2048;
2244
+ if (!isInteger(requested) || requested < 0) throw new ContractError("Fault text limit must be a non-negative integer", { code: "range" });
2245
+ const limit = Math.min(requested, FAULT_TEXT_LIMIT);
2246
+ const send = schema === void 0 ? "" : `send ${renderForm(schema, Math.min(160, Math.floor(limit / 3)))}`;
2247
+ const lines = limitEntries(faults, 64).map((fault) => describeFaultLine(fault, schema ?? {}));
2248
+ const room = Math.max(0, limit - send.length - 82);
2249
+ const kept = lines.filter((_, index) => lines.slice(0, index + 1).join("\n").length <= room);
2250
+ const hidden = faults.length - kept.length;
2251
+ const note = [...hidden > 0 ? [`and ${String(hidden)} more faults`] : [], ...faults.length >= 64 ? [`the report stops at ${String(64)}`] : []].join(", ");
2252
+ return truncateFaultText([
2253
+ ...kept,
2254
+ ...kept.length === 0 && lines.length > 0 && room > 0 ? [truncateFaultText(lines[0] ?? "", room)] : [],
2255
+ ...note.length === 0 ? [] : [note],
2256
+ ...send.length === 0 ? [] : [send]
2257
+ ].join("\n"), limit);
2258
+ }
2259
+ /**
1843
2260
  * Iterates indices while rereading the upper bound before every step.
1844
2261
  *
1845
2262
  * @remarks
@@ -1997,10 +2414,10 @@ function limitEntries(entries, limit) {
1997
2414
  *
1998
2415
  * @example
1999
2416
  * ```ts
2000
- * compareValues('a', 'b') // -1
2417
+ * comparePrimitives('a', 'b') // -1
2001
2418
  * ```
2002
2419
  */
2003
- function compareValues(left, right) {
2420
+ function comparePrimitives(left, right) {
2004
2421
  return left < right ? -1 : left > right ? 1 : 0;
2005
2422
  }
2006
2423
  /**
@@ -2014,7 +2431,7 @@ function compareValues(left, right) {
2014
2431
  * `valueToSchema({ b: 1, a: 2 })` publish `{"type":"object","additionalProperties":false}`
2015
2432
  * — a successful answer with the caller's properties silently gone. The copy is
2016
2433
  * taken first so a caller-owned array is never reordered in place, and the order
2017
- * is decided by {@link compareValues}, whose `<` / `>` comparison dispatches
2434
+ * is decided by {@link comparePrimitives}, whose `<` / `>` comparison dispatches
2018
2435
  * through nothing.
2019
2436
  *
2020
2437
  * @param values - The keys or indices to order
@@ -2028,7 +2445,7 @@ function compareValues(left, right) {
2028
2445
  function sortValues(values) {
2029
2446
  const observed = INTRINSICS.from(iterateIndices(() => values.length), (index) => values[index]);
2030
2447
  const owned = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(value) => value !== void 0]);
2031
- INTRINSICS.reflect.apply(INTRINSICS.order, owned, [compareValues]);
2448
+ INTRINSICS.reflect.apply(INTRINSICS.order, owned, [comparePrimitives]);
2032
2449
  return owned;
2033
2450
  }
2034
2451
  /**
@@ -2272,7 +2689,7 @@ function readSampleMemo(memo, reader) {
2272
2689
  *
2273
2690
  * @remarks
2274
2691
  * Extracted rather than written inline for the same reason
2275
- * {@link compareValues} is: `Reflect.apply` takes its arguments as a LIST, so an
2692
+ * {@link comparePrimitives} is: `Reflect.apply` takes its arguments as a LIST, so an
2276
2693
  * inline collector is a function expression inside an array literal rather than
2277
2694
  * one passed directly as an argument — a hidden function assignment this
2278
2695
  * repository forbids wherever it appears. Returned directly from a factory it is
@@ -2422,6 +2839,133 @@ function matchesPattern(pattern, value) {
2422
2839
  return INTRINSICS.reflect.apply(INTRINSICS.captures, pattern, [value]) !== null;
2423
2840
  }
2424
2841
  /**
2842
+ * Checks whether a string's length in code points falls within optional bounds.
2843
+ *
2844
+ * @remarks
2845
+ * Counts what JSON Schema's `minLength` and `maxLength` count: a surrogate pair is
2846
+ * one, and a lone surrogate is one. A string holds at most `.length` code points and
2847
+ * at least half that, so `.length` decides every bound it can with no count. The
2848
+ * count runs only where a bound sits between those two figures, which limits its
2849
+ * work to about twice the bound rather than to the size of the string.
2850
+ *
2851
+ * @param value - The string to measure
2852
+ * @param min - The inclusive lower bound, when there is one
2853
+ * @param max - The inclusive upper bound, when there is one
2854
+ * @returns True if the code-point count is within every present bound; false otherwise
2855
+ *
2856
+ * @example
2857
+ * ```ts
2858
+ * matchesStringLength('😀😀', undefined, 2) // true
2859
+ * matchesStringLength('😀', 2, undefined) // false
2860
+ * ```
2861
+ */
2862
+ function matchesStringLength(value, min, max) {
2863
+ const length = value.length;
2864
+ if (min !== void 0 && length < min) return false;
2865
+ if (max !== void 0 && length > 2 * max) return false;
2866
+ if ((min === void 0 || INTRINSICS.ceil(length / 2) >= min) && (max === void 0 || length <= max)) return true;
2867
+ const points = length - computeSurrogatePairs(value, length - (min === void 0 ? max ?? 0 : min - 1));
2868
+ return (min === void 0 || points >= min) && (max === void 0 || points <= max);
2869
+ }
2870
+ /**
2871
+ * Counts the surrogate pairs in a string, stopping at a limit.
2872
+ *
2873
+ * @remarks
2874
+ * A regular-expression literal builds a fresh `RegExp` per evaluation, so this call
2875
+ * owns the `lastIndex` that is its cursor, and the captured `exec` reads the internal
2876
+ * slots and no member a caller can replace. Text with no surrogate costs one native
2877
+ * scan, and a string of pairs costs one `exec` per pair up to the limit.
2878
+ *
2879
+ * @param value - The string to scan
2880
+ * @param limit - The count to stop at
2881
+ * @returns The number of surrogate pairs, or `limit` when the string holds at least that many
2882
+ *
2883
+ * @example
2884
+ * ```ts
2885
+ * computeSurrogatePairs('😀a😀', 8) // 2
2886
+ * computeSurrogatePairs('😀😀😀', 2) // 2
2887
+ * ```
2888
+ */
2889
+ function computeSurrogatePairs(value, limit) {
2890
+ const pair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
2891
+ const steps = limit > 0 ? INTRINSICS.ceil(limit) : 0;
2892
+ for (const step of iterateIndices(() => steps)) if (INTRINSICS.reflect.apply(INTRINSICS.captures, pair, [value]) === null) return step;
2893
+ return steps;
2894
+ }
2895
+ /**
2896
+ * Refuses an options record that holds a key its builder does not read.
2897
+ *
2898
+ * @remarks
2899
+ * The door for an option that decides what a contract accepts, where a misspelled key
2900
+ * would otherwise read as an absent option and fail open. It looks at own enumerable
2901
+ * string keys, so an inherited or symbol-keyed member is not a misspelling.
2902
+ *
2903
+ * @param source - The builder options, when there are any
2904
+ * @param keys - The keys that builder reads
2905
+ * @param builder - The builder name used in the refusal
2906
+ * @param shape - The shape category used in structured error context
2907
+ * @throws {ContractError} When the record holds any other key
2908
+ *
2909
+ * @example
2910
+ * ```ts
2911
+ * refuseOptionKeys({ strict: true }, ['strict'], 'schemaToShape', 'schema') // returns
2912
+ * refuseOptionKeys({ strct: true }, ['strict'], 'schemaToShape', 'schema') // throws
2913
+ * ```
2914
+ */
2915
+ function refuseOptionKeys(source, keys, builder, shape) {
2916
+ if (source === void 0) return;
2917
+ const first = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(INTRINSICS.keys(source)), [(key) => !INTRINSICS.reflect.apply(INTRINSICS.some, keys, [(name) => name === key])])[0];
2918
+ if (first === void 0) return;
2919
+ const known = INTRINSICS.reflect.apply(INTRINSICS.join, keys, [", "]);
2920
+ throw new ContractError(`${builder}: unknown option ${preview(first)}; the options are ${known}`, {
2921
+ code: "structure",
2922
+ context: {
2923
+ path: [first],
2924
+ shape
2925
+ }
2926
+ });
2927
+ }
2928
+ /**
2929
+ * Escapes every regular-expression metacharacter in a text, so the text
2930
+ * matches literally inside a larger `RegExp` source.
2931
+ *
2932
+ * @remarks
2933
+ * Prefixes each of `\ ^ $ . * + ? ( ) [ ] { } |` with a backslash and leaves
2934
+ * every other character, `-` and `/` included, unchanged; the empty string
2935
+ * returns unchanged. The escape is an INDEXED character map rather than
2936
+ * `String.prototype.replace`, which dispatches through the caller-writable
2937
+ * `RegExp.prototype[Symbol.replace]` and `exec` members.
2938
+ *
2939
+ * @param value - The literal text to escape
2940
+ * @returns The text with every metacharacter backslash-escaped
2941
+ *
2942
+ * @example
2943
+ * ```ts
2944
+ * escapeRegExp('a.b*c') // 'a\\.b\\*c'
2945
+ * new RegExp(`^${escapeRegExp('a.b')}$`).test('axb') // false
2946
+ * ```
2947
+ */
2948
+ function escapeRegExp(value) {
2949
+ const metacharacters = collectMembers([
2950
+ "\\",
2951
+ "^",
2952
+ "$",
2953
+ ".",
2954
+ "*",
2955
+ "+",
2956
+ "?",
2957
+ "(",
2958
+ ")",
2959
+ "[",
2960
+ "]",
2961
+ "{",
2962
+ "}",
2963
+ "|"
2964
+ ]);
2965
+ const characters = INTRINSICS.from(iterateIndices(() => value.length), (index) => matchesMember(metacharacters, value[index]) ? `\\${value[index]}` : value[index]);
2966
+ return INTRINSICS.reflect.apply(INTRINSICS.join, characters, [""]);
2967
+ }
2968
+ /**
2425
2969
  * Rebuilds a caller's regular expression as a stateless pattern this package
2426
2970
  * owns.
2427
2971
  *
@@ -2547,6 +3091,68 @@ function pinMembers(prototype, owner) {
2547
3091
  }
2548
3092
  }
2549
3093
  /**
3094
+ * Boxes a value as the {@link Success} branch of a {@link Result}.
3095
+ *
3096
+ * @param value - The value to box, retained exactly
3097
+ * @returns A fresh `{ success: true, value }` record
3098
+ *
3099
+ * @example
3100
+ * ```ts
3101
+ * success(42) // { success: true, value: 42 }
3102
+ * ```
3103
+ */
3104
+ function success(value) {
3105
+ return {
3106
+ success: true,
3107
+ value
3108
+ };
3109
+ }
3110
+ /**
3111
+ * Boxes an error as the {@link Failure} branch of a {@link Result}.
3112
+ *
3113
+ * @param error - The error to box, retained exactly
3114
+ * @returns A fresh `{ success: false, error }` record
3115
+ *
3116
+ * @example
3117
+ * ```ts
3118
+ * failure('offline') // { success: false, error: 'offline' }
3119
+ * ```
3120
+ */
3121
+ function failure(error) {
3122
+ return {
3123
+ success: false,
3124
+ error
3125
+ };
3126
+ }
3127
+ /**
3128
+ * Narrows a {@link Result} to its {@link Success} branch.
3129
+ *
3130
+ * @param result - The result to narrow
3131
+ * @returns True if the result succeeded; false otherwise
3132
+ *
3133
+ * @example
3134
+ * ```ts
3135
+ * isSuccess(success(1)) // true
3136
+ * ```
3137
+ */
3138
+ function isSuccess(result) {
3139
+ return result.success;
3140
+ }
3141
+ /**
3142
+ * Narrows a {@link Result} to its {@link Failure} branch.
3143
+ *
3144
+ * @param result - The result to narrow
3145
+ * @returns True if the result failed; false otherwise
3146
+ *
3147
+ * @example
3148
+ * ```ts
3149
+ * isFailure(failure('offline')) // true
3150
+ * ```
3151
+ */
3152
+ function isFailure(result) {
3153
+ return !result.success;
3154
+ }
3155
+ /**
2550
3156
  * Invokes a callback once and synchronously captures its exact outcome as a
2551
3157
  * {@link Result}.
2552
3158
  *
@@ -2574,23 +3180,42 @@ function pinMembers(prototype, owner) {
2574
3180
  * @example
2575
3181
  * ```ts
2576
3182
  * const outcome = attempt(() => predicate(value))
2577
- * return outcome.success && outcome.value
3183
+ * return isSuccess(outcome) && outcome.value
2578
3184
  * ```
2579
3185
  */
2580
3186
  function attempt(callback) {
2581
3187
  try {
2582
- return {
2583
- success: true,
2584
- value: callback()
2585
- };
3188
+ return success(callback());
2586
3189
  } catch (error) {
2587
- return {
2588
- success: false,
2589
- error
2590
- };
3190
+ return failure(error);
2591
3191
  }
2592
3192
  }
2593
3193
  /**
3194
+ * Renders a thrown value as a non-empty message.
3195
+ *
3196
+ * @remarks
3197
+ * Reads an `Error`'s `message` and converts any other value with the `String`
3198
+ * function {@link INTRINSICS} captured at load, so a symbol renders as
3199
+ * `Symbol(description)` and a caller that replaces the global `String` does not
3200
+ * change the result. Returns `'unknown failure'` when
3201
+ * that read throws, as a throwing `message` getter or `toString` method does,
3202
+ * when an `Error`'s `message` is not a string, and when the rendered text is
3203
+ * empty. Never throws.
3204
+ *
3205
+ * @param error - The caught value, of any shape
3206
+ * @returns The rendered message, never empty
3207
+ *
3208
+ * @example
3209
+ * ```ts
3210
+ * errorToMessage(new Error('boom')) // 'boom'
3211
+ * errorToMessage('') // 'unknown failure'
3212
+ * ```
3213
+ */
3214
+ function errorToMessage(error) {
3215
+ const read = attempt(() => isError(error) ? error.message : INTRINSICS.text(error));
3216
+ return isSuccess(read) && isString(read.value) && read.value.length > 0 ? read.value : "unknown failure";
3217
+ }
3218
+ /**
2594
3219
  * Reads a value through the shared containment boundary or refuses it with the
2595
3220
  * contract module's uniform read diagnostic.
2596
3221
  *
@@ -2626,7 +3251,7 @@ function readValue(callback, reader, options) {
2626
3251
  };
2627
3252
  const requested = options?.code;
2628
3253
  const subject = options?.subject;
2629
- const code = requested !== void 0 && matchesMember(collectMembers(CONTRACT_CODES), requested) ? requested : "structure";
3254
+ const code = requested !== void 0 && INTRINSICS.reflect.apply(INTRINSICS.some, CONTRACT_CODES, [(known) => known === requested]) ? requested : "structure";
2630
3255
  return {
2631
3256
  reader: isString(reader) ? reader : "readValue",
2632
3257
  subject: isString(subject) ? subject : "value",
@@ -2634,12 +3259,12 @@ function readValue(callback, reader, options) {
2634
3259
  owned
2635
3260
  };
2636
3261
  });
2637
- if (!diagnostics.success) throw new ContractError("readValue: options could not be read", {
3262
+ if (isFailure(diagnostics)) throw new ContractError("readValue: options could not be read", {
2638
3263
  code: "structure",
2639
3264
  cause: diagnostics.error
2640
3265
  });
2641
3266
  const outcome = attempt(callback);
2642
- if (!outcome.success) {
3267
+ if (isFailure(outcome)) {
2643
3268
  const owned = diagnostics.value.owned;
2644
3269
  const context = owned === void 0 ? void 0 : {
2645
3270
  ...owned.path === void 0 ? {} : { path: owned.path },
@@ -2701,7 +3326,7 @@ function readValue(callback, reader, options) {
2701
3326
  */
2702
3327
  function contain(callback, door, options) {
2703
3328
  const outcome = attempt(callback);
2704
- if (outcome.success) return outcome.value;
3329
+ if (isSuccess(outcome)) return outcome.value;
2705
3330
  if (isContractError(outcome.error)) throw outcome.error;
2706
3331
  throw new ContractError(`${door}: a host operation this door depends on failed`, {
2707
3332
  code: options?.code ?? "structure",
@@ -2727,7 +3352,7 @@ function contain(callback, door, options) {
2727
3352
  */
2728
3353
  function holds(callback) {
2729
3354
  const outcome = attempt(callback);
2730
- return outcome.success && outcome.value === true;
3355
+ return isSuccess(outcome) && outcome.value === true;
2731
3356
  }
2732
3357
  /**
2733
3358
  * Determines whether a value carries the plain-record brand, raising a hostile
@@ -2933,7 +3558,7 @@ function readGuardShape(shape, optional, reader) {
2933
3558
  if (optional === true) return collectMembers(declared.names);
2934
3559
  if (!INTRINSICS.array(optional)) return collectMembers([]);
2935
3560
  const entries = readArrayEntries(optional);
2936
- if (!entries.success) throw entries.error;
3561
+ if (isFailure(entries)) throw entries.error;
2937
3562
  if (!entries.value.dense) throw new INTRINSICS.error("Optional key list must be dense");
2938
3563
  return collectMembers(INTRINSICS.from(iterateIndices(() => entries.value.entries.length), (index) => INTRINSICS.text(entries.value.entries[index])));
2939
3564
  }, reader, { subject: "optional" });
@@ -2964,7 +3589,7 @@ function readGuardShape(shape, optional, reader) {
2964
3589
  */
2965
3590
  function enumerableKeys(value) {
2966
3591
  const outcome = attempt(() => INTRINSICS.freeze(INTRINSICS.keys(value)));
2967
- return outcome.success ? outcome.value : void 0;
3592
+ return isSuccess(outcome) ? outcome.value : void 0;
2968
3593
  }
2969
3594
  /**
2970
3595
  * Validates and snapshots a shape-builder options record through every reflective
@@ -3061,7 +3686,7 @@ function readOptions(source, keys, builder, shape) {
3061
3686
  function drawRandom(random, shape) {
3062
3687
  return contain(() => {
3063
3688
  const outcome = attempt(random);
3064
- if (!outcome.success) throw new ContractError("drawRandom: the random source threw", {
3689
+ if (isFailure(outcome)) throw new ContractError("drawRandom: the random source threw", {
3065
3690
  code: "random",
3066
3691
  context: {
3067
3692
  shape,
@@ -3119,23 +3744,87 @@ function resolveField(record, path) {
3119
3744
  return INTRINSICS.reflect.read(current, key);
3120
3745
  }, record]);
3121
3746
  });
3122
- return outcome.success ? outcome.value : void 0;
3747
+ return isSuccess(outcome) ? outcome.value : void 0;
3123
3748
  }
3124
3749
  /**
3125
- * Determines whether a readable value stays within the fixed JSON container-depth limit.
3750
+ * Determines whether an object holds exactly the named own keys.
3126
3751
  *
3127
3752
  * @remarks
3128
- * Counts array and plain-record containers on each active root-to-value path.
3129
- * Primitive and readable non-record objects are leaves, active cycles add no
3130
- * level, and shared aliases are answered from the shallowest depth at which
3131
- * the alias already fit. Arrays are traversed through their reflected
3132
- * own-index population, so sparse work is proportional to populated entries
3133
- * rather than advertised length. Every observable operation is contained;
3134
- * hostile or contradictory reads return `false`.
3753
+ * Every required key must be own, and every own key, symbols and non-enumerable ones
3754
+ * included, must be named, so an inherited field and a stray one both answer `false`.
3135
3755
  *
3136
- * The walk carries a settled-depth memo beside its active-path set: a
3137
- * container that fit at depth `d` also fits at any depth `<= d`, because every
3138
- * path below it is then shallower than the one already measured. Without it a
3756
+ * @param value - The object to inspect
3757
+ * @param required - The keys it must own
3758
+ * @param optional - The keys it may own
3759
+ * @returns True if its own keys are exactly those; false otherwise
3760
+ *
3761
+ * @example
3762
+ * ```ts
3763
+ * matchesExactKeys({ a: 1 }, ['a']) // true
3764
+ * matchesExactKeys({ a: 1, b: 2 }, ['a']) // false
3765
+ * matchesExactKeys({ a: 1, b: 2 }, ['a'], ['b']) // true
3766
+ * ```
3767
+ */
3768
+ function matchesExactKeys(value, required, optional = []) {
3769
+ if (INTRINSICS.reflect.apply(INTRINSICS.some, required, [(key) => !INTRINSICS.own(value, key)])) return false;
3770
+ return !INTRINSICS.reflect.apply(INTRINSICS.some, INTRINSICS.reflect.members(value), [(key) => !INTRINSICS.reflect.apply(INTRINSICS.some, required, [(name) => name === key]) && !INTRINSICS.reflect.apply(INTRINSICS.some, optional, [(name) => name === key])]);
3771
+ }
3772
+ /**
3773
+ * Determines whether a repair `parse` made kept everything the value said.
3774
+ *
3775
+ * @remarks
3776
+ * `parse`'s coercions are published and form input relies on them, but some change what
3777
+ * a value means: `1` to `true`, `'9007199254740993'` to `...992`, `'1e-400'` to `0`,
3778
+ * `'0x10'` to `16`. A door that must not guess asks this about each fault `audit` reported,
3779
+ * since `audit` already names every nested repair with its path and the kind it wanted.
3780
+ *
3781
+ * Only a `type` fault is a repair. A number needs a string whose trim is the number's own
3782
+ * text, so `'30'` and `' 30 '` pass while `'30.0'`, `'007'`, `'0x10'`, `'1e3'`, `'+5'`,
3783
+ * `'.5'`, `'-0'`, and `'9007199254740993'` do not. A boolean needs `'true'` or `'false'`,
3784
+ * a literal its trimmed text, and a string a finite number. Anything else refuses.
3785
+ *
3786
+ * @param fault - A fault `audit` reported
3787
+ * @param input - The value as it arrived
3788
+ * @param parsed - What `parse` made of it
3789
+ * @returns True if the repair loses nothing; false otherwise
3790
+ *
3791
+ * @example
3792
+ * ```ts
3793
+ * const fault = { reason: 'type', path: ['a'], expected: 'number', received: '' } as const
3794
+ * matchesLosslessRepair(fault, { a: ' 30 ' }, { a: 30 }) // true
3795
+ * matchesLosslessRepair(fault, { a: '30.0' }, { a: 30 }) // false
3796
+ * ```
3797
+ */
3798
+ function matchesLosslessRepair(fault, input, parsed) {
3799
+ if (fault.reason !== "type") return false;
3800
+ const keys = isString(fault.path) ? [fault.path] : fault.path;
3801
+ const route = INTRINSICS.from(iterateIndices(() => keys.length + 1), (index) => index === 0 ? "root" : keys[index - 1] ?? "");
3802
+ const raw = resolveField({ root: input }, route);
3803
+ const value = resolveField({ root: parsed }, route);
3804
+ switch (fault.expected) {
3805
+ case "number":
3806
+ case "integer": return isString(raw) && isNumber(value) && raw.trim() === INTRINSICS.text(value);
3807
+ case "literal": return isString(raw) && (isString(value) || isNumber(value) || isBoolean(value)) && raw.trim() === INTRINSICS.text(value);
3808
+ case "boolean": return raw === "true" || raw === "false";
3809
+ case "string": return isFiniteNumber(raw);
3810
+ default: return false;
3811
+ }
3812
+ }
3813
+ /**
3814
+ * Determines whether a readable value stays within the fixed JSON container-depth limit.
3815
+ *
3816
+ * @remarks
3817
+ * Counts array and plain-record containers on each active root-to-value path.
3818
+ * Primitive and readable non-record objects are leaves, active cycles add no
3819
+ * level, and shared aliases are answered from the shallowest depth at which
3820
+ * the alias already fit. Arrays are traversed through their reflected
3821
+ * own-index population, so sparse work is proportional to populated entries
3822
+ * rather than advertised length. Every observable operation is contained;
3823
+ * hostile or contradictory reads return `false`.
3824
+ *
3825
+ * The walk carries a settled-depth memo beside its active-path set: a
3826
+ * container that fit at depth `d` also fits at any depth `<= d`, because every
3827
+ * path below it is then shallower than the one already measured. Without it a
3139
3828
  * node reachable by `k` distinct paths was re-walked `k` times, so an ORDINARY
3140
3829
  * record graph with thirty shared aliases — thirty-one nodes — cost `2^30`
3141
3830
  * visits through a public guard.
@@ -3182,7 +3871,7 @@ function matchesJSONDepth(value) {
3182
3871
  };
3183
3872
  if (array) {
3184
3873
  const snapshot = readArrayEntries(entry);
3185
- if (!snapshot.success) return false;
3874
+ if (isFailure(snapshot)) return false;
3186
3875
  const children = INTRINSICS.values(snapshot.value.entries);
3187
3876
  for (const index of iterateIndices(() => children.length)) stack[stack.length] = {
3188
3877
  operation: "enter",
@@ -3229,13 +3918,16 @@ function matchesJSONDepth(value) {
3229
3918
  *
3230
3919
  * Beside the ancestor set the walk keeps a walk-local PROVED set, so a node
3231
3920
  * whose whole subtree already matched is not re-walked when a second path
3232
- * reaches it. Removing the recursion alone left the work exponential in shared
3921
+ * reaches it. A supplied capture budget instead charges each occurrence that
3922
+ * ownership would copy; exhaustion throws `structure` with a `clone` cause.
3923
+ * Removing the recursion alone left the work exponential in shared
3233
3924
  * aliases: thirty aliases — thirty-one ordinary records — cost `2^30` visits
3234
3925
  * through `isJSONValue`, `parseJSONValue`, `canonicalStringify` and every
3235
3926
  * `jsonShape` contract.
3236
3927
  *
3237
3928
  * @param entry - The value to inspect
3238
3929
  * @param ancestors - Objects on the active traversal path
3930
+ * @param budget - Remaining capture nodes; aliases are charged for each copied occurrence when supplied
3239
3931
  * @returns True if the value is a cycle-free JSON value; false otherwise
3240
3932
  *
3241
3933
  * @example
@@ -3244,8 +3936,12 @@ function matchesJSONDepth(value) {
3244
3936
  * matchesJSONValue(Number.NaN, new WeakSet()) // false
3245
3937
  * ```
3246
3938
  */
3247
- function matchesJSONValue(entry, ancestors) {
3939
+ function matchesJSONValue(entry, ancestors, budget) {
3248
3940
  return readValue(() => {
3941
+ if (budget !== void 0) {
3942
+ if (!INTRINSICS.safe(budget.left)) throw new ContractError("matchesJSONValue: invalid node budget", { code: "clone" });
3943
+ budget.left = INTRINSICS.min(budget.left, CLONE_NODE_LIMIT);
3944
+ }
3249
3945
  const stack = [{
3250
3946
  operation: "enter",
3251
3947
  value: entry
@@ -3259,13 +3955,20 @@ function matchesJSONValue(entry, ancestors) {
3259
3955
  admitVisited(proved, frame.value);
3260
3956
  continue;
3261
3957
  }
3958
+ if (budget !== void 0) {
3959
+ budget.left -= 1;
3960
+ if (budget.left < 0) throw new ContractError(`validateShape: default exceeds the capture node limit ${CLONE_NODE_LIMIT}`, {
3961
+ code: "clone",
3962
+ context: { limit: CLONE_NODE_LIMIT }
3963
+ });
3964
+ }
3262
3965
  const node = frame.value;
3263
3966
  if (node === null || isString(node) || isBoolean(node) || isFiniteNumber(node)) continue;
3264
3967
  if (INTRINSICS.array(node)) {
3265
3968
  if (matchesVisited(ancestors, node)) return false;
3266
- if (matchesVisited(proved, node)) continue;
3969
+ if (budget === void 0 && matchesVisited(proved, node)) continue;
3267
3970
  const snapshot = readArrayEntries(node);
3268
- if (!snapshot.success) throw snapshot.error;
3971
+ if (isFailure(snapshot)) throw snapshot.error;
3269
3972
  if (!snapshot.value.dense) return false;
3270
3973
  admitVisited(ancestors, node);
3271
3974
  stack[stack.length] = {
@@ -3284,7 +3987,7 @@ function matchesJSONValue(entry, ancestors) {
3284
3987
  }
3285
3988
  if (!isRecord(node)) return false;
3286
3989
  if (matchesVisited(ancestors, node)) return false;
3287
- if (matchesVisited(proved, node)) continue;
3990
+ if (budget === void 0 && matchesVisited(proved, node)) continue;
3288
3991
  admitVisited(ancestors, node);
3289
3992
  stack[stack.length] = {
3290
3993
  operation: "exit",
@@ -3394,7 +4097,7 @@ function schemaToObject(schema) {
3394
4097
  return contain(() => {
3395
4098
  return readValue(() => {
3396
4099
  INTRINSICS.values(schema);
3397
- if (schema.type === "object") return schema;
4100
+ if (INTRINSICS.own(schema, "type") && schema.type === "object") return schema;
3398
4101
  return {
3399
4102
  type: "object",
3400
4103
  properties: { value: schema },
@@ -3500,7 +4203,7 @@ function canonicalStringify(value) {
3500
4203
  if (matchesVisited(ancestors, container)) return void 0;
3501
4204
  if (INTRINSICS.reflect.apply(INTRINSICS.recall, encodings, [container]) !== void 0) continue;
3502
4205
  const snapshot = isArray(container) ? readArrayEntries(container) : void 0;
3503
- if (snapshot !== void 0 && !snapshot.success) throw snapshot.error;
4206
+ if (snapshot !== void 0 && isFailure(snapshot)) throw snapshot.error;
3504
4207
  if (snapshot !== void 0 && !snapshot.value.dense) return void 0;
3505
4208
  const keys = snapshot === void 0 ? sortValues(INTRINSICS.keys(container)) : void 0;
3506
4209
  const members = snapshot === void 0 ? INTRINSICS.from(iterateIndices(() => keys?.length ?? 0), (index) => {
@@ -3573,7 +4276,7 @@ function matchesISOInstant(value) {
3573
4276
  const date = new INTRINSICS.date(value);
3574
4277
  return !INTRINSICS.nan(INTRINSICS.reflect.apply(INTRINSICS.instant, date, []));
3575
4278
  });
3576
- return outcome.success && outcome.value;
4279
+ return isSuccess(outcome) && outcome.value;
3577
4280
  }
3578
4281
  /**
3579
4282
  * Classifies an already-bounded string against the pattern-only and
@@ -3863,7 +4566,7 @@ function preview(value) {
3863
4566
  function buildStringFaults(shape, value, path, pattern) {
3864
4567
  return readValue(() => {
3865
4568
  const faults = [];
3866
- if (shape.min !== void 0 && value.length < shape.min) faults[faults.length] = {
4569
+ if (INTRINSICS.own(shape, "min") && shape.min !== void 0 && !matchesStringLength(value, shape.min, void 0)) faults[faults.length] = {
3867
4570
  reason: "constraint",
3868
4571
  path,
3869
4572
  expected: "string",
@@ -3871,7 +4574,7 @@ function buildStringFaults(shape, value, path, pattern) {
3871
4574
  limit: shape.min,
3872
4575
  received: preview(value)
3873
4576
  };
3874
- if (shape.max !== void 0 && value.length > shape.max) faults[faults.length] = {
4577
+ if (INTRINSICS.own(shape, "max") && shape.max !== void 0 && !matchesStringLength(value, void 0, shape.max)) faults[faults.length] = {
3875
4578
  reason: "constraint",
3876
4579
  path,
3877
4580
  expected: "string",
@@ -3879,7 +4582,7 @@ function buildStringFaults(shape, value, path, pattern) {
3879
4582
  limit: shape.max,
3880
4583
  received: preview(value)
3881
4584
  };
3882
- const stateless = pattern ?? (shape.pattern === void 0 ? void 0 : readPattern(shape.pattern));
4585
+ const stateless = pattern ?? (!INTRINSICS.own(shape, "pattern") || shape.pattern === void 0 ? void 0 : readPattern(shape.pattern));
3883
4586
  if (stateless !== void 0 && !matchesPattern(stateless, value)) {
3884
4587
  const limit = readPatternSource(stateless);
3885
4588
  faults[faults.length] = {
@@ -3919,16 +4622,16 @@ function buildStringFaults(shape, value, path, pattern) {
3919
4622
  */
3920
4623
  function buildNumberFaults(shape, value, path) {
3921
4624
  return readValue(() => {
3922
- const expected = shape.integer === true ? "integer" : "number";
4625
+ const expected = INTRINSICS.own(shape, "integer") && shape.integer === true ? "integer" : "number";
3923
4626
  const faults = [];
3924
- if (shape.integer === true && !INTRINSICS.integer(value)) faults[faults.length] = {
4627
+ if (INTRINSICS.own(shape, "integer") && shape.integer === true && !INTRINSICS.integer(value)) faults[faults.length] = {
3925
4628
  reason: "constraint",
3926
4629
  path,
3927
4630
  expected,
3928
4631
  constraint: "integer",
3929
4632
  received: preview(value)
3930
4633
  };
3931
- if (shape.min !== void 0 && value < shape.min) faults[faults.length] = {
4634
+ if (INTRINSICS.own(shape, "min") && shape.min !== void 0 && value < shape.min) faults[faults.length] = {
3932
4635
  reason: "constraint",
3933
4636
  path,
3934
4637
  expected,
@@ -3936,7 +4639,7 @@ function buildNumberFaults(shape, value, path) {
3936
4639
  limit: shape.min,
3937
4640
  received: preview(value)
3938
4641
  };
3939
- if (shape.max !== void 0 && value > shape.max) faults[faults.length] = {
4642
+ if (INTRINSICS.own(shape, "max") && shape.max !== void 0 && value > shape.max) faults[faults.length] = {
3940
4643
  reason: "constraint",
3941
4644
  path,
3942
4645
  expected,
@@ -3974,7 +4677,7 @@ function buildNumberFaults(shape, value, path) {
3974
4677
  function buildArrayFaults(shape, length, path) {
3975
4678
  return readValue(() => {
3976
4679
  const faults = [];
3977
- if (shape.min !== void 0 && length < shape.min) faults[faults.length] = {
4680
+ if (INTRINSICS.own(shape, "min") && shape.min !== void 0 && length < shape.min) faults[faults.length] = {
3978
4681
  reason: "constraint",
3979
4682
  path,
3980
4683
  expected: "array",
@@ -3982,7 +4685,7 @@ function buildArrayFaults(shape, length, path) {
3982
4685
  limit: shape.min,
3983
4686
  received: INTRINSICS.text(length)
3984
4687
  };
3985
- if (shape.max !== void 0 && length > shape.max) faults[faults.length] = {
4688
+ if (INTRINSICS.own(shape, "max") && shape.max !== void 0 && length > shape.max) faults[faults.length] = {
3986
4689
  reason: "constraint",
3987
4690
  path,
3988
4691
  expected: "array",
@@ -4056,7 +4759,7 @@ function shapeToKind(shape) {
4056
4759
  return readValue(() => {
4057
4760
  switch (shape.category) {
4058
4761
  case "string": return "string";
4059
- case "number": return shape.integer === true ? "integer" : "number";
4762
+ case "number": return INTRINSICS.own(shape, "integer") && shape.integer === true ? "integer" : "number";
4060
4763
  case "boolean": return "boolean";
4061
4764
  case "null": return "null";
4062
4765
  case "literal": return "literal";
@@ -4064,6 +4767,7 @@ function shapeToKind(shape) {
4064
4767
  case "object": return "object";
4065
4768
  case "union": return "union";
4066
4769
  case "json": return "json";
4770
+ case "shape": return "shape";
4067
4771
  case "optional": return shapeToKind(shape.inner);
4068
4772
  case "nullable": return shapeToKind(shape.inner);
4069
4773
  case "raw": return "json";
@@ -4208,6 +4912,233 @@ for (const generator of [iterateIndices, encodeParts]) {
4208
4912
  INTRINSICS.freeze(generator.prototype);
4209
4913
  INTRINSICS.freeze(generator);
4210
4914
  }
4915
+ /**
4916
+ * Extracts a fault's path as its segments, reading a string path as one segment.
4917
+ *
4918
+ * @param fault - The fault to read
4919
+ * @returns The path's segments, empty at the root
4920
+ *
4921
+ * @example
4922
+ * ```ts
4923
+ * import { extractPath } from '@orkestrel/contract'
4924
+ *
4925
+ * extractPath({ reason: 'extra', path: ['page', 'typo'] }) // ['page', 'typo']
4926
+ * ```
4927
+ */
4928
+ function extractPath(fault) {
4929
+ return isString(fault.path) ? [fault.path] : fault.path;
4930
+ }
4931
+ /**
4932
+ * Extracts a schema's forms: the schema itself, then its union arms, so a read looks
4933
+ * through a nullable the same way everywhere.
4934
+ *
4935
+ * @param schema - The schema to read, or `undefined` where none was found
4936
+ * @returns The forms, empty when there is no schema
4937
+ *
4938
+ * @example
4939
+ * ```ts
4940
+ * import { extractForms } from '@orkestrel/contract'
4941
+ *
4942
+ * const object = { type: 'object' } as const
4943
+ * extractForms({ anyOf: [object] }) // [{ anyOf: [object] }, object]
4944
+ * ```
4945
+ */
4946
+ function extractForms(schema) {
4947
+ if (schema === void 0) return [];
4948
+ const anyOf = INTRINSICS.own(schema, "anyOf") ? schema.anyOf : void 0;
4949
+ const oneOf = INTRINSICS.own(schema, "oneOf") ? schema.oneOf : void 0;
4950
+ return [schema, ...anyOf ?? oneOf ?? []];
4951
+ }
4952
+ /**
4953
+ * Extracts the part of a schema a path reaches, through properties, array items, record values,
4954
+ * and the arms of a union.
4955
+ *
4956
+ * @remarks
4957
+ * Each path segment takes one step, so a union that nests itself cannot hold the walk. Only a
4958
+ * schema's own `properties` keys match, so `constructor` reaches nothing. The walk keeps every
4959
+ * matching union declaration until the end; differing declarations yield no schema. Independently
4960
+ * built declarations agree when their canonical JSON encodings agree.
4961
+ *
4962
+ * @param schema - The schema to walk
4963
+ * @param path - The segments to follow
4964
+ * @returns The schema at that path, or `undefined` where no declaration or no agreement exists
4965
+ *
4966
+ * @example
4967
+ * ```ts
4968
+ * import { extractSchema } from '@orkestrel/contract'
4969
+ *
4970
+ * const schema = { type: 'object', properties: { limit: { type: 'number' } } } as const
4971
+ * extractSchema(schema, ['limit']) // { type: 'number' }
4972
+ * ```
4973
+ */
4974
+ function extractSchema(schema, path) {
4975
+ const nodes = path.reduce((parents, key) => Array.from(new Set(parents.flatMap((node) => extractForms(node)).map((form) => {
4976
+ const properties = INTRINSICS.own(form, "properties") ? form.properties : void 0;
4977
+ const additional = INTRINSICS.own(form, "additionalProperties") ? form.additionalProperties : void 0;
4978
+ return properties !== void 0 && INTRINSICS.own(properties, key) ? properties[key] : isRecord(additional) ? additional : INTRINSICS.own(form, "items") ? form.items : void 0;
4979
+ }).filter((child) => child !== void 0))), [schema]);
4980
+ const first = nodes[0];
4981
+ if (nodes.length < 2) return first;
4982
+ const encoded = canonicalStringify(first);
4983
+ return encoded !== void 0 && nodes.every((node) => canonicalStringify(node) === encoded) ? first : void 0;
4984
+ }
4985
+ /**
4986
+ * Renders a path as text, encoding what a caller could have sent and eliding the middle of a long
4987
+ * one.
4988
+ *
4989
+ * @remarks
4990
+ * A segment that is not a plain identifier is JSON-encoded and length-capped, because a key the
4991
+ * caller sent is untrusted text. A path of more than four segments past 120 characters keeps its
4992
+ * first segment and its last three.
4993
+ *
4994
+ * @param path - The segments to render
4995
+ * @returns The segments joined with `.`, empty at the root
4996
+ *
4997
+ * @example
4998
+ * ```ts
4999
+ * import { renderPath } from '@orkestrel/contract'
5000
+ *
5001
+ * renderPath(['rows', '0', 'a b']) // 'rows.0."a b"'
5002
+ * ```
5003
+ */
5004
+ function renderPath(path) {
5005
+ const segments = path.map((segment) => /^[\w$-]{1,64}$/u.test(segment) ? segment : preview(segment));
5006
+ const text = segments.join(".");
5007
+ return segments.length <= 4 || text.length <= 120 ? text : [
5008
+ ...segments.slice(0, 1),
5009
+ "…",
5010
+ ...segments.slice(-3)
5011
+ ].join(".");
5012
+ }
5013
+ /**
5014
+ * Renders a list as text, naming at most `FAULT_LIST_LIMIT` of its entries and counting the rest.
5015
+ *
5016
+ * @param entries - The rendered entries
5017
+ * @returns The entries joined with `, `
5018
+ *
5019
+ * @example
5020
+ * ```ts
5021
+ * import { renderList } from '@orkestrel/contract'
5022
+ *
5023
+ * renderList(['city', 'units']) // 'city, units'
5024
+ * ```
5025
+ */
5026
+ function renderList(entries) {
5027
+ const listed = entries.slice(0, 12).join(", ");
5028
+ return entries.length > 12 ? `${listed} and ${String(entries.length - 12)} more` : listed;
5029
+ }
5030
+ /**
5031
+ * Renders a schema as a short summary of what to send, such as `{"city": string, "note"?: string}`.
5032
+ *
5033
+ * @remarks
5034
+ * An object lists its required keys first and marks the rest with `?`, at most `FAULT_LIST_LIMIT`
5035
+ * of them. A leaf or array keeps its numeric bounds and pattern, a union joins its forms with ` | `,
5036
+ * and a schema that says nothing reads `any`. Each nested form takes half the room of its parent, and
5037
+ * below 16 characters a form stops at its type, so a schema that holds itself still ends. Text past
5038
+ * `room` is cut and closes with `…`. A type word outside JSON Schema's vocabulary is encoded.
5039
+ *
5040
+ * @param schema - The schema to summarize
5041
+ * @param room - The characters the summary can take. Default: `FAULT_SCHEMA_LIMIT`
5042
+ * @returns The summary
5043
+ *
5044
+ * @example
5045
+ * ```ts
5046
+ * import { renderForm } from '@orkestrel/contract'
5047
+ *
5048
+ * renderForm({ type: 'object', properties: { zip: { type: 'number' } }, required: ['zip'] }) // '{"zip": number}'
5049
+ * ```
5050
+ */
5051
+ function renderForm(schema, room = 160) {
5052
+ const deep = room >= 16;
5053
+ const inner = Math.floor(room / 2);
5054
+ const anyOf = INTRINSICS.own(schema, "anyOf") ? schema.anyOf : void 0;
5055
+ const oneOf = INTRINSICS.own(schema, "oneOf") ? schema.oneOf : void 0;
5056
+ const forms = anyOf ?? oneOf;
5057
+ const required = (INTRINSICS.own(schema, "required") ? schema.required : void 0) ?? [];
5058
+ const entries = Object.entries((INTRINSICS.own(schema, "properties") ? schema.properties : void 0) ?? {});
5059
+ const type = INTRINSICS.own(schema, "type") ? schema.type : void 0;
5060
+ const enumeration = INTRINSICS.own(schema, "enum") ? schema.enum : void 0;
5061
+ const additional = INTRINSICS.own(schema, "additionalProperties") ? schema.additionalProperties : void 0;
5062
+ const listed = (deep ? entries : []).toSorted(([left], [right]) => Number(required.includes(right)) - Number(required.includes(left))).slice(0, 12).map(([key, child]) => `${preview(key)}${required.includes(key) ? "" : "?"}: ${renderForm(child, inner)}`);
5063
+ const left = entries.length - listed.length;
5064
+ const child = type === "array" ? INTRINSICS.own(schema, "items") ? schema.items : void 0 : isRecord(additional) ? additional : void 0;
5065
+ const bounds = Object.entries(schema).filter(([key]) => [
5066
+ "minLength",
5067
+ "maxLength",
5068
+ "minimum",
5069
+ "maximum",
5070
+ "minItems",
5071
+ "maxItems",
5072
+ "pattern"
5073
+ ].includes(key)).map(([key, value]) => `${key} ${preview(value)}`);
5074
+ return truncateFaultText(forms !== void 0 ? deep ? forms.map((form) => renderForm(form, inner)).join(" | ") : "any" : enumeration !== void 0 ? enumeration.map((value) => preview(value)).join(" | ") : listed.length > 0 ? `{${[...listed, ...left > 0 ? [`and ${String(left)} more`] : []].join(", ")}}` : [
5075
+ type === void 0 ? entries.length > 0 ? "object" : "any" : JSON_SCHEMA_TYPES.some((name) => name === type) ? type : preview(type),
5076
+ ...deep && child !== void 0 ? [` of ${renderForm(child, inner)}`] : [],
5077
+ ...bounds.length > 0 ? [` (${bounds.join(", ")})`] : []
5078
+ ].join(""), room);
5079
+ }
5080
+ /**
5081
+ * Describes one fault as the line a caller corrects from, naming what to send where the schema
5082
+ * says.
5083
+ *
5084
+ * @remarks
5085
+ * Each line opens with the fault's path (or `value` at the root) and reason. An `extra` fault lists
5086
+ * its parent's keys only when the declaring arms agree. A literal names candidates only where
5087
+ * the declarations agree; lists are deduplicated and bounded. A received preview stays as written
5088
+ * within PREVIEW_LIMIT and without control or line-separator characters; otherwise it is encoded
5089
+ * through preview. Received, constraint, and limit details read only own fields. A `variant` or
5090
+ * `oneOf` fault says that the value matches none of the declared forms, or several where one must
5091
+ * match, and summarizes each form through `renderForm`. It names no fault of any one form, because
5092
+ * none of them holds for the others. Those summaries share half of `FAULT_TEXT_LIMIT`.
5093
+ *
5094
+ * @param fault - The fault to describe
5095
+ * @param schema - The compiled schema the fault's path reads
5096
+ * @returns The line, with no line break
5097
+ *
5098
+ * @example
5099
+ * ```ts
5100
+ * import { describeFaultLine } from '@orkestrel/contract'
5101
+ *
5102
+ * describeFaultLine({ reason: 'missing', path: ['left'], expected: 'number' }, {}) // 'left: missing; expected number'
5103
+ * ```
5104
+ */
5105
+ function describeFaultLine(fault, schema) {
5106
+ const path = extractPath(fault);
5107
+ const head = `${renderPath(path) || "value"}: ${fault.reason}`;
5108
+ if (fault.reason === "extra") {
5109
+ const declarations = extractForms(extractSchema(schema, path.slice(0, -1))).filter((form) => INTRINSICS.own(form, "properties") && form.properties !== void 0).map((form) => Object.keys(form.properties ?? {}));
5110
+ const first = declarations[0] ?? [];
5111
+ const keys = declarations.every((declared) => declared.length === first.length && declared.every((key) => first.includes(key))) ? first : [];
5112
+ return keys.length === 0 ? `${head}; this key is not declared, remove it` : `${head}; this key is not declared, remove it or use a declared key: ${renderList(keys.map((key) => renderPath([key])))}`;
5113
+ }
5114
+ const node = extractSchema(schema, path);
5115
+ const anyOf = node !== void 0 && INTRINSICS.own(node, "anyOf") ? node.anyOf : void 0;
5116
+ const oneOf = node !== void 0 && INTRINSICS.own(node, "oneOf") ? node.oneOf : void 0;
5117
+ if (fault.reason === "variant" || fault.reason === "oneOf") {
5118
+ const count = fault.reason === "variant" ? fault.variants : oneOf?.length;
5119
+ const forms = count === void 0 ? "the declared forms" : `the ${String(count)} declared forms`;
5120
+ const claim = fault.reason === "oneOf" && fault.matched > 0 ? `the value matches ${String(fault.matched)} of ${forms} and must match exactly one` : `the value matches none of ${forms}`;
5121
+ const declared = anyOf ?? oneOf ?? [];
5122
+ const shown = declared.slice(0, 12);
5123
+ const room = Math.min(160, Math.floor(FAULT_TEXT_LIMIT / 2 / Math.max(shown.length, 1)));
5124
+ const more = declared.length - shown.length;
5125
+ const summary = shown.length === 0 ? "" : `, one of: ${shown.map((form) => renderForm(form, room)).join(" or ")}${more > 0 ? ` and ${String(more)} more` : ""}`;
5126
+ return `${head}; ${claim}${fault.key === void 0 ? "" : `; discriminator ${preview(fault.key)} expects ${renderList((fault.expected ?? []).map((value) => preview(value)))}`}; send it exactly as the schema declares${summary}`;
5127
+ }
5128
+ const candidates = fault.expected === "literal" ? extractForms(node).flatMap((form) => [...(INTRINSICS.own(form, "enum") ? form.enum : void 0) ?? [], ...INTRINSICS.own(form, "type") && form.type === "null" ? [null] : []]) : [];
5129
+ const description = node !== void 0 && INTRINSICS.own(node, "description") ? node.description : void 0;
5130
+ const received = "received" in fault && INTRINSICS.own(fault, "received") ? fault.received : void 0;
5131
+ const shown = received !== void 0 && received.length <= 64 && !/[\p{Cc}\p{Zl}\p{Zp}]/u.test(received) ? received : preview(received);
5132
+ return [
5133
+ head,
5134
+ `expected ${fault.expected}`,
5135
+ ...received !== void 0 ? [`received ${shown}`] : [],
5136
+ ..."constraint" in fault && INTRINSICS.own(fault, "constraint") ? [`constraint ${fault.constraint}`] : [],
5137
+ ..."limit" in fault && INTRINSICS.own(fault, "limit") && fault.limit !== void 0 ? [`limit ${preview(fault.limit)}`] : [],
5138
+ ...description === void 0 ? [] : [`description ${preview(description)}`],
5139
+ ...candidates.length > 0 ? [`send one of ${renderList(Array.from(new Set(candidates), (value) => preview(value)))}`] : []
5140
+ ].join("; ");
5141
+ }
4211
5142
  // src/core/JSONCloner.ts
4212
5143
  /**
4213
5144
  * Owns the state of one exact JSON snapshot operation.
@@ -4239,7 +5170,6 @@ var JSONCloner = class JSONCloner {
4239
5170
  #owned;
4240
5171
  #active;
4241
5172
  #pending;
4242
- #produced;
4243
5173
  #poison;
4244
5174
  #terminal;
4245
5175
  constructor(value) {
@@ -4247,38 +5177,35 @@ var JSONCloner = class JSONCloner {
4247
5177
  this.#owned = new JSONCloner.#weakSet();
4248
5178
  this.#active = new JSONCloner.#weakSet();
4249
5179
  this.#pending = [];
4250
- this.#produced = 0;
4251
5180
  this.#poison = void 0;
4252
5181
  this.#terminal = void 0;
4253
5182
  }
4254
5183
  /**
4255
5184
  * Clones the retained source into exact, deeply frozen JSON data.
4256
5185
  *
5186
+ * @param budget - Remaining nodes shared with an enclosing ownership operation
4257
5187
  * @returns The settled JSON snapshot
4258
5188
  * @throws {ContractError} When the source is inexact, cyclic, unreadable, or cloning is reentered
4259
5189
  */
4260
- clone() {
5190
+ clone(budget = { left: CLONE_NODE_LIMIT }) {
4261
5191
  const terminal = this.#terminal;
4262
5192
  if (terminal !== void 0) {
4263
- if (terminal.success) return terminal.value;
5193
+ if (isSuccess(terminal)) return terminal.value;
4264
5194
  throw terminal.error;
4265
5195
  }
4266
5196
  const poison = this.#poison;
4267
5197
  if (poison !== void 0) {
4268
- this.#terminal = {
4269
- success: false,
4270
- error: poison
4271
- };
5198
+ this.#terminal = failure(poison);
4272
5199
  throw poison;
4273
5200
  }
4274
5201
  this.#poison = this.#create("JSONCloner.clone: JSON cloning may not be reentered");
4275
- const outcome = attempt(() => this.#execute());
5202
+ const outcome = attempt(() => this.#execute(budget));
4276
5203
  const interruption = this.#terminal;
4277
5204
  if (interruption !== void 0) {
4278
- if (interruption.success) return interruption.value;
5205
+ if (isSuccess(interruption)) return interruption.value;
4279
5206
  this.#fail(interruption.error);
4280
5207
  }
4281
- if (outcome.success) {
5208
+ if (isSuccess(outcome)) {
4282
5209
  this.#terminal = outcome;
4283
5210
  return outcome.value;
4284
5211
  }
@@ -4286,19 +5213,18 @@ var JSONCloner = class JSONCloner {
4286
5213
  this.#fail(error);
4287
5214
  }
4288
5215
  #fail(error) {
4289
- this.#terminal = {
4290
- success: false,
4291
- error
4292
- };
5216
+ this.#terminal = failure(error);
4293
5217
  this.#pending = JSONCloner.#emptyPending;
4294
5218
  throw error;
4295
5219
  }
4296
- #execute() {
4297
- const root = this.#capture(this.#source);
4298
- this.#drain();
5220
+ #execute(budget) {
5221
+ if (!INTRINSICS.safe(budget.left)) this.#refuse("cloneJSONValue: invalid node budget");
5222
+ budget.left = INTRINSICS.min(budget.left, CLONE_NODE_LIMIT);
5223
+ const root = this.#capture(this.#source, budget);
5224
+ this.#drain(budget);
4299
5225
  return root;
4300
5226
  }
4301
- #drain() {
5227
+ #drain(budget) {
4302
5228
  while (this.#pending.length > 0) {
4303
5229
  const frame = this.#pending[this.#pending.length - 1];
4304
5230
  if (frame === void 0) continue;
@@ -4311,7 +5237,7 @@ var JSONCloner = class JSONCloner {
4311
5237
  continue;
4312
5238
  }
4313
5239
  frame.index += 1;
4314
- const clone = this.#capture(entry[1]);
5240
+ const clone = this.#capture(entry[1], budget);
4315
5241
  INTRINSICS.define(frame.clone, entry[0], {
4316
5242
  value: clone,
4317
5243
  enumerable: true,
@@ -4320,9 +5246,9 @@ var JSONCloner = class JSONCloner {
4320
5246
  });
4321
5247
  }
4322
5248
  }
4323
- #capture(value) {
4324
- this.#produced += 1;
4325
- if (this.#produced > 262144) this.#refuse("cloneJSONValue: snapshot exceeds the node limit");
5249
+ #capture(value, budget) {
5250
+ budget.left -= 1;
5251
+ if (budget.left < 0) this.#refuse(`cloneJSONValue: snapshot exceeds the node limit ${CLONE_NODE_LIMIT}`, CLONE_NODE_LIMIT);
4326
5252
  if (value === null || typeof value === "string" || typeof value === "boolean") return value;
4327
5253
  if (typeof value === "number") {
4328
5254
  if (INTRINSICS.finite(value)) return value;
@@ -4334,7 +5260,7 @@ var JSONCloner = class JSONCloner {
4334
5260
  #captureObject(source) {
4335
5261
  if (matchesVisited(this.#active, source)) this.#refuse("cloneJSONValue: cycle detected");
4336
5262
  const arrayOutcome = attempt(() => INTRINSICS.array(source));
4337
- if (!arrayOutcome.success) this.#refuse("cloneJSONValue: value brand could not be inspected");
5263
+ if (isFailure(arrayOutcome)) this.#refuse("cloneJSONValue: value brand could not be inspected");
4338
5264
  if (arrayOutcome.value) return this.#schedule(source, true);
4339
5265
  if (isRecord(source)) return this.#schedule(source, false);
4340
5266
  this.#refuse("cloneJSONValue: object is not a plain record");
@@ -4353,9 +5279,9 @@ var JSONCloner = class JSONCloner {
4353
5279
  }
4354
5280
  #captureArray(source) {
4355
5281
  const keysOutcome = attempt(() => INTRINSICS.reflect.members(source));
4356
- if (!keysOutcome.success) this.#refuse("cloneJSONValue: own keys could not be inspected");
5282
+ if (isFailure(keysOutcome)) this.#refuse("cloneJSONValue: own keys could not be inspected");
4357
5283
  const lengthOutcome = attempt(() => INTRINSICS.reflect.describe(source, "length"));
4358
- if (!lengthOutcome.success) this.#refuse("cloneJSONValue: array length could not be inspected");
5284
+ if (isFailure(lengthOutcome)) this.#refuse("cloneJSONValue: array length could not be inspected");
4359
5285
  const lengthDescriptor = lengthOutcome.value;
4360
5286
  if (lengthDescriptor === void 0 || !("value" in lengthDescriptor) || typeof lengthDescriptor.value !== "number" || !INTRINSICS.integer(lengthDescriptor.value) || lengthDescriptor.value < 0 || lengthDescriptor.value > 4294967295 || lengthDescriptor.enumerable !== false || lengthDescriptor.configurable !== false) this.#refuse("cloneJSONValue: array is not intrinsic and dense");
4361
5287
  const owned = collectMembers(keysOutcome.value);
@@ -4365,7 +5291,7 @@ var JSONCloner = class JSONCloner {
4365
5291
  const key = INTRINSICS.text(index);
4366
5292
  if (!matchesMember(owned, key)) this.#refuse("cloneJSONValue: array own keys are not exact");
4367
5293
  const descriptorOutcome = attempt(() => INTRINSICS.reflect.describe(source, key));
4368
- if (!descriptorOutcome.success) this.#refuse("cloneJSONValue: array index could not be inspected");
5294
+ if (isFailure(descriptorOutcome)) this.#refuse("cloneJSONValue: array index could not be inspected");
4369
5295
  const descriptor = descriptorOutcome.value;
4370
5296
  if (descriptor === void 0 || !("value" in descriptor) || descriptor.enumerable !== true) this.#refuse("cloneJSONValue: array index is not enumerable data");
4371
5297
  return [key, descriptor.value];
@@ -4373,22 +5299,25 @@ var JSONCloner = class JSONCloner {
4373
5299
  }
4374
5300
  #captureRecord(source) {
4375
5301
  const keysOutcome = attempt(() => INTRINSICS.reflect.members(source));
4376
- if (!keysOutcome.success) this.#refuse("cloneJSONValue: own keys could not be inspected");
5302
+ if (isFailure(keysOutcome)) this.#refuse("cloneJSONValue: own keys could not be inspected");
4377
5303
  const names = keysOutcome.value;
4378
5304
  return INTRINSICS.from(iterateIndices(() => names.length), (index) => {
4379
5305
  const key = names[index];
4380
5306
  if (typeof key !== "string") this.#refuse("cloneJSONValue: record has a symbol property");
4381
5307
  const descriptorOutcome = attempt(() => INTRINSICS.reflect.describe(source, key));
4382
- if (!descriptorOutcome.success) this.#refuse("cloneJSONValue: record property could not be inspected");
5308
+ if (isFailure(descriptorOutcome)) this.#refuse("cloneJSONValue: record property could not be inspected");
4383
5309
  const descriptor = descriptorOutcome.value;
4384
5310
  if (descriptor === void 0 || !("value" in descriptor) || descriptor.enumerable !== true) this.#refuse("cloneJSONValue: record property is not enumerable data");
4385
5311
  return [key, descriptor.value];
4386
5312
  });
4387
5313
  }
4388
- #create(message) {
5314
+ #create(message, limit) {
4389
5315
  const error = new ContractError(message, {
4390
5316
  code: "clone",
4391
- context: { shape: "json" }
5317
+ context: {
5318
+ shape: "json",
5319
+ ...limit === void 0 ? {} : { limit }
5320
+ }
4392
5321
  });
4393
5322
  admitVisited(this.#owned, error);
4394
5323
  return error;
@@ -4396,10 +5325,10 @@ var JSONCloner = class JSONCloner {
4396
5325
  #owns(error) {
4397
5326
  return isObject(error) && matchesVisited(this.#owned, error);
4398
5327
  }
4399
- #refuse(message) {
5328
+ #refuse(message, limit) {
4400
5329
  const terminal = this.#terminal;
4401
- if (terminal !== void 0 && !terminal.success) throw terminal.error;
4402
- throw this.#create(message);
5330
+ if (terminal !== void 0 && isFailure(terminal)) throw terminal.error;
5331
+ throw this.#create(message, limit);
4403
5332
  }
4404
5333
  static {
4405
5334
  INTRINSICS.freeze(JSONCloner.#emptyPending);
@@ -4457,7 +5386,7 @@ var SchemaCloner = class SchemaCloner {
4457
5386
  const state = this.#state;
4458
5387
  switch (state.phase) {
4459
5388
  case "settled":
4460
- if (state.result.success) return state.result.value;
5389
+ if (isSuccess(state.result)) return state.result.value;
4461
5390
  throw state.result.error;
4462
5391
  case "running":
4463
5392
  case "interrupted":
@@ -4476,16 +5405,10 @@ var SchemaCloner = class SchemaCloner {
4476
5405
  }
4477
5406
  #complete(outcome) {
4478
5407
  const state = this.#state;
4479
- if (state.phase === "interrupted") return this.#settle({
4480
- success: false,
4481
- error: state.poison
4482
- });
4483
- if (outcome.success) return this.#settle(outcome);
5408
+ if (state.phase === "interrupted") return this.#settle(failure(state.poison));
5409
+ if (isSuccess(outcome)) return this.#settle(outcome);
4484
5410
  const error = this.#owns(outcome.error) ? outcome.error : this.#create("cloneSchema: failed to create an owned schema snapshot", { cause: outcome.error });
4485
- return this.#settle({
4486
- success: false,
4487
- error
4488
- });
5411
+ return this.#settle(failure(error));
4489
5412
  }
4490
5413
  #execute() {
4491
5414
  if (INTRINSICS.array(this.#source)) this.#refuse("cloneSchema: a schema root must be a record, not an array", "structure", []);
@@ -4547,7 +5470,7 @@ var SchemaCloner = class SchemaCloner {
4547
5470
  }
4548
5471
  #read(source, key, path) {
4549
5472
  const outcome = attempt(() => INTRINSICS.reflect.read(source, key));
4550
- if (outcome.success) return outcome.value;
5473
+ if (isSuccess(outcome)) return outcome.value;
4551
5474
  throw this.#create("cloneSchema: property access failed", {
4552
5475
  path,
4553
5476
  cause: outcome.error
@@ -4598,7 +5521,7 @@ var SchemaCloner = class SchemaCloner {
4598
5521
  phase: "settled",
4599
5522
  result
4600
5523
  };
4601
- if (result.success) return result.value;
5524
+ if (isSuccess(result)) return result.value;
4602
5525
  throw result.error;
4603
5526
  }
4604
5527
  static {
@@ -4611,7 +5534,23 @@ var SchemaCloner = class SchemaCloner {
4611
5534
  var ShapePass = class ShapePass {
4612
5535
  static #weakSet = WeakSet;
4613
5536
  static #weakMap = WeakMap;
5537
+ static #arrays = Array.prototype;
5538
+ static #pop = Array.prototype.pop;
5539
+ static #iterators = INTRINSICS.prototype(INTRINSICS.reflect.apply(INTRINSICS.indices, [], []));
5540
+ static #blank = INTRINSICS.freeze(new INTRINSICS.pattern(""));
5541
+ static #fields = [
5542
+ "min",
5543
+ "max",
5544
+ "pattern",
5545
+ "description",
5546
+ "integer",
5547
+ "additionalProperties",
5548
+ "mode",
5549
+ "default"
5550
+ ];
5551
+ static #seals = new ShapePass.#weakMap();
4614
5552
  #source;
5553
+ #budget;
4615
5554
  #stack = [];
4616
5555
  #path = [];
4617
5556
  #active = new ShapePass.#weakSet();
@@ -4621,20 +5560,91 @@ var ShapePass = class ShapePass {
4621
5560
  #height = [];
4622
5561
  #reach = [];
4623
5562
  #via = [];
5563
+ #within = [];
4624
5564
  #counts = [];
4625
5565
  #schemas = new ShapePass.#weakMap();
4626
5566
  #children = [];
4627
5567
  #category;
4628
5568
  #raw = 0;
5569
+ #defaulted = false;
5570
+ #open = false;
4629
5571
  #structure;
4630
5572
  #cycle;
4631
5573
  #domain;
4632
- #clock = 0;
4633
- #oldest = 0;
4634
- #trail = [];
4635
5574
  #poison;
4636
- constructor(shape) {
5575
+ constructor(shape, budget) {
4637
5576
  this.#source = shape;
5577
+ this.#budget = budget;
5578
+ }
5579
+ /**
5580
+ * Validates a node fresh from a builder, freezes it, and records what the walk found.
5581
+ *
5582
+ * @remarks
5583
+ * The node's own fields are always observed, and each child is answered from its
5584
+ * seal rather than walked. Anything short of a clean answer takes the whole walk
5585
+ * instead, which is what authors every refusal, so a refusal reads the same and
5586
+ * fires at the same call as it would with no seals at all. That second look is safe
5587
+ * because the first read nothing a caller wrote: the node is this package's own
5588
+ * literal, and a child with no seal stops the survey before it is read.
5589
+ *
5590
+ * @param shape - The builder's fresh node, which no caller has seen
5591
+ * @param check - What the whole walk validates, when the node is only legal in a slot
5592
+ * @returns The frozen node
5593
+ * @throws {ContractError} When the node is refused
5594
+ */
5595
+ static seal(shape, check = shape) {
5596
+ const frozen = INTRINSICS.freeze(shape);
5597
+ if (!new ShapePass(shape).#survey(check === shape ? 0 : 1)) new ShapePass(check, { left: CLONE_NODE_LIMIT }).validate();
5598
+ return frozen;
5599
+ }
5600
+ /**
5601
+ * Reports the expansion of a sealed node a compiler can take as it stands.
5602
+ *
5603
+ * @remarks
5604
+ * `undefined` sends the caller to its own ownership and validation: the node was
5605
+ * never sealed, an inherited field would answer a walk of it, or it is an `optional`
5606
+ * node, which a walk refuses as a root.
5607
+ *
5608
+ * @param shape - The declaration to look up
5609
+ * @returns The expansion a walk would report, or `undefined`
5610
+ */
5611
+ static expansionOf(shape) {
5612
+ if (ShapePass.polluted()) return void 0;
5613
+ const seal = INTRINSICS.reflect.apply(INTRINSICS.recall, ShapePass.#seals, [shape]);
5614
+ return seal === void 0 || seal.category === "optional" ? void 0 : seal.count;
5615
+ }
5616
+ /**
5617
+ * Reports whether a walk could answer differently from a seal.
5618
+ *
5619
+ * @remarks
5620
+ * A field a node may leave out reads through to `Object.prototype`, which is a
5621
+ * verdict about the declaration, and a {@link tampered} host breaks a walk into a
5622
+ * refusal a seal would otherwise skip.
5623
+ *
5624
+ * @returns True when a walk has to answer rather than a seal
5625
+ */
5626
+ static polluted() {
5627
+ if (ShapePass.tampered()) return true;
5628
+ return INTRINSICS.reflect.apply(INTRINSICS.some, ShapePass.#fields, [(field) => INTRINSICS.own(INTRINSICS.base, field)]);
5629
+ }
5630
+ /**
5631
+ * Reports whether a member a walk or a compile runs on has been replaced.
5632
+ *
5633
+ * @remarks
5634
+ * An index on either prototype, reached by array writes, a replaced `pop` or array
5635
+ * iterator `next`, and a flag getter a pattern's `flags` reads. An array's `length`
5636
+ * always passes its highest index, and own keys list an index first, so one read
5637
+ * answers for every index, and a name that merely opens with a digit only costs a walk.
5638
+ *
5639
+ * @returns True when the host is not the one this package loaded on
5640
+ */
5641
+ static tampered() {
5642
+ if (ShapePass.#arrays.length !== 0) return true;
5643
+ const first = INTRINSICS.reflect.members(INTRINSICS.base)[0];
5644
+ if (typeof first === "string" && first >= "0" && first < ":") return true;
5645
+ if (INTRINSICS.describe(ShapePass.#arrays, "pop")?.value !== ShapePass.#pop) return true;
5646
+ if (INTRINSICS.describe(ShapePass.#iterators, "next")?.value !== INTRINSICS.advance) return true;
5647
+ return !holds(() => readPatternFlags(ShapePass.#blank) === "");
4638
5648
  }
4639
5649
  /** Poisons this pass and throws the same refusal on every reentry. */
4640
5650
  interrupt() {
@@ -4648,7 +5658,7 @@ var ShapePass = class ShapePass {
4648
5658
  validate() {
4649
5659
  const outcome = attempt(() => this.#execute());
4650
5660
  if (this.#poison !== void 0) throw this.#poison;
4651
- if (outcome.success) return this.#counts[0] ?? 1;
5661
+ if (isSuccess(outcome)) return this.#counts[0] ?? 1;
4652
5662
  if (isContractError(outcome.error)) throw outcome.error;
4653
5663
  throw new ContractError("validateShape: shape reflection failed", {
4654
5664
  code: "structure",
@@ -4656,6 +5666,34 @@ var ShapePass = class ShapePass {
4656
5666
  cause: outcome.error
4657
5667
  });
4658
5668
  }
5669
+ #survey(lift) {
5670
+ if (ShapePass.polluted()) return false;
5671
+ const shape = this.#source;
5672
+ if (!isRecord(shape)) return false;
5673
+ const outcome = attempt(() => this.#observe(shape, 0));
5674
+ if (isFailure(outcome) || !outcome.value || this.#domain !== void 0) return false;
5675
+ const seal = {
5676
+ category: shape.category,
5677
+ reach: this.#raw,
5678
+ count: 1,
5679
+ defaulted: this.#defaulted,
5680
+ held: this.#defaulted
5681
+ };
5682
+ for (const index of iterateIndices(() => this.#children.length)) {
5683
+ const child = this.#children[index];
5684
+ const known = INTRINSICS.reflect.apply(INTRINSICS.recall, ShapePass.#seals, [child?.shape]);
5685
+ if (child === void 0 || known === void 0) return false;
5686
+ if (known.category === "optional" && !child.optional) return false;
5687
+ if (known.held && shape.category === "union") return false;
5688
+ if (known.defaulted && this.#open) return false;
5689
+ seal.reach = INTRINSICS.max(seal.reach, known.reach + 1);
5690
+ seal.count += known.count;
5691
+ seal.held ||= known.held;
5692
+ }
5693
+ if (seal.reach + lift > 512) return false;
5694
+ INTRINSICS.reflect.apply(INTRINSICS.retain, ShapePass.#seals, [shape, seal]);
5695
+ return true;
5696
+ }
4659
5697
  #execute() {
4660
5698
  this.#stack[this.#stack.length] = {
4661
5699
  operation: "enter",
@@ -4677,9 +5715,11 @@ var ShapePass = class ShapePass {
4677
5715
  this.#path.length -= frame.segments;
4678
5716
  return;
4679
5717
  }
4680
- const segments = (frame.first === void 0 ? 0 : 1) + (frame.second === void 0 ? 0 : 1);
4681
- if (frame.first !== void 0) this.#path[this.#path.length] = frame.first;
4682
- if (frame.second !== void 0) this.#path[this.#path.length] = frame.second;
5718
+ const first = INTRINSICS.own(frame, "first") ? frame.first : void 0;
5719
+ const second = INTRINSICS.own(frame, "second") ? frame.second : void 0;
5720
+ const segments = (first === void 0 ? 0 : 1) + (second === void 0 ? 0 : 1);
5721
+ if (first !== void 0) this.#path[this.#path.length] = first;
5722
+ if (second !== void 0) this.#path[this.#path.length] = second;
4683
5723
  const current = frame.shape;
4684
5724
  if (typeof current !== "object" || current === null || !isRecord(current)) {
4685
5725
  this.#structure ??= new ContractError("validateShape: every structural child must be a shape", {
@@ -4706,8 +5746,11 @@ var ShapePass = class ShapePass {
4706
5746
  this.#children = [];
4707
5747
  this.#category = void 0;
4708
5748
  this.#raw = 0;
5749
+ this.#defaulted = false;
5750
+ this.#open = false;
4709
5751
  const outcome = attempt(() => this.#observe(current, frame.depth));
4710
- if (!outcome.success || !outcome.value) {
5752
+ this.#spend(0);
5753
+ if (isFailure(outcome) || !outcome.value) {
4711
5754
  this.#structure ??= new ContractError("validateShape: every node must be a recognized shape", {
4712
5755
  code: "structure",
4713
5756
  context: { path: pathOf(this.#path) }
@@ -4723,7 +5766,7 @@ var ShapePass = class ShapePass {
4723
5766
  if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) return this.#refuse("validateShape: every node must be a recognized shape");
4724
5767
  const category = current.category;
4725
5768
  if (current.category !== category || descriptor.value !== category) return this.#refuse("validateShape: every node must be a recognized shape");
4726
- const fields = this.#recognize(category);
5769
+ const fields = typeof category === "string" && INTRINSICS.own(SHAPE_FIELDS, category) ? SHAPE_FIELDS[category] : void 0;
4727
5770
  if (fields === void 0) return this.#refuse("validateShape: every node must be a recognized shape");
4728
5771
  this.#category = category;
4729
5772
  if (!this.#scan(current, fields)) return false;
@@ -4731,66 +5774,27 @@ var ShapePass = class ShapePass {
4731
5774
  if (category === "raw") {
4732
5775
  const schema = current.schema;
4733
5776
  const outcome = attempt(() => this.#inspect(schema));
4734
- if (!outcome.success) return this.#refuse("validateShape: every node must be a recognized shape", "schema");
5777
+ if (isFailure(outcome)) return this.#refuse("validateShape: every node must be a recognized shape", "schema");
4735
5778
  if (!outcome.value) return false;
4736
5779
  if (depth + this.#raw > 512) return this.#refuse("validateShape: raw schema exceeds the compilation depth limit", "schema");
4737
5780
  }
4738
5781
  if (category === "object") {
4739
5782
  const outcome = attempt(() => this.#populate(current));
4740
- if (!outcome.success) return this.#refuse("validateShape: every node must be a recognized shape", "properties");
5783
+ if (isFailure(outcome)) return this.#refuse("validateShape: every node must be a recognized shape", "properties");
4741
5784
  return outcome.value;
4742
5785
  }
4743
5786
  if (category === "union") {
4744
5787
  const outcome = attempt(() => this.#populate(current));
4745
- if (!outcome.success) return this.#refuse("validateShape: every node must be a recognized shape", "variants");
5788
+ if (isFailure(outcome)) return this.#refuse("validateShape: every node must be a recognized shape", "variants");
4746
5789
  return outcome.value;
4747
5790
  }
4748
5791
  if (category === "literal") {
4749
5792
  const outcome = attempt(() => this.#populate(current));
4750
- if (!outcome.success) return this.#refuse("validateShape: every node must be a recognized shape", "values");
5793
+ if (isFailure(outcome)) return this.#refuse("validateShape: every node must be a recognized shape", "values");
4751
5794
  return outcome.value;
4752
5795
  }
4753
5796
  return this.#populate(current);
4754
5797
  }
4755
- #recognize(category) {
4756
- switch (category) {
4757
- case "string": return [
4758
- "min",
4759
- "max",
4760
- "pattern",
4761
- "description"
4762
- ];
4763
- case "number": return [
4764
- "integer",
4765
- "min",
4766
- "max",
4767
- "description"
4768
- ];
4769
- case "boolean":
4770
- case "null":
4771
- case "json": return ["description"];
4772
- case "literal": return ["values", "description"];
4773
- case "array": return [
4774
- "items",
4775
- "min",
4776
- "max",
4777
- "description"
4778
- ];
4779
- case "object": return [
4780
- "properties",
4781
- "additionalProperties",
4782
- "description"
4783
- ];
4784
- case "union": return [
4785
- "variants",
4786
- "mode",
4787
- "description"
4788
- ];
4789
- case "optional":
4790
- case "nullable": return ["inner"];
4791
- case "raw": return ["schema"];
4792
- }
4793
- }
4794
5798
  #scan(current, fields) {
4795
5799
  for (const fieldIndex of iterateIndices(() => fields.length)) {
4796
5800
  const field = fields[fieldIndex];
@@ -4807,12 +5811,16 @@ var ShapePass = class ShapePass {
4807
5811
  }
4808
5812
  return field === "pattern" && isRegExp(first) && isRegExp(second) && readPatternSource(first) === readPatternSource(second) && readPatternFlags(first) === readPatternFlags(second) && INTRINSICS.frozen(first) && INTRINSICS.frozen(second);
4809
5813
  });
4810
- if (!outcome.success || !outcome.value) return this.#refuse("validateShape: every node must be a recognized shape", field);
5814
+ if (isFailure(outcome) || !outcome.value) return this.#refuse("validateShape: every node must be a recognized shape", field);
4811
5815
  }
4812
5816
  return true;
4813
5817
  }
4814
5818
  #constrain(current) {
4815
5819
  if (current.category !== "optional" && current.category !== "nullable" && current.category !== "raw" && current.description !== void 0 && typeof current.description !== "string") return this.#refuse("validateShape: description must be a string", "description");
5820
+ if (current.category === "optional" && INTRINSICS.own(current, "default")) {
5821
+ if (!holds(() => matchesJSONValue(current.default, new ShapePass.#weakSet(), this.#budget))) return this.#refuse("validateShape: an optional default must be a JSON value", "default");
5822
+ this.#defaulted = true;
5823
+ }
4816
5824
  if (current.category === "string") {
4817
5825
  if (current.min !== void 0 && typeof current.min !== "number") return this.#refuse("validateShape: string min must be a number", "min");
4818
5826
  if (current.max !== void 0 && typeof current.max !== "number") return this.#refuse("validateShape: string max must be a number", "max");
@@ -4848,7 +5856,7 @@ var ShapePass = class ShapePass {
4848
5856
  received: INTRINSICS.text(current.max)
4849
5857
  }
4850
5858
  });
4851
- if (this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && current.min > current.max) this.#domain = new ContractError("validateShape: a number shape has min greater than max", {
5859
+ if (this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && typeof current.min === "number" && typeof current.max === "number" && current.min > current.max) this.#domain = new ContractError("validateShape: a number shape has min greater than max", {
4852
5860
  code: "range",
4853
5861
  context: {
4854
5862
  path: pathOf(this.#path),
@@ -4867,7 +5875,7 @@ var ShapePass = class ShapePass {
4867
5875
  }
4868
5876
  if (current.category === "array" && current.min !== void 0 && typeof current.min !== "number") return this.#refuse("validateShape: array min must be a number", "min");
4869
5877
  if (current.category === "array" && current.max !== void 0 && typeof current.max !== "number") return this.#refuse("validateShape: array max must be a number", "max");
4870
- if (current.category === "array" && this.#domain === void 0 && current.min !== void 0 && (!INTRINSICS.safe(current.min) || current.min < 0)) this.#domain = new ContractError("validateShape: an array shape min must be a non-negative safe integer", {
5878
+ if (current.category === "array" && this.#domain === void 0 && current.min !== void 0 && (typeof current.min !== "number" || !INTRINSICS.safe(current.min) || current.min < 0)) this.#domain = new ContractError("validateShape: an array shape min must be a non-negative safe integer", {
4871
5879
  code: "bound",
4872
5880
  context: {
4873
5881
  path: pathOf(this.#path),
@@ -4876,7 +5884,7 @@ var ShapePass = class ShapePass {
4876
5884
  received: INTRINSICS.text(current.min)
4877
5885
  }
4878
5886
  });
4879
- if (current.category === "array" && this.#domain === void 0 && current.max !== void 0 && (!INTRINSICS.safe(current.max) || current.max < 0)) this.#domain = new ContractError("validateShape: an array shape max must be a non-negative safe integer", {
5887
+ if (current.category === "array" && this.#domain === void 0 && current.max !== void 0 && (typeof current.max !== "number" || !INTRINSICS.safe(current.max) || current.max < 0)) this.#domain = new ContractError("validateShape: an array shape max must be a non-negative safe integer", {
4880
5888
  code: "bound",
4881
5889
  context: {
4882
5890
  path: pathOf(this.#path),
@@ -4885,7 +5893,7 @@ var ShapePass = class ShapePass {
4885
5893
  received: INTRINSICS.text(current.max)
4886
5894
  }
4887
5895
  });
4888
- if (current.category === "array" && this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && current.min > current.max) this.#domain = new ContractError("validateShape: an array shape has min greater than max", {
5896
+ if (current.category === "array" && this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && typeof current.min === "number" && typeof current.max === "number" && current.min > current.max) this.#domain = new ContractError("validateShape: an array shape has min greater than max", {
4889
5897
  code: "range",
4890
5898
  context: {
4891
5899
  path: pathOf(this.#path),
@@ -4907,7 +5915,7 @@ var ShapePass = class ShapePass {
4907
5915
  });
4908
5916
  }
4909
5917
  #restrict(current, source = "", flags = "") {
4910
- if (this.#domain === void 0 && current.min !== void 0 && (!INTRINSICS.safe(current.min) || current.min < 0)) this.#domain = new ContractError("validateShape: a string shape min must be a non-negative safe integer", {
5918
+ if (this.#domain === void 0 && current.min !== void 0 && (typeof current.min !== "number" || !INTRINSICS.safe(current.min) || current.min < 0)) this.#domain = new ContractError("validateShape: a string shape min must be a non-negative safe integer", {
4911
5919
  code: "bound",
4912
5920
  context: {
4913
5921
  path: pathOf(this.#path),
@@ -4916,7 +5924,7 @@ var ShapePass = class ShapePass {
4916
5924
  received: INTRINSICS.text(current.min)
4917
5925
  }
4918
5926
  });
4919
- if (this.#domain === void 0 && current.max !== void 0 && (!INTRINSICS.safe(current.max) || current.max < 0)) this.#domain = new ContractError("validateShape: a string shape max must be a non-negative safe integer", {
5927
+ if (this.#domain === void 0 && current.max !== void 0 && (typeof current.max !== "number" || !INTRINSICS.safe(current.max) || current.max < 0)) this.#domain = new ContractError("validateShape: a string shape max must be a non-negative safe integer", {
4920
5928
  code: "bound",
4921
5929
  context: {
4922
5930
  path: pathOf(this.#path),
@@ -4933,7 +5941,7 @@ var ShapePass = class ShapePass {
4933
5941
  received: `/${source}/${flags}`
4934
5942
  }
4935
5943
  });
4936
- if (this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && current.min > current.max) this.#domain = new ContractError("validateShape: a string shape has min greater than max", {
5944
+ if (this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && typeof current.min === "number" && typeof current.max === "number" && current.min > current.max) this.#domain = new ContractError("validateShape: a string shape has min greater than max", {
4937
5945
  code: "range",
4938
5946
  context: {
4939
5947
  path: pathOf(this.#path),
@@ -4942,6 +5950,7 @@ var ShapePass = class ShapePass {
4942
5950
  });
4943
5951
  }
4944
5952
  #inspect(source) {
5953
+ if (this.#structure !== void 0) return true;
4945
5954
  if (!isRecord(source)) return this.#refuse("validateShape: raw schema must be a plain record", "schema");
4946
5955
  const active = new ShapePass.#weakSet();
4947
5956
  const stack = [{
@@ -4956,24 +5965,27 @@ var ShapePass = class ShapePass {
4956
5965
  this.#settleSchema(frame.schema, frame.nested);
4957
5966
  continue;
4958
5967
  }
5968
+ const first = INTRINSICS.own(frame, "first") ? frame.first : void 0;
5969
+ const second = INTRINSICS.own(frame, "second") ? frame.second : void 0;
4959
5970
  const schema = frame.schema;
4960
- if (!isRecord(schema)) return this.#refuse("validateShape: every raw schema child must be a plain record", "schema");
4961
- if (matchesVisited(active, schema)) return this.#refuse("validateShape: a raw schema may not contain a cycle", "schema");
5971
+ if (!isRecord(schema)) return this.#refuseSchema("validateShape: every raw schema child must be a plain record", stack, first, second, void 0);
5972
+ if (matchesVisited(active, schema)) return this.#refuseSchema("validateShape: a raw schema may not contain a cycle", stack, first, second, void 0);
4962
5973
  if (INTRINSICS.reflect.apply(INTRINSICS.recall, this.#schemas, [schema]) !== void 0) continue;
4963
5974
  admitVisited(active, schema);
4964
5975
  const keyList = INTRINSICS.keys(schema);
4965
5976
  for (const keyIndex of iterateIndices(() => keyList.length)) {
4966
5977
  const key = keyList[keyIndex];
4967
5978
  if (key === void 0) continue;
4968
- if (key !== "type" && key !== "description" && key !== "enum" && key !== "minLength" && key !== "maxLength" && key !== "pattern" && key !== "format" && key !== "minimum" && key !== "maximum" && key !== "minItems" && key !== "maxItems" && key !== "items" && key !== "properties" && key !== "required" && key !== "additionalProperties" && key !== "anyOf" && key !== "oneOf") return this.#refuse("validateShape: raw schema contains an unsupported keyword", "schema");
5979
+ if (key !== "type" && key !== "description" && key !== "default" && key !== "enum" && key !== "minLength" && key !== "maxLength" && key !== "pattern" && key !== "format" && key !== "minimum" && key !== "maximum" && key !== "minItems" && key !== "maxItems" && key !== "items" && key !== "properties" && key !== "required" && key !== "additionalProperties" && key !== "anyOf" && key !== "oneOf") return this.#refuseSchema("validateShape: raw schema contains an unsupported keyword", stack, first, second, key);
4969
5980
  }
4970
- const category = schema.type;
4971
- if (category !== void 0 && category !== "null" && category !== "boolean" && category !== "object" && category !== "array" && category !== "number" && category !== "integer" && category !== "string") return this.#refuse("validateShape: raw schema type is outside the supported vocabulary", "schema");
4972
- if (schema.description !== void 0 && typeof schema.description !== "string") return this.#refuse("validateShape: raw schema description must be a string", "schema");
4973
- if (schema.format !== void 0 && typeof schema.format !== "string") return this.#refuse("validateShape: raw schema format must be a string", "schema");
4974
- if (schema.pattern !== void 0) {
4975
- if (typeof schema.pattern !== "string") return this.#refuse("validateShape: raw schema pattern must be a string", "schema");
4976
- if (!attempt(() => INTRINSICS.reflect.apply(INTRINSICS.pattern, void 0, [schema.pattern])).success) return this.#refuse("validateShape: raw schema pattern must be valid", "schema");
5981
+ const category = INTRINSICS.own(schema, "type") ? schema.type : void 0;
5982
+ if (category !== void 0 && category !== "null" && category !== "boolean" && category !== "object" && category !== "array" && category !== "number" && category !== "integer" && category !== "string") return this.#refuseSchema("validateShape: raw schema type is outside the supported vocabulary", stack, first, second, "type");
5983
+ if (INTRINSICS.own(schema, "description") && schema.description !== void 0 && typeof schema.description !== "string") return this.#refuseSchema("validateShape: raw schema description must be a string", stack, first, second, "description");
5984
+ if (INTRINSICS.own(schema, "default") && !isJSONValue(schema.default)) return this.#refuseSchema("validateShape: raw schema default must be a JSON value", stack, first, second, "default");
5985
+ if (INTRINSICS.own(schema, "format") && schema.format !== void 0 && typeof schema.format !== "string") return this.#refuseSchema("validateShape: raw schema format must be a string", stack, first, second, "format");
5986
+ if (INTRINSICS.own(schema, "pattern") && schema.pattern !== void 0) {
5987
+ if (typeof schema.pattern !== "string") return this.#refuseSchema("validateShape: raw schema pattern must be a string", stack, first, second, "pattern");
5988
+ if (isFailure(attempt(() => INTRINSICS.reflect.apply(INTRINSICS.pattern, void 0, [schema.pattern])))) return this.#refuseSchema("validateShape: raw schema pattern must be valid", stack, first, second, "pattern");
4977
5989
  }
4978
5990
  const lengthList = [
4979
5991
  "minLength",
@@ -4984,77 +5996,95 @@ var ShapePass = class ShapePass {
4984
5996
  for (const lengthIndex of iterateIndices(() => lengthList.length)) {
4985
5997
  const key = lengthList[lengthIndex];
4986
5998
  if (key === void 0) continue;
4987
- const value = schema[key];
4988
- if (value !== void 0 && (!INTRINSICS.safe(value) || INTRINSICS.numeric(value) < 0)) return this.#refuse("validateShape: raw schema length bounds must be non-negative safe integers", "schema");
5999
+ const value = INTRINSICS.own(schema, key) ? schema[key] : void 0;
6000
+ if (value !== void 0 && (!INTRINSICS.safe(value) || INTRINSICS.numeric(value) < 0)) return this.#refuseSchema("validateShape: raw schema length bounds must be non-negative safe integers", stack, first, second, key);
4989
6001
  }
4990
6002
  const rangeList = ["minimum", "maximum"];
4991
6003
  for (const rangeIndex of iterateIndices(() => rangeList.length)) {
4992
6004
  const key = rangeList[rangeIndex];
4993
6005
  if (key === void 0) continue;
4994
- const value = schema[key];
4995
- if (value !== void 0 && (typeof value !== "number" || !INTRINSICS.finite(value))) return this.#refuse("validateShape: raw schema numeric bounds must be finite numbers", "schema");
6006
+ const value = INTRINSICS.own(schema, key) ? schema[key] : void 0;
6007
+ if (value !== void 0 && (typeof value !== "number" || !INTRINSICS.finite(value))) return this.#refuseSchema("validateShape: raw schema numeric bounds must be finite numbers", stack, first, second, key);
4996
6008
  }
4997
- const population = schema.enum;
6009
+ const population = INTRINSICS.own(schema, "enum") ? schema.enum : void 0;
4998
6010
  if (population !== void 0) {
4999
- if (!INTRINSICS.array(population)) return this.#refuse("validateShape: raw schema enum must be a non-empty array", "schema");
6011
+ if (!INTRINSICS.array(population)) return this.#refuseSchema("validateShape: raw schema enum must be a non-empty array", stack, first, second, "enum");
5000
6012
  const snapshot = readArrayEntries(population);
5001
- if (!snapshot.success || snapshot.value.entries.length === 0) return this.#refuse("validateShape: raw schema enum must be a non-empty array", "schema");
5002
- if (!snapshot.value.dense) return this.#refuse("validateShape: raw schema enum must be dense", "schema");
6013
+ if (isFailure(snapshot) || snapshot.value.entries.length === 0) return this.#refuseSchema("validateShape: raw schema enum must be a non-empty array", stack, first, second, "enum");
6014
+ if (!snapshot.value.dense) return this.#refuseSchema("validateShape: raw schema enum must be dense", stack, first, second, "enum");
5003
6015
  const values = collectMembers([]);
5004
6016
  for (const valueIndex of iterateIndices(() => snapshot.value.entries.length)) {
5005
6017
  const value = snapshot.value.entries[valueIndex];
5006
- if (!isLiteralValue(value) || typeof value === "number" && !INTRINSICS.finite(value) || matchesMember(values, value)) return this.#refuse("validateShape: raw schema enum values must be finite unique primitives", "schema");
6018
+ if (!isLiteralValue(value) || typeof value === "number" && !INTRINSICS.finite(value) || matchesMember(values, value)) return this.#refuseSchema("validateShape: raw schema enum values must be finite unique primitives", stack, first, second, "enum", INTRINSICS.text(valueIndex));
5007
6019
  admitMember(values, value);
5008
6020
  }
5009
6021
  }
5010
- const names = schema.required;
6022
+ const names = INTRINSICS.own(schema, "required") ? schema.required : void 0;
5011
6023
  if (names !== void 0) {
5012
- if (!INTRINSICS.array(names)) return this.#refuse("validateShape: raw schema required must be an array", "schema");
6024
+ if (!INTRINSICS.array(names)) return this.#refuseSchema("validateShape: raw schema required must be an array", stack, first, second, "required");
5013
6025
  const snapshot = readArrayEntries(names);
5014
- if (!snapshot.success) return this.#refuse("validateShape: raw schema required must be an array", "schema");
5015
- if (!snapshot.value.dense) return this.#refuse("validateShape: raw schema required must be dense", "schema");
6026
+ if (isFailure(snapshot)) return this.#refuseSchema("validateShape: raw schema required must be an array", stack, first, second, "required");
6027
+ if (!snapshot.value.dense) return this.#refuseSchema("validateShape: raw schema required must be dense", stack, first, second, "required");
5016
6028
  const required = collectMembers([]);
5017
6029
  for (const valueIndex of iterateIndices(() => snapshot.value.entries.length)) {
5018
6030
  const value = snapshot.value.entries[valueIndex];
5019
6031
  if (value === void 0) continue;
5020
- if (typeof value !== "string" || matchesMember(required, value)) return this.#refuse("validateShape: raw schema required values must be unique strings", "schema");
6032
+ if (typeof value !== "string" || matchesMember(required, value)) return this.#refuseSchema("validateShape: raw schema required values must be unique strings", stack, first, second, "required", INTRINSICS.text(valueIndex));
5021
6033
  admitMember(required, value);
5022
6034
  }
5023
6035
  }
5024
6036
  const nested = [];
5025
- if (schema.items !== void 0) nested[nested.length] = schema.items;
5026
- if (schema.properties !== void 0) {
5027
- if (!isRecord(schema.properties)) return this.#refuse("validateShape: raw schema properties must be a plain record", "schema");
6037
+ const edges = [];
6038
+ if (INTRINSICS.own(schema, "items") && schema.items !== void 0) {
6039
+ edges[nested.length] = ["items"];
6040
+ nested[nested.length] = schema.items;
6041
+ }
6042
+ if (INTRINSICS.own(schema, "properties") && schema.properties !== void 0) {
6043
+ if (!isRecord(schema.properties)) return this.#refuseSchema("validateShape: raw schema properties must be a plain record", stack, first, second, "properties");
5028
6044
  const propertyList = INTRINSICS.keys(schema.properties);
5029
6045
  for (const propertyIndex of iterateIndices(() => propertyList.length)) {
5030
6046
  const key = propertyList[propertyIndex];
5031
6047
  if (key === void 0) continue;
5032
- nested[nested.length] = schema.properties[key];
6048
+ edges[nested.length] = ["properties", key];
6049
+ nested[nested.length] = INTRINSICS.own(schema.properties, key) ? schema.properties[key] : void 0;
5033
6050
  }
5034
6051
  }
5035
- if (schema.additionalProperties !== void 0 && schema.additionalProperties !== true && schema.additionalProperties !== false) nested[nested.length] = schema.additionalProperties;
6052
+ if (INTRINSICS.own(schema, "additionalProperties") && schema.additionalProperties !== void 0 && schema.additionalProperties !== true && schema.additionalProperties !== false) {
6053
+ edges[nested.length] = ["additionalProperties"];
6054
+ nested[nested.length] = schema.additionalProperties;
6055
+ }
5036
6056
  const unionList = ["anyOf", "oneOf"];
5037
6057
  for (const unionIndex of iterateIndices(() => unionList.length)) {
5038
6058
  const key = unionList[unionIndex];
5039
6059
  if (key === void 0) continue;
5040
- const variants = schema[key];
6060
+ const variants = INTRINSICS.own(schema, key) ? schema[key] : void 0;
5041
6061
  if (variants === void 0) continue;
5042
- if (!INTRINSICS.array(variants)) return this.#refuse("validateShape: raw schema unions must be non-empty arrays", "schema");
6062
+ if (!INTRINSICS.array(variants)) return this.#refuseSchema("validateShape: raw schema unions must be non-empty arrays", stack, first, second, key);
5043
6063
  const snapshot = readArrayEntries(variants);
5044
- if (!snapshot.success || snapshot.value.entries.length === 0) return this.#refuse("validateShape: raw schema unions must be non-empty arrays", "schema");
5045
- if (!snapshot.value.dense) return this.#refuse("validateShape: raw schema unions must be dense arrays", "schema");
5046
- for (const variantIndex of iterateIndices(() => snapshot.value.entries.length)) nested[nested.length] = snapshot.value.entries[variantIndex];
6064
+ if (isFailure(snapshot) || snapshot.value.entries.length === 0) return this.#refuseSchema("validateShape: raw schema unions must be non-empty arrays", stack, first, second, key);
6065
+ if (!snapshot.value.dense) return this.#refuseSchema("validateShape: raw schema unions must be dense arrays", stack, first, second, key);
6066
+ for (const variantIndex of iterateIndices(() => snapshot.value.entries.length)) {
6067
+ edges[nested.length] = [key, INTRINSICS.text(variantIndex)];
6068
+ nested[nested.length] = snapshot.value.entries[variantIndex];
6069
+ }
5047
6070
  }
5048
6071
  stack[stack.length] = {
5049
6072
  operation: "exit",
5050
6073
  schema,
5051
- nested
6074
+ nested,
6075
+ ...first === void 0 ? {} : { first },
6076
+ ...second === void 0 ? {} : { second }
5052
6077
  };
5053
6078
  for (const offset of iterateIndices(() => nested.length)) {
5054
6079
  const index = nested.length - 1 - offset;
6080
+ const childFirst = edges[index]?.[0];
6081
+ const edge = edges[index];
6082
+ const childSecond = edge !== void 0 && INTRINSICS.own(edge, 1) ? edge[1] : void 0;
5055
6083
  stack[stack.length] = {
5056
6084
  operation: "enter",
5057
- schema: nested[index]
6085
+ schema: nested[index],
6086
+ ...childFirst === void 0 ? {} : { first: childFirst },
6087
+ ...childSecond === void 0 ? {} : { second: childSecond }
5058
6088
  };
5059
6089
  }
5060
6090
  }
@@ -5071,6 +6101,7 @@ var ShapePass = class ShapePass {
5071
6101
  #populate(current) {
5072
6102
  switch (current.category) {
5073
6103
  case "array":
6104
+ this.#spend(1);
5074
6105
  this.#children[this.#children.length] = {
5075
6106
  shape: current.items,
5076
6107
  first: "items",
@@ -5084,8 +6115,9 @@ var ShapePass = class ShapePass {
5084
6115
  for (const keyIndex of iterateIndices(() => keys.length)) {
5085
6116
  const key = keys[keyIndex];
5086
6117
  if (key === void 0) continue;
6118
+ this.#spend(1);
5087
6119
  const descriptorOutcome = attempt(() => INTRINSICS.describe(properties, key));
5088
- if (!descriptorOutcome.success) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
6120
+ if (isFailure(descriptorOutcome)) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
5089
6121
  const descriptor = descriptorOutcome.value;
5090
6122
  if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) {
5091
6123
  this.#children[this.#children.length] = {
@@ -5096,11 +6128,17 @@ var ShapePass = class ShapePass {
5096
6128
  };
5097
6129
  continue;
5098
6130
  }
5099
- const childOutcome = attempt(() => current.properties[key]);
5100
- if (!childOutcome.success) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
6131
+ const childOutcome = attempt(() => {
6132
+ const population = current.properties;
6133
+ return isRecord(population) ? population[key] : void 0;
6134
+ });
6135
+ if (isFailure(childOutcome)) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
5101
6136
  const child = childOutcome.value;
5102
- const stable = attempt(() => INTRINSICS.same(current.properties[key], child) && INTRINSICS.same(descriptor.value, child));
5103
- if (!stable.success) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
6137
+ const stable = attempt(() => {
6138
+ const population = current.properties;
6139
+ return isRecord(population) && INTRINSICS.same(population[key], child) && INTRINSICS.same(descriptor.value, child);
6140
+ });
6141
+ if (isFailure(stable)) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
5104
6142
  if (!stable.value) {
5105
6143
  this.#children[this.#children.length] = {
5106
6144
  shape: void 0,
@@ -5118,17 +6156,21 @@ var ShapePass = class ShapePass {
5118
6156
  };
5119
6157
  }
5120
6158
  const extra = current.additionalProperties;
5121
- if (extra !== void 0 && extra !== true && extra !== false) this.#children[this.#children.length] = {
5122
- shape: extra,
5123
- first: "additionalProperties",
5124
- optional: false
5125
- };
6159
+ this.#open = extra !== void 0 && extra !== false;
6160
+ if (extra !== void 0 && extra !== true && extra !== false) {
6161
+ this.#spend(1);
6162
+ this.#children[this.#children.length] = {
6163
+ shape: extra,
6164
+ first: "additionalProperties",
6165
+ optional: false
6166
+ };
6167
+ }
5126
6168
  break;
5127
6169
  }
5128
6170
  case "union": {
5129
6171
  if (!INTRINSICS.array(current.variants)) return this.#refuse("validateShape: variants must be a finite array", "variants");
5130
6172
  const snapshot = readArrayEntries(current.variants);
5131
- if (!snapshot.success) return this.#refuse("validateShape: variants must be a finite array", "variants");
6173
+ if (isFailure(snapshot)) return this.#refuse("validateShape: variants must be a finite array", "variants");
5132
6174
  if (!snapshot.value.dense) return this.#refuse("validateShape: variants must be a dense data array", "variants");
5133
6175
  const variants = snapshot.value.entries;
5134
6176
  const length = variants.length;
@@ -5141,8 +6183,9 @@ var ShapePass = class ShapePass {
5141
6183
  });
5142
6184
  for (const index of iterateIndices(() => length)) {
5143
6185
  const key = INTRINSICS.text(index);
6186
+ this.#spend(1);
5144
6187
  const descriptorOutcome = attempt(() => INTRINSICS.describe(current.variants, key));
5145
- if (!descriptorOutcome.success) return this.#refuse("validateShape: every node must be a recognized shape", "variants", key);
6188
+ if (isFailure(descriptorOutcome)) return this.#refuse("validateShape: every node must be a recognized shape", "variants", key);
5146
6189
  const descriptor = descriptorOutcome.value;
5147
6190
  if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) {
5148
6191
  this.#children[this.#children.length] = {
@@ -5154,8 +6197,11 @@ var ShapePass = class ShapePass {
5154
6197
  continue;
5155
6198
  }
5156
6199
  const variant = variants[index];
5157
- const stable = attempt(() => INTRINSICS.same(current.variants[index], variant) && INTRINSICS.same(descriptor.value, variant));
5158
- if (!stable.success) return this.#refuse("validateShape: every node must be a recognized shape", "variants", key);
6200
+ const stable = attempt(() => {
6201
+ const population = current.variants;
6202
+ return INTRINSICS.array(population) && INTRINSICS.same(population[index], variant) && INTRINSICS.same(descriptor.value, variant);
6203
+ });
6204
+ if (isFailure(stable)) return this.#refuse("validateShape: every node must be a recognized shape", "variants", key);
5159
6205
  if (!stable.value) {
5160
6206
  this.#children[this.#children.length] = {
5161
6207
  shape: void 0,
@@ -5177,7 +6223,7 @@ var ShapePass = class ShapePass {
5177
6223
  case "literal": {
5178
6224
  if (!INTRINSICS.array(current.values)) return this.#refuse("validateShape: values must be a finite literal array", "values");
5179
6225
  const snapshot = readArrayEntries(current.values);
5180
- if (!snapshot.success) return this.#refuse("validateShape: values must be a finite literal array", "values");
6226
+ if (isFailure(snapshot)) return this.#refuse("validateShape: values must be a finite literal array", "values");
5181
6227
  if (!snapshot.value.dense) return this.#refuse("validateShape: values must be a dense data array", "values");
5182
6228
  const literals = snapshot.value.entries;
5183
6229
  const length = literals.length;
@@ -5192,12 +6238,15 @@ var ShapePass = class ShapePass {
5192
6238
  for (const index of iterateIndices(() => length)) {
5193
6239
  const key = INTRINSICS.text(index);
5194
6240
  const descriptorOutcome = attempt(() => INTRINSICS.describe(current.values, key));
5195
- if (!descriptorOutcome.success) return this.#refuse("validateShape: every node must be a recognized shape", "values", key);
6241
+ if (isFailure(descriptorOutcome)) return this.#refuse("validateShape: every node must be a recognized shape", "values", key);
5196
6242
  const descriptor = descriptorOutcome.value;
5197
6243
  if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) return this.#refuse("validateShape: values must be a dense data array", "values", key);
5198
6244
  const value = literals[index];
5199
- const stable = attempt(() => INTRINSICS.same(current.values[index], value) && INTRINSICS.same(descriptor.value, value));
5200
- if (!stable.success) return this.#refuse("validateShape: every node must be a recognized shape", "values", key);
6245
+ const stable = attempt(() => {
6246
+ const population = current.values;
6247
+ return INTRINSICS.array(population) && INTRINSICS.same(population[index], value) && INTRINSICS.same(descriptor.value, value);
6248
+ });
6249
+ if (isFailure(stable)) return this.#refuse("validateShape: every node must be a recognized shape", "values", key);
5201
6250
  if (!stable.value) return this.#refuse("validateShape: values must be a stable data array", "values", key);
5202
6251
  if (!isLiteralValue(value)) return this.#refuse("validateShape: every literal value must be a string, number, or boolean", "values", key);
5203
6252
  if (matchesMember(values, value)) return this.#refuse("validateShape: literal values must be unique", "values", key);
@@ -5214,14 +6263,28 @@ var ShapePass = class ShapePass {
5214
6263
  break;
5215
6264
  }
5216
6265
  case "optional":
5217
- case "nullable": this.#children[this.#children.length] = {
5218
- shape: current.inner,
5219
- first: "inner",
5220
- optional: false
5221
- };
6266
+ case "nullable":
6267
+ this.#spend(1);
6268
+ this.#children[this.#children.length] = {
6269
+ shape: current.inner,
6270
+ first: "inner",
6271
+ optional: false
6272
+ };
5222
6273
  }
5223
6274
  return true;
5224
6275
  }
6276
+ #spend(count) {
6277
+ const budget = this.#budget;
6278
+ if (budget === void 0) return;
6279
+ budget.left -= count;
6280
+ if (budget.left < 0) throw new ContractError(`validateShape: capture exceeds the node limit ${CLONE_NODE_LIMIT}`, {
6281
+ code: "clone",
6282
+ context: {
6283
+ path: pathOf(this.#path),
6284
+ limit: CLONE_NODE_LIMIT
6285
+ }
6286
+ });
6287
+ }
5225
6288
  #schedule(current, depth, segments) {
5226
6289
  admitVisited(this.#active, current);
5227
6290
  const children = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(this.#children), [(child) => child !== void 0]);
@@ -5240,7 +6303,7 @@ var ShapePass = class ShapePass {
5240
6303
  depth: depth + 1,
5241
6304
  optional: child.optional,
5242
6305
  first: child.first,
5243
- ...child.second === void 0 ? {} : { second: child.second }
6306
+ ...INTRINSICS.own(child, "second") && child.second !== void 0 ? { second: child.second } : {}
5244
6307
  };
5245
6308
  }
5246
6309
  return captured;
@@ -5251,25 +6314,27 @@ var ShapePass = class ShapePass {
5251
6314
  shape,
5252
6315
  category: this.#category,
5253
6316
  children,
5254
- raw: this.#raw
6317
+ raw: this.#raw,
6318
+ defaulted: this.#defaulted,
6319
+ open: this.#open
5255
6320
  };
5256
6321
  INTRINSICS.reflect.apply(INTRINSICS.retain, this.#index, [shape, index]);
5257
6322
  return index;
5258
6323
  }
5259
6324
  #locate(shape) {
5260
- if (shape === void 0) return void 0;
6325
+ if (typeof shape !== "object" || shape === null) return void 0;
5261
6326
  return INTRINSICS.reflect.apply(INTRINSICS.recall, this.#index, [shape]);
5262
6327
  }
5263
6328
  #measure() {
6329
+ if (this.#cycle !== void 0) {
6330
+ this.#finish();
6331
+ return;
6332
+ }
5264
6333
  for (const index of iterateIndices(() => this.#captures.length)) {
5265
6334
  this.#height[index] = 0;
5266
6335
  this.#reach[index] = 0;
5267
6336
  this.#counts[index] = 1;
5268
6337
  }
5269
- if (this.#cycle !== void 0) {
5270
- this.#trace();
5271
- return;
5272
- }
5273
6338
  for (const step of iterateIndices(() => this.#post.length)) {
5274
6339
  const index = this.#post[step];
5275
6340
  if (index === void 0) continue;
@@ -5307,7 +6372,7 @@ var ShapePass = class ShapePass {
5307
6372
  this.#via[located] = {
5308
6373
  parent: index,
5309
6374
  first: child.first,
5310
- ...child.second === void 0 ? {} : { second: child.second }
6375
+ ...INTRINSICS.own(child, "second") && child.second !== void 0 ? { second: child.second } : {}
5311
6376
  };
5312
6377
  }
5313
6378
  }
@@ -5320,11 +6385,52 @@ var ShapePass = class ShapePass {
5320
6385
  context: { path: pathOf(this.#ascend(index), "schema") }
5321
6386
  });
5322
6387
  }
6388
+ this.#placeDefaults();
6389
+ }
6390
+ #placeDefaults() {
6391
+ if (!INTRINSICS.reflect.apply(INTRINSICS.some, this.#captures, [(capture) => capture.defaulted])) return;
6392
+ for (const offset of iterateIndices(() => this.#post.length)) {
6393
+ const index = this.#post[this.#post.length - 1 - offset];
6394
+ if (index === void 0) continue;
6395
+ const capture = this.#captures[index];
6396
+ if (capture === void 0) continue;
6397
+ const enclosed = capture.category === "union" || INTRINSICS.own(this.#within, index) && this.#within[index] !== void 0;
6398
+ for (const edge of iterateIndices(() => capture.children.length)) {
6399
+ const child = capture.children[edge];
6400
+ if (child === void 0) continue;
6401
+ const located = this.#locate(child.shape);
6402
+ if (located === void 0) continue;
6403
+ if (enclosed && (!INTRINSICS.own(this.#within, located) || this.#within[located] === void 0)) this.#within[located] = {
6404
+ parent: index,
6405
+ first: child.first,
6406
+ ...INTRINSICS.own(child, "second") && child.second !== void 0 ? { second: child.second } : {}
6407
+ };
6408
+ if (this.#captures[located]?.defaulted !== true) continue;
6409
+ if (enclosed) this.#domain ??= new ContractError("validateShape: a default may not sit under a union, whose parser can return a valid value without filling it; move the default outside the union or remove it", {
6410
+ code: "placement",
6411
+ context: {
6412
+ path: pathOf(this.#route(index), child.first, INTRINSICS.own(child, "second") ? child.second : void 0),
6413
+ shape: "optional"
6414
+ }
6415
+ });
6416
+ if (capture.open) this.#domain ??= new ContractError("validateShape: a default may not sit on a property of an open object, where a misspelled key would fill it unreported; close the object or remove the default", {
6417
+ code: "placement",
6418
+ context: {
6419
+ path: pathOf(this.#ascend(index), child.first, INTRINSICS.own(child, "second") ? child.second : void 0),
6420
+ shape: "optional"
6421
+ }
6422
+ });
6423
+ }
6424
+ }
6425
+ }
6426
+ #route(index) {
6427
+ const edge = INTRINSICS.own(this.#within, index) ? this.#within[index] : void 0;
6428
+ return edge === void 0 ? this.#ascend(index) : pathOf(this.#route(edge.parent), edge.first, INTRINSICS.own(edge, "second") ? edge.second : void 0);
5323
6429
  }
5324
6430
  #ascend(index) {
5325
6431
  if (index === 0) return [];
5326
- const edge = this.#via[index];
5327
- return edge === void 0 ? [] : pathOf(this.#ascend(edge.parent), edge.first, edge.second);
6432
+ const edge = INTRINSICS.own(this.#via, index) ? this.#via[index] : void 0;
6433
+ return edge === void 0 ? [] : pathOf(this.#ascend(edge.parent), edge.first, INTRINSICS.own(edge, "second") ? edge.second : void 0);
5328
6434
  }
5329
6435
  #witness(index, depth, path) {
5330
6436
  if (depth <= 512) {
@@ -5335,7 +6441,7 @@ var ShapePass = class ShapePass {
5335
6441
  const reached = located === void 0 ? 0 : this.#height[located] ?? 0;
5336
6442
  return depth + 1 + reached > 512;
5337
6443
  }])];
5338
- if (chosen !== void 0) return this.#witness(this.#locate(chosen.shape), depth + 1, pathOf(path, chosen.first, chosen.second));
6444
+ if (chosen !== void 0) return this.#witness(this.#locate(chosen.shape), depth + 1, pathOf(path, chosen.first, INTRINSICS.own(chosen, "second") ? chosen.second : void 0));
5339
6445
  }
5340
6446
  throw new ContractError("validateShape: a shape exceeds the compilation depth limit", {
5341
6447
  code: "depth",
@@ -5345,86 +6451,24 @@ var ShapePass = class ShapePass {
5345
6451
  }
5346
6452
  });
5347
6453
  }
5348
- #trace() {
5349
- const settled = [];
5350
- const order = [];
5351
- const active = new ShapePass.#weakSet();
5352
- const stack = [{
5353
- operation: "enter",
5354
- index: 0,
5355
- depth: 0
5356
- }];
5357
- while (stack.length > 0) {
5358
- const frame = stack.pop();
5359
- if (frame === void 0) continue;
5360
- if (frame.operation === "exit") {
5361
- const capture = this.#captures[frame.index];
5362
- if (capture !== void 0) omitVisited(active, capture.shape);
5363
- if (this.#oldest >= (order[frame.index] ?? 0) && (settled[frame.index] ?? -1) < frame.depth) settled[frame.index] = frame.depth;
5364
- if (frame.outer < this.#oldest) this.#oldest = frame.outer;
5365
- this.#trail.length -= frame.segments;
5366
- continue;
5367
- }
5368
- const segments = (frame.first === void 0 ? 0 : 1) + (frame.second === void 0 ? 0 : 1);
5369
- if (frame.first !== void 0) this.#trail[this.#trail.length] = frame.first;
5370
- if (frame.second !== void 0) this.#trail[this.#trail.length] = frame.second;
5371
- if (frame.depth > 512) throw new ContractError("validateShape: a shape exceeds the compilation depth limit", {
5372
- code: "depth",
5373
- context: {
5374
- path: pathOf(this.#trail),
5375
- limit: 512
5376
- }
5377
- });
5378
- const index = frame.index;
5379
- const capture = index === void 0 ? void 0 : this.#captures[index];
5380
- if (index === void 0 || capture === void 0) {
5381
- this.#trail.length -= segments;
5382
- continue;
5383
- }
5384
- if (matchesVisited(active, capture.shape)) {
5385
- const blocker = order[index] ?? 0;
5386
- if (blocker < this.#oldest) this.#oldest = blocker;
5387
- this.#trail.length -= segments;
5388
- continue;
5389
- }
5390
- const recorded = settled[index];
5391
- if (recorded !== void 0 && frame.depth <= recorded) {
5392
- this.#trail.length -= segments;
5393
- continue;
5394
- }
5395
- admitVisited(active, capture.shape);
5396
- order[index] = this.#clock;
5397
- this.#clock += 1;
5398
- stack[stack.length] = {
5399
- operation: "exit",
5400
- index,
5401
- depth: frame.depth,
5402
- segments,
5403
- outer: this.#oldest
5404
- };
5405
- this.#oldest = this.#clock;
5406
- for (const offset of iterateIndices(() => capture.children.length)) {
5407
- const edge = capture.children.length - 1 - offset;
5408
- const child = capture.children[edge];
5409
- if (child === void 0) continue;
5410
- stack[stack.length] = {
5411
- operation: "enter",
5412
- index: this.#locate(child.shape),
5413
- depth: frame.depth + 1,
5414
- first: child.first,
5415
- ...child.second === void 0 ? {} : { second: child.second }
5416
- };
5417
- }
5418
- }
5419
- }
5420
6454
  #finish() {
5421
6455
  if (this.#structure !== void 0) throw this.#structure;
5422
6456
  if (this.#cycle !== void 0) throw this.#cycle;
5423
6457
  if (this.#domain !== void 0) throw this.#domain;
5424
6458
  }
5425
- #refuse(message, first, second) {
6459
+ #refuseSchema(message, stack, first, second, keyword, member) {
6460
+ if (this.#structure !== void 0) return false;
6461
+ const ancestors = INTRINSICS.reflect.apply(INTRINSICS.expand, readIndexView(stack), [(frame) => frame.operation === "exit" ? pathOf([], INTRINSICS.own(frame, "first") ? frame.first : void 0, INTRINSICS.own(frame, "second") ? frame.second : void 0) : []]);
6462
+ const prefix = [];
6463
+ appendEntries(prefix, this.#path);
6464
+ prefix[prefix.length] = "schema";
6465
+ appendEntries(prefix, ancestors);
6466
+ const path = pathOf(prefix, first, second);
6467
+ return this.#refuse(message, keyword, member, path);
6468
+ }
6469
+ #refuse(message, first, second, prefix = this.#path) {
5426
6470
  if (this.#structure === void 0) {
5427
- const path = pathOf(this.#path, first, second);
6471
+ const path = pathOf(prefix, first, second);
5428
6472
  this.#structure = new ContractError(message, {
5429
6473
  code: "structure",
5430
6474
  context: { path }
@@ -5492,7 +6536,7 @@ var ShapeValidator = class ShapeValidator {
5492
6536
  */
5493
6537
  validate() {
5494
6538
  INTRINSICS.reflect.apply(INTRINSICS.sweep, this.#passes, [(pass) => pass.interrupt()]);
5495
- const pass = new ShapePass(this.#source);
6539
+ const pass = new ShapePass(this.#source, { left: CLONE_NODE_LIMIT });
5496
6540
  INTRINSICS.reflect.apply(INTRINSICS.admit, this.#passes, [pass]);
5497
6541
  this.#expansion = void 0;
5498
6542
  try {
@@ -5563,7 +6607,7 @@ var ShapeCloner = class ShapeCloner {
5563
6607
  clone() {
5564
6608
  const state = this.#state;
5565
6609
  if (state.phase === "settled") {
5566
- if (state.result.success) return state.result.value;
6610
+ if (isSuccess(state.result)) return state.result.value;
5567
6611
  throw state.result.error;
5568
6612
  }
5569
6613
  if (state.phase === "running" || state.phase === "interrupted") {
@@ -5585,22 +6629,17 @@ var ShapeCloner = class ShapeCloner {
5585
6629
  }
5586
6630
  #complete(outcome) {
5587
6631
  const state = this.#state;
5588
- if (state.phase === "interrupted") return this.#settle({
5589
- success: false,
5590
- error: state.poison
5591
- });
5592
- if (outcome.success) return this.#settle(outcome);
6632
+ if (state.phase === "interrupted") return this.#settle(failure(state.poison));
6633
+ if (isSuccess(outcome)) return this.#settle(outcome);
5593
6634
  const error = this.#owns(outcome.error) ? outcome.error : this.#create("cloneShape: failed to create an owned shape snapshot", {
5594
6635
  code: "clone",
5595
6636
  context: { shape: "shape" },
5596
6637
  cause: outcome.error
5597
6638
  });
5598
- return this.#settle({
5599
- success: false,
5600
- error
5601
- });
6639
+ return this.#settle(failure(error));
5602
6640
  }
5603
6641
  #execute() {
6642
+ const budget = { left: CLONE_NODE_LIMIT };
5604
6643
  const paths = this.#paths;
5605
6644
  const memo = this.#memo;
5606
6645
  if (paths === void 0 || memo === void 0) throw this.#unavailable();
@@ -5609,7 +6648,7 @@ var ShapeCloner = class ShapeCloner {
5609
6648
  shape: this.#source,
5610
6649
  depth: 0
5611
6650
  };
5612
- this.#drain();
6651
+ this.#drain(budget);
5613
6652
  this.#wireNodes();
5614
6653
  const root = INTRINSICS.reflect.apply(INTRINSICS.fetch, memo, [this.#source]);
5615
6654
  if (root === void 0) throw this.#create("ShapeCloner.clone: captured root is unavailable", {
@@ -5621,19 +6660,19 @@ var ShapeCloner = class ShapeCloner {
5621
6660
  if (this.#fidelity !== void 0) throw this.#fidelity;
5622
6661
  return root;
5623
6662
  }
5624
- #drain() {
6663
+ #drain(budget) {
5625
6664
  const memo = this.#memo;
5626
6665
  if (memo === void 0) throw this.#unavailable();
5627
6666
  for (const cursor of iterateIndices(() => this.#pending.length)) {
5628
6667
  const entry = this.#pending[cursor];
5629
6668
  if (entry === void 0) continue;
5630
6669
  if (INTRINSICS.reflect.apply(INTRINSICS.keyed, memo, [entry.shape])) continue;
5631
- if (entry.depth > 512) this.#refuseDepth();
5632
- this.#captureNode(entry.shape, entry.depth);
6670
+ if (entry.depth > 512) this.#refuseDepth(budget);
6671
+ this.#captureNode(entry.shape, entry.depth, budget);
5633
6672
  }
5634
6673
  }
5635
- #refuseDepth() {
5636
- this.#validateShape(this.#source);
6674
+ #refuseDepth(budget) {
6675
+ this.#validateShape(this.#source, [], budget);
5637
6676
  throw this.#create("validateShape: a shape exceeds the compilation depth limit", {
5638
6677
  code: "depth",
5639
6678
  context: {
@@ -5642,7 +6681,7 @@ var ShapeCloner = class ShapeCloner {
5642
6681
  }
5643
6682
  });
5644
6683
  }
5645
- #captureShell(source, path) {
6684
+ #captureShell(source, path, budget) {
5646
6685
  if (!matchesRecordBrand(source)) throw this.#create("validateShape: every structural child must be a shape", {
5647
6686
  code: "structure",
5648
6687
  context: { path }
@@ -5664,13 +6703,14 @@ var ShapeCloner = class ShapeCloner {
5664
6703
  case "boolean": return this.#captureSimple(source, path, "boolean");
5665
6704
  case "null": return this.#captureSimple(source, path, "null");
5666
6705
  case "literal": return this.#captureLiteral(source, path);
5667
- case "array": return this.#captureArray(source, path);
5668
- case "object": return this.#captureObject(source, path);
5669
- case "union": return this.#captureUnion(source, path);
5670
- case "optional": return this.#captureWrapper(source, path, "optional");
5671
- case "nullable": return this.#captureWrapper(source, path, "nullable");
6706
+ case "array": return this.#captureArray(source, path, budget);
6707
+ case "object": return this.#captureObject(source, path, budget);
6708
+ case "union": return this.#captureUnion(source, path, budget);
6709
+ case "optional": return this.#captureOptional(source, path, budget);
6710
+ case "nullable": return this.#captureNullable(source, path, budget);
5672
6711
  case "json": return this.#captureSimple(source, path, "json");
5673
- case "raw": return this.#captureRaw(source, path);
6712
+ case "shape": return this.#captureSimple(source, path, "shape");
6713
+ case "raw": return this.#captureRaw(source, path, budget);
5674
6714
  default: throw this.#create("validateShape: every node must be a recognized shape", {
5675
6715
  code: "structure",
5676
6716
  context: { path }
@@ -5746,7 +6786,7 @@ var ShapeCloner = class ShapeCloner {
5746
6786
  source: readPatternSource(pattern)
5747
6787
  };
5748
6788
  });
5749
- if (typeof sourceText !== "string" || typeof flags !== "string" || !repeated.success || typeof repeated.value.source !== "string" || typeof repeated.value.flags !== "string" || repeated.value.source !== sourceText || repeated.value.flags !== flags) {
6789
+ if (typeof sourceText !== "string" || typeof flags !== "string" || isFailure(repeated) || typeof repeated.value.source !== "string" || typeof repeated.value.flags !== "string" || repeated.value.source !== sourceText || repeated.value.flags !== flags) {
5750
6790
  this.#fidelity ??= this.#create("validateShape: string pattern must be stable", {
5751
6791
  code: "structure",
5752
6792
  context: { path: pathOf(path, "pattern") }
@@ -5758,12 +6798,12 @@ var ShapeCloner = class ShapeCloner {
5758
6798
  flags
5759
6799
  };
5760
6800
  }
5761
- #captureNode(source, depth) {
6801
+ #captureNode(source, depth, budget) {
5762
6802
  const paths = this.#paths;
5763
6803
  const memo = this.#memo;
5764
6804
  if (paths === void 0 || memo === void 0) throw this.#unavailable();
5765
6805
  const path = INTRINSICS.reflect.apply(INTRINSICS.fetch, paths, [source]) ?? [];
5766
- const clone = this.#captureShell(source, path);
6806
+ const clone = this.#captureShell(source, path, budget);
5767
6807
  INTRINSICS.reflect.apply(INTRINSICS.store, memo, [source, clone]);
5768
6808
  this.#sources[this.#sources.length] = source;
5769
6809
  this.#scheduleNode(source, clone, path, depth);
@@ -5812,6 +6852,10 @@ var ShapeCloner = class ShapeCloner {
5812
6852
  category: "null",
5813
6853
  ...description === void 0 ? {} : { description }
5814
6854
  };
6855
+ if (category === "shape") return {
6856
+ category: "shape",
6857
+ ...description === void 0 ? {} : { description }
6858
+ };
5815
6859
  return {
5816
6860
  category: "json",
5817
6861
  ...description === void 0 ? {} : { description }
@@ -5826,7 +6870,8 @@ var ShapeCloner = class ShapeCloner {
5826
6870
  ...description === void 0 ? {} : { description }
5827
6871
  };
5828
6872
  }
5829
- #captureArray(source, path) {
6873
+ #captureArray(source, path, budget) {
6874
+ this.#spend(budget, 1, path);
5830
6875
  const items = this.#captureField(source, "items", path);
5831
6876
  const min = this.#captureField(source, "min", path);
5832
6877
  const max = this.#captureField(source, "max", path);
@@ -5843,7 +6888,7 @@ var ShapeCloner = class ShapeCloner {
5843
6888
  ...description === void 0 ? {} : { description }
5844
6889
  };
5845
6890
  }
5846
- #captureObject(source, path) {
6891
+ #captureObject(source, path, budget) {
5847
6892
  const propertySource = this.#captureField(source, "properties", path);
5848
6893
  const additional = this.#captureField(source, "additionalProperties", path);
5849
6894
  const description = this.#captureField(source, "description", path);
@@ -5851,7 +6896,8 @@ var ShapeCloner = class ShapeCloner {
5851
6896
  code: "structure",
5852
6897
  context: { path: pathOf(path, "properties") }
5853
6898
  });
5854
- this.#captureProperties(source, propertySource, path);
6899
+ this.#captureProperties(source, propertySource, path, budget);
6900
+ if (additional !== void 0 && additional !== true && additional !== false) this.#spend(budget, 1, path);
5855
6901
  return {
5856
6902
  category: "object",
5857
6903
  properties: INTRINSICS.create(null),
@@ -5859,11 +6905,11 @@ var ShapeCloner = class ShapeCloner {
5859
6905
  ...description === void 0 ? {} : { description }
5860
6906
  };
5861
6907
  }
5862
- #captureUnion(source, path) {
6908
+ #captureUnion(source, path, budget) {
5863
6909
  const variantSource = this.#captureField(source, "variants", path);
5864
6910
  const mode = this.#captureField(source, "mode", path);
5865
6911
  const description = this.#captureField(source, "description", path);
5866
- this.#captureVariants(source, variantSource, path);
6912
+ this.#captureVariants(source, variantSource, path, budget);
5867
6913
  return {
5868
6914
  category: "union",
5869
6915
  variants: [],
@@ -5871,21 +6917,41 @@ var ShapeCloner = class ShapeCloner {
5871
6917
  ...description === void 0 ? {} : { description }
5872
6918
  };
5873
6919
  }
5874
- #captureWrapper(source, path, category) {
5875
- const inner = this.#captureField(source, "inner", path);
5876
- if (inner === void 0) throw this.#create("validateShape: every structural child must be a shape", {
6920
+ #captureOptional(source, path, budget) {
6921
+ const inner = this.#captureInner(source, path, budget);
6922
+ const value = this.#captureField(source, "default", path);
6923
+ if (!INTRINSICS.own(source, "default")) return {
6924
+ category: "optional",
6925
+ inner
6926
+ };
6927
+ const owned = isJSONValue(value) ? attempt(() => new JSONCloner(value).clone(budget)) : void 0;
6928
+ if (owned !== void 0 && isFailure(owned) && budget.left < 0 && isContractError(owned.error)) throw this.#prefix(owned.error, pathOf(path, "default"));
6929
+ if (owned === void 0 || isFailure(owned)) throw this.#create("validateShape: an optional default must be a JSON value", {
5877
6930
  code: "structure",
5878
- context: { path: pathOf(path, "inner") }
6931
+ context: { path: pathOf(path, "default") }
5879
6932
  });
5880
- return category === "optional" ? {
6933
+ return {
5881
6934
  category: "optional",
5882
- inner
5883
- } : {
6935
+ inner,
6936
+ default: owned.value
6937
+ };
6938
+ }
6939
+ #captureNullable(source, path, budget) {
6940
+ return {
5884
6941
  category: "nullable",
5885
- inner
6942
+ inner: this.#captureInner(source, path, budget)
5886
6943
  };
5887
6944
  }
5888
- #captureRaw(source, path) {
6945
+ #captureInner(source, path, budget) {
6946
+ this.#spend(budget, 1, path);
6947
+ const inner = this.#captureField(source, "inner", path);
6948
+ if (inner === void 0) throw this.#create("validateShape: every structural child must be a shape", {
6949
+ code: "structure",
6950
+ context: { path: pathOf(path, "inner") }
6951
+ });
6952
+ return inner;
6953
+ }
6954
+ #captureRaw(source, path, budget) {
5889
6955
  const schema = this.#captureField(source, "schema", path);
5890
6956
  if (!isRecord(schema)) throw this.#create("validateShape: raw schema must be a plain record", {
5891
6957
  code: "structure",
@@ -5894,10 +6960,10 @@ var ShapeCloner = class ShapeCloner {
5894
6960
  this.#validateShape({
5895
6961
  category: "raw",
5896
6962
  schema
5897
- });
6963
+ }, path, budget);
5898
6964
  const outcome = attempt(() => new SchemaCloner(schema).clone());
5899
- if (!outcome.success) {
5900
- if (isContractError(outcome.error)) admitVisited(this.#owned, outcome.error);
6965
+ if (isFailure(outcome)) {
6966
+ if (isContractError(outcome.error)) throw this.#prefix(outcome.error, pathOf(path, "schema"));
5901
6967
  throw outcome.error;
5902
6968
  }
5903
6969
  return {
@@ -5911,7 +6977,7 @@ var ShapeCloner = class ShapeCloner {
5911
6977
  context: { path: pathOf(path, "values") }
5912
6978
  });
5913
6979
  const snapshot = readArrayEntries(values);
5914
- if (!snapshot.success) throw this.#create("validateShape: values must be a finite literal array", {
6980
+ if (isFailure(snapshot)) throw this.#create("validateShape: values must be a finite literal array", {
5915
6981
  code: "structure",
5916
6982
  context: { path: pathOf(path, "values") }
5917
6983
  });
@@ -5926,11 +6992,11 @@ var ShapeCloner = class ShapeCloner {
5926
6992
  const key = INTRINSICS.text(index);
5927
6993
  const descriptor = attempt(() => INTRINSICS.describe(values, key));
5928
6994
  const repeated = attempt(() => values[index]);
5929
- if (!descriptor.success || descriptor.value === void 0 || !INTRINSICS.own(descriptor.value, "value")) this.#fidelity ??= this.#create("validateShape: values must be a dense data array", {
6995
+ if (isFailure(descriptor) || descriptor.value === void 0 || !INTRINSICS.own(descriptor.value, "value")) this.#fidelity ??= this.#create("validateShape: values must be a dense data array", {
5930
6996
  code: "structure",
5931
6997
  context: { path: pathOf(path, "values", key) }
5932
6998
  });
5933
- else if (!repeated.success || !INTRINSICS.same(repeated.value, value) || !INTRINSICS.same(descriptor.value.value, value)) this.#fidelity ??= this.#create("validateShape: values must be a stable data array", {
6999
+ else if (isFailure(repeated) || !INTRINSICS.same(repeated.value, value) || !INTRINSICS.same(descriptor.value.value, value)) this.#fidelity ??= this.#create("validateShape: values must be a stable data array", {
5934
7000
  code: "structure",
5935
7001
  context: { path: pathOf(path, "values", key) }
5936
7002
  });
@@ -5940,9 +7006,10 @@ var ShapeCloner = class ShapeCloner {
5940
7006
  });
5941
7007
  return value;
5942
7008
  }
5943
- #captureProperties(source, properties, path) {
7009
+ #captureProperties(source, properties, path, budget) {
5944
7010
  const keys = INTRINSICS.keys(properties);
5945
7011
  const snapshot = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(keys), [(key) => {
7012
+ this.#spend(budget, 1, path);
5946
7013
  const descriptor = INTRINSICS.describe(properties, key);
5947
7014
  if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) throw this.#create("validateShape: every structural child must be a shape", {
5948
7015
  code: "structure",
@@ -5969,13 +7036,13 @@ var ShapeCloner = class ShapeCloner {
5969
7036
  if (captured === void 0) throw this.#unavailable();
5970
7037
  INTRINSICS.reflect.apply(INTRINSICS.store, captured, [source, snapshot]);
5971
7038
  }
5972
- #captureVariants(source, variants, path) {
7039
+ #captureVariants(source, variants, path, budget) {
5973
7040
  if (!INTRINSICS.array(variants)) throw this.#create("validateShape: variants must be a finite array", {
5974
7041
  code: "structure",
5975
7042
  context: { path: pathOf(path, "variants") }
5976
7043
  });
5977
7044
  const snapshot = readArrayEntries(variants);
5978
- if (!snapshot.success) throw this.#create("validateShape: variants must be a finite array", {
7045
+ if (isFailure(snapshot)) throw this.#create("validateShape: variants must be a finite array", {
5979
7046
  code: "structure",
5980
7047
  context: { path: pathOf(path, "variants") }
5981
7048
  });
@@ -5984,6 +7051,7 @@ var ShapeCloner = class ShapeCloner {
5984
7051
  context: { path: pathOf(path, "variants") }
5985
7052
  });
5986
7053
  const entries = snapshot.value.entries;
7054
+ this.#spend(budget, entries.length, path);
5987
7055
  const captured = this.#variants;
5988
7056
  if (captured === void 0) throw this.#unavailable();
5989
7057
  INTRINSICS.reflect.apply(INTRINSICS.store, captured, [source, entries]);
@@ -5992,7 +7060,7 @@ var ShapeCloner = class ShapeCloner {
5992
7060
  const key = INTRINSICS.text(index);
5993
7061
  const descriptor = attempt(() => INTRINSICS.describe(variants, key));
5994
7062
  const repeated = attempt(() => variants[index]);
5995
- if (!descriptor.success || descriptor.value === void 0 || !INTRINSICS.own(descriptor.value, "value") || !repeated.success || !INTRINSICS.same(repeated.value, variant) || !INTRINSICS.same(descriptor.value.value, variant)) this.#fidelity ??= this.#create("validateShape: every structural child must be a shape", {
7063
+ if (isFailure(descriptor) || descriptor.value === void 0 || !INTRINSICS.own(descriptor.value, "value") || isFailure(repeated) || !INTRINSICS.same(repeated.value, variant) || !INTRINSICS.same(descriptor.value.value, variant)) this.#fidelity ??= this.#create("validateShape: every structural child must be a shape", {
5996
7064
  code: "structure",
5997
7065
  context: { path: pathOf(path, "variants", key) }
5998
7066
  });
@@ -6167,12 +7235,40 @@ var ShapeCloner = class ShapeCloner {
6167
7235
  if (clone !== void 0) INTRINSICS.freeze(clone);
6168
7236
  }
6169
7237
  }
6170
- #validateShape(shape) {
6171
- const outcome = attempt(() => new ShapeValidator(shape).validate());
6172
- if (outcome.success) return;
6173
- if (isContractError(outcome.error)) admitVisited(this.#owned, outcome.error);
7238
+ #validateShape(shape, path = [], budget) {
7239
+ const outcome = attempt(() => new ShapePass(shape, budget).validate());
7240
+ if (isSuccess(outcome)) return;
7241
+ if (isContractError(outcome.error)) throw this.#prefix(outcome.error, path);
6174
7242
  throw outcome.error;
6175
7243
  }
7244
+ #spend(budget, count, path) {
7245
+ budget.left -= count;
7246
+ if (budget.left < 0) throw this.#create(`cloneShape: capture exceeds the node limit ${CLONE_NODE_LIMIT}`, {
7247
+ code: "clone",
7248
+ context: {
7249
+ path,
7250
+ limit: CLONE_NODE_LIMIT
7251
+ }
7252
+ });
7253
+ }
7254
+ #prefix(error, path) {
7255
+ if (path.length === 0) {
7256
+ admitVisited(this.#owned, error);
7257
+ return error;
7258
+ }
7259
+ const tail = error.context?.path;
7260
+ const location = [];
7261
+ appendEntries(location, path);
7262
+ appendEntries(location, typeof tail === "string" ? [tail] : tail ?? []);
7263
+ return this.#create(error.message, {
7264
+ code: error.code,
7265
+ context: {
7266
+ ...error.context,
7267
+ path: location
7268
+ },
7269
+ ...INTRINSICS.own(error, "cause") ? { cause: error.cause } : {}
7270
+ });
7271
+ }
6176
7272
  #unavailable() {
6177
7273
  return this.#create("ShapeCloner.clone: the capture state is unavailable", {
6178
7274
  code: "clone",
@@ -6199,7 +7295,7 @@ var ShapeCloner = class ShapeCloner {
6199
7295
  phase: "settled",
6200
7296
  result
6201
7297
  };
6202
- if (result.success) return result.value;
7298
+ if (isSuccess(result)) return result.value;
6203
7299
  throw result.error;
6204
7300
  }
6205
7301
  static {
@@ -6337,11 +7433,11 @@ function ownShape(shape) {
6337
7433
  return contain(() => {
6338
7434
  const frozen = holds(() => INTRINSICS.frozen(shape));
6339
7435
  const fidelity = attempt(() => cloneShape(shape));
6340
- if (fidelity.success) return fidelity.value;
6341
- if (isContractError(fidelity.error) && fidelity.error.code !== "clone") throw fidelity.error;
7436
+ if (isSuccess(fidelity)) return fidelity.value;
7437
+ if (isContractError(fidelity.error) && (fidelity.error.code !== "clone" || fidelity.error.context?.limit === 262144)) throw fidelity.error;
6342
7438
  if (!frozen) throw fidelity.error;
6343
7439
  const validation = attempt(() => new ShapeValidator(shape).validate());
6344
- if (!validation.success && isContractError(validation.error)) throw validation.error;
7440
+ if (isFailure(validation) && isContractError(validation.error)) throw validation.error;
6345
7441
  throw fidelity.error;
6346
7442
  }, "ownShape");
6347
7443
  }
@@ -6369,7 +7465,7 @@ function arrayOf(elementGuard) {
6369
7465
  return (value) => holds(() => {
6370
7466
  if (!isArray(value)) return false;
6371
7467
  const entries = readArrayEntries(value);
6372
- if (!entries.success || !entries.value.dense) return false;
7468
+ if (isFailure(entries) || !entries.value.dense) return false;
6373
7469
  for (const index of iterateIndices(() => entries.value.entries.length)) if (!elementGuard(entries.value.entries[index])) return false;
6374
7470
  return true;
6375
7471
  });
@@ -6378,7 +7474,7 @@ function tupleOf(...guards) {
6378
7474
  return (value) => holds(() => {
6379
7475
  if (!isArray(value)) return false;
6380
7476
  const entries = readArrayEntries(value);
6381
- if (!entries.success || !entries.value.dense) return false;
7477
+ if (isFailure(entries) || !entries.value.dense) return false;
6382
7478
  if (entries.value.entries.length !== guards.length) return false;
6383
7479
  for (const index of iterateIndices(() => guards.length)) {
6384
7480
  const guard = guards[index];
@@ -6398,7 +7494,7 @@ function literalOf(...literals) {
6398
7494
  }
6399
7495
  }) : false) && isArray(first) ? readValue(() => {
6400
7496
  const entries = readArrayEntries(first);
6401
- if (!entries.success) throw entries.error;
7497
+ if (isFailure(entries)) throw entries.error;
6402
7498
  if (!entries.value.dense) throw new INTRINSICS.error("Literal vocabulary must be dense");
6403
7499
  return entries.value.entries;
6404
7500
  }, "literalOf", {
@@ -6480,7 +7576,7 @@ function setOf(elementGuard) {
6480
7576
  return (value) => holds(() => {
6481
7577
  if (!isSet(value)) return false;
6482
7578
  const entries = readSetEntries(value);
6483
- if (!entries.success) return false;
7579
+ if (isFailure(entries)) return false;
6484
7580
  for (const index of iterateIndices(() => entries.value.length)) if (!elementGuard(entries.value[index])) return false;
6485
7581
  return true;
6486
7582
  });
@@ -6489,7 +7585,7 @@ function mapOf(keyGuard, valueGuard) {
6489
7585
  return (value) => holds(() => {
6490
7586
  if (!isMap(value)) return false;
6491
7587
  const entries = readMapEntries(value);
6492
- if (!entries.success) return false;
7588
+ if (isFailure(entries)) return false;
6493
7589
  for (const index of iterateIndices(() => entries.value.length)) {
6494
7590
  const entry = entries.value[index];
6495
7591
  if (entry === void 0) return false;
@@ -6589,7 +7685,7 @@ function pickOf(shape, keys) {
6589
7685
  return contain(() => {
6590
7686
  const selected = readValue(() => {
6591
7687
  const entries = readArrayEntries(keys);
6592
- if (!entries.success) throw entries.error;
7688
+ if (isFailure(entries)) throw entries.error;
6593
7689
  if (!entries.value.dense) throw new INTRINSICS.error("Picked key list must be dense");
6594
7690
  return collectMembers(entries.value.entries);
6595
7691
  }, "pickOf", { subject: "keys" });
@@ -6628,7 +7724,7 @@ function omitOf(shape, keys) {
6628
7724
  return contain(() => {
6629
7725
  const skipped = readValue(() => {
6630
7726
  const entries = readArrayEntries(keys);
6631
- if (!entries.success) throw entries.error;
7727
+ if (isFailure(entries)) throw entries.error;
6632
7728
  if (!entries.value.dense) throw new INTRINSICS.error("Omitted key list must be dense");
6633
7729
  return collectMembers(entries.value.entries);
6634
7730
  }, "omitOf", { subject: "keys" });
@@ -6815,8 +7911,9 @@ function matchOf(pattern) {
6815
7911
  * refinements — `min` / `max` length and a `pattern`.
6816
7912
  *
6817
7913
  * @remarks
6818
- * Composes {@link isString} with {@link boundsOf} on the string's `.length` and
6819
- * an owned stateless pattern (the same refinement {@link matchOf} performs).
7914
+ * Composes {@link isString} with {@link matchesStringLength}, which counts code
7915
+ * points as the `minLength` and `maxLength` a string shape emits do, and an owned
7916
+ * stateless pattern (the same refinement {@link matchOf} performs).
6820
7917
  * When `min`, `max`, and `pattern` are all absent it returns the bare {@link isString} guard
6821
7918
  * (the unconstrained fast path), so an unrefined string leaf pays no wrapping
6822
7919
  * cost. The single source of the string refinement shared by the compiled guard
@@ -6843,14 +7940,13 @@ function stringOf(options) {
6843
7940
  "max",
6844
7941
  "pattern"
6845
7942
  ], "stringOf", "string");
6846
- const min = safe?.min;
6847
- const max = safe?.max;
6848
- const source = safe?.pattern;
7943
+ const min = safe !== void 0 && INTRINSICS.own(safe, "min") ? safe.min : void 0;
7944
+ const max = safe !== void 0 && INTRINSICS.own(safe, "max") ? safe.max : void 0;
7945
+ const source = safe !== void 0 && INTRINSICS.own(safe, "pattern") ? safe.pattern : void 0;
6849
7946
  if (source !== void 0 && !isRegExp(source)) throw new ContractError("stringOf: pattern must be a RegExp", { code: "pattern" });
6850
7947
  const pattern = source === void 0 ? void 0 : ownPattern(source, "stringOf");
6851
7948
  if (min === void 0 && max === void 0 && pattern === void 0) return isString;
6852
- const withinLength = boundsOf(min, max);
6853
- return whereOf(isString, (value) => withinLength(value.length) && (pattern === void 0 || matchesPattern(pattern, value)));
7949
+ return whereOf(isString, (value) => matchesStringLength(value, min, max) && (pattern === void 0 || matchesPattern(pattern, value)));
6854
7950
  }, "stringOf");
6855
7951
  }
6856
7952
  /**
@@ -6936,7 +8032,7 @@ function parseNumber(value) {
6936
8032
  const parsed = INTRINSICS.numeric(value);
6937
8033
  return INTRINSICS.finite(parsed) ? parsed : void 0;
6938
8034
  });
6939
- return outcome.success ? outcome.value : void 0;
8035
+ return isSuccess(outcome) ? outcome.value : void 0;
6940
8036
  }
6941
8037
  /**
6942
8038
  * Parses an unknown value to a finite integer.
@@ -7043,7 +8139,7 @@ function parseArray(value, guard) {
7043
8139
  if (!isArray(value)) return void 0;
7044
8140
  if (guard === void 0) return value;
7045
8141
  const entries = readArrayEntries(value);
7046
- if (!entries.success || !entries.value.dense) return void 0;
8142
+ if (isFailure(entries) || !entries.value.dense) return void 0;
7047
8143
  if (!holds(() => INTRINSICS.reflect.apply(INTRINSICS.find, entries.value.entries, [(entry) => !guard(entry)]) === -1)) return;
7048
8144
  return value;
7049
8145
  }
@@ -7076,7 +8172,7 @@ function parseJSONValue(value) {
7076
8172
  }
7077
8173
  function parseEnum(value, allowed) {
7078
8174
  const outcome = readArrayEntries(allowed);
7079
- if (!outcome.success || !outcome.value.dense) return void 0;
8175
+ if (isFailure(outcome) || !outcome.value.dense) return void 0;
7080
8176
  if (!holds(() => matchesMember(collectMembers(outcome.value.entries), value))) return void 0;
7081
8177
  return isLiteralValue(value) ? value : void 0;
7082
8178
  }
@@ -7284,7 +8380,7 @@ function parseJSONAs(value, guard) {
7284
8380
  const parsed = parseJSON(value);
7285
8381
  if (parsed === void 0) return void 0;
7286
8382
  const checked = attempt(() => guard(parsed) ? parsed : void 0);
7287
- return checked.success ? checked.value : void 0;
8383
+ return isSuccess(checked) ? checked.value : void 0;
7288
8384
  }
7289
8385
  // src/core/EvaluationScope.ts
7290
8386
  /** Owns compiled-node memo entries for one synchronous evaluation. */
@@ -7296,7 +8392,7 @@ var EvaluationScope = class EvaluationScope {
7296
8392
  static run(plan, value, path = EvaluationScope.#path, clean = false) {
7297
8393
  if (!isObject(value)) return plan(value, path);
7298
8394
  const entries = readSetEntries(EvaluationScope.#active);
7299
- if (!entries.success) throw entries.error;
8395
+ if (isFailure(entries)) throw entries.error;
7300
8396
  const active = entries.value[0];
7301
8397
  if (active instanceof EvaluationScope) return active.#evaluate(plan, value, path, clean);
7302
8398
  if (active !== void 0) throw new INTRINSICS.error("Evaluation scope is unavailable");
@@ -7375,7 +8471,9 @@ function seededRandom(seed) {
7375
8471
  * chain pays a hundred clones of shrinking graphs and a hundred validations —
7376
8472
  * quadratic work for a linear declaration. Here ownership runs once, validation runs once over
7377
8473
  * that owned result, and each unique node and structural edge is indexed once
7378
- * into children-before-parent order. Every artifact family is then a single
8474
+ * into children-before-parent order. A declaration a builder sealed is frozen and
8475
+ * validated all the way down already, so it takes neither and is indexed as it
8476
+ * stands. Every artifact family is then a single
7379
8477
  * postorder pass whose entries are keyed by node identity, so a shared child is
7380
8478
  * compiled once however many parents point at it. The same asymmetry exists on
7381
8479
  * the VALUE side and is answered the same way: `guard`, `auditor` and `reporter`
@@ -7387,7 +8485,9 @@ function seededRandom(seed) {
7387
8485
  * getters after it replay. A getter builds its own family and no other, except
7388
8486
  * that `parser`, `reporter` and `generator` build the guard plan when the graph
7389
8487
  * holds a union, because a union's membership question IS a guard question in
7390
- * all three.
8488
+ * all three, and every getter builds it when the graph holds a default, because
8489
+ * a default that its inner shape refuses refuses at whichever artifact is read
8490
+ * first.
7391
8491
  *
7392
8492
  * One terminal lifecycle covers preparation and every family. A failure settles
7393
8493
  * the compiler: later getters rethrow that exact error, while an artifact
@@ -7558,7 +8658,7 @@ var ContractCompiler = class ContractCompiler {
7558
8658
  #leave(outcome) {
7559
8659
  const state = this.#state;
7560
8660
  if (state.phase === "interrupted") return this.#fail(state.poison);
7561
- if (!outcome.success) return this.#fail(isContractError(outcome.error) ? outcome.error : new ContractError("ContractCompiler: contract compilation failed", {
8661
+ if (isFailure(outcome)) return this.#fail(isContractError(outcome.error) ? outcome.error : new ContractError("ContractCompiler: contract compilation failed", {
7562
8662
  code: "structure",
7563
8663
  context: {
7564
8664
  path: [],
@@ -7607,10 +8707,15 @@ var ContractCompiler = class ContractCompiler {
7607
8707
  shape: "contract"
7608
8708
  }
7609
8709
  });
8710
+ const sealed = ShapePass.expansionOf(source);
8711
+ if (sealed !== void 0) {
8712
+ refuseExpansion(sealed);
8713
+ this.#discover(source);
8714
+ this.#source = void 0;
8715
+ return;
8716
+ }
7610
8717
  const owned = ownShape(source);
7611
- const validator = new ShapeValidator(owned);
7612
- validator.validate();
7613
- refuseExpansion(validator.expansion);
8718
+ refuseExpansion(new ShapePass(owned).validate());
7614
8719
  this.#discover(owned);
7615
8720
  this.#source = void 0;
7616
8721
  }
@@ -7639,7 +8744,9 @@ var ContractCompiler = class ContractCompiler {
7639
8744
  const shape = frame.shape;
7640
8745
  if (INTRINSICS.reflect.apply(INTRINSICS.recall, known, [shape]) !== void 0) continue;
7641
8746
  const index = this.#nodes.length;
7642
- this.#nodes[index] = shape;
8747
+ const node = INTRINSICS.rebase({ ...shape }, null);
8748
+ this.#nodes[index] = node;
8749
+ INTRINSICS.reflect.apply(INTRINSICS.retain, known, [node, index]);
7643
8750
  INTRINSICS.reflect.apply(INTRINSICS.retain, known, [shape, index]);
7644
8751
  this.#stack[this.#stack.length] = {
7645
8752
  operation: "exit",
@@ -7723,12 +8830,60 @@ var ContractCompiler = class ContractCompiler {
7723
8830
  path: [],
7724
8831
  shape: "contract"
7725
8832
  }
7726
- });
7727
- return shape;
7728
- }
7729
- #unions() {
7730
- for (const index of iterateIndices(() => this.#nodes.length)) if (this.#nodes[index]?.category === "union") return true;
7731
- return false;
8833
+ });
8834
+ return shape;
8835
+ }
8836
+ #unions() {
8837
+ for (const index of iterateIndices(() => this.#nodes.length)) if (this.#nodes[index]?.category === "union") return true;
8838
+ return false;
8839
+ }
8840
+ #defaults() {
8841
+ for (const index of iterateIndices(() => this.#nodes.length)) {
8842
+ const node = this.#nodes[index];
8843
+ if (node?.category === "optional" && INTRINSICS.own(node, "default")) return true;
8844
+ }
8845
+ return false;
8846
+ }
8847
+ #checkDefaults(shape, path) {
8848
+ switch (shape.category) {
8849
+ case "array":
8850
+ this.#checkDefaults(shape.items, pathOf(path, "items"));
8851
+ return;
8852
+ case "nullable":
8853
+ this.#checkDefaults(shape.inner, pathOf(path, "inner"));
8854
+ return;
8855
+ case "optional":
8856
+ this.#checkDefaults(shape.inner, pathOf(path, "inner"));
8857
+ if (!INTRINSICS.own(shape, "default") || this.#guardAt(shape.inner)(shape.default)) return;
8858
+ throw new ContractError("ContractCompiler: a default must satisfy the shape it fills; change the default or the shape", {
8859
+ code: "structure",
8860
+ context: {
8861
+ path: pathOf(path, "default"),
8862
+ shape: "optional",
8863
+ received: preview(shape.default)
8864
+ }
8865
+ });
8866
+ case "union":
8867
+ for (const index of iterateIndices(() => shape.variants.length)) {
8868
+ const variant = shape.variants[index];
8869
+ if (variant === void 0) continue;
8870
+ this.#checkDefaults(variant, pathOf(path, "variants", INTRINSICS.text(index)));
8871
+ }
8872
+ return;
8873
+ case "object": {
8874
+ const keys = INTRINSICS.keys(shape.properties);
8875
+ for (const index of iterateIndices(() => keys.length)) {
8876
+ const key = keys[index];
8877
+ const child = key === void 0 ? void 0 : shape.properties[key];
8878
+ if (child === void 0) continue;
8879
+ this.#checkDefaults(child, pathOf(path, "properties", key));
8880
+ }
8881
+ const extra = shape.additionalProperties;
8882
+ if (extra !== void 0 && extra !== true && extra !== false) this.#checkDefaults(extra, pathOf(path, "additionalProperties"));
8883
+ return;
8884
+ }
8885
+ default: return;
8886
+ }
7732
8887
  }
7733
8888
  #repeats(index) {
7734
8889
  const category = this.#node(index).category;
@@ -7741,10 +8896,64 @@ var ContractCompiler = class ContractCompiler {
7741
8896
  #trackFaults(plan) {
7742
8897
  return (value, path) => EvaluationScope.run(plan, value, path, true);
7743
8898
  }
8899
+ #discriminate(owned) {
8900
+ const arms = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(owned.variants), [(variant) => variant?.category === "object"]);
8901
+ const first = arms[0];
8902
+ if (first === void 0 || arms.length !== owned.variants.length) return void 0;
8903
+ const keys = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(INTRINSICS.keys(first.properties)), [(key) => !INTRINSICS.reflect.apply(INTRINSICS.some, arms, [(arm) => !INTRINSICS.own(arm.properties, key) || arm.properties[key]?.category !== "literal"])]);
8904
+ const tables = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(keys), [(key) => ContractCompiler.#tableOf(key, arms)]);
8905
+ const named = tables[0];
8906
+ if (named === void 0) return void 0;
8907
+ return {
8908
+ hint: INTRINSICS.freeze({
8909
+ key: named.key,
8910
+ expected: named.expected
8911
+ }),
8912
+ select: (value) => {
8913
+ if (!isObject(value)) return void 0;
8914
+ for (const index of iterateIndices(() => tables.length)) {
8915
+ const table = tables[index];
8916
+ if (table === void 0) continue;
8917
+ const held = attempt(() => INTRINSICS.describe(value, table.key));
8918
+ if (isFailure(held) || held.value === void 0) continue;
8919
+ if (!INTRINSICS.own(held.value, "value")) continue;
8920
+ const arm = INTRINSICS.reflect.apply(INTRINSICS.fetch, table.members, [held.value.value]);
8921
+ if (arm !== void 0 && arm >= 0) return arm;
8922
+ }
8923
+ }
8924
+ };
8925
+ }
8926
+ static #tableOf(key, arms) {
8927
+ const members = new INTRINSICS.map();
8928
+ const expected = [];
8929
+ for (const armIndex of iterateIndices(() => arms.length)) {
8930
+ const node = arms[armIndex]?.properties[key];
8931
+ if (node?.category !== "literal") continue;
8932
+ for (const valueIndex of iterateIndices(() => node.values.length)) {
8933
+ const literal = node.values[valueIndex];
8934
+ if (literal === void 0) continue;
8935
+ const known = INTRINSICS.reflect.apply(INTRINSICS.fetch, members, [literal]);
8936
+ if (known === void 0) expected[expected.length] = literal;
8937
+ const arm = known === void 0 || known === armIndex ? armIndex : -1;
8938
+ INTRINSICS.reflect.apply(INTRINSICS.store, members, [literal, arm]);
8939
+ }
8940
+ }
8941
+ return {
8942
+ key,
8943
+ members,
8944
+ expected: INTRINSICS.freeze(expected)
8945
+ };
8946
+ }
8947
+ static #parseArm(arm, value) {
8948
+ if (arm.guard(value)) return value;
8949
+ const parsed = arm.parse(value);
8950
+ return parsed !== void 0 && arm.guard(parsed) ? parsed : void 0;
8951
+ }
7744
8952
  #buildSchema() {
7745
8953
  const ready = this.#schema;
7746
8954
  if (ready !== void 0) return ready;
7747
8955
  this.#prepare();
8956
+ if (this.#defaults()) this.#buildGuard();
7748
8957
  for (const step of iterateIndices(() => this.#order.length)) {
7749
8958
  const index = this.#order[step];
7750
8959
  if (index === void 0) continue;
@@ -7768,6 +8977,13 @@ var ContractCompiler = class ContractCompiler {
7768
8977
  #schemaOf(index) {
7769
8978
  const owned = this.#node(index);
7770
8979
  switch (owned.category) {
8980
+ case "shape": return INTRINSICS.freeze({
8981
+ type: "object",
8982
+ description: owned.description ?? "Over-approximates declarations whose JSON projection preserves their own enumerable data; values without that projection are outside this schema. is decides whether the complete shape is valid.",
8983
+ properties: INTRINSICS.freeze({ category: INTRINSICS.freeze({ enum: INTRINSICS.freeze(INTRINSICS.keys(SHAPE_FIELDS)) }) }),
8984
+ required: INTRINSICS.freeze(["category"]),
8985
+ additionalProperties: true
8986
+ });
7771
8987
  case "string": {
7772
8988
  const text = owned.pattern === void 0 ? void 0 : readPatternSource(owned.pattern);
7773
8989
  if (owned.pattern !== void 0 && text === void 0) throw new ContractError("compileSchema: pattern source could not be read", {
@@ -7817,7 +9033,7 @@ var ContractCompiler = class ContractCompiler {
7817
9033
  if (child === void 0) return [];
7818
9034
  return [{
7819
9035
  key,
7820
- schema: this.#schemaAt(child.category === "optional" ? child.inner : child),
9036
+ schema: this.#schemaAt(child),
7821
9037
  required: child.category !== "optional"
7822
9038
  }];
7823
9039
  }]);
@@ -7841,7 +9057,14 @@ var ContractCompiler = class ContractCompiler {
7841
9057
  ...owned.description !== void 0 ? { description: owned.description } : {}
7842
9058
  });
7843
9059
  }
7844
- case "optional": return this.#schemaAt(owned.inner);
9060
+ case "optional": {
9061
+ const emitted = this.#schemaAt(owned.inner);
9062
+ const value = owned.default;
9063
+ return value === void 0 ? emitted : INTRINSICS.freeze({
9064
+ ...emitted,
9065
+ default: value
9066
+ });
9067
+ }
7845
9068
  case "nullable": return INTRINSICS.freeze({ anyOf: INTRINSICS.freeze([this.#schemaAt(owned.inner), INTRINSICS.freeze({ type: "null" })]) });
7846
9069
  case "raw": return cloneSchema(owned.schema);
7847
9070
  }
@@ -7857,6 +9080,7 @@ var ContractCompiler = class ContractCompiler {
7857
9080
  this.#guards[index] = this.#repeats(index) ? this.#trackGuard(plan) : plan;
7858
9081
  }
7859
9082
  const root = this.#guardAt(this.#node(0));
9083
+ if (this.#defaults()) this.#checkDefaults(this.#node(0), []);
7860
9084
  this.#guard = root;
7861
9085
  return root;
7862
9086
  }
@@ -7871,14 +9095,24 @@ var ContractCompiler = class ContractCompiler {
7871
9095
  });
7872
9096
  return compiled;
7873
9097
  }
9098
+ #stringGuard(owned) {
9099
+ return stringOf(INTRINSICS.rebase({
9100
+ ...owned.min === void 0 ? {} : { min: owned.min },
9101
+ ...owned.max === void 0 ? {} : { max: owned.max },
9102
+ ...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
9103
+ }, null));
9104
+ }
9105
+ static #acceptShape(value) {
9106
+ return isSuccess(attempt(() => {
9107
+ const validator = new ShapeValidator(value);
9108
+ validator.validate();
9109
+ refuseExpansion(validator.expansion);
9110
+ }));
9111
+ }
7874
9112
  #guardOf(index) {
7875
9113
  const owned = this.#node(index);
7876
9114
  switch (owned.category) {
7877
- case "string": return stringOf({
7878
- ...owned.min === void 0 ? {} : { min: owned.min },
7879
- ...owned.max === void 0 ? {} : { max: owned.max },
7880
- ...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
7881
- });
9115
+ case "string": return this.#stringGuard(owned);
7882
9116
  case "number": {
7883
9117
  const base = owned.integer === true ? isInteger : isFiniteNumber;
7884
9118
  if (owned.min === void 0 && owned.max === void 0) return base;
@@ -7887,6 +9121,7 @@ var ContractCompiler = class ContractCompiler {
7887
9121
  case "boolean": return isBoolean;
7888
9122
  case "null": return isNull;
7889
9123
  case "json": return isJSONValue;
9124
+ case "shape": return (value) => ContractCompiler.#acceptShape(value);
7890
9125
  case "literal": return literalOf(owned.values);
7891
9126
  case "array": {
7892
9127
  const base = arrayOf(this.#guardAt(owned.items));
@@ -7944,7 +9179,7 @@ var ContractCompiler = class ContractCompiler {
7944
9179
  }
7945
9180
  return true;
7946
9181
  });
7947
- return outcome.success && outcome.value;
9182
+ return isSuccess(outcome) && outcome.value;
7948
9183
  };
7949
9184
  }
7950
9185
  case "union": {
@@ -7963,7 +9198,7 @@ var ContractCompiler = class ContractCompiler {
7963
9198
  const ready = this.#parser;
7964
9199
  if (ready !== void 0) return ready;
7965
9200
  this.#prepare();
7966
- if (this.#unions()) this.#buildGuard();
9201
+ if (this.#unions() || this.#defaults()) this.#buildGuard();
7967
9202
  for (const step of iterateIndices(() => this.#order.length)) {
7968
9203
  const index = this.#order[step];
7969
9204
  if (index === void 0) continue;
@@ -7989,11 +9224,7 @@ var ContractCompiler = class ContractCompiler {
7989
9224
  switch (owned.category) {
7990
9225
  case "string": {
7991
9226
  if (owned.min === void 0 && owned.max === void 0 && owned.pattern === void 0) return parseString;
7992
- const guard = stringOf({
7993
- ...owned.min === void 0 ? {} : { min: owned.min },
7994
- ...owned.max === void 0 ? {} : { max: owned.max },
7995
- ...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
7996
- });
9227
+ const guard = this.#stringGuard(owned);
7997
9228
  return (value) => {
7998
9229
  const parsed = parseString(value);
7999
9230
  return parsed !== void 0 && guard(parsed) ? parsed : void 0;
@@ -8011,6 +9242,7 @@ var ContractCompiler = class ContractCompiler {
8011
9242
  case "boolean": return parseBoolean;
8012
9243
  case "null": return (value) => value === null ? null : void 0;
8013
9244
  case "json": return parseJSONValue;
9245
+ case "shape": return (value) => ContractCompiler.#acceptShape(value) ? value : void 0;
8014
9246
  case "literal": {
8015
9247
  const allowed = literalOf(owned.values);
8016
9248
  return (value) => {
@@ -8032,7 +9264,7 @@ var ContractCompiler = class ContractCompiler {
8032
9264
  });
8033
9265
  if (!isArray(value)) return void 0;
8034
9266
  const entries = readArrayEntries(value);
8035
- if (!entries.success) return readValue(() => {
9267
+ if (isFailure(entries)) return readValue(() => {
8036
9268
  throw entries.error;
8037
9269
  }, "compileParser", {
8038
9270
  subject: "array",
@@ -8058,7 +9290,8 @@ var ContractCompiler = class ContractCompiler {
8058
9290
  return [{
8059
9291
  key,
8060
9292
  parse: this.#parserAt(inner),
8061
- optional
9293
+ optional,
9294
+ fill: optional && INTRINSICS.own(child, "default") ? child.default : void 0
8062
9295
  }];
8063
9296
  }]);
8064
9297
  const known = readValue(() => collectMembers(INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(entries), [(entry) => entry.key])), "compileParser", {
@@ -8082,14 +9315,14 @@ var ContractCompiler = class ContractCompiler {
8082
9315
  for (const entryIndex of iterateIndices(() => entries.length)) {
8083
9316
  const entry = entries[entryIndex];
8084
9317
  if (entry === void 0) continue;
8085
- if (present === void 0 ? (seen & 1 << entryIndex) === 0 : !matchesMember(present, entry.key)) {
8086
- if (entry.optional) continue;
8087
- return;
8088
- }
8089
- const raw = record[entry.key];
9318
+ const raw = (present === void 0 ? (seen & 1 << entryIndex) === 0 : !matchesMember(present, entry.key)) ? void 0 : record[entry.key];
8090
9319
  if (raw === void 0) {
8091
- if (entry.optional) continue;
8092
- return;
9320
+ if (!entry.optional) return void 0;
9321
+ if (entry.fill !== void 0) {
9322
+ const fill = isObject(entry.fill) ? cloneJSONValue(entry.fill) : entry.fill;
9323
+ selected[selected.length] = [entry.key, entry.parse(fill)];
9324
+ }
9325
+ continue;
8093
9326
  }
8094
9327
  const parsed = entry.parse(raw);
8095
9328
  if (parsed === void 0) return void 0;
@@ -8108,7 +9341,7 @@ var ContractCompiler = class ContractCompiler {
8108
9341
  }
8109
9342
  return INTRINSICS.rebase(INTRINSICS.record({ [Symbol.iterator]: INTRINSICS.reflect.apply(INTRINSICS.bind, INTRINSICS.iterator, [selected]) }), null);
8110
9343
  });
8111
- if (outcome.success) return outcome.value;
9344
+ if (isSuccess(outcome)) return outcome.value;
8112
9345
  if (isContractError(outcome.error)) throw outcome.error;
8113
9346
  return readValue(() => {
8114
9347
  throw outcome.error;
@@ -8123,12 +9356,19 @@ var ContractCompiler = class ContractCompiler {
8123
9356
  parse: this.#parserAt(variant),
8124
9357
  guard: this.#guardAt(variant)
8125
9358
  }]]);
9359
+ const discriminated = this.#discriminate(owned);
8126
9360
  if (owned.mode === "oneOf") return (value) => {
9361
+ const selected = discriminated?.select(value);
9362
+ const arm = selected === void 0 ? void 0 : variants[selected];
9363
+ if (arm !== void 0) return ContractCompiler.#parseArm(arm, value);
8127
9364
  const matching = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(variants), [(variant) => variant.guard(value)]);
8128
9365
  const only = matching[0];
8129
- return matching.length === 1 && only !== void 0 ? only.parse(value) : void 0;
9366
+ return matching.length === 1 && only !== void 0 ? value : void 0;
8130
9367
  };
8131
9368
  return (value) => {
9369
+ const selected = discriminated?.select(value);
9370
+ const arm = selected === void 0 ? void 0 : variants[selected];
9371
+ if (arm !== void 0) return ContractCompiler.#parseArm(arm, value);
8132
9372
  for (const variantIndex of iterateIndices(() => variants.length)) {
8133
9373
  const variant = variants[variantIndex];
8134
9374
  if (variant === void 0) continue;
@@ -8157,6 +9397,7 @@ var ContractCompiler = class ContractCompiler {
8157
9397
  const ready = this.#auditor;
8158
9398
  if (ready !== void 0) return ready;
8159
9399
  this.#prepare();
9400
+ if (this.#defaults()) this.#buildGuard();
8160
9401
  for (const step of iterateIndices(() => this.#order.length)) {
8161
9402
  const index = this.#order[step];
8162
9403
  if (index === void 0) continue;
@@ -8231,6 +9472,12 @@ var ContractCompiler = class ContractCompiler {
8231
9472
  expected: "json",
8232
9473
  received: preview(value)
8233
9474
  }];
9475
+ case "shape": return (value, path) => ContractCompiler.#acceptShape(value) ? [] : [{
9476
+ reason: "type",
9477
+ path,
9478
+ expected: "shape",
9479
+ received: preview(value)
9480
+ }];
8234
9481
  case "literal": {
8235
9482
  const allowed = literalOf(owned.values);
8236
9483
  return (value, path) => allowed(value) ? [] : [{
@@ -8258,7 +9505,7 @@ var ContractCompiler = class ContractCompiler {
8258
9505
  received: preview(value)
8259
9506
  }];
8260
9507
  const entries = readArrayEntries(value);
8261
- if (!entries.success) return readValue(() => {
9508
+ if (isFailure(entries)) return readValue(() => {
8262
9509
  throw entries.error;
8263
9510
  }, "compileAuditor", {
8264
9511
  subject: "array",
@@ -8294,7 +9541,7 @@ var ContractCompiler = class ContractCompiler {
8294
9541
  const closed = extra === void 0 || extra === false;
8295
9542
  const additional = closed || extra === true ? void 0 : this.#auditAt(extra);
8296
9543
  const planned = attempt(() => collectMembers(declaredKeys));
8297
- const declared = planned.success ? planned.value : void 0;
9544
+ const declared = isSuccess(planned) ? planned.value : void 0;
8298
9545
  const maskable = entries.length <= 31;
8299
9546
  const positions = buildPositions(maskable ? INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(entries), [(entry) => entry.key]) : []);
8300
9547
  return (value, path) => {
@@ -8354,7 +9601,7 @@ var ContractCompiler = class ContractCompiler {
8354
9601
  if (additional !== void 0) appendEntries(faults, additional(observed, pathOf(path, key)));
8355
9602
  }
8356
9603
  });
8357
- if (!outcome.success) {
9604
+ if (isFailure(outcome)) {
8358
9605
  if (isContractError(outcome.error)) throw outcome.error;
8359
9606
  return readValue(() => {
8360
9607
  throw outcome.error;
@@ -8373,7 +9620,11 @@ var ContractCompiler = class ContractCompiler {
8373
9620
  const plans = INTRINSICS.reflect.apply(INTRINSICS.expand, readIndexView(owned.variants), [(variant) => variant === void 0 ? [] : [this.#auditAt(variant)]]);
8374
9621
  const exclusive = owned.mode === "oneOf";
8375
9622
  const count = owned.variants.length;
9623
+ const discriminated = this.#discriminate(owned);
8376
9624
  return (value, path) => {
9625
+ const selected = discriminated?.select(value);
9626
+ const arm = selected === void 0 ? void 0 : plans[selected];
9627
+ if (arm !== void 0) return arm(value, path);
8377
9628
  const perVariant = [];
8378
9629
  for (const index2 of iterateIndices(() => plans.length)) {
8379
9630
  const plan = plans[index2];
@@ -8390,18 +9641,21 @@ var ContractCompiler = class ContractCompiler {
8390
9641
  if (matched > 1) return [{
8391
9642
  reason: "oneOf",
8392
9643
  path,
8393
- matched
9644
+ matched,
9645
+ ...discriminated?.hint
8394
9646
  }];
8395
9647
  }
8396
9648
  const closest = selectClosestFaults(perVariant);
8397
9649
  const report = [exclusive ? {
8398
9650
  reason: "oneOf",
8399
9651
  path,
8400
- matched: 0
9652
+ matched: 0,
9653
+ ...discriminated?.hint
8401
9654
  } : {
8402
9655
  reason: "variant",
8403
9656
  path,
8404
- variants: count
9657
+ variants: count,
9658
+ ...discriminated?.hint
8405
9659
  }];
8406
9660
  appendEntries(report, closest);
8407
9661
  return limitEntries(report, 64);
@@ -8427,7 +9681,7 @@ var ContractCompiler = class ContractCompiler {
8427
9681
  const ready = this.#reporter;
8428
9682
  if (ready !== void 0) return ready;
8429
9683
  this.#prepare();
8430
- if (this.#unions()) this.#buildGuard();
9684
+ if (this.#unions() || this.#defaults()) this.#buildGuard();
8431
9685
  for (const step of iterateIndices(() => this.#order.length)) {
8432
9686
  const index = this.#order[step];
8433
9687
  if (index === void 0) continue;
@@ -8513,6 +9767,12 @@ var ContractCompiler = class ContractCompiler {
8513
9767
  received: preview(value)
8514
9768
  }];
8515
9769
  }
9770
+ case "shape": return (value, path) => ContractCompiler.#acceptShape(value) ? [] : [{
9771
+ reason: "type",
9772
+ path,
9773
+ expected: "shape",
9774
+ received: preview(value)
9775
+ }];
8516
9776
  case "array": {
8517
9777
  const node = owned;
8518
9778
  const item = this.#reportAt(owned.items);
@@ -8524,7 +9784,7 @@ var ContractCompiler = class ContractCompiler {
8524
9784
  received: preview(value)
8525
9785
  }];
8526
9786
  const entries = readArrayEntries(value);
8527
- if (!entries.success) return [{
9787
+ if (isFailure(entries)) return [{
8528
9788
  reason: "type",
8529
9789
  path,
8530
9790
  expected: "array",
@@ -8558,7 +9818,7 @@ var ContractCompiler = class ContractCompiler {
8558
9818
  const tail = extra === void 0 || extra === true || extra === false ? void 0 : this.#reportAt(extra);
8559
9819
  const open = extra === true || tail !== void 0;
8560
9820
  const planned = attempt(() => collectMembers(names));
8561
- const known = planned.success ? planned.value : void 0;
9821
+ const known = isSuccess(planned) ? planned.value : void 0;
8562
9822
  const maskable = entries.length <= 31;
8563
9823
  const positions = buildPositions(maskable ? INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(entries), [(entry) => entry.key]) : []);
8564
9824
  return (value, path) => {
@@ -8577,7 +9837,7 @@ var ContractCompiler = class ContractCompiler {
8577
9837
  received: preview(value)
8578
9838
  }];
8579
9839
  const faults = [];
8580
- if (!attempt(() => {
9840
+ if (isFailure(attempt(() => {
8581
9841
  const present = maskable ? void 0 : collectMembers(keys);
8582
9842
  const vocabulary = known ?? collectMembers(names);
8583
9843
  const seen = present === void 0 ? readPresence(keys, positions) : 0;
@@ -8612,7 +9872,7 @@ var ContractCompiler = class ContractCompiler {
8612
9872
  const observed = record[key];
8613
9873
  if (tail !== void 0) appendEntries(faults, tail(observed, pathOf(path, key)));
8614
9874
  }
8615
- }).success) return [{
9875
+ }))) return [{
8616
9876
  reason: "type",
8617
9877
  path,
8618
9878
  expected: "object",
@@ -8630,7 +9890,11 @@ var ContractCompiler = class ContractCompiler {
8630
9890
  const guards = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(variants), [(variant) => variant.guard]);
8631
9891
  const exclusive = owned.mode === "oneOf";
8632
9892
  const count = owned.variants.length;
9893
+ const discriminated = this.#discriminate(owned);
8633
9894
  return (value, path) => {
9895
+ const selected = discriminated?.select(value);
9896
+ const arm = selected === void 0 ? void 0 : plans[selected];
9897
+ if (arm !== void 0) return arm(value, path);
8634
9898
  const perVariant = [];
8635
9899
  for (const index2 of iterateIndices(() => plans.length)) {
8636
9900
  const plan = plans[index2];
@@ -8647,7 +9911,8 @@ var ContractCompiler = class ContractCompiler {
8647
9911
  const report = [{
8648
9912
  reason: "oneOf",
8649
9913
  path,
8650
- matched: 0
9914
+ matched: 0,
9915
+ ...discriminated?.hint
8651
9916
  }];
8652
9917
  appendEntries(report, closest);
8653
9918
  return limitEntries(report, 64);
@@ -8655,13 +9920,15 @@ var ContractCompiler = class ContractCompiler {
8655
9920
  return [{
8656
9921
  reason: "oneOf",
8657
9922
  path,
8658
- matched
9923
+ matched,
9924
+ ...discriminated?.hint
8659
9925
  }];
8660
9926
  }
8661
9927
  const report = [{
8662
9928
  reason: "variant",
8663
9929
  path,
8664
- variants: count
9930
+ variants: count,
9931
+ ...discriminated?.hint
8665
9932
  }];
8666
9933
  appendEntries(report, closest);
8667
9934
  return limitEntries(report, 64);
@@ -8687,7 +9954,7 @@ var ContractCompiler = class ContractCompiler {
8687
9954
  const ready = this.#generator;
8688
9955
  if (ready !== void 0) return ready;
8689
9956
  this.#prepare();
8690
- if (this.#unions()) this.#buildGuard();
9957
+ if (this.#unions() || this.#defaults()) this.#buildGuard();
8691
9958
  for (const step of iterateIndices(() => this.#order.length)) {
8692
9959
  const index = this.#order[step];
8693
9960
  if (index === void 0) continue;
@@ -8754,6 +10021,11 @@ var ContractCompiler = class ContractCompiler {
8754
10021
  }
8755
10022
  case "boolean": return (random) => drawRandom(random, "boolean") >= .5;
8756
10023
  case "null": return () => null;
10024
+ case "shape": return () => ({
10025
+ category: "object",
10026
+ properties: {},
10027
+ additionalProperties: false
10028
+ });
8757
10029
  case "json": return (random) => {
8758
10030
  const pick = INTRINSICS.floor(drawRandom(random, "json") * 5);
8759
10031
  if (pick === 0) return null;
@@ -8837,8 +10109,8 @@ var ContractCompiler = class ContractCompiler {
8837
10109
  const plan = plans[(start + attemptIndex) % count];
8838
10110
  if (plan === void 0) continue;
8839
10111
  const outcome = attempt(() => plan(random));
8840
- if (!outcome.success && isContractError(outcome.error) && outcome.error.code === "random") throw outcome.error;
8841
- if (outcome.success && guard(outcome.value)) return outcome.value;
10112
+ if (isFailure(outcome) && isContractError(outcome.error) && outcome.error.code === "random") throw outcome.error;
10113
+ if (isSuccess(outcome) && guard(outcome.value)) return outcome.value;
8842
10114
  }
8843
10115
  throw new ContractError("compileGenerator: no union candidate satisfied the compiled guard", {
8844
10116
  code: "generate",
@@ -8920,14 +10192,15 @@ var ContractCompiler = class ContractCompiler {
8920
10192
  * eager well-formedness pass — there is no second prepass and no alias for it:
8921
10193
  * it enforces every bound domain and range used by the artifacts, including
8922
10194
  * non-empty literal/union vocabularies, finite literal numbers, integer-range
8923
- * satisfiability, unflagged string patterns, optional-shape placement, and the
8924
- * recursively supported raw-schema vocabulary where every present property or
8925
- * dense union member is a record.
10195
+ * satisfiability, unflagged string patterns, optional-shape and default
10196
+ * placement, and the recursively supported raw-schema vocabulary where every
10197
+ * present property or dense union member is a record. It judges a default's
10198
+ * structure only; each compiler refuses a default its inner guard refuses.
8926
10199
  * Active ancestors are tracked so shared children remain legal. Every
8927
10200
  * standalone compiler reaches this same validation once, over its owned
8928
10201
  * snapshot, through {@link ContractCompiler} preparation.
8929
- * Failures have deterministic precedence independent of traversal order: depth,
8930
- * then structure, then cycle, then field and vocabulary policy.
10202
+ * Cyclic graphs refuse before depth measurement, with structure before cycle.
10203
+ * Acyclic graphs report depth before structure, then field and vocabulary policy.
8931
10204
  *
8932
10205
  * @param shape - The shape graph to gate
8933
10206
  * @returns Nothing; successful return means recursive compilation is structurally safe, depth-safe, and bounded in emitted nodes
@@ -9069,9 +10342,104 @@ function compileReporter(shape, value, path = []) {
9069
10342
  function compileAuditor(shape, value, path = []) {
9070
10343
  return contain(() => new ContractCompiler(shape).auditor(value, path), "compileAuditor");
9071
10344
  }
10345
+ // src/core/LazyContract.ts
10346
+ /**
10347
+ * Owns a contract whose function members compile together on the first call to any.
10348
+ *
10349
+ * @remarks
10350
+ * For a declaration made entirely by builders, where preparation and the schema have
10351
+ * already asked everything that can refuse. A module that declares its contracts as
10352
+ * data then pays for a contract only when something uses it, and each member is a
10353
+ * plain function with one identity, so destructuring and spreading compile nothing.
10354
+ *
10355
+ * A compile can still fail for the host's reasons: a first call near the stack limit,
10356
+ * or a host whose members were replaced after this contract was created, which it
10357
+ * refuses to compile on since the result would outlive the replacement. Neither says
10358
+ * anything about a later call, which compiles afresh. Until then a guard answers
10359
+ * `false` and a parser `undefined`, and the diagnostic and seed members publish the
10360
+ * failure as their doors do.
10361
+ */
10362
+ var LazyContract = class {
10363
+ #shape;
10364
+ #pending;
10365
+ #settled;
10366
+ #bundle;
10367
+ /**
10368
+ * Retains a declaration and the compiler already prepared from it.
10369
+ *
10370
+ * @param shape - The sealed declaration
10371
+ * @param compiler - The compiler that owns its prepared index
10372
+ */
10373
+ constructor(shape, compiler) {
10374
+ this.#shape = shape;
10375
+ this.#pending = compiler;
10376
+ }
10377
+ /**
10378
+ * Compiles the schema, which refuses a bad declaration, and publishes the bundle.
10379
+ *
10380
+ * @param schema - The schema the prepared compiler emitted
10381
+ * @returns The frozen bundle, in the key order the compiler's own bundle uses
10382
+ */
10383
+ publish(schema) {
10384
+ return INTRINSICS.freeze({
10385
+ schema,
10386
+ is: this.#is(),
10387
+ parse: this.#parse(),
10388
+ audit: this.#audit(),
10389
+ explain: this.#explain(),
10390
+ generate: this.#generate()
10391
+ });
10392
+ }
10393
+ #is() {
10394
+ return (value) => {
10395
+ const bundle = this.#bundle ?? this.#attempt();
10396
+ return bundle !== void 0 && bundle.is(value);
10397
+ };
10398
+ }
10399
+ #parse() {
10400
+ return (value) => {
10401
+ const bundle = this.#bundle ?? this.#attempt();
10402
+ return bundle === void 0 ? void 0 : bundle.parse(value);
10403
+ };
10404
+ }
10405
+ #audit() {
10406
+ return (value, path = []) => (this.#settled ?? this.#settle("compileAuditor")).auditor(value, path);
10407
+ }
10408
+ #explain() {
10409
+ return (value, path = []) => (this.#settled ?? this.#settle("compileReporter")).reporter(value, path);
10410
+ }
10411
+ #generate() {
10412
+ return (random) => (this.#settled ?? this.#settle("compileGenerator")).generator(random);
10413
+ }
10414
+ #attempt() {
10415
+ attempt(() => this.#settle("createContract"));
10416
+ return this.#bundle;
10417
+ }
10418
+ #settle(door) {
10419
+ return contain(() => {
10420
+ if (ShapePass.tampered()) throw new ContractError(`${door}: a host member this contract compiles on was replaced after it was created`, {
10421
+ code: "structure",
10422
+ context: {
10423
+ path: [],
10424
+ shape: "contract"
10425
+ }
10426
+ });
10427
+ const compiler = this.#pending ?? new ContractCompiler(this.#shape);
10428
+ this.#pending = void 0;
10429
+ this.#bundle = compiler.contract;
10430
+ this.#settled = compiler;
10431
+ return compiler;
10432
+ }, door);
10433
+ }
10434
+ };
9072
10435
  // src/core/factories.ts
9073
10436
  function createContract(shape) {
9074
- return contain(() => new ContractCompiler(shape).contract, "createContract");
10437
+ return contain(() => {
10438
+ const compiler = new ContractCompiler(shape);
10439
+ const expansion = ShapePass.expansionOf(shape);
10440
+ if (expansion === void 0 || expansion === 1) return compiler.contract;
10441
+ return new LazyContract(shape, compiler).publish(compiler.schema);
10442
+ }, "createContract");
9075
10443
  }
9076
10444
  // src/core/ValueInferer.ts
9077
10445
  /**
@@ -9152,14 +10520,14 @@ var ValueInferer = class ValueInferer {
9152
10520
  admitVisited(this.#visited, value);
9153
10521
  const outcome = attempt(() => {
9154
10522
  const snapshot = readArrayEntries(value);
9155
- if (!snapshot.success) throw snapshot.error;
10523
+ if (isFailure(snapshot)) throw snapshot.error;
9156
10524
  if (!snapshot.value.dense) return void 0;
9157
10525
  const entries = snapshot.value.entries;
9158
10526
  const length = INTRINSICS.ceil(INTRINSICS.min(entries.length, this.#breadth));
9159
10527
  return INTRINSICS.from(iterateIndices(() => length), (index) => this.#infer(entries[index], depth - 1));
9160
10528
  });
9161
10529
  omitVisited(this.#visited, value);
9162
- if (!outcome.success) throw outcome.error;
10530
+ if (isFailure(outcome)) throw outcome.error;
9163
10531
  const sampled = outcome.value;
9164
10532
  const schema = sampled === void 0 ? {} : sampled.length > 0 ? {
9165
10533
  type: "array",
@@ -9203,7 +10571,7 @@ var ValueInferer = class ValueInferer {
9203
10571
  };
9204
10572
  });
9205
10573
  omitVisited(this.#visited, value);
9206
- if (!outcome.success) throw outcome.error;
10574
+ if (isFailure(outcome)) throw outcome.error;
9207
10575
  const { properties, required, partial } = outcome.value;
9208
10576
  const schema = {
9209
10577
  type: "object",
@@ -9330,7 +10698,7 @@ var SampleInferer = class {
9330
10698
  dropped: INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry.dropped])
9331
10699
  };
9332
10700
  });
9333
- if (!valuesOutcome.success) throw valuesOutcome.error;
10701
+ if (isFailure(valuesOutcome)) throw valuesOutcome.error;
9334
10702
  const { values, dropped } = valuesOutcome.value;
9335
10703
  return {
9336
10704
  key,
@@ -9393,7 +10761,7 @@ function unifySchemas(schemas) {
9393
10761
  return contain(() => {
9394
10762
  return readValue(() => {
9395
10763
  const snapshot = readArrayEntries(schemas);
9396
- if (!snapshot.success) throw snapshot.error;
10764
+ if (isFailure(snapshot)) throw snapshot.error;
9397
10765
  if (!snapshot.value.dense) throw new INTRINSICS.error("unifySchemas: schemas must be dense");
9398
10766
  const owned = snapshot.value.entries;
9399
10767
  if (owned.length === 0) return {};
@@ -9451,7 +10819,7 @@ function stringToFormat(value) {
9451
10819
  if (!isString(value)) return void 0;
9452
10820
  if (value.length > 128) return void 0;
9453
10821
  const outcome = attempt(() => classifyFormat(value));
9454
- return outcome.success ? outcome.value : void 0;
10822
+ return isSuccess(outcome) ? outcome.value : void 0;
9455
10823
  }
9456
10824
  /**
9457
10825
  * Classifies a list of sample values against the {@link SchemaFormat}
@@ -9480,7 +10848,7 @@ function samplesToFormat(values) {
9480
10848
  return contain(() => {
9481
10849
  return readValue(() => {
9482
10850
  const snapshot = readArrayEntries(values);
9483
- if (!snapshot.success) throw snapshot.error;
10851
+ if (isFailure(snapshot)) throw snapshot.error;
9484
10852
  if (!snapshot.value.dense) throw new INTRINSICS.error("samplesToFormat: values must be dense");
9485
10853
  const owned = snapshot.value.entries;
9486
10854
  if (owned.length === 0) return void 0;
@@ -9531,7 +10899,7 @@ function inferPrimitiveEnum(values, limit) {
9531
10899
  return contain(() => {
9532
10900
  return readValue(() => {
9533
10901
  const snapshot = readArrayEntries(values);
9534
- if (!snapshot.success) throw snapshot.error;
10902
+ if (isFailure(snapshot)) throw snapshot.error;
9535
10903
  if (!snapshot.value.dense) throw new INTRINSICS.error("inferPrimitiveEnum: values must be dense");
9536
10904
  const owned = snapshot.value.entries;
9537
10905
  if (owned.length < 2) return void 0;
@@ -9661,7 +11029,7 @@ function samplesToSchema(samples, options) {
9661
11029
  const enumOn = optionsSnapshot?.enum ?? false;
9662
11030
  const read = readValue(() => {
9663
11031
  const snapshot = readArrayEntries(samples);
9664
- if (!snapshot.success) throw snapshot.error;
11032
+ if (isFailure(snapshot)) throw snapshot.error;
9665
11033
  return snapshot.value;
9666
11034
  }, "samplesToSchema", { subject: "samples" });
9667
11035
  if (!read.dense) throw new ContractError("samplesToSchema: samples must be a dense array", { code: "structure" });
@@ -9678,7 +11046,9 @@ function samplesToSchema(samples, options) {
9678
11046
  * rather than parameters, so no caller can pre-populate either and change what
9679
11047
  * the conversion widens. Construction observes nothing; `shape` runs the whole
9680
11048
  * walk and every refusal it raises is published by that door under the door's
9681
- * own name.
11049
+ * own name. A strict walk refuses where a lenient one widens, through the one
11050
+ * `#widen` both share, and its per-node `#inspect` refuses every keyword the
11051
+ * lenient precedence would read past.
9682
11052
  *
9683
11053
  * The recursion is `#` private for the same reason it is bounded: it is the
9684
11054
  * class's defining spine, and its state has no meaning outside one call. The
@@ -9694,73 +11064,314 @@ var SchemaShaper = class SchemaShaper {
9694
11064
  static #weakSet = WeakSet;
9695
11065
  static #weakMap = WeakMap;
9696
11066
  #source;
11067
+ #strict;
9697
11068
  #visited;
9698
11069
  #memo;
9699
- constructor(schema) {
11070
+ #enclosed;
11071
+ #exclusive;
11072
+ #path;
11073
+ #oneOfs;
11074
+ #built;
11075
+ #shared;
11076
+ constructor(schema, strict = false) {
9700
11077
  this.#source = schema;
11078
+ this.#strict = strict;
9701
11079
  this.#visited = new SchemaShaper.#weakSet();
9702
11080
  this.#memo = new SchemaShaper.#weakMap();
11081
+ this.#enclosed = new SchemaShaper.#weakMap();
11082
+ this.#exclusive = new SchemaShaper.#weakMap();
11083
+ this.#path = [];
11084
+ this.#oneOfs = 0;
11085
+ this.#built = 0;
11086
+ this.#shared = false;
9703
11087
  }
9704
11088
  /**
9705
11089
  * Converts the retained schema into a validating contract shape.
9706
11090
  *
9707
- * @returns The built shape, widened wherever the schema is inexpressible
9708
- * @throws {ContractError} When schema traversal fails
11091
+ * @returns The built shape, widened wherever a lenient schema is inexpressible
11092
+ * @throws {ContractError} When schema traversal fails, or when a strict conversion refuses
9709
11093
  */
9710
11094
  shape() {
9711
- return this.#convert(this.#source, 32);
11095
+ if (this.#strict && isRecord(this.#source) && INTRINSICS.own(this.#source, "default")) throw this.#refusal("a default needs an optional property to fill", "default");
11096
+ const shape = this.#convert(this.#source, 32, false);
11097
+ return !this.#strict && this.#exceeds(shape) ? this.#shallow(shape) : shape;
11098
+ }
11099
+ #exceeds(shape) {
11100
+ if (!this.#shared && this.#built <= 1024) return false;
11101
+ const validator = new ShapeValidator(shape);
11102
+ validator.validate();
11103
+ return (validator.expansion ?? 0) > COMPILE_NODE_LIMIT;
11104
+ }
11105
+ #shallow(shape) {
11106
+ const raw = rawShape({});
11107
+ switch (shape.category) {
11108
+ case "nullable": return nullableShape(this.#shallow(shape.inner));
11109
+ case "array": return arrayShape(raw, INTRINSICS.rebase({
11110
+ ...shape.min === void 0 ? {} : { min: shape.min },
11111
+ ...shape.max === void 0 ? {} : { max: shape.max },
11112
+ ...shape.description === void 0 ? {} : { description: shape.description }
11113
+ }, null));
11114
+ case "object": {
11115
+ const pairs = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(INTRINSICS.keys(shape.properties)), [(key) => [key, shape.properties[key]?.category === "optional" ? optionalShape(raw) : raw]]);
11116
+ const properties = INTRINSICS.rebase(INTRINSICS.record({ [Symbol.iterator]: INTRINSICS.reflect.apply(INTRINSICS.bind, INTRINSICS.iterator, [pairs]) }), null);
11117
+ const extra = shape.additionalProperties;
11118
+ return objectShape(properties, INTRINSICS.rebase({
11119
+ additionalProperties: isObject(extra) ? raw : extra ?? false,
11120
+ ...shape.description === void 0 ? {} : { description: shape.description }
11121
+ }, null));
11122
+ }
11123
+ default: return raw;
11124
+ }
9712
11125
  }
9713
- #convert(schema, depth) {
9714
- if (!(depth > 0)) return rawShape({});
9715
- if (!matchesRecordBrand(schema)) return rawShape({});
9716
- if (matchesVisited(this.#visited, schema)) return rawShape({});
9717
- const depthMemo = INTRINSICS.reflect.apply(INTRINSICS.recall, this.#memo, [schema]);
11126
+ #convert(schema, depth, enclosed) {
11127
+ if (!(depth > 0)) return this.#widen("a schema may not nest past the depth limit", void 0);
11128
+ if (!matchesRecordBrand(schema)) return this.#widen("every schema node must be a plain record", void 0);
11129
+ if (matchesVisited(this.#visited, schema)) return this.#widen("a schema may not contain a cycle", void 0);
11130
+ const memo = this.#oneOfs > 0 ? this.#exclusive : enclosed ? this.#enclosed : this.#memo;
11131
+ const depthMemo = INTRINSICS.reflect.apply(INTRINSICS.recall, memo, [schema]);
9718
11132
  const cached = depthMemo === void 0 ? void 0 : INTRINSICS.reflect.apply(INTRINSICS.fetch, depthMemo, [depth]);
9719
- if (cached) return cached;
11133
+ if (cached) {
11134
+ this.#shared = true;
11135
+ return cached;
11136
+ }
9720
11137
  admitVisited(this.#visited, schema);
9721
11138
  try {
9722
- const shape = this.#build(schema, depth);
9723
- retainDepth(this.#memo, schema, depth, shape);
11139
+ if (this.#strict) this.#inspect(schema);
11140
+ const built = this.#build(schema, depth, enclosed);
11141
+ const shape = INTRINSICS.own(schema, "nullable") && INTRINSICS.reflect.read(schema, "nullable") === true ? nullableShape(built) : built;
11142
+ retainDepth(memo, schema, depth, shape);
9724
11143
  return shape;
9725
11144
  } finally {
9726
11145
  omitVisited(this.#visited, schema);
9727
11146
  }
9728
11147
  }
9729
- #build(schema, depth) {
9730
- const description = isString(schema.description) ? schema.description : void 0;
9731
- if (isArray(schema.enum)) {
11148
+ #descend(schema, depth, enclosed, first, second) {
11149
+ this.#path[this.#path.length] = first;
11150
+ if (second !== void 0) this.#path[this.#path.length] = second;
11151
+ if (this.#strict && first !== "properties" && isRecord(schema) && INTRINSICS.own(schema, "default")) throw this.#refusal("a default needs an optional property to fill", "default");
11152
+ const shape = this.#convert(schema, depth, enclosed);
11153
+ this.#path.length -= second === void 0 ? 1 : 2;
11154
+ return shape;
11155
+ }
11156
+ #widen(message, description, first, second) {
11157
+ if (this.#strict) throw this.#refusal(message, first, second);
11158
+ this.#built += 1;
11159
+ return rawShape(description === void 0 ? {} : { description });
11160
+ }
11161
+ #describe(shape, description) {
11162
+ if (description === void 0) return shape;
11163
+ switch (shape.category) {
11164
+ case "optional": return shape;
11165
+ case "nullable": return nullableShape(this.#describe(shape.inner, description));
11166
+ case "raw": return rawShape({
11167
+ ...shape.schema,
11168
+ description
11169
+ });
11170
+ default: return INTRINSICS.freeze({
11171
+ ...shape,
11172
+ description
11173
+ });
11174
+ }
11175
+ }
11176
+ #refusal(message, first, second, third) {
11177
+ const path = pathOf(this.#path, first, second, third);
11178
+ return new ContractError(`schemaToShape: ${message} at ${truncateFaultText(renderPath(path) || "value", 160)}`, {
11179
+ code: "structure",
11180
+ context: {
11181
+ path,
11182
+ shape: "schema"
11183
+ }
11184
+ });
11185
+ }
11186
+ #inspect(schema) {
11187
+ const keys = INTRINSICS.keys(schema);
11188
+ for (const index of iterateIndices(() => keys.length)) {
11189
+ const key = keys[index];
11190
+ if (key === void 0) continue;
11191
+ if (!INTRINSICS.reflect.apply(INTRINSICS.some, STRICT_SCHEMA_KEYWORDS, [(keyword) => keyword === key])) throw this.#refusal("a strict conversion refuses a keyword it cannot honour", key);
11192
+ }
11193
+ this.#inspectAnnotations(schema);
11194
+ if (INTRINSICS.own(schema, "default") && !isJSONValue(schema.default)) throw this.#refusal("a default must be a JSON value", "default");
11195
+ const types = this.#inspectType(schema);
11196
+ this.#inspectForm(schema, types);
11197
+ const hasForm = INTRINSICS.own(schema, "enum") || INTRINSICS.own(schema, "oneOf") || INTRINSICS.own(schema, "anyOf");
11198
+ const object = types.length === 0 && INTRINSICS.own(schema, "properties") ? ["object"] : types;
11199
+ const effective = hasForm ? [] : object;
11200
+ this.#confine(schema, ["minLength", "maxLength"], this.#names(effective, "string"));
11201
+ this.#confine(schema, ["minimum", "maximum"], this.#names(effective, "number", "integer"));
11202
+ this.#confine(schema, [
11203
+ "items",
11204
+ "minItems",
11205
+ "maxItems"
11206
+ ], this.#names(effective, "array"));
11207
+ this.#confine(schema, [
11208
+ "properties",
11209
+ "required",
11210
+ "additionalProperties"
11211
+ ], this.#names(effective, "object"));
11212
+ this.#inspectLength(INTRINSICS.own(schema, "minLength") ? schema.minLength : void 0, INTRINSICS.own(schema, "maxLength") ? schema.maxLength : void 0, "minLength", "maxLength");
11213
+ this.#inspectLength(INTRINSICS.own(schema, "minItems") ? schema.minItems : void 0, INTRINSICS.own(schema, "maxItems") ? schema.maxItems : void 0, "minItems", "maxItems");
11214
+ this.#inspectRange(schema, this.#names(effective, "integer"));
11215
+ this.#inspectObject(schema);
11216
+ }
11217
+ #inspectAnnotations(schema) {
11218
+ const texts = [
11219
+ "title",
11220
+ "description",
11221
+ "$schema",
11222
+ "$id",
11223
+ "$comment"
11224
+ ];
11225
+ for (const index of iterateIndices(() => texts.length)) {
11226
+ const keyword = texts[index];
11227
+ if (keyword === void 0) continue;
11228
+ const value = INTRINSICS.own(schema, keyword) ? INTRINSICS.reflect.read(schema, keyword) : void 0;
11229
+ if (value !== void 0 && !isString(value)) throw this.#refusal(`${keyword} must be a string`, keyword);
11230
+ }
11231
+ const flags = [
11232
+ "deprecated",
11233
+ "readOnly",
11234
+ "writeOnly"
11235
+ ];
11236
+ for (const index of iterateIndices(() => flags.length)) {
11237
+ const keyword = flags[index];
11238
+ if (keyword === void 0) continue;
11239
+ const value = INTRINSICS.own(schema, keyword) ? INTRINSICS.reflect.read(schema, keyword) : void 0;
11240
+ if (value !== void 0 && !isBoolean(value)) throw this.#refusal(`${keyword} must be a boolean`, keyword);
11241
+ }
11242
+ const examples = INTRINSICS.own(schema, "examples") ? INTRINSICS.reflect.read(schema, "examples") : void 0;
11243
+ if (examples !== void 0 && !isArray(examples)) throw this.#refusal("examples must be an array", "examples");
11244
+ }
11245
+ #inspectType(schema) {
11246
+ const declared = INTRINSICS.own(schema, "type") ? schema.type : void 0;
11247
+ if (declared === void 0) return [];
11248
+ const names = isArray(declared) ? this.#entries(declared, "type") : [declared];
11249
+ const known = names.length > 0 && this.#unique(names);
11250
+ const types = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(JSON_SCHEMA_TYPES), [(type) => INTRINSICS.reflect.apply(INTRINSICS.some, names, [(name) => name === type])]);
11251
+ if (!known || types.length !== names.length) throw this.#refusal("type must name the supported types", "type");
11252
+ return types;
11253
+ }
11254
+ #inspectForm(schema, types) {
11255
+ if (INTRINSICS.own(schema, "enum")) {
11256
+ const members = this.#entries(schema.enum, "enum");
11257
+ const malformed = INTRINSICS.reflect.apply(INTRINSICS.some, members, [(entry) => entry !== null && (!isLiteralValue(entry) || typeof entry === "number" && !isFiniteNumber(entry))]);
11258
+ if (members.length === 0 || malformed || !this.#unique(members)) throw this.#refusal("enum must list unique finite primitives", "enum");
11259
+ if (INTRINSICS.reflect.apply(INTRINSICS.some, members, [(entry) => types.length > 0 && !this.#fits(entry, types)])) throw this.#refusal("an enum member contradicts the type", "enum");
11260
+ if (INTRINSICS.own(schema, "oneOf")) throw this.#refusal("a strict conversion refuses oneOf beside enum", "oneOf");
11261
+ if (INTRINSICS.own(schema, "anyOf")) throw this.#refusal("a strict conversion refuses anyOf beside enum", "anyOf");
11262
+ return;
11263
+ }
11264
+ const keywords = ["oneOf", "anyOf"];
11265
+ for (const index of iterateIndices(() => keywords.length)) {
11266
+ const keyword = keywords[index];
11267
+ if (keyword === void 0 || !INTRINSICS.own(schema, keyword)) continue;
11268
+ const variants = this.#entries(INTRINSICS.reflect.read(schema, keyword), keyword);
11269
+ if (variants.length === 0) throw this.#refusal(`${keyword} needs a variant`, keyword);
11270
+ for (const variantIndex of iterateIndices(() => variants.length)) if (!isRecord(variants[variantIndex])) throw this.#refusal("every variant must be a schema", keyword, INTRINSICS.text(variantIndex));
11271
+ }
11272
+ const union = INTRINSICS.own(schema, "oneOf") || INTRINSICS.own(schema, "anyOf");
11273
+ if (INTRINSICS.own(schema, "oneOf") && INTRINSICS.own(schema, "anyOf")) throw this.#refusal("a strict conversion refuses anyOf beside oneOf", "anyOf");
11274
+ if (union && types.length > 0) throw this.#refusal("a strict conversion refuses type beside a union", "type");
11275
+ }
11276
+ #inspectLength(min, max, minKey, maxKey) {
11277
+ if (min !== void 0 && !(INTRINSICS.safe(min) && INTRINSICS.numeric(min) >= 0)) throw this.#refusal("a length bound must be a non-negative safe integer", minKey);
11278
+ if (max !== void 0 && !(INTRINSICS.safe(max) && INTRINSICS.numeric(max) >= 0)) throw this.#refusal("a length bound must be a non-negative safe integer", maxKey);
11279
+ if (isFiniteNumber(min) && isFiniteNumber(max) && min > max) throw this.#refusal("a length range may not be contradictory", minKey);
11280
+ }
11281
+ #inspectRange(schema, integer) {
11282
+ const min = INTRINSICS.own(schema, "minimum") ? schema.minimum : void 0;
11283
+ const max = INTRINSICS.own(schema, "maximum") ? schema.maximum : void 0;
11284
+ if (min !== void 0 && !isFiniteNumber(min)) throw this.#refusal("a range bound must be a finite number", "minimum");
11285
+ if (max !== void 0 && !isFiniteNumber(max)) throw this.#refusal("a range bound must be a finite number", "maximum");
11286
+ if (isFiniteNumber(min) && isFiniteNumber(max)) {
11287
+ if (min > max) throw this.#refusal("a range may not be contradictory", "minimum");
11288
+ if (integer && INTRINSICS.ceil(min) > INTRINSICS.floor(max)) throw this.#refusal("an integer range may not be empty", "minimum");
11289
+ }
11290
+ }
11291
+ #inspectObject(schema) {
11292
+ const properties = INTRINSICS.own(schema, "properties") ? schema.properties : void 0;
11293
+ if (properties !== void 0 && !isRecord(properties)) throw this.#refusal("properties must be a plain record", "properties");
11294
+ const extra = INTRINSICS.own(schema, "additionalProperties") ? schema.additionalProperties : void 0;
11295
+ if (extra !== void 0 && !isBoolean(extra) && !isRecord(extra)) throw this.#refusal("additionalProperties must be a boolean or a schema", "additionalProperties");
11296
+ if (!INTRINSICS.own(schema, "required")) return;
11297
+ const names = this.#entries(schema.required, "required");
11298
+ if (INTRINSICS.reflect.apply(INTRINSICS.some, names, [(name) => !isString(name) || !isRecord(properties) || !INTRINSICS.own(properties, name)]) || !this.#unique(names)) throw this.#refusal("required must list unique declared properties", "required");
11299
+ }
11300
+ #confine(schema, keywords, applies) {
11301
+ if (applies) return;
11302
+ for (const index of iterateIndices(() => keywords.length)) {
11303
+ const keyword = keywords[index];
11304
+ if (keyword !== void 0 && INTRINSICS.own(schema, keyword)) throw this.#refusal("a strict conversion refuses a keyword this node never reads", keyword);
11305
+ }
11306
+ }
11307
+ #names(types, ...names) {
11308
+ return INTRINSICS.reflect.apply(INTRINSICS.some, types, [(type) => INTRINSICS.reflect.apply(INTRINSICS.some, names, [(name) => name === type])]);
11309
+ }
11310
+ #fits(entry, types) {
11311
+ if (entry === null) return this.#names(types, "null");
11312
+ if (isString(entry)) return this.#names(types, "string");
11313
+ if (isBoolean(entry)) return this.#names(types, "boolean");
11314
+ return isInteger(entry) ? this.#names(types, "number", "integer") : this.#names(types, "number");
11315
+ }
11316
+ #entries(value, keyword) {
11317
+ if (!isArray(value)) throw this.#refusal(`${keyword} must be an array`, keyword);
11318
+ const snapshot = readArrayEntries(value);
11319
+ if (isFailure(snapshot)) throw snapshot.error;
11320
+ if (!snapshot.value.dense) throw this.#refusal(`${keyword} must be a dense array`, keyword);
11321
+ return snapshot.value.entries;
11322
+ }
11323
+ #unique(entries) {
11324
+ const seen = collectMembers([]);
11325
+ for (const index of iterateIndices(() => entries.length)) {
11326
+ const entry = entries[index];
11327
+ if (matchesMember(seen, entry)) return false;
11328
+ admitMember(seen, entry);
11329
+ }
11330
+ return true;
11331
+ }
11332
+ #build(schema, depth, enclosed) {
11333
+ this.#built += 1;
11334
+ const description = INTRINSICS.own(schema, "description") && isString(schema.description) ? schema.description : void 0;
11335
+ if (INTRINSICS.own(schema, "$ref")) return this.#widen("a reference is not resolved", description, "$ref");
11336
+ if (INTRINSICS.own(schema, "enum") && isArray(schema.enum)) {
9732
11337
  const observed = INTRINSICS.from(iterateIndices(() => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "enum"]).length), (index) => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "enum"])[index]);
9733
- const valid = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(entry) => isLiteralValue(entry) && (typeof entry !== "number" || isFiniteNumber(entry))]);
11338
+ if (INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry !== null && (!isLiteralValue(entry) || typeof entry === "number" && !isFiniteNumber(entry))])) return this.#widen("an enum entry has no literal form", description, "enum");
11339
+ const valid = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(entry) => entry !== null]);
11340
+ const nullable = valid.length < observed.length;
9734
11341
  const pairs = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(valid), [(entry, index) => [`${typeof entry}:${INTRINSICS.text(entry)}`, index]]);
9735
11342
  const reversed = INTRINSICS.reflect.apply(INTRINSICS.flip, pairs, []);
9736
11343
  const first = INTRINSICS.record({ [Symbol.iterator]: INTRINSICS.reflect.apply(INTRINSICS.bind, INTRINSICS.iterator, [reversed]) });
9737
11344
  const literals = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(valid), [(entry, index) => first[`${typeof entry}:${INTRINSICS.text(entry)}`] === index]);
9738
- if (literals.length > 0) return literalShape(literals, description === void 0 ? void 0 : { description });
11345
+ if (literals.length > 0) {
11346
+ const literal = literalShape(literals, description === void 0 ? void 0 : { description });
11347
+ return nullable ? nullableShape(literal) : literal;
11348
+ }
11349
+ if (nullable) return nullShape(description === void 0 ? void 0 : { description });
9739
11350
  }
9740
- if (isArray(schema.oneOf)) {
9741
- const observed = INTRINSICS.from(iterateIndices(() => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "oneOf"]).length), (index) => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "oneOf"])[index]);
9742
- const records = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [isRecord]);
9743
- if (records.length > 256) return rawShape(description === void 0 ? {} : { description });
9744
- const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(records), [(entry) => this.#convert(entry, depth - 1)]);
9745
- if (variants.length > 0) return INTRINSICS.reflect.apply(oneOfShape, void 0, variants);
11351
+ if (INTRINSICS.own(schema, "oneOf") && isArray(schema.oneOf)) {
11352
+ const union = this.#buildUnion(schema.oneOf, "oneOf", depth, description, enclosed);
11353
+ if (union !== void 0) return union;
9746
11354
  }
9747
- if (isArray(schema.anyOf)) {
9748
- const observed = INTRINSICS.from(iterateIndices(() => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "anyOf"]).length), (index) => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "anyOf"])[index]);
9749
- const records = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [isRecord]);
9750
- if (records.length > 256) return rawShape(description === void 0 ? {} : { description });
9751
- const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(records), [(entry) => this.#convert(entry, depth - 1)]);
9752
- if (variants.length > 0) return INTRINSICS.reflect.apply(unionShape, void 0, variants);
11355
+ if (INTRINSICS.own(schema, "anyOf") && isArray(schema.anyOf)) {
11356
+ const union = this.#buildUnion(schema.anyOf, "anyOf", depth, description, enclosed);
11357
+ if (union !== void 0) return union;
9753
11358
  }
9754
- const category = schema.type;
11359
+ const category = INTRINSICS.own(schema, "type") ? schema.type : void 0;
9755
11360
  if (isArray(category)) {
9756
11361
  const observed = INTRINSICS.from(parseEnumValues(category, JSON_SCHEMA_TYPES));
9757
- if (INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry === void 0])) return rawShape(description === void 0 ? {} : { description });
11362
+ if (INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry === void 0])) return this.#widen("type must name the supported types", description, "type");
9758
11363
  const members = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(member, index) => INTRINSICS.reflect.apply(INTRINSICS.find, observed, [(entry) => entry === member]) === index]);
9759
- if (members.length === 0 || members.length > 256) return rawShape(description === void 0 ? {} : { description });
11364
+ if (members.length === 0 || members.length > 256) return this.#widen("type must name the supported types", description, "type");
11365
+ const others = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(members), [(member) => member !== "null"]);
11366
+ const other = others[0];
11367
+ if (members.length === 2 && others.length === 1 && other !== void 0) return nullableShape(this.#build({
11368
+ ...schema,
11369
+ type: other
11370
+ }, depth, enclosed));
9760
11371
  const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(members), [(member) => this.#build({
9761
11372
  ...schema,
9762
11373
  type: member
9763
- }, depth)]);
11374
+ }, depth, enclosed || members.length > 1)]);
9764
11375
  const first = variants[0];
9765
11376
  if (variants.length === 1 && first !== void 0) return first;
9766
11377
  const union = INTRINSICS.reflect.apply(unionShape, void 0, variants);
@@ -9769,45 +11380,88 @@ var SchemaShaper = class SchemaShaper {
9769
11380
  description
9770
11381
  });
9771
11382
  }
9772
- const type = isString(category) ? schema.type : void 0;
9773
- if (type === "string") return stringShape({
9774
- ...deriveLengthBounds(schema.minLength, schema.maxLength),
9775
- ...description === void 0 ? {} : { description }
9776
- });
9777
- if (type === "number") return numberShape({
9778
- ...deriveRangeBounds(schema.minimum, schema.maximum),
9779
- ...description === void 0 ? {} : { description }
9780
- });
11383
+ const type = isString(category) && INTRINSICS.own(schema, "type") ? schema.type : void 0;
11384
+ if (type === "string") {
11385
+ const bounds = deriveLengthBounds(INTRINSICS.own(schema, "minLength") ? schema.minLength : void 0, INTRINSICS.own(schema, "maxLength") ? schema.maxLength : void 0);
11386
+ return stringShape(INTRINSICS.rebase({
11387
+ ...bounds,
11388
+ ...description === void 0 ? {} : { description }
11389
+ }, null));
11390
+ }
11391
+ if (type === "number") {
11392
+ const bounds = deriveRangeBounds(INTRINSICS.own(schema, "minimum") ? schema.minimum : void 0, INTRINSICS.own(schema, "maximum") ? schema.maximum : void 0);
11393
+ return numberShape(INTRINSICS.rebase({
11394
+ ...bounds,
11395
+ ...description === void 0 ? {} : { description }
11396
+ }, null));
11397
+ }
9781
11398
  if (type === "integer") {
9782
- const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
9783
- return integerShape(INTRINSICS.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > INTRINSICS.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? description === void 0 ? void 0 : { description } : {
11399
+ const bounds = deriveRangeBounds(INTRINSICS.own(schema, "minimum") ? schema.minimum : void 0, INTRINSICS.own(schema, "maximum") ? schema.maximum : void 0);
11400
+ return integerShape(INTRINSICS.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > INTRINSICS.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? description === void 0 ? void 0 : INTRINSICS.rebase({ description }, null) : INTRINSICS.rebase({
9784
11401
  ...bounds,
9785
11402
  ...description === void 0 ? {} : { description }
9786
- });
11403
+ }, null));
9787
11404
  }
9788
11405
  if (type === "boolean") return booleanShape(description === void 0 ? void 0 : { description });
9789
11406
  if (type === "null") return nullShape(description === void 0 ? void 0 : { description });
9790
- if (type === "array") return arrayShape(isRecord(schema.items) ? this.#convert(schema.items, depth - 1) : rawShape({}), {
9791
- ...deriveLengthBounds(schema.minItems, schema.maxItems),
9792
- ...description === void 0 ? {} : { description }
9793
- });
9794
- if (type === "object" || type === void 0 && isRecord(schema.properties)) return this.#buildObject(schema, depth, description);
9795
- return rawShape(description === void 0 ? {} : { description });
11407
+ if (type === "array") {
11408
+ const items = INTRINSICS.own(schema, "prefixItems") ? rawShape({}) : INTRINSICS.own(schema, "items") && isRecord(schema.items) ? this.#descend(schema.items, depth - 1, enclosed, "items") : this.#widen("an array needs an items schema", void 0, "items");
11409
+ const bounds = deriveLengthBounds(INTRINSICS.own(schema, "minItems") ? schema.minItems : void 0, INTRINSICS.own(schema, "maxItems") ? schema.maxItems : void 0);
11410
+ return arrayShape(items, INTRINSICS.rebase({
11411
+ ...bounds,
11412
+ ...description === void 0 ? {} : { description }
11413
+ }, null));
11414
+ }
11415
+ if (type === "object" || this.#strict && type === void 0 && INTRINSICS.own(schema, "properties") && isRecord(schema.properties)) return this.#buildObject(schema, depth, description, enclosed);
11416
+ if (type === void 0 && INTRINSICS.own(schema, "properties") && isRecord(schema.properties)) return this.#describe(unionShape(this.#buildObject(schema, depth, void 0, true), stringShape(), numberShape(), booleanShape(), nullShape(), arrayShape(rawShape({}))), description);
11417
+ return this.#widen("a schema must name a type, an enum, or a union", description);
11418
+ }
11419
+ #buildUnion(list, keyword, depth, description, enclosed) {
11420
+ const observed = INTRINSICS.from(iterateIndices(() => list.length), (index) => list[index]);
11421
+ const arms = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(entry) => entry === true || isRecord(entry)]);
11422
+ if (arms.length > 256) return this.#widen(`${keyword} exceeds the breadth limit`, description, keyword);
11423
+ const nulls = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(arms), [(entry) => entry !== true && INTRINSICS.own(entry, "type") && entry.type === "null" && !INTRINSICS.own(entry, "$ref") && !INTRINSICS.own(entry, "enum") && !INTRINSICS.own(entry, "oneOf") && !INTRINSICS.own(entry, "anyOf")]);
11424
+ const hasTrue = INTRINSICS.reflect.apply(INTRINSICS.some, arms, [(entry) => entry === true]);
11425
+ const paired = arms.length === 2 && nulls.length === 1 && !hasTrue && !(this.#strict && keyword === "oneOf");
11426
+ const exclusive = this.#strict && keyword === "oneOf" ? 1 : 0;
11427
+ this.#oneOfs += exclusive;
11428
+ const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(arms), [(entry, index) => {
11429
+ if (entry !== true) {
11430
+ const position = paired ? enclosed : true;
11431
+ return this.#descend(entry, depth - 1, position, keyword, INTRINSICS.text(index));
11432
+ }
11433
+ this.#built += 1;
11434
+ return rawShape({});
11435
+ }]);
11436
+ this.#oneOfs -= exclusive;
11437
+ const other = variants[arms[0] === nulls[0] ? 1 : 0];
11438
+ if (paired && other !== void 0) return nullableShape(this.#describe(other, description));
11439
+ if (variants.length > 0) {
11440
+ const build = this.#strict && keyword === "oneOf" ? oneOfShape : unionShape;
11441
+ return this.#describe(INTRINSICS.reflect.apply(build, void 0, variants), description);
11442
+ }
11443
+ return INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry === false]) ? this.#widen(`${keyword} admits nothing`, description, keyword) : void 0;
9796
11444
  }
9797
- #buildObject(schema, depth, description) {
9798
- const propertiesSource = isRecord(schema.properties) ? schema.properties : void 0;
9799
- const requiredSource = isArray(schema.required) ? INTRINSICS.from(iterateIndices(() => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "required"]).length), (index) => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "required"])[index]) : [];
11445
+ #buildObject(schema, depth, description, enclosed) {
11446
+ if (this.#oneOfs > 0 && !INTRINSICS.own(schema, "additionalProperties")) throw this.#refusal("an object below a oneOf must declare additionalProperties, because closing it could change which arms match", "additionalProperties");
11447
+ const propertiesSource = INTRINSICS.own(schema, "properties") && isRecord(schema.properties) ? schema.properties : void 0;
11448
+ const requiredSource = INTRINSICS.own(schema, "required") && isArray(schema.required) ? INTRINSICS.from(iterateIndices(() => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "required"]).length), (index) => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "required"])[index]) : [];
9800
11449
  const allKeys = propertiesSource === void 0 ? [] : INTRINSICS.keys(propertiesSource);
9801
11450
  const truncated = allKeys.length > 256;
11451
+ if (this.#strict && truncated) throw this.#refusal("properties exceeds the breadth limit", "properties");
9802
11452
  const keys = limitEntries(allKeys, 256);
11453
+ const extra = INTRINSICS.own(schema, "additionalProperties") ? schema.additionalProperties : void 0;
11454
+ const unread = truncated || INTRINSICS.own(schema, "patternProperties");
11455
+ const open = unread || extra !== false && (!this.#strict || extra !== void 0);
9803
11456
  const pairs = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(keys), [(key) => {
9804
- const child = propertiesSource?.[key];
9805
- const childShape = isRecord(child) ? this.#convert(child, depth - 1) : rawShape({});
9806
- return [key, INTRINSICS.reflect.apply(INTRINSICS.some, requiredSource, [(entry) => isString(entry) && entry === key]) ? childShape : optionalShape(childShape)];
11457
+ const child = propertiesSource !== void 0 && INTRINSICS.own(propertiesSource, key) ? propertiesSource[key] : void 0;
11458
+ const childShape = isRecord(child) ? this.#descend(child, depth - 1, enclosed, "properties", key) : this.#widen("every property schema must be a plain record", void 0, "properties", key);
11459
+ if (!INTRINSICS.reflect.apply(INTRINSICS.some, requiredSource, [(entry) => isString(entry) && entry === key])) return [key, this.#wrap(key, child, childShape, open || enclosed)];
11460
+ if (this.#strict && isRecord(child) && INTRINSICS.own(child, "default")) throw this.#refusal("a default needs an optional property to fill", "properties", key, "default");
11461
+ return [key, childShape];
9807
11462
  }]);
9808
11463
  const properties = INTRINSICS.rebase(INTRINSICS.record({ [Symbol.iterator]: INTRINSICS.reflect.apply(INTRINSICS.bind, INTRINSICS.iterator, [pairs]) }), null);
9809
- const extra = schema.additionalProperties;
9810
- const additionalProperties = truncated ? true : extra === false ? false : isRecord(extra) ? this.#convert(extra, depth - 1) : true;
11464
+ const additionalProperties = unread ? true : isRecord(extra) ? this.#descend(extra, depth - 1, enclosed, "additionalProperties") : open;
9811
11465
  return INTRINSICS.freeze({
9812
11466
  category: "object",
9813
11467
  properties: INTRINSICS.freeze(properties),
@@ -9815,9 +11469,115 @@ var SchemaShaper = class SchemaShaper {
9815
11469
  ...description === void 0 ? {} : { description }
9816
11470
  });
9817
11471
  }
11472
+ #wrap(key, child, shape, sealed) {
11473
+ this.#built += 1;
11474
+ if (!isRecord(child) || !INTRINSICS.own(child, "default")) return optionalShape(shape);
11475
+ const value = child.default;
11476
+ if (!isJSONValue(value)) return optionalShape(shape);
11477
+ if (this.#strict) {
11478
+ if (sealed) throw new ContractError("schemaToShape: a default cannot fill under a union or on a property of an open object; close the object or remove the default", {
11479
+ code: "placement",
11480
+ context: {
11481
+ path: pathOf(this.#path, "properties", key, "default"),
11482
+ shape: "schema"
11483
+ }
11484
+ });
11485
+ if (new ContractCompiler(shape).guard(value)) return optionalShape(shape, { default: value });
11486
+ throw this.#refusal("a default must satisfy its schema", "properties", key, "default");
11487
+ }
11488
+ const leaf = shape.category === "string" || shape.category === "number" || shape.category === "boolean" || shape.category === "null" || shape.category === "literal";
11489
+ return !sealed && leaf && new ContractCompiler(shape).guard(value) ? optionalShape(shape, { default: value }) : optionalShape(shape);
11490
+ }
11491
+ };
11492
+ // src/core/FaultShaper.ts
11493
+ /**
11494
+ * Retains a lazily built fault declaration without building shapes during module evaluation.
11495
+ *
11496
+ * @example
11497
+ * ```ts
11498
+ * FaultShaper.shape === FaultShaper.shape // true
11499
+ * ```
11500
+ */
11501
+ var FaultShaper = class FaultShaper {
11502
+ static #shape;
11503
+ /** Returns the shared fault declaration, building it on the first read. */
11504
+ static get shape() {
11505
+ return FaultShaper.#shape ??= new FaultShaper().build();
11506
+ }
11507
+ /**
11508
+ * Builds a closed fault union whose inferred values satisfy the audit fault contract.
11509
+ *
11510
+ * @example
11511
+ * ```ts
11512
+ * createContract(new FaultShaper().build()).is({ reason: 'extra', path: [] }) // true
11513
+ * ```
11514
+ */
11515
+ build() {
11516
+ const path = unionShape(stringShape(), arrayShape(stringShape()));
11517
+ const expected = literalShape(FAULT_KINDS);
11518
+ const hints = arrayShape(unionShape(stringShape(), numberShape(), booleanShape()));
11519
+ return unionShape(objectShape({
11520
+ reason: literalShape(["type"]),
11521
+ path,
11522
+ expected,
11523
+ received: stringShape()
11524
+ }), objectShape({
11525
+ reason: literalShape(["missing"]),
11526
+ path,
11527
+ expected
11528
+ }), objectShape({
11529
+ reason: literalShape(["constraint"]),
11530
+ path,
11531
+ expected,
11532
+ constraint: literalShape(FAULT_CONSTRAINTS),
11533
+ limit: optionalShape(unionShape(numberShape(), stringShape())),
11534
+ received: stringShape()
11535
+ }), objectShape({
11536
+ reason: literalShape(["variant"]),
11537
+ path,
11538
+ variants: integerShape({ min: 0 })
11539
+ }), objectShape({
11540
+ reason: literalShape(["variant"]),
11541
+ path,
11542
+ variants: integerShape({ min: 0 }),
11543
+ key: stringShape(),
11544
+ expected: hints
11545
+ }), objectShape({
11546
+ reason: literalShape(["oneOf"]),
11547
+ path,
11548
+ matched: integerShape({ min: 0 })
11549
+ }), objectShape({
11550
+ reason: literalShape(["oneOf"]),
11551
+ path,
11552
+ matched: integerShape({ min: 0 }),
11553
+ key: stringShape(),
11554
+ expected: hints
11555
+ }), objectShape({
11556
+ reason: literalShape(["extra"]),
11557
+ path
11558
+ }));
11559
+ }
11560
+ static {
11561
+ pinMembers(FaultShaper.prototype, "FaultShaper");
11562
+ }
9818
11563
  };
9819
11564
  // src/core/shapers.ts
9820
11565
  /**
11566
+ * Returns the shared closed audit-fault shape, building it on the first call.
11567
+ *
11568
+ * @remarks
11569
+ * Numeric bounds, counts, and discriminator literals must be finite. Discriminator hints
11570
+ * carry both key and expected together. The inferred union is assignable to AuditFault.
11571
+ *
11572
+ * @example
11573
+ * ```ts
11574
+ * createContract(auditFaultShape()).is({ reason: 'extra', path: ['typo'] }) // true
11575
+ * ```
11576
+ */
11577
+ function auditFaultShape() {
11578
+ return contain(() => FaultShaper.shape, "auditFaultShape");
11579
+ }
11580
+ /**
9821
11581
  * Builds a string {@link StringShape}.
9822
11582
  *
9823
11583
  * @remarks
@@ -9894,8 +11654,9 @@ function stringShape(options) {
9894
11654
  ...patternSnapshot === void 0 ? {} : { pattern: new INTRINSICS.pattern(patternSnapshot.source) },
9895
11655
  ...safe?.description === void 0 ? {} : { description: safe.description }
9896
11656
  };
11657
+ if (patternSnapshot === void 0 && !ShapePass.polluted()) return ShapePass.seal(shape);
9897
11658
  new ShapeValidator(shape).validate();
9898
- return cloneShape(shape);
11659
+ return ShapePass.seal(cloneShape(shape));
9899
11660
  }, "stringShape");
9900
11661
  }
9901
11662
  /**
@@ -9947,8 +11708,7 @@ function numberShape(options) {
9947
11708
  ...safe?.integer === void 0 ? {} : { integer: safe.integer },
9948
11709
  ...safe?.description === void 0 ? {} : { description: safe.description }
9949
11710
  };
9950
- new ShapeValidator(result).validate();
9951
- return INTRINSICS.freeze(result);
11711
+ return ShapePass.seal(result);
9952
11712
  }, "numberShape");
9953
11713
  }
9954
11714
  /**
@@ -9992,8 +11752,7 @@ function booleanShape(options) {
9992
11752
  category: "boolean",
9993
11753
  ...safe?.description === void 0 ? {} : { description: safe.description }
9994
11754
  };
9995
- new ShapeValidator(shape).validate();
9996
- return INTRINSICS.freeze(shape);
11755
+ return ShapePass.seal(shape);
9997
11756
  }, "booleanShape");
9998
11757
  }
9999
11758
  /**
@@ -10014,25 +11773,24 @@ function nullShape(options) {
10014
11773
  category: "null",
10015
11774
  ...safe?.description === void 0 ? {} : { description: safe.description }
10016
11775
  };
10017
- new ShapeValidator(shape).validate();
10018
- return INTRINSICS.freeze(shape);
11776
+ return ShapePass.seal(shape);
10019
11777
  }, "nullShape");
10020
11778
  }
10021
11779
  function literalShape(values, options) {
10022
11780
  return contain(() => {
10023
11781
  const input = values;
10024
11782
  const array = attempt(() => INTRINSICS.array(input));
10025
- if (!array.success || !array.value) throw new ContractError("literalShape: values must be an array", {
11783
+ if (isFailure(array) || !array.value) throw new ContractError("literalShape: values must be an array", {
10026
11784
  code: "structure",
10027
11785
  context: {
10028
11786
  path: ["values"],
10029
11787
  shape: "literal"
10030
11788
  },
10031
- ...!array.success ? { cause: array.error } : {}
11789
+ ...isFailure(array) ? { cause: array.error } : {}
10032
11790
  });
10033
11791
  const safe = readOptions(options, ["description"], "literalShape", "literal");
10034
11792
  const snapshot = readArrayEntries(values);
10035
- if (!snapshot.success) throw new ContractError("literalShape: values could not be copied", {
11793
+ if (isFailure(snapshot)) throw new ContractError("literalShape: values could not be copied", {
10036
11794
  code: "structure",
10037
11795
  context: {
10038
11796
  path: ["values"],
@@ -10063,8 +11821,7 @@ function literalShape(values, options) {
10063
11821
  values: INTRINSICS.freeze(literals),
10064
11822
  ...safe?.description === void 0 ? {} : { description: safe.description }
10065
11823
  };
10066
- new ShapeValidator(shape).validate();
10067
- return INTRINSICS.freeze(shape);
11824
+ return ShapePass.seal(shape);
10068
11825
  }, "literalShape");
10069
11826
  }
10070
11827
  /**
@@ -10110,8 +11867,7 @@ function arrayShape(items, options) {
10110
11867
  ...safe?.max === void 0 ? {} : { max: safe.max },
10111
11868
  ...safe?.description === void 0 ? {} : { description: safe.description }
10112
11869
  };
10113
- new ShapeValidator(shape).validate();
10114
- return INTRINSICS.freeze(shape);
11870
+ return ShapePass.seal(shape);
10115
11871
  }, "arrayShape");
10116
11872
  }
10117
11873
  /**
@@ -10181,8 +11937,7 @@ function objectShape(properties, options) {
10181
11937
  ...safe?.additionalProperties === void 0 ? {} : { additionalProperties: safe.additionalProperties },
10182
11938
  ...safe?.description === void 0 ? {} : { description: safe.description }
10183
11939
  };
10184
- new ShapeValidator(shape).validate();
10185
- return INTRINSICS.freeze(shape);
11940
+ return ShapePass.seal(shape);
10186
11941
  }, "objectShape");
10187
11942
  }
10188
11943
  /**
@@ -10219,13 +11974,19 @@ function recordShape(values, options) {
10219
11974
  additionalProperties: values,
10220
11975
  ...safe?.description === void 0 ? {} : { description: safe.description }
10221
11976
  };
10222
- new ShapeValidator(shape).validate();
10223
- return INTRINSICS.freeze(shape);
11977
+ return ShapePass.seal(shape);
10224
11978
  }, "recordShape");
10225
11979
  }
10226
11980
  /**
10227
11981
  * Builds a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).
10228
11982
  *
11983
+ * @remarks
11984
+ * When every arm is an object declaring one required literal property, and a value's
11985
+ * own property exactly equals a literal only one arm holds, that arm answers: `explain`
11986
+ * and `audit` report its faults at their real paths, and `parse` repairs through it
11987
+ * alone. Any other value reports `variant`, with `key` and `expected` saying what would
11988
+ * have named an arm. `is` does not change.
11989
+ *
10229
11990
  * @param variants - The candidate shapes; the first match wins at runtime
10230
11991
  * @returns A union shape whose `Infer` is the union of the variants
10231
11992
  *
@@ -10237,11 +11998,7 @@ function recordShape(values, options) {
10237
11998
  */
10238
11999
  function unionShape(...variants) {
10239
12000
  return contain(() => {
10240
- new ShapeValidator({
10241
- category: "union",
10242
- variants
10243
- }).validate();
10244
- return INTRINSICS.freeze({
12001
+ return ShapePass.seal({
10245
12002
  category: "union",
10246
12003
  variants: INTRINSICS.freeze(variants)
10247
12004
  });
@@ -10260,9 +12017,11 @@ function unionShape(...variants) {
10260
12017
  * {@link unionShape}'s guard.
10261
12018
  * - **Parser**: judged on the RAW input's guard matches only, with NO
10262
12019
  * coercion fallback for an ambiguous input. When exactly one variant's
10263
- * guard accepts the raw value, that variant's parser runs. Zero matches or
12020
+ * guard accepts the raw value, the input itself is returned. Zero matches or
10264
12021
  * two-or-more matches both parse to `undefined` — a value ambiguous
10265
- * between variants has no well-defined coercion target.
12022
+ * between variants has no well-defined coercion target. A value that names one
12023
+ * arm through a required literal is not ambiguous, so as in {@link unionShape}
12024
+ * that arm answers alone, and its parser may coerce.
10266
12025
  *
10267
12026
  * Prefer {@link unionShape} when a value may legitimately satisfy more than
10268
12027
  * one variant (for example overlapping shapes) and any match is acceptable. Prefer
@@ -10281,15 +12040,10 @@ function unionShape(...variants) {
10281
12040
  */
10282
12041
  function oneOfShape(...variants) {
10283
12042
  return contain(() => {
10284
- const shape = {
12043
+ return ShapePass.seal({
10285
12044
  category: "union",
10286
- variants,
12045
+ variants: INTRINSICS.freeze(variants),
10287
12046
  mode: "oneOf"
10288
- };
10289
- new ShapeValidator(shape).validate();
10290
- return INTRINSICS.freeze({
10291
- ...shape,
10292
- variants: INTRINSICS.freeze(variants)
10293
12047
  });
10294
12048
  }, "oneOfShape");
10295
12049
  }
@@ -10298,22 +12052,55 @@ function oneOfShape(...variants) {
10298
12052
  *
10299
12053
  * @remarks
10300
12054
  * As an {@link objectShape} property, the field becomes a true optional property
10301
- * in the inferred type.
12055
+ * in the inferred type. A `default` is captured as an owned frozen copy, and the
12056
+ * compiled parser fills it where the property is absent or `undefined`; the guard,
12057
+ * the audit, the report, and the generator keep treating the property as optional.
12058
+ * The compilers refuse a default `inner` refuses, a default under a union, and a
12059
+ * default on a property of an open object.
10302
12060
  *
10303
12061
  * @param inner - The wrapped shape
12062
+ * @param options - Optional `default`, a JSON value
10304
12063
  * @returns An optional shape
12064
+ * @throws {ContractError} When a present `default` is not a JSON value, `undefined` included
12065
+ *
12066
+ * @example
12067
+ * ```ts
12068
+ * const retries = optionalShape(integerShape({ min: 0 }), { default: 3 })
12069
+ * ```
10305
12070
  */
10306
- function optionalShape(inner) {
12071
+ function optionalShape(inner, options) {
10307
12072
  return contain(() => {
12073
+ const safe = readOptions(options, ["default"], "optionalShape", "optional");
12074
+ refuseOptionKeys(options, ["default"], "optionalShape", "optional");
12075
+ const present = options !== void 0 && INTRINSICS.own(options, "default");
12076
+ const value = present ? safe?.default : void 0;
12077
+ if (present && !isJSONValue(value)) throw new ContractError("optionalShape: default must be a JSON value", {
12078
+ code: "structure",
12079
+ context: {
12080
+ path: ["default"],
12081
+ shape: "optional",
12082
+ received: preview(value)
12083
+ }
12084
+ });
12085
+ const owned = value === void 0 ? void 0 : attempt(() => cloneJSONValue(value));
12086
+ if (owned !== void 0 && isFailure(owned)) throw new ContractError("optionalShape: default must be a JSON value", {
12087
+ code: "structure",
12088
+ context: {
12089
+ path: ["default"],
12090
+ shape: "optional",
12091
+ received: preview(value)
12092
+ },
12093
+ cause: owned.error
12094
+ });
10308
12095
  const shape = {
10309
12096
  category: "optional",
10310
- inner
12097
+ inner,
12098
+ ...owned === void 0 ? {} : { default: owned.value }
10311
12099
  };
10312
- new ShapeValidator({
12100
+ return ShapePass.seal(shape, {
10313
12101
  category: "object",
10314
12102
  properties: { value: shape }
10315
- }).validate();
10316
- return INTRINSICS.freeze(shape);
12103
+ });
10317
12104
  }, "optionalShape");
10318
12105
  }
10319
12106
  /**
@@ -10334,8 +12121,7 @@ function nullableShape(inner) {
10334
12121
  category: "nullable",
10335
12122
  inner
10336
12123
  };
10337
- new ShapeValidator(shape).validate();
10338
- return INTRINSICS.freeze(shape);
12124
+ return ShapePass.seal(shape);
10339
12125
  }, "nullableShape");
10340
12126
  }
10341
12127
  /**
@@ -10367,17 +12153,39 @@ function jsonShape(options) {
10367
12153
  category: "json",
10368
12154
  ...safe?.description === void 0 ? {} : { description: safe.description }
10369
12155
  };
10370
- new ShapeValidator(shape).validate();
10371
- return INTRINSICS.freeze(shape);
12156
+ return ShapePass.seal(shape);
10372
12157
  }, "jsonShape");
10373
12158
  }
10374
12159
  /**
12160
+ * Builds a {@link ShapeShape}.
12161
+ *
12162
+ * @param options - Optional description
12163
+ * @returns A shape-valued declaration
12164
+ *
12165
+ * @example
12166
+ * ```ts
12167
+ * const definition = objectShape({ shape: shapeShape() })
12168
+ * ```
12169
+ */
12170
+ function shapeShape(options) {
12171
+ return contain(() => {
12172
+ const safe = readOptions(options, ["description"], "shapeShape", "shape");
12173
+ const shape = {
12174
+ category: "shape",
12175
+ ...safe?.description === void 0 ? {} : { description: safe.description }
12176
+ };
12177
+ return ShapePass.seal(shape);
12178
+ }, "shapeShape");
12179
+ }
12180
+ /**
10375
12181
  * Builds a {@link RawShape} from a supported JSON Schema fragment.
10376
12182
  *
10377
12183
  * @remarks
10378
12184
  * For values the shape DSL can't express. The fragment is recursively checked
10379
12185
  * against the lean {@link JSONSchema} vocabulary before ownership is taken;
10380
12186
  * malformed or unsupported keywords throw a coded {@link ContractError}. The
12187
+ * refusal path starts at `schema` and names the nested keyword or member.
12188
+ * A non-record root is refused at `schema` itself. The
10381
12189
  * compiled guard accepts every
10382
12190
  * DEFINED value — `undefined` alone fails, because it is the parser's failure
10383
12191
  * sentinel; wrap the shape in {@link optionalShape} to admit absence. The
@@ -10405,22 +12213,18 @@ function rawShape(schema) {
10405
12213
  category: "raw",
10406
12214
  schema
10407
12215
  }).validate();
10408
- const owned = cloneSchema(schema);
10409
- new ShapeValidator({
10410
- category: "raw",
10411
- schema: owned
10412
- }).validate();
10413
- return INTRINSICS.freeze({
12216
+ return ShapePass.seal({
10414
12217
  category: "raw",
10415
- schema: owned
12218
+ schema: cloneSchema(schema)
10416
12219
  });
10417
12220
  }, "rawShape");
10418
12221
  }
10419
12222
  /**
10420
12223
  * Converts a runtime `JSONSchema` value into a validating {@link ContractShape}
10421
12224
  * — the inverse of {@link compileSchema}. Unlike direct {@link rawShape}
10422
- * construction, which rejects malformed supported-vocabulary keywords, this
10423
- * conversion is total and widens an inexpressible input to a valid raw `{}`.
12225
+ * construction, which rejects malformed supported-vocabulary keywords, the
12226
+ * lenient conversion is total and widens an inexpressible input to a valid raw
12227
+ * `{}`, and a strict conversion refuses that input.
10424
12228
  *
10425
12229
  * @remarks
10426
12230
  * Readable malformed, cyclic, or deeply nested schema nodes widen to
@@ -10471,9 +12275,36 @@ function rawShape(schema) {
10471
12275
  * when the conversion widened anywhere — `schema` / `is` / `parse` / `explain`
10472
12276
  * stay total.
10473
12277
  *
12278
+ * LENIENT LAW: a value a JSON Schema accepts is never refused by the shape a
12279
+ * lenient conversion builds from it, because the walk widens what it cannot read.
12280
+ * So `oneOf` builds an inclusive union, a `true` arm is a raw variant and a `false`
12281
+ * arm is dropped, an `enum` holding `null` admits it, `nullable: true` wraps the
12282
+ * node, a present `patternProperties` opens the object, a present `prefixItems`
12283
+ * widens the elements, and a `$ref` widens the node before anything beside it is read.
12284
+ * A schema past the compile limit keeps only its root's type, an array's bounds, and an
12285
+ * object's required keys and closure, with every value below them raw.
12286
+ *
12287
+ * DEFAULTS: a lenient conversion carries a property's `default` when the key is
12288
+ * not `required`, its object is closed with no union ancestor, and the value is
12289
+ * one the property's primitive or literal guard accepts. It drops every other
12290
+ * `default`, because carrying it would make the shape refuse to compile.
12291
+ *
12292
+ * STRICT: `{ strict: true }` is the door for a foreign schema. It refuses, with
12293
+ * code `structure`, every node the lenient walk would widen, every keyword it
12294
+ * would ignore (`pattern`, `format`, `nullable`, `patternProperties`,
12295
+ * `propertyNames`, `prefixItems`, and anything else outside
12296
+ * {@link STRICT_SCHEMA_KEYWORDS}), a malformed keyword or annotation, a boolean schema, an `enum` entry
12297
+ * that is neither a finite primitive nor `null`, a contradictory bound, a `required` name not in
12298
+ * `properties`, breadth past {@link INFER_BREADTH_LIMIT}, and a `default` with no
12299
+ * optional property to fill. An object with no `additionalProperties` closes
12300
+ * rather than opens, and `oneOf` keeps exactly-one, because a strict walk reads
12301
+ * every keyword that could keep two arms apart. Below a `oneOf` that object refuses
12302
+ * instead, since closing it could change which arms match.
12303
+ *
10474
12304
  * @param schema - The JSON Schema value to convert
12305
+ * @param options - Optional `strict`, default `false`
10475
12306
  * @returns The built {@link ContractShape}
10476
- * @throws {ContractError} When schema traversal fails
12307
+ * @throws {ContractError} When schema traversal fails, or when a strict conversion refuses
10477
12308
  *
10478
12309
  * @example
10479
12310
  * ```ts
@@ -10483,14 +12314,35 @@ function rawShape(schema) {
10483
12314
  * contract.parse({ id: 'nope' }) // undefined
10484
12315
  * ```
10485
12316
  */
10486
- function schemaToShape(schema) {
12317
+ function schemaToShape(schema, options) {
10487
12318
  return contain(() => {
10488
- return readValue(() => new SchemaShaper(schema).shape(), "schemaToShape", {
12319
+ const safe = readOptions(options, ["strict"], "schemaToShape", "schema");
12320
+ refuseOptionKeys(options, ["strict"], "schemaToShape", "schema");
12321
+ const strict = options !== void 0 && INTRINSICS.own(options, "strict") ? safe?.strict : void 0;
12322
+ if (strict !== void 0 && typeof strict !== "boolean") throw new ContractError("schemaToShape: strict must be a boolean", {
12323
+ code: "structure",
12324
+ context: {
12325
+ path: ["strict"],
12326
+ shape: "schema",
12327
+ received: preview(strict)
12328
+ }
12329
+ });
12330
+ const shaper = new SchemaShaper(schema, strict === true);
12331
+ if (strict !== true) return readValue(() => shaper.shape(), "schemaToShape", {
12332
+ subject: "schema",
12333
+ context: { shape: "schema" }
12334
+ });
12335
+ const outcome = attempt(() => shaper.shape());
12336
+ if (isSuccess(outcome)) return outcome.value;
12337
+ if (isContractError(outcome.error)) throw outcome.error;
12338
+ return readValue(() => {
12339
+ throw outcome.error;
12340
+ }, "schemaToShape", {
10489
12341
  subject: "schema",
10490
12342
  context: { shape: "schema" }
10491
12343
  });
10492
12344
  }, "schemaToShape");
10493
12345
  }
10494
- export { CLONE_NODE_LIMIT, COMPILE_DEPTH_LIMIT, COMPILE_NODE_LIMIT, CONTRACT_CODES, CONTRACT_ERROR_BRAND, ContractCompiler, ContractError, FAULT_LIMIT, FORMAT_MAX_LENGTH, FORMAT_PATTERNS, GENERATION_ATTEMPT_LIMIT, GUARD_DEPTH_LIMIT, INFER_BREADTH_LIMIT, INFER_DEPTH_LIMIT, INFER_ENUM_LIMIT, INTRINSICS, JSONCloner, JSON_SCHEMA_TYPES, PRESENCE_MASK_LIMIT, PREVIEW_LIMIT, SchemaCloner, ShapeCloner, ShapeValidator, admitMember, admitVisited, andOf, appendEntries, arrayOf, arrayShape, attempt, booleanShape, boundsOf, buildArrayFaults, buildNumberFaults, buildPositions, buildSampleMemo, buildStringFaults, canonicalStringify, classifyFormat, cloneJSONRecord, cloneJSONValue, cloneSchema, cloneShape, collectEntries, collectMembers, compareValues, compileAuditor, compileGenerator, compileGuard, compileParser, compileReporter, compileSchema, complementOf, contain, createContract, deriveLengthBounds, deriveRangeBounds, drawRandom, encodeLeaf, encodeParts, enumOf, enumerableKeys, enumerableSymbolCount, holds, inferPrimitiveEnum, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isBoundedJSONRecord, isBoundedJSONValue, isConstructor, isContractError, isDataView, isDate, isDefined, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isError, isFalse, isFiniteNumber, isFloat32Array, isFloat64Array, isFunction, isGeneratorFunction, isInstance, isInt16Array, isInt32Array, isInt8Array, isInteger, isIterable, isJSONPrimitive, isJSONValue, isLiteralValue, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptySet, isNonEmptyString, isNonNegativeInteger, isNonNegativeNumber, isNull, isNullableBoolean, isNullableNumber, isNullableString, isNumber, isObject, isPromise, isPromiseLike, isRecord, isRegExp, isSet, isSharedArrayBuffer, isString, isSymbol, isTrue, isUint16Array, isUint32Array, isUint8Array, isUint8ClampedArray, isUndefined, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, iterateIndices, jsonShape, keyOf, lazyOf, limitEntries, literalOf, literalShape, mapOf, matchOf, matchesISOInstant, matchesJSONDepth, matchesJSONValue, matchesMember, matchesPattern, matchesRecordBrand, matchesVisited, notOf, nullShape, nullableOf, nullableShape, numberShape, objectOf, objectShape, omitOf, omitVisited, oneOfShape, optionalOf, optionalShape, orOf, ownPattern, ownShape, parseArray, parseArrayField, parseBoolean, parseBooleanField, parseEnum, parseEnumField, parseEnumValues, parseInteger, parseIntegerField, parseJSON, parseJSONAs, parseJSONValue, parseJSONValueField, parseNull, parseNullField, parseNumber, parseNumberField, parseRecord, parseRecordField, parseString, parseStringField, pathOf, pickOf, pinMembers, preview, previewParts, rawShape, readArrayEntries, readGuardShape, readIndexView, readMapEntries, readOptions, readPattern, readPatternFlags, readPatternSource, readPresence, readSampleMemo, readSetEntries, readValue, recordOf, recordShape, refuseExpansion, resolveField, retainDepth, samplesToFormat, samplesToSchema, sanitizeBudget, sanitizeDepth, schemaToObject, schemaToParameters, schemaToShape, seededRandom, selectClosestFaults, setOf, shapeToKind, sortValues, stringOf, stringShape, stringToFormat, transformOf, tupleOf, unifySchemas, unionOf, unionShape, validateShape, valueToSchema, whereOf };
12346
+ export { CHOICE_LIMIT, CLONE_NODE_LIMIT, COMPILE_DEPTH_LIMIT, COMPILE_NODE_LIMIT, CONTRACT_CODES, CONTRACT_ERROR_BRAND, ContractCompiler, ContractError, FAULT_CONSTRAINTS, FAULT_KINDS, FAULT_LIMIT, FAULT_LIST_LIMIT, FAULT_SCHEMA_LIMIT, FAULT_TEXT_LIMIT, FORMAT_MAX_LENGTH, FORMAT_PATTERNS, GENERATION_ATTEMPT_LIMIT, GUARD_DEPTH_LIMIT, INFER_BREADTH_LIMIT, INFER_DEPTH_LIMIT, INFER_ENUM_LIMIT, INTRINSICS, JSONCloner, JSON_SCHEMA_TYPES, NAME_LIMIT, NODE_LIMIT, PRESENCE_MASK_LIMIT, PREVIEW_LIMIT, SHAPE_FIELDS, STRICT_SCHEMA_KEYWORDS, STRING_LIMIT, SchemaCloner, ShapeCloner, ShapeValidator, TEXT_LIMIT, admitMember, admitValue, admitVisited, andOf, appendEntries, arrayOf, arrayShape, attempt, auditFaultShape, booleanShape, boundsOf, buildArrayFaults, buildNumberFaults, buildPositions, buildSampleMemo, buildStringFaults, canonicalStringify, classifyFormat, cloneJSONRecord, cloneJSONValue, cloneSchema, cloneShape, collectEntries, collectMembers, comparePrimitives, compileAuditor, compileGenerator, compileGuard, compileParser, compileReporter, compileSchema, complementOf, computeSurrogatePairs, contain, createContract, deriveLengthBounds, deriveRangeBounds, describeFaultLine, describeFaults, drawRandom, encodeLeaf, encodeParts, enumOf, enumerableKeys, enumerableSymbolCount, errorToMessage, escapeRegExp, extractForms, extractPath, extractSchema, failure, holds, inferPrimitiveEnum, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isAuditFault, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isBoundedJSONRecord, isBoundedJSONValue, isConstructor, isContractError, isDataView, isDate, isDefined, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isError, isFailure, isFalse, isFault, isFaultPath, isFiniteNumber, isFloat32Array, isFloat64Array, isFunction, isGeneratorFunction, isInstance, isInt16Array, isInt32Array, isInt8Array, isInteger, isIterable, isJSONPrimitive, isJSONValue, isLiteralValue, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptySet, isNonEmptyString, isNonNegativeInteger, isNonNegativeNumber, isNull, isNullableBoolean, isNullableNumber, isNullableString, isNumber, isObject, isPromise, isPromiseLike, isRecord, isRegExp, isSet, isSharedArrayBuffer, isString, isSuccess, isSymbol, isTrue, isUint16Array, isUint32Array, isUint8Array, isUint8ClampedArray, isUndefined, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, iterateIndices, jsonShape, keyOf, lazyOf, limitEntries, literalOf, literalShape, mapOf, matchOf, matchesExactKeys, matchesISOInstant, matchesJSONDepth, matchesJSONValue, matchesLosslessRepair, matchesMember, matchesPattern, matchesRecordBrand, matchesStringLength, matchesUndefinedField, matchesVisited, notOf, nullShape, nullableOf, nullableShape, numberShape, objectOf, objectShape, omitOf, omitVisited, oneOfShape, optionalOf, optionalShape, orOf, ownPattern, ownShape, parseArray, parseArrayField, parseBoolean, parseBooleanField, parseEnum, parseEnumField, parseEnumValues, parseInteger, parseIntegerField, parseJSON, parseJSONAs, parseJSONValue, parseJSONValueField, parseNull, parseNullField, parseNumber, parseNumberField, parseRecord, parseRecordField, parseString, parseStringField, pathOf, pickOf, pinMembers, preview, previewParts, rawShape, readArrayEntries, readGuardShape, readIndexView, readMapEntries, readOptions, readPattern, readPatternFlags, readPatternSource, readPresence, readSampleMemo, readSetEntries, readValue, recordOf, recordShape, refuseExpansion, refuseOptionKeys, renderForm, renderList, renderPath, resolveField, retainDepth, samplesToFormat, samplesToSchema, sanitizeBudget, sanitizeDepth, schemaToObject, schemaToParameters, schemaToShape, seededRandom, selectClosestFaults, setOf, shapeShape, shapeToKind, sortValues, stringOf, stringShape, stringToFormat, success, transformOf, truncateFaultText, tupleOf, unifySchemas, unionOf, unionShape, validateShape, valueToSchema, whereOf };
10495
12347
 
10496
12348
  //# sourceMappingURL=index.js.map